Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

v1.5 beta — character track, material pipeline, and a release path that actually runs (#75)

Hoài Nhớd6673386f896
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 357ad72..23354a4 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -14,6 +14,7 @@ jobs:
with:
tag: ${{ github.ref_name }}
version-file: SKILL.md
- bootstrap-release: ${{ github.ref_name == 'v1.4.3' }}
- # For the first governed tag this remains empty. Update it in the next release-prep PR.
- previous-governed-tag: ""
+ # v1.4.3 bootstrapped the governed line and is already published; nothing bootstraps again.
+ bootstrap-release: false
+ # Last published governed tag. `git ls-remote --tags origin` shows v1.4.3 as the only one.
+ previous-governed-tag: "v1.4.3"
diff --git a/.gitignore b/.gitignore
index 129fbb0..9d72418 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,6 +28,7 @@ cs2_textures/
runtime/**/node_modules/
runtime/**/dist/
runtime/**/.vite/
+integrations/vision/.venv/
.cache/spec-search/
# Demo GIFs/renders in assets/ stay local, but the README's logo must ship with the repo.
@@ -39,3 +40,18 @@ assets/*
!assets/sponsors/
openspec/
runtime/
+
+# Run-time capture output: review renders, focus shots, comparison sheets.
+# These are produced by every capture and gate run, are large, and are never inputs to a build.
+.screenshot/
+
+# Research distillations. Kept locally as the provenance behind a routing or contract decision, but
+# no script reads them and every operational rule they back already lives in grimoire/ or docs/specs/.
+# Shipping them in the skill package costs size and maintenance for reference nobody executes.
+docs/research/
+
+# Per-subject tuning artifacts: sculpt specs, assessments, feedback plans and comparison renders
+# for one character or object. Same reasoning as .screenshot/ above -- they are outputs of a tuning
+# session, never inputs to a build, and they carry multi-megabyte PNGs. Tuning ships with the
+# stable release, not with a beta of the scripts.
+work/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25758eb..eade046 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@ All notable changes to **img2threejs** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [1.4.4-beta-2]
+## [1.4.4-beta.2]
### Added
- Add a repository-local mandatory workflow checklist, resume gate, and evidence-backed step
@@ -224,10 +224,10 @@ and harness improvements to the underlying code generator.
- Action-ready runtime hierarchy exposing pivots, sockets, and colliders.
- Token-efficient, code-only output (diffable TypeScript + JSON spec, no binaries).
+[1.4.1]: https://github.com/hoainho/img2threejs/compare/v1.4.0...4e9fbecae0e63b370581737c89991d4dca84c287
+[1.4.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.4.0
+[1.3.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.3
+[1.2.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.2.0
+[1.1.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.1.0
+[1.0.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.0.0
[1.4.3]: https://github.com/img2threejs/img2threejs/releases/tag/v1.4.3
-[1.4.1]: https://github.com/img2threejs/img2threejs/compare/v1.4.0...4e9fbecae0e63b370581737c89991d4dca84c287
-[1.4.0]: https://github.com/img2threejs/img2threejs/releases/tag/v1.4.0
-[1.3.0]: https://github.com/img2threejs/img2threejs/releases/tag/v1.3
-[1.2.0]: https://github.com/img2threejs/img2threejs/releases/tag/v1.2.0
-[1.1.0]: https://github.com/img2threejs/img2threejs/releases/tag/v1.1.0
-[1.0.0]: https://github.com/img2threejs/img2threejs/releases/tag/v1.0.0
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..04f2bb6
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,49 @@
+# Shared project instructions
+
+This repository is the canonical source for the `img2threejs` skill. Host entrypoints
+(`~/.claude/skills/img2threejs`, `~/.codex/skills/img2threejs`) should be symlinks to one checkout —
+never independent copies, or the two hosts drift apart silently.
+
+## Change rules
+
+- Preserve the code-only procedural Three.js contract; do not silently download meshes or art packs.
+- Keep claims honest: distinguish implemented capability from roadmap or design-only documentation.
+- Treat `forge/` as deterministic tooling and `grimoire/` as routed reference material.
+- Keep backward compatibility for existing sculpt specs unless a migration is explicitly planned.
+- When changing schema, gates, generators, or review behavior, add or update focused tests.
+- Keep `SKILL.md`, `README.md`, `CHANGELOG.md`, and `ROADMAP.md` consistent when release-facing
+ behavior changes.
+- Reference the companion showcase through `IMG2THREEJS_SHOWCASE_ROOT`, never an absolute path — a
+ path that only exists on one machine passes there and fails everywhere else, CI included.
+
+## Verification
+
+```bash
+python3 -m unittest discover -s forge/tests -p 'test_*.py'
+```
+
+Set `IMG2THREEJS_SHOWCASE_ROOT` to a showcase checkout to include the TypeScript typecheck gates;
+without it they skip, and a green run has not proven the emitted Three.js compiles. Add
+`IMG2THREEJS_REQUIRE_SHOWCASE=1` to turn that skip into a failure.
+
+Do not report completion without reading the fresh outputs. For visual reconstruction changes,
+structural tests and screenshot/reference-loop validation are separate required gates.
+
+## Mandatory visual screenshot gate
+
+For every visual reconstruction task, a readable screenshot is a hard prerequisite for visual
+implementation claims and completion:
+
+1. Before accepting visual results, verify that the browser/screenshot tooling is installed,
+ authenticated, reachable, and able to capture the running showcase.
+2. Save fresh PNG/JPEG screenshots inside the workspace, including the fixed reference view and the
+ required orbit views. Inline previews alone are not evidence.
+3. Read the saved screenshots back with an image-capable tool and verify they contain the rendered
+ model at the expected dimensions. A screenshot that cannot be opened or visually read is a failed
+ gate.
+4. Produce and retain a side-by-side reference/render comparison, semantic image scoring,
+ pixel/feature comparison, and the `diagnose_render.py` output for the saved render before
+ reporting visual validation.
+5. If capture, file write, readback, comparison, scoring, or diagnosis fails, stop the visual
+ workflow and repair the tooling first. Do not infer visual evidence from runtime readiness,
+ structural tests, inline previews, or code review, and do not claim the visual gate passed.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 131e6fd..658c355 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -26,7 +26,9 @@ explicit, flagged, opt-in mode.
## Development
- Scripts are pure Python 3.10+ standard library. No pip dependencies.
-- Run the test suite from the skill root: `python3 forge/tests/test_pipeline.py`.
+- Run the test suite from the skill root: `python3 -m unittest discover -s forge/tests -p 'test_*.py'`.
+ Set `IMG2THREEJS_SHOWCASE_ROOT` to a showcase checkout to include the TypeScript typecheck gates;
+ without it they skip, so a green run has not proven the emitted Three.js compiles.
- Validate a spec before generation: `python3 forge/stage2_spec/validate_sculpt_spec.py spec.json --strict-quality`.
- Keep changes backward compatible: existing object specs must continue to validate.
- No emojis in source, docs, or generated output.
diff --git a/README.md b/README.md
index 6e9abb0..7e1c823 100644
--- a/README.md
+++ b/README.md
@@ -9,11 +9,12 @@
Quality-gated, animation-ready, and deliberately token-efficient — reconstruction-by-code, not photogrammetry, mesh extraction, or downloaded art packs.
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/version-1.4.3-green.svg)](https://github.com/img2threejs/img2threejs/releases)
+[![Version](https://img.shields.io/badge/version-1.4.4-green.svg)](CHANGELOG.md)
[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
[![Runtime](https://img.shields.io/badge/runtime-Three.js-000000.svg)](https://threejs.org)
-[![Tooling](https://img.shields.io/badge/tooling-Python%203.10%2B%20stdlib-3776ab.svg)](scripts)
+[![Tooling](https://img.shields.io/badge/tooling-Python%203.10%2B%20stdlib-3776ab.svg)](forge)
[![Sponsor](https://img.shields.io/badge/Sponsor-Buy%20Me%20A%20Coffee-FFDD00.svg?logo=buymeacoffee&logoColor=black)](https://www.buymeacoffee.com/hoainhowors)
+[![Scripts](https://img.shields.io/badge/scripts-forge%20%2F%20scripts-3776ab.svg)](scripts)
[![Sponsored by Atlas Cloud](https://img.shields.io/badge/Sponsored%20by-Atlas%20Cloud-000000.svg?labelColor=1a1a1a&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4NDUuOTUgNzkyIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNNzEyLjA1LDU5NC4zTDQyMi45OCwxNS40NiwxMzMuOSw1OTQuM2wtOTEuMDEsMTgyLjI1YzU3LjE4LTM0LjU1LDExOS40OS02MS40LDE4NS40NC03OS40NSw2Mi4wMi0xNi45NywxMjcuMjQtMjYuMjEsMTk0LjY1LTI2LjIxLDM0LjY5LDAsNjguNzksMi40OSwxMDIuMTksNy4xOGwtNjUuNzItMTQxLjc2Yy0xOC42MS0zLjIzLTEwMS4yOC0zLjIzLTE2MS44Myw5Ljg0bDEyNS4zNi0yNzMuMTYsMTk0LjY1LDQyNC4xMmMuMzUuMS42OS4yMSwxLjAzLjMsNjUuNTcsMTguMDQsMTI3LjUzLDQ0Ljc4LDE4NC40MSw3OS4xNGwtOTEuMDEtMTgyLjI1WiIvPjwvc3ZnPg%3D%3D)](https://www.atlascloud.ai/console/coding-plan)
<table align="center">
@@ -76,12 +77,19 @@ It runs under Claude Code, Codex, or OpenCode. It is agent-agnostic: wherever th
- **Objects and characters.** Each subject is classified `object`, `character`, or `hybrid`. Objects follow the hard-surface pipeline; characters route through an anatomy-aware track (head-unit proportions, facial landmarks, pose) documented in `grimoire/character/reconstruction.md`.
- **Detail-first analysis.** Before code generation the pipeline enumerates a `detailInventory` of identity-defining small details (gloss, bevel/rounding, screws/rivets, engraved or painted linework, contours, stains and wear). Every detail must map to a real component or material entry, and a strict-quality gate blocks generation until the inventory is complete. Taxonomy: `grimoire/intake/detail_inventory.md`.
- **Maximum likeness for a specific person or character.** An opt-in projection-first path fits a parametric template to image landmarks, de-lights the photo, camera-matches the render, and projects the reference onto the mesh. A single image cannot guarantee 100 percent likeness, so the pipeline reports per-region confidence and asks for more views when it matters. Details: `grimoire/character/likeness_maximization.md`.
+- **Multi-view silhouette carving.** An opt-in `geometryDescriptor.visualHull` intersects at least two deterministic orthographic binary silhouettes into a bounded, welded voxel mesh. It records unseen areas as low-confidence rather than inventing hidden detail. Schema and runtime check: `grimoire/scripts.md`.
- **CS2 weapon review gates.** Knife and Glock-18 routes use family-specific component contracts. The review records exactness tier, family identity, painted-region and projection coverage, per-region confidence, approximation notes, and versioned review-scene metadata; component-coverage and map-stripped blockout gates prevent a convincing texture from standing in for real structure. See [`docs/cs2/review-gates.md`](docs/cs2/review-gates.md).
+- **Resumable local workflow.** `forge/state.py` records an ordered, evidence-backed intake/pass checklist for generic, character, and CS2 profiles. `forge/next.py --state` resumes from that checklist while the existing spec, render, and review gates remain authoritative.
+- **Material reference pipeline.** Every visible material region can be cropped, analyzed, resolved against the versioned Three.js material registry, fitted into `ObjectSculptSpec`, rendered from controlled camera views, and accepted only after a per-region comparison gate. See [`docs/materials/README.md`](docs/materials/README.md).
+- **Python-assisted browser rendering.** Python may orchestrate camera batches, hashes, manifests, and deterministic diagnostics, but the target browser Three.js route remains the rendering authority. See [`grimoire/build/python_threejs_render_bridge.md`](grimoire/build/python_threejs_render_bridge.md).
---
## How it works
+A staged sculpting pipeline turns the reference image into a spec, then generates and vision-reviews one build pass at a time — `blockout → structural → form → material → surface → lighting → interaction → optimization` — self-correcting until every identity-defining feature clears its threshold.
+
+**→ Full pipeline diagram, gates, self-correction logic, and the token-efficiency design: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)**
A staged sculpting pipeline turns the reference image into a spec, then generates and vision-reviews one build pass at a time — `blockout → structural → form → material → surface → lighting → interaction → optimization` — self-correcting until every identity-defining feature clears its threshold. Deterministic Python scripts handle validation and gating; model tokens are spent only on visual judgment and code.
**→ Full pipeline diagram, gates, self-correction logic, script reference, and the token-efficiency design: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)**
@@ -96,6 +104,14 @@ A staged sculpting pipeline turns the reference image into a spec, then generate
git clone https://github.com/img2threejs/img2threejs.git ~/.claude/skills/img2threejs
```
+ If you use more than one host, keep a single checkout and point each entrypoint at it as a
+ symlink, so they cannot drift apart:
+
+ ```text
+ ~/.claude/skills/img2threejs -> <your checkout>
+ ~/.codex/skills/img2threejs -> <your checkout>
+ ```
+
2. **Invoke** — in Claude Code, attach or point to an object image and run:
```
@@ -106,6 +122,13 @@ A staged sculpting pipeline turns the reference image into a spec, then generate
3. **Follow the pipeline** — the skill validates the image, writes an assessment and spec, generates the factory pass by pass, and shows you a side-by-side comparison at each step until the render matches.
+ For a multi-session reconstruction, create a local state index first:
+
+ ```bash
+ python3 forge/state.py init --reference <image> --profile character --spec object-sculpt-spec.json
+ python3 forge/next.py --state .img2threejs/state.json
+ ```
+
### Driving it harder
The one-liner leaves the judgement calls to the skill. When you already know what "correct" means for your subject, say so — each line below maps onto a real gate or artifact in the pipeline, so it changes what gets enforced rather than just adding adjectives:
@@ -142,6 +165,74 @@ python3 forge/stage2_spec/validate_sculpt_spec.py spec.json --strict-quality
python3 forge/stage3_build/generate_threejs_factory.py spec.json --out src/createObjectModel.ts
```
+The factory generator repeats the strict-quality gate and is fail-closed: on failure it returns
+`BLOCKED` with the spec artifact, failure metrics, causes, and next action, and does not write a
+factory. `--allow-nonstrict` is only for explicit legacy test fixtures, never production output.
+
+For the script-by-script reference, the full scripts table, and expected artifacts, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
+
+---
+
+## Why it is token-efficient
+
+Most image-to-3D agent loops burn tokens by asking the model to do mechanical work — re-reading the whole model every pass, scoring pixels, validating JSON by hand, re-running steps it already did. img2threejs pushes all of that into deterministic scripts and spends model tokens only where judgment is actually required.
+
+- **Scripts enforce, the model judges.** The Python scripts handle validation, gating, spec authoring, PBR extraction, comparison-sheet packaging, and pipeline state. They never score visuals. The model's tokens go to one thing: looking at a single side-by-side sheet and deciding pass or fail.
+- **Zero dependencies, zero install churn.** Every script is pure Python 3.10+ standard library. No pip, no PIL, no numpy, no Playwright. PNG read/write is done with `struct` and `zlib`. Nothing to install means nothing to debug in-context.
+- **Pass-gated generation.** The code generator emits only the currently unlocked build pass. The model does not regenerate or re-read the entire model on every iteration — each step is small and scoped.
+- **Fail fast, before codegen.** A strict-quality gate blocks shallow specs before a single line of Three.js is generated, so you never spend tokens rendering a model that was underspecified from the start.
+- **One image per review.** Each pass is judged from exactly one packaged comparison sheet (reference beside render), not a scattering of screenshots.
+- **Text output, not binaries.** The result is diffable TypeScript plus a JSON spec — small, reviewable, and version-controllable, instead of multi-megabyte mesh files.
+
+The net effect: you still get a faithful 3D model from an image, but the expensive model context is reserved for visual judgment and code, not bookkeeping. For the full per-stage and per-cycle token breakdown, see [docs/TOKEN_COST.md](docs/TOKEN_COST.md).
+
+---
+
+## Scripts
+
+| Script | Role |
+| --- | --- |
+| `stage1_intake/probe_image.py` | Image metadata and obvious technical issues (not a visual check). |
+| `stage2_spec/new_pre_spec_assessment.py` | Classify the object, score complexity, emit a quality contract. |
+| `stage2_spec/new_sculpt_spec.py` | Author the ObjectSculptSpec from the assessment. |
+| `stage2_spec/validate_sculpt_spec.py` | Validate the spec; `--strict-quality` blocks shallow specs before codegen. |
+| `stage1_intake/extract_pbr_evidence.py` | Reference-derived PBR evidence per crop (inference, not inverse rendering). |
+| `stage1_intake/material_region_analysis.py` | Crop material regions, run texture/PBR evidence, and resolve registry profiles. |
+| `stage2_spec/apply_material_analysis.py` | Wire region assignments, priors, maps, and provenance into ObjectSculptSpec. |
+| `stage3_build/orchestrate_passes.py` | Locked pass state: status, check, sync. |
+| `stage3_build/generate_threejs_factory.py` | Emit the Three.js `Group` factory for the current unlocked pass. |
+| `stage4_review/material_views.py` | Emit multi-angle, zoomed, microscope, environment, and capture-readback contracts. |
+| `stage4_review/material_comparator.py` | Compare the visible material crop and classify per-channel mismatches. |
+| `stage4_review/material_feedback.py` | Apply bounded, material-scoped corrections through the existing stop policy. |
+| `stage4_review/material_gate.py` | Block material-pass until registry, crop, render, compatibility, and comparison evidence passes. |
+| `stage4_review/make_comparison_sheet.py` | Package one reference-vs-render sheet for review. |
+| `stage4_review/append_review.py` | Record a per-pass review: scores, decision, evidence. |
+| `stage4_review/cs2_review.py` | Evaluate the blocking CS2 knife review contract and versioned scene thresholds. |
+| `_shared/feature_acceptance_policy.py` | Internal helper enforcing per-feature score thresholds. |
+| `stage1_intake/build_detail_inventory.py` | Slice the reference into zones and scaffold a detail inventory. |
+| `stage1_intake/extract_landmarks.py` | Overlay a landmark grid and scaffold an anatomy block for characters. |
+| `stage1_intake/solve_camera_pose.py` | Emit a reference-camera block so the render can be camera-matched. |
+| `stage1_intake/delight_albedo.py` | Approximate a neutral albedo from the photo before texture projection. |
+| `stage3_build/bake_projected_texture.py` | Emit a projection/UV-bake descriptor for photo-texture projection. |
+
+The `grimoire/` folder holds the detailed rubrics each gate applies (validation, pre-spec assessment, procedural patterns, material and lighting realism, attachment correctness, action-ready models, self-correction).
+
+### Optional reference-fidelity tooling
+
+The stdlib-only core can use an isolated evidence layer without taking on runtime dependencies:
+SAM2 component masks, Depth Anything V2 relative-depth priors, MediaPipe face/pose landmarks,
+Chrome DevTools diagnostics, Three.js scene inspection, Playwright cross-browser fallback, and
+version-aware Context7 retrieval. These tools never approve a pass or silently provide geometry.
+Install, routing, provenance rules and exact commands:
+[`docs/integrations/reference_fidelity_tooling.md`](docs/integrations/reference_fidelity_tooling.md).
+
+---
+
+## What you get
+
+- An `ObjectSculptSpec` JSON: the full component tree, materials, repetition systems, sockets, and a recorded review history for every pass.
+- A TypeScript `createObjectNameModel(spec, options)` factory returning a `THREE.Group`, with `root.userData.sculptRuntime` exposing nodes, sockets, colliders, and destruction groups.
+- A render plus comparison sheets documenting the fidelity at each pass.
For the script-by-script reference and the full list of output artifacts, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
---
@@ -199,6 +290,7 @@ img2threejs is free and open source. If it saved you time or found its way into
<a href="https://www.buymeacoffee.com/hoainhowors" target="_blank" rel="noopener noreferrer"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me a Coffee" style="height: 60px !important;width: 217px !important;" ></a>
+VietQR / MoMo / PayPal also work — see the [donate page](https://hoainho.github.io/img2threejs-showcase/donate.html).
VietQR / MoMo / PayPal also work — see the [donate page](https://img2threejs.github.io/img2threejs-showcase/donate.html).
---
diff --git a/ROADMAP.md b/ROADMAP.md
index cda1515..0de488e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -72,6 +72,12 @@ judgment is spent only where a script cannot decide.
| Version | Theme | Primary goal | Highlights |
|---|---|---|---|
+| v1.0 | Object pipeline | Shipped | Staged sculpt pipeline (blockout through optimization), render-vs-reference review loop, action-ready runtime hierarchy |
+| v1.1 | Detail-first analysis | Shipped | Required `detailInventory` artifact (gloss, bevel, fasteners, linework, stains), strict-quality gate blocking shallow specs before codegen |
+| v1.2-gates | Portable structural gates | In progress | Host-specific tool-call enforcement is deferred; portable ledger, geometry, evidence, and report gates run in forge scripts. |
+| v1.2 | Humanoid character generator | Shipped | Character/hybrid domain detection, anatomy and facial landmarks, proportion-lock and feature-placement build passes, per-part character materials |
+| v1.3 | Quality & efficiency (Divine Eye) | Shipped | Deterministic review harness, input-integrity and geometry-truth gates, projection-first texture/material analysis, CIEDE2000 colour math |
+| v1.4 | Weapon Pipeline | Shipped | CS2 image-matched reconstruction, provenance-aware intake, projection-first finishes, family-specific adapters, structural and component-coverage gates |
| **v1.5** | Character Pipeline | Start supporting characters properly | Character reconstruction · facial features · rigging-ready topology · blendshape preparation · hair & clothing improvements |
| **v1.6** | Environment Pipeline | Build scenes, not just objects | Buildings · rooms · streets · trees & vegetation · terrain-aware generation · multi-object reconstruction |
| **v1.7** | Game Pipeline | Game-ready assets | Unity exporter · Unreal exporter · Blender bridge · FBX / OBJ / glTF improvements · LOD generation · collision mesh generation |
@@ -110,7 +116,11 @@ Characters become a first-class subject rather than a stylized approximation. Fa
dedicated treatment, and the output topology is built to be rigged: clean, predictable loops that
deform without artifacts, plus blendshape preparation so expression work has somewhere to attach.
Hair and clothing — the two things that most often break a code-built character — get their own
-material and geometry improvements.
+material and geometry improvements. Optional local SAM2 masks, MediaPipe face/pose landmarks and
+Depth Anything V2 relative-depth priors feed provenance-backed evidence into intake without changing
+the zero-dependency core or gaining authority over geometry and review gates. The local v1.5 line
+also records resumable, evidence-backed workflow state so character intake and correction loops can
+continue across agents without turning state into a pass bypass.
### v1.6 — The Environment Update
diff --git a/SKILL.md b/SKILL.md
index 9f6df47..3075c34 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -2,8 +2,7 @@
name: img2threejs
description: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.
license: Apache-2.0
-
-version: 1.4.4-beta.3
+version: 1.4.4
---
# img2threejs — Image to procedural Three.js
@@ -16,6 +15,16 @@ Agent-agnostic: works under Claude Code, Codex, or OpenCode. Wherever this doc s
vision" or "agent browser tool", use whatever the host provides — native image reading, a
browser MCP (playwright/chrome-devtools), the project preview, or a user-supplied screenshot.
+## Canonical shared checkout
+
+Keep one checkout of this repository and let every host enter it through a symlink, so Claude and
+Codex execute the same code instead of drifting apart:
+
+```text
+~/.claude/skills/img2threejs -> <your checkout>
+~/.codex/skills/img2threejs -> <your checkout>
+```
+
## When To Use
The user attaches/points to an object image and wants a procedural Three.js model, a
@@ -25,6 +34,7 @@ action-ready props, game objects, botanical/mechanical parts, and stylized recon
## Core Promise
Sculpt from a photo, in order — never one-shot a mesh:
+1. **Run `python3 forge/next.py <spec>` first, or `python3 forge/next.py --state .img2threejs/state.json`.** The state form reports the ordered local checklist, exact next command, evidence status, and bounded correction-loop status; it never replaces the spec/pass gates.
1. **Use local state first.** Initialize it once, then run
`python3 forge/next.py --state .img2threejs/state.json [<spec>]` at every start/resume and before
every correction iteration. Obey a hard stop; never continue from memory.
@@ -37,12 +47,72 @@ Sculpt from a photo, in order — never one-shot a mesh:
State explicitly when output is approximate/stylized/low-poly. A single image cannot reveal
hidden sides or guarantee exact geometry — say so instead of faking confidence.
+## Resumable local workflow
+
+For a cross-agent or multi-session reconstruction, initialize the local state before intake:
+
+```bash
+python3 forge/state.py init --reference <image> --profile character --spec object-sculpt-spec.json
+python3 forge/next.py --state .img2threejs/state.json
+python3 forge/state.py mark image-analysis --evidence analysis.md
+```
+
+`generic`, `character`, and `cs2` profiles insert their required intake gates in order. Every
+completed step needs evidence; every skipped step needs a reason. The state file is a resumability
+index, not visual evidence: renders, specs, review history, and deterministic gates remain the
+authoritative artifacts.
+
+## Transparency and Process Debugging (Critical — from Bowie Knife reconstruction)
+
+**The problem:** When the user cannot tell what was done or where something went wrong, they cannot debug the process. Over-claiming (reporting success when features still don't match) destroys trust and makes iterative improvement impossible.
+
+**Rule:** Be transparent + don't over-claim. State exactly what changed each pass, with evidence, and name what still doesn't match:
+- After each pass, explicitly list what changed: "Updated guard shape to extend left edge from -0.56 to -0.48 for handle overlap"
+- Provide evidence: reference the specific values, coordinates, or parameters that changed
+- Name what still doesn't match: "Handle silhouette traced but still flat plane (no Z palm-swell), procedural crosshatch not reference's exact dot-grid knurl"
+- Explain why a change was made: "Extended guard left edge because handle ends at X=-0.42 and guard ended at X=-0.20, causing visual gap"
+- Never claim a feature is "done" when it's only "improved" — use precise language
+- When a gate passes but visual inspection shows issues, explain the limitation: "2D gate passed (fidelity 0.83) but three-quarter render shows blade reads as toy (no grind wedge) — 2D gates are blind to 3D realism"
+
+**The user needs to be able to debug the process, not just the output.** If something is wrong, they should be able to trace which decision led to the error and correct it. Opaque processes force restarts; transparent processes enable refinement.
## Transparency and Process Debugging
Report what changed each pass with evidence (exact values/coordinates), name what still doesn't
match, and never claim "done" when only "improved". A passing gate is not proof of 3D realism.
Full rule + examples: `grimoire/review/self_correction.md`.
+## GLB-mediated v2 render-fidelity track (1.5 alpha)
+
+When the user supplies a GLB as an intermediate reference, use the browser-rendered GLB
+as the structural and visual baseline, then author an independent procedural factory. The
+raw GLB is never pixel evidence and its topology/materials are never copied into the factory.
+
+Before any factory edit:
+
+1. Run `forge/stage1_intake/probe_glb.py` and inspect `semanticDecomposition`. A merged
+ one-node/one-mesh/one-primitive/one-material asset is `insufficient` for reliable semantic
+ labels; connected-component/curvature/normal/UV segmentation is hypothesis evidence only.
+ Request a multipart GLB or capture a browser semantic-ID pass before claiming exact regions.
+2. Author and validate one shared `render-profile.v2` with
+ `forge/stage4_review/validate_render_profile.py`. Both GLB and procedural routes must use
+ the same output color space, linear working space, tone mapping/exposure, PMREM environment,
+ viewport/DPR, camera, background and lighting settings.
+3. Capture six passes for every admitted view: `beauty`, `alpha-silhouette`, `semantic-id`,
+ `depth`, `normal`, and `roughness-material-id`. Use
+ `forge/stage4_review/compare_region_passes.py` for deterministic global/per-region evidence;
+ missing semantic-ID data blocks per-region confidence instead of falling back to whole-image
+ color or silhouette scores.
+4. Use region-specific continuous geometry/material strategies. Do not replace a face/head volume,
+ cloth shell, kasa, staff, or tail with a generic collection of floating primitives when the
+ region's silhouette or attachment requires a continuous surface.
+5. Run one correction group per loop in this order: `camera → silhouette → face → clothing →
+ accessory → materials → lighting`. Recapture the full pass set after each group and record
+ the changed group, hashes and score. Never combine groups when diagnosing improvement.
+
+The machine-readable contract lives in `docs/specs/render-profile.v2.schema.json` and
+`docs/specs/render-profile.v2.example.json`. The executable manifest bridge accepts
+`--render-profile` and exposes `record-pass`; its `glb-mediated-v2` validation is fail-closed.
+
## Required Inputs
- one image path / screenshot / URL / attached image (if missing or unreadable, ask)
@@ -87,6 +157,59 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
what the single view hides. Observation before inference; controlled 3D vocabulary; 3D
object-space not 2D image-space. This is generic for any subject and feeds every field below.
Then probe local images: `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).
+1a. **Local Spec Search** — after image analysis and before writing or refining a spec, local
+ evidence is a pipeline stage, not an optional memory lookup, whenever the request needs
+ domain-specific anatomy, PBR, wear, geometry, runtime, or physics specifications. The pre-spec
+ command automatically runs BM25, chooses `cs2` for CS2 targets and `core_3d` otherwise, and
+ writes a `localSpecSearch` evidence bundle into the assessment:
+ `python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`.
+ Add observed terms with repeatable `--spec-query "<term>"`; use `--collection <collection>` only
+ when the automatic collection choice is insufficient. `new_sculpt_spec.py --assessment` carries
+ that bundle into the final spec, including snippets, `source_refs`, and `evidence_refs`.
+ For extra focused retrieval, the direct CLI remains available:
+ `python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json`.
+ For CS2, include the anatomical and the colloquial name, for example
+ `--spec-query "safety ring finger ring"` or `search_specs.py "roughness matte" --collection cs2`.
+ Expand queries with object names,
+ component names, material/finish terms, behavior terms, and known aliases; retry focused
+ alternatives when the first result is incomplete. Build the spec from returned evidence and do
+ not invent domain specs when local evidence exists. Search caches are local/generated only;
+ preserve JSONL records and source provenance rather than replacing them with cache output.
+1aa. **Optional fidelity evidence adapters** — use them only when they improve an observed weak
+ point; the stdlib core remains authoritative. Route thin/complex masks to local SAM2, character
+ face/pose evidence to MediaPipe, and weak front/back cues to Depth Anything V2:
+ `python3 forge/stage1_intake/run_vision_adapter.py <segment|landmarks|depth> ...`.
+ Every adapter emits provenance. Confirm SAM2 selected the intended component; treat monocular
+ depth as relative only; review landmarks before copying them into anatomy. For browser work,
+ prefer Chrome DevTools MCP for live console/network/performance diagnosis, use
+ threejs-devtools MCP read-only to inspect scene/material/renderer state, and reserve Playwright
+ MCP for cross-browser or host fallback. MCP-only scene mutations never count as implementation:
+ write the proven change back to the spec or TypeScript, rebuild, and recapture. Use Context7
+ only with the target project's installed Three.js version; local types, typecheck and runtime
+ smoke tests override live docs. Full routing and commands:
+ `docs/integrations/reference_fidelity_tooling.md`.
+1b. **CS2 intake manifest** — for a CS2 request, create and validate `cs2-intake.json` before
+ pre-spec authoring. Run admission and probing for every source view, record the heuristic signal
+ as non-authoritative evidence, attach the classification record, resolve the supported family,
+ and choose `route` independently from `exactnessTier`. Missing classification, insufficient
+ coverage, or a contradictory high-confidence class is `request-input`; unsupported families do
+ not continue into spec generation.
+2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:
+ `forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `grimoire/intake/quality_contract.md`.
+ Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded
+ `detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knife skins
+ and Glock-18 assets**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`
+ (`targetMinDetails` 16) — the finish/wear/hardware is the item, so CS2 is held to the top
+ fidelity bar; `targetMinDetails` never drops below the 9 floor even if downgraded by hand.
+ **Author procedural GEOMETRY (blade/guard/grip profiles) but make the FINISH a de-lit
+ reference-crop PROJECTION, not a procedural finish material** — projecting the photo's own
+ pixels is what reaches reference fidelity for patterned skins (Doppler/Gamma/Marble/Fade), and
+ is what the v1.3 baseline demos do; a procedural finish for a patterned skin reads visibly wrong
+ against the reference. Take the projection path in step 2c (it generalizes from characters to
+ any reference-matched surface). Procedural finish is the fallback ONLY when live view-dependent
+ response matters more than matching this one reference. Finish routes + rulebook:
+ `grimoire/build/cs2_finishes.md`; optional exact-texture acquisition:
+ `grimoire/intake/cs2_texture_acquisition.md`.
1a. **Local Spec Search** — after image analysis, before writing or refining a spec, pull local
domain evidence (anatomy/PBR/wear/geometry/runtime/physics) rather than inventing it:
`python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`
@@ -114,7 +237,7 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
`forge/stage1_intake/build_detail_inventory.py <image> --mode grid-3x3 --out-dir <dir> --out di.json`.
Each detail MUST map to a `component.localFeatures` or `material.localOverrides` entry — never
prose only. Taxonomy + 3D-term recipes: `grimoire/intake/detail_inventory.md`.
-2c. **Projection-first fidelity (characters AND reference-matched surfaces — supported CS2 knife skins, decals,
+2c. **Projection-first fidelity (characters AND reference-matched surfaces — supported CS2 skins, decals,
painted patterns)** — when the goal is matching a specific reference's surface, put the photo's
own pixels on the mesh instead of approximating them procedurally. This is the single biggest
fidelity lever; a procedural material for a patterned surface is the #1 reconstruction failure.
@@ -124,11 +247,27 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
free of baked lighting (`stage1_intake/delight_albedo.py`, hard requirement — this is what makes
projection safe, not the flat-lit icon), then project the de-lit crop onto the mesh and bake it
into UVs (`stage3_build/bake_projected_texture.py --mesh-id <id>`). For a CS2 skin the mesh is the
- procedural blade/guard/grip you author in the spec, and the projected de-lit crop IS the finish
+ procedural family-specific component tree you author in the spec, and the projected de-lit crop IS the finish
(front + back from the two views) — no procedural Doppler material. For characters, first capture
landmarks (`stage1_intake/extract_landmarks.py --out anatomy.json`), fill `preSpecAssessment.anatomy`,
route `grimoire/character/reconstruction.md`. A single view cannot show hidden sides — report
per-region confidence and request more views when it matters.
+ Character sub-routes, in the order they are needed — decide what parts exist before shaping any
+ of them, and shape the head before the hair that sits on it:
+ - **Parts** — `grimoire/character/structure_decomposition.md`: which parts the figure is made of,
+ and where each one's boundary falls.
+ - **Head** — `grimoire/character/head_construction.md`: skull, face plane and feature placement,
+ the sub-route the likeness gate reads against.
+ - **Hair** — `grimoire/character/stylized_hair_threejs.md`, with the parameter contract in
+ `grimoire/character/threejs_hair_parameter_contract.json`. Lock topology first: material
+ tuning cannot repair wrong lock topology, so run it only after the silhouette review passes.
+2d. **Reference-free humanoid** — when the request is a generic figure with no reference image
+ ("a low-poly humanoid"), there is nothing to measure, so fill anatomy from public canon with
+ `forge/stage2_spec/humanoid_proportions.py <spec> --style-heads 8 --in-place`. It writes
+ `anatomy.source: "canon-table"` so canon is never mistaken for measured evidence, refuses to
+ run at all when the spec names a reference image, and lists what the corpus does NOT supply
+ under `anatomy.unsourced`. Only complete head counts are derivable (currently 8); anything
+ else fails with the missing landmark named rather than being interpolated.
3. Author the spec from the assessment:
`forge/stage2_spec/new_sculpt_spec.py "Name" --image <img> --assessment assessment.json --manifest cs2-intake.json --out object-sculpt-spec.json`.
Replace generic starter `featureReviewTargets` with the object's real identity-defining
@@ -149,6 +288,8 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
real reference crop for patterned finishes** (doppler/quartz/hydro-dip/camo).
- `forge/stage1_intake/extract_pbr_evidence.py <crop> --out-dir <dir> --material-id <id> --target-threshold 0.7`.
Confidence < 0.7 is a stop/refine-input signal, not a pass. It is inference, not inverse rendering.
+ - For multiple named regions, use `forge/stage1_intake/material_region_analysis.py --manifest regions.json --out-dir material-evidence --out material-analysis.json`. Resolve each accepted assignment from `docs/materials/material-reference.json`, then wire it into the spec with `forge/stage2_spec/apply_material_analysis.py`.
+ - Emit the controlled material camera/crop contract with `forge/stage4_review/material_views.py`, compare saved visible-footprint crops with `forge/stage4_review/material_comparator.py`, apply only bounded material-scoped corrections with `forge/stage4_review/material_feedback.py`, and record the blocking result with `forge/stage4_review/material_gate.py`.
5. Validate, then strict-validate before generating code:
`forge/stage2_spec/validate_sculpt_spec.py object-sculpt-spec.json` then `--strict-quality`.
Strict blocks shallow specs (a complex object with one root, no repetition systems, no
@@ -156,6 +297,56 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
6. **Locked build passes** — only touch the currently unlocked pass:
`forge/stage3_build/orchestrate_passes.py status object-sculpt-spec.json`
`forge/stage3_build/generate_threejs_factory.py object-sculpt-spec.json --out src/createObjectModel.ts`
+ (generator is fail-closed: `strict-quality` must pass before it can write any factory; a future
+ `--pass-id` also fails until prior passes are reviewed `continue`). If blocked, preserve the
+ `BLOCKED` artifact and refine the subject-specific spec; do not substitute a generic template.
+6a. **Hitting a triangle budget.** `performanceBudget.targetTriangles` selects a tessellation
+ tier for every primitive that has segment counts (low ≤6k, standard ≤60k, else hero), and
+ caps implicit-surface sampling grids. Where that is not precise enough — an SDF's grid is
+ quantised, so a tier can only get near a number — add
+ `geometryDescriptor.decimate: {"targetRatio": 0.4}` to that component. It emits a
+ Garland-Heckbert quadric collapse into the generated factory and runs **before** skin
+ binding, so weights are computed on the surviving vertices and no skinning data is
+ interpolated across a vertex merge. It keeps `position` only, recomputing normals, so it is
+ refused on an authored/unwrapped `uvStrategy`. For offline LOD tiers from an exported mesh,
+ `forge/stage3_build/decimate.py <mesh.json> --ratio <r> --json` is the same algorithm.
+7. Render the current pass in a browser/preview, capture a screenshot at a review viewpoint.
+7a. **Off-axis and placement gates — a single review viewpoint is not evidence about the model.**
+ Capture a turntable, not one frame, and run all three. Each catches a defect class the older gates
+ pass by construction; skipping them is how a hole through a skull, a hat at hip height and a charm
+ floating below the ground plane survived eight front-only review rounds.
+ `forge/stage4_review/turntable_gate.py --capture 0=front.png --capture 90=right.png --capture 180=rear.png --capture 270=left.png --json`
+ `node runtime/scripts/export_mesh_geometry.mjs --url <preview> --out meshes.json` then
+ `forge/stage4_review/self_intersection.py meshes.json --json`
+ `forge/stage4_review/attachment_anchor.py object-sculpt-spec.json --measured measured.json --json`
+ All three exit `0` clean / `1` gate failure / `2` error. A failure blocks `continue` for the pass
+ even when the global fidelity score passes — the score is computed from one camera and a 64×64 luma
+ grid, and neither can represent any of these defects. Read `sampledVertexCount` /
+ `unmeasuredAttachments` / `missingAzimuths` before believing a clean verdict: each names the part of
+ the model the gate did not actually look at.
+8. Package one side-by-side sheet, then inspect it with agent vision:
+ `forge/stage4_review/make_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.
+9. Record the review (overall + per-layer + per-feature scores + decision):
+ `forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.
+ For the CS2 family path, also attach the versioned report with
+ `--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.
+ A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks
+ `continue` even when the global score passes. See `docs/cs2/review-gates.md`.
+10. Sync pipeline state after manual review edits:
+ `forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`.
+
+## Forge Runtime Contracts
+
+Subdivision runtime tests compile generated TypeScript against the showcase checkout. Set
+`IMG2THREEJS_SHOWCASE_ROOT` to that checkout; without it, local runtime-only tests skip with an
+actionable message while static contracts still run. CI should set `IMG2THREEJS_REQUIRE_SHOWCASE=1`
+to turn a missing showcase checkout into a test failure.
+
+```bash
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_subdivision.py
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 -m unittest discover -s forge/tests
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_showcase_tsc_smoke.py
+```
(generator is pass-gated: a future `--pass-id` fails until prior passes are reviewed `continue`).
The local state adds `--force` only for a new pass or `refine-spec`; `refine-code` edits the
current artifact without regenerating it. Before overwriting, carry valid hand refinement back
@@ -193,6 +384,146 @@ item: silhouette, proportions, edge profile, hardware layout, coating colour, pa
wear, roughness response, and camera framing. Every decision must be traceable to evidence or be
labelled as an approximation.
+The initial CS2 family boundary covers supported **knife** subtypes and the **Glock-18** pistol
+adapter. Rifle, SMG, sniper, heavy, glove, unsupported pistol, and unknown knife subtypes must stop
+with `unsupported-family` or `unsupported-subtype`; they must not receive another family's component
+tree as a generic fallback.
+
+### Layer contract
+
+Pass these records between layers. Do not copy an informal vision description into the next stage:
+
+| Layer | Owns | Must emit | Must not decide alone |
+| --- | --- | --- | --- |
+| Intake | view validity and technical evidence | role, path/hash, resolution, coverage, duplicate status, admission verdict | item identity from aspect ratio or filename |
+| Classification | semantic identity | family, subtype, confidence, evidence refs, provider/version, timeout state | geometry or finish parameters |
+| Identity | skin/name/paint metadata | precedence, resolved values, ambiguity candidates, provenance | guessed paint index, float, or seed |
+| Surface evidence | pixels and texture sources | de-lit reference, PBR channels, map provenance, colour space, UV orientation, confidence | albedo reused as roughness/normal/AO |
+| Geometry adapter | family-specific form | component tree, topology, dimensions, edge/spine, hardware relationships, painted regions | hidden geometry without confidence notes |
+| Spec/route | evidence-backed implementation choice | route, exactness tier, assumptions, feature targets, camera contract | exact-texture claim without exact evidence |
+| Build/review | rendered observables | fixed view, two non-degenerate orbit views, per-region results, failed gates, next action | overriding a failed critical feature with a global score |
+
+The canonical hand-off is `cs2-intake.json` (`schemaVersion: 1`). Its state is one of
+`proceed`, `request-input`, `fallback`, `rejected`, `unsupported-family`, or
+`unsupported-subtype`. Write it atomically and preserve unknown provider fields under
+`extensions`; a fallback must never erase prior evidence.
+
+### CS2 intake order
+
+1. Admit and technically probe every view. Reject undecodable, empty, tiny, fragmented, or
+ duplicate references before classification.
+2. Record the heuristic CS2 signal only as a routing hint. `detect_cs2.py` is never authoritative
+ identity evidence.
+3. Require a classification record before selecting a family adapter. If classification is absent,
+ timed out, or contradicts a high-confidence objectness result, return `request-input`.
+4. Resolve identity in this order: explicit user metadata, uniquely resolved metadata, then the
+ authoritative classification record. Preserve ambiguity rather than guessing.
+5. Select route and exactness independently:
+ - `reference-projection`: default for matching a specific patterned image;
+ - `authored-texture`: only when independent texture maps are supplied or legally acquired;
+ - `procedural-finish`: fallback when projection evidence is unavailable or live response is the
+ stated priority.
+ Exactness is `image-only`, `metadata-assisted`, or `exact-texture`; changing route must not
+ silently upgrade or downgrade the evidence tier.
+6. Select the family adapter only after family/subtype validation. Record painted regions, unpainted
+ substrate, visible hardware, hidden-region confidence, and every approximation in the spec.
+7. For projection, solve the camera and de-light the source first. Projected pixels provide colour
+ evidence, not automatic geometry truth; geometry still comes from the adapter and silhouette
+ review.
+
+### Surface and review rule
+
+For a specific CS2 reference, preserve the reference's own colour/pattern pixels whenever legal and
+technically possible. Procedural Doppler/Fade/Gamma/Marble patterns are not equivalent to the input
+image and may only be used with an explicit `procedural-finish` route and approximation warning.
+Keep albedo, roughness, metalness, normal/height, AO, mask, and wear as independent channels. Record
+channel source, colour space, UV orientation, dimensions, packed-channel decoding, and missing-channel
+derivation. A low-confidence PBR inference is a refine-input signal, not proof of exact material.
+
+Single-view reconstruction may proceed only when visible identity features are sufficiently covered;
+hidden blade sides, underside, and back hardware must carry inference confidence and may trigger
+`request-input`. Review the fixed camera plus two meaningful orbit views. Report what changed, which
+evidence caused it, what still differs, and choose exactly one next action:
+`continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`.
+
+## Gates (do not skip)
+
+- **Suitability + reference integrity**: pass / conditional / reject before any planning
+ (`grimoire/intake/validation_rubric.md`), AND every reference admitted via
+ `forge/stage1_intake/check_reference_admission.py` (rejects empty/fragmented/tiny/duplicate/
+ undecodable refs with a reason). Intake understanding cross-checked by
+ `forge/stage1_intake/check_intake_correctness.py` (halts on a confident class contradiction).
+- **Divine Eye (the harness heart) — deterministic-first, model-last**: the render evaluator is
+ `forge/stage4_review/divine_eye.py` — a zero-token multi-signal ensemble (IoU/scale HARD gates;
+ proportion/symmetry-parity/pHash/SSIM/edge/blowout/flat/tonal-parity soft) with self-uncertainty
+ (`probe` on signal disagreement) and deterministic routing (`continue`/`refine-spec`/`refine-code`/
+ `probe`). The VLM (`forge/stage4_review/vlm_gate.py`) is a gated, calibrated, cross-checked
+ last layer: **never consulted on a hard-gate failure**, multi-sample-voted, and can rescue a
+ soft near-threshold reject but never grant past a hard geometric failure.
+- **Multi-angle or it didn't happen**: a non-planar form must hold from ≥2 camera angles.
+ `forge/stage4_review/diagnose_render_multi_angle.py` flags `degenerate-view` when an orbited
+ silhouette collapses (a flat plane faking a volume). Orbit angles use reference-free
+ self-consistency — never scored against a reference angle the photo doesn't cover.
+- **CS2 review contract**: `forge/stage4_review/cs2_review.py` consumes the manifest and
+ versioned scene fixture, then blocks wrong family identity, missing projection coverage,
+ painted-region mismatch, critical identity-detail failure, finish/material response failure,
+ and degenerate orbit form. It records exactness tier, hidden-region confidence, per-region
+ confidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,
+ background, and renderer version.
+- **Bounded correction loop (token-burn safety)**: `forge/stage4_review/correction_loop.py`
+ guarantees termination: hard gates route to `refine-code`; repeated defects and oscillation route
+ to `refine-spec`; plateau and the hard ceiling route to `request-input` — never a silent infinite
+ burn. Deterministic analysis-by-synthesis parameter fitting and Divine Eye provenance are
+ documented in `grimoire/build/analysis_by_synthesis_fitting.md`.
+- **Executable Divine Eye fitting**: `fit_against_divine_eye()` in
+ `forge/stage4_review/fit_params.py` connects deterministic parameter-to-render callbacks to
+ bounded gate-aware Divine Eye optimization. Clean candidates use raw fidelity; hard-gated
+ candidates score below all clean results while retaining original fidelity and provenance. The
+ returned objective and optional selected raw fidelity are explicit, and each copied record has
+ candidate/reference/render provenance. It lazily loads the default evaluator and returns
+ normalized raw-fidelity correction-loop provenance without mutating sources.
+- **Tier 1 (legacy, still valid)**: "Tier 2 (AI-vision) never runs against a render that has not passed Tier 1." Run `forge/stage4_review/diagnose_render.py` (silhouette IoU/proportion/symmetry/per-part color) and record it (`--spec ... --in-place`) before requesting a comparison sheet; `orchestrate_passes.py check` refuses otherwise.
+- **Pre-spec / strict-quality**: blocks code gen until the spec is deep enough for its contract.
+- **Screenshot feedback**: `continue` is allowed only with a render + comparison sheet + global
+ AI-vision score ≥ threshold (default 0.7) AND every critical feature ≥ its own threshold.
+ Details + per-layer scorecard: `grimoire/feedback/render_capture.md`.
+- **Action-ready**: build a runtime hierarchy (pivots, sockets, colliders, destruction groups),
+ never an inert lump; expose `root.userData.sculptRuntime`. `grimoire/readiness/action_rigging.md`.
+- **Procedural rig contract (1.5-alpha)**: for humanoid/character builds, validate the authored
+ `joints`/`parents`/`names`/`matrix_local`/packed skin payload with
+ `forge/stage5_rig/validate_rig_payload.py` before binding `THREE.Skeleton`. The gate proves
+ structural payload integrity only; pose stress, dynamic bounds, readable screenshots, and
+ visual likeness remain separate gates. Payload ownership and non-goals:
+ `grimoire/readiness/procedural_rigging_contract.md`.
+- **Assembly gate (structure, not pixels) — every model ships explodable AND clickable**: this is
+ a build requirement, not a per-project extra. Name every mesh; flag surface relief
+ `userData.explodeWithParent` so it rides its shell; let a named group of *anonymous* meshes be one
+ part while a named group of *named* parts stays a container. Explode and part-picking must share
+ one definition of "a part" — if they disagree, both are wrong. Separate parts by SCALING the
+ layout about the model centre, never by pushing every part the same distance (that translates the
+ arrangement without opening any gap). Then run
+ `forge/stage4_review/check_part_coverage.py --spec <spec> --manifest <parts.json>`: it FAILS on a
+ specified component that was never built and on two components fused onto one mesh; it warns on
+ inventoried details that never reached the spec and on meshes belonging to no named part. This is
+ the only gate that scores STRUCTURE — every other one scores pixels, and a single fused mesh
+ wearing a projected photo passes all of those. Its limit is honest and must be stated when
+ reporting: it proves you built what you specified, never that you specified enough.
+ Full contract + the two rules it took a wrong pass to learn: `grimoire/build/geometry_patterns.md`.
+- **Attachment**: child appendages (branches/limbs/handles/tubes) need `attachment.parentSocket`,
+ `localStart`, `localEnd`, `contactType`, `embedDepth`/`overlap`, `gapTolerance` — no mid-air parts.
+ `grimoire/readiness/joint_attachment.md`.
+- **Material/lighting**: `grimoire/feedback/shading_realism.md` — independent PBR channels
+ (never alias albedo into roughness/normal/AO), macro/meso/micro frequency bands, real lights.
+- **Detail inventory**: for `moderate`+ subjects strict-quality blocks code gen until the
+ `detailInventory` reaches `targetMinDetails` and every detail maps to a real component/material
+ entry (gloss needs low-roughness/clearcoat; fasteners need instancing/micro parts).
+- **Character track**: when `primaryDomain` is `character`/`hybrid` (or `--character`), the spec
+ author auto-builds a stylized humanoid template (head/neck/torso/arms + hair, glasses,
+ headphones, face features), flattened to world space under a hidden root, with per-part
+ character materials and character build passes (`proportion-lock`, `feature-placement`).
+ strict-quality requires a filled `anatomy` block (head-units, proportions, face landmarks) and
+ character feature targets. Suitability routing for humans: `grimoire/intake/validation_rubric.md`
+ (stylized vs maximum-likeness). Stylized bust, not a face-copy; refine positions per reference.
The initial CS2 family boundary is **knife only**. Pistol, rifle, SMG, sniper, heavy, glove, and
unknown knife subtypes must stop with `unsupported-family` or `unsupported-subtype`; they must not
receive the knife component tree as a generic fallback.
@@ -231,6 +562,17 @@ After every pass, decide exactly one: `continue | refine-spec | refine-code | re
decision, MUST read the root-cause guide + fidelity scale in `grimoire/review/self_correction.md`,
record the decision, and re-run the local state gate.
+**Small features need a different instrument.** Divine Eye's SSIM/tonal/edge signals run on a 64×64
+luma grid and a 96×96 edge grid, so a detail a few pixels wide in the reference is not scored badly —
+it is absent before any comparison happens, and `per_feature.py` cannot compensate because it consumes
+a scores dict and never opens an image. When fidelity depends on individual tears, spars, fangs or
+eyes, use the four-tier microscope: `grimoire/review/divine_eye_microscope.md`. Two rules there are
+empirically established rather than proposed, and both produced confident false findings before being
+understood: measure fidelity on a component's **visible footprint** (the full frame minus a
+component-hidden frame), never on an isolation render, which reveals geometry the reference cannot
+see; and never colour-gate a **concave** feature, where a dark ratio captures cavity shading rather
+than material.
+
## Implementation Rules (brief)
TypeScript + plain Three.js unless the project uses a wrapper. `Group` factory
@@ -239,6 +581,29 @@ deterministic seeds for all procedural noise. Prefer primitives / `Shape` extrud
instancing / displacement / generated canvas textures before any external art. Full geometry &
material recipes + hard-won failure patterns: `grimoire/build/geometry_patterns.md`.
+### Optional Python ↔ Three.js render bridge
+
+When Python is requested for character rendering, use it as a deterministic job/evidence layer
+around the browser Three.js runtime: camera-batch manifests, source/output hashes, readiness and
+settle checks, screenshot persistence, masks, diagnostics, and comparison packaging. The target
+Three.js browser route remains the rendering authority. Do not silently replace the procedural
+TypeScript factory with Blender/VRM/GLB output. Full routing, manifest fields, and failure rules:
+`grimoire/build/python_threejs_render_bridge.md`.
+
+### Standard character pipeline (merged 1.5 beta + alpha)
+
+Use `grimoire/readiness/standard_character_pipeline.md` for character work. Beta owns the
+strict sculpt/build/review gates; alpha owns deterministic camera manifests, browser screenshot
+evidence and UniRig-shaped rig validation. CharacterGen, Tripo, VRM and other neural/asset
+systems are opt-in adapters with source, checkpoint, license, coordinate conversion and output
+hashes. They never silently replace the procedural TypeScript factory. Image-to-mesh systems emit a
+static mesh with no skeleton, so their output is never animation-ready however good it looks; neural
+riggers are offline inference whose value here is the serialized payload, not a browser dependency.
+
+Executable entry points are `forge/stage4_review/render_bridge.py` and
+`scripts/capture_threejs_playwright.py`. Run `init → browser capture → validate → diagnose`;
+capture must operate on the real showcase/browser route and leave readable PNGs in the workspace.
+
## Output
- **Analysis-only**: suitability verdict + scores, object extraction, macro→micro hierarchy,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 406a62d..bdfddcf 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -12,6 +12,8 @@ The skill runs a staged sculpting pipeline. Scripts gate each stage; the agent's
flowchart TD
A[Reference image] --> B[Probe and suitability gate]
B --> C[Pre-Spec Assessment: class, complexity, quality contract]
+ B -. when useful .-> A1[Optional mask, landmark and relative-depth evidence]
+ A1 --> C
C --> D[Author ObjectSculptSpec: components, materials, sockets]
D --> E{Validate and strict-quality}
E -- too shallow --> D
@@ -27,6 +29,27 @@ flowchart TD
L -- no --> M[Animation-ready Three.js model]
```
+### Material reference hand-off
+
+Material identity is an executable sub-pipeline rather than prose in the spec:
+
+```text
+named component region
+ -> verified crop + observation
+ -> material-reference.json resolver
+ -> reference-derived PBR maps and bounded prior
+ -> ObjectSculptSpec materialReference/materialPipeline
+ -> generated material userData and color-space-safe maps
+ -> multi-angle zoom/microscope capture
+ -> per-region comparator and bounded feedback
+ -> materialGate + material-pass unlock
+```
+
+`forge/materials/reference.py` is the runtime registry contract. The registry never decides from
+colour alone and an ambiguous or low-confidence region remains `probe`/`request-input`. The
+material gate also checks that UV/map bindings survive geometry, visual hull, skinning, collision,
+morph and LOD changes. Existing specs without `materialPipeline` remain backward-compatible.
+
### Build passes
The model is sculpted in a fixed order; a pass unlocks only after the previous one is reviewed and accepted:
@@ -35,6 +58,12 @@ The model is sculpted in a fixed order; a pass unlocks only after the previous o
Each pass has its own acceptance criteria. A pass is marked `continue` only with a real render, a comparison sheet, an agent-vision score at or above threshold, and every identity-defining feature at or above its own threshold.
+For resumable work, `forge/state.py` stores an atomic JSON checklist around this pipeline. Profile
+steps for `character` and `cs2` are inserted before local spec authoring; correction counts are
+bounded per pass and globally. `forge/next.py --state` reports the next ordered action and rejects
+a positional spec that differs from the state artifact. This state index does not grant a pass:
+the ObjectSculptSpec, render evidence, review history, and deterministic gates still decide.
+
### The gates
- **Suitability** — is the image a viable 3D target at all.
@@ -70,20 +99,29 @@ The net effect: you still get a faithful 3D model from an image, but the expensi
| Script | Role |
| --- | --- |
| `stage1_intake/probe_image.py` | Image metadata and obvious technical issues (not a visual check). |
+| `stage1_intake/probe_glb.py` | GLB provenance, bounds, scene inventory and conservative semantic-readiness assessment. |
| `stage2_spec/new_pre_spec_assessment.py` | Classify the object, score complexity, emit a quality contract. |
| `stage2_spec/new_sculpt_spec.py` | Author the ObjectSculptSpec from the assessment. |
| `stage2_spec/validate_sculpt_spec.py` | Validate the spec; `--strict-quality` blocks shallow specs before codegen. |
| `stage1_intake/extract_pbr_evidence.py` | Reference-derived PBR evidence per crop (inference, not inverse rendering). |
+| `stage1_intake/material_region_analysis.py` | Region crop admission, PBR extraction, and material-reference resolution. |
+| `stage2_spec/apply_material_analysis.py` | Material analysis to ObjectSculptSpec hand-off. |
| `stage3_build/orchestrate_passes.py` | Locked pass state: status, check, sync. |
| `stage3_build/generate_threejs_factory.py` | Emit the Three.js `Group` factory for the current unlocked pass. |
| `stage4_review/make_comparison_sheet.py` | Package one reference-vs-render sheet for review. |
| `stage4_review/append_review.py` | Record a per-pass review: scores, decision, evidence. |
+| `stage4_review/material_views.py` | Deterministic material camera/crop/microscope plan and capture readback validation. |
+| `stage4_review/material_comparator.py` | Per-region crop metrics and mismatch tags. |
+| `stage4_review/material_gate.py` | Blocking material acceptance and cross-pass compatibility gate. |
+| `stage4_review/validate_render_profile.py` | Validate the shared GLB/procedural renderer, camera and six-pass profile. |
+| `stage4_review/compare_region_passes.py` | Compare paired browser diagnostic passes and block unsupported per-region claims. |
| `stage4_review/cs2_review.py` | Evaluate the blocking CS2 knife review contract and versioned scene thresholds. |
| `_shared/feature_acceptance_policy.py` | Internal helper enforcing per-feature score thresholds. |
| `stage1_intake/build_detail_inventory.py` | Slice the reference into zones and scaffold a detail inventory. |
| `stage1_intake/extract_landmarks.py` | Overlay a landmark grid and scaffold an anatomy block for characters. |
| `stage1_intake/solve_camera_pose.py` | Emit a reference-camera block so the render can be camera-matched. |
| `stage1_intake/delight_albedo.py` | Approximate a neutral albedo from the photo before texture projection. |
+| `stage1_intake/run_vision_adapter.py` | Invoke optional isolated SAM2, MediaPipe, and Depth Anything evidence adapters. |
| `stage3_build/bake_projected_texture.py` | Emit a projection/UV-bake descriptor for photo-texture projection. |
The `grimoire/` folder holds the detailed rubrics each gate applies (validation, pre-spec assessment, procedural patterns, material and lighting realism, attachment correctness, action-ready models, self-correction).
diff --git a/docs/RESEARCH_TRELLIS2_TO_IMG2THREEJS.md b/docs/RESEARCH_TRELLIS2_TO_IMG2THREEJS.md
new file mode 100644
index 0000000..8a41989
--- /dev/null
+++ b/docs/RESEARCH_TRELLIS2_TO_IMG2THREEJS.md
@@ -0,0 +1,596 @@
+# TRELLIS.2 → img2threejs: what transfers, what must not
+
+Research note, 2026-07-30. Question asked: *how does img2threejs get closer to the fidelity of an
+image-to-3D generative system like TRELLIS.2 while its output stays a semantic, editable,
+animation-ready `THREE.Group`?*
+
+Sources read for TRELLIS.2: the repo README, the project page, the paper (arXiv 2512.14692,
+*Native and Compact Structured Latents for 3D Generation*), and
+`trellis2/pipelines/trellis2_image_to_3d.py`. I did **not** clone or run the CUDA source
+(FlexGEMM / CuMesh / o-voxel); claims about internals below come from the paper and that pipeline
+file, and are labelled where they are inference rather than quotation.
+
+Sources read for img2threejs: this checkout — `SKILL.md`, `docs/ARCHITECTURE.md`, `ROADMAP.md`,
+`forge/stage1_intake/*`, `forge/stage2_spec/validate_sculpt_spec.py` (the real schema),
+`forge/stage3_build/*`, `forge/stage4_review/*`, `forge/_shared/*`, and the working review
+apparatus in the sibling `img2threejs-showcase` checkout.
+
+---
+
+## 0. Thesis
+
+The two systems fail in opposite directions.
+
+- **TRELLIS.2 has maximal representational capacity and zero semantics.** Its output is one
+ `MeshWithVoxel`. No parts, no pivots, no sockets, no skeleton. Any shape is representable; nothing
+ is editable.
+- **img2threejs has maximal semantics and minimal representational capacity.** Its output is a
+ `THREE.Group` of named parts drawn from **14 primitive kinds**
+ (`VALID_PRIMITIVES` in `validate_sculpt_spec.py:38`). Everything is editable; a large class of
+ shapes is not representable — and, critically, **nothing in the pipeline detects
+ "inexpressible"**. It only detects "this render scored low", which is a different fact.
+
+So the fidelity gap is not primarily a review-loop problem. It is:
+
+1. a **representation-expressiveness** problem (§2.1, §4), and
+2. a **correction-granularity** problem — the loop re-decides at whole-object fidelity and
+ regenerates the whole factory (§6).
+
+Three transfers close most of the gap without giving up the Group:
+
+- **A two-layer representation.** Add a dense per-part field layer that is a *fitting and measuring
+ target*, never the output. The semantic layer stays authoritative for hierarchy; the dense layer
+ becomes authoritative for shape. That is O-Voxel's role, scoped per part, at 32³–128³ instead of
+ 1536³ — cheap enough for stdlib Python.
+- **TRELLIS's conditional stage ordering.** structure → geometry → appearance, where appearance is
+ *conditioned on final geometry* and is never allowed to compensate for it.
+- **Localized correction.** Move the loop's unit of decision from the object to the
+ `(view, component, feature)` cell, and regenerate only the failing part's module.
+
+None of this requires running TRELLIS.2 or O-Voxel.
+
+---
+
+## 1. What TRELLIS.2 actually does
+
+### 1.1 Geometry — O-Voxel ("omni-voxel")
+
+A sparse voxel grid where each occupied voxel carries a tuple: **geometry features** (dual vertex
+position, edge-intersection flags, splitting weights) + **material features** (base colour, metallic,
+roughness, opacity) + integer coordinates on an N³ grid.
+
+The load-bearing property is stated in the abstract: O-Voxel *"can robustly model arbitrary topology,
+including open, non-manifold, and fully-enclosed surfaces"*. It is **field-free** — no SDF, no
+Flexicubes, no iso-surface. That is why it handles cloth and leaves.
+
+**This is the single most relevant claim for img2threejs.** An SDF cannot represent a zero-thickness
+membrane; it must thicken it. img2threejs's `implicit` topologyClass and
+`_shared/sdf_primitives.py` inherit exactly that limit, and it is precisely the limit that bites on a
+dragon wing membrane, a cape, a leaf, or a fin.
+
+The *Flexible Dual Grid* — "one vertex per primal cell and one quadrilateral face per primal edge" —
+is what preserves sharp edges where marching cubes would round them.
+
+Conversion mesh↔O-Voxel is described as instant, "fully rendering-free and optimization-free".
+
+### 1.2 Compression — Sparse Compression VAE
+
+16× spatial downsampling, sparse residual autoencoding (eight children aggregated into the channel
+dimension), early-pruning upsampling. A 1024³ textured asset becomes ~9.6K latent tokens.
+
+The transferable point is not the VAE. It is that **the inter-stage message is compact and lossy in a
+characterised way**. img2threejs's inter-stage message is the spec JSON, which is compact — but its
+loss of shape information is *uncharacterised*. Nobody can say how much of the subject the spec
+cannot express.
+
+### 1.3 Stage decomposition — from the source, not the README
+
+`trellis2/pipelines/trellis2_image_to_3d.py`:
+
+```
+preprocess_image → get_cond
+ → sample_sparse_structure(cond, resolution) # occupancy layout only
+ → sample_shape_slat / sample_shape_slat_cascade(cond, coords)
+ → decode_shape_slat # mesh + substructures
+ → sample_tex_slat(cond, shape_slat as concat_cond) # PBR, conditioned on geometry
+ → decode_tex_slat → decode_latent
+```
+
+Three facts worth stealing outright:
+
+- **(a) Structure is solved before shape.** A separate, cheap model decides *where matter is* before
+ anything decides *what shape it has*.
+- **(b) Appearance is conditioned on final geometry**, passed in as `concat_cond`. Materials are
+ never sampled concurrently with geometry.
+- **(c) The `_cascade` variants exist only for 1024/1536.** High resolution is reached by *refining a
+ converged lower-resolution result*, never by generating at target resolution directly.
+
+### 1.4 PBR
+
+`baseColor`, `metallic`, `roughness`, `alpha` as **per-voxel surface attributes**, not a UV texture —
+relightable by construction. Note the honest caveat in their README: the exported `.glb` is
+`OPAQUE` by default even though alpha survives in the texture. Even TRELLIS treats transparency as a
+downstream authoring decision rather than a solved output property.
+
+### 1.5 What must not transfer
+
+4B parameters, H100-class GPU, ≥24 GB VRAM, CUDA 12.4, Linux, FlexGEMM/CuMesh/nvdiffrast. And more
+importantly the *shape of the output*: one mesh. Running TRELLIS.2 inside img2threejs would hand
+img2threejs exactly the artifact it exists to avoid. Its only legitimate role is as an **optional
+dense evidence layer to fit against** (MA4 in §10).
+
+---
+
+## 2. Transferable ideas, and where each lands
+
+| TRELLIS.2 mechanism | Why it works | img2threejs transfer | Touches |
+|---|---|---|---|
+| Field-free representation | open / non-manifold / enclosed surfaces are native | new `open-shell` topology class + a **part-shell field** with an explicit two-sided zero-thickness mode; SDF stays for solids only | new `_shared/part_shell.py`; `validate_sculpt_spec.py:58` (`VALID_TOPOLOGY_CLASSES`) |
+| Sparse-structure stage runs first | proportion and layout are settled before detail | promote `visual_hull.py` from an optional `geometryDescriptor` to a **mandatory Stage-S1 occupancy artifact**, and use it as the bbox/proportion oracle | `stage3_build/visual_hull.py` → new `forge/stage2_structure/` |
+| Dual grid preserves sharp edges | no marching-cubes rounding | never mesh-extract as the primary path: keep the parametric profile and *fit* it to the field | `_shared/subdivision.py`, new fitter |
+| `_cascade` refinement | refine what has converged, not everything | **per-component refinement budget**: only components whose cell failed get re-generated | `stage3_build/orchestrate_passes.py`, `stage3_build/module_cache.py` |
+| Appearance conditioned on geometry | material cannot paper over shape error | **hard ordering gate**: `material-pass` is illegal for a component whose geometry cell has not converged | `orchestrate_passes.py:387-420` |
+| Compact structured latent as the only inter-stage message | stages cannot reach behind each other | S3S (§3) becomes the *only* channel between stages, hashed per stage | `stage2_spec/*`, new provenance block |
+| PBR as per-point attributes | relightable, channels independent | per-part attribute maps (vertex colour / small `DataTexture`) with per-channel `source` + `confidence` | `stage1_intake/extract_pbr_evidence.py`, `analyze_texture.py` |
+
+---
+
+## 3. The Structured 3D Spec (S3S)
+
+Design it as a **strict superset of `ObjectSculptSpec`**, `schemaVersion: 2`, so every v1.5 spec
+migrates by addition. Emit two artifacts from one source of truth: TypeScript interfaces for the
+runtime/codegen contract, JSON Schema for the Python validator.
+
+```ts
+export interface StructuredSpec {
+ schemaVersion: 2;
+ provenance: Provenance;
+ subject: Subject; // class, complexity tier, qualityContract (unchanged)
+ frame: Frame; // NEW — explicit world contract
+ structure: Structure; // NEW — the S1 occupancy solve
+ parts: Part[]; // replaces componentTree (tree via parentId)
+ materials: MaterialSpec[];
+ articulation: Articulation; // NEW — was scattered across actionProfile/attachment
+ evidence: EvidenceBundle; // detailInventory, referencePbr, localSpecSearch, cs2Intake
+ review: ReviewBlock; // featureReviewTargets + reviewHistory (unchanged)
+}
+
+export interface Provenance {
+ referenceHashes: Record<string, string>; // path → sha256
+ specHash: string;
+ stageStamps: Array<{ stage: StageId; inputHash: string; outputHash: string }>;
+ /** A stage may read ONLY the previous stage's outputHash artifact + evidence. */
+ sealed: true;
+}
+
+export interface Frame {
+ unit: 'meter' | 'model-height-1';
+ up: [number, number, number];
+ forward: [number, number, number];
+ worldBounds: { min: Vec3; max: Vec3 };
+ referenceCameras: ReferenceCamera[]; // from solve_camera_pose.py
+}
+
+export interface ReferenceCamera {
+ viewId: string; // 'front-primary', 'side', ...
+ azimuthDeg: number; elevationDeg: number;
+ fovDeg: number | null; // null ⇒ UNSOLVED, must not be faked
+ /** Discriminator for the bbox-inflation vs perspective-mismatch ambiguity — see §6.4 */
+ fovEvidence: 'solved' | 'assumed' | 'ambiguous-with-part-inflation';
+}
+
+export interface Structure {
+ /** The coarse "where is matter" solve. Deliberately low resolution. */
+ occupancy: {
+ resolution: number; // 32 → 128
+ boundsSpace: 'model' | 'world';
+ views: Array<{ axis: 'front' | 'side' | 'top'; maskRef: string; confidence: number }>;
+ hiddenRegions: Array<{ region: string; confidence: number }>;
+ };
+ proportionAnchors: Array<{ id: string; position: Vec3; source: 'landmark' | 'occupancy' | 'assumed' }>;
+ symmetryPlanes: Array<{ normal: Vec3; origin: Vec3; enforced: boolean }>;
+}
+
+export interface Part {
+ id: string;
+ parentId: string | null;
+ semanticRole: string; // 'wing-left', 'horn-r', 'tail-dart'
+ level: 'macro' | 'meso' | 'micro';
+ transform: { position: Vec3; rotation: Vec3; scale: Vec3 };
+
+ topologyClass: TopologyClass; // + 'open-shell'
+ topologyRationale: string;
+ geometry: GeometryRepr; // §4 — discriminated union
+
+ materialIds: string[];
+ pivot?: Vec3;
+ sockets?: Socket[];
+ collider?: Collider;
+ attachment?: Attachment; // unchanged contract
+ articulationBinding?: { boneId?: string; jointId?: string; skinWeightHint?: string };
+
+ confidence: PartConfidence;
+ editability: {
+ tier: GeometryRepr['kind'];
+ /** For baked tiers: how to regenerate. Never emit opaque vertex data. */
+ refitCommand?: string;
+ };
+}
+
+export interface PartConfidence {
+ /** Per axis, because a single view constrains x/y far better than z. */
+ shape: { x: number; y: number; z: number };
+ material: number;
+ occluded: boolean;
+ /** Set when the reference cannot resolve a declared feature at all. */
+ insufficientReferenceResolution?: { featureId: string; referencePx: number; requiredPx: number };
+}
+
+export interface MaterialSpec {
+ id: string;
+ /** Every channel independent, with its own provenance. One extractor call ⇒ one channel. */
+ channels: {
+ baseColor?: Channel; roughness?: Channel; metalness?: Channel;
+ normal?: Channel; opacity?: Channel; transmission?: Channel;
+ ao?: Channel; emissive?: Channel;
+ };
+ /** True when reference lighting is unsolved ⇒ roughness/metalness are REPORT-ONLY, never gated. */
+ lightingUnknown: boolean;
+ doubleSided?: boolean; // required for open-shell parts
+}
+
+export interface Channel {
+ source: 'delit-reference-projection' | 'reference-inference' | 'procedural' | 'authored-map' | 'assumed';
+ value?: number | [number, number, number];
+ mapRef?: string;
+ colorSpace?: 'srgb' | 'linear';
+ confidence: number; // < 0.7 ⇒ refine-input, not a pass
+ gating: 'hard' | 'soft' | 'report-only';
+}
+
+export interface Articulation {
+ skeleton?: { bones: Bone[]; bindMode: 'attached' | 'detached' };
+ joints: Joint[]; // hinge/ball/slider + limits
+ blendshapes?: Array<{ id: string; targetPartIds: string[]; driver: string }>;
+ deformationStack?: DeformationOp[];
+ rootMotionNode?: string;
+}
+```
+
+Notes on the two fields that carry the most weight:
+
+- **`Channel.gating`** is what makes confidence *actionable*. The rule established the hard way in
+ the showcase build is: **never hard-gate a signal you cannot measure** — a dark-pixel ratio on a
+ concave part measures cavity shading, not material; roughness from an unknown-lighting photo
+ measures the photographer, not the surface. `lightingUnknown: true` must mechanically demote
+ roughness/metalness to `report-only`.
+- **`editability.refitCommand`** is what keeps the philosophy intact at the T5 escape hatch (§4). A
+ baked `BufferGeometry` is acceptable *only* if it is regenerable and still wears a name, a pivot, a
+ socket and a material.
+
+---
+
+## 4. Hybrid geometry system
+
+A ladder, cheapest and most editable first. A part declares exactly one tier.
+
+| Tier | Kind | What it is | Editable by | Example |
+|---|---|---|---|---|
+| T0 | `primitive` | box, sphere, ellipsoid, cylinder, cone, capsule, torus | changing a scalar | a gold ring, a bolt |
+| T1 | `parametric` | lathe / extrude+bevel / ground-blade / tube | profile2D, bevel, spine | a knife blade, a horn |
+| T2 | `sweep` | station list (position + radius) swept along a spine | editing one station | a tail, a wing spar |
+| T3 | `proceduralSurface` | deterministic generator layered on T1/T2 (displacement, noise, tear notches) | generator parameters + seed | wing tears, knurling, scales |
+| T4 | `field` | SDF union/subtract **or** open-shell field | primitive + op list | a continuous organic torso; a **membrane** |
+| T5 | `fittedBuffer` | baked vertex data fitted to a field/mask | `refitCommand` re-derives it | a shape nothing above can express |
+
+Routing keyed to the existing `topologyClass` (extends
+`DISALLOWED_TOPOLOGY_PRIMITIVE_PAIRS`, `validate_sculpt_spec.py:71`):
+
+| topologyClass | allowed tiers | forbidden |
+|---|---|---|
+| `assembled-solid` | T0, T1 | T4 (an assembly is not one field) |
+| `continuous-sculpt` | T2, T4 | T0 box/cylinder/cone (already), thin straight extrude (already) |
+| `conforming-shell` | T4 open-shell | closed SDF |
+| `open-shell` *(new)* | T4 open-shell only | **SDF** — it cannot express zero thickness |
+| `surface-relief` | T3 on the parent's surface | standalone T0 |
+| `fiber-strand` | T1 tube, T0 instanced-cluster | box, plane-card (already) |
+| `material-only` | none | any geometry |
+
+Two rules matter more than the ladder itself:
+
+**Promotion (toward T5) requires two agreeing instruments.** A part may only escalate its
+representation when its cell has failed **twice, on converged measurements**, and the failure is a
+*shape* failure rather than a measurement artefact. In the showcase build three geometry changes were
+reverted by the silhouette ratchet, and at least one of them (thinning the wing spars ×0.72) was
+chasing a measurement error — the isolation render was showing wing root that the reference cannot
+see. Escalating representation on one instrument's word bakes that error into geometry, where it is
+much harder to retract.
+
+**Demotion is a required step, not an aspiration.** At `optimization-pass`, attempt to lift each T5
+back to T4/T2 and accept the lift if the cell does not regress. Without this the model accumulates
+baked geometry over its lifetime and quietly stops being editable — which is the failure mode that
+would make img2threejs into the thing it is trying not to be.
+
+---
+
+## 5. Stage separation
+
+| Stage | Owns | Reads | Emits | Where |
+|---|---|---|---|---|
+| **S0 Intake** | admission, camera solve, de-light, detail inventory, **reference resolution budget** | images | `evidence.json` | `forge/stage1_intake/` (exists) |
+| **S1 Structure** | occupancy, proportion anchors, symmetry, part inventory + confidence | S0 | `structure.json` | **new** `forge/stage2_structure/` (promote `visual_hull.py`) |
+| **S2 Geometry** | tier choice per part + parameter fitting to the occupancy field and silhouettes | S1 | `parts[].geometry` | `stage2_spec/derive_geometry.py` + **new** fitter |
+| **S3 Material** | PBR channels, per-channel confidence and gating | S2 (**gated on per-part geometry convergence**) | `materials[]` | `stage1_intake/extract_pbr_evidence.py`, `analyze_texture.py` |
+| **S4 Articulation** | pivots, sockets, colliders, joints, skeleton, skin weights, blendshape stubs | S2/S3 | `articulation` | **new** `forge/stage5_rig/` |
+| **S5 Optimization** | merge/instance/LOD + **T5→T4 demotion attempt** | S4 | final spec + factory | `stage3_build/` |
+
+The discipline that makes this worth doing is the one the showcase apparatus proved: each stage reads
+**only** the previous stage's artifact plus the evidence bundle, and each stamps an input and output
+hash. A stage that can reach behind its predecessor cannot be regression-tested, and a pipeline whose
+artifacts are not hash-linked will silently measure a stale render — five separate stale-artifact
+paths were found and closed in the showcase build, all from one root cause.
+
+Note the gap this exposes: **S4 does not exist today.** `actionProfile`, `attachment`, `sockets`,
+`joints` and `deformationStack` are all in the schema, `docs/PLAN_1.5_ANIMATION_READY_RIGS.md`
+describes the intent, and the "action-ready" gate checks that `root.userData.sculptRuntime` is
+populated — but nothing measures whether the rig is *correct*. That is the v1.5/v1.8 theme and it is
+the least-defended part of the "animation-ready" promise.
+
+---
+
+## 6. The localized correction loop
+
+### 6.1 What is there now
+
+`stage4_review/correction_loop.py::decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02)`
+takes a history of **whole-object fidelity scalars plus tags**. It is a sound bounded loop — hard
+gates route to `refine-code`, oscillation to `refine-spec`, plateau and ceiling to `request-input` —
+but it structurally *cannot say which part to fix*, so every correction regenerates the whole factory.
+
+`divine_eye.py` measures the whole image on a 64×64 luma grid and a 96×96 edge grid
+(`LUMA_SIZE`/`EDGE_SIZE`, lines 73-74). `per_feature.py` gates correctly per feature but consumes a
+scores dict and never opens an image. So the tier machinery is sound and starved — exactly as
+`grimoire/review/divine_eye_microscope.md` already records.
+
+### 6.2 The loop to build
+
+```
+for each planned view:
+ capture beauty pass
+ capture object-ID pass # flat unique emissive colour per component,
+ # lights and environment OFF, depth testing ON
+ for each declared component:
+ footprint = pixels where this component's ID is frontmost # occlusion-correct
+ for each declared feature:
+ patch = setViewOffset crop, ≥128 px, projection UNCHANGED
+ metrics = { sdf, directionalChamfer, curvatureExtrema, deltaE00 }
+
+aggregate: worst patch → worst component → worst view → verdict # never average
+route: failing cells NAME the parts to edit
+regenerate: only those parts' factory modules
+```
+
+`module_cache.py` already does per-module codegen caching with neighbour invalidation, so the last
+line is a smaller change than it looks: make a failing cell invalidate exactly one module.
+
+### 6.3 There is already a working implementation — promote it
+
+The sibling `img2threejs-showcase` checkout contains the only working build of this loop. These are
+production-tested and should move into the skill rather than be rewritten:
+
+| Showcase file | What it does | Suggested home |
+|---|---|---|
+| `scripts/capture-views.mjs` | plan-driven capture, per-component object-ID pass, white-background hard fail | `forge/runtime/capture/` |
+| `scripts/multiview_gate.py` | per-view silhouette IoU with coarse-to-fine alignment + **convergence status** | `forge/stage4_review/microscope/` |
+| `scripts/component_report.py` | per-component footprint from the ID pass, fail-closed in both directions | `forge/stage4_review/microscope/` |
+| `scripts/correction_loop.mjs` | bounded runner, 7 proven exit paths, stagnation detected via `renderSetHash` | merge into `correction_loop.py` |
+| `scripts/provenance.mjs` | content-derived `runId`, `planHash` / `modelHash` / `shadingHash` | `forge/_shared/provenance.py` |
+| `scripts/gate_record.py` | self-describing gate JSON; invariant `verdict == 'pass'` iff `blockers == []` | `forge/_shared/gate_record.py` |
+
+### 6.4 Four rules that were learned the expensive way
+
+These belong in the skill because each one produced a *confident false finding* before it was
+understood, and each generalises past the dragon.
+
+1. **Measure the visible footprint via an object-ID pass — not an isolation render, and not
+ full-minus-hidden.** An isolation render shows geometry the reference cannot see: the dragon's
+ wings measured 0.4362 dark-share against a reference 0.2240 ("the spars are twice too thick"), and
+ at the *original* radii, measured correctly, 0.1891 against 0.2240 — inside tolerance. The spars
+ were never too thick. The obvious fix, full-frame minus component-hidden-frame, is also wrong:
+ 71% of that pixel difference is indirect-lighting change, not occlusion. Only a flat-colour ID
+ pass with depth testing gives the true frontmost footprint.
+2. **Normalise robustly — 2nd–98th percentile of foreground mass — identically on both sides.**
+ min/max bbox normalisation penalised every view by roughly 0.10 IoU and produced a width finding
+ that was not merely wrong in magnitude but **reversed in direction**: 5.34× "too wide" was
+ actually 0.85× narrower. The tell was self-consistency: across five views the min/max ratios read
+ 5.34 / 1.39 / 2.70 / 2.56 / 0.26 (incoherent) while the robust ratios read 0.85 / 0.50 / 0.59 /
+ 0.59 / 0.60.
+3. **Refuse to decide on an unconverged or clamped alignment.** Every locked per-view floor in the
+ showcase was derived from a clamped search. The "worst view", chased for ~50 iterations at a
+ locked 0.4838, reads 0.5002 converged and 0.6112 under robust normalisation — **with no geometry
+ change at all.** A ratchet anchored to a search boundary is anchored to the boundary, not to an
+ optimum.
+4. **Two instruments disagreeing is information, and the newer one is not automatically right.**
+ Thinning the spars improved the new feature metric and cost the trusted silhouette ratchet 0.0075
+ IoU on one view — twice its tolerance. The ratchet was right. Investigate the disagreement; never
+ let a freshly written metric override a regression in one already trusted.
+
+And one open discriminator worth encoding in the camera solve, because it is general to any
+image-matched pipeline: **part bbox-inflation and a capture-FOV perspective mismatch predict the same
+signature** ("shift down and magnify"). They separate on locality — part inflation is LOCAL, so
+excluding the suspect part should collapse `dy` toward zero and leave `scale` alone; perspective
+mismatch is GLOBAL, so `dy` tracks view angle and persists with all parts included. That belongs in
+`ReferenceCamera.fovEvidence`.
+
+---
+
+## 7. PBR: what to take from TRELLIS.2
+
+- **Opacity as a first-class channel.** TRELLIS carries `alpha` per voxel. img2threejs has
+ `transmission`/`ior` via `analyze_texture.py` but no way to *declare* "thin, translucent,
+ double-sided surface" as a topology + material pair. A wing membrane, a leaf, a cape and a lampshade
+ all need it. This pairs with the new `open-shell` topology class and `MaterialSpec.doubleSided`.
+- **Geometry-conditioned appearance, enforced.** TRELLIS passes the shape latent into
+ `sample_tex_slat` as `concat_cond`. The enforceable version here: if a component's geometry cell is
+ failing, the router must **reject** `refine-code` on that component's material. A material change
+ is not allowed to be the fix for a shape error — and under a whole-image gate it very often looks
+ like one.
+- **Keep channels independent, structurally.** The rule already exists in
+ `grimoire/feedback/shading_realism.md` ("never alias albedo into roughness/normal/AO"). Make it
+ mechanical: one extractor call writes one channel, each with its own `source` and `confidence`.
+- **Roughness and metalness from a single unknown-lighting photograph stay report-only.** Already the
+ rule; `lightingUnknown` makes it automatic instead of a matter of discipline.
+- **Prefer generated surface detail to a photo-derived normal map.** A normal map baked from the
+ reference is entangled with the reference's lighting. Where one is unavoidable, require the de-lit
+ albedo (`delight_albedo.py`) as its source, never the raw crop.
+- **Add a relighting self-check.** Render the same part under two different environments; if the two
+ ΔE00 scores against the reference differ by more than a threshold, the material is *compensating
+ for lighting* rather than describing a surface. This is cheap, it is directly inspired by TRELLIS's
+ relightability claim, and it catches the most common PBR cheat.
+
+---
+
+## 8. Concrete file-level change list
+
+### New
+
+| Path | Purpose |
+|---|---|
+| `forge/stage2_structure/solve_occupancy.py` | S1: promote `visual_hull.py` into a mandatory occupancy artifact; raise the 32³ cap |
+| `forge/stage2_structure/proportion_anchors.py` | proportion + symmetry solve, the bbox oracle |
+| `forge/_shared/part_shell.py` | open-shell / two-sided zero-thickness field; sibling to `sdf_primitives.py` |
+| `forge/_shared/geometry_tiers.py` | the T0–T5 ladder, routing table, promotion/demotion rules |
+| `forge/_shared/provenance.py` | content-derived run IDs and stage hashes (port from showcase) |
+| `forge/_shared/gate_record.py` | self-describing gate JSON with the pass/blockers invariant |
+| `forge/stage4_review/microscope/` | feature-level patches, SDF + directional Chamfer + curvature + ΔE00, worst-patch aggregation |
+| `forge/stage4_review/microscope/id_pass.py` | object-ID footprint extraction |
+| `forge/stage5_rig/` | S4: skeleton, skin weights, joint limits, blendshape stubs, and their gates |
+| `forge/runtime/capture/` | plan-driven multi-view capture with the ID pass and a background hard fail |
+
+### Modified
+
+| Path | Change |
+|---|---|
+| `forge/stage2_spec/validate_sculpt_spec.py` | `schemaVersion: 2`; add `open-shell` to `VALID_TOPOLOGY_CLASSES:58`; extend `DISALLOWED_TOPOLOGY_PRIMITIVE_PAIRS:71` with the tier routing table; validate `Part.confidence`, `Channel.gating`, `editability.refitCommand` |
+| `forge/stage2_spec/new_sculpt_spec.py` | author S3S; per-part confidence; per-channel material provenance |
+| `forge/stage2_spec/derive_geometry.py` | tier selection + parameter fitting against the occupancy field |
+| `forge/stage3_build/orchestrate_passes.py` | **per-component** pass state; geometry-before-material ordering gate (`:387-420`) |
+| `forge/stage3_build/module_cache.py` | a failing cell invalidates exactly one module |
+| `forge/stage3_build/generate_threejs_factory.py` | emit T4 field meshing and T5 `refitCommand`; keep every tier a named part with pivot/socket/material |
+| `forge/stage3_build/visual_hull.py` | move to S1; raise `MAX_VISUAL_HULL_RESOLUTION:7` from 32 |
+| `forge/stage4_review/divine_eye.py` | robust foreground-mass normalisation; emit alignment convergence; keep `LUMA_SIZE`/`EDGE_SIZE` as the *macro* tier only |
+| `forge/stage4_review/per_feature.py` | consume microscope metrics, not just a precomputed scores dict (`:59`) |
+| `forge/stage4_review/correction_loop.py` | cell-level history; refuse to decide on unconverged alignment; route by named part |
+| `forge/stage4_review/make_comparison_sheet.py` | per-feature zoom panels alongside the whole-image sheet (`:216`) |
+| `forge/stage1_intake/build_detail_inventory.py` | named-ROI authoring as the default path, not the upper/middle/lower thirds of `DEFAULT_COMPONENT_ZONES:38` (used at `:198`) |
+| `forge/stage1_intake/solve_camera_pose.py` | emit `fovEvidence`; run the locality discriminator in §6.4 |
+| `forge/stage1_intake/extract_pbr_evidence.py` | one call ⇒ one channel, each with `source`/`confidence`/`gating` |
+| `forge/stage4_review/fit_params.py` | extend `fit_against_divine_eye()` to fit T1/T2 parameters against the occupancy field, not only against gate scalars |
+
+---
+
+## 9. Prioritised roadmap
+
+### Quick wins — days, no architecture change
+
+1. **Emit `insufficient-reference-resolution` per declared feature.** It is specified in
+ `grimoire/review/divine_eye_microscope.md` and unimplemented. It prevents an entire class of false
+ gates: a feature the reference cannot resolve currently scores badly instead of being excluded.
+2. **Object-ID capture pass + per-component footprint.** Port `capture-views.mjs` and
+ `component_report.py`. This is the single highest-value port — it is what turns a whole-image score
+ into a per-part one.
+3. **Robust foreground-mass normalisation everywhere a silhouette is normalised** (`divine_eye.py`,
+ `diagnose_render.py`), and bump the metric version so cached comparisons are invalidated.
+4. **Refuse to decide on unconverged alignment** in `correction_loop.py`, and surface the convergence
+ status in the record.
+5. **Per-channel `source`/`confidence`/`gating` + `lightingUnknown`**, mechanically demoting
+ roughness/metalness to report-only when lighting is unsolved.
+
+### Medium term
+
+6. **S3S schema v2** — additive superset, with a migration test proving every v1.5 spec still validates.
+7. **S1 Structure stage** — occupancy as a mandatory artifact and the proportion oracle.
+8. **Per-component pass state + the geometry-before-material ordering gate.**
+9. **Localized regeneration** — one failing cell invalidates one module.
+10. **The T0–T5 tier ladder** with routing and the two-instrument promotion rule.
+11. **Feature-level microscope** — `setViewOffset` patches, SDF/directional Chamfer/curvature/ΔE00,
+ worst-patch aggregation, no averaging.
+
+### Major architectural
+
+12. **The part-shell field layer** (`open-shell` + field fitting). This is the change that actually
+ raises the fidelity ceiling for organic and membrane subjects, because it removes the SDF's
+ zero-thickness limit — the same limit TRELLIS.2 removed with O-Voxel.
+13. **Analysis-by-synthesis fitting at scale** — finite-difference fitting of T1/T2 parameters
+ against the occupancy field and silhouettes. `fit_params.py` and
+ `grimoire/build/analysis_by_synthesis_fitting.md` are the seed.
+14. **S4 Articulation stage** with rig-correctness gates. The "animation-ready" promise is currently
+ checked structurally (`sculptRuntime` is populated) but never for correctness.
+15. **Optional dense-evidence adapter.** If a TRELLIS-class output is available offline, ingest it as
+ a **dense evidence layer to fit semantic parts against** — never as the output, never as a
+ dependency. The pipeline must produce the same artifact without it.
+
+### Top 10 by impact
+
+| # | Change | Impact | Cost |
+|---|---|---|---|
+| 1 | Object-ID pass + per-component footprint | turns every score per-part; unblocks localized correction | S |
+| 2 | Robust normalisation + convergence reporting | ~+0.10 IoU of pure measurement error removed; stops false findings | S |
+| 3 | Cell-level correction loop routing by named part | corrections stop being whole-object rewrites | M |
+| 4 | Feature-level microscope with worst-patch aggregation | small identity features become measurable at all | M |
+| 5 | Part-shell field / `open-shell` topology | removes the zero-thickness limit — the actual ceiling | L |
+| 6 | S1 Structure stage as the proportion oracle | fixes proportion/bbox errors before any detail work | M |
+| 7 | Geometry-before-material ordering gate | stops material from papering over shape error | S |
+| 8 | S3S v2 with actionable confidence and per-channel gating | makes "don't gate what you can't measure" mechanical | M |
+| 9 | T0–T5 ladder with two-instrument promotion | expressiveness grows without losing editability | M |
+| 10 | S4 articulation stage + rig gates | makes "animation-ready" a measured claim | L |
+
+---
+
+## 10. The answer to the question
+
+**img2threejs closes the fidelity gap by borrowing TRELLIS.2's *representation strategy* and
+*conditional stage ordering*, while keeping the semantic tree as the output and demoting the dense
+representation to a measuring and fitting target.**
+
+Concretely, three inversions of the current design:
+
+1. **Dense where you measure, semantic where you emit.** TRELLIS is dense end-to-end; img2threejs is
+ semantic end-to-end. Neither is right. Solve a cheap dense occupancy field per subject and a shell
+ field per part, then *fit* named parametric parts to it. The field is never shipped. The Group is.
+ This is what lets a wing membrane exist without an SDF having to thicken it, and it is the change
+ that actually moves the ceiling.
+
+2. **Order the stages by conditioning, not by convenience.** TRELLIS's pipeline settles occupancy
+ before shape and shape before appearance, and passes the shape latent forward as an explicit
+ condition. img2threejs's eight passes run in a fixed order but are not *conditioned*: a material
+ pass can visually compensate for a geometry error and the whole-image gate will accept it. Make
+ the ordering a gate rather than a convention.
+
+3. **Refine cells, not objects.** TRELLIS's cascade refines the tokens that need refining.
+ img2threejs regenerates the whole factory and re-decides on one scalar. Move the decision unit to
+ `(view, component, feature)`, keep the aggregation worst-first with no averaging, and regenerate
+ one module. The working implementation of this already exists in the showcase checkout — the
+ remaining work is promotion, not invention.
+
+What must not be traded away, and is not traded away by any of the above: every part keeps a name, a
+transform, a pivot, its sockets and colliders, its material references, and its articulation binding.
+The escape hatch at T5 bakes *vertex data*, never *hierarchy*, and it carries the command that
+regenerates it. Editability degrades at the leaf, never at the tree.
+
+The honest limit, which should be stated in any report this feeds: **a dense field fitted from one
+photograph is still one photograph's worth of information.** Higher-resolution measurement does not
+create evidence the reference never contained. That is why item 1 in the quick wins is
+`insufficient-reference-resolution` — the pipeline needs to be able to say "this cannot be resolved
+from this image" before it is given sharper instruments to say it more confidently.
+
+---
+
+## Sources
+
+- [microsoft/TRELLIS.2](https://github.com/microsoft/TRELLIS.2)
+- [TRELLIS.2 project page](https://microsoft.github.io/TRELLIS.2/)
+- [Native and Compact Structured Latents for 3D Generation (arXiv 2512.14692)](https://huggingface.co/papers/2512.14692)
+- [microsoft/TRELLIS.2-4B on Hugging Face](https://huggingface.co/microsoft/TRELLIS.2-4B)
+- [img2threejs](https://github.com/img2threejs/img2threejs) — plus this local checkout, which is the
+ authority for the file paths and schema line numbers cited above.
diff --git a/docs/cs2/3D_Technical_Mapping.json b/docs/cs2/3D_Technical_Mapping.json
index 1fcc57b..2ccb1fd 100644
--- a/docs/cs2/3D_Technical_Mapping.json
+++ b/docs/cs2/3D_Technical_Mapping.json
@@ -156,16 +156,16 @@
},
"spatial_wear_glossary": {
"core_industry_terms": {
- "surface_imperfections": {"en": "Surface Imperfections", "vi": "Khuyết điểm bề mặt", "def": "Microscopic variations (fingerprints, micro-scratches) that break uniform reflections."},
- "weathering_aging": {"en": "Weathering / Aging", "vi": "Phong hóa / Lão hóa", "def": "Surface degradation from environmental exposure over time."},
- "wear_and_tear": {"en": "Wear and Tear", "vi": "Hao mòn sử dụng", "def": "Physical damage from active use or friction."},
- "edge_wear": {"en": "Edge Wear", "vi": "Mòn cạnh viền", "def": "Damage concentrated along sharp corners or high-exposure edges."},
- "procedural_grunge": {"en": "Procedural Grunge", "vi": "Cáu bẩn thuật toán", "def": "Algorithmically generated dirt distributed via AO or curvature masks."}
+ "surface_imperfections": {"en": "Surface Imperfections", "def": "Microscopic variations (fingerprints, micro-scratches) that break uniform reflections."},
+ "weathering_aging": {"en": "Weathering / Aging", "def": "Surface degradation from environmental exposure over time."},
+ "wear_and_tear": {"en": "Wear and Tear", "def": "Physical damage from active use or friction."},
+ "edge_wear": {"en": "Edge Wear", "def": "Damage concentrated along sharp corners or high-exposure edges."},
+ "procedural_grunge": {"en": "Procedural Grunge", "def": "Algorithmically generated dirt distributed via AO or curvature masks."}
},
"damage_types_pbr_impact": {
"oxidation_rust_patina": {
"en": "Oxidation / Rust / Patina",
- "vi": "Oxy hóa / Rỉ sét / Lớp ô-xy hóa",
+
"albedo": "Orange-brown or dark-green shift",
"roughness": {"range": [0.8, 1.0], "impact": "Increases significantly"},
"metalness": {"range": [0.0, 0.0], "impact": "Drops to 0 (Dielectric oxide)"},
@@ -173,7 +173,7 @@
},
"scratches_dents": {
"en": "Scratches / Dents",
- "vi": "Vết xước / Móp méo",
+
"albedo": "Exposes base silver/grey metal",
"roughness": {"range": [0.1, 0.2], "impact": "Decreases at center (shiny base)"},
"metalness": {"range": [1.0, 1.0], "impact": "Increases if paint is scraped"},
@@ -181,7 +181,7 @@
},
"smudges_fingerprints": {
"en": "Smudges / Fingerprints",
- "vi": "Vết ố / Dấu vân tay",
+
"albedo": "Negligible change",
"roughness": {"range": [0.4, 0.6], "impact": "Localized increase (oily layer)"},
"metalness": {"range": [null, null], "impact": "Unchanged"},
@@ -189,7 +189,7 @@
},
"dust_dirt_mud": {
"en": "Dust / Dirt / Mud",
- "vi": "Bụi / Đất sét / Bùn",
+
"albedo": "Matches environment (tan/brown/grey)",
"roughness": {"range": [0.9, 1.0], "impact": "Becomes completely rough"},
"metalness": {"range": [0.0, 0.0], "impact": "Drops to 0 (Non-metallic soil)"},
@@ -197,11 +197,11 @@
}
},
"spatial_modifiers": {
- "tip_to_spine_gradient": {"en": "Tip-to-spine gradient", "vi": "Gradient từ mũi đến sống dao"},
- "edge_heavy": {"en": "Edge-heavy wear", "vi": "Mòn tập trung ở cạnh"},
- "friction_point": {"en": "Friction-point wear", "vi": "Mòn điểm ma sát"},
- "speckled": {"en": "Speckled", "vi": "Dạng đốm"},
- "exposed_core": {"en": "Exposed core", "vi": "Lộ lõi"}
+ "tip_to_spine_gradient": {"en": "Tip-to-spine gradient"},
+ "edge_heavy": {"en": "Edge-heavy wear"},
+ "friction_point": {"en": "Friction-point wear"},
+ "speckled": {"en": "Speckled"},
+ "exposed_core": {"en": "Exposed core"}
}
}
}
diff --git a/docs/cs2/3D_Vocabulary_CS2.json b/docs/cs2/3D_Vocabulary_CS2.json
index a2b2cbd..c3dcf45 100644
--- a/docs/cs2/3D_Vocabulary_CS2.json
+++ b/docs/cs2/3D_Vocabulary_CS2.json
@@ -9,153 +9,153 @@
"core_3d_modeling": {
"name": "Core 3D Modeling",
"terms": {
- "vertex": {"en": "Vertex", "vi": "Đỉnh", "def": "A point in 3D space with X, Y, Z coordinates"},
- "edge": {"en": "Edge", "vi": "Cạnh", "def": "A line connecting two vertices"},
- "face": {"en": "Face", "vi": "Mặt", "def": "A flat surface enclosed by 3+ edges"},
- "polygon": {"en": "Polygon", "vi": "Đa giác", "def": "Generic term for a face (triangles, quads)"},
- "triangle": {"en": "Triangle (Tris)", "vi": "Tam giác", "def": "A 3-sided polygon"},
- "quad": {"en": "Quad", "vi": "Tứ giác", "def": "A 4-sided polygon, preferred for clean topology"},
- "n_gon": {"en": "N-gon", "vi": "N-cạnh", "def": "Polygon with 5+ sides, generally avoided"},
- "mesh": {"en": "Mesh", "vi": "Lưới", "def": "Complete geometric structure of a 3D object"},
- "topology": {"en": "Topology", "vi": "Cấu trúc", "def": "Arrangement and flow of polygons on mesh surface"},
- "edge_loop": {"en": "Edge Loop", "vi": "Vòng cạnh", "def": "Continuous ring of edges flowing around mesh"},
- "retopology": {"en": "Retopology", "vi": "Tái cấu trúc", "def": "Redrawing mesh with cleaner topology"},
- "high_poly": {"en": "High-Poly", "vi": "Đa giác cao", "def": "Mesh with many polygons for detail"},
- "low_poly": {"en": "Low-Poly", "vi": "Đa giác thấp", "def": "Mesh with few polygons, optimized for real-time"},
- "buffer_geometry": {"en": "BufferGeometry", "vi": "BufferGeometry", "def": "Three.js class for custom geometry"}
+ "vertex": {"en": "Vertex", "def": "A point in 3D space with X, Y, Z coordinates"},
+ "edge": {"en": "Edge", "def": "A line connecting two vertices"},
+ "face": {"en": "Face", "def": "A flat surface enclosed by 3+ edges"},
+ "polygon": {"en": "Polygon", "def": "Generic term for a face (triangles, quads)"},
+ "triangle": {"en": "Triangle (Tris)", "def": "A 3-sided polygon"},
+ "quad": {"en": "Quad", "def": "A 4-sided polygon, preferred for clean topology"},
+ "n_gon": {"en": "N-gon", "def": "Polygon with 5+ sides, generally avoided"},
+ "mesh": {"en": "Mesh", "def": "Complete geometric structure of a 3D object"},
+ "topology": {"en": "Topology", "def": "Arrangement and flow of polygons on mesh surface"},
+ "edge_loop": {"en": "Edge Loop", "def": "Continuous ring of edges flowing around mesh"},
+ "retopology": {"en": "Retopology", "def": "Redrawing mesh with cleaner topology"},
+ "high_poly": {"en": "High-Poly", "def": "Mesh with many polygons for detail"},
+ "low_poly": {"en": "Low-Poly", "def": "Mesh with few polygons, optimized for real-time"},
+ "buffer_geometry": {"en": "BufferGeometry", "def": "Three.js class for custom geometry"}
}
},
"uv_mapping": {
"name": "UV Mapping & Texturing",
"terms": {
- "uv_mapping": {"en": "UV Mapping", "vi": "Ánh xạ UV", "def": "Unwrapping 3D surface onto 2D plane for textures"},
- "uv_coordinates": {"en": "UV Coordinates", "vi": "Tọa độ UV", "def": "2D coordinates mapping texture to surface"},
- "uv_seam": {"en": "UV Seam", "vi": "Đường may UV", "def": "Edges where UV map is cut for flattening"},
- "diffuse_map": {"en": "Diffuse/Albedo Map", "vi": "Bản đồ màu", "def": "Base color texture without lighting"},
- "normal_map": {"en": "Normal Map", "vi": "Bản đồ Normal", "def": "RGB texture simulating surface bumps"},
- "roughness_map": {"en": "Roughness Map", "vi": "Bản đồ thô", "def": "Controls surface smoothness (0=smooth, 1=rough)"},
- "metallic_map": {"en": "Metallic Map", "vi": "Bản đồ kim loại", "def": "Defines metallic vs non-metallic areas"},
- "ao_map": {"en": "Ambient Occlusion", "vi": "Che sáng môi trường", "def": "Shows areas where ambient light is blocked"},
- "displacement_map": {"en": "Displacement Map", "vi": "Bản đồ dịch chuyển", "def": "Actually moves vertices for real detail"},
- "emission_map": {"en": "Emission Map", "vi": "Bản đồ phát sáng", "def": "Defines which parts emit light"},
- "mipmapping": {"en": "Mipmapping", "vi": "Mipmap", "def": "Pre-calculated lower-res texture copies"}
+ "uv_mapping": {"en": "UV Mapping", "def": "Unwrapping 3D surface onto 2D plane for textures"},
+ "uv_coordinates": {"en": "UV Coordinates", "def": "2D coordinates mapping texture to surface"},
+ "uv_seam": {"en": "UV Seam", "def": "Edges where UV map is cut for flattening"},
+ "diffuse_map": {"en": "Diffuse/Albedo Map", "def": "Base color texture without lighting"},
+ "normal_map": {"en": "Normal Map", "def": "RGB texture simulating surface bumps"},
+ "roughness_map": {"en": "Roughness Map", "def": "Controls surface smoothness (0=smooth, 1=rough)"},
+ "metallic_map": {"en": "Metallic Map", "def": "Defines metallic vs non-metallic areas"},
+ "ao_map": {"en": "Ambient Occlusion", "def": "Shows areas where ambient light is blocked"},
+ "displacement_map": {"en": "Displacement Map", "def": "Actually moves vertices for real detail"},
+ "emission_map": {"en": "Emission Map", "def": "Defines which parts emit light"},
+ "mipmapping": {"en": "Mipmapping", "def": "Pre-calculated lower-res texture copies"}
}
},
"pbr_materials": {
"name": "PBR Materials",
"terms": {
- "pbr": {"en": "PBR (Physically Based Rendering)", "vi": "Render dựa trên vật lý", "def": "Rendering simulating real-world light interaction"},
- "metallic_roughness": {"en": "Metallic/Roughness Workflow", "vi": "Quy trình Kim loại/Thô", "def": "PBR workflow using Base Color + Metallic + Roughness"},
- "specular_glossiness": {"en": "Specular/Glossiness Workflow", "vi": "Quy trình Phản chiếu/Bóng", "def": "Alternative PBR workflow"},
- "base_color": {"en": "Base Color", "vi": "Màu cơ bản", "def": "Fundamental surface color without lighting"},
- "metalness": {"en": "Metalness", "vi": "Độ kim loại", "def": "0=dielectric, 1=metal"},
- "roughness": {"en": "Roughness", "vi": "Độ thô", "def": "0=mirror-smooth, 1=completely rough"},
- "fresnel": {"en": "Fresnel", "vi": "Fresnel", "def": "Reflectivity increases at grazing angles"},
- "energy_conservation": {"en": "Energy Conservation", "vi": "Bảo toàn năng lượng", "def": "Reflected light cannot exceed incoming light"}
+ "pbr": {"en": "PBR (Physically Based Rendering)", "def": "Rendering simulating real-world light interaction"},
+ "metallic_roughness": {"en": "Metallic/Roughness Workflow", "def": "PBR workflow using Base Color + Metallic + Roughness"},
+ "specular_glossiness": {"en": "Specular/Glossiness Workflow", "def": "Alternative PBR workflow"},
+ "base_color": {"en": "Base Color", "def": "Fundamental surface color without lighting"},
+ "metalness": {"en": "Metalness", "def": "0=dielectric, 1=metal"},
+ "roughness": {"en": "Roughness", "def": "0=mirror-smooth, 1=completely rough"},
+ "fresnel": {"en": "Fresnel", "def": "Reflectivity increases at grazing angles"},
+ "energy_conservation": {"en": "Energy Conservation", "def": "Reflected light cannot exceed incoming light"}
}
},
"cs2_specific": {
"name": "CS2 Specific Terminology",
"terms": {
- "skin": {"en": "Skin", "vi": "Da súng", "def": "Cosmetic finish changing weapon appearance"},
- "paint_kit": {"en": "Paint Kit", "vi": "Bộ sơn", "def": "Complete texture set defining skin appearance"},
- "float_value": {"en": "Float Value", "vi": "Giá trị float", "def": "Decimal 0.000-1.000 determining wear"},
- "factory_new": {"en": "Factory New (FN)", "vi": "Mới từ nhà máy", "def": "Float 0.00-0.07, pristine condition"},
- "minimal_wear": {"en": "Minimal Wear (MW)", "vi": "Mòn tối thiểu", "def": "Float 0.07-0.15, minor scratches"},
- "field_tested": {"en": "Field-Tested (FT)", "vi": "Đã thử nghiệm", "def": "Float 0.15-0.38, noticeable wear"},
- "well_worn": {"en": "Well-Worn (WW)", "vi": "Mòn nhiều", "def": "Float 0.38-0.45, significant wear"},
- "battle_scarred": {"en": "Battle-Scarred (BS)", "vi": "Chiến tích", "def": "Float 0.45-1.00, heavy damage"},
- "pattern_index": {"en": "Pattern Index", "vi": "Chỉ mẫu", "def": "Integer 0-1000 controlling texture slice"},
- "blue_gem": {"en": "Blue Gem", "vi": "Đá xanh", "def": "Rare Case Hardened pattern, mostly blue"},
- "fade_percentage": {"en": "Fade Percentage", "vi": "Phần trăm Fade", "def": "Color gradient visibility on Fade skins"},
- "doppler_phase": {"en": "Doppler Phase", "vi": "Giai đoạn Doppler", "def": "Color variations in Doppler skins"},
- "stattrak": {"en": "StatTrak™", "vi": "StatTrak™", "def": "Kill counter variant, ~10% drop rate"},
- "souvenir": {"en": "Souvenir", "vi": "Hàng lưu niệm", "def": "Major tournament exclusive with stickers"},
- "sticker": {"en": "Sticker", "vi": "Tem", "def": "Cosmetic item applied to weapons"},
- "sticker_craft": {"en": "Sticker Craft", "vi": "Bộ tem", "def": "Combination of skin with applied stickers"},
- "wear_remap": {"en": "Float Clipping", "vi": "Cắt float", "def": "Per-skin float range restriction"}
+ "skin": {"en": "Skin", "def": "Cosmetic finish changing weapon appearance"},
+ "paint_kit": {"en": "Paint Kit", "def": "Complete texture set defining skin appearance"},
+ "float_value": {"en": "Float Value", "def": "Decimal 0.000-1.000 determining wear"},
+ "factory_new": {"en": "Factory New (FN)", "def": "Float 0.00-0.07, pristine condition"},
+ "minimal_wear": {"en": "Minimal Wear (MW)", "def": "Float 0.07-0.15, minor scratches"},
+ "field_tested": {"en": "Field-Tested (FT)", "def": "Float 0.15-0.38, noticeable wear"},
+ "well_worn": {"en": "Well-Worn (WW)", "def": "Float 0.38-0.45, significant wear"},
+ "battle_scarred": {"en": "Battle-Scarred (BS)", "def": "Float 0.45-1.00, heavy damage"},
+ "pattern_index": {"en": "Pattern Index", "def": "Integer 0-1000 controlling texture slice"},
+ "blue_gem": {"en": "Blue Gem", "def": "Rare Case Hardened pattern, mostly blue"},
+ "fade_percentage": {"en": "Fade Percentage", "def": "Color gradient visibility on Fade skins"},
+ "doppler_phase": {"en": "Doppler Phase", "def": "Color variations in Doppler skins"},
+ "stattrak": {"en": "StatTrak™", "def": "Kill counter variant, ~10% drop rate"},
+ "souvenir": {"en": "Souvenir", "def": "Major tournament exclusive with stickers"},
+ "sticker": {"en": "Sticker", "def": "Cosmetic item applied to weapons"},
+ "sticker_craft": {"en": "Sticker Craft", "def": "Combination of skin with applied stickers"},
+ "wear_remap": {"en": "Float Clipping", "def": "Per-skin float range restriction"}
}
},
"file_formats": {
"name": "3D File Formats",
"terms": {
- "obj": {"en": "OBJ", "vi": "OBJ", "def": "Simple text format for geometry, no animation"},
- "fbx": {"en": "FBX", "vi": "FBX", "def": "Autodesk format, primary game engine exchange"},
- "gltf_glb": {"en": "glTF/GLB", "vi": "glTF/GLB", "def": "Open web standard, GLB is binary version"},
- "stl": {"en": "STL", "vi": "STL", "def": "Geometry-only, standard for 3D printing"},
- "mdl": {"en": "MDL", "vi": "MDL", "def": "Valve's model format for Source engine"},
- "vtf": {"en": "VTF", "vi": "VTF", "def": "Valve Texture Format"},
- "vmt": {"en": "VMT", "vi": "VMT", "def": "Valve Material Type definition"},
- "items_game": {"en": "items_game.txt", "vi": "items_game.txt", "def": "CS2 config defining all item properties"}
+ "obj": {"en": "OBJ", "def": "Simple text format for geometry, no animation"},
+ "fbx": {"en": "FBX", "def": "Autodesk format, primary game engine exchange"},
+ "gltf_glb": {"en": "glTF/GLB", "def": "Open web standard, GLB is binary version"},
+ "stl": {"en": "STL", "def": "Geometry-only, standard for 3D printing"},
+ "mdl": {"en": "MDL", "def": "Valve's model format for Source engine"},
+ "vtf": {"en": "VTF", "def": "Valve Texture Format"},
+ "vmt": {"en": "VMT", "def": "Valve Material Type definition"},
+ "items_game": {"en": "items_game.txt", "def": "CS2 config defining all item properties"}
}
},
"animation_rigging": {
"name": "Animation & Rigging",
"terms": {
- "skeleton": {"en": "Skeleton", "vi": "Bộ xương", "def": "Hierarchical bone structure for deformation"},
- "bone": {"en": "Bone", "vi": "Xương", "def": "Individual element in skeleton hierarchy"},
- "rigging": {"en": "Rigging", "vi": "Cấp xương", "def": "Creating and binding skeleton to mesh"},
- "weight_painting": {"en": "Weight Painting", "vi": "Vẽ trọng số", "def": "Defining bone influence on vertices"},
- "keyframe": {"en": "Keyframe Animation", "vi": "Hoạt hình khoá khung", "def": "Animation defined by specific poses at times"},
- "ik": {"en": "Inverse Kinematics (IK)", "vi": "Động học nghịch đảo", "def": "Calculate joints from end position"},
- "fk": {"en": "Forward Kinematics (FK)", "vi": "Động học thuận", "def": "Set rotations from root to tip"},
- "morph_targets": {"en": "Morph Targets", "vi": "Mục tiêu biến đổi", "def": "Pre-defined vertex positions for blending"},
- "skinned_mesh": {"en": "SkinnedMesh", "vi": "SkinnedMesh", "def": "Three.js mesh deformable by skeleton"}
+ "skeleton": {"en": "Skeleton", "def": "Hierarchical bone structure for deformation"},
+ "bone": {"en": "Bone", "def": "Individual element in skeleton hierarchy"},
+ "rigging": {"en": "Rigging", "def": "Creating and binding skeleton to mesh"},
+ "weight_painting": {"en": "Weight Painting", "def": "Defining bone influence on vertices"},
+ "keyframe": {"en": "Keyframe Animation", "def": "Animation defined by specific poses at times"},
+ "ik": {"en": "Inverse Kinematics (IK)", "def": "Calculate joints from end position"},
+ "fk": {"en": "Forward Kinematics (FK)", "def": "Set rotations from root to tip"},
+ "morph_targets": {"en": "Morph Targets", "def": "Pre-defined vertex positions for blending"},
+ "skinned_mesh": {"en": "SkinnedMesh", "def": "Three.js mesh deformable by skeleton"}
}
},
"rendering_optimization": {
"name": "Rendering & Optimization",
"terms": {
- "draw_call": {"en": "Draw Call", "vi": "Lệnh vẽ", "def": "Single CPU→GPU command to render"},
- "batching": {"en": "Batching", "vi": "Gộp", "def": "Combining objects into fewer draw calls"},
- "instancing": {"en": "Instancing", "vi": "Thực thể hóa", "def": "Rendering many copies with one draw call"},
- "lod": {"en": "Level of Detail (LOD)", "vi": "Chi tiết cấp độ", "def": "Lower-poly models at distance"},
- "polygon_budget": {"en": "Polygon Budget", "vi": "Ngân sách đa giác", "def": "Max polygons allowed for object/scene"},
- "occlusion_culling": {"en": "Occlusion Culling", "vi": "Loại trừ che khuất", "def": "Not rendering hidden objects"},
- "frustum_culling": {"en": "Frustum Culling", "vi": "Loại trừ ngoài khung hình", "def": "Not rendering objects outside view"}
+ "draw_call": {"en": "Draw Call", "def": "Single CPU→GPU command to render"},
+ "batching": {"en": "Batching", "def": "Combining objects into fewer draw calls"},
+ "instancing": {"en": "Instancing", "def": "Rendering many copies with one draw call"},
+ "lod": {"en": "Level of Detail (LOD)", "def": "Lower-poly models at distance"},
+ "polygon_budget": {"en": "Polygon Budget", "def": "Max polygons allowed for object/scene"},
+ "occlusion_culling": {"en": "Occlusion Culling", "def": "Not rendering hidden objects"},
+ "frustum_culling": {"en": "Frustum Culling", "def": "Not rendering objects outside view"}
}
},
"threejs_web3d": {
"name": "Three.js / Web 3D",
"terms": {
- "webgl": {"en": "WebGL", "vi": "WebGL", "def": "JavaScript API for hardware-accelerated 3D"},
- "scene": {"en": "Scene", "vi": "Cảnh", "def": "Container for all 3D objects"},
- "camera": {"en": "Camera", "vi": "Máy ảnh", "def": "Defines the viewpoint"},
- "renderer": {"en": "Renderer", "vi": "Bộ kết xuất", "def": "Converts scene to pixels"},
- "mesh_standard": {"en": "MeshStandardMaterial", "vi": "MeshStandardMaterial", "def": "PBR material, most realistic"},
- "mesh_phong": {"en": "MeshPhongMaterial", "vi": "MeshPhongMaterial", "def": "Simpler, faster for mobile"},
- "gltf_loader": {"en": "GLTFLoader", "vi": "GLTFLoader", "def": "Loads glTF/GLB files"},
- "instanced_mesh": {"en": "InstancedMesh", "vi": "InstancedMesh", "def": "Many copies with one draw call"}
+ "webgl": {"en": "WebGL", "def": "JavaScript API for hardware-accelerated 3D"},
+ "scene": {"en": "Scene", "def": "Container for all 3D objects"},
+ "camera": {"en": "Camera", "def": "Defines the viewpoint"},
+ "renderer": {"en": "Renderer", "def": "Converts scene to pixels"},
+ "mesh_standard": {"en": "MeshStandardMaterial", "def": "PBR material, most realistic"},
+ "mesh_phong": {"en": "MeshPhongMaterial", "def": "Simpler, faster for mobile"},
+ "gltf_loader": {"en": "GLTFLoader", "def": "Loads glTF/GLB files"},
+ "instanced_mesh": {"en": "InstancedMesh", "def": "Many copies with one draw call"}
}
},
"cs2_workshop": {
"name": "CS2 Workshop Workflow",
"terms": {
- "workshop_submission": {"en": "Workshop Submission", "vi": "Gửi lên Workshop", "def": "Submitting custom skins to CS2"},
- "substance_painter": {"en": "Substance Painter", "vi": "Substance Painter", "def": "Industry-standard texture painting tool"},
- "source_2": {"en": "Source 2", "vi": "Source 2", "def": "Valve's game engine for CS2"},
- "tri_count": {"en": "Tri Count", "vi": "Số tam giác", "def": "Total triangle count of weapon model"},
- "paint_pattern": {"en": "Paint Pattern", "vi": "Mẫu sơn", "def": "2D texture projected onto 3D via UV"},
- "wear_overlay": {"en": "Wear Overlay", "vi": "Lớp phủ mòn", "def": "Texture adding damage based on float"},
- "material_proxy": {"en": "Material Proxy", "vi": "Proxy vật liệu", "def": "Dynamic parameter changes based on state"}
+ "workshop_submission": {"en": "Workshop Submission", "def": "Submitting custom skins to CS2"},
+ "substance_painter": {"en": "Substance Painter", "def": "Industry-standard texture painting tool"},
+ "source_2": {"en": "Source 2", "def": "Valve's game engine for CS2"},
+ "tri_count": {"en": "Tri Count", "def": "Total triangle count of weapon model"},
+ "paint_pattern": {"en": "Paint Pattern", "def": "2D texture projected onto 3D via UV"},
+ "wear_overlay": {"en": "Wear Overlay", "def": "Texture adding damage based on float"},
+ "material_proxy": {"en": "Material Proxy", "def": "Dynamic parameter changes based on state"}
}
}
},
"cs2_wear_ranges": {
- "factory_new": {"min": 0.00, "max": 0.07, "abbreviation": "FN", "vi": "Mới từ nhà máy"},
- "minimal_wear": {"min": 0.07, "max": 0.15, "abbreviation": "MW", "vi": "Mòn tối thiểu"},
- "field_tested": {"min": 0.15, "max": 0.38, "abbreviation": "FT", "vi": "Đã thử nghiệm"},
- "well_worn": {"min": 0.38, "max": 0.45, "abbreviation": "WW", "vi": "Mòn nhiều"},
- "battle_scarred": {"min": 0.45, "max": 1.00, "abbreviation": "BS", "vi": "Chiến tích"}
+ "factory_new": {"min": 0.00, "max": 0.07, "abbreviation": "FN"},
+ "minimal_wear": {"min": 0.07, "max": 0.15, "abbreviation": "MW"},
+ "field_tested": {"min": 0.15, "max": 0.38, "abbreviation": "FT"},
+ "well_worn": {"min": 0.38, "max": 0.45, "abbreviation": "WW"},
+ "battle_scarred": {"min": 0.45, "max": 1.00, "abbreviation": "BS"}
},
"cs2_rarity_grades": [
- {"grade": "Consumer Grade", "vi": "Hàng tiêu dùng", "color": "white"},
- {"grade": "Industrial Grade", "vi": "Hàng công nghiệp", "color": "light blue"},
- {"grade": "Mil-Spec", "vi": "Mil-Spec", "color": "blue"},
- {"grade": "Restricted", "vi": "Hạn chế", "color": "purple"},
- {"grade": "Classified", "vi": "Phân loại", "color": "pink"},
- {"grade": "Covert", "vi": "Bí mật", "color": "red"},
- {"grade": "Contraband", "vi": "Hàng cấm", "color": "gold"}
+ {"grade": "Consumer Grade", "color": "white"},
+ {"grade": "Industrial Grade", "color": "light blue"},
+ {"grade": "Mil-Spec", "color": "blue"},
+ {"grade": "Restricted", "color": "purple"},
+ {"grade": "Classified", "color": "pink"},
+ {"grade": "Covert", "color": "red"},
+ {"grade": "Contraband", "color": "gold"}
],
"cs2_finish_styles": [
"Anodized",
diff --git a/docs/integrations/reference_fidelity_tooling.md b/docs/integrations/reference_fidelity_tooling.md
new file mode 100644
index 0000000..d914e56
--- /dev/null
+++ b/docs/integrations/reference_fidelity_tooling.md
@@ -0,0 +1,143 @@
+# Reference-fidelity tooling
+
+This integration layer strengthens image matching without changing the core contract: output remains
+procedural, reviewable Three.js code. External tools may produce evidence and diagnostics; they may
+not silently provide meshes, decide hidden geometry, mutate the accepted source, or approve a pass.
+
+## Default routing
+
+| Need | Primary tool | Output | Authority boundary |
+| --- | --- | --- | --- |
+| Browser render, console, network and performance trace | Chrome DevTools MCP | screenshot, trace, console/network evidence | diagnostic only |
+| Three.js scene/material/renderer inspection | threejs-devtools MCP | scene tree, material/texture state, renderer metrics | read-only findings until reflected in code |
+| Cross-browser reproduction | Playwright MCP | Chrome/Firefox/WebKit screenshot and trace | fallback; do not duplicate the default Chrome loop |
+| Version-aware Three.js documentation | Context7 | cited, version-specific API context | local installed Three.js and typecheck remain authoritative |
+| Thin/complex foreground or component mask | SAM2 adapter | binary PNG mask + provenance JSON | agent confirms the intended subject/component |
+| Character face or body evidence | MediaPipe adapter | normalized landmark JSON | anatomy/spec review required |
+| Weak front/back depth cues | Depth Anything V2 adapter | 16-bit relative-depth PNG + provenance JSON | relative prior only, never metric or hidden geometry |
+
+## Codex MCP configuration
+
+The intended user-level servers are pinned:
+
+```text
+chrome-devtools [email protected]
+threejs-devtools [email protected]
+playwright @playwright/[email protected] (Chromium)
+playwright-firefox @playwright/[email protected]
+playwright-webkit @playwright/[email protected]
+context7 @upstash/[email protected]
+```
+
+For the reference loop, use Chrome DevTools in an isolated, headless profile with usage statistics
+and CrUX URL lookup disabled. Use a 1600x900 viewport unless the reference contract specifies
+another size. The repository's own screenshot harness remains the evidence producer; MCP captures
+are for diagnosis or a host fallback.
+
+The three Playwright routes use isolated, headless 1600x900 profiles with service workers blocked.
+Use Chromium for the default reproduction and call the Firefox/WebKit server only when validating a
+cross-browser discrepancy.
+
+### Chrome DevTools MCP
+
+Use during render and optimization:
+
+1. Navigate to the exact local preview URL.
+2. Wait for `window.__IMG2THREEJS_READY__ === true`.
+3. Confirm texture/asset readiness and collect console/network failures.
+4. Disable controls and set the named review camera.
+5. Capture a PNG at the reference viewport.
+6. Read `window.__IMG2THREEJS_VIEWER__.renderer.info` and record draw calls, triangles,
+ geometries, textures and programs.
+7. Run a performance trace only after the visual pass is accepted.
+
+Never accept an MCP-only scene edit. Copy the proven parameter change into the spec or generated
+TypeScript, rebuild, and recapture.
+
+### threejs-devtools MCP
+
+Use the read-only tools first: scene tree, object/geometry details, material and texture details,
+camera, renderer info, performance snapshot and memory diagnostics. Mutation tools are scratch
+experiments. A changed transform, material, light, camera or renderer setting has no standing until
+the source/spec contains it and the deterministic capture loop reproduces it.
+
+### Playwright MCP
+
+Use the `playwright` server for the normal Chromium fallback. Repeat an already-failing case with
+`playwright-firefox` or `playwright-webkit`; do not run three browsers on every refinement cycle.
+Cross-browser captures diagnose runtime portability and cannot replace the named-camera fidelity
+gate.
+
+### Context7
+
+Ask for the installed Three.js version explicitly. The companion showcase currently controls the
+runtime version; its `package-lock.json`, local `.d.ts`, typecheck and runtime smoke tests override
+live documentation. WebGPU/TSL advice must not be applied to the WebGL/r169 path without an explicit
+version migration.
+
+## Local vision environment
+
+Install:
+
+```bash
+uv sync --project integrations/vision --python 3.11
+python3 forge/stage1_intake/run_vision_adapter.py prefetch
+python3 forge/stage1_intake/run_vision_adapter.py health
+```
+
+### SAM2 component masks
+
+Use one positive point inside the visible subject or component:
+
+```bash
+python3 forge/stage1_intake/run_vision_adapter.py \
+ segment reference.png --point 512 320 --out evidence/body-mask.png
+```
+
+Inspect the PNG before recording it. Store the JSON sidecar as an evidence record. Use separate
+masks for identity systems such as body, wing, blade, handle, hair or face; do not treat one global
+foreground mask as component decomposition.
+
+### Depth Anything V2
+
+```bash
+python3 forge/stage1_intake/run_vision_adapter.py \
+ depth reference.png --out evidence/relative-depth.png
+```
+
+Use the result to propose front/back ordering, thickness candidates and camera hypotheses. Do not
+use its values as metric dimensions or invent unseen backsides.
+
+### MediaPipe
+
+```bash
+python3 forge/stage1_intake/run_vision_adapter.py \
+ landmarks face reference.png --out evidence/face-landmarks.json
+
+python3 forge/stage1_intake/run_vision_adapter.py \
+ landmarks pose reference.png --out evidence/pose-landmarks.json
+```
+
+Normalize and map accepted landmarks into `preSpecAssessment.anatomy`; keep the source image and
+model hashes in evidence refs. On macOS, MediaPipe Tasks creates a Metal graphics context even when
+the inference delegate is CPU, so a restricted/headless sandbox must grant graphics access.
+
+## Loop placement
+
+```text
+reference admission
+ -> optional SAM2 / MediaPipe / relative-depth evidence
+ -> pre-spec assessment and local spec search
+ -> camera solve, de-light and projection bake
+ -> strict ObjectSculptSpec
+ -> pass-gated Three.js generation
+ -> deterministic repository capture
+ -> MCP diagnosis when needed
+ -> Divine Eye + feature microscope
+ -> refine-spec / refine-code / request-input / continue
+ -> performance trace after fidelity acceptance
+```
+
+The reference view and meaningful orbit views remain separate gates. Projection can make the
+reference camera match closely, but it cannot substitute for thickness, attachment, component
+coverage or multi-angle 3D truth.
diff --git a/docs/materials/IMAGE_MATERIAL_ANALYSIS.md b/docs/materials/IMAGE_MATERIAL_ANALYSIS.md
new file mode 100644
index 0000000..433a713
--- /dev/null
+++ b/docs/materials/IMAGE_MATERIAL_ANALYSIS.md
@@ -0,0 +1,112 @@
+# Mandatory image material analysis
+
+Material analysis is an admission gate for material authoring. A model may not enter or pass the
+material build pass merely because every component has a material ID. Each critical visible region
+must have evidence that the ID and rendered response are plausible for the reference.
+
+## 1. Inputs
+
+- admitted reference images with hashes, roles and camera metadata;
+- component masks and material-region masks per usable view;
+- prompt or authoritative metadata supplied by the user;
+- named component and region IDs that remain stable through UV, skinning, morphs and LOD;
+- crop resolution and visible-footprint coverage.
+
+Reject empty, inverted, fragmented, duplicate or too-small crops before classification. Cropping a
+nearby component is a failed gate, not low-confidence evidence.
+
+## 2. Observation before classification
+
+For each material region, record observable signals without naming the material first:
+
+- de-lit base-colour distribution and colour variation;
+- highlight colour, width, sharpness, elongation and view dependence;
+- diffuse versus specular balance;
+- fibre, grain, strand, brushing or machining direction;
+- macro, meso and micro surface frequency bands;
+- opacity, refraction, transmission and apparent thickness cues;
+- edge wear, coating chips, oxidation, dirt, wetness and cavity response;
+- component context: garment, skin surface, blade, trim, lens, hair mass, tyre, wood panel;
+- occlusion and uncertainty per view.
+
+Do not classify material from colour alone. Black plastic, rubber, leather and cloth can share an
+albedo. Gold metal, brass and metallic yellow paint can share a hue. The light-response evidence is
+the discriminator.
+
+## 3. Hypothesis record
+
+Every region emits:
+
+```json
+{
+ "componentId": "jacket",
+ "regionId": "body-cloth",
+ "family": "fabric",
+ "subtype": "woven",
+ "finish": "matte",
+ "confidence": 0.78,
+ "evidenceViews": ["front-primary", "three-quarter-right"],
+ "sourceCropPaths": ["jacket-front.png", "jacket-3q.png"],
+ "observations": [],
+ "alternatives": [
+ {"materialId": "leather.matte", "confidence": 0.31}
+ ],
+ "status": "proceed"
+}
+```
+
+Allowed status values are `proceed`, `probe`, `request-input` and `unknown`. Missing confidence,
+crop, mask or evidence view fails closed.
+
+## 4. Lookup and evidence reconciliation
+
+Resolve the hypothesis against `material-reference.json`. Semantic vision provides candidate
+identity; deterministic image analysis provides colour, gradient, highlight and frequency evidence.
+Neither source decides alone.
+
+- If both agree above the configured threshold, seed the candidate recipe.
+- If identity is known but surface evidence is weak, retain the identity and mark PBR values for
+ controlled-render fitting.
+- If the highest candidates are materially different and the distinction is critical, request
+ another view or explicit user metadata.
+- Never raise confidence merely because a default recipe produced an attractive render.
+
+## 5. Map and shader authoring
+
+- `map`, `emissiveMap`, `sheenColorMap` and `specularColorMap` are colour data and use sRGB.
+- Roughness, metalness, normal, AO, clearcoat, thickness, transmission, anisotropy and iridescence
+ maps are mathematical data and use no colour-space transform.
+- Albedo, roughness, metalness, normal/height and AO are independent signals.
+- Coated surfaces represent the top layer correctly: intact paint is dielectric even when its
+ substrate is metal; exposed chips may use a separate metallic region or mask.
+- Geometry supplies silhouette-scale fibres, fur tufts, hair clumps, folds, facets and deep damage.
+ Normal/bump maps supply sub-pixel or small-scale relief; albedo must not fake missing form.
+
+## 6. Controlled validation views
+
+Every critical material requires the views named by its lookup record:
+
+- `albedo-unlit`: verifies de-lit colour and pattern;
+- `neutral-studio`: verifies balanced diffuse/specular response;
+- `grazing`: reveals roughness, normal strength, sheen and anisotropy;
+- `environment-reflection`: distinguishes conductors and polished coatings;
+- `backlight-transmission`: required for transmissive or thin materials;
+- `reference-beauty`: verifies the final appearance at the solved camera.
+
+Wait for every texture to load before capture. Save each image, read it back, and compare the
+component's visible footprint rather than an isolation render that reveals occluded surface.
+
+## 7. Gate policy
+
+The material pass fails when:
+
+- a critical visible region has no hypothesis or lookup result;
+- one material is assigned across visibly incompatible regions;
+- evidence confidence is below threshold and no explicit user identity resolves it;
+- required maps or controlled views are missing;
+- a conductor renders like a dielectric, fabric like smooth plastic, hair like rubber, or glass as
+ alpha-blended air;
+- a high global beauty score hides a failed critical material region;
+- texture loading, colour space, environment preprocessing or screenshot readback fails.
+
+Unknown is an acceptable analysis result. Silent substitution is not.
diff --git a/docs/materials/README.md b/docs/materials/README.md
new file mode 100644
index 0000000..c435d5b
--- /dev/null
+++ b/docs/materials/README.md
@@ -0,0 +1,111 @@
+# img2threejs material reference library
+
+This directory is the canonical bridge between image material analysis and Three.js material
+authoring. It is deliberately split into a human contract and machine-readable data:
+
+- `THREEJS_MATERIAL_REFERENCE.md` explains the rendering rules and the starter recipes.
+- `IMAGE_MATERIAL_ANALYSIS.md` defines the mandatory per-component analysis gate.
+- `material-reference.json` is the versioned lookup table consumed by future analyzer/spec wiring.
+
+The library stores **starting priors**, not universal truth. Roughness, clearcoat, transmission and
+other appearance parameters depend on finish, wear, scale, lighting and the actual reference. The
+pipeline must first classify a visible material region, then use the matching record as a bounded
+starting point, fit it against the admitted image evidence, and verify it under controlled renders.
+
+## Lookup contract
+
+The image analyzer must emit a structured hypothesis rather than a bare word:
+
+```json
+{
+ "componentId": "torso-armor",
+ "regionId": "gold-trim",
+ "family": "metal",
+ "subtype": "brass",
+ "finish": "polished",
+ "confidence": 0.81,
+ "alternatives": ["metal.gold.polished", "coating.metallic-paint"]
+}
+```
+
+Resolution order:
+
+1. Exact canonical `materialId` supplied by authoritative metadata or a reviewed spec.
+2. Exact `family + subtype + finish` match.
+3. Alias match, retaining every matching candidate rather than choosing silently.
+4. Family fallback with reduced confidence.
+5. `unknown` and `request-input` when the distinction affects a critical visible region.
+
+User-supplied material identity has precedence over image inference. A low-confidence visual guess
+must not overwrite explicit metadata. Conversely, a textual material name supplies identity but not
+the final colour, wear or roughness; those still come from image evidence.
+
+## Application contract
+
+After lookup:
+
+1. Copy the record's `renderPrior` into a candidate material, never directly into an accepted spec.
+2. Derive colour and pattern from the admitted, de-lit component crop. Do not use the reference's
+ baked shadow or highlight as albedo.
+3. Keep colour maps in `THREE.SRGBColorSpace`; keep roughness, metalness, normal, AO, thickness,
+ anisotropy and other data maps in `THREE.NoColorSpace`.
+4. Author every `requiredMap`; an explicit documented constant may replace a map only when the
+ surface is genuinely uniform at the target resolution.
+5. Fit only inside the prior range initially. Expanding beyond a range requires a recorded reason
+ such as coating, weathering, stylization or contradictory reference evidence.
+6. Capture every `validationView` and compare the component's visible footprint. Beauty alone is
+ never sufficient material evidence.
+
+## Hard limits
+
+- A single RGB image does not uniquely separate illumination, reflectance, roughness and geometry.
+- Steel versus aluminium, real versus synthetic leather, and gold versus metallic paint may remain
+ ambiguous without context, multiple views or controlled light.
+- `MeshPhysicalMaterial` approximates skin, hair, fur and layered textiles; it is not a spectral,
+ subsurface or strand renderer.
+- Environment intensity and exposure are scene calibration controls, not intrinsic material
+ constants. They are intentionally excluded from per-material physical identity.
+- Hidden regions inherit only a low-confidence family prior until additional evidence is available.
+
+## Research provenance
+
+NotebookLM notebook:
+
+```text
+ThreeJS Materials Textures PBR
+34554cd6-c897-4077-9561-308876bf2716
+```
+
+The contract was distilled from official Three.js material, texture, colour-management, renderer
+and PMREM documentation plus Khronos glTF material specifications. Two NotebookLM deep-research
+runs then covered (1) PBR foundations, specialist skin/hair models and image material recognition,
+and (2) current Three.js/Khronos property contracts and production recipes. They found 101 and 100
+sources, importing 73 and 52 cited sources respectively.
+
+Only the source hierarchy recorded in `material-reference.json` may influence the canonical
+contract: official Three.js first, Khronos specifications second, primary research/reference
+implementations third, and established industry PBR guides fourth. Search-result blogs, forums and
+uncited preset lists are not canonical sources. No generated numerical recipe becomes authoritative
+until it is represented here as a bounded prior, carries source references and passes repository
+tests.
+
+## Future pipeline wiring
+
+The intended hand-off is:
+
+```text
+component/material-region mask
+ -> semantic material hypothesis
+ -> material-reference.json lookup
+ -> image-derived colour/PBR evidence
+ -> ObjectSculptSpec material assignment
+ -> Three.js material generation
+ -> controlled render and component microscope
+```
+
+This directory defines that hand-off. The current wiring is implemented by
+`forge/stage1_intake/material_region_analysis.py`,
+`forge/stage2_spec/apply_material_analysis.py`, the generated factory provenance hooks, and the
+material review/gate scripts. Specs without `materialPipeline` remain backward-compatible; a spec
+that opts into the contract is blocked until its regions, crops, controlled comparisons and
+geometry/UV/rig/LOD compatibility evidence pass.
diff --git a/docs/materials/THREEJS_MATERIAL_REFERENCE.md b/docs/materials/THREEJS_MATERIAL_REFERENCE.md
new file mode 100644
index 0000000..1dfe5cd
--- /dev/null
+++ b/docs/materials/THREEJS_MATERIAL_REFERENCE.md
@@ -0,0 +1,222 @@
+# Three.js material rendering reference
+
+This is the human-readable companion to `material-reference.json`. The JSON file is canonical for
+machine lookup; this document explains how to interpret it when reconstructing a model from images.
+
+## Source-backed Three.js contract
+
+The following are renderer contracts from official Three.js/Khronos sources, not material presets:
+
+- `MeshStandardMaterial` and `MeshPhysicalMaterial` use metallic-roughness PBR.
+- `metalness` and `roughness` are in `[0, 1]`; roughness and metalness maps multiply their scalar.
+- `MeshPhysicalMaterial` adds clearcoat, sheen, transmission/volume, IOR, iridescence, anisotropy
+ and dispersion at additional GPU cost.
+- `ior` is constrained to `[1, 2.333]`; transmission uses `opacity = 1` and needs meaningful
+ geometry thickness or a thickness map.
+- PBR validation needs a meaningful environment. Prefilter HDR environments with `PMREMGenerator`.
+- Colour textures use sRGB; mathematical data maps stay untagged/linear (`NoColorSpace`).
+- Switching texture slots or material features may trigger shader recompilation. Wait for texture
+ upload before capturing review evidence.
+
+Primary sources are listed with NotebookLM source IDs in `material-reference.json`. Context7 was
+also used to check the current `/mrdoob/three.js` API and official examples before freezing the code
+patterns below.
+
+## Research source hierarchy
+
+1. Three.js official documentation, source and examples define the runtime API.
+2. Khronos glTF core and material extensions define portable metallic-roughness, sheen,
+ transmission and volume semantics.
+3. Primary research/reference implementations explain phenomena not modeled directly by stock
+ Three.js, especially skin subsurface scattering, hair scattering and visual material recognition.
+4. Adobe's PBR Guide and Google's Filament documentation supply established production guardrails.
+
+The library intentionally excludes forum recipes from its canonical values. Official Three.js
+examples are API evidence, not automatically physically correct presets; for example, a demo named
+"car paint" does not override the layer rule that intact pigment/binder is dielectric.
+
+## How to read the numbers
+
+Every per-material value is an **inferred starting prior** constrained by the official property
+semantics. It is not a claim that all objects of that material have one roughness. The image analyst
+must select a family, subtype and finish, apply the prior, then fit colour/variation within the range
+against the admitted component crops.
+
+| Canonical material | metalness | roughness | advanced starting values | Essential evidence |
+| --- | ---: | ---: | --- | --- |
+| Human skin | 0 | 0.52 | clearcoat 0.12, IOR 1.4 | neutral + grazing; pores without plastic shine |
+| Human hair | 0 | 0.45 | anisotropy 0.65 | directional highlight follows strands/clumps |
+| Stylized fur | 0 | 0.78 | sheen 0.45 | grazing response plus broken silhouette |
+| Woven matte fabric | 0 | 0.85 | sheen 0.65 | woven normal and broad grazing sheen |
+| Silk/satin | 0 | 0.32 | sheen 0.85, anisotropy 0.45 | moving directional highlight |
+| Velvet | 0 | 0.72 | sheen 1.0 | dark frontal body with soft bright rim |
+| Matte leather | 0 | 0.62 | clearcoat 0.08 | irregular grain and smoother worn edges |
+| Polished steel/chrome | 1 | 0.12 | — | sharp neutral environment reflection |
+| Brushed steel | 1 | 0.35 | anisotropy 0.85 | elongated reflection aligned with brushing |
+| Aluminium | 1 | 0.30 | anisotropy 0.20 | bright neutral satin conductor |
+| Copper | 1 | 0.28 | — | red-orange conductor reflection; patina is separate |
+| Brass/bronze | 1 | 0.30 | — | yellow-brown conductor response |
+| Gold | 1 | 0.22 | — | yellow reflected energy, not yellow diffuse paint |
+| Painted/coated metal | 0 | 0.45 | clearcoat 0.75 | dielectric paint; metallic chips need a mask/region |
+| Glossy plastic | 0 | 0.28 | clearcoat 0.20, IOR 1.5 | neutral specular over coloured diffuse body |
+| Matte plastic | 0 | 0.68 | IOR 1.5 | broad highlight; molded/stipple microstructure |
+| Matte rubber | 0 | 0.88 | IOR 1.48 | weak broad highlight with grip microtexture |
+| Unfinished wood | 0 | 0.72 | anisotropy 0.12 | grain direction affects colour and roughness |
+| Varnished wood | 0 | 0.42 | clearcoat 0.75 | wood grain under a separate coating reflection |
+| Natural stone | 0 | 0.78 | optional clearcoat | multi-scale mineral pattern and relief |
+| Glazed ceramic | 0 | 0.26 | clearcoat 0.70, IOR 1.5 | hard dielectric body with glaze reflection |
+| Clear glass | 0 | 0.05 | transmission 1, IOR 1.5 | background distortion, reflection and thickness |
+| Frosted glass | 0 | 0.52 | transmission 0.85, IOR 1.5 | blurred transmission and etched micro-normal |
+| Quartz-like gemstone | 0 | 0.06 | transmission 0.9, IOR 1.54 | facets and thickness-dependent transmission |
+
+Use the JSON ranges, not only this default column. Worn, wet, oxidized, dusty, scratched, polished
+or stylized surfaces may sit elsewhere in the range or require a new finish record.
+
+## Current Three.js implementation pattern
+
+Create candidates from the selected profile, then attach independently authored maps. Do not bake
+lighting into `map`, and do not assign sRGB to mathematical maps:
+
+```ts
+import * as THREE from "three";
+
+const loader = new THREE.TextureLoader();
+
+function loadColorMap(url: string): THREE.Texture {
+ const texture = loader.load(url);
+ texture.colorSpace = THREE.SRGBColorSpace;
+ return texture;
+}
+
+function loadDataMap(url: string): THREE.Texture {
+ const texture = loader.load(url);
+ texture.colorSpace = THREE.NoColorSpace;
+ return texture;
+}
+
+const material = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff, // image-derived tint; keep white when map already owns colour
+ map: loadColorMap("base-color.png"),
+ roughness: 0.85,
+ roughnessMap: loadDataMap("roughness.png"),
+ metalness: 0.0,
+ metalnessMap: loadDataMap("metalness.png"),
+ normalMap: loadDataMap("normal.png"),
+ sheen: 0.65,
+ sheenRoughness: 0.75,
+});
+```
+
+The scalar and map multiply one another, so a white data map preserves the scalar while black
+suppresses it. When a texture slot is attached after first compilation, set `material.needsUpdate =
+true`. Wait for all texture loads before recording comparison evidence.
+
+Use a stable HDR environment for every PBR comparison:
+
+```ts
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+renderer.toneMapping = THREE.ACESFilmicToneMapping;
+renderer.toneMappingExposure = 1.0; // calibrate once, never per material
+
+const pmrem = new THREE.PMREMGenerator(renderer);
+const environment = pmrem.fromEquirectangular(hdrTexture).texture;
+scene.environment = environment;
+pmrem.dispose();
+```
+
+For glass, use `MeshPhysicalMaterial({ transmission: 1, opacity: 1, metalness: 0, ior: 1.5,
+thickness })`. `thickness` is in world-space units, so it cannot be a universal preset: derive it
+from model scale or a thickness map. A background/environment and closed, correctly oriented
+geometry are part of the material test.
+
+## Material creation recipes
+
+### Skin
+
+- Use de-lit image colour for `map`; never bake facial shadow into albedo.
+- Use independent pore/wrinkle normal and low-amplitude roughness variation.
+- Keep metalness at zero. Clearcoat is a restrained wet-oil approximation, not a plastic shell.
+- Geometry owns facial planes, folds and wrinkles that alter silhouette.
+- If likeness requires real subsurface transport, record that `MeshPhysicalMaterial` is insufficient
+ rather than compensating with orange albedo.
+
+### Hair and fur
+
+- Geometry clumps/cards own silhouette and parting; maps own strand-scale variation.
+- Author an anisotropy map with direction matching UV/tangent flow for hair.
+- Fur and velvet use sheen for grazing response, but still require geometry where fibres change the
+ visible outline.
+- Validate under a moving grazing light. A static beauty view cannot prove directional response.
+
+### Fabric and leather
+
+- Fabric is a dielectric: metalness zero, high roughness, weave normal, optional sheen.
+- Satin/silk needs lower roughness and directional response; matte cotton does not.
+- Leather needs irregular grain and wear-aware roughness. Do not identify leather from brown colour.
+- Large folds, seams, hems, stitches and panel thickness are geometry or explicit relief, not albedo.
+
+### Bare metal
+
+- Set metalness to one for a clean exposed conductor; drive visible tint through base colour/map.
+- A PMREM-filtered environment is mandatory for useful validation.
+- Roughness controls reflection spread; anisotropy plus a directional map models brushing.
+- Oxidation, dirt, paint and patina are separate dielectric/transition regions. Do not average them
+ into one fractional-metalness surface unless the pixels are genuinely unresolved at target scale.
+
+### Painted metal
+
+- Intact paint is dielectric (`metalness` near zero) even though its substrate is metal.
+- Use clearcoat for lacquer/automotive coatings and an independent clearcoat roughness map.
+- Chips exposing substrate need a region or metalness mask. Paint colour alone cannot reveal the
+ underlying metal.
+
+### Plastic and rubber
+
+- Both are dielectrics. Distinguish them through roughness, deformation/context and microstructure,
+ not black colour or highlight presence alone.
+- Glossy plastic may use a restrained clearcoat; matte rubber generally does not.
+- Add molded stipple/grip normals and wear-specific roughness where visible.
+
+### Wood, stone and ceramic
+
+- Wood grain must align across colour, roughness and normal channels.
+- Varnished wood is a layered dielectric: grain body plus a clear coating.
+- Stone uses multi-scale albedo and relief; polished stone remains dielectric.
+- Glazed ceramic uses a coating reflection; chips should expose a rougher body region.
+
+### Glass and gemstones
+
+- Use `transmission`, not low opacity, for physically based transparency.
+- Keep opacity at one; derive thickness from geometry scale and/or `thicknessMap`.
+- Provide a PMREM environment and a background that can be refracted.
+- Frosting is primarily roughness plus etched micro-normal, not grey albedo.
+- Opaque gem-like paint is a coating, not transmissive quartz; classify by light response.
+
+## Required controlled renders
+
+| View | What it proves |
+| --- | --- |
+| `albedo-unlit` | De-lit colour, pattern and region assignment |
+| `neutral-studio` | Balanced diffuse/specular response |
+| `grazing` | Roughness, normal strength, sheen, anisotropy and coating |
+| `environment-reflection` | Conductor and polished-layer response |
+| `backlight-transmission` | Transmission, volume, absorption and thickness |
+| `reference-beauty` | Final agreement at the solved camera |
+
+The component microscope must use the full scene's visible footprint. Isolation renders are useful
+for structural inspection but can expose surfaces hidden in the reference and produce false material
+scores.
+
+## Common classification failures
+
+- Black fabric, leather, rubber and plastic classified only from albedo.
+- Brass, gold and metallic yellow paint collapsed into one `gold` preset.
+- Painted metal assigned `metalness = 1` across intact paint.
+- Hair made matte and uniform, so it reads as rubber or clay.
+- Fabric given a flat normal and no sheen, so it reads as plastic.
+- Clear glass implemented with opacity, so it lacks volume/refraction.
+- Environment or exposure changed to hide a wrong material instead of fixing the material.
+- Raw reference highlights baked into albedo and then lit a second time.
+
+If controlled views disagree, retain the disagreement in evidence and refine the classification or
+request input. Do not let a high beauty similarity score override a failed material hard gate.
diff --git a/docs/materials/material-reference.json b/docs/materials/material-reference.json
new file mode 100644
index 0000000..f4cd787
--- /dev/null
+++ b/docs/materials/material-reference.json
@@ -0,0 +1,751 @@
+{
+ "schemaVersion": 1,
+ "libraryId": "img2threejs.threejs-material-reference",
+ "renderer": {
+ "engine": "three.js",
+ "workflow": "metallic-roughness",
+ "defaultMaterial": "MeshPhysicalMaterial",
+ "workingColorSpace": "LinearSRGBColorSpace",
+ "displayColorSpace": "SRGBColorSpace"
+ },
+ "research": {
+ "provider": "NotebookLM",
+ "notebookTitle": "ThreeJS Materials Textures PBR",
+ "notebookId": "34554cd6-c897-4077-9561-308876bf2716",
+ "researchTaskIds": [
+ "5ab630a8-a49a-438f-8b01-284ec879b1d6",
+ "434f776e-3947-4182-bef8-9dbb0ef7585f"
+ ],
+ "deepResearchRuns": [
+ {
+ "taskId": "5ab630a8-a49a-438f-8b01-284ec879b1d6",
+ "focus": "PBR foundations, specialist material models and image-based material recognition",
+ "sourcesFound": 101,
+ "citedSourcesImported": 73
+ },
+ {
+ "taskId": "434f776e-3947-4182-bef8-9dbb0ef7585f",
+ "focus": "Official Three.js and Khronos material property contracts and production recipes",
+ "sourcesFound": 100,
+ "citedSourcesImported": 52
+ }
+ ],
+ "sourceHierarchy": [
+ "Three.js official documentation and source contracts",
+ "Khronos glTF specifications and extension specifications",
+ "primary rendering research and reference implementations",
+ "widely used industry PBR guides"
+ ],
+ "policy": "Direct Three.js and glTF facts define property contracts. Per-material numbers are bounded starting priors and must be fitted against admitted image evidence and controlled renders."
+ },
+ "textureContract": {
+ "colorMaps": ["map", "emissiveMap", "sheenColorMap", "specularColorMap"],
+ "colorMapColorSpace": "SRGBColorSpace",
+ "dataMaps": [
+ "roughnessMap",
+ "metalnessMap",
+ "normalMap",
+ "aoMap",
+ "bumpMap",
+ "displacementMap",
+ "clearcoatMap",
+ "clearcoatRoughnessMap",
+ "clearcoatNormalMap",
+ "sheenRoughnessMap",
+ "transmissionMap",
+ "thicknessMap",
+ "anisotropyMap",
+ "iridescenceMap",
+ "iridescenceThicknessMap"
+ ],
+ "dataMapColorSpace": "NoColorSpace",
+ "channelPacking": {
+ "roughnessMap": "green",
+ "metalnessMap": "blue",
+ "aoMap": "red; requires UV channel 1",
+ "clearcoatMap": "red",
+ "clearcoatRoughnessMap": "green",
+ "transmissionMap": "red",
+ "thicknessMap": "green",
+ "sheenRoughnessMap": "alpha",
+ "anisotropyMap": "red-green direction, blue strength"
+ },
+ "environment": {
+ "requiredForPbrValidation": true,
+ "prefilter": "PMREMGenerator",
+ "hdrColorSpace": "LinearSRGBColorSpace"
+ }
+ },
+ "legalRanges": {
+ "metalness": [0.0, 1.0],
+ "roughness": [0.0, 1.0],
+ "clearcoat": [0.0, 1.0],
+ "clearcoatRoughness": [0.0, 1.0],
+ "sheen": [0.0, 1.0],
+ "sheenRoughness": [0.0, 1.0],
+ "transmission": [0.0, 1.0],
+ "ior": [1.0, 2.333],
+ "anisotropy": [0.0, 1.0],
+ "iridescence": [0.0, 1.0],
+ "dispersion": [0.0, 1.0]
+ },
+ "sources": [
+ {
+ "id": "three.mesh-physical",
+ "title": "MeshPhysicalMaterial - three.js docs",
+ "url": "https://threejs.org/docs/pages/MeshPhysicalMaterial.html",
+ "notebookSourceId": "5ded9c1b-a798-4f3c-a5f6-83e6bd0ae6de",
+ "authority": "official"
+ },
+ {
+ "id": "three.mesh-standard",
+ "title": "MeshStandardMaterial - three.js docs",
+ "url": "https://threejs.org/docs/pages/MeshStandardMaterial.html",
+ "notebookSourceId": "47ee0b29-95c6-4516-92e7-436332922bca",
+ "authority": "official"
+ },
+ {
+ "id": "three.texture",
+ "title": "Texture - three.js docs",
+ "url": "https://threejs.org/docs/pages/Texture.html",
+ "notebookSourceId": "55236b6a-c1a3-45e2-b3b7-4dc635ea5784",
+ "authority": "official"
+ },
+ {
+ "id": "three.renderer",
+ "title": "WebGLRenderer - three.js docs",
+ "url": "https://threejs.org/docs/pages/WebGLRenderer.html",
+ "notebookSourceId": "99eb283c-adfe-4a5b-bd6d-584bdb82af2a",
+ "authority": "official"
+ },
+ {
+ "id": "three.pmrem",
+ "title": "PMREMGenerator - three.js docs",
+ "url": "https://threejs.org/docs/pages/PMREMGenerator.html",
+ "notebookSourceId": "e7ae92f6-1b92-497a-8ff4-5abe0311741c",
+ "authority": "official"
+ },
+ {
+ "id": "three.materials-manual",
+ "title": "Materials - three.js manual",
+ "url": "https://threejs.org/manual/en/materials.html",
+ "notebookSourceId": "54042985-ed61-4074-baf9-4d5b82262e72",
+ "authority": "official"
+ },
+ {
+ "id": "three.color-management",
+ "title": "Color Management - three.js manual",
+ "url": "https://threejs.org/manual/en/color-management.html",
+ "notebookSourceId": "eb0350a4-e0d7-48e9-9259-9cd3723d8f5b",
+ "authority": "official"
+ },
+ {
+ "id": "gltf.2",
+ "title": "glTF 2.0 specification - Khronos Group",
+ "url": "https://github.com/KhronosGroup/glTF/tree/main/specification/2.0",
+ "notebookSourceId": "fef339d2-4fcd-4663-a423-bb8ad19195bd",
+ "authority": "official"
+ },
+ {
+ "id": "khronos.gltf-pbr",
+ "title": "glTF 2.0: PBR Materials - Khronos Group",
+ "url": "https://www.khronos.org/assets/uploads/developers/library/2017-gtc/glTF-2.0-and-PBR-GTC_May17.pdf",
+ "notebookSourceId": "265ebc28-1d0d-4cd5-9d50-108172875c1a",
+ "authority": "official"
+ },
+ {
+ "id": "khronos.sheen",
+ "title": "KHR_materials_sheen - Khronos Group",
+ "url": "https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_sheen/README.md",
+ "notebookSourceId": "a46c7f93-f19e-4a0b-b273-03ffb90018d8",
+ "authority": "official"
+ },
+ {
+ "id": "khronos.transmission",
+ "title": "KHR_materials_transmission - Khronos Group",
+ "url": "https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_transmission/README.md",
+ "notebookSourceId": "8a316973-8bb0-44a7-a8e3-ccfc23074c65",
+ "authority": "official"
+ },
+ {
+ "id": "khronos.volume",
+ "title": "KHR_materials_volume - Khronos Group",
+ "url": "https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md",
+ "notebookSourceId": "5a4ce5ed-1ace-4707-a562-1df5577f5ab3",
+ "authority": "official"
+ },
+ {
+ "id": "adobe.pbr-guide-1",
+ "title": "The PBR Guide, Part 1 - Adobe Substance 3D",
+ "url": "https://www.adobe.com/learn/substance-3d-designer/web/the-pbr-guide-part-1",
+ "notebookSourceId": "c09727e9-d489-40bc-82e8-73daa4927d4a",
+ "authority": "industry-reference"
+ },
+ {
+ "id": "adobe.pbr-guide-2",
+ "title": "The PBR Guide, Part 2 - Adobe Substance 3D",
+ "url": "https://www.adobe.com/learn/substance-3d-designer/web/the-pbr-guide-part-2",
+ "notebookSourceId": "47bfa258-b6c4-488a-907d-0277286a9da0",
+ "authority": "industry-reference"
+ },
+ {
+ "id": "google.filament-pbr",
+ "title": "Physically Based Rendering in Filament - Google",
+ "url": "https://google.github.io/filament/Filament.md.html",
+ "notebookSourceId": "e8f97cd1-9b73-497d-9e55-4de545310d6d",
+ "authority": "reference-implementation"
+ },
+ {
+ "id": "mit.material-recognition",
+ "title": "Recognizing Materials Using Perceptually Inspired Features - MIT CSAIL",
+ "url": "https://people.csail.mit.edu/celiu/pdfs/IJCV13-MaterialRecognition.pdf",
+ "notebookSourceId": "f84b37f9-71cb-4830-bb58-ca2f140a88ef",
+ "authority": "primary-research"
+ },
+ {
+ "id": "nvidia.faceworks",
+ "title": "FaceWorks skin and eye rendering - NVIDIA GameWorks",
+ "url": "https://github.com/NVIDIAGameWorks/FaceWorks",
+ "notebookSourceId": "dc940b82-dfaf-4857-925e-0b1828df3a64",
+ "authority": "reference-implementation"
+ },
+ {
+ "id": "activision.separable-sss",
+ "title": "Separable Subsurface Scattering - Activision",
+ "url": "https://www.activision.com/cdn/research/Separable_Subsurface_Scattering_Expanded_Technical_Report_NEW.pdf",
+ "notebookSourceId": "6f8a4c71-47f3-4b55-93a3-f294ed47b36f",
+ "authority": "primary-research"
+ },
+ {
+ "id": "pbrt.hair",
+ "title": "Scattering from Hair - Physically Based Rendering",
+ "url": "https://pbr-book.org/4ed/Reflection_Models/Scattering_from_Hair",
+ "notebookSourceId": "4c538546-148e-4d29-b59f-acce911cd5bc",
+ "authority": "reference-text"
+ }
+ ],
+ "materials": [
+ {
+ "id": "skin.human",
+ "aliases": ["skin", "human skin"],
+ "family": "skin",
+ "subtype": "human",
+ "finish": "natural",
+ "model": "dielectric-approximation",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.52, "range": [0.35, 0.7]},
+ "clearcoat": {"default": 0.12, "range": [0.0, 0.25]},
+ "clearcoatRoughness": {"default": 0.35, "range": [0.2, 0.6]},
+ "ior": {"default": 1.4, "range": [1.33, 1.5]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["aoMap"],
+ "visualCues": ["warm dielectric diffuse response", "broad soft highlights", "pores and wrinkles at micro scale"],
+ "confusableWith": ["plastic.matte", "rubber.matte", "coating.paint-matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["MeshPhysicalMaterial has no true multilayer skin subsurface scattering"],
+ "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "nvidia.faceworks", "activision.separable-sss", "mit.material-recognition"]
+ },
+ {
+ "id": "hair.human",
+ "aliases": ["hair", "human hair"],
+ "family": "hair",
+ "subtype": "human",
+ "finish": "strand-directional",
+ "model": "anisotropic-dielectric-approximation",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.45, "range": [0.3, 0.7]},
+ "anisotropy": {"default": 0.65, "range": [0.4, 1.0]},
+ "ior": {"default": 1.5, "range": [1.4, 1.6]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],
+ "optionalMaps": ["aoMap"],
+ "visualCues": ["elongated highlights follow strand or clump direction", "silhouette breakup", "dark masses retain directional specular"],
+ "confusableWith": ["fabric.velvet", "plastic.glossy", "rubber.matte"],
+ "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Use geometry clumps or cards for silhouette; a normal map cannot replace hair volume"],
+ "sourceRefs": ["three.mesh-physical", "pbrt.hair", "mit.material-recognition"]
+ },
+ {
+ "id": "fur.stylized",
+ "aliases": ["fur", "animal fur"],
+ "family": "fur",
+ "subtype": "stylized",
+ "finish": "fibre-matte",
+ "model": "sheen-dielectric-approximation",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.78, "range": [0.55, 1.0]},
+ "sheen": {"default": 0.45, "range": [0.2, 0.8]},
+ "sheenRoughness": {"default": 0.75, "range": [0.5, 1.0]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["sheenColorMap", "sheenRoughnessMap", "aoMap"],
+ "visualCues": ["soft grazing response", "directional fibres", "broken outer silhouette"],
+ "confusableWith": ["fabric.velvet", "hair.human"],
+ "validationViews": ["neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Geometry shells, tufts or cards are required for identity-scale fur"],
+ "sourceRefs": ["three.mesh-physical", "pbrt.hair", "khronos.sheen"]
+ },
+ {
+ "id": "fabric.woven-matte",
+ "aliases": ["fabric", "cloth", "cotton", "linen"],
+ "family": "fabric",
+ "subtype": "woven",
+ "finish": "matte",
+ "model": "sheen-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.85, "range": [0.7, 1.0]},
+ "sheen": {"default": 0.65, "range": [0.3, 1.0]},
+ "sheenRoughness": {"default": 0.75, "range": [0.5, 1.0]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["sheenColorMap", "sheenRoughnessMap", "aoMap"],
+ "visualCues": ["diffuse body with grazing-angle sheen", "woven directional microstructure", "soft broad highlights"],
+ "confusableWith": ["leather.matte", "rubber.matte", "plastic.matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Large folds and hems belong in geometry"],
+ "sourceRefs": ["three.mesh-physical", "three.texture", "khronos.sheen", "mit.material-recognition"]
+ },
+ {
+ "id": "fabric.silk-satin",
+ "aliases": ["silk", "satin"],
+ "family": "fabric",
+ "subtype": "silk-satin",
+ "finish": "smooth-directional",
+ "model": "sheen-anisotropic-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.32, "range": [0.18, 0.55]},
+ "sheen": {"default": 0.85, "range": [0.5, 1.0]},
+ "sheenRoughness": {"default": 0.4, "range": [0.2, 0.65]},
+ "anisotropy": {"default": 0.45, "range": [0.2, 0.8]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],
+ "optionalMaps": ["sheenColorMap", "sheenRoughnessMap"],
+ "visualCues": ["bright moving grazing highlight", "directional weave response", "smooth drape"],
+ "confusableWith": ["plastic.glossy", "coating.paint-gloss", "fabric.woven-matte"],
+ "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Highlight direction must follow the authored fibre tangent"],
+ "sourceRefs": ["three.mesh-physical", "khronos.sheen", "google.filament-pbr"]
+ },
+ {
+ "id": "fabric.velvet",
+ "aliases": ["velvet", "nhung"],
+ "family": "fabric",
+ "subtype": "velvet",
+ "finish": "pile-sheen",
+ "model": "sheen-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.72, "range": [0.55, 0.95]},
+ "sheen": {"default": 1.0, "range": [0.75, 1.0]},
+ "sheenRoughness": {"default": 0.65, "range": [0.4, 0.9]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap", "sheenColorMap"],
+ "optionalMaps": ["sheenRoughnessMap", "aoMap"],
+ "visualCues": ["dark frontal body", "strong soft rim or grazing sheen", "pile direction changes tone"],
+ "confusableWith": ["fur.stylized", "hair.human", "fabric.woven-matte"],
+ "validationViews": ["neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Short pile is an approximation without a fibre shader"],
+ "sourceRefs": ["three.mesh-physical", "khronos.sheen", "google.filament-pbr"]
+ },
+ {
+ "id": "leather.matte",
+ "aliases": ["leather", "matte leather"],
+ "family": "leather",
+ "subtype": "natural-or-synthetic",
+ "finish": "matte-worn",
+ "model": "dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.62, "range": [0.35, 0.85]},
+ "clearcoat": {"default": 0.08, "range": [0.0, 0.3]},
+ "clearcoatRoughness": {"default": 0.45, "range": [0.2, 0.8]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["aoMap", "clearcoatMap"],
+ "visualCues": ["irregular grain", "worn edges become smoother", "creases darken without becoming metallic"],
+ "confusableWith": ["fabric.woven-matte", "rubber.matte", "plastic.matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Single images rarely prove natural versus synthetic leather"],
+ "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "adobe.pbr-guide-2", "mit.material-recognition"]
+ },
+ {
+ "id": "metal.steel-polished",
+ "aliases": ["polished steel", "chrome", "stainless steel"],
+ "family": "metal",
+ "subtype": "steel",
+ "finish": "polished",
+ "model": "conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.12, "range": [0.03, 0.25]},
+ "anisotropy": {"default": 0.0, "range": [0.0, 0.15]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "metalnessMap"],
+ "visualCues": ["neutral tinted environment reflection", "sharp high-contrast highlights", "little diffuse body colour"],
+ "confusableWith": ["metal.aluminum", "coating.metallic-paint", "plastic.glossy"],
+ "validationViews": ["neutral-studio", "environment-reflection", "grazing", "reference-beauty"],
+ "limitations": ["A meaningful environment map is mandatory; flat lighting cannot validate polished metal"],
+ "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "metal.steel-brushed",
+ "aliases": ["brushed steel", "machined steel"],
+ "family": "metal",
+ "subtype": "steel",
+ "finish": "brushed",
+ "model": "anisotropic-conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.35, "range": [0.2, 0.55]},
+ "anisotropy": {"default": 0.85, "range": [0.5, 1.0]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],
+ "optionalMaps": ["metalnessMap"],
+ "visualCues": ["elongated highlight aligned to brushing", "neutral conductor reflection", "parallel micro-scratches"],
+ "confusableWith": ["metal.aluminum", "plastic.glossy"],
+ "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Anisotropy direction must agree with geometry tangent and visible brushing"],
+ "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "metal.aluminum",
+ "aliases": ["aluminum", "aluminium"],
+ "family": "metal",
+ "subtype": "aluminum",
+ "finish": "satin",
+ "model": "conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.3, "range": [0.15, 0.55]},
+ "anisotropy": {"default": 0.2, "range": [0.0, 0.8]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "anisotropyMap"],
+ "visualCues": ["bright neutral conductor", "soft satin highlight unless polished", "often fine machining direction"],
+ "confusableWith": ["metal.steel-polished", "coating.metallic-paint"],
+ "validationViews": ["neutral-studio", "environment-reflection", "grazing"],
+ "limitations": ["Steel versus aluminium may require context or metadata"],
+ "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "metal.copper",
+ "aliases": ["copper"],
+ "family": "metal",
+ "subtype": "copper",
+ "finish": "polished-or-aged",
+ "model": "coloured-conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.28, "range": [0.08, 0.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "metalnessMap", "aoMap"],
+ "visualCues": ["warm red-orange conductor reflection", "patina may create rough dielectric corrosion regions"],
+ "confusableWith": ["metal.brass", "coating.metallic-paint"],
+ "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],
+ "limitations": ["Patina and oxidation require region masks rather than one uniform metal recipe"],
+ "sourceRefs": ["three.mesh-standard", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "metal.brass",
+ "aliases": ["brass", "bronze"],
+ "family": "metal",
+ "subtype": "brass-bronze",
+ "finish": "polished-or-aged",
+ "model": "coloured-conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.3, "range": [0.1, 0.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "aoMap", "metalnessMap"],
+ "visualCues": ["warm yellow-to-brown conductor reflection", "aged recesses darken and roughen"],
+ "confusableWith": ["metal.gold", "metal.copper", "coating.metallic-paint"],
+ "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],
+ "limitations": ["Brass versus bronze versus gold may require context or metadata"],
+ "sourceRefs": ["three.mesh-standard", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "metal.gold",
+ "aliases": ["gold"],
+ "family": "metal",
+ "subtype": "gold",
+ "finish": "polished",
+ "model": "coloured-conductor",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 1.0, "range": [1.0, 1.0]},
+ "roughness": {"default": 0.22, "range": [0.08, 0.45]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "metalnessMap"],
+ "visualCues": ["yellow conductor reflection rather than yellow diffuse paint", "strong environment-dependent highlight"],
+ "confusableWith": ["metal.brass", "coating.metallic-paint"],
+ "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],
+ "limitations": ["Gold identity should not be inferred from yellow albedo alone"],
+ "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]
+ },
+ {
+ "id": "coating.painted-metal",
+ "aliases": ["painted metal", "coated metal"],
+ "family": "coating",
+ "subtype": "paint-over-metal",
+ "finish": "gloss-or-satin",
+ "model": "coated-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.1]},
+ "roughness": {"default": 0.45, "range": [0.2, 0.7]},
+ "clearcoat": {"default": 0.75, "range": [0.0, 1.0]},
+ "clearcoatRoughness": {"default": 0.12, "range": [0.02, 0.35]},
+ "ior": {"default": 1.5, "range": [1.35, 1.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "clearcoatMap", "clearcoatRoughnessMap", "metalnessMap"],
+ "visualCues": ["diffuse paint colour under a separate glossy coat", "chips may expose metallic substrate"],
+ "confusableWith": ["plastic.glossy", "metal.gold", "metal.steel-polished"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Intact paint is dielectric; exposed substrate needs a separate region or mask"],
+ "sourceRefs": ["three.mesh-physical", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-1", "adobe.pbr-guide-2"]
+ },
+ {
+ "id": "plastic.glossy",
+ "aliases": ["glossy plastic", "acrylic"],
+ "family": "plastic",
+ "subtype": "generic-polymer",
+ "finish": "glossy",
+ "model": "dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.28, "range": [0.12, 0.5]},
+ "clearcoat": {"default": 0.2, "range": [0.0, 0.6]},
+ "clearcoatRoughness": {"default": 0.18, "range": [0.05, 0.4]},
+ "ior": {"default": 1.5, "range": [1.4, 1.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "clearcoatMap"],
+ "visualCues": ["untinted or light-coloured specular over coloured diffuse body", "smooth molded surface"],
+ "confusableWith": ["coating.painted-metal", "ceramic.glazed", "metal.steel-polished"],
+ "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Do not set metalness from highlight sharpness alone"],
+ "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]
+ },
+ {
+ "id": "plastic.matte",
+ "aliases": ["matte plastic", "polymer"],
+ "family": "plastic",
+ "subtype": "generic-polymer",
+ "finish": "matte",
+ "model": "dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.68, "range": [0.48, 0.88]},
+ "ior": {"default": 1.5, "range": [1.4, 1.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "aoMap"],
+ "visualCues": ["coloured diffuse body", "broad neutral highlight", "mold seams or fine stipple"],
+ "confusableWith": ["rubber.matte", "leather.matte", "skin.human"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing"],
+ "limitations": ["Context and texture frequency often distinguish matte plastics from rubber"],
+ "sourceRefs": ["three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]
+ },
+ {
+ "id": "rubber.matte",
+ "aliases": ["rubber", "matte rubber", "cao su"],
+ "family": "rubber",
+ "subtype": "generic-elastomer",
+ "finish": "matte",
+ "model": "dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.88, "range": [0.68, 1.0]},
+ "ior": {"default": 1.48, "range": [1.4, 1.55]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["aoMap"],
+ "visualCues": ["dark diffuse body", "weak broad highlight", "molded or grippy microtexture"],
+ "confusableWith": ["plastic.matte", "leather.matte", "fabric.woven-matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Wet or polished rubber needs a separate finish record"],
+ "sourceRefs": ["three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]
+ },
+ {
+ "id": "wood.unfinished",
+ "aliases": ["wood", "raw wood"],
+ "family": "wood",
+ "subtype": "generic",
+ "finish": "unfinished",
+ "model": "directional-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.72, "range": [0.5, 0.95]},
+ "anisotropy": {"default": 0.12, "range": [0.0, 0.4]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["aoMap", "anisotropyMap"],
+ "visualCues": ["directional grain", "pores and growth rings", "roughness follows grain and wear"],
+ "confusableWith": ["plastic.matte", "leather.matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing"],
+ "limitations": ["Species identity cannot usually be established from a small crop"],
+ "sourceRefs": ["three.mesh-standard", "three.texture", "adobe.pbr-guide-1", "mit.material-recognition"]
+ },
+ {
+ "id": "wood.varnished",
+ "aliases": ["varnished wood", "lacquered wood"],
+ "family": "wood",
+ "subtype": "generic",
+ "finish": "varnished",
+ "model": "coated-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.42, "range": [0.25, 0.65]},
+ "clearcoat": {"default": 0.75, "range": [0.35, 1.0]},
+ "clearcoatRoughness": {"default": 0.16, "range": [0.04, 0.35]},
+ "ior": {"default": 1.5, "range": [1.4, 1.6]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["clearcoatMap", "clearcoatRoughnessMap", "aoMap"],
+ "visualCues": ["wood grain under a separate glossy layer", "coating scratches differ from grain"],
+ "confusableWith": ["plastic.glossy", "coating.painted-metal"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "environment-reflection"],
+ "limitations": ["Do not bake the coating highlight into the grain albedo"],
+ "sourceRefs": ["three.mesh-physical", "three.texture", "adobe.pbr-guide-1", "google.filament-pbr"]
+ },
+ {
+ "id": "stone.natural",
+ "aliases": ["stone", "rock", "granite", "marble"],
+ "family": "stone",
+ "subtype": "natural",
+ "finish": "rough-or-polished",
+ "model": "dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.78, "range": [0.25, 1.0]},
+ "clearcoat": {"default": 0.0, "range": [0.0, 0.35]}
+ },
+ "requiredMaps": ["map", "roughnessMap", "normalMap"],
+ "optionalMaps": ["aoMap", "displacementMap", "clearcoatMap"],
+ "visualCues": ["multi-scale mineral pattern", "fracture or pore relief", "polished stone retains dielectric reflection"],
+ "confusableWith": ["ceramic.glazed", "plastic.matte", "coating.paint-matte"],
+ "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],
+ "limitations": ["Marble and polished stone may need transmission or subsurface approximation beyond this base record"],
+ "sourceRefs": ["three.mesh-standard", "three.mesh-physical", "adobe.pbr-guide-1", "mit.material-recognition"]
+ },
+ {
+ "id": "ceramic.glazed",
+ "aliases": ["ceramic", "porcelain", "glazed ceramic"],
+ "family": "ceramic",
+ "subtype": "glazed",
+ "finish": "glossy",
+ "model": "coated-dielectric",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.26, "range": [0.1, 0.5]},
+ "clearcoat": {"default": 0.7, "range": [0.4, 1.0]},
+ "clearcoatRoughness": {"default": 0.12, "range": [0.02, 0.3]},
+ "ior": {"default": 1.5, "range": [1.4, 1.65]}
+ },
+ "requiredMaps": ["map", "roughnessMap"],
+ "optionalMaps": ["normalMap", "clearcoatMap", "clearcoatRoughnessMap"],
+ "visualCues": ["hard dielectric body", "smooth glaze reflection", "small chips reveal matte body"],
+ "confusableWith": ["plastic.glossy", "stone.natural", "coating.painted-metal"],
+ "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],
+ "limitations": ["Unglazed ceramic needs a separate matte finish"],
+ "sourceRefs": ["three.mesh-physical", "adobe.pbr-guide-1", "google.filament-pbr"]
+ },
+ {
+ "id": "glass.clear",
+ "aliases": ["glass", "clear glass"],
+ "family": "glass",
+ "subtype": "clear",
+ "finish": "polished",
+ "model": "transmissive-dielectric-volume",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.05, "range": [0.0, 0.18]},
+ "transmission": {"default": 1.0, "range": [0.85, 1.0]},
+ "ior": {"default": 1.5, "range": [1.45, 1.55]}
+ },
+ "requiredMaps": ["roughnessMap", "thicknessMap"],
+ "optionalMaps": ["map", "normalMap", "transmissionMap"],
+ "visualCues": ["background distortion", "bright interface reflection", "visible thickness or absorption"],
+ "confusableWith": ["plastic.glossy", "gemstone.quartz", "alpha-transparent material"],
+ "validationViews": ["neutral-studio", "environment-reflection", "backlight-transmission", "reference-beauty"],
+ "limitations": ["Use opacity 1 with transmission; thickness must be derived from geometry scale"],
+ "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.transmission", "khronos.volume", "google.filament-pbr"]
+ },
+ {
+ "id": "glass.frosted",
+ "aliases": ["frosted glass", "etched glass"],
+ "family": "glass",
+ "subtype": "frosted",
+ "finish": "rough-transmissive",
+ "model": "transmissive-dielectric-volume",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.52, "range": [0.3, 0.8]},
+ "transmission": {"default": 0.85, "range": [0.6, 1.0]},
+ "ior": {"default": 1.5, "range": [1.45, 1.55]}
+ },
+ "requiredMaps": ["roughnessMap", "normalMap", "thicknessMap"],
+ "optionalMaps": ["transmissionMap", "map"],
+ "visualCues": ["blurred transmitted background", "broad interface highlight", "fine etched normal structure"],
+ "confusableWith": ["plastic.matte", "glass.clear"],
+ "validationViews": ["neutral-studio", "grazing", "backlight-transmission", "reference-beauty"],
+ "limitations": ["Transmission quality and cost depend on renderer and scene configuration"],
+ "sourceRefs": ["three.mesh-physical", "three.pmrem", "khronos.transmission", "khronos.volume", "google.filament-pbr"]
+ },
+ {
+ "id": "gemstone.quartz",
+ "aliases": ["quartz", "crystal", "gemstone"],
+ "family": "gemstone",
+ "subtype": "quartz-like",
+ "finish": "polished",
+ "model": "transmissive-dielectric-volume",
+ "recipeBasis": "inferred-starting-prior",
+ "renderPrior": {
+ "metalness": {"default": 0.0, "range": [0.0, 0.0]},
+ "roughness": {"default": 0.06, "range": [0.01, 0.2]},
+ "transmission": {"default": 0.9, "range": [0.5, 1.0]},
+ "ior": {"default": 1.54, "range": [1.45, 1.7]},
+ "dispersion": {"default": 0.0, "range": [0.0, 0.3]}
+ },
+ "requiredMaps": ["roughnessMap", "thicknessMap"],
+ "optionalMaps": ["map", "normalMap", "transmissionMap"],
+ "visualCues": ["faceted interface reflections", "transmitted or internally varied colour", "thickness-dependent appearance"],
+ "confusableWith": ["glass.clear", "plastic.glossy", "coating.candy"],
+ "validationViews": ["neutral-studio", "environment-reflection", "backlight-transmission", "reference-beauty"],
+ "limitations": ["A painted opaque gem-like surface is not a transmissive gemstone and needs a coating record"],
+ "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.transmission", "khronos.volume", "google.filament-pbr"]
+ }
+ ]
+}
diff --git a/docs/specs/render-profile.v2.example.json b/docs/specs/render-profile.v2.example.json
new file mode 100644
index 0000000..ab26e37
--- /dev/null
+++ b/docs/specs/render-profile.v2.example.json
@@ -0,0 +1,60 @@
+{
+ "schemaVersion": "render-profile.v2",
+ "kind": "threejs-render-profile",
+ "authority": "browser-threejs",
+ "renderer": {
+ "backend": "WebGLRenderer",
+ "colorManagementEnabled": true,
+ "workingColorSpace": "Linear-sRGB",
+ "outputColorSpace": "SRGBColorSpace",
+ "toneMapping": "ACESFilmicToneMapping",
+ "toneMappingExposure": 1.0,
+ "viewport": [620, 1000],
+ "devicePixelRatio": 1.0,
+ "antialias": true,
+ "alpha": false,
+ "shadowMap": { "enabled": true, "type": "PCFSoftShadowMap" }
+ },
+ "environment": {
+ "kind": "pmrem-hdr",
+ "source": "assets/studio-neutral.hdr",
+ "intensity": 1.0,
+ "prefilter": "PMREMGenerator"
+ },
+ "camera": {
+ "projection": "perspective",
+ "position": [0.0, 0.85, 4.0],
+ "target": [0.0, 0.8, 0.0],
+ "near": 0.01,
+ "far": 100.0,
+ "fovDegrees": 25.0
+ },
+ "background": { "kind": "solid", "color": "#3b2c2a", "alpha": 1.0 },
+ "passes": [
+ { "id": "beauty", "required": true, "colorSpace": "SRGBColorSpace", "toneMapped": true },
+ { "id": "alpha-silhouette", "required": true, "colorSpace": "NoColorSpace", "toneMapped": false },
+ { "id": "semantic-id", "required": true, "colorSpace": "NoColorSpace", "toneMapped": false, "encoding": "region-id-rgb" },
+ { "id": "depth", "required": true, "colorSpace": "NoColorSpace", "toneMapped": false, "encoding": "linear-depth" },
+ { "id": "normal", "required": true, "colorSpace": "NoColorSpace", "toneMapped": false, "encoding": "view-space-xyz-remapped" },
+ { "id": "roughness-material-id", "required": true, "colorSpace": "NoColorSpace", "toneMapped": false, "encoding": "roughness-plus-region-id" }
+ ],
+ "regions": [
+ { "id": "face", "criticality": "critical", "idColor": [255, 0, 0] },
+ { "id": "kasa", "criticality": "high", "idColor": [255, 128, 0] },
+ { "id": "scarf", "criticality": "high", "idColor": [255, 255, 0] },
+ { "id": "tunic", "criticality": "high", "idColor": [0, 255, 0] },
+ { "id": "staff", "criticality": "high", "idColor": [0, 255, 255] },
+ { "id": "tail", "criticality": "high", "idColor": [0, 0, 255] },
+ { "id": "feet", "criticality": "important", "idColor": [128, 0, 255] },
+ { "id": "materials", "criticality": "high", "idColor": [255, 0, 255] }
+ ],
+ "feedbackGroups": [
+ { "id": "camera", "order": 1 },
+ { "id": "silhouette", "order": 2 },
+ { "id": "face", "order": 3 },
+ { "id": "clothing", "order": 4 },
+ { "id": "accessory", "order": 5 },
+ { "id": "materials", "order": 6 },
+ { "id": "lighting", "order": 7 }
+ ]
+}
diff --git a/docs/specs/render-profile.v2.schema.json b/docs/specs/render-profile.v2.schema.json
new file mode 100644
index 0000000..3a5e9fc
--- /dev/null
+++ b/docs/specs/render-profile.v2.schema.json
@@ -0,0 +1,55 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://img2threejs.local/specs/render-profile.v2.schema.json",
+ "title": "img2threejs shared Three.js render profile v2",
+ "type": "object",
+ "required": ["schemaVersion", "kind", "authority", "renderer", "environment", "camera", "background", "passes", "regions", "feedbackGroups"],
+ "properties": {
+ "schemaVersion": { "const": "render-profile.v2" },
+ "kind": { "const": "threejs-render-profile" },
+ "authority": { "const": "browser-threejs" },
+ "renderer": {
+ "type": "object",
+ "required": ["backend", "colorManagementEnabled", "workingColorSpace", "outputColorSpace", "toneMapping", "toneMappingExposure", "viewport", "devicePixelRatio", "antialias"],
+ "properties": {
+ "backend": { "const": "WebGLRenderer" },
+ "colorManagementEnabled": { "const": true },
+ "workingColorSpace": { "const": "Linear-sRGB" },
+ "outputColorSpace": { "const": "SRGBColorSpace" },
+ "toneMapping": { "type": "string", "enum": ["NoToneMapping", "ACESFilmicToneMapping", "AgXToneMapping", "NeutralToneMapping"] },
+ "toneMappingExposure": { "type": "number", "exclusiveMinimum": 0 },
+ "viewport": { "type": "array", "prefixItems": [{ "type": "integer", "minimum": 1 }, { "type": "integer", "minimum": 1 }], "minItems": 2, "maxItems": 2 },
+ "devicePixelRatio": { "type": "number", "exclusiveMinimum": 0 },
+ "antialias": { "type": "boolean" }
+ },
+ "additionalProperties": true
+ },
+ "environment": {
+ "type": "object",
+ "required": ["kind", "source", "intensity"],
+ "properties": {
+ "kind": { "type": "string", "enum": ["none", "pmrem-hdr", "pmrem-equirectangular", "pmrem-cubemap"] },
+ "source": { "type": "string" },
+ "intensity": { "type": "number", "minimum": 0 }
+ },
+ "additionalProperties": true
+ },
+ "camera": {
+ "type": "object",
+ "required": ["projection", "position", "target", "near", "far"],
+ "properties": {
+ "projection": { "enum": ["perspective", "orthographic"] },
+ "position": { "type": "array", "minItems": 3, "maxItems": 3 },
+ "target": { "type": "array", "minItems": 3, "maxItems": 3 },
+ "near": { "type": "number", "exclusiveMinimum": 0 },
+ "far": { "type": "number", "exclusiveMinimum": 0 }
+ },
+ "additionalProperties": true
+ },
+ "background": { "type": "object", "required": ["kind"], "properties": { "kind": { "enum": ["solid", "transparent", "scene"] } }, "additionalProperties": true },
+ "passes": { "type": "array", "minItems": 6, "items": { "type": "object", "required": ["id", "required"], "properties": { "id": { "type": "string" }, "required": { "type": "boolean" } }, "additionalProperties": true } },
+ "regions": { "type": "array", "items": { "type": "object", "required": ["id", "criticality"], "properties": { "id": { "type": "string" }, "criticality": { "enum": ["critical", "high", "important", "detail"] }, "idColor": { "type": "array", "prefixItems": [{ "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }], "minItems": 3, "maxItems": 3 } }, "additionalProperties": true } },
+ "feedbackGroups": { "type": "array", "minItems": 7, "items": { "type": "object", "required": ["id", "order"], "properties": { "id": { "type": "string" }, "order": { "type": "integer", "minimum": 1 } }, "additionalProperties": true } }
+ },
+ "additionalProperties": true
+}
diff --git a/forge/_shared/jpeg.py b/forge/_shared/jpeg.py
new file mode 100644
index 0000000..9a4d821
--- /dev/null
+++ b/forge/_shared/jpeg.py
@@ -0,0 +1,448 @@
+#!/usr/bin/env python3
+"""Baseline JPEG decoder in pure Python 3.10+ standard library.
+
+Why this exists: every image-consuming script fell back to macOS `sips` for any
+format that is not PNG, so a JPEG reference — the most common kind of reference
+photo there is — failed hard on Linux and Windows, and in CI. This decodes
+baseline JPEG directly so the pipeline behaves the same on every platform.
+
+Scope is deliberately narrow and honest about it:
+ * baseline sequential DCT (SOF0) and extended sequential (SOF1), 8-bit
+ * grayscale (1 component) and YCbCr (3 components), any sampling factors
+ * restart intervals
+ * progressive (SOF2), arithmetic coding, 12-bit and CMYK raise a clear
+ UnsupportedJpeg so callers can fall back rather than silently mis-decode
+
+Returns the same shape as read_png(): (width, height, [(r, g, b, a), ...]).
+"""
+from __future__ import annotations
+
+import struct
+from math import cos, pi
+
+__all__ = ["decode_jpeg", "is_jpeg", "UnsupportedJpeg"]
+
+
+class UnsupportedJpeg(ValueError):
+ """A JPEG this decoder deliberately does not handle (e.g. progressive)."""
+
+
+SOI, EOI, SOS, DQT, DHT, DRI = 0xD8, 0xD9, 0xDA, 0xDB, 0xC4, 0xDD
+SOF_BASELINE, SOF_EXTENDED, SOF_PROGRESSIVE = 0xC0, 0xC1, 0xC2
+
+ZIGZAG = (
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
+)
+
+# IDCT[u][x] = C(u)/2 * cos((2x+1) u pi / 16); applying it on rows then columns
+# yields the 1/4 scaling of the 2-D inverse DCT.
+_IDCT = [
+ [((0.353553390593273762 if u == 0 else 0.5) * cos((2 * x + 1) * u * pi / 16))
+ for x in range(8)]
+ for u in range(8)
+]
+
+
+def is_jpeg(data: bytes) -> bool:
+ return len(data) >= 2 and data[0] == 0xFF and data[1] == SOI
+
+
+class _BitReader:
+ """MSB-first bit reader over entropy-coded data, unstuffing 0xFF 0x00."""
+
+ __slots__ = ("data", "pos", "bits", "nbits")
+
+ def __init__(self, data: bytes, pos: int) -> None:
+ self.data = data
+ self.pos = pos
+ self.bits = 0
+ self.nbits = 0
+
+ def _fill(self) -> None:
+ data = self.data
+ while self.nbits <= 24:
+ if self.pos >= len(data):
+ self.bits = (self.bits << 8) | 0
+ self.nbits += 8
+ continue
+ byte = data[self.pos]
+ self.pos += 1
+ if byte == 0xFF:
+ nxt = data[self.pos] if self.pos < len(data) else 0
+ if nxt == 0x00:
+ self.pos += 1
+ elif 0xD0 <= nxt <= 0xD7:
+ # restart marker: stop feeding, sync() consumes it
+ self.pos -= 1
+ self.bits = (self.bits << 8) | 0
+ self.nbits += 8
+ continue
+ else:
+ self.pos -= 1
+ self.bits = (self.bits << 8) | 0
+ self.nbits += 8
+ continue
+ self.bits = (self.bits << 8) | byte
+ self.nbits += 8
+
+ def receive(self, length: int) -> int:
+ if length == 0:
+ return 0
+ if self.nbits < length:
+ self._fill()
+ self.nbits -= length
+ value = (self.bits >> self.nbits) & ((1 << length) - 1)
+ self.bits &= (1 << self.nbits) - 1
+ return value
+
+ def bit(self) -> int:
+ return self.receive(1)
+
+ def sync_restart(self) -> None:
+ """Consume an RSTn marker and drop partial bits."""
+ self.bits = 0
+ self.nbits = 0
+ data = self.data
+ while self.pos + 1 < len(data):
+ if data[self.pos] == 0xFF and 0xD0 <= data[self.pos + 1] <= 0xD7:
+ self.pos += 2
+ return
+ self.pos += 1
+
+
+def _build_huffman(counts: bytes, symbols: bytes) -> dict[tuple[int, int], int]:
+ """Map (bit-length, code) -> symbol. Canonical JPEG Huffman assignment."""
+ table: dict[tuple[int, int], int] = {}
+ code = 0
+ index = 0
+ for length in range(1, 17):
+ for _ in range(counts[length - 1]):
+ table[(length, code)] = symbols[index]
+ index += 1
+ code += 1
+ code <<= 1
+ return table
+
+
+def _decode_huffman(reader: _BitReader, table: dict[tuple[int, int], int]) -> int:
+ code = 0
+ for length in range(1, 17):
+ code = (code << 1) | reader.bit()
+ symbol = table.get((length, code))
+ if symbol is not None:
+ return symbol
+ raise ValueError("invalid Huffman code in entropy-coded data")
+
+
+def _extend(value: int, length: int) -> int:
+ """Convert an unsigned magnitude to its signed JPEG value."""
+ if length == 0:
+ return 0
+ return value if value >= (1 << (length - 1)) else value - (1 << length) + 1
+
+
+def _idct_2d(block: list[float]) -> list[float]:
+ """Separable 8x8 inverse DCT. DC-only blocks short-circuit."""
+ if not any(block[1:]):
+ flat = block[0] * 0.125
+ return [flat] * 64
+
+ tmp = [0.0] * 64
+ for y in range(8):
+ row = y * 8
+ coeffs = block[row:row + 8]
+ if not any(coeffs[1:]):
+ value = coeffs[0] * 0.353553390593273762
+ for x in range(8):
+ tmp[row + x] = value
+ continue
+ for x in range(8):
+ total = 0.0
+ for u in range(8):
+ c = coeffs[u]
+ if c:
+ total += c * _IDCT[u][x]
+ tmp[row + x] = total
+
+ out = [0.0] * 64
+ for x in range(8):
+ column = [tmp[y * 8 + x] for y in range(8)]
+ if not any(column[1:]):
+ value = column[0] * 0.353553390593273762
+ for y in range(8):
+ out[y * 8 + x] = value
+ continue
+ for y in range(8):
+ total = 0.0
+ for v in range(8):
+ c = column[v]
+ if c:
+ total += c * _IDCT[v][y]
+ out[y * 8 + x] = total
+ return out
+
+
+def _axis_map(out_len: int, samp: int, samp_max: int, plane_len: int) -> list[tuple[int, int, float]]:
+ """Per-output-pixel (low, high, fraction) for triangular chroma upsampling.
+
+ Subsampled chroma samples sit at the centre of the luma pixels they cover, so
+ output pixel x maps to chroma coordinate (x + 0.5) * samp/samp_max - 0.5.
+ Nearest-neighbour replication instead of this interpolation is visible as
+ banding on sharp colour edges (~30/255 against a libjpeg reference)."""
+ scale = samp / samp_max
+ mapping: list[tuple[int, int, float]] = []
+ last = max(0, plane_len - 1)
+ for x in range(out_len):
+ coord = (x + 0.5) * scale - 0.5
+ low = int(coord // 1)
+ frac = coord - low
+ if low < 0:
+ low, frac = 0, 0.0
+ high = low + 1
+ if low > last:
+ low = last
+ if high > last:
+ high = last
+ mapping.append((low, high, frac))
+ return mapping
+
+
+def _bilinear(plane: list[float], row0: int, row1: int, yfrac: float,
+ xmap: tuple[int, int, float]) -> float:
+ x0, x1, xfrac = xmap
+ top = plane[row0 + x0] + (plane[row0 + x1] - plane[row0 + x0]) * xfrac
+ if yfrac == 0.0 and row0 == row1:
+ return top
+ bottom = plane[row1 + x0] + (plane[row1 + x1] - plane[row1 + x0]) * xfrac
+ return top + (bottom - top) * yfrac
+
+
+def _clamp(value: float) -> int:
+ if value <= 0.0:
+ return 0
+ if value >= 255.0:
+ return 255
+ return int(value + 0.5)
+
+
+def decode_jpeg(data: bytes) -> tuple[int, int, list[tuple[int, int, int, int]]]:
+ """Decode baseline JPEG bytes to (width, height, RGBA pixel list)."""
+ if not is_jpeg(data):
+ raise ValueError("not a JPEG file")
+
+ quant: dict[int, list[int]] = {}
+ huff_dc: dict[int, dict[tuple[int, int], int]] = {}
+ huff_ac: dict[int, dict[tuple[int, int], int]] = {}
+ components: list[dict] = []
+ width = height = 0
+ restart_interval = 0
+ scan_start = -1
+ scan_components: list[dict] = []
+
+ pos = 2
+ while pos + 3 < len(data):
+ if data[pos] != 0xFF:
+ pos += 1
+ continue
+ marker = data[pos + 1]
+ pos += 2
+ if marker in (0x01, EOI) or 0xD0 <= marker <= 0xD7:
+ continue
+ if pos + 2 > len(data):
+ break
+ seg_len = struct.unpack(">H", data[pos:pos + 2])[0]
+ segment = data[pos + 2:pos + seg_len]
+
+ if marker == SOF_PROGRESSIVE:
+ raise UnsupportedJpeg("progressive JPEG is not supported by this decoder")
+ if marker in (0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
+ raise UnsupportedJpeg(f"unsupported JPEG coding mode (SOF marker 0x{marker:02X})")
+
+ if marker in (SOF_BASELINE, SOF_EXTENDED):
+ precision = segment[0]
+ if precision != 8:
+ raise UnsupportedJpeg(f"only 8-bit JPEG is supported, got {precision}-bit")
+ height, width = struct.unpack(">HH", segment[1:5])
+ count = segment[5]
+ if count not in (1, 3):
+ raise UnsupportedJpeg(
+ f"only grayscale and YCbCr JPEG are supported, got {count} components"
+ )
+ components = []
+ for i in range(count):
+ cid, sampling, tq = segment[6 + i * 3:9 + i * 3]
+ components.append({
+ "id": cid,
+ "h": sampling >> 4,
+ "v": sampling & 15,
+ "tq": tq,
+ })
+ elif marker == DQT:
+ cursor = 0
+ while cursor < len(segment):
+ pq_tq = segment[cursor]
+ cursor += 1
+ precision, table_id = pq_tq >> 4, pq_tq & 15
+ values = [0] * 64
+ for i in range(64):
+ if precision:
+ values[ZIGZAG[i]] = struct.unpack(">H", segment[cursor:cursor + 2])[0]
+ cursor += 2
+ else:
+ values[ZIGZAG[i]] = segment[cursor]
+ cursor += 1
+ quant[table_id] = values
+ elif marker == DHT:
+ cursor = 0
+ while cursor < len(segment):
+ tc_th = segment[cursor]
+ cursor += 1
+ counts = segment[cursor:cursor + 16]
+ cursor += 16
+ total = sum(counts)
+ symbols = segment[cursor:cursor + total]
+ cursor += total
+ table = _build_huffman(counts, symbols)
+ if tc_th >> 4:
+ huff_ac[tc_th & 15] = table
+ else:
+ huff_dc[tc_th & 15] = table
+ elif marker == DRI:
+ restart_interval = struct.unpack(">H", segment[0:2])[0]
+ elif marker == SOS:
+ count = segment[0]
+ scan_components = []
+ for i in range(count):
+ cid, tables = segment[1 + i * 2:3 + i * 2]
+ for comp in components:
+ if comp["id"] == cid:
+ comp["dc"] = tables >> 4
+ comp["ac"] = tables & 15
+ scan_components.append(comp)
+ break
+ scan_start = pos + seg_len
+ break
+ pos += seg_len
+
+ if not components or width == 0 or height == 0:
+ raise ValueError("JPEG is missing a frame header")
+ if scan_start < 0:
+ raise ValueError("JPEG is missing scan data")
+
+ h_max = max(c["h"] for c in components)
+ v_max = max(c["v"] for c in components)
+ mcu_w, mcu_h = 8 * h_max, 8 * v_max
+ mcus_x = (width + mcu_w - 1) // mcu_w
+ mcus_y = (height + mcu_h - 1) // mcu_h
+
+ for comp in components:
+ comp["bw"] = mcus_x * comp["h"]
+ comp["bh"] = mcus_y * comp["v"]
+ comp["plane"] = [0] * (comp["bw"] * 8 * comp["bh"] * 8)
+ comp["stride"] = comp["bw"] * 8
+ comp["pred"] = 0
+
+ reader = _BitReader(data, scan_start)
+ block = [0.0] * 64
+ mcu_index = 0
+
+ for my in range(mcus_y):
+ for mx in range(mcus_x):
+ if restart_interval and mcu_index and mcu_index % restart_interval == 0:
+ reader.sync_restart()
+ for comp in components:
+ comp["pred"] = 0
+ mcu_index += 1
+
+ for comp in scan_components:
+ qt = quant.get(comp["tq"])
+ if qt is None:
+ raise ValueError("JPEG references an undefined quantization table")
+ dc_table = huff_dc.get(comp["dc"])
+ ac_table = huff_ac.get(comp["ac"])
+ if dc_table is None or ac_table is None:
+ raise ValueError("JPEG references an undefined Huffman table")
+
+ for by in range(comp["v"]):
+ for bx in range(comp["h"]):
+ for i in range(64):
+ block[i] = 0.0
+
+ t = _decode_huffman(reader, dc_table)
+ diff = _extend(reader.receive(t), t) if t else 0
+ comp["pred"] += diff
+ block[0] = float(comp["pred"] * qt[0])
+
+ k = 1
+ while k < 64:
+ rs = _decode_huffman(reader, ac_table)
+ run, size = rs >> 4, rs & 15
+ if size == 0:
+ if run == 15:
+ k += 16
+ continue
+ break
+ k += run
+ if k > 63:
+ break
+ zz = ZIGZAG[k]
+ block[zz] = float(_extend(reader.receive(size), size) * qt[zz])
+ k += 1
+
+ pixels = _idct_2d(block)
+ px0 = (mx * comp["h"] + bx) * 8
+ py0 = (my * comp["v"] + by) * 8
+ stride = comp["stride"]
+ plane = comp["plane"]
+ for y in range(8):
+ row = (py0 + y) * stride + px0
+ src = y * 8
+ for x in range(8):
+ plane[row + x] = pixels[src + x] + 128.0
+
+ out: list[tuple[int, int, int, int]] = []
+ if len(components) == 1:
+ comp = components[0]
+ plane, stride = comp["plane"], comp["stride"]
+ for y in range(height):
+ base = y * stride
+ for x in range(width):
+ grey = _clamp(plane[base + x])
+ out.append((grey, grey, grey, 255))
+ return width, height, out
+
+ y_c, cb_c, cr_c = components[0], components[1], components[2]
+ for comp in (y_c, cb_c, cr_c):
+ comp["w"] = -(-width * comp["h"] // h_max)
+ comp["h_px"] = -(-height * comp["v"] // v_max)
+ comp["xmap"] = _axis_map(width, comp["h"], h_max, comp["w"])
+ comp["ymap"] = _axis_map(height, comp["v"], v_max, comp["h_px"])
+
+ y_plane, y_stride, y_xmap, y_ymap = (
+ y_c["plane"], y_c["stride"], y_c["xmap"], y_c["ymap"])
+ cb_plane, cb_stride, cb_xmap, cb_ymap = (
+ cb_c["plane"], cb_c["stride"], cb_c["xmap"], cb_c["ymap"])
+ cr_plane, cr_stride, cr_xmap, cr_ymap = (
+ cr_c["plane"], cr_c["stride"], cr_c["xmap"], cr_c["ymap"])
+
+ for y in range(height):
+ yy0, yy1, yfr = y_ymap[y]
+ cby0, cby1, cbyfr = cb_ymap[y]
+ cry0, cry1, cryfr = cr_ymap[y]
+ y_r0, y_r1 = yy0 * y_stride, yy1 * y_stride
+ cb_r0, cb_r1 = cby0 * cb_stride, cby1 * cb_stride
+ cr_r0, cr_r1 = cry0 * cr_stride, cry1 * cr_stride
+ for x in range(width):
+ luma = _bilinear(y_plane, y_r0, y_r1, yfr, y_xmap[x])
+ cb = _bilinear(cb_plane, cb_r0, cb_r1, cbyfr, cb_xmap[x]) - 128.0
+ cr = _bilinear(cr_plane, cr_r0, cr_r1, cryfr, cr_xmap[x]) - 128.0
+ out.append((
+ _clamp(luma + 1.402 * cr),
+ _clamp(luma - 0.344136 * cb - 0.714136 * cr),
+ _clamp(luma + 1.772 * cb),
+ 255,
+ ))
+ return width, height, out
diff --git a/forge/_shared/pipeline_routing.py b/forge/_shared/pipeline_routing.py
new file mode 100644
index 0000000..6b28145
--- /dev/null
+++ b/forge/_shared/pipeline_routing.py
@@ -0,0 +1,177 @@
+"""Fail-closed routing for the weapon and character authoring tracks."""
+
+from __future__ import annotations
+
+from typing import Any, Final
+
+
+CONFIDENCE_THRESHOLD: Final[float] = 0.82
+TRACK_BY_KIND: Final[dict[str, str]] = {
+ "weapon": "weapon-v1.4",
+ "character": "character-v1.5",
+}
+VALID_TRACKS: Final[frozenset[str]] = frozenset(TRACK_BY_KIND.values())
+VALID_KINDS: Final[frozenset[str]] = frozenset({"weapon", "character", "hybrid", "unknown"})
+VALID_SOURCES: Final[frozenset[str]] = frozenset({"explicit", "classification", "legacy"})
+VALID_STATUSES: Final[frozenset[str]] = frozenset({"resolved", "request-input"})
+
+
+def _fallback_classification(reason: str) -> dict[str, Any]:
+ return {
+ "kind": "unknown",
+ "confidence": 0.0,
+ "evidenceRefs": [f"pipeline-routing:{reason}"],
+ "provider": "pipeline-routing",
+ "version": "1",
+ }
+
+
+def _explicit_classification(track: str) -> dict[str, Any]:
+ kind = "weapon" if track == "weapon-v1.4" else "character"
+ return {
+ "kind": kind,
+ "confidence": 1.0,
+ "evidenceRefs": [f"pipeline-routing:explicit:{track}"],
+ "provider": "pipeline-routing-cli",
+ "version": "1",
+ }
+
+
+def _normalize_classification(classification: Any) -> tuple[dict[str, Any], list[str]]:
+ if classification is None:
+ return _fallback_classification("missing-classification"), []
+ if not isinstance(classification, dict):
+ return _fallback_classification("malformed-classification"), ["classification is malformed"]
+ kind = classification.get("kind")
+ confidence = classification.get("confidence")
+ refs = classification.get("evidenceRefs")
+ provider = classification.get("provider")
+ version = classification.get("version")
+ malformed = (
+ kind not in VALID_KINDS
+ or not isinstance(confidence, (int, float))
+ or isinstance(confidence, bool)
+ or not 0.0 <= confidence <= 1.0
+ or not isinstance(refs, list)
+ or not refs
+ or not all(isinstance(ref, str) and ref for ref in refs)
+ or not isinstance(provider, str)
+ or not provider
+ or not isinstance(version, str)
+ or not version
+ )
+ if malformed:
+ return _fallback_classification("malformed-classification"), ["classification is malformed"]
+ return {
+ "kind": kind,
+ "confidence": float(confidence),
+ "evidenceRefs": list(refs),
+ "provider": provider,
+ "version": version,
+ }, []
+
+
+def classification_from_cs2_manifest(manifest: dict[str, Any]) -> dict[str, Any]:
+ """Translate the CS2 authoritative record into the shared routing classification."""
+ record = manifest.get("classification")
+ if not isinstance(record, dict):
+ return _fallback_classification("cs2-manifest-missing-classification")
+ return {
+ "kind": "weapon",
+ "confidence": record.get("confidence"),
+ "evidenceRefs": record.get("evidenceRefs"),
+ "provider": record.get("provider"),
+ "version": record.get("version"),
+ }
+
+
+def resolve_pipeline_routing(
+ *,
+ explicit_track: str | None = None,
+ classification: Any = None,
+ legacy_cs2: bool = False,
+) -> dict[str, Any]:
+ """Resolve one supported track or return request-input without guessing a template."""
+ if legacy_cs2:
+ resolved_classification = {
+ "kind": "weapon",
+ "confidence": 1.0,
+ "evidenceRefs": ["legacy:cs2Intake"],
+ "provider": "legacy-cs2-intake",
+ "version": "1",
+ }
+ if explicit_track is not None and explicit_track != "weapon-v1.4":
+ return {
+ "version": 1,
+ "track": explicit_track,
+ "source": "explicit",
+ "status": "request-input",
+ "classification": resolved_classification,
+ "conflicts": [
+ f"explicit track {explicit_track!r} contradicts legacy CS2 weapon routing"
+ ],
+ }
+ return {
+ "version": 1,
+ "track": "weapon-v1.4",
+ "source": "legacy",
+ "status": "resolved",
+ "classification": resolved_classification,
+ "conflicts": [],
+ }
+
+ normalized, conflicts = _normalize_classification(classification)
+ if explicit_track is not None and explicit_track not in VALID_TRACKS:
+ conflicts.append("explicit track is invalid")
+ explicit_track = None
+ if explicit_track is not None and classification is None:
+ normalized = _explicit_classification(explicit_track)
+
+ kind = normalized["kind"]
+ confidence = normalized["confidence"]
+ reliable_kind = kind in TRACK_BY_KIND and confidence >= CONFIDENCE_THRESHOLD
+ requested_track = explicit_track or TRACK_BY_KIND.get(kind, "weapon-v1.4")
+ if kind in {"hybrid", "unknown"}:
+ conflicts.append(f"classification kind {kind!r} requires input")
+ elif confidence < CONFIDENCE_THRESHOLD:
+ conflicts.append(f"classification confidence {confidence:.2f} is below {CONFIDENCE_THRESHOLD:.2f}")
+ elif explicit_track is not None and reliable_kind and TRACK_BY_KIND[kind] != explicit_track:
+ conflicts.append(f"explicit track {explicit_track!r} contradicts reliable classification {kind!r}")
+
+ status = "resolved" if reliable_kind and not conflicts else "request-input"
+ source = "explicit" if explicit_track is not None else "classification"
+ return {
+ "version": 1,
+ "track": requested_track,
+ "source": source,
+ "status": status,
+ "classification": normalized,
+ "conflicts": conflicts,
+ }
+
+
+def validate_pipeline_routing(routing: Any) -> list[str]:
+ """Return contract errors for a persisted routing record."""
+ if not isinstance(routing, dict):
+ return ["pipelineRouting must be an object"]
+ errors: list[str] = []
+ if routing.get("version") != 1:
+ errors.append("pipelineRouting.version must be 1")
+ if routing.get("track") not in VALID_TRACKS:
+ errors.append("pipelineRouting.track must be weapon-v1.4 or character-v1.5")
+ if routing.get("source") not in VALID_SOURCES:
+ errors.append("pipelineRouting.source must be explicit, classification, or legacy")
+ if routing.get("status") not in VALID_STATUSES:
+ errors.append("pipelineRouting.status must be resolved or request-input")
+ classification = routing.get("classification")
+ normalized, classification_errors = _normalize_classification(classification)
+ if classification_errors:
+ errors.append("pipelineRouting.classification is malformed")
+ if not isinstance(classification, dict) or classification != normalized:
+ errors.append("pipelineRouting.classification must use the shared classification contract")
+ conflicts = routing.get("conflicts")
+ if not isinstance(conflicts, list) or not all(isinstance(conflict, str) for conflict in conflicts):
+ errors.append("pipelineRouting.conflicts must be a list")
+ elif routing.get("status") == "resolved" and conflicts:
+ errors.append("resolved pipelineRouting cannot contain conflicts")
+ return errors
diff --git a/forge/_shared/sdf_primitives.py b/forge/_shared/sdf_primitives.py
new file mode 100644
index 0000000..6ab1df4
--- /dev/null
+++ b/forge/_shared/sdf_primitives.py
@@ -0,0 +1,172 @@
+"""Validation for opt-in implicit signed-distance-field descriptors."""
+
+from __future__ import annotations
+
+import math
+from typing import Any
+
+
+VALID_SDF_PRIMITIVES = {"sphere", "capsule", "box", "cone", "ellipsoid"}
+VALID_SDF_OPERATIONS = {"smooth-union", "subtract", "intersect"}
+MAX_SDF_PRIMITIVES = 64
+MAX_SDF_OPERATIONS = 128
+_PRIMITIVE_FIELDS = {"id", "type", "center", "radius", "height", "size", "dimensions", "radii", "transform"}
+_VECTOR_FIELDS = {"center", "size", "radii"}
+_TRANSFORM_FIELDS = {"position", "translation", "rotation", "scale"}
+_OPERATION_FIELDS = {"id", "output", "type", "left", "right", "radius"}
+
+
+def _is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _validate_finite(value: Any, label: str, errors: list[str]) -> None:
+ if _is_number(value):
+ if not math.isfinite(float(value)):
+ errors.append(f"{label} must be finite")
+ return
+ if isinstance(value, list):
+ for index, item in enumerate(value):
+ _validate_finite(item, f"{label}[{index}]", errors)
+ elif isinstance(value, dict):
+ for key, item in value.items():
+ _validate_finite(item, f"{label}.{key}", errors)
+
+
+def _validate_vector(value: Any, label: str, errors: list[str], positive: bool = False) -> None:
+ if not isinstance(value, list) or len(value) != 3:
+ errors.append(f"{label} must be [number, number, number]")
+ return
+ for index, item in enumerate(value):
+ if not _is_number(item):
+ errors.append(f"{label}[{index}] must be numeric")
+ elif positive and float(item) <= 0:
+ errors.append(f"{label}[{index}] must be greater than 0")
+
+
+def _validate_positive(value: Any, label: str, errors: list[str], allow_zero: bool = False) -> None:
+ if not _is_number(value):
+ errors.append(f"{label} must be numeric")
+ elif float(value) < 0 or (not allow_zero and float(value) == 0):
+ errors.append(f"{label} must be greater than {0 if allow_zero else 0}")
+
+
+def _validate_primitive(primitive: Any, index: int, ids: set[str], errors: list[str]) -> None:
+ label = f"geometryDescriptor.sdf.primitives[{index}]"
+ if not isinstance(primitive, dict):
+ errors.append(f"{label} must be an object")
+ return
+ primitive_id = primitive.get("id")
+ if not isinstance(primitive_id, str) or not primitive_id.strip():
+ errors.append(f"{label}.id is required")
+ elif primitive_id in ids:
+ errors.append(f"{label}.id duplicates {primitive_id!r}")
+ else:
+ ids.add(primitive_id)
+ primitive_type = primitive.get("type")
+ if primitive_type not in VALID_SDF_PRIMITIVES:
+ errors.append(f"{label}.type must be one of: {', '.join(sorted(VALID_SDF_PRIMITIVES))}")
+ for field in primitive:
+ if field not in _PRIMITIVE_FIELDS:
+ errors.append(f"{label}.{field} is not supported")
+ for field in _VECTOR_FIELDS & set(primitive):
+ _validate_vector(primitive[field], f"{label}.{field}", errors, positive=field in {"size", "radii"})
+ transform = primitive.get("transform")
+ if transform is not None:
+ if not isinstance(transform, dict):
+ errors.append(f"{label}.transform must be an object")
+ else:
+ for field in transform:
+ if field not in _TRANSFORM_FIELDS:
+ errors.append(f"{label}.transform.{field} is not supported")
+ for field in _TRANSFORM_FIELDS & set(transform):
+ _validate_vector(
+ transform[field], f"{label}.transform.{field}", errors, positive=field == "scale"
+ )
+ if primitive_type in {"sphere", "capsule", "cone"}:
+ _validate_positive(primitive.get("radius"), f"{label}.radius", errors)
+ if primitive_type == "capsule":
+ _validate_positive(primitive.get("height"), f"{label}.height", errors, allow_zero=True)
+ if primitive_type == "cone":
+ _validate_positive(primitive.get("height"), f"{label}.height", errors)
+ if primitive_type == "box" and "size" not in primitive:
+ _validate_vector(primitive.get("dimensions"), f"{label}.dimensions", errors, positive=True)
+ if primitive_type == "ellipsoid" and "radii" not in primitive:
+ _validate_vector(primitive.get("radius"), f"{label}.radius", errors, positive=True)
+ _validate_finite(primitive, label, errors)
+
+
+def _validate_operation(operation: Any, index: int, known_ids: set[str], errors: list[str]) -> None:
+ label = f"geometryDescriptor.sdf.operations[{index}]"
+ if not isinstance(operation, dict):
+ errors.append(f"{label} must be an object")
+ return
+ for field in operation:
+ if field not in _OPERATION_FIELDS:
+ errors.append(f"{label}.{field} is not supported")
+ operation_type = operation.get("type")
+ if operation_type not in VALID_SDF_OPERATIONS:
+ errors.append(f"{label}.type must be one of: {', '.join(sorted(VALID_SDF_OPERATIONS))}")
+ for side in ("left", "right"):
+ value = operation.get(side)
+ if not isinstance(value, str) or not value.strip():
+ errors.append(f"{label}.{side} must reference a primitive or previous operation")
+ elif value not in known_ids:
+ errors.append(f"{label}.{side} references unknown SDF id {value!r}")
+ if operation_type == "smooth-union":
+ _validate_positive(operation.get("radius"), f"{label}.radius", errors)
+ if "id" in operation and "output" in operation:
+ errors.append(f"{label}.id and output cannot both be set")
+ output = operation.get("id", operation.get("output", f"operation-{index}"))
+ if not isinstance(output, str) or not output.strip():
+ errors.append(f"{label}.id/output must be a non-empty string when present")
+ elif output in known_ids:
+ field = "id" if "id" in operation else "output"
+ errors.append(f"{label}.{field} duplicates existing SDF id {output!r}")
+ else:
+ known_ids.add(output)
+ _validate_finite(operation, label, errors)
+
+
+def validate_sdf_descriptor(component_id: str, descriptor: Any, errors: list[str]) -> None:
+ """Append schema errors for an opt-in component SDF descriptor."""
+ label = f"component {component_id!r} geometryDescriptor.sdf"
+ if not isinstance(descriptor, dict):
+ errors.append(f"{label} must be an object")
+ return
+ primitives = descriptor.get("primitives")
+ if not isinstance(primitives, list) or not primitives:
+ errors.append(f"{label}.primitives must be a non-empty array")
+ return
+ if len(primitives) > MAX_SDF_PRIMITIVES:
+ errors.append(f"{label}.primitives must not contain more than {MAX_SDF_PRIMITIVES} entries")
+ ids: set[str] = set()
+ for index, primitive in enumerate(primitives):
+ _validate_primitive(primitive, index, ids, errors)
+ operations = descriptor.get("operations", [])
+ if not isinstance(operations, list):
+ errors.append(f"{label}.operations must be an array")
+ else:
+ if len(operations) > MAX_SDF_OPERATIONS:
+ errors.append(f"{label}.operations must not contain more than {MAX_SDF_OPERATIONS} entries")
+ for index, operation in enumerate(operations):
+ _validate_operation(operation, index, ids, errors)
+ resolution = descriptor.get("resolution")
+ if not isinstance(resolution, int) or isinstance(resolution, bool) or resolution < 4:
+ errors.append(f"{label}.resolution must be an integer from 4 to 64")
+ elif resolution > 64:
+ errors.append(f"{label}.resolution must not exceed 64")
+ bounds = descriptor.get("bounds")
+ if bounds is not None:
+ if not isinstance(bounds, dict):
+ errors.append(f"{label}.bounds must be an object")
+ else:
+ minimum = bounds.get("min")
+ maximum = bounds.get("max")
+ _validate_vector(minimum, f"{label}.bounds.min", errors)
+ _validate_vector(maximum, f"{label}.bounds.max", errors)
+ if isinstance(minimum, list) and isinstance(maximum, list) and len(minimum) == len(maximum) == 3:
+ for index, (minimum_value, maximum_value) in enumerate(zip(minimum, maximum)):
+ if _is_number(minimum_value) and _is_number(maximum_value) and minimum_value >= maximum_value:
+ errors.append(f"{label}.bounds.min[{index}] must be less than bounds.max[{index}]")
+ _validate_finite(descriptor, label, errors)
diff --git a/forge/_shared/subdivision.py b/forge/_shared/subdivision.py
new file mode 100644
index 0000000..565b416
--- /dev/null
+++ b/forge/_shared/subdivision.py
@@ -0,0 +1,232 @@
+MAX_SUBDIVISION_ITERATIONS = 4
+MAX_SUBDIVISION_QUAD_FACES = 100_000
+
+CYLINDER_RADIAL_SEGMENTS = 48
+CYLINDER_HEIGHT_SEGMENTS = 16
+ATTACHMENT_CYLINDER_RADIAL_SEGMENTS = 32
+ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS = 12
+CONE_SUBDIVISION_TOP_RADIUS = 0.0001
+# A tapering ConeGeometry, unlike a constant-radius CylinderGeometry, does not weld
+# cleanly at CYLINDER_HEIGHT_SEGMENTS (16): measured 2448 raw / 2160 welded boundary
+# edges (a real topology defect, not a benign UV seam -- box/cylinder/sphere/torus/
+# ellipsoid all weld to 0/0 at their own segment counts). A cone built with
+# heightSegments=1 (three.js's own default) welds cleanly to 0/0, verified directly;
+# a solid cone's lateral surface does not need internal height rings for shading or
+# silhouette quality at rest, only the subdivision-requested substitute (a near-
+# degenerate CylinderGeometry, unaffected by this constant) needs a denser cage.
+CONE_HEIGHT_SEGMENTS = 1
+SPHERE_WIDTH_SEGMENTS = 64
+SPHERE_HEIGHT_SEGMENTS = 40
+CAPSULE_CAP_SEGMENTS = 16
+CAPSULE_RADIAL_SEGMENTS = 32
+TORUS_TUBULAR_SEGMENTS = 24
+TORUS_RADIAL_SEGMENTS = 96
+PLANE_WIDTH_SEGMENTS = 24
+PLANE_HEIGHT_SEGMENTS = 24
+
+
+# --- Tessellation tiers -------------------------------------------------------
+#
+# The constants above are the `hero` tier and stay the module-level defaults, so
+# every existing caller keeps its current output byte-for-byte. A spec that wants
+# a cheaper mesh selects a tier via `performanceBudget.targetTriangles`, which
+# was already in the schema and read by nothing (`lodPlan` has the same problem;
+# see decimate.py's docstring).
+#
+# Two floors are load-bearing and are asserted by `validate_tier()`:
+#
+# * HEIGHT segments >= MIN_JOINT_HEIGHT_SEGMENTS on anything a bone deforms. One
+# quad spanning a joint leaves no vertex at the pivot, so the influenced region
+# skips the joint entirely and the elbow collapses instead of bending.
+#
+# The value is 4, not the 3 of the standard "rule of three" (one loop on the
+# joint plane, one supporting loop each side). External practice says 3 is the
+# minimum; this repository already decided 3 was not enough. `emit_rig.py:399`
+# derives its own ring count as `max(4, ceil(cyl_length / target_ring_spacing))`
+# -- a hard floor of 4 -- in the same module whose NOTES.md documents the
+# single-quad-band joint-pinch failure this floor exists to prevent. Where an
+# in-repo measurement and an external rule of thumb disagree, the measurement
+# wins, so this matches emit_rig.py rather than the textbook.
+# * RADIAL segments >= MIN_RADIAL_SEGMENTS, below which a swept primitive stops
+# reading as a round limb and the silhouette goes visibly polygonal.
+MIN_JOINT_HEIGHT_SEGMENTS = 4
+MIN_RADIAL_SEGMENTS = 6
+
+# Deliberately NOT tiered. A tapering cone does not weld cleanly at higher height
+# segment counts -- 2448 raw / 2160 welded boundary edges, a real topology defect,
+# see the comment on CONE_HEIGHT_SEGMENTS above -- and 1 is the value that welds to
+# 0/0. `validate_tier()` pins it so a future tier cannot quietly reintroduce that
+# defect while chasing a triangle budget.
+REQUIRED_CONE_HEIGHT_SEGMENTS = 1
+
+TESSELLATION_TIERS: dict[str, dict[str, int]] = {
+ "low": {
+ "CYLINDER_RADIAL_SEGMENTS": 10,
+ "CYLINDER_HEIGHT_SEGMENTS": 4,
+ "ATTACHMENT_CYLINDER_RADIAL_SEGMENTS": 8,
+ "ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS": 4,
+ "CONE_HEIGHT_SEGMENTS": 1,
+ "SPHERE_WIDTH_SEGMENTS": 16,
+ "SPHERE_HEIGHT_SEGMENTS": 10,
+ "CAPSULE_CAP_SEGMENTS": 4,
+ "CAPSULE_RADIAL_SEGMENTS": 8,
+ "TORUS_TUBULAR_SEGMENTS": 8,
+ "TORUS_RADIAL_SEGMENTS": 16,
+ "PLANE_WIDTH_SEGMENTS": 4,
+ "PLANE_HEIGHT_SEGMENTS": 4,
+ "BOX_SEGMENTS": 1,
+ "SDF_MAX_RESOLUTION": 24,
+ },
+ "standard": {
+ "CYLINDER_RADIAL_SEGMENTS": 24,
+ "CYLINDER_HEIGHT_SEGMENTS": 8,
+ "ATTACHMENT_CYLINDER_RADIAL_SEGMENTS": 16,
+ "ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS": 6,
+ "CONE_HEIGHT_SEGMENTS": 1,
+ "SPHERE_WIDTH_SEGMENTS": 32,
+ "SPHERE_HEIGHT_SEGMENTS": 20,
+ "CAPSULE_CAP_SEGMENTS": 8,
+ "CAPSULE_RADIAL_SEGMENTS": 16,
+ "TORUS_TUBULAR_SEGMENTS": 12,
+ "TORUS_RADIAL_SEGMENTS": 48,
+ "PLANE_WIDTH_SEGMENTS": 12,
+ "PLANE_HEIGHT_SEGMENTS": 12,
+ "BOX_SEGMENTS": 4,
+ "SDF_MAX_RESOLUTION": 40,
+ },
+ "hero": {
+ "CYLINDER_RADIAL_SEGMENTS": CYLINDER_RADIAL_SEGMENTS,
+ "CYLINDER_HEIGHT_SEGMENTS": CYLINDER_HEIGHT_SEGMENTS,
+ "ATTACHMENT_CYLINDER_RADIAL_SEGMENTS": ATTACHMENT_CYLINDER_RADIAL_SEGMENTS,
+ "ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS": ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS,
+ "CONE_HEIGHT_SEGMENTS": CONE_HEIGHT_SEGMENTS,
+ "SPHERE_WIDTH_SEGMENTS": SPHERE_WIDTH_SEGMENTS,
+ "SPHERE_HEIGHT_SEGMENTS": SPHERE_HEIGHT_SEGMENTS,
+ "CAPSULE_CAP_SEGMENTS": CAPSULE_CAP_SEGMENTS,
+ "CAPSULE_RADIAL_SEGMENTS": CAPSULE_RADIAL_SEGMENTS,
+ "TORUS_TUBULAR_SEGMENTS": TORUS_TUBULAR_SEGMENTS,
+ "TORUS_RADIAL_SEGMENTS": TORUS_RADIAL_SEGMENTS,
+ "PLANE_WIDTH_SEGMENTS": PLANE_WIDTH_SEGMENTS,
+ "PLANE_HEIGHT_SEGMENTS": PLANE_HEIGHT_SEGMENTS,
+ "BOX_SEGMENTS": 12,
+ "SDF_MAX_RESOLUTION": 64,
+ },
+}
+
+DEFAULT_TESSELLATION_TIER = "hero"
+
+# Measured, not guessed: a 61-component humanoid spec generated at `hero` builds
+# 14,208 triangles (counted by constructing the emitted factory under node, not
+# by parsing the source). The same primitive mix at each tier, using three.js's
+# own triangle formulas, is what these thresholds are drawn from.
+TIER_TRIANGLE_CEILINGS: tuple[tuple[int, str], ...] = (
+ (6_000, "low"),
+ (60_000, "standard"),
+)
+
+
+def tier_for_target_triangles(target_triangles: object) -> str:
+ """Pick a tessellation tier from `performanceBudget.targetTriangles`.
+
+ Anything missing, non-numeric or non-positive keeps the current behaviour
+ (`hero`), so specs written before this existed are unaffected.
+ """
+ if isinstance(target_triangles, bool) or not isinstance(target_triangles, (int, float)):
+ return DEFAULT_TESSELLATION_TIER
+ if target_triangles <= 0:
+ return DEFAULT_TESSELLATION_TIER
+ for ceiling, tier in TIER_TRIANGLE_CEILINGS:
+ if target_triangles <= ceiling:
+ return tier
+ return DEFAULT_TESSELLATION_TIER
+
+
+def validate_tier(name: str) -> dict[str, int]:
+ """Return a tier's segment table, refusing one that would break deformation."""
+ if name not in TESSELLATION_TIERS:
+ raise ValueError(
+ f"unknown tessellation tier {name!r}; expected one of {sorted(TESSELLATION_TIERS)}"
+ )
+ table = TESSELLATION_TIERS[name]
+ for key in ("CYLINDER_HEIGHT_SEGMENTS", "ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS"):
+ if table[key] < MIN_JOINT_HEIGHT_SEGMENTS:
+ raise ValueError(
+ f"tier {name!r} sets {key}={table[key]}, below the "
+ f"{MIN_JOINT_HEIGHT_SEGMENTS}-segment floor a bone needs to deform a joint"
+ )
+ for key in (
+ "CYLINDER_RADIAL_SEGMENTS",
+ "ATTACHMENT_CYLINDER_RADIAL_SEGMENTS",
+ "CAPSULE_RADIAL_SEGMENTS",
+ ):
+ if table[key] < MIN_RADIAL_SEGMENTS:
+ raise ValueError(
+ f"tier {name!r} sets {key}={table[key]}, below the "
+ f"{MIN_RADIAL_SEGMENTS}-segment floor a swept primitive needs to read as round"
+ )
+ if table["CONE_HEIGHT_SEGMENTS"] != REQUIRED_CONE_HEIGHT_SEGMENTS:
+ raise ValueError(
+ f"tier {name!r} sets CONE_HEIGHT_SEGMENTS={table['CONE_HEIGHT_SEGMENTS']}; a cone "
+ f"only welds cleanly at {REQUIRED_CONE_HEIGHT_SEGMENTS} and this is not a budget knob"
+ )
+ return table
+
+
+def segments_for_spec(spec: object) -> dict[str, int]:
+ """Resolve the segment table a spec should generate with."""
+ budget = spec.get("performanceBudget") if isinstance(spec, dict) else None
+ target = budget.get("targetTriangles") if isinstance(budget, dict) else None
+ return validate_tier(tier_for_target_triangles(target))
+
+
+def cylinder_source_face_count(radial_segments: int, height_segments: int) -> int:
+ return radial_segments * (height_segments + 1)
+
+
+def capsule_source_face_count(cap_segments: int, radial_segments: int, height_segments: int = 1) -> int:
+ """Return the exact triangle count emitted by `buildWatertightCapsule` in
+ generate_threejs_factory.py, which replaced THREE.CapsuleGeometry as the capsule
+ primitive's construction (see that file's `geometry_for()` and the
+ `buildWatertightCapsule` helper it emits). Raw THREE.CapsuleGeometry duplicates
+ every UV-seam vertex, same benign pattern as box/cylinder/sphere/torus -- it is
+ NOT actually non-manifold (a naive vertex-only mergeVertices() reports 64 such
+ edges, but that is a counting artifact from degenerate near-pole triangles, not
+ a real defect; confirmed by replicating subdivideCatmullClark's own degenerate-
+ aware vertex identity). `buildWatertightCapsule` is worth having regardless: it
+ is closed by construction (shared poles, radial index taken `% radialSegments`)
+ rather than relying on a weld, and has a smaller, exact triangle count: 2 pole
+ fans of `radial_segments` triangles each, plus `(2*cap_segments + height_segments
+ - 2)` ring bands of `2*radial_segments` triangles each -- fewer vertices for the
+ per-vertex skinning weight pass to visit. `height_segments` defaults to 1,
+ matching the one call site.
+ """
+ return 2 * radial_segments * (2 * cap_segments + height_segments - 1)
+
+
+def resolve_instanced_cluster_base(
+ primitive: str,
+ descriptor: dict[str, object],
+ valid_primitives: set[str],
+) -> str:
+ if primitive != "instanced-cluster":
+ return primitive
+ base = descriptor.get("baseGeometry")
+ if isinstance(base, str) and base not in {"", "instanced-cluster"} and base in valid_primitives:
+ return base
+ return "box"
+
+
+SUBDIVISION_SOURCE_FACE_ESTIMATES: dict[str, int] = {
+ "box": 6,
+ "sphere": 2 * SPHERE_WIDTH_SEGMENTS * SPHERE_HEIGHT_SEGMENTS,
+ "ellipsoid": 2 * SPHERE_WIDTH_SEGMENTS * SPHERE_HEIGHT_SEGMENTS,
+ "cylinder": cylinder_source_face_count(CYLINDER_RADIAL_SEGMENTS, CYLINDER_HEIGHT_SEGMENTS),
+ "cone": cylinder_source_face_count(CYLINDER_RADIAL_SEGMENTS, CYLINDER_HEIGHT_SEGMENTS),
+ "capsule": capsule_source_face_count(CAPSULE_CAP_SEGMENTS, CAPSULE_RADIAL_SEGMENTS),
+ "torus": 2 * TORUS_TUBULAR_SEGMENTS * TORUS_RADIAL_SEGMENTS,
+ "plane-card": 2 * PLANE_WIDTH_SEGMENTS * PLANE_HEIGHT_SEGMENTS,
+}
+ATTACHMENT_CYLINDER_SUBDIVISION_SOURCE_FACES = cylinder_source_face_count(
+ ATTACHMENT_CYLINDER_RADIAL_SEGMENTS,
+ ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS,
+)
diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.py
index 35ead94..cf24c34 100644
--- a/forge/_shared/workflow_state.py
+++ b/forge/_shared/workflow_state.py
@@ -31,8 +31,10 @@ SETUP_STEPS: Final = (
("spec-authoring", "python3 forge/stage2_spec/new_sculpt_spec.py \"<name>\" --image {reference} --assessment assessment.json --out object-sculpt-spec.json"),
(
"material-evidence",
- "When material fidelity matters, run analyze_texture.py and extract_pbr_evidence.py per verified crop; otherwise skip with a reason",
+ "python3 forge/stage1_intake/material_region_analysis.py --manifest material-regions.json --out-dir material-evidence --out material-analysis.json"
+ " (single-crop route: analyze_texture.py + extract_pbr_evidence.py per verified crop; otherwise skip with a reason)",
),
+ ("material-spec-wiring", "python3 forge/stage2_spec/apply_material_analysis.py {spec} material-analysis.json --in-place"),
("strict-validation", "python3 forge/stage2_spec/validate_sculpt_spec.py {spec} --strict-quality"),
)
diff --git a/forge/materials/__init__.py b/forge/materials/__init__.py
new file mode 100644
index 0000000..1382d8f
--- /dev/null
+++ b/forge/materials/__init__.py
@@ -0,0 +1,17 @@
+"""Runtime material-reference contracts for the img2threejs forge."""
+
+from .reference import (
+ MaterialReferenceError,
+ build_assignment,
+ load_reference,
+ resolve_material,
+ validate_reference,
+)
+
+__all__ = [
+ "MaterialReferenceError",
+ "build_assignment",
+ "load_reference",
+ "resolve_material",
+ "validate_reference",
+]
diff --git a/forge/materials/compatibility.py b/forge/materials/compatibility.py
new file mode 100644
index 0000000..8fc9255
--- /dev/null
+++ b/forge/materials/compatibility.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Check material bindings against geometry, UV, rig, collision and LOD contracts."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+
+def check_compatibility(spec: dict[str, Any]) -> dict[str, Any]:
+ materials = {str(item.get("id")): item for item in spec.get("materials", []) if isinstance(item, dict) and item.get("id")}
+ components = [item for item in spec.get("componentTree", []) if isinstance(item, dict)]
+ failures: list[str] = []
+ warnings: list[str] = []
+ component_ids = {str(item.get("id")) for item in components if item.get("id")}
+ referenced: set[str] = set()
+ for component in components:
+ component_id = str(component.get("id") or component.get("name") or "(unnamed)")
+ material_id = component.get("material")
+ if material_id:
+ referenced.add(str(material_id))
+ if str(material_id) not in materials:
+ failures.append(f"component {component_id!r} references missing material {material_id!r}")
+ if component.get("materialRegions") and not material_id:
+ failures.append(f"component {component_id!r} has materialRegions but no material binding")
+ for material_id, material in materials.items():
+ reference = material.get("materialReference")
+ required_maps = reference.get("requiredMaps", []) if isinstance(reference, dict) else []
+ pbr = material.get("referencePbr") if isinstance(material.get("referencePbr"), dict) else {}
+ maps = pbr.get("maps", {}) if isinstance(pbr.get("maps"), dict) else {}
+ projection = material.get("textureProjection")
+ has_uv_contract = isinstance(projection, dict) or any(
+ isinstance(component.get("uv"), dict) or isinstance(component.get("uvContract"), dict)
+ for component in components if component.get("material") == material_id
+ )
+ if required_maps and not has_uv_contract:
+ failures.append(f"material {material_id!r} requires maps but no UV/textureProjection contract exists")
+ missing_maps = [channel for channel in required_maps if channel.endswith("Map") and channel not in maps and channel not in {"map", "normalMap"}]
+ if missing_maps and pbr:
+ warnings.append(f"material {material_id!r} profile requires map slots not present in extracted PBR maps: {missing_maps}")
+ unbound = sorted(set(materials) - referenced)
+ if unbound:
+ warnings.append(f"materials not referenced by componentTree: {unbound}")
+ rig = spec.get("rig")
+ rigged_components = {
+ str(item.get("component")) for item in (rig.get("bones", []) if isinstance(rig, dict) else [])
+ if isinstance(item, dict) and item.get("component")
+ }
+ for component_id in sorted(rigged_components & component_ids):
+ component = next(item for item in components if str(item.get("id")) == component_id)
+ if not component.get("material"):
+ failures.append(f"rigged component {component_id!r} lost its material binding")
+ lod = spec.get("lodPlan")
+ if lod is not None:
+ if not isinstance(lod, list):
+ failures.append("lodPlan must remain an array")
+ else:
+ for index, level in enumerate(lod):
+ if isinstance(level, dict):
+ ids = level.get("materialIds", level.get("materials", []))
+ if isinstance(ids, list):
+ missing = sorted({str(value) for value in ids} - set(materials))
+ if missing:
+ failures.append(f"lodPlan[{index}] references missing material IDs: {missing}")
+ collision = spec.get("collisionGroups", spec.get("colliders"))
+ if collision is not None and not isinstance(collision, (list, dict)):
+ failures.append("collisionGroups/colliders must remain an object or array")
+ return {
+ "schemaVersion": 1,
+ "passed": not failures,
+ "failures": failures,
+ "warnings": warnings,
+ "checked": {
+ "materialCount": len(materials),
+ "componentCount": len(components),
+ "referencedMaterialCount": len(referenced),
+ "riggedComponentCount": len(rigged_components),
+ "lodPresent": lod is not None,
+ "collisionPresent": collision is not None,
+ },
+ "invariant": "material IDs and UV/map contracts survive geometry, skinning, collision and LOD changes",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("--out", type=Path)
+ args = parser.parse_args(argv)
+ try:
+ result = check_compatibility(json.loads(args.spec.read_text(encoding="utf-8")))
+ if args.out:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps(result, indent=2))
+ return 0 if result["passed"] else 2
+ except Exception as exc:
+ print(f"error: {exc}")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/materials/reference.py b/forge/materials/reference.py
new file mode 100644
index 0000000..3ead65c
--- /dev/null
+++ b/forge/materials/reference.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Load and resolve the canonical Three.js material reference library.
+
+This is the runtime bridge for ``docs/materials/material-reference.json``. The
+registry is intentionally data-driven: profile numbers seed a candidate, while
+image evidence and user metadata decide whether that candidate may proceed.
+The module is stdlib-only so it can be used by every forge stage and in CI.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_REFERENCE = ROOT / "docs" / "materials" / "material-reference.json"
+
+
+class MaterialReferenceError(ValueError):
+ """Raised when the canonical registry cannot safely be consumed."""
+
+
+def _token(value: Any) -> str:
+ return re.sub(r"[^a-z0-9]+", " ", str(value or "").strip().lower()).strip()
+
+
+def _tokens(value: Any) -> set[str]:
+ token = _token(value)
+ return {token, token.replace(" ", "-")} if token else set()
+
+
+def validate_reference(payload: dict[str, Any]) -> list[str]:
+ """Return structural errors; an empty list means the registry is usable."""
+ errors: list[str] = []
+ if not isinstance(payload, dict):
+ return ["reference must be a JSON object"]
+ if payload.get("schemaVersion") != 1:
+ errors.append("schemaVersion must be 1")
+ renderer = payload.get("renderer")
+ if not isinstance(renderer, dict) or renderer.get("engine") != "three.js":
+ errors.append("renderer.engine must be three.js")
+ sources = payload.get("sources")
+ if not isinstance(sources, list) or not sources:
+ errors.append("sources must be a non-empty array")
+ source_ids: set[str] = set()
+ else:
+ source_ids = set()
+ for index, source in enumerate(sources):
+ if not isinstance(source, dict):
+ errors.append(f"sources[{index}] must be an object")
+ continue
+ source_id = source.get("id")
+ if not isinstance(source_id, str) or not source_id:
+ errors.append(f"sources[{index}].id is required")
+ elif source_id in source_ids:
+ errors.append(f"duplicate source id {source_id!r}")
+ source_ids.add(str(source_id))
+ if not isinstance(source.get("url"), str) or not source["url"].startswith("https://"):
+ errors.append(f"source {source_id!r} must have an https URL")
+ materials = payload.get("materials")
+ if not isinstance(materials, list) or not materials:
+ errors.append("materials must be a non-empty array")
+ materials = []
+ ids: set[str] = set()
+ legal = payload.get("legalRanges", {})
+ if not isinstance(legal, dict):
+ errors.append("legalRanges must be an object")
+ legal = {}
+ for index, material in enumerate(materials):
+ if not isinstance(material, dict):
+ errors.append(f"materials[{index}] must be an object")
+ continue
+ material_id = material.get("id")
+ if not isinstance(material_id, str) or not material_id:
+ errors.append(f"materials[{index}].id is required")
+ continue
+ if material_id in ids:
+ errors.append(f"duplicate material id {material_id!r}")
+ ids.add(material_id)
+ if material.get("recipeBasis") != "inferred-starting-prior":
+ errors.append(f"material {material_id!r} must label its recipeBasis as a prior")
+ for source_ref in material.get("sourceRefs", []):
+ if source_ref not in source_ids:
+ errors.append(f"material {material_id!r} has unresolved sourceRef {source_ref!r}")
+ render_prior = material.get("renderPrior", {})
+ if not isinstance(render_prior, dict):
+ errors.append(f"material {material_id!r}.renderPrior must be an object")
+ continue
+ for property_name, prior in render_prior.items():
+ if property_name not in legal:
+ errors.append(f"material {material_id!r} uses undocumented property {property_name!r}")
+ continue
+ if not isinstance(prior, dict) or not isinstance(prior.get("default"), (int, float)):
+ errors.append(f"material {material_id!r}.{property_name} prior is malformed")
+ continue
+ bounds = prior.get("range")
+ allowed = legal[property_name]
+ if not isinstance(bounds, list) or len(bounds) != 2 or not isinstance(allowed, list) or len(allowed) != 2:
+ errors.append(f"material {material_id!r}.{property_name} prior range is malformed")
+ continue
+ if bounds[0] > prior["default"] or prior["default"] > bounds[1] or bounds[0] < allowed[0] or bounds[1] > allowed[1]:
+ errors.append(f"material {material_id!r}.{property_name} prior escapes legal range")
+ return errors
+
+
+def load_reference(path: Path | str = DEFAULT_REFERENCE) -> dict[str, Any]:
+ reference_path = Path(path)
+ try:
+ payload = json.loads(reference_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise MaterialReferenceError(f"cannot load material reference {reference_path}: {exc}") from exc
+ errors = validate_reference(payload)
+ if errors:
+ raise MaterialReferenceError("invalid material reference: " + "; ".join(errors))
+ return payload
+
+
+def _material_index(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ return [item for item in payload.get("materials", []) if isinstance(item, dict)]
+
+
+def _candidate(profile: dict[str, Any], method: str, confidence: float, reason: str) -> dict[str, Any]:
+ return {
+ "materialId": profile.get("id"),
+ "profile": profile,
+ "method": method,
+ "confidence": max(0.0, min(1.0, float(confidence))),
+ "reason": reason,
+ }
+
+
+def resolve_material(hypothesis: dict[str, Any], payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Resolve one hypothesis while retaining alternatives and uncertainty.
+
+ Explicit user/metadata identity wins. Alias and family matching never
+ silently chooses between materially different candidates.
+ """
+ registry = payload or load_reference()
+ materials = _material_index(registry)
+ by_id = {str(item.get("id")): item for item in materials}
+ explicit = hypothesis.get("materialId")
+ if isinstance(explicit, str) and explicit in by_id:
+ result = _candidate(by_id[explicit], "explicit-material-id", 1.0, "authoritative material id")
+ result["status"] = "proceed"
+ result["alternatives"] = []
+ return result
+
+ family = _token(hypothesis.get("family"))
+ subtype = _token(hypothesis.get("subtype"))
+ finish = _token(hypothesis.get("finish"))
+ exact = [
+ item for item in materials
+ if _token(item.get("family")) == family
+ and (not subtype or _token(item.get("subtype")) == subtype)
+ and (not finish or _token(item.get("finish")) == finish)
+ ]
+ if len(exact) == 1:
+ result = _candidate(exact[0], "family-subtype-finish", float(hypothesis.get("confidence", 0.7)), "exact semantic match")
+ result["status"] = "proceed" if result["confidence"] >= 0.7 else "probe"
+ result["alternatives"] = []
+ return result
+
+ aliases = set()
+ for field in ("aliases", "alternatives"):
+ value = hypothesis.get(field, [])
+ if isinstance(value, list):
+ for item in value:
+ aliases.update(_tokens(item.get("materialId") if isinstance(item, dict) else item))
+ alias_matches = [item for item in materials if aliases & set().union(*(_tokens(alias) for alias in item.get("aliases", [])))]
+ if len(alias_matches) == 1:
+ result = _candidate(alias_matches[0], "alias", float(hypothesis.get("confidence", 0.5)), "unique alias match")
+ result["status"] = "proceed" if result["confidence"] >= 0.7 else "probe"
+ result["alternatives"] = []
+ return result
+
+ family_matches = [item for item in materials if family and _token(item.get("family")) == family]
+ family_matches.sort(key=lambda item: str(item.get("id")))
+ alternatives = [
+ _candidate(item, "family-fallback", max(0.1, float(hypothesis.get("confidence", 0.3)) * 0.65), "family fallback")
+ for item in family_matches
+ ]
+ if len(family_matches) == 1:
+ result = alternatives[0]
+ result["status"] = "probe"
+ result["alternatives"] = []
+ return result
+ return {
+ "materialId": None,
+ "profile": None,
+ "method": "unresolved",
+ "confidence": 0.0,
+ "reason": "ambiguous or unknown material; request more evidence",
+ "status": "request-input" if family_matches else "unknown",
+ "alternatives": alternatives,
+ }
+
+
+def _prior_values(profile: dict[str, Any]) -> dict[str, float]:
+ return {
+ name: float(value["default"])
+ for name, value in profile.get("renderPrior", {}).items()
+ if isinstance(value, dict) and isinstance(value.get("default"), (int, float))
+ }
+
+
+def build_assignment(
+ hypothesis: dict[str, Any],
+ evidence: dict[str, Any] | None = None,
+ payload: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Return the spec-ready assignment without mutating the input hypothesis."""
+ result = resolve_material(hypothesis, payload)
+ profile = result.get("profile")
+ assignment: dict[str, Any] = {
+ "materialId": result.get("materialId"),
+ "status": result["status"],
+ "source": hypothesis.get("source", "vision"),
+ "confidence": result["confidence"],
+ "method": result["method"],
+ "alternatives": [item["materialId"] for item in result.get("alternatives", [])],
+ "evidence": copy.deepcopy(evidence or {}),
+ }
+ if profile:
+ assignment.update({
+ "profileId": profile["id"],
+ "family": profile.get("family"),
+ "subtype": profile.get("subtype"),
+ "finish": profile.get("finish"),
+ "renderPrior": _prior_values(profile),
+ "requiredMaps": list(profile.get("requiredMaps", [])),
+ "optionalMaps": list(profile.get("optionalMaps", [])),
+ "validationViews": list(profile.get("validationViews", [])),
+ "sourceRefs": list(profile.get("sourceRefs", [])),
+ "visualCues": list(profile.get("visualCues", [])),
+ })
+ return assignment
diff --git a/forge/stage1_intake/analyze_texture.py b/forge/stage1_intake/analyze_texture.py
index 2e04fbc..5d2e9bf 100644
--- a/forge/stage1_intake/analyze_texture.py
+++ b/forge/stage1_intake/analyze_texture.py
@@ -221,17 +221,22 @@ def main(argv=None) -> int:
ap.add_argument("--material-id", help="material id to apply the recipe to (with --spec)")
ap.add_argument("--in-place", action="store_true", help="write the spec back")
args = ap.parse_args(argv)
+ has_patch_target = args.spec is not None and args.material_id is not None
+ if (args.spec is None) != (args.material_id is None):
+ ap.error("--spec and --material-id must be used together")
+ if args.in_place and not has_patch_target:
+ ap.error("--in-place requires --spec and --material-id")
result = analyze(args.image)
- if args.spec and args.material_id:
- spec = json.loads(args.spec.read_text())
+ if has_patch_target:
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
mats = [m for m in spec.get("materials", []) if m.get("id") == args.material_id]
if not mats:
print(f"material {args.material_id!r} not found in spec", file=sys.stderr)
return 2
apply_to_material(mats[0], result)
if args.in_place:
- args.spec.write_text(json.dumps(spec, indent=2))
+ args.spec.write_text(json.dumps(spec, indent=2), encoding="utf-8")
print(f"applied {result['finishClass']} recipe to material {args.material_id!r} in {args.spec.name}")
else:
print(json.dumps(mats[0], indent=2))
diff --git a/forge/stage1_intake/build_detail_inventory.py b/forge/stage1_intake/build_detail_inventory.py
index b2cb01b..6b946b8 100644
--- a/forge/stage1_intake/build_detail_inventory.py
+++ b/forge/stage1_intake/build_detail_inventory.py
@@ -21,6 +21,9 @@ import tempfile
import zlib
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -31,6 +34,10 @@ TARGET_MIN_DETAILS = {
"ultra-complex": 16,
}
+# These thirds are a DEFAULT, not a limit -- `component-zones` mode with --components takes any named
+# normalized regions, so an arbitrary per-feature ROI is already expressible. What is genuinely absent
+# is automatic detection and scoring of details: nothing here finds a tear, only describes where to
+# look. See grimoire/review/divine_eye_microscope.md for the feature-descriptor schema.
DEFAULT_COMPONENT_ZONES = [
("upper", 0.0, 0.0, 1.0, 1.0 / 3),
("middle", 0.0, 1.0 / 3, 1.0, 1.0 / 3),
@@ -144,6 +151,12 @@ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
try:
return read_png(path)
except Exception as direct_error:
+ jpeg_bytes = path.read_bytes()
+ if is_jpeg(jpeg_bytes):
+ try:
+ return decode_jpeg(jpeg_bytes)[:3]
+ except UnsupportedJpeg:
+ pass
sips = shutil.which("sips")
if not sips:
raise ValueError(f"could not decode {path.name} as PNG and sips is unavailable: {direct_error}") from direct_error
diff --git a/forge/stage1_intake/camera_fitting_math.py b/forge/stage1_intake/camera_fitting_math.py
new file mode 100644
index 0000000..e1c29d5
--- /dev/null
+++ b/forge/stage1_intake/camera_fitting_math.py
@@ -0,0 +1,133 @@
+"""Projection, residual, and degeneracy math for camera fitting."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+
+from forge.stage1_intake.camera_fitting_types import (
+ MAXIMUM_FOV_DEGREES,
+ MINIMUM_CAMERA_DEPTH,
+ MINIMUM_FOV_DEGREES,
+ CameraParameters,
+ NormalizedCorrespondence,
+ Point2,
+ Point3,
+)
+
+
+def project_landmark(point: Point3, camera: CameraParameters) -> Point2 | None:
+ """Project a world point using the established pitch, yaw, then roll convention."""
+ if not MINIMUM_FOV_DEGREES <= camera.fov_degrees <= MAXIMUM_FOV_DEGREES:
+ return None
+ tangent = math.tan(math.radians(camera.fov_degrees) / 2.0)
+ if not math.isfinite(tangent) or abs(tangent) <= MINIMUM_CAMERA_DEPTH:
+ return None
+ focal_length = (camera.image_height / 2.0) / tangent
+ translated_x = point[0] - camera.position[0]
+ translated_y = point[1] - camera.position[1]
+ translated_z = camera.position[2] - point[2]
+
+ pitch_radians = math.radians(camera.pitch_degrees)
+ pitch_cosine = math.cos(pitch_radians)
+ pitch_sine = math.sin(pitch_radians)
+ pitched_x = translated_x
+ pitched_y = translated_y * pitch_cosine - translated_z * pitch_sine
+ pitched_z = translated_y * pitch_sine + translated_z * pitch_cosine
+
+ yaw_radians = math.radians(camera.yaw_degrees)
+ yaw_cosine = math.cos(yaw_radians)
+ yaw_sine = math.sin(yaw_radians)
+ yawed_x = pitched_x * yaw_cosine + pitched_z * yaw_sine
+ yawed_y = pitched_y
+ yawed_z = -pitched_x * yaw_sine + pitched_z * yaw_cosine
+
+ roll_radians = math.radians(camera.roll_degrees)
+ roll_cosine = math.cos(roll_radians)
+ roll_sine = math.sin(roll_radians)
+ rolled_x = yawed_x * roll_cosine - yawed_y * roll_sine
+ rolled_y = yawed_x * roll_sine + yawed_y * roll_cosine
+ if yawed_z <= MINIMUM_CAMERA_DEPTH:
+ return None
+ projected_x = (camera.image_width / 2.0) + (focal_length * rolled_x / yawed_z)
+ projected_y = (camera.image_height / 2.0) - (focal_length * rolled_y / yawed_z)
+ if not math.isfinite(projected_x) or not math.isfinite(projected_y):
+ return None
+ return projected_x, projected_y
+
+
+def residual_components(
+ correspondences: Sequence[NormalizedCorrespondence], camera: CameraParameters
+) -> tuple[float, ...] | None:
+ components: list[float] = []
+ for correspondence in correspondences:
+ projected = project_landmark(correspondence.world, camera)
+ if projected is None:
+ return None
+ delta_x = projected[0] - correspondence.observed[0]
+ delta_y = projected[1] - correspondence.observed[1]
+ if not math.isfinite(delta_x) or not math.isfinite(delta_y):
+ return None
+ components.extend((delta_x, delta_y))
+ return tuple(components)
+
+
+def rms_reprojection_error(components: tuple[float, ...]) -> float:
+ return math.sqrt(sum(component * component for component in components) / (len(components) // 2))
+
+
+def has_degenerate_world_geometry(correspondences: Sequence[NormalizedCorrespondence]) -> bool:
+ coordinate_scale = 1.0
+ for correspondence in correspondences:
+ coordinate_scale = max(coordinate_scale, *(abs(value) for value in correspondence.world))
+ count = len(correspondences)
+ centroid = (
+ sum(correspondence.world[0] for correspondence in correspondences) / count,
+ sum(correspondence.world[1] for correspondence in correspondences) / count,
+ sum(correspondence.world[2] for correspondence in correspondences) / count,
+ )
+ span_square = 0.0
+ first_index = 0
+ second_index = 0
+ for index, first in enumerate(correspondences):
+ centered = (
+ first.world[0] - centroid[0],
+ first.world[1] - centroid[1],
+ first.world[2] - centroid[2],
+ )
+ span_square = max(span_square, sum(component * component for component in centered))
+ for candidate_index in range(index + 1, count):
+ second = correspondences[candidate_index]
+ delta_x = second.world[0] - first.world[0]
+ delta_y = second.world[1] - first.world[1]
+ delta_z = second.world[2] - first.world[2]
+ separation_square = delta_x * delta_x + delta_y * delta_y + delta_z * delta_z
+ if separation_square > span_square:
+ span_square = separation_square
+ first_index = index
+ second_index = candidate_index
+ minimum_span = coordinate_scale * 1e-9
+ if span_square <= minimum_span * minimum_span:
+ return True
+ first_point = correspondences[first_index].world
+ second_point = correspondences[second_index].world
+ axis = (
+ second_point[0] - first_point[0],
+ second_point[1] - first_point[1],
+ second_point[2] - first_point[2],
+ )
+ axis_square = sum(component * component for component in axis)
+ maximum_perpendicular_square = 0.0
+ for correspondence in correspondences:
+ offset = (
+ correspondence.world[0] - first_point[0],
+ correspondence.world[1] - first_point[1],
+ correspondence.world[2] - first_point[2],
+ )
+ projection = sum(offset[index] * axis[index] for index in range(3)) / axis_square
+ perpendicular = tuple(offset[index] - projection * axis[index] for index in range(3))
+ maximum_perpendicular_square = max(
+ maximum_perpendicular_square,
+ sum(component * component for component in perpendicular),
+ )
+ return maximum_perpendicular_square <= span_square * 1e-12
diff --git a/forge/stage1_intake/camera_fitting_solver.py b/forge/stage1_intake/camera_fitting_solver.py
new file mode 100644
index 0000000..380b335
--- /dev/null
+++ b/forge/stage1_intake/camera_fitting_solver.py
@@ -0,0 +1,197 @@
+"""Deterministic seven-parameter damped least-squares camera solver."""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+from forge.stage1_intake.camera_fitting_math import (
+ residual_components,
+ rms_reprojection_error,
+)
+from forge.stage1_intake.camera_fitting_types import (
+ CameraParameters,
+ FitState,
+ NormalizedCorrespondence,
+ ParameterVector,
+ SolverLimits,
+)
+
+
+def fit_parameters(
+ correspondences: Sequence[NormalizedCorrespondence],
+ initial_camera: CameraParameters,
+ limits: SolverLimits,
+) -> FitState:
+ """Fit FOV, Euler angles, and position with fixed finite-difference steps."""
+ initial_residuals = residual_components(correspondences, initial_camera)
+ if initial_residuals is None:
+ raise RuntimeError("validated initial camera must be projectable before solver entry")
+ camera = initial_camera
+ residuals = initial_residuals
+ rms_error = rms_reprojection_error(residuals)
+ damping = limits.initial_damping
+ accepted_steps = 0
+ rejected_steps = 0
+ for iteration in range(1, limits.maximum_iterations + 1):
+ jacobian = _central_difference_jacobian(correspondences, camera, limits.finite_difference_steps)
+ if jacobian is None:
+ return FitState(camera, rms_error, iteration, accepted_steps, rejected_steps, damping, "stalled")
+ accepted = False
+ for _ in range(limits.maximum_damping_retries):
+ hessian, gradient = _normal_equations(jacobian, residuals, damping, limits.finite_difference_steps)
+ delta = _solve_linear_system(hessian, gradient)
+ if delta is None:
+ damping = min(damping * 10.0, limits.maximum_damping)
+ rejected_steps += 1
+ continue
+ candidate = _parameters_from_vector(
+ _vector_with_addition(_parameter_vector(camera), delta),
+ camera.image_width,
+ camera.image_height,
+ )
+ candidate_residuals = residual_components(correspondences, candidate)
+ if candidate_residuals is None:
+ damping = min(damping * 10.0, limits.maximum_damping)
+ rejected_steps += 1
+ continue
+ candidate_error = rms_reprojection_error(candidate_residuals)
+ if candidate_error < rms_error:
+ camera = candidate
+ residuals = candidate_residuals
+ rms_error = candidate_error
+ damping = max(damping / 3.0, 1e-12)
+ accepted_steps += 1
+ accepted = True
+ if rms_error <= limits.converged_rms_pixels or _scaled_step_is_small(delta):
+ return FitState(camera, rms_error, iteration, accepted_steps, rejected_steps, damping, "converged")
+ break
+ damping = min(damping * 10.0, limits.maximum_damping)
+ rejected_steps += 1
+ if not accepted:
+ return FitState(camera, rms_error, iteration, accepted_steps, rejected_steps, damping, "stalled")
+ status = "converged" if rms_error <= limits.converged_rms_pixels else "max-iterations"
+ return FitState(camera, rms_error, limits.maximum_iterations, accepted_steps, rejected_steps, damping, status)
+
+
+def _parameter_vector(camera: CameraParameters) -> ParameterVector:
+ return (
+ camera.fov_degrees,
+ camera.yaw_degrees,
+ camera.pitch_degrees,
+ camera.roll_degrees,
+ camera.position[0],
+ camera.position[1],
+ camera.position[2],
+ )
+
+
+def _parameters_from_vector(vector: ParameterVector, image_width: int, image_height: int) -> CameraParameters:
+ return CameraParameters(
+ image_width=image_width,
+ image_height=image_height,
+ fov_degrees=vector[0],
+ yaw_degrees=vector[1],
+ pitch_degrees=vector[2],
+ roll_degrees=vector[3],
+ position=(vector[4], vector[5], vector[6]),
+ )
+
+
+def _vector_with_delta(vector: ParameterVector, index: int, delta: float) -> ParameterVector:
+ values = list(vector)
+ values[index] += delta
+ return values[0], values[1], values[2], values[3], values[4], values[5], values[6]
+
+
+def _vector_with_addition(vector: ParameterVector, delta: ParameterVector) -> ParameterVector:
+ return (
+ vector[0] + delta[0],
+ vector[1] + delta[1],
+ vector[2] + delta[2],
+ vector[3] + delta[3],
+ vector[4] + delta[4],
+ vector[5] + delta[5],
+ vector[6] + delta[6],
+ )
+
+
+def _central_difference_jacobian(
+ correspondences: Sequence[NormalizedCorrespondence],
+ camera: CameraParameters,
+ steps: ParameterVector,
+) -> list[list[float]] | None:
+ vector = _parameter_vector(camera)
+ columns: list[tuple[float, ...]] = []
+ for parameter_index, step in enumerate(steps):
+ positive_camera = _parameters_from_vector(
+ _vector_with_delta(vector, parameter_index, step), camera.image_width, camera.image_height
+ )
+ negative_camera = _parameters_from_vector(
+ _vector_with_delta(vector, parameter_index, -step), camera.image_width, camera.image_height
+ )
+ positive_residuals = residual_components(correspondences, positive_camera)
+ negative_residuals = residual_components(correspondences, negative_camera)
+ if positive_residuals is None or negative_residuals is None:
+ return None
+ columns.append(
+ tuple(
+ (positive - negative) / (2.0 * step)
+ for positive, negative in zip(positive_residuals, negative_residuals, strict=True)
+ )
+ )
+ return [[column[row] for column in columns] for row in range(len(columns[0]))]
+
+
+def _normal_equations(
+ jacobian: list[list[float]],
+ residuals: tuple[float, ...],
+ damping: float,
+ steps: ParameterVector,
+) -> tuple[list[list[float]], list[float]]:
+ dimension = len(steps)
+ hessian = [[0.0 for _ in range(dimension)] for _ in range(dimension)]
+ gradient = [0.0 for _ in range(dimension)]
+ for row, residual in zip(jacobian, residuals, strict=True):
+ for column, value in enumerate(row):
+ gradient[column] += value * residual
+ for secondary_column in range(column, dimension):
+ hessian[column][secondary_column] += value * row[secondary_column]
+ for column in range(dimension):
+ for secondary_column in range(column):
+ hessian[column][secondary_column] = hessian[secondary_column][column]
+ hessian[column][column] += damping * max(hessian[column][column], 1.0)
+ return hessian, [-value for value in gradient]
+
+
+def _solve_linear_system(matrix: list[list[float]], right_hand_side: list[float]) -> ParameterVector | None:
+ dimension = len(right_hand_side)
+ augmented = [row.copy() + [right_hand_side[index]] for index, row in enumerate(matrix)]
+ largest_entry = max(abs(value) for row in matrix for value in row)
+ pivot_tolerance = max(1.0, largest_entry) * 1e-12
+ for column in range(dimension):
+ pivot_row = column
+ for candidate_row in range(column + 1, dimension):
+ if abs(augmented[candidate_row][column]) > abs(augmented[pivot_row][column]):
+ pivot_row = candidate_row
+ pivot = augmented[pivot_row][column]
+ if abs(pivot) <= pivot_tolerance:
+ return None
+ augmented[column], augmented[pivot_row] = augmented[pivot_row], augmented[column]
+ pivot = augmented[column][column]
+ for row in range(column + 1, dimension):
+ factor = augmented[row][column] / pivot
+ augmented[row][column] = 0.0
+ for secondary_column in range(column + 1, dimension + 1):
+ augmented[row][secondary_column] -= factor * augmented[column][secondary_column]
+ solution = [0.0 for _ in range(dimension)]
+ for row in range(dimension - 1, -1, -1):
+ remaining = sum(augmented[row][column] * solution[column] for column in range(row + 1, dimension))
+ solution[row] = (augmented[row][dimension] - remaining) / augmented[row][row]
+ return (
+ solution[0], solution[1], solution[2], solution[3], solution[4], solution[5], solution[6]
+ )
+
+
+def _scaled_step_is_small(delta: ParameterVector) -> bool:
+ scale = (30.0, 10.0, 10.0, 10.0, 1.0, 1.0, 1.0)
+ return max(abs(value) / scale[index] for index, value in enumerate(delta)) <= 1e-8
diff --git a/forge/stage1_intake/camera_fitting_types.py b/forge/stage1_intake/camera_fitting_types.py
new file mode 100644
index 0000000..349a7be
--- /dev/null
+++ b/forge/stage1_intake/camera_fitting_types.py
@@ -0,0 +1,291 @@
+"""Typed camera-fitting contracts and public validation errors."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import Final, Literal, Protocol, TypeAlias, TypedDict
+
+Point2: TypeAlias = tuple[float, float]
+Point3: TypeAlias = tuple[float, float, float]
+ParameterVector: TypeAlias = tuple[float, float, float, float, float, float, float]
+NumericScalar: TypeAlias = int | float
+SolverStatus: TypeAlias = Literal["converged", "stalled", "max-iterations"]
+
+MINIMUM_CORRESPONDENCES: Final = 6
+MINIMUM_FOV_DEGREES: Final = 10.0
+MAXIMUM_FOV_DEGREES: Final = 120.0
+MINIMUM_CAMERA_DEPTH: Final = 1e-8
+DEFAULT_MAXIMUM_ITERATIONS: Final = 80
+DEFAULT_MAXIMUM_DAMPING_RETRIES: Final = 12
+INITIAL_DAMPING: Final = 1e-3
+MAXIMUM_DAMPING: Final = 1e12
+CONVERGED_RMS_PIXELS: Final = 1e-6
+FINITE_DIFFERENCE_STEPS: Final[ParameterVector] = (1e-3, 1e-4, 1e-4, 1e-4, 1e-5, 1e-5, 1e-5)
+
+
+class CameraInitialization(Protocol):
+ @property
+ def image_width(self) -> int: ...
+
+ @property
+ def image_height(self) -> int: ...
+
+ @property
+ def fov_degrees(self) -> float: ...
+
+ @property
+ def yaw_degrees(self) -> float: ...
+
+ @property
+ def pitch_degrees(self) -> float: ...
+
+ @property
+ def roll_degrees(self) -> float: ...
+
+ @property
+ def position(self) -> Point3: ...
+
+
+class LandmarkCorrespondence(Protocol):
+ @property
+ def name(self) -> str: ...
+
+ @property
+ def world(self) -> Point3: ...
+
+ @property
+ def observed(self) -> Point2: ...
+
+
+@dataclass(frozen=True, slots=True)
+class InsufficientCorrespondencesError(Exception):
+ required: int
+ actual: int
+
+ def __str__(self) -> str:
+ return f"camera fit requires at least {self.required} correspondences; received {self.actual}"
+
+
+@dataclass(frozen=True, slots=True)
+class DegenerateCorrespondencesError(Exception):
+ correspondence_count: int
+
+ def __str__(self) -> str:
+ return f"camera fit requires non-collinear 3D landmarks; received {self.correspondence_count} degenerate correspondences"
+
+
+@dataclass(frozen=True, slots=True)
+class InvalidInitialCameraError(Exception):
+ correspondence_name: str
+
+ def __str__(self) -> str:
+ return f"initial camera cannot project correspondence {self.correspondence_name!r}"
+
+
+@dataclass(frozen=True, slots=True)
+class InvalidCameraDimensionsError(Exception):
+ image_width: int
+ image_height: int
+
+ def __str__(self) -> str:
+ return f"camera image dimensions must be positive finite integers; received {self.image_width}x{self.image_height}"
+
+
+@dataclass(frozen=True, slots=True)
+class NonFiniteCameraInputError(Exception):
+ field: str
+
+ def __str__(self) -> str:
+ return f"camera input field {self.field!r} must be a finite non-boolean number"
+
+
+@dataclass(frozen=True, slots=True)
+class CameraParameters:
+ image_width: int
+ image_height: int
+ fov_degrees: float
+ yaw_degrees: float
+ pitch_degrees: float
+ roll_degrees: float
+ position: Point3
+
+
+@dataclass(frozen=True, slots=True)
+class NormalizedCorrespondence:
+ name: str
+ world: Point3
+ observed: Point2
+
+
+@dataclass(frozen=True, slots=True)
+class NormalizedFitInput:
+ correspondences: tuple[NormalizedCorrespondence, ...]
+ initial_camera: CameraParameters
+
+
+@dataclass(frozen=True, slots=True)
+class FitState:
+ parameters: CameraParameters
+ rms_error: float
+ iterations: int
+ accepted_steps: int
+ rejected_steps: int
+ damping: float
+ status: SolverStatus
+
+
+@dataclass(frozen=True, slots=True)
+class SolverLimits:
+ maximum_iterations: int
+ maximum_damping_retries: int
+ initial_damping: float
+ maximum_damping: float
+ converged_rms_pixels: float
+ finite_difference_steps: ParameterVector
+
+
+class ScalarField(TypedDict):
+ value: float
+ source: str
+ agentFill: bool
+
+
+class FovField(ScalarField):
+ rationale: str
+
+
+class OrientationDescriptor(TypedDict):
+ yawDegrees: ScalarField
+ pitchDegrees: ScalarField
+ rollDegrees: ScalarField
+ note: str
+
+
+class PositionDescriptor(TypedDict):
+ hint: list[float]
+ distance: ScalarField
+ note: str
+
+
+class AspectDescriptor(TypedDict):
+ value: float
+ source: str
+ agentFill: bool
+
+
+class FitCameraParameters(TypedDict):
+ fovDegrees: float
+ yawDegrees: float
+ pitchDegrees: float
+ rollDegrees: float
+ position: list[float]
+
+
+class ResidualDiagnostic(TypedDict):
+ name: str
+ errorPixels: float
+
+
+class ConvergenceDiagnostic(TypedDict):
+ status: SolverStatus
+ iterations: int
+ acceptedSteps: int
+ rejectedSteps: int
+ damping: float
+
+
+class FitDiagnostic(TypedDict):
+ method: str
+ cameraParameters: FitCameraParameters
+ initialReprojectionError: float
+ finalReprojectionError: float
+ residuals: list[ResidualDiagnostic]
+ convergence: ConvergenceDiagnostic
+
+
+class CameraFitDescriptor(TypedDict):
+ version: str
+ sourceImage: str
+ solver: str
+ method: str
+ imageWidth: int
+ imageHeight: int
+ fovDegrees: FovField
+ aspect: AspectDescriptor
+ orientation: OrientationDescriptor
+ position: PositionDescriptor
+ confidence: float
+ limitations: list[str]
+ note: str
+ fit: FitDiagnostic
+
+
+def normalize_fit_input(
+ correspondences: Sequence[LandmarkCorrespondence],
+ initial_camera: CameraInitialization,
+) -> NormalizedFitInput:
+ """Parse the public fitting inputs before any geometry arithmetic occurs."""
+ correspondence_items = tuple(correspondences)
+ if len(correspondence_items) < MINIMUM_CORRESPONDENCES:
+ raise InsufficientCorrespondencesError(required=MINIMUM_CORRESPONDENCES, actual=len(correspondence_items))
+ normalized_camera = _normalize_initial_camera(initial_camera)
+ normalized_correspondences = tuple(
+ _normalize_correspondence(correspondence, index)
+ for index, correspondence in enumerate(correspondence_items)
+ )
+ return NormalizedFitInput(normalized_correspondences, normalized_camera)
+
+
+def _normalize_initial_camera(camera: CameraInitialization) -> CameraParameters:
+ if not _is_positive_dimension(camera.image_width) or not _is_positive_dimension(camera.image_height):
+ raise InvalidCameraDimensionsError(image_width=camera.image_width, image_height=camera.image_height)
+ return CameraParameters(
+ image_width=camera.image_width,
+ image_height=camera.image_height,
+ fov_degrees=_finite_scalar(camera.fov_degrees, "initial_camera.fov_degrees"),
+ yaw_degrees=_finite_scalar(camera.yaw_degrees, "initial_camera.yaw_degrees"),
+ pitch_degrees=_finite_scalar(camera.pitch_degrees, "initial_camera.pitch_degrees"),
+ roll_degrees=_finite_scalar(camera.roll_degrees, "initial_camera.roll_degrees"),
+ position=_point3(camera.position, "initial_camera.position"),
+ )
+
+
+def _normalize_correspondence(correspondence: LandmarkCorrespondence, index: int) -> NormalizedCorrespondence:
+ prefix = f"correspondences[{index}]"
+ return NormalizedCorrespondence(
+ name=correspondence.name,
+ world=_point3(correspondence.world, f"{prefix}.world"),
+ observed=_point2(correspondence.observed, f"{prefix}.observed"),
+ )
+
+
+def _is_positive_dimension(value: int) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
+
+
+def _finite_scalar(value: NumericScalar, field: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
+ raise NonFiniteCameraInputError(field=field)
+ return float(value)
+
+
+def _point2(values: Sequence[NumericScalar], field: str) -> Point2:
+ if not _is_numeric_sequence(values, 2):
+ raise NonFiniteCameraInputError(field=field)
+ return _finite_scalar(values[0], f"{field}[0]"), _finite_scalar(values[1], f"{field}[1]")
+
+
+def _point3(values: Sequence[NumericScalar], field: str) -> Point3:
+ if not _is_numeric_sequence(values, 3):
+ raise NonFiniteCameraInputError(field=field)
+ return (
+ _finite_scalar(values[0], f"{field}[0]"),
+ _finite_scalar(values[1], f"{field}[1]"),
+ _finite_scalar(values[2], f"{field}[2]"),
+ )
+
+
+def _is_numeric_sequence(values: Sequence[NumericScalar], length: int) -> bool:
+ return isinstance(values, Sequence) and not isinstance(values, str | bytes) and len(values) == length
diff --git a/forge/stage1_intake/camera_image_helpers.py b/forge/stage1_intake/camera_image_helpers.py
new file mode 100644
index 0000000..7f1538e
--- /dev/null
+++ b/forge/stage1_intake/camera_image_helpers.py
@@ -0,0 +1,133 @@
+"""Image metadata parsing and heuristic default-camera descriptor helpers."""
+
+from __future__ import annotations
+
+import argparse
+import struct
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import TypeAlias
+
+JsonValue: TypeAlias = str | int | float | bool | None | Sequence["JsonValue"] | Mapping[str, "JsonValue"]
+
+
+def png_size(data: bytes) -> tuple[int, int] | None:
+ if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:
+ return struct.unpack(">II", data[16:24])
+ return None
+
+
+def gif_size(data: bytes) -> tuple[int, int] | None:
+ if data[:6] in {b"GIF87a", b"GIF89a"} and len(data) >= 10:
+ return struct.unpack("<HH", data[6:10])
+ return None
+
+
+def jpeg_size(data: bytes) -> tuple[int, int] | None:
+ if not data.startswith(b"\xff\xd8"):
+ return None
+ index = 2
+ while index + 9 < len(data):
+ if data[index] != 0xFF:
+ index += 1
+ continue
+ marker = data[index + 1]
+ index += 2
+ if marker in {0xD8, 0xD9}:
+ continue
+ if index + 2 > len(data):
+ return None
+ length = struct.unpack(">H", data[index : index + 2])[0]
+ if length < 2 or index + length > len(data):
+ return None
+ if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} and length >= 7:
+ height, width = struct.unpack(">HH", data[index + 3 : index + 7])
+ return width, height
+ index += length
+ return None
+
+
+def webp_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":
+ return None
+ chunk = data[12:16]
+ if chunk == b"VP8X":
+ width = 1 + int.from_bytes(data[24:27], "little")
+ height = 1 + int.from_bytes(data[27:30], "little")
+ return width, height
+ if chunk == b"VP8 ":
+ start = data.find(b"\x9d\x01\x2a")
+ if start != -1 and start + 7 <= len(data):
+ width, height = struct.unpack("<HH", data[start + 3 : start + 7])
+ return width & 0x3FFF, height & 0x3FFF
+ return None
+
+
+def bmp_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) >= 26 and data[:2] == b"BM":
+ width = struct.unpack("<I", data[18:22])[0]
+ height = abs(struct.unpack("<i", data[22:26])[0])
+ return width, height
+ return None
+
+
+def detect_size(data: bytes) -> tuple[int, int] | None:
+ return png_size(data) or jpeg_size(data) or gif_size(data) or webp_size(data) or bmp_size(data)
+
+
+def clamp(value: float, minimum: float, maximum: float) -> float:
+ return max(minimum, min(maximum, value))
+
+
+def estimate_fov(aspect: float | None) -> tuple[float, str]:
+ """Return the established default vertical FOV guess and rationale."""
+ if aspect is not None and aspect < 0.75:
+ return 38.0, "default guess for a portrait-oriented photo (typical phone/short-tele framing)"
+ return 35.0, "default guess for a landscape/square photo (typical phone/short-tele framing)"
+
+
+def build_camera(image: Path, args: argparse.Namespace) -> dict[str, JsonValue]:
+ """Build the existing heuristic reference-camera descriptor from image metadata."""
+ size = detect_size(image.read_bytes())
+ warnings: list[str] = []
+ if size is None:
+ warnings.append("could not read image dimensions; aspect defaults to 1.0")
+ width = height = None
+ aspect = 1.0
+ else:
+ width, height = size
+ aspect = round(width / height, 4) if height else 1.0
+ default_fov, fov_rationale = estimate_fov(aspect)
+ fov_degrees = args.fov_degrees if args.fov_degrees is not None else default_fov
+ fov_source = "user-supplied" if args.fov_degrees is not None else "default-guess"
+ distance = args.distance if args.distance is not None else 2.5
+ distance_source = "user-supplied" if args.distance is not None else "placeholder"
+ return {
+ "version": "1.0",
+ "sourceImage": str(image),
+ "solver": "stage1_intake/solve_camera_pose.py",
+ "method": "heuristic default-guess camera, not solved from image content; image dimensions give an exact aspect ratio, everything else is a starting point for agent refinement",
+ "imageWidth": width,
+ "imageHeight": height,
+ "fovDegrees": {"value": round(fov_degrees, 2), "source": fov_source, "agentFill": fov_source == "default-guess", "rationale": fov_rationale},
+ "aspect": {"value": aspect, "source": "image-dimensions" if size else "fallback-default", "agentFill": size is None},
+ "orientation": {
+ "yawDegrees": {"value": args.yaw, "source": "placeholder", "agentFill": True},
+ "pitchDegrees": {"value": args.pitch, "source": "placeholder", "agentFill": True},
+ "rollDegrees": {"value": args.roll, "source": "placeholder", "agentFill": True},
+ "note": "0/0/0 assumes a straight-on, level shot; adjust by eye against the reference image.",
+ },
+ "position": {
+ "hint": [0.0, args.height_offset, distance],
+ "distance": {"value": distance, "source": distance_source, "agentFill": distance_source == "placeholder"},
+ "note": "Position hint assumes the subject is centered at the origin and the camera looks down -Z.",
+ },
+ "confidence": 0.35 if size else 0.15,
+ "limitations": [
+ "no true camera calibration is performed; focal length/FOV/orientation are not recovered from pixels",
+ "fovDegrees is a genre default, not a measurement; wrong FOV distorts perceived proportions under overlay",
+ "orientation and position are placeholders and will almost always need manual/agent adjustment",
+ "this script cannot detect lens distortion, perspective foreshortening, or non-zero roll",
+ ] + warnings,
+ "note": "Final camera match must be confirmed by overlay review: render the fitted mesh from this camera, place it beside or over the reference image, and adjust fovDegrees/orientation/position until silhouette and landmark alignment match before trusting projected texture bakes.",
+ }
diff --git a/forge/stage1_intake/delight_albedo.py b/forge/stage1_intake/delight_albedo.py
index b408d5c..0867f9b 100755
--- a/forge/stage1_intake/delight_albedo.py
+++ b/forge/stage1_intake/delight_albedo.py
@@ -26,6 +26,9 @@ import zlib
from pathlib import Path
from typing import Any
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -161,6 +164,12 @@ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]], l
try:
return (*read_png(path), warnings)
except Exception as direct_error:
+ jpeg_bytes = path.read_bytes()
+ if is_jpeg(jpeg_bytes):
+ try:
+ return (*decode_jpeg(jpeg_bytes), warnings)
+ except UnsupportedJpeg as unsupported:
+ warnings.append(f"{path.name} needs an external converter: {unsupported}")
sips = shutil.which("sips")
if not sips:
raise ValueError(
diff --git a/forge/stage1_intake/extract_landmarks.py b/forge/stage1_intake/extract_landmarks.py
index c6def80..53203a1 100644
--- a/forge/stage1_intake/extract_landmarks.py
+++ b/forge/stage1_intake/extract_landmarks.py
@@ -21,6 +21,9 @@ import tempfile
import zlib
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -163,6 +166,12 @@ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
try:
return read_png(path)
except Exception as direct_error:
+ jpeg_bytes = path.read_bytes()
+ if is_jpeg(jpeg_bytes):
+ try:
+ return decode_jpeg(jpeg_bytes)[:3]
+ except UnsupportedJpeg:
+ pass
sips = shutil.which("sips")
if not sips:
raise ValueError(f"could not decode {path.name} as PNG and sips is unavailable: {direct_error}") from direct_error
diff --git a/forge/stage1_intake/extract_pbr_evidence.py b/forge/stage1_intake/extract_pbr_evidence.py
index c4e41ee..e9afdc0 100755
--- a/forge/stage1_intake/extract_pbr_evidence.py
+++ b/forge/stage1_intake/extract_pbr_evidence.py
@@ -24,6 +24,9 @@ from collections import Counter
from pathlib import Path
from typing import Any
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -191,6 +194,12 @@ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]], l
try:
return (*read_png(path), warnings)
except Exception as direct_error:
+ jpeg_bytes = path.read_bytes()
+ if is_jpeg(jpeg_bytes):
+ try:
+ return (*decode_jpeg(jpeg_bytes), warnings)
+ except UnsupportedJpeg as unsupported:
+ warnings.append(f"{path.name} needs an external converter: {unsupported}")
sips = shutil.which("sips")
if not sips:
raise ValueError(
diff --git a/forge/stage1_intake/material_region_analysis.py b/forge/stage1_intake/material_region_analysis.py
new file mode 100644
index 0000000..0f5afb6
--- /dev/null
+++ b/forge/stage1_intake/material_region_analysis.py
@@ -0,0 +1,227 @@
+#!/usr/bin/env python3
+"""Analyze admitted material regions and connect them to the registry.
+
+Input manifest example::
+
+ {"referenceId":"armor-front", "regions":[
+ {"componentId":"torso-armor", "regionId":"paint", "sourceImage":"front.png",
+ "bbox":{"x":120,"y":80,"width":420,"height":300},
+ "family":"coating", "subtype":"paint-over-metal", "finish":"gloss-or-satin",
+ "materialSpecId":"armor-paint"}
+ ]}
+
+The command creates verified crops, runs the existing pixel/PBR evidence
+extractor, resolves the canonical material profile, and emits one durable
+``material-analysis.json`` artifact. It never silently promotes a low
+confidence inference to ``proceed``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from argparse import Namespace
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge" / "stage1_intake"))
+from analyze_texture import analyze # noqa: E402
+from extract_pbr_evidence import extract, load_image, write_png_rgb # noqa: E402
+
+sys.path.insert(0, str(ROOT / "forge"))
+from materials.reference import build_assignment, load_reference # noqa: E402
+
+
+def _bounded_bbox(raw: Any, width: int, height: int) -> tuple[int, int, int, int]:
+ if not isinstance(raw, dict):
+ raise ValueError("region bbox must be an object")
+ values = [raw.get(key) for key in ("x", "y", "width", "height")]
+ if not all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in values):
+ raise ValueError("region bbox requires numeric x, y, width and height")
+ x, y, box_width, box_height = (float(value) for value in values)
+ if raw.get("normalized") is True:
+ x, box_width = x * width, box_width * width
+ y, box_height = y * height, box_height * height
+ x0 = max(0, min(width - 1, round(x)))
+ y0 = max(0, min(height - 1, round(y)))
+ x1 = max(x0 + 1, min(width, round(x + box_width)))
+ y1 = max(y0 + 1, min(height, round(y + box_height)))
+ if (x1 - x0) < 8 or (y1 - y0) < 8:
+ raise ValueError("material crop is too small; minimum crop dimension is 8 pixels")
+ return x0, y0, x1 - x0, y1 - y0
+
+
+def crop_region(source: Path, bbox: dict[str, Any], output: Path) -> dict[str, Any]:
+ width, height, pixels, warnings = load_image(source)
+ x0, y0, crop_width, crop_height = _bounded_bbox(bbox, width, height)
+ rgb = bytearray()
+ for y in range(y0, y0 + crop_height):
+ for x in range(x0, x0 + crop_width):
+ red, green, blue, alpha = pixels[y * width + x]
+ if alpha < 16:
+ red = green = blue = 0
+ rgb.extend((red, green, blue))
+ write_png_rgb(output, crop_width, crop_height, bytes(rgb))
+ return {
+ "path": str(output.resolve()),
+ "bbox": {"x": x0, "y": y0, "width": crop_width, "height": crop_height},
+ "sourceWidth": width,
+ "sourceHeight": height,
+ "loaderWarnings": warnings,
+ "coverage": round((crop_width * crop_height) / max(1, width * height), 4),
+ }
+
+
+def _observations(texture_report: dict[str, Any]) -> list[str]:
+ stats = texture_report.get("stats", {})
+ observations: list[str] = []
+ if float(stats.get("meanSaturation", 0.0)) < 0.18:
+ observations.append("near-neutral colour response")
+ else:
+ observations.append("chromatic base-colour response")
+ if float(stats.get("streakRatio", 1.0)) > 1.9 or float(stats.get("streakRatio", 1.0)) < 0.53:
+ observations.append("directional surface frequency")
+ if float(stats.get("mottle", 0.0)) > 0.038:
+ observations.append("visible meso/micro variation")
+ if float(stats.get("gradientStrength", 0.0)) > 0.18:
+ observations.append("strong image-space gradient; verify it is material pattern, not lighting")
+ observations.append("single-image PBR inference requires controlled render validation")
+ return observations
+
+
+def analyze_manifest(
+ manifest_path: Path,
+ out_dir: Path,
+ reference_path: Path | None = None,
+ registry_path: Path | None = None,
+ target_threshold: float = 0.7,
+ multi_view_reference: bool = False,
+) -> dict[str, Any]:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ if not isinstance(manifest, dict) or not isinstance(manifest.get("regions"), list):
+ raise ValueError("material region manifest must contain a regions array")
+ registry = load_reference(registry_path) if registry_path else load_reference()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ regions: list[dict[str, Any]] = []
+ for index, region in enumerate(manifest["regions"]):
+ if not isinstance(region, dict):
+ raise ValueError(f"regions[{index}] must be an object")
+ component_id = str(region.get("componentId") or "").strip()
+ region_id = str(region.get("regionId") or "").strip()
+ if not component_id or not region_id:
+ raise ValueError(f"regions[{index}] requires componentId and regionId")
+ source = Path(region.get("sourceImage") or reference_path or "")
+ if not source.is_absolute():
+ source = (manifest_path.parent / source).resolve()
+ if not source.exists():
+ raise ValueError(f"region {region_id!r} source image does not exist: {source}")
+ crop_path = out_dir / f"{index:02d}-{region_id.replace('/', '-').replace(' ', '-')}.png"
+ crop_info = crop_region(source, region.get("bbox"), crop_path)
+ texture_report = analyze(crop_path)
+ pbr_dir = out_dir / f"pbr-{index:02d}-{region_id.replace('/', '-').replace(' ', '-')}"
+ args = Namespace(
+ image=crop_path,
+ out_dir=pbr_dir,
+ material_id=str(region.get("materialSpecId") or region_id),
+ size=512,
+ palette_size=5,
+ target_threshold=target_threshold,
+ url_prefix="",
+ multi_view_reference=multi_view_reference,
+ )
+ pbr_report, pbr_patch = extract(args)
+ hypothesis = {
+ "componentId": component_id,
+ "regionId": region_id,
+ "materialId": region.get("materialId"),
+ "family": region.get("family"),
+ "subtype": region.get("subtype"),
+ "finish": region.get("finish"),
+ "aliases": region.get("aliases", []),
+ "confidence": min(float(region.get("confidence", 1.0)), float(pbr_report["confidence"])),
+ "source": region.get("source", "vision"),
+ }
+ assignment = build_assignment(hypothesis, {
+ "crop": crop_info,
+ "pbr": pbr_report,
+ "texture": texture_report,
+ }, registry)
+ if pbr_report["confidence"] < target_threshold and assignment["status"] == "proceed":
+ assignment["status"] = "probe"
+ regions.append({
+ "componentId": component_id,
+ "regionId": region_id,
+ "materialSpecId": region.get("materialSpecId") or region_id,
+ "hypothesis": hypothesis,
+ "assignment": assignment,
+ "observations": _observations(texture_report),
+ "crop": crop_info,
+ "textureAnalysis": texture_report,
+ "pbrReport": pbr_report,
+ "referencePbr": pbr_patch["referencePbr"],
+ "maps": pbr_report.get("maps", {}),
+ })
+ not_observed = manifest.get("notObservedMaterials", [])
+ if not isinstance(not_observed, list):
+ raise ValueError("notObservedMaterials must be an array when present")
+ unresolved_not_observed = [
+ item for item in not_observed
+ if isinstance(item, dict) and item.get("status") in {"probe", "request-input", "unknown"}
+ ]
+ return {
+ "schemaVersion": 1,
+ "kind": "img2threejs.material-analysis",
+ "referenceId": manifest.get("referenceId", manifest_path.stem),
+ "manifest": str(manifest_path.resolve()),
+ "registry": str((registry_path or ROOT / "docs/materials/material-reference.json").resolve()),
+ "targetThreshold": target_threshold,
+ "notObservedMaterials": not_observed,
+ "unresolvedNotObservedMaterials": unresolved_not_observed,
+ "regions": regions,
+ "status": (
+ "proceed"
+ if regions
+ and all(item["assignment"]["status"] == "proceed" for item in regions)
+ and not unresolved_not_observed
+ else "probe"
+ ),
+ "limitations": [
+ "PBR extraction is reference-derived inference, not inverse rendering.",
+ "A crop must be checked against the component visible footprint before accepting material scores.",
+ ],
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, required=True)
+ parser.add_argument("--out-dir", type=Path, required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument("--reference", type=Path)
+ parser.add_argument("--registry", type=Path)
+ parser.add_argument("--target-threshold", type=float, default=0.7)
+ parser.add_argument("--multi-view-reference", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ result = analyze_manifest(
+ args.manifest,
+ args.out_dir,
+ args.reference,
+ args.registry,
+ max(0.0, min(1.0, args.target_threshold)),
+ args.multi_view_reference,
+ )
+ result["artifact"] = str(args.out.resolve())
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps({"status": result["status"], "regions": len(result["regions"]), "out": str(args.out.resolve())}, indent=2))
+ return 0 if result["status"] == "proceed" else 2
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/probe_glb.py b/forge/stage1_intake/probe_glb.py
new file mode 100644
index 0000000..5b14e11
--- /dev/null
+++ b/forge/stage1_intake/probe_glb.py
@@ -0,0 +1,357 @@
+#!/usr/bin/env python3
+"""Probe a binary glTF (GLB) as an explicit reference-mesh artifact.
+
+This is metadata/provenance inspection only. It does not import, render, or copy
+the source mesh into a procedural factory. The browser Three.js route remains the
+authority for reference and output pixels.
+
+Pure Python 3.10+ standard library; no PIL, numpy, Blender, or glTF dependency.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import struct
+from pathlib import Path
+from typing import Any
+
+try:
+ from .semantic_decomposition import assess_semantic_decomposition
+except ImportError: # pragma: no cover - direct script execution
+ from semantic_decomposition import assess_semantic_decomposition
+
+
+GLB_MAGIC = b"glTF"
+JSON_CHUNK = 0x4E4F534A
+BIN_CHUNK = 0x004E4942
+MAX_FALLBACK_BOUND_SAMPLES = 1_000_000
+
+
+def sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _chunk_type_name(chunk_type: int) -> str:
+ try:
+ return chunk_type.to_bytes(4, "little").decode("ascii", errors="replace")
+ except OverflowError:
+ return hex(chunk_type)
+
+
+def parse_glb(path: Path) -> tuple[dict[str, Any], bytes, dict[str, Any]]:
+ data = path.read_bytes()
+ if len(data) < 12:
+ raise ValueError("GLB is shorter than the 12-byte header")
+ magic, version, declared_length = struct.unpack_from("<4sII", data, 0)
+ if magic != GLB_MAGIC:
+ raise ValueError("file does not start with the glTF binary magic")
+ if version != 2:
+ raise ValueError(f"unsupported GLB version {version}; expected 2")
+ if declared_length != len(data):
+ raise ValueError(f"header length {declared_length} does not match file size {len(data)}")
+
+ cursor = 12
+ json_payload: bytes | None = None
+ bin_payload = b""
+ chunks: list[dict[str, Any]] = []
+ while cursor < len(data):
+ if cursor + 8 > len(data):
+ raise ValueError("truncated GLB chunk header")
+ chunk_length, chunk_type = struct.unpack_from("<II", data, cursor)
+ cursor += 8
+ end = cursor + chunk_length
+ if end > len(data):
+ raise ValueError("GLB chunk extends beyond the declared file")
+ payload = data[cursor:end]
+ cursor = end
+ chunks.append({"type": _chunk_type_name(chunk_type), "bytes": chunk_length})
+ if chunk_type == JSON_CHUNK:
+ if json_payload is not None:
+ raise ValueError("GLB contains more than one JSON chunk")
+ json_payload = payload.rstrip(b" \t\r\n\x00")
+ elif chunk_type == BIN_CHUNK:
+ if bin_payload:
+ raise ValueError("GLB contains more than one BIN chunk")
+ bin_payload = payload
+
+ if json_payload is None:
+ raise ValueError("GLB has no JSON chunk")
+ try:
+ document = json.loads(json_payload.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ValueError(f"GLB JSON chunk is invalid: {exc}") from exc
+ if not isinstance(document, dict):
+ raise ValueError("GLB JSON root must be an object")
+ return document, bin_payload, {
+ "version": version,
+ "declaredLength": declared_length,
+ "jsonChunkBytes": len(json_payload),
+ "binChunkBytes": len(bin_payload),
+ "chunks": chunks,
+ }
+
+
+def _buffer_view_bytes(document: dict[str, Any], bin_payload: bytes, view_index: int) -> bytes:
+ views = document.get("bufferViews", [])
+ if not isinstance(views, list) or not 0 <= view_index < len(views):
+ raise ValueError(f"accessor references missing bufferView {view_index}")
+ view = views[view_index]
+ if not isinstance(view, dict):
+ raise ValueError(f"bufferView {view_index} is not an object")
+ if view.get("buffer", 0) != 0:
+ raise ValueError("external/multi-buffer GLB references are not supported by the stdlib probe")
+ start = int(view.get("byteOffset", 0))
+ length = int(view.get("byteLength", 0))
+ end = start + length
+ if start < 0 or end > len(bin_payload):
+ raise ValueError(f"bufferView {view_index} exceeds the GLB BIN chunk")
+ return bin_payload[start:end]
+
+
+_COMPONENT_FORMATS: dict[int, tuple[str, int]] = {
+ 5120: ("b", 1),
+ 5121: ("B", 1),
+ 5122: ("h", 2),
+ 5123: ("H", 2),
+ 5124: ("i", 4),
+ 5125: ("I", 4),
+ 5126: ("f", 4),
+}
+_TYPE_COMPONENTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT2": 4, "MAT3": 9, "MAT4": 16}
+
+
+def _accessor_bounds(
+ document: dict[str, Any], bin_payload: bytes, accessor_index: int
+) -> tuple[list[float], list[float], list[str]]:
+ accessors = document.get("accessors", [])
+ warnings: list[str] = []
+ if not isinstance(accessors, list) or not 0 <= accessor_index < len(accessors):
+ raise ValueError(f"missing accessor {accessor_index}")
+ accessor = accessors[accessor_index]
+ if not isinstance(accessor, dict):
+ raise ValueError(f"accessor {accessor_index} is not an object")
+ if accessor.get("type") != "VEC3":
+ raise ValueError(f"POSITION accessor {accessor_index} is not VEC3")
+ minimum = accessor.get("min")
+ maximum = accessor.get("max")
+ if isinstance(minimum, list) and isinstance(maximum, list) and len(minimum) == 3 and len(maximum) == 3:
+ return [float(v) for v in minimum], [float(v) for v in maximum], warnings
+
+ count = int(accessor.get("count", 0))
+ if count <= 0:
+ raise ValueError(f"POSITION accessor {accessor_index} has no elements")
+ if count > MAX_FALLBACK_BOUND_SAMPLES:
+ warnings.append(
+ f"POSITION accessor {accessor_index} has {count} vertices and no min/max; bounds were not decoded"
+ )
+ return [math.nan] * 3, [math.nan] * 3, warnings
+ component_type = int(accessor.get("componentType", 5126))
+ fmt_info = _COMPONENT_FORMATS.get(component_type)
+ if fmt_info is None:
+ raise ValueError(f"unsupported POSITION componentType {component_type}")
+ fmt, component_bytes = fmt_info
+ view_index = accessor.get("bufferView")
+ if view_index is None:
+ raise ValueError(f"POSITION accessor {accessor_index} has no bufferView")
+ raw = _buffer_view_bytes(document, bin_payload, int(view_index))
+ view = document["bufferViews"][int(view_index)]
+ stride = int(view.get("byteStride", component_bytes * 3))
+ base = int(accessor.get("byteOffset", 0))
+ if stride < component_bytes * 3:
+ raise ValueError(f"bufferView stride is too small for POSITION accessor {accessor_index}")
+ mins = [float("inf")] * 3
+ maxs = [float("-inf")] * 3
+ for index in range(count):
+ offset = base + index * stride
+ if offset + component_bytes * 3 > len(raw):
+ raise ValueError(f"POSITION accessor {accessor_index} exceeds its bufferView")
+ values = struct.unpack_from(f"<3{fmt}", raw, offset)
+ for axis, value in enumerate(values):
+ mins[axis] = min(mins[axis], float(value))
+ maxs[axis] = max(maxs[axis], float(value))
+ return mins, maxs, warnings
+
+
+def _merge_bounds(bounds: list[tuple[list[float], list[float]]]) -> dict[str, Any] | None:
+ valid = [item for item in bounds if all(math.isfinite(v) for v in item[0] + item[1])]
+ if not valid:
+ return None
+ minimum = [min(item[0][axis] for item in valid) for axis in range(3)]
+ maximum = [max(item[1][axis] for item in valid) for axis in range(3)]
+ size = [maximum[axis] - minimum[axis] for axis in range(3)]
+ return {
+ "space": "mesh-local-untransformed",
+ "min": minimum,
+ "max": maximum,
+ "size": size,
+ "center": [(minimum[axis] + maximum[axis]) / 2.0 for axis in range(3)],
+ }
+
+
+def probe_glb(path: Path) -> dict[str, Any]:
+ path = path.expanduser().resolve()
+ if not path.is_file():
+ raise ValueError(f"GLB does not exist: {path}")
+ document, bin_payload, binary = parse_glb(path)
+ warnings: list[str] = []
+ meshes = document.get("meshes", []) if isinstance(document.get("meshes", []), list) else []
+ nodes = document.get("nodes", []) if isinstance(document.get("nodes", []), list) else []
+ materials = document.get("materials", []) if isinstance(document.get("materials", []), list) else []
+ skins = document.get("skins", []) if isinstance(document.get("skins", []), list) else []
+ animations = document.get("animations", []) if isinstance(document.get("animations", []), list) else []
+ scenes = document.get("scenes", []) if isinstance(document.get("scenes", []), list) else []
+ textures = document.get("textures", []) if isinstance(document.get("textures", []), list) else []
+
+ mesh_records: list[dict[str, Any]] = []
+ all_bounds: list[tuple[list[float], list[float]]] = []
+ primitive_count = 0
+ for mesh_index, mesh in enumerate(meshes):
+ if not isinstance(mesh, dict):
+ warnings.append(f"mesh {mesh_index} is not an object")
+ continue
+ primitives = mesh.get("primitives", []) if isinstance(mesh.get("primitives", []), list) else []
+ primitive_records: list[dict[str, Any]] = []
+ mesh_bounds: list[tuple[list[float], list[float]]] = []
+ for primitive_index, primitive in enumerate(primitives):
+ primitive_count += 1
+ if not isinstance(primitive, dict):
+ warnings.append(f"mesh {mesh_index} primitive {primitive_index} is not an object")
+ continue
+ attributes = primitive.get("attributes", {}) if isinstance(primitive.get("attributes", {}), dict) else {}
+ record: dict[str, Any] = {
+ "index": primitive_index,
+ "mode": primitive.get("mode", 4),
+ "attributes": sorted(str(key) for key in attributes),
+ "material": primitive.get("material"),
+ }
+ position_accessor = attributes.get("POSITION")
+ if position_accessor is not None:
+ try:
+ minimum, maximum, accessor_warnings = _accessor_bounds(document, bin_payload, int(position_accessor))
+ record["positionBounds"] = {"min": minimum, "max": maximum}
+ mesh_bounds.append((minimum, maximum))
+ all_bounds.append((minimum, maximum))
+ warnings.extend(accessor_warnings)
+ except ValueError as exc:
+ warnings.append(f"mesh {mesh_index} primitive {primitive_index}: {exc}")
+ else:
+ warnings.append(f"mesh {mesh_index} primitive {primitive_index} has no POSITION attribute")
+ primitive_records.append(record)
+ mesh_record: dict[str, Any] = {
+ "index": mesh_index,
+ "name": mesh.get("name") or f"mesh-{mesh_index}",
+ "primitiveCount": len(primitives),
+ "primitives": primitive_records,
+ }
+ bounds = _merge_bounds(mesh_bounds)
+ if bounds:
+ mesh_record["bounds"] = bounds
+ mesh_records.append(mesh_record)
+
+ node_records = []
+ for index, node in enumerate(nodes):
+ if not isinstance(node, dict):
+ continue
+ node_records.append(
+ {
+ "index": index,
+ "name": node.get("name") or f"node-{index}",
+ "mesh": node.get("mesh"),
+ "skin": node.get("skin"),
+ "children": node.get("children", []),
+ }
+ )
+ material_records = [
+ {"index": index, "name": material.get("name") or f"material-{index}", "alphaMode": material.get("alphaMode", "OPAQUE")}
+ for index, material in enumerate(materials)
+ if isinstance(material, dict)
+ ]
+ skeleton_records = [
+ {"index": index, "name": skin.get("name") or f"skin-{index}", "jointCount": len(skin.get("joints", []))}
+ for index, skin in enumerate(skins)
+ if isinstance(skin, dict)
+ ]
+ bounds = _merge_bounds(all_bounds)
+ if not meshes:
+ warnings.append("GLB contains no meshes")
+ if not bin_payload:
+ warnings.append("GLB contains no BIN payload; external buffers are not accepted by this probe")
+ if not materials:
+ warnings.append("GLB contains no materials; visual appearance must be inferred or supplied separately")
+ if not skins:
+ warnings.append("GLB contains no skin; this is acceptable for static reference geometry but not animation evidence")
+ semantic_decomposition = assess_semantic_decomposition(
+ node_count=len(nodes),
+ mesh_count=len(meshes),
+ primitive_count=primitive_count,
+ material_count=len(materials),
+ nodes=node_records,
+ meshes=mesh_records,
+ materials=material_records,
+ texture_count=len(textures),
+ )
+ if semantic_decomposition["status"] == "insufficient":
+ warnings.append("GLB metadata has no reliable semantic part boundaries; request multipart GLB or capture ID masks")
+ return {
+ "schemaVersion": 1,
+ "kind": "glb-reference",
+ "path": str(path),
+ "sha256": sha256(path),
+ "bytes": path.stat().st_size,
+ "binary": binary,
+ "asset": {
+ "version": document.get("asset", {}).get("version") if isinstance(document.get("asset"), dict) else None,
+ "generator": document.get("asset", {}).get("generator") if isinstance(document.get("asset"), dict) else None,
+ },
+ "scene": {
+ "defaultScene": document.get("scene"),
+ "sceneCount": len(scenes),
+ "nodeCount": len(nodes),
+ "meshCount": len(meshes),
+ "primitiveCount": primitive_count,
+ "materialCount": len(materials),
+ "skinCount": len(skins),
+ "animationCount": len(animations),
+ },
+ "nodes": node_records,
+ "meshes": mesh_records,
+ "materials": material_records,
+ "skins": skeleton_records,
+ "bounds": bounds,
+ "semanticDecomposition": semantic_decomposition,
+ "referenceReadiness": "pass" if meshes and bin_payload else "reject",
+ "warnings": sorted(set(warnings)),
+ "note": "Metadata only. Render the GLB through the target Three.js route before using it as a visual baseline; do not copy its topology into a procedural factory.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("glb", type=Path)
+ parser.add_argument("--out", type=Path, help="also write the machine-readable probe artifact")
+ args = parser.parse_args(argv)
+ try:
+ result = probe_glb(args.glb)
+ rendered = json.dumps(result, indent=2, ensure_ascii=False) + "\n"
+ if args.out:
+ output = args.out.expanduser().resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ temporary = output.with_suffix(output.suffix + ".tmp")
+ temporary.write_text(rendered, encoding="utf-8")
+ temporary.replace(output)
+ print(rendered, end="")
+ return 0
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(__import__("sys").argv[1:]))
diff --git a/forge/stage1_intake/run_vision_adapter.py b/forge/stage1_intake/run_vision_adapter.py
new file mode 100644
index 0000000..cfcdbaf
--- /dev/null
+++ b/forge/stage1_intake/run_vision_adapter.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python3
+"""Run an optional vision adapter without adding dependencies to forge."""
+
+from __future__ import annotations
+
+import argparse
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_PYTHON = ROOT / "integrations" / "vision" / ".venv" / "bin" / "python"
+ADAPTER = ROOT / "integrations" / "vision" / "reference_vision.py"
+
+
+def resolve_python(explicit: str | None) -> Path:
+ configured = explicit or os.environ.get("IMG2THREEJS_VISION_PYTHON")
+ return Path(configured).expanduser().resolve() if configured else DEFAULT_PYTHON
+
+
+def build_command(python: Path, forwarded: list[str]) -> list[str]:
+ return [str(python), str(ADAPTER), *forwarded]
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--vision-python", help="Override the isolated adapter interpreter")
+ parser.add_argument("adapter_args", nargs=argparse.REMAINDER)
+ args = parser.parse_args(argv)
+ python = resolve_python(args.vision_python)
+ if not python.exists():
+ parser.error(
+ f"optional vision interpreter not found at {python}; "
+ "run `uv sync --project integrations/vision --python 3.11`"
+ )
+ if not args.adapter_args:
+ parser.error("provide an adapter command: health, prefetch, segment, depth, or landmarks")
+ completed = subprocess.run(build_command(python, args.adapter_args), check=False)
+ return int(completed.returncode)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/semantic_decomposition.py b/forge/stage1_intake/semantic_decomposition.py
new file mode 100644
index 0000000..b7ea4c4
--- /dev/null
+++ b/forge/stage1_intake/semantic_decomposition.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""Classify how much semantic part evidence a GLB exposes.
+
+This module is deliberately conservative. It does not pretend that a mesh name,
+normal discontinuity, or a guessed connected component is proof of ``head`` or
+``scarf``. It reports what the GLB metadata can support and routes ambiguous
+assets to a browser ID-mask or multipart-GLB decision.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+SEMANTIC_STRATEGIES = (
+ "named-node",
+ "primitive-material-boundary",
+ "uv-texture-boundary",
+ "connected-component-hypothesis",
+ "curvature-normal-region-growing-hypothesis",
+ "multiview-id-mask",
+ "multipart-glb",
+)
+
+
+def assess_semantic_decomposition(
+ *,
+ node_count: int,
+ mesh_count: int,
+ primitive_count: int,
+ material_count: int,
+ nodes: list[dict[str, Any]],
+ meshes: list[dict[str, Any]],
+ materials: list[dict[str, Any]],
+ texture_count: int = 0,
+) -> dict[str, Any]:
+ """Return a fail-closed semantic readiness assessment from GLB metadata.
+
+ ``insufficient`` means insufficient for *reliable semantic reconstruction*,
+ not that geometry algorithms are unable to propose partitions. Hypotheses
+ must be validated by a browser ID-mask or by a multipart export before they
+ may drive a subject-specific procedural factory.
+ """
+
+ named_nodes = [
+ str(item.get("name"))
+ for item in nodes
+ if isinstance(item, dict) and item.get("name") and not str(item["name"]).startswith("node-")
+ ]
+ named_meshes = [
+ str(item.get("name"))
+ for item in meshes
+ if isinstance(item, dict) and item.get("name") and not str(item["name"]).startswith("mesh-")
+ ]
+ named_materials = [
+ str(item.get("name"))
+ for item in materials
+ if isinstance(item, dict) and item.get("name") and not str(item["name"]).startswith("material-")
+ ]
+
+ if node_count == 1 and mesh_count == 1 and primitive_count == 1 and material_count <= 1:
+ status = "insufficient"
+ boundary = "multipart-glb-required"
+ reason = (
+ "The metadata exposes one merged drawable and no semantic material boundary. "
+ "Connected-component or curvature analysis may produce hypotheses, but cannot "
+ "prove which region is head, clothing, weapon, or tail."
+ )
+ elif len(named_nodes) >= 2 or len(named_meshes) >= 2:
+ status = "rich"
+ boundary = "named-node-or-mesh"
+ reason = "Multiple named scene/mesh entities provide an explicit semantic starting point."
+ else:
+ status = "partial"
+ boundary = "browser-id-mask-or-multipart-glb"
+ reason = (
+ "Multiple drawable/material records exist, but metadata names do not establish a "
+ "complete semantic part map."
+ )
+
+ strategy_status: dict[str, str] = {
+ "named-node": "available" if len(named_nodes) >= 2 else "not-proven",
+ "primitive-material-boundary": "available" if primitive_count > 1 or material_count > 1 else "not-proven",
+ "uv-texture-boundary": "available" if texture_count > 0 else "not-proven",
+ "connected-component-hypothesis": "candidate-only",
+ "curvature-normal-region-growing-hypothesis": "candidate-only",
+ "multiview-id-mask": "required-for-runtime-region-evidence",
+ "multipart-glb": "required" if status == "insufficient" else "recommended",
+ }
+ return {
+ "schemaVersion": 1,
+ "status": status,
+ "reliableSemanticBoundary": boundary,
+ "reason": reason,
+ "metadataEvidence": {
+ "nodeCount": node_count,
+ "meshCount": mesh_count,
+ "primitiveCount": primitive_count,
+ "materialCount": material_count,
+ "textureCount": texture_count,
+ "namedNodes": named_nodes,
+ "namedMeshes": named_meshes,
+ "namedMaterials": named_materials,
+ },
+ "strategies": [
+ {"id": strategy, "status": strategy_status[strategy]}
+ for strategy in SEMANTIC_STRATEGIES
+ ],
+ "claimsAllowed": [
+ "scene and drawable inventory",
+ "material/primitive boundaries explicitly present in the GLB",
+ "browser-rendered ID-mask evidence when captured",
+ ],
+ "claimsForbiddenUntilEvidence": [
+ "exact semantic labels inferred from a merged mesh",
+ "per-region material equality without region crops or ID masks",
+ "multipart topology reconstructed from metadata alone",
+ ],
+ }
diff --git a/forge/stage1_intake/solve_camera_pose.py b/forge/stage1_intake/solve_camera_pose.py
index 5b6cc11..11fe377 100755
--- a/forge/stage1_intake/solve_camera_pose.py
+++ b/forge/stage1_intake/solve_camera_pose.py
@@ -15,160 +15,215 @@ from __future__ import annotations
import argparse
import json
-import struct
+import math
import sys
+from collections.abc import Sequence
from pathlib import Path
-from typing import Any
-
-
-def png_size(data: bytes) -> tuple[int, int] | None:
- if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:
- return struct.unpack(">II", data[16:24])
- return None
-
-
-def gif_size(data: bytes) -> tuple[int, int] | None:
- if data[:6] in {b"GIF87a", b"GIF89a"} and len(data) >= 10:
- return struct.unpack("<HH", data[6:10])
- return None
-
-
-def jpeg_size(data: bytes) -> tuple[int, int] | None:
- if not data.startswith(b"\xff\xd8"):
- return None
- index = 2
- while index + 9 < len(data):
- if data[index] != 0xFF:
- index += 1
- continue
- marker = data[index + 1]
- index += 2
- if marker in {0xD8, 0xD9}:
- continue
- if index + 2 > len(data):
- return None
- length = struct.unpack(">H", data[index : index + 2])[0]
- if length < 2 or index + length > len(data):
- return None
- if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}:
- if length >= 7:
- height, width = struct.unpack(">HH", data[index + 3 : index + 7])
- return width, height
- index += length
- return None
-
-
-def webp_size(data: bytes) -> tuple[int, int] | None:
- if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":
- return None
- chunk = data[12:16]
- if chunk == b"VP8X" and len(data) >= 30:
- width = 1 + int.from_bytes(data[24:27], "little")
- height = 1 + int.from_bytes(data[27:30], "little")
- return width, height
- if chunk == b"VP8 " and len(data) >= 30:
- start = data.find(b"\x9d\x01\x2a")
- if start != -1 and start + 7 <= len(data):
- width, height = struct.unpack("<HH", data[start + 3 : start + 7])
- return width & 0x3FFF, height & 0x3FFF
- return None
-
-
-def bmp_size(data: bytes) -> tuple[int, int] | None:
- if len(data) >= 26 and data[:2] == b"BM":
- width = struct.unpack("<I", data[18:22])[0]
- height = abs(struct.unpack("<i", data[22:26])[0])
- return width, height
- return None
-
-
-def detect_size(data: bytes) -> tuple[int, int] | None:
- return png_size(data) or jpeg_size(data) or gif_size(data) or webp_size(data) or bmp_size(data)
-
-
-def clamp(value: float, minimum: float, maximum: float) -> float:
- return max(minimum, min(maximum, value))
-
-
-def estimate_fov(aspect: float | None) -> tuple[float, str]:
- """Return a default vertical FOV guess plus the rationale.
-
- Most product/character reference photos are shot on a phone or a short
- telephoto lens at a comfortable working distance, which lands roughly in
- the 30-45 degree vertical FOV band. There is no way to recover the true
- lens from pixels alone, so this is a fixed default, not a measurement.
- """
- if aspect is not None and aspect < 0.75:
- return 38.0, "default guess for a portrait-oriented photo (typical phone/short-tele framing)"
- return 35.0, "default guess for a landscape/square photo (typical phone/short-tele framing)"
-
-
-def build_camera(image: Path, args: argparse.Namespace) -> dict[str, Any]:
- data = image.read_bytes()
- size = detect_size(data)
- warnings: list[str] = []
- if size is None:
- warnings.append("could not read image dimensions; aspect defaults to 1.0")
- width = height = None
- aspect = 1.0
- else:
- width, height = size
- aspect = round(width / height, 4) if height else 1.0
-
- default_fov, fov_rationale = estimate_fov(aspect)
- fov_degrees = args.fov_degrees if args.fov_degrees is not None else default_fov
- fov_source = "user-supplied" if args.fov_degrees is not None else "default-guess"
-
- distance = args.distance if args.distance is not None else 2.5
- distance_source = "user-supplied" if args.distance is not None else "placeholder"
-
- camera: dict[str, Any] = {
+
+if __package__:
+ from . import camera_fitting_math as _math
+ from . import camera_fitting_solver as _solver
+ from . import camera_fitting_types as _types
+ from . import camera_image_helpers as _images
+else:
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+ from forge.stage1_intake import camera_fitting_math as _math
+ from forge.stage1_intake import camera_fitting_solver as _solver
+ from forge.stage1_intake import camera_fitting_types as _types
+ from forge.stage1_intake import camera_image_helpers as _images
+
+CONVERGED_RMS_PIXELS = _types.CONVERGED_RMS_PIXELS
+DEFAULT_MAXIMUM_DAMPING_RETRIES = _types.DEFAULT_MAXIMUM_DAMPING_RETRIES
+DEFAULT_MAXIMUM_ITERATIONS = _types.DEFAULT_MAXIMUM_ITERATIONS
+FINITE_DIFFERENCE_STEPS = _types.FINITE_DIFFERENCE_STEPS
+INITIAL_DAMPING = _types.INITIAL_DAMPING
+MAXIMUM_DAMPING = _types.MAXIMUM_DAMPING
+MAXIMUM_FOV_DEGREES = _types.MAXIMUM_FOV_DEGREES
+MINIMUM_CAMERA_DEPTH = _types.MINIMUM_CAMERA_DEPTH
+MINIMUM_CORRESPONDENCES = _types.MINIMUM_CORRESPONDENCES
+MINIMUM_FOV_DEGREES = _types.MINIMUM_FOV_DEGREES
+CameraFitDescriptor = _types.CameraFitDescriptor
+CameraInitialization = _types.CameraInitialization
+CameraParameters = _types.CameraParameters
+DegenerateCorrespondencesError = _types.DegenerateCorrespondencesError
+FitCameraParameters = _types.FitCameraParameters
+InsufficientCorrespondencesError = _types.InsufficientCorrespondencesError
+InvalidCameraDimensionsError = _types.InvalidCameraDimensionsError
+InvalidInitialCameraError = _types.InvalidInitialCameraError
+LandmarkCorrespondence = _types.LandmarkCorrespondence
+NonFiniteCameraInputError = _types.NonFiniteCameraInputError
+NormalizedCorrespondence = _types.NormalizedCorrespondence
+ResidualDiagnostic = _types.ResidualDiagnostic
+ScalarField = _types.ScalarField
+SolverLimits = _types.SolverLimits
+bmp_size = _images.bmp_size
+build_camera = _images.build_camera
+clamp = _images.clamp
+detect_size = _images.detect_size
+estimate_fov = _images.estimate_fov
+gif_size = _images.gif_size
+jpeg_size = _images.jpeg_size
+png_size = _images.png_size
+webp_size = _images.webp_size
+
+# Mutable public seams retained for deterministic test callers.
+MAXIMUM_ITERATIONS = DEFAULT_MAXIMUM_ITERATIONS
+MAXIMUM_DAMPING_RETRIES = DEFAULT_MAXIMUM_DAMPING_RETRIES
+
+__all__ = [
+ "CONVERGED_RMS_PIXELS",
+ "FINITE_DIFFERENCE_STEPS",
+ "INITIAL_DAMPING",
+ "MAXIMUM_DAMPING",
+ "MAXIMUM_DAMPING_RETRIES",
+ "MAXIMUM_FOV_DEGREES",
+ "MAXIMUM_ITERATIONS",
+ "MINIMUM_CAMERA_DEPTH",
+ "MINIMUM_CORRESPONDENCES",
+ "MINIMUM_FOV_DEGREES",
+ "CameraFitDescriptor",
+ "CameraInitialization",
+ "DegenerateCorrespondencesError",
+ "InsufficientCorrespondencesError",
+ "InvalidCameraDimensionsError",
+ "InvalidInitialCameraError",
+ "LandmarkCorrespondence",
+ "NonFiniteCameraInputError",
+ "bmp_size",
+ "build_camera",
+ "clamp",
+ "detect_size",
+ "estimate_fov",
+ "fit_camera_to_correspondences",
+ "gif_size",
+ "jpeg_size",
+ "main",
+ "png_size",
+ "webp_size",
+]
+
+
+def fit_camera_to_correspondences(
+ correspondences: Sequence[LandmarkCorrespondence],
+ *,
+ initial_camera: CameraInitialization,
+) -> CameraFitDescriptor:
+ """Fit the seven-DOF camera model after parsing all public numerical input."""
+ normalized = _types.normalize_fit_input(correspondences, initial_camera)
+ if _math.has_degenerate_world_geometry(normalized.correspondences):
+ raise DegenerateCorrespondencesError(correspondence_count=len(normalized.correspondences))
+ initial_residuals = _math.residual_components(normalized.correspondences, normalized.initial_camera)
+ if initial_residuals is None:
+ raise _invalid_initial_camera_error(normalized.correspondences, normalized.initial_camera)
+ initial_error = _math.rms_reprojection_error(initial_residuals)
+ fit_state = _solver.fit_parameters(normalized.correspondences, normalized.initial_camera, _solver_limits())
+ fitted_camera = _camera_parameters_payload(fit_state.parameters)
+ residuals = _residual_diagnostics(normalized.correspondences, fit_state.parameters)
+ final_error = math.sqrt(sum(item["errorPixels"] * item["errorPixels"] for item in residuals) / len(residuals))
+ return {
"version": "1.0",
- "sourceImage": str(image),
+ "sourceImage": "landmark-correspondences",
"solver": "stage1_intake/solve_camera_pose.py",
- "method": (
- "heuristic default-guess camera, not solved from image content; image dimensions give an "
- "exact aspect ratio, everything else is a starting point for agent refinement"
- ),
- "imageWidth": width,
- "imageHeight": height,
+ "method": "numerical-landmark-fit",
+ "imageWidth": fit_state.parameters.image_width,
+ "imageHeight": fit_state.parameters.image_height,
"fovDegrees": {
- "value": round(fov_degrees, 2),
- "source": fov_source,
- "agentFill": fov_source == "default-guess",
- "rationale": fov_rationale,
+ "value": fitted_camera["fovDegrees"],
+ "source": "numerical-landmark-fit",
+ "agentFill": False,
+ "rationale": "fitted from ordered 3D-to-2D landmark correspondences",
},
"aspect": {
- "value": aspect,
- "source": "image-dimensions" if size else "fallback-default",
- "agentFill": size is None,
+ "value": fit_state.parameters.image_width / fit_state.parameters.image_height,
+ "source": "initial-camera-image-dimensions",
+ "agentFill": False,
},
"orientation": {
- "yawDegrees": {"value": args.yaw, "source": "placeholder", "agentFill": True},
- "pitchDegrees": {"value": args.pitch, "source": "placeholder", "agentFill": True},
- "rollDegrees": {"value": args.roll, "source": "placeholder", "agentFill": True},
- "note": "0/0/0 assumes a straight-on, level shot; adjust by eye against the reference image.",
+ "yawDegrees": _fitted_scalar(fitted_camera["yawDegrees"]),
+ "pitchDegrees": _fitted_scalar(fitted_camera["pitchDegrees"]),
+ "rollDegrees": _fitted_scalar(fitted_camera["rollDegrees"]),
+ "note": "Fitted using pitch, yaw, then roll rotations matching the stage-1 projection convention.",
},
"position": {
- "hint": [0.0, args.height_offset, distance],
- "distance": {"value": distance, "source": distance_source, "agentFill": distance_source == "placeholder"},
- "note": "Position hint assumes the subject is centered at the origin and the camera looks down -Z.",
+ "hint": fitted_camera["position"],
+ "distance": _fitted_scalar(fitted_camera["position"][2]),
+ "note": "Fitted camera position in the existing scene-coordinate convention.",
},
- "confidence": 0.35 if size else 0.15,
+ "confidence": 0.95 if fit_state.status == "converged" else 0.5,
"limitations": [
- "no true camera calibration is performed; focal length/FOV/orientation are not recovered from pixels",
- "fovDegrees is a genre default, not a measurement; wrong FOV distorts perceived proportions under overlay",
- "orientation and position are placeholders and will almost always need manual/agent adjustment",
- "this script cannot detect lens distortion, perspective foreshortening, or non-zero roll",
- ]
- + warnings,
- "note": (
- "Final camera match must be confirmed by overlay review: render the fitted mesh from this "
- "camera, place it beside or over the reference image, and adjust fovDegrees/orientation/"
- "position until silhouette and landmark alignment match before trusting projected texture bakes."
- ),
+ "The fit holds image dimensions and principal point fixed from the initialization.",
+ "The fit does not estimate lens distortion, sensor size, or a multi-view reconstruction.",
+ ],
+ "note": "Residuals are recomputed from the emitted cameraParameters descriptor in correspondence input order.",
+ "fit": {
+ "method": "central-difference-damped-least-squares",
+ "cameraParameters": fitted_camera,
+ "initialReprojectionError": initial_error,
+ "finalReprojectionError": final_error,
+ "residuals": residuals,
+ "convergence": {
+ "status": fit_state.status,
+ "iterations": fit_state.iterations,
+ "acceptedSteps": fit_state.accepted_steps,
+ "rejectedSteps": fit_state.rejected_steps,
+ "damping": fit_state.damping,
+ },
+ },
+ }
+
+
+def _solver_limits() -> SolverLimits:
+ return SolverLimits(
+ maximum_iterations=MAXIMUM_ITERATIONS,
+ maximum_damping_retries=MAXIMUM_DAMPING_RETRIES,
+ initial_damping=INITIAL_DAMPING,
+ maximum_damping=MAXIMUM_DAMPING,
+ converged_rms_pixels=CONVERGED_RMS_PIXELS,
+ finite_difference_steps=FINITE_DIFFERENCE_STEPS,
+ )
+
+
+def _invalid_initial_camera_error(
+ correspondences: Sequence[NormalizedCorrespondence], camera: CameraParameters
+) -> InvalidInitialCameraError:
+ for correspondence in correspondences:
+ if _math.project_landmark(correspondence.world, camera) is None:
+ return InvalidInitialCameraError(correspondence_name=correspondence.name)
+ return InvalidInitialCameraError(correspondence_name=correspondences[0].name)
+
+
+def _camera_parameters_payload(camera: CameraParameters) -> FitCameraParameters:
+ return {
+ "fovDegrees": camera.fov_degrees,
+ "yawDegrees": camera.yaw_degrees,
+ "pitchDegrees": camera.pitch_degrees,
+ "rollDegrees": camera.roll_degrees,
+ "position": [camera.position[0], camera.position[1], camera.position[2]],
}
- return camera
+
+
+def _fitted_scalar(value: float) -> ScalarField:
+ return {"value": value, "source": "numerical-landmark-fit", "agentFill": False}
+
+
+def _residual_diagnostics(
+ correspondences: Sequence[NormalizedCorrespondence], camera: CameraParameters
+) -> list[ResidualDiagnostic]:
+ diagnostics: list[ResidualDiagnostic] = []
+ for correspondence in correspondences:
+ projected = _math.project_landmark(correspondence.world, camera)
+ if projected is None:
+ raise _invalid_initial_camera_error(correspondences, camera)
+ diagnostics.append(
+ {
+ "name": correspondence.name,
+ "errorPixels": math.hypot(
+ projected[0] - correspondence.observed[0],
+ projected[1] - correspondence.observed[1],
+ ),
+ }
+ )
+ return diagnostics
def main(argv: list[str]) -> int:
@@ -182,14 +237,11 @@ def main(argv: list[str]) -> int:
parser.add_argument("--height-offset", type=float, default=0.0, help="Camera Y offset hint, scene units")
parser.add_argument("--out", type=Path, help="Write the referenceCamera JSON block to this path")
args = parser.parse_args(argv)
-
image = args.image.expanduser().resolve()
if not image.exists():
parser.error(f"{image} does not exist")
-
camera = build_camera(image, args)
- payload = {"referenceCamera": camera}
- text = json.dumps(payload, indent=2, ensure_ascii=False)
+ text = json.dumps({"referenceCamera": camera}, indent=2, ensure_ascii=False)
if args.out:
out_path = args.out.expanduser().resolve()
out_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/forge/stage2_spec/apply_material_analysis.py b/forge/stage2_spec/apply_material_analysis.py
new file mode 100644
index 0000000..2da5463
--- /dev/null
+++ b/forge/stage2_spec/apply_material_analysis.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Apply region-level material analysis to an ObjectSculptSpec.
+
+This is the Phase 7 hand-off: analyzer output is copied with provenance into
+the spec, profile priors become explicit candidate scalars, and components are
+bound to the resolved material region. Existing specs remain valid when this
+field is absent.
+"""
+
+from __future__ import annotations
+
+import argparse
+import copy
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+
+SCALAR_FIELDS = (
+ "metalness", "roughness", "clearcoat", "clearcoatRoughness", "ior",
+ "anisotropy", "sheen", "sheenRoughness", "transmission", "dispersion",
+)
+
+
+def _layer(existing: Any, value: Any) -> dict[str, Any]:
+ result = dict(existing) if isinstance(existing, dict) else {}
+ result["base"] = value
+ result.setdefault("variation", 0.0)
+ return result
+
+
+def apply_material_analysis(
+ spec: dict[str, Any],
+ analysis: dict[str, Any],
+ *,
+ allow_probe: bool = False,
+) -> dict[str, Any]:
+ if not isinstance(spec, dict) or not isinstance(analysis, dict):
+ raise ValueError("spec and analysis must be JSON objects")
+ regions = analysis.get("regions")
+ if not isinstance(regions, list) or not regions:
+ raise ValueError("analysis.regions must be a non-empty array")
+ statuses = {str(item.get("assignment", {}).get("status")) for item in regions if isinstance(item, dict)}
+ analysis_status = str(analysis.get("status", "probe"))
+ unresolved_not_observed = analysis.get("unresolvedNotObservedMaterials", [])
+ if not isinstance(unresolved_not_observed, list):
+ raise ValueError("analysis.unresolvedNotObservedMaterials must be an array")
+ if analysis_status != "proceed" and not allow_probe:
+ raise ValueError("material analysis is not proceed; review unresolved material regions before wiring")
+ if not allow_probe and statuses - {"proceed"}:
+ raise ValueError("material analysis contains probe/unknown regions; pass --allow-probe after review")
+ materials = spec.setdefault("materials", [])
+ if not isinstance(materials, list):
+ raise ValueError("spec.materials must be an array")
+ components = spec.setdefault("componentTree", [])
+ if not isinstance(components, list):
+ raise ValueError("spec.componentTree must be an array")
+ by_material = {str(item.get("id")): item for item in materials if isinstance(item, dict) and item.get("id")}
+ by_component = {str(item.get("id")): item for item in components if isinstance(item, dict) and item.get("id")}
+ applied: list[dict[str, Any]] = []
+ for region in regions:
+ if not isinstance(region, dict):
+ raise ValueError("analysis region must be an object")
+ assignment = region.get("assignment")
+ if not isinstance(assignment, dict) or not assignment.get("profileId"):
+ raise ValueError(f"region {region.get('regionId')!r} has no resolved profile")
+ spec_material_id = str(region.get("materialSpecId") or region.get("regionId"))
+ material = by_material.get(spec_material_id)
+ if material is None:
+ material = {"id": spec_material_id, "baseColor": "#FFFFFF"}
+ materials.append(material)
+ by_material[spec_material_id] = material
+ profile_id = str(assignment["profileId"])
+ material["referenceMaterialId"] = profile_id
+ material["materialFamily"] = assignment.get("family")
+ material["materialSubtype"] = assignment.get("subtype")
+ material["materialFinish"] = assignment.get("finish")
+ material["materialReference"] = {
+ "registry": analysis.get("registry"),
+ "profileId": profile_id,
+ "method": assignment.get("method"),
+ "confidence": assignment.get("confidence"),
+ "sourceRefs": copy.deepcopy(assignment.get("sourceRefs", [])),
+ "requiredMaps": copy.deepcopy(assignment.get("requiredMaps", [])),
+ "optionalMaps": copy.deepcopy(assignment.get("optionalMaps", [])),
+ "validationViews": copy.deepcopy(assignment.get("validationViews", [])),
+ }
+ for field, value in assignment.get("renderPrior", {}).items():
+ if field in SCALAR_FIELDS and isinstance(value, (int, float)):
+ material[field] = _layer(material.get(field), value)
+ material.setdefault("textureResolution", 1024)
+ material.setdefault("textureProjection", {
+ "mode": "uv",
+ "repeat": [1, 1],
+ "anisotropy": 8,
+ "colorSpace": "SRGBColorSpace for albedo; NoColorSpace for scalar/normal maps",
+ "mapBindings": copy.deepcopy(assignment.get("requiredMaps", [])),
+ })
+ pbr = region.get("referencePbr")
+ if isinstance(pbr, dict):
+ material["referencePbr"] = copy.deepcopy(pbr)
+ texture_analysis = region.get("textureAnalysis")
+ if isinstance(texture_analysis, dict):
+ material["textureAnalysis"] = copy.deepcopy(texture_analysis)
+ material["materialEvidence"] = {
+ "componentId": region.get("componentId"),
+ "regionId": region.get("regionId"),
+ "crop": copy.deepcopy(region.get("crop")),
+ "observations": copy.deepcopy(region.get("observations", [])),
+ "hypothesis": copy.deepcopy(region.get("hypothesis", {})),
+ "alternatives": copy.deepcopy(assignment.get("alternatives", [])),
+ }
+ if assignment.get("family") in {"metal", "glass", "gemstone"}:
+ material["needsEnvironment"] = True
+ component = by_component.get(str(region.get("componentId")))
+ if component is not None:
+ component["material"] = spec_material_id
+ component.setdefault("uvContract", {
+ "status": "unwrapped",
+ "strategy": "generated procedural coordinates",
+ "materialId": spec_material_id,
+ })
+ component.setdefault("materialRegions", []).append({
+ "regionId": region.get("regionId"),
+ "materialId": spec_material_id,
+ "profileId": profile_id,
+ "crop": copy.deepcopy(region.get("crop")),
+ })
+ applied.append({
+ "componentId": region.get("componentId"),
+ "regionId": region.get("regionId"),
+ "specMaterialId": spec_material_id,
+ "profileId": profile_id,
+ "status": assignment.get("status"),
+ })
+ spec["materialPipeline"] = {
+ "schemaVersion": 1,
+ "status": (
+ "proceed"
+ if analysis_status == "proceed"
+ and not statuses - {"proceed"}
+ and not unresolved_not_observed
+ else "probe"
+ ),
+ "registry": analysis.get("registry"),
+ "analysisArtifact": analysis.get("artifact", analysis.get("manifest")),
+ "targetThreshold": analysis.get("targetThreshold", 0.7),
+ "unresolvedNotObservedMaterials": copy.deepcopy(unresolved_not_observed),
+ "regions": applied,
+ "controlledViewsRequired": sorted({
+ view
+ for region in regions
+ if isinstance(region.get("assignment"), dict)
+ for view in region["assignment"].get("validationViews", [])
+ }),
+ }
+ spec.setdefault("materialAnalysisHistory", []).append({
+ "analysisArtifact": analysis.get("artifact", analysis.get("manifest")),
+ "status": spec["materialPipeline"]["status"],
+ "unresolvedNotObservedMaterials": copy.deepcopy(unresolved_not_observed),
+ "regions": len(applied),
+ })
+ return spec
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("analysis", type=Path)
+ parser.add_argument("--in-place", action="store_true")
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--allow-probe", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
+ analysis = json.loads(args.analysis.read_text(encoding="utf-8"))
+ result = apply_material_analysis(spec, analysis, allow_probe=args.allow_probe)
+ output = args.spec if args.in_place else args.out
+ if output is None:
+ raise ValueError("choose --in-place or --out")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps({"status": result["materialPipeline"]["status"], "out": str(output.resolve())}, indent=2))
+ return 0
+ except Exception as exc:
+ print(f"error: {exc}")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage2_spec/humanoid_proportions.py b/forge/stage2_spec/humanoid_proportions.py
new file mode 100644
index 0000000..f79ae2f
--- /dev/null
+++ b/forge/stage2_spec/humanoid_proportions.py
@@ -0,0 +1,214 @@
+#!/usr/bin/env python3
+"""Canonical humanoid proportions, so a reference-free stylized figure can be specified.
+
+`validate_sculpt_spec.py` blocks any character spec whose `anatomy.applies` is not true, and
+tells the author to "fill anatomy (styleHeads, proportions, pose, faceLandmarks) from the
+reference". That is the right demand when there IS a reference: a specific person's
+proportions are evidence, and a canon table would be a fabrication of that evidence.
+
+But it also made a reference-free request impossible to express. "Build me a 4-head stylized
+low-poly humanoid" has no reference to measure, and the canon it should follow is public
+figure-drawing convention, not an invented number. This module supplies that canon and marks
+it as canon, so the two cases stay distinguishable downstream: anatomy derived here carries
+`source: "canon-table"`, never `"reference"`.
+
+## Provenance of every number below
+
+Cited to the low-poly humanoid research corpus (NotebookLM notebook
+`ab7334f3-818b-427d-a7eb-96c0581d812f`, 77 sources) or marked DEFINITIONAL where the value
+follows from the head-unit system itself rather than from a source.
+
+| Landmark | 8-head | 4-head | Provenance |
+|---------------------|---------|---------|--------------|
+| head height / H | 0.125 | 0.25 | DEFINITIONAL (1/styleHeads) |
+| shoulder width / H | 0.25 | -- | research |
+| waist width / H | 0.125 | -- | research |
+| hip width / H | 0.1875 | -- | research |
+| hip line Y / H | 0.50 | -- | research |
+| knee line Y / H | 0.25 | -- | research |
+| upper arm / H | 0.187 | 0.125 | research |
+| forearm / H | 0.187 | 0.125 | research |
+| shin / H | 0.25 | 0.125 | research |
+
+Values the research corpus did NOT supply are absent rather than guessed: chest width,
+shoulder Y, waist Y, hand length, thigh length, foot length. `derive_anatomy()` reports them
+in `unsourced` so a caller can see what it is NOT being told, instead of receiving a
+confident-looking number nobody measured. Filling them in later is a research task, not an
+editing task.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+# Fractions of total height H. Only entries with a stated provenance above appear here.
+#
+# 8 is the only COMPLETE canon. The corpus supplies stylized limb lengths but was asked
+# directly for the 4-head hip line, torso span, leg span and shoulder width and answered
+# "NOT IN SOURCES" for all four. Without a hip line there is no torso/legs split, which is
+# precisely what the character gate checks — so a 4-head figure cannot be derived honestly
+# here yet, and `derive_anatomy()` says so instead of interpolating toward the 8-head row.
+CANON_BY_HEADS: dict[int, dict[str, float]] = {
+ 8: {
+ "shoulderWidth": 0.25,
+ "waistWidth": 0.125,
+ "hipWidth": 0.1875,
+ "hipLineY": 0.50,
+ "kneeLineY": 0.25,
+ "upperArmLength": 0.187,
+ "forearmLength": 0.187,
+ "shinLength": 0.25,
+ },
+}
+
+# Sourced, but not enough on their own to satisfy the gate. Kept so the missing pieces are
+# named rather than forgotten: filling in a 4-head hip line makes this row usable.
+PARTIAL_CANON_BY_HEADS: dict[int, dict[str, float]] = {
+ 4: {
+ "upperArmLength": 0.125,
+ "forearmLength": 0.125,
+ "shinLength": 0.125,
+ },
+}
+
+REQUIRED_FOR_GATE: tuple[str, ...] = ("hipLineY",)
+
+UNSOURCED_LANDMARKS: tuple[str, ...] = (
+ "chestWidth",
+ "shoulderLineY",
+ "waistLineY",
+ "handLength",
+ "thighLength",
+ "footLength",
+)
+
+# Face landmarks as a fraction of HEAD height, measured from the top of the skull down.
+# DEFINITIONAL under the standard head-division convention: the eye line halves the head,
+# the nose base and mouth line divide the lower half. The research corpus was not asked for
+# these, so they are marked as convention rather than as measured evidence.
+FACE_LANDMARKS_BY_HEAD_FRACTION: dict[str, float] = {
+ "eyeLine": 0.50,
+ "noseBase": 0.75,
+ "mouthLine": 0.85,
+}
+
+SUPPORTED_HEADS: tuple[int, ...] = tuple(sorted(CANON_BY_HEADS))
+
+
+def nearest_supported_heads(style_heads: float) -> int:
+ """Snap to the nearest COMPLETE table, rather than interpolating between tables.
+
+ Interpolating would invent numbers with the same confident shape as the sourced ones,
+ which is exactly what this module exists to avoid.
+ """
+ return min(SUPPORTED_HEADS, key=lambda h: abs(h - style_heads))
+
+
+def missing_for_heads(style_heads: float) -> list[str]:
+ """Name the landmarks that stop a head count from being derivable, or return []."""
+ heads = int(style_heads) if float(style_heads).is_integer() else None
+ if heads in CANON_BY_HEADS:
+ return []
+ partial = PARTIAL_CANON_BY_HEADS.get(heads or -1)
+ if partial is None:
+ return []
+ return [key for key in REQUIRED_FOR_GATE if key not in partial]
+
+
+def derive_anatomy(style_heads: float) -> dict[str, Any]:
+ """Build an `anatomy` block from canon, explicitly labelled as canon.
+
+ The returned block satisfies `validate_sculpt_spec.py`'s character gate — `applies`,
+ `styleHeads`, `proportions` with torso/legs head-unit ratios, and `faceLandmarks` — while
+ `source` and `unsourced` keep it honest about where the numbers came from and what is
+ still missing.
+ """
+ if not isinstance(style_heads, (int, float)) or isinstance(style_heads, bool):
+ raise ValueError(f"styleHeads must be a number, got {style_heads!r}")
+ if style_heads <= 0:
+ raise ValueError(f"styleHeads must be greater than 0, got {style_heads}")
+
+ missing = missing_for_heads(style_heads)
+ if missing:
+ raise ValueError(
+ f"no complete canon for {style_heads} heads: the corpus supplies limb lengths but "
+ f"not {', '.join(missing)}, and without a hip line there is no torso/legs split for "
+ f"the character gate to check. Measure it from a reference, or extend "
+ f"CANON_BY_HEADS once a source states it. Complete tables: {list(SUPPORTED_HEADS)}"
+ )
+
+ heads = nearest_supported_heads(style_heads)
+ fractions = dict(CANON_BY_HEADS[heads])
+ head_height = 1.0 / style_heads
+
+ # The gate asks for head-unit ratios, so convert once here rather than at every call site.
+ def in_heads(fraction: float) -> float:
+ return round(fraction / head_height, 4)
+
+ legs_fraction = fractions.get("hipLineY")
+ return {
+ "applies": True,
+ "source": "canon-table",
+ "styleHeads": style_heads,
+ "snappedToHeads": heads,
+ "proportions": {
+ # Torso spans the hip line up to the shoulders; with no sourced shoulder Y the
+ # honest statement is "everything above the hips minus the head".
+ "torso": in_heads(1.0 - (legs_fraction or 0.5)) - 1.0 if legs_fraction else None,
+ "legs": in_heads(legs_fraction) if legs_fraction else None,
+ "headHeightFraction": round(head_height, 4),
+ **{key: round(value, 4) for key, value in fractions.items()},
+ },
+ "faceLandmarks": dict(FACE_LANDMARKS_BY_HEAD_FRACTION),
+ "pose": {"name": "bind", "description": "A-pose bind, arms lowered, palms inward"},
+ "unsourced": list(UNSOURCED_LANDMARKS),
+ }
+
+
+def apply_to_spec(spec: dict[str, Any], style_heads: float) -> dict[str, Any]:
+ """Write a canon anatomy block into a spec's `preSpecAssessment`.
+
+ Refuses a spec that names a reference image: when a reference exists the anatomy is
+ supposed to be measured from it, and silently substituting canon would turn a gate that
+ demands evidence into one that accepts a default.
+ """
+ source_image = spec.get("sourceImage")
+ if isinstance(source_image, str) and source_image.strip() and source_image != "/dev/null":
+ raise ValueError(
+ f"spec names a reference image ({source_image}); measure anatomy from it rather "
+ "than substituting the canon table"
+ )
+ assessment = spec.setdefault("preSpecAssessment", {})
+ assessment["anatomy"] = derive_anatomy(style_heads)
+ return spec
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("spec", type=Path, help="ObjectSculptSpec to fill")
+ parser.add_argument("--style-heads", type=float, required=True,
+ help="head-unit height of the figure (8 = realistic, 4 = stylized)")
+ parser.add_argument("--in-place", action="store_true")
+ args = parser.parse_args(argv)
+
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
+ try:
+ apply_to_spec(spec, args.style_heads)
+ except ValueError as error:
+ print(f"error: {error}", file=sys.stderr)
+ return 2
+ payload = json.dumps(spec, indent=2)
+ if args.in_place:
+ args.spec.write_text(payload + "\n", encoding="utf-8")
+ print(f"{args.spec}: anatomy filled from canon at {args.style_heads} heads")
+ else:
+ print(payload)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/forge/stage2_spec/new_pre_spec_assessment.py b/forge/stage2_spec/new_pre_spec_assessment.py
index 0c35151..3a305cb 100755
--- a/forge/stage2_spec/new_pre_spec_assessment.py
+++ b/forge/stage2_spec/new_pre_spec_assessment.py
@@ -30,6 +30,9 @@ from forge._shared.spec_search import ( # noqa: E402
load_profile,
serialize_search_results,
)
+from forge._shared.pipeline_routing import ( # noqa: E402
+ resolve_pipeline_routing,
+)
from forge.stage2_spec.new_sculpt_spec import ( # noqa: E402
make_pre_spec_assessment,
make_quality_contract,
@@ -119,8 +122,6 @@ class PreSpecPayloadRequired(TypedDict):
preSpecAssessment: dict[str, JsonValue]
qualityContract: dict[str, JsonValue]
authoringInstruction: str
-
-
class PreSpecPayload(PreSpecPayloadRequired, total=False):
localSpecSearch: LocalSpecSearchPayload
@@ -135,8 +136,6 @@ def select_spec_collection(target_name: str, requested_collection: str | None) -
if requested_collection:
return requested_collection
return "cs2" if detect_cs2_intent(target_name) else "core_3d"
-
-
def search_local_specs(
target_name: str,
collection: str,
@@ -171,6 +170,7 @@ def make_payload(
complexity: str,
is_cs2: bool = False,
manifest: dict | None = None,
+ is_character: bool = False,
) -> PreSpecPayload:
assessment = make_pre_spec_assessment(target_name)
contract = make_quality_contract()
@@ -202,6 +202,34 @@ def make_payload(
"and unknowns before generating or implementing ObjectSculptSpec."
),
}
+ if manifest is not None:
+ existing_routing = manifest.get("pipelineRouting")
+ if isinstance(existing_routing, dict):
+ routing = resolve_pipeline_routing(
+ classification=existing_routing.get("classification")
+ )
+ else:
+ routing = resolve_pipeline_routing(legacy_cs2=True)
+ elif is_character and is_cs2:
+ routing = resolve_pipeline_routing(
+ explicit_track="character-v1.5",
+ classification={
+ "kind": "weapon",
+ "confidence": 1.0,
+ "evidenceRefs": ["pipeline-routing:explicit:weapon-v1.4"],
+ "provider": "pipeline-routing-cli",
+ "version": "1",
+ },
+ )
+ elif is_character:
+ routing = resolve_pipeline_routing(explicit_track="character-v1.5")
+ elif is_cs2:
+ routing = resolve_pipeline_routing(explicit_track="weapon-v1.4")
+ else:
+ routing = None
+ if routing is not None:
+ payload["pipelineRouting"] = routing
+ payload["preSpecAssessment"]["pipelineRouting"] = routing
if manifest is not None:
intake = {
"schemaVersion": manifest.get("schemaVersion"),
@@ -242,6 +270,7 @@ def main(argv: list[str]) -> int:
f"never below the {CS2_DETAIL_MINIMUM} floor even if --complexity is set lower.",
)
parser.add_argument("--manifest", type=Path, help="CS2 intake manifest")
+ parser.add_argument("--character", action="store_true", help="Use the character-v1.5 authoring track")
parser.add_argument(
"--collection",
help="Spec-search collection; defaults to cs2 for CS2 targets and core_3d otherwise.",
@@ -269,7 +298,14 @@ def main(argv: list[str]) -> int:
if manifest.get("state") not in {"proceed", "fallback"}:
parser.error(f"CS2 intake is not ready for assessment: {manifest.get('state', 'unknown')}")
is_cs2 = True
- payload_object = make_payload(args.target_name, args.image, complexity, is_cs2, manifest)
+ payload_object = make_payload(
+ args.target_name,
+ args.image,
+ complexity,
+ is_cs2,
+ manifest,
+ args.character,
+ )
collection = select_spec_collection(args.target_name, args.collection)
try:
payload_object["localSpecSearch"] = search_local_specs(
diff --git a/forge/stage2_spec/new_sculpt_spec.py b/forge/stage2_spec/new_sculpt_spec.py
index a598cc7..257f728 100755
--- a/forge/stage2_spec/new_sculpt_spec.py
+++ b/forge/stage2_spec/new_sculpt_spec.py
@@ -10,6 +10,7 @@ import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from pipeline_routing import resolve_pipeline_routing
from status_banner import emit_status
@@ -255,14 +256,29 @@ def _cnode(cid, name, primitive, parent, position, scale,
material="skin", role="body", level="meso", rotation=(0, 0, 0),
importance=0.7, sockets=None, local_features=None, anim_role="static",
pivot_mode="center", evidence=None, topology_class="assembled-solid",
- topology_rationale=None):
- """Build a full schema-valid componentTree node with humanoid-friendly defaults."""
+ topology_rationale=None, attachment=None, sdf=None, transform_scale=None):
+ """Build a full schema-valid componentTree node with humanoid-friendly defaults.
+
+ `attachment` (optional) supplies a validate_sculpt_spec.py-complete attachment contract
+ (parentSocket, localStart/localEnd, contactType, baseRadius/endRadius, embedDepth,
+ gapTolerance). When localStart/localEnd form a non-degenerate segment, the factory's
+ makeAttachmentEndpoint() auto-builds a tapered cylinder spanning them and IGNORES this
+ node's own transform/scale for geometry -- so `position`/`scale` above still populate the
+ schema's transform/dimensions fields (informational + a render fallback) but the actual
+ mesh is driven by the attachment endpoints. `sdf` (optional) supplies a
+ geometryDescriptor.sdf block for an implicit/concave part (e.g. a recessed eye socket via
+ `subtract`); when given, topologyClass is forced to 'implicit' and transform.scale is
+ forced to identity since the SDF primitives already encode real world-unit sizes.
+ """
if topology_rationale is None:
topology_rationale = (
f"{name} is a discrete primitive body part assembled onto the humanoid rig, "
f"not a continuous sculpt or shell."
)
- return {
+ if sdf is not None:
+ topology_class = "implicit"
+ transform_scale = (1.0, 1.0, 1.0)
+ node = {
"id": cid, "name": name, "level": level, "role": role,
"importance": importance, "confidence": 0.8, "primitive": primitive,
"topologyClass": topology_class,
@@ -273,10 +289,11 @@ def _cnode(cid, name, primitive, parent, position, scale,
"deformationStack": [], "uvStrategy": "generated procedural coordinates",
"normalStrategy": "smooth vertex normals",
},
- "parent": parent, "attachment": None,
+ "parent": parent, "attachment": attachment,
"dimensions": {"width": float(scale[0]), "height": float(scale[1]),
"depth": float(scale[2]), "units": "relative", "confidence": 0.8},
- "transform": {"position": list(position), "rotation": list(rotation), "scale": list(scale)},
+ "transform": {"position": list(position), "rotation": list(rotation),
+ "scale": list(transform_scale if transform_scale is not None else scale)},
"actionProfile": {
"animationRole": anim_role,
"pivot": {"mode": pivot_mode, "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.7},
@@ -297,62 +314,497 @@ def _cnode(cid, name, primitive, parent, position, scale,
"edgeWearPattern": "", "notes": ""},
"evidenceRefs": evidence or ["full-object"], "details": [], "fidelityTier": "blockout",
}
+ if sdf is not None:
+ node["geometryDescriptor"]["sdf"] = sdf
+ return node
+
+
+def _hu_ratio(anatomy: dict | None, key: str, default: float) -> float:
+ """A head-unit proportion ratio (torso/legs/shoulderWidth/hipWidth) sourced from
+ preSpecAssessment.anatomy.proportions when present and positive, else a stylized default.
+ This is what lets a real reference's measured proportions drive the template instead of a
+ fixed bust-shaped guess."""
+ if isinstance(anatomy, dict):
+ proportions = anatomy.get("proportions")
+ if isinstance(proportions, dict):
+ value = proportions.get(key)
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
+ return float(value)
+ return default
+
+
+def _limb_attachment(start, end, base_radius, end_radius, socket,
+ contact_type="socket-joint", embed_depth=0.03, gap_tolerance=0.01,
+ evidence=None) -> dict:
+ """A validate_sculpt_spec.py-complete attachment contract for a linear body segment
+ (torso spine, neck, or a limb bone). `socket` fills attachment.parentSocket, a free-text
+ joint-name label -- used instead of parentId because a bare parentId would just restate
+ the component's own `parent` field with no more information, and validate_sculpt_spec.py's
+ strict-quality mode errors if a supplied parentId ever drifts out of sync with `parent`.
+ localStart/localEnd are points in the OWNING COMPONENT'S PARENT's local space (this
+ template now authors a real parent chain -- see make_character_component_tree), and drive
+ generate_threejs_factory.py's makeAttachmentEndpoint() to auto-build a tapered cylinder
+ spanning them -- so the owning component's own primitive/scale/rotation become a
+ schema-metadata fallback only."""
+ return {
+ "parentSocket": socket,
+ "localStart": [round(float(v), 5) for v in start],
+ "localEnd": [round(float(v), 5) for v in end],
+ "contactType": contact_type,
+ "baseRadius": round(float(base_radius), 5),
+ "endRadius": round(float(end_radius), 5),
+ "embedDepth": embed_depth,
+ "gapTolerance": gap_tolerance,
+ "evidenceRefs": evidence or ["full-object"],
+ }
-def make_character_component_tree(anatomy: dict | None = None) -> list:
- """A stylized humanoid bust template (head/neck/torso/arms + hair, glasses, headphones,
- face features). Head-unit driven; HU ~= 0.28 world units.
+def _eye_socket_sdf(hu: float) -> dict:
+ """A concave eye socket: a spherical shell with a smaller, forward-offset sphere carved out
+ of it via a boolean subtraction -- a real cavity, not a shaded/decal patch (the recorded
+ defect US-004: 'the eye reads as a patch, not a recessed socket'). See
+ forge/_shared/sdf_primitives.py VALID_SDF_OPERATIONS for 'subtract'."""
+ outer_radius = 0.09 * hu
+ carve_radius = 0.075 * hu
+ carve_offset = 0.055 * hu
+
+ # `bounds` is REQUIRED here, not optional. polygonizeSdf falls back to a [-2,-2,-2]..[2,2,2]
+ # box, and at resolution 20 that makes each sample cell 0.2 across while this shell's radius is
+ # 0.0252 -- the whole sphere falls between samples and marching cubes emits NOTHING. The eye
+ # sockets have therefore been EMPTY GEOMETRY in every render so far: the spec said `subtract`,
+ # the validator's recessed-feature gate was satisfied by that, and 457 tests passed, while the
+ # cavity did not exist in the model. Nothing checked that the emitted geometry was non-empty.
+ #
+ # Fit the box to the primitives instead of defaulting: the carve sphere reaches furthest, at
+ # its offset plus its radius, and 1.25x leaves room for the surface without wasting samples.
+ extent = max(outer_radius, carve_offset + carve_radius) * 1.25
+ return {
+ "primitives": [
+ {"id": "shell", "type": "sphere", "center": [0.0, 0.0, 0.0], "radius": round(outer_radius, 5)},
+ {"id": "carve", "type": "sphere", "center": [0.0, 0.0, round(carve_offset, 5)], "radius": round(carve_radius, 5)},
+ ],
+ # id only -- validate_sculpt_spec rejects setting both id and output; they are alternatives.
+ "operations": [{"id": "socket", "type": "subtract", "left": "shell", "right": "carve"}],
+ "bounds": {"min": [round(-extent, 5)] * 3, "max": [round(extent, 5)] * 3},
+ "resolution": 24,
+ }
+
- The generator nests children under a parent node whose transform (incl. scale) cascades,
- so non-uniform parent scale would distort descendants. To avoid that, every visible part is
- authored with a logical parent + local offset, then FLATTENED to world space and parented to
- a hidden, unit-scaled root. Parents used for offsets (torso, head) are unrotated, so summing
- offsets is exact. Parts use primitives the generator already supports."""
+def make_character_component_tree(
+ anatomy: dict | None = None,
+ include_accessories: bool = False,
+) -> list:
+ """A stylized GENERAL HUMANOID template: head/neck/torso/pelvis, full arms (upper arm ->
+ forearm -> hand) and full legs (thigh -> shin -> foot), face features including recessed
+ eye sockets, and hair. Head-unit driven; HU ~= 0.28 world units. Reads
+ preSpecAssessment.anatomy.proportions (torso/legs/shoulderWidth/hipWidth, in head units)
+ when supplied, else falls back to stylized full-body defaults (~7.5 heads tall).
+
+ Glasses, headphones, and a chest decal are NOT part of the baseline -- they were traits of
+ one specific reference person, not general humanoid anatomy. Pass include_accessories=True
+ to restore them. Digits ARE baseline (US-003): five per hand, three phalanges each.
+
+ REAL NESTED HIERARCHY (worker-flatten's WS-E fix has landed: a pivot Group always carries
+ identity scale and a part's dimensions are baked into its own geometry, so a non-uniformly
+ scaled parent can no longer distort a nested child -- see generate_threejs_factory.py). So,
+ unlike the earlier revision of this function, every part below is parented on its real
+ anatomical parent (neck -> torso, head -> neck, upper-arm -> torso, forearm -> upper-arm,
+ hand -> forearm, thigh -> pelvis, shin -> thigh, foot -> shin, face features -> head, ...),
+ not flattened onto a single hidden root.
+
+ Layout math below is still computed as absolute joint coordinates in one shared coordinate
+ space (torso_top_pt, shoulder_pt, hip_pt, ...) because that keeps the trig/anatomy formulas
+ simple and easy to check by eye. Each point is then converted to the LOCAL space of the
+ component's real parent with `_rel(point, parent_id)` immediately before it is authored onto
+ a component -- Three.js interprets a child's position/attachment endpoints relative to its
+ own parent Group, not the world, so this conversion is required once nesting is real.
+ `world_anchor[parent_id]` tracks, for every already-built component, the point that becomes
+ its own pivot Group's world position (its attachment localStart for limb/spine segments, or
+ its own authored position for a plain part) so `_rel()` can look it up.
+ """
hu = 0.28
- # (id, name, primitive, logical_parent, offset, scale, material, role, level, rotation, importance, features)
- parts = [
- ("torso", "Torso (shirt)", "capsule", "root", (0, 0.55 * hu, 0), (2.4 * hu, 2.2 * hu, 1.5 * hu), "shirt", "shell", "macro", (0, 0, 0), 1.0, []),
- ("shirt-decal", "Chest graphic (Orioles)", "plane-card", "torso", (0, 0.1 * hu, 0.78 * hu), (1.5 * hu, 0.9 * hu, 1.0), "shirt-decal", "decal", "micro", (0, 0, 0), 0.7, ["cursive orange team wordmark with white outline"]),
- ("neck", "Neck", "cylinder", "root", (0, 1.65 * hu, 0), (0.55 * hu, 0.7 * hu, 0.55 * hu), "skin", "support", "meso", (0, 0, 0), 0.6, []),
- ("head", "Head", "ellipsoid", "root", (0, 2.5 * hu, 0.02 * hu), (0.92 * hu, 1.12 * hu, 0.98 * hu), "skin", "body", "macro", (0, 0, 0), 1.0, []),
- ("hair", "Hair (side-swept)", "ellipsoid", "head", (0, 0.28 * hu, -0.04 * hu), (1.06 * hu, 0.82 * hu, 1.08 * hu), "hair", "hair", "meso", (0, 0, 0), 0.9, ["short sides, longer swept-back top"]),
- ("hair-front", "Hair front mass", "ellipsoid", "head", (0.12 * hu, 0.34 * hu, 0.34 * hu), (0.7 * hu, 0.5 * hu, 0.6 * hu), "hair", "hair", "micro", (0, 0, 0), 0.6, []),
- ("brow-l", "Eyebrow L", "box", "head", (0.2 * hu, 0.12 * hu, 0.46 * hu), (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
- ("brow-r", "Eyebrow R", "box", "head", (-0.2 * hu, 0.12 * hu, 0.46 * hu), (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
- ("nose", "Nose", "cone", "head", (0, -0.04 * hu, 0.5 * hu), (0.14 * hu, 0.28 * hu, 0.18 * hu), "skin", "detail", "micro", (1.4, 0, 0), 0.4, []),
- ("mouth", "Mouth", "box", "head", (0, -0.34 * hu, 0.46 * hu), (0.24 * hu, 0.04 * hu, 0.05 * hu), "lips", "detail", "micro", (0, 0, 0), 0.4, []),
- ("glasses-frame-l", "Glasses frame L", "torus", "head", (0.21 * hu, 0.02 * hu, 0.48 * hu), (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "connector", "meso", (0, 0, 0), 0.85, []),
- ("glasses-frame-r", "Glasses frame R", "torus", "head", (-0.21 * hu, 0.02 * hu, 0.48 * hu), (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "connector", "meso", (0, 0, 0), 0.85, []),
- ("glasses-bridge", "Glasses bridge", "box", "head", (0, 0.04 * hu, 0.5 * hu), (0.12 * hu, 0.04 * hu, 0.04 * hu), "glasses-frame", "connector", "micro", (0, 0, 0), 0.5, []),
- ("lens-l", "Lens L", "plane-card", "head", (0.21 * hu, 0.02 * hu, 0.485 * hu), (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
- ("lens-r", "Lens R", "plane-card", "head", (-0.21 * hu, 0.02 * hu, 0.485 * hu), (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
- ("hp-band", "Headphone band", "torus", "root", (0, 1.78 * hu, 0.05 * hu), (0.95 * hu, 0.62 * hu, 0.7 * hu), "headphone", "ring", "meso", (1.2, 0, 0), 0.85, []),
- ("hp-cup-l", "Ear cup L", "cylinder", "root", (0.5 * hu, 1.52 * hu, 0.35 * hu), (0.42 * hu, 0.28 * hu, 0.42 * hu), "headphone", "detail", "meso", (0, 0, 1.57), 0.7, []),
- ("hp-cup-r", "Ear cup R", "cylinder", "root", (-0.5 * hu, 1.52 * hu, 0.35 * hu), (0.42 * hu, 0.28 * hu, 0.42 * hu), "headphone", "detail", "meso", (0, 0, 1.57), 0.7, []),
- ("arm-l", "Upper arm L", "capsule", "torso", (1.15 * hu, -0.35 * hu, 0.1 * hu), (0.55 * hu, 1.5 * hu, 0.55 * hu), "shirt", "arm", "meso", (0, 0, 0.25), 0.7, []),
- ("arm-r", "Upper arm R", "capsule", "torso", (-1.15 * hu, -0.35 * hu, 0.1 * hu), (0.55 * hu, 1.5 * hu, 0.55 * hu), "shirt", "arm", "meso", (0, 0, -0.25), 0.7, []),
- ]
- offsets = {"root": (0.0, 0.0, 0.0)}
- for pid, _n, _p, parent, off, *_rest in parts:
- offsets[pid] = off # local offset; world resolved below
-
- def world_pos(pid, parent, off):
- x, y, z = off
- cur = parent
- # walk up the logical parent chain (parents are unrotated), summing offsets
- while cur and cur != "root":
- po = offsets.get(cur, (0.0, 0.0, 0.0))
- x += po[0]; y += po[1]; z += po[2]
- cur = parent_of.get(cur, "root")
- return (x, y, z)
-
- parent_of = {p[0]: p[3] for p in parts}
+ torso_h = _hu_ratio(anatomy, "torso", 2.2) * hu
+ legs_h = _hu_ratio(anatomy, "legs", 3.6) * hu
+ shoulder_w = _hu_ratio(anatomy, "shoulderWidth", 2.3) * hu
+ hip_w = _hu_ratio(anatomy, "hipWidth", 1.7) * hu
+
+ # ---- core body-mass landmarks (world Y, root-relative -- see class docstring on _rel()) ----
+ torso_center_y = 0.55 * hu
+ torso_top_y = torso_center_y + torso_h * 0.5
+ torso_bottom_y = torso_center_y - torso_h * 0.5
+
+ # The head is DERIVED from the spine, bottom-up, not pinned to an absolute height.
+ #
+ # It used to be `head_y = 2.5 * hu`, fixed. Because `torso_h` comes from anatomy and the head
+ # did not, shortening the torso did not lower the head -- it STRETCHED THE NECK to fill the
+ # gap. Measured: at the default torso ratio 2.2 the neck is 15% of torso height; at the
+ # regret reference's measured 1.584 it became 40%, and the torso-top-to-head-bottom gap
+ # doubled from 0.081 to 0.167. That is the giraffe neck visible in the first render, and no
+ # per-part check could see it because every part was individually correct.
+ #
+ # A skeleton has to be built in the order the bones actually stack.
+ NECK_LENGTH_HU = 0.33 # a neck is about a third of a head unit
+ HEAD_HEIGHT_HU = 1.12 # matches the head ellipsoid's own y scale below
+ neck_bottom_y = torso_top_y - 0.08 * hu
+ neck_top_y = neck_bottom_y + NECK_LENGTH_HU * hu
+ head_y = neck_top_y + HEAD_HEIGHT_HU * hu * 0.5 - 0.04 * hu
+
+ pelvis_center_y = torso_bottom_y - 0.1 * hu
+ # The pelvis height co-varies with its width. It used to be a fixed 0.22 hu while the width
+ # scaled with `hip_w`, so a wide-hipped anatomy produced a SLAB: at the regret reference's
+ # measured hipWidth the box came out 0.455 wide x 0.123 tall x 0.360 deep, which renders as a
+ # tabletop the figure appears to be sitting on. A front-on human pelvis is roughly as tall as
+ # it is wide, so tie the two together and keep the old value as the floor for narrow hips.
+ pelvis_half_h = max(0.22 * hu, hip_w * 0.30)
+ hip_joint_y = pelvis_center_y - pelvis_half_h + 0.05 * hu
+
+ thigh_len = legs_h * 0.53
+ shin_len = legs_h * 0.47
+ knee_joint_y = hip_joint_y - thigh_len
+ ankle_joint_y = knee_joint_y - shin_len
+ foot_y = ankle_joint_y - 0.05 * hu
+
+ hip_x = hip_w * 0.30
+ shoulder_x = shoulder_w * 0.5
+
+ # The abdomen/chest division. A single torso cannot bend at the waist, so the spine is two
+ # segments: below this line is abdomen, above it is chest. 0.42 puts the joint slightly below
+ # mid-torso, which is where a human actually flexes.
+ waist_y = torso_bottom_y + torso_h * 0.42
+
+ torso_top_pt = (0.0, torso_top_y, 0.02 * hu)
+ torso_bottom_pt = (0.0, torso_bottom_y, 0.0)
+ waist_pt = (0.0, waist_y, 0.01 * hu)
+ neck_bottom_pt = (0.0, neck_bottom_y, 0.02 * hu)
+ neck_top_pt = (0.0, neck_top_y, 0.02 * hu)
+ head_world = (0.0, head_y, 0.02 * hu)
+ pelvis_world = (0.0, pelvis_center_y, 0.0)
+
+ world_anchor = {"root": (0.0, 0.0, 0.0)}
+
+ def _rel(point, parent_id):
+ anchor = world_anchor[parent_id]
+ return (point[0] - anchor[0], point[1] - anchor[1], point[2] - anchor[2])
+
tree = [_cnode("root", "Character (root)", "box", None, (0, 0, 0), (1, 1, 1),
material="hidden", role="body", level="macro", importance=1.0, anim_role="root")]
- for pid, name, prim, parent, off, scale, mat, role, level, rot, imp, feats in parts:
- tree.append(_cnode(pid, name, prim, "root", world_pos(pid, parent, off), scale,
+
+ # ---- pelvis FIRST: the spine hangs off it, so it has to exist before the abdomen can be
+ # parented to it. Previously the torso and pelvis were siblings under "root", which forced
+ # derive_character_rig() to pick one as the bone root by hand; a real pelvis->abdomen edge
+ # removes that special case entirely.
+ tree.append(_cnode(
+ # An ellipsoid, not a box. A box gave three consecutive profile bands at exactly the same
+ # width (measured: 0.4554, 0.4554, 0.4554) because its sides are flat and vertical -- the
+ # signature of a slab in a silhouette. Hip mass is rounded, so an ellipsoid both reads
+ # correctly and lets the profile taper into the thighs.
+ "pelvis", "Pelvis", "ellipsoid", "root", _rel(pelvis_world, "root"),
+ (hip_w * 0.95, pelvis_half_h * 2, hip_w * 0.75), material="pants", role="body",
+ level="macro", importance=0.9,
+ ))
+ world_anchor["pelvis"] = pelvis_world
+
+ # ---- spine and neck: capsule/cylinder primitives trigger validate_sculpt_spec.py's
+ # attachment requirement regardless of role (ATTACHMENT_PRIMITIVES), so each gets a real
+ # spine-line attachment segment instead of a bare scale/rotation capsule. That is a genuine
+ # improvement rather than a validator workaround: base/end radius gives the waist taper and
+ # the neck-to-shoulder taper a uniform capsule could never express.
+ #
+ # Each segment is anchored at its PROXIMAL (lower) end, exactly like a limb. That is what
+ # makes a component's origin its own joint, and it is why derive_character_rig() no longer
+ # needs a torso-specific joint exception: summing offsets lands on a real joint every time.
+ tree.append(_cnode(
+ "abdomen", "Abdomen", "capsule", "pelvis", _rel(torso_bottom_pt, "pelvis"),
+ (hip_w * 0.9, waist_y - torso_bottom_y, hip_w * 0.8), material="shirt", role="shell",
+ level="macro", importance=0.95,
+ attachment=_limb_attachment(_rel(torso_bottom_pt, "pelvis"), _rel(waist_pt, "pelvis"),
+ hip_w * 0.40, shoulder_w * 0.34,
+ socket="pelvis-waist", contact_type="rigid-weld"),
+ ))
+ world_anchor["abdomen"] = torso_bottom_pt
+
+ tree.append(_cnode(
+ "chest", "Chest", "capsule", "abdomen", _rel(waist_pt, "abdomen"),
+ (shoulder_w * 0.95, torso_top_y - waist_y, hip_w * 0.85), material="shirt", role="shell",
+ level="macro", importance=1.0,
+ # The chest now tapers INWARD toward the neck (end radius < base) instead of being widest
+ # at its flat top. Previously the chest's top radius WAS the shoulder width, so the
+ # silhouette jumped from the neck straight to full torso width in a single profile band --
+ # measured 0.091 -> 0.262 with no intermediate value, where the reference slopes
+ # 0.116 -> 0.229 over ~8% of its height. The shoulder mass belongs to the clavicles.
+ attachment=_limb_attachment(_rel(waist_pt, "abdomen"), _rel(torso_top_pt, "abdomen"),
+ shoulder_w * 0.38, shoulder_w * 0.26,
+ socket="abdomen-chest", contact_type="rigid-weld"),
+ ))
+ world_anchor["chest"] = waist_pt
+
+ tree.append(_cnode(
+ "neck", "Neck", "cylinder", "chest", _rel(neck_bottom_pt, "chest"),
+ (0.55 * hu, neck_top_y - neck_bottom_y, 0.55 * hu), material="skin", role="support",
+ level="meso", importance=0.6,
+ attachment=_limb_attachment(_rel(neck_bottom_pt, "chest"), _rel(neck_top_pt, "chest"),
+ 0.26 * hu, 0.2 * hu,
+ socket="chest-neck-base", contact_type="rigid-weld"),
+ ))
+ world_anchor["neck"] = neck_bottom_pt
+
+ tree.append(_cnode(
+ "head", "Head", "ellipsoid", "neck", _rel(head_world, "neck"),
+ (0.92 * hu, 1.12 * hu, 0.98 * hu), material="skin", role="body", level="macro",
+ importance=1.0,
+ ))
+ world_anchor["head"] = head_world
+
+ # ---- face features and hair: parented to "head". Offsets are already authored local to
+ # head (never went through world_pos/flattening even before the un-flatten), so they need
+ # no _rel() conversion. ----
+ # (id, name, primitive, offset, scale, material, role, level, rotation, importance, features)
+ face_parts = [
+ ("hair", "Hair", "ellipsoid", (0, 0.3 * hu, -0.02 * hu),
+ (1.0 * hu, 0.78 * hu, 1.02 * hu), "hair", "hair", "meso", (0, 0, 0), 0.8,
+ ["short, neutral stylized hairstyle"]),
+ ("brow-l", "Eyebrow L", "box", (0.2 * hu, 0.12 * hu, 0.46 * hu),
+ (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
+ ("brow-r", "Eyebrow R", "box", (-0.2 * hu, 0.12 * hu, 0.46 * hu),
+ (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),
+ # Ears. Offsets are head-unit multiples like every other feature here, so they scale with
+ # the anatomy ratios instead of being pinned to one figure's dimensions. x = 0.43 hu puts
+ # them on the skull surface (the head's own half-width is 0.46 hu), y at eye level, z
+ # slightly aft of centre. They are detail, not bones: an ear does not articulate.
+ ("ear-l", "Ear L", "ellipsoid", (0.43 * hu, 0.02 * hu, -0.02 * hu),
+ (0.09 * hu, 0.26 * hu, 0.17 * hu), "skin", "detail", "micro", (0, 0, 0), 0.45,
+ ["outer helix reads as a flattened shell against the skull, not a disc"]),
+ ("ear-r", "Ear R", "ellipsoid", (-0.43 * hu, 0.02 * hu, -0.02 * hu),
+ (0.09 * hu, 0.26 * hu, 0.17 * hu), "skin", "detail", "micro", (0, 0, 0), 0.45,
+ ["outer helix reads as a flattened shell against the skull, not a disc"]),
+ ("nose", "Nose", "ellipsoid", (0, -0.04 * hu, 0.5 * hu),
+ (0.14 * hu, 0.28 * hu, 0.18 * hu), "skin", "detail", "micro", (1.4, 0, 0), 0.4, []),
+ ("mouth", "Mouth", "box", (0, -0.34 * hu, 0.46 * hu),
+ (0.24 * hu, 0.04 * hu, 0.05 * hu), "lips", "detail", "micro", (0, 0, 0), 0.4, []),
+ ]
+ if include_accessories:
+ face_parts.extend([
+ ("glasses-frame-l", "Glasses frame L", "torus", (0.21 * hu, 0.02 * hu, 0.48 * hu),
+ (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "rim", "meso", (0, 0, 0), 0.85, []),
+ ("glasses-frame-r", "Glasses frame R", "torus", (-0.21 * hu, 0.02 * hu, 0.48 * hu),
+ (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "rim", "meso", (0, 0, 0), 0.85, []),
+ ("glasses-bridge", "Glasses bridge", "box", (0, 0.04 * hu, 0.5 * hu),
+ (0.12 * hu, 0.04 * hu, 0.04 * hu), "glasses-frame", "trim", "micro", (0, 0, 0), 0.5, []),
+ ("lens-l", "Lens L", "plane-card", (0.21 * hu, 0.02 * hu, 0.485 * hu),
+ (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
+ ("lens-r", "Lens R", "plane-card", (-0.21 * hu, 0.02 * hu, 0.485 * hu),
+ (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),
+ ("hp-band", "Headphone band", "torus", (0, -0.72 * hu, 0.05 * hu),
+ (0.95 * hu, 0.62 * hu, 0.7 * hu), "headphone", "ring", "meso", (1.2, 0, 0), 0.85, []),
+ ("hp-cup-l", "Ear cup L", "sphere", (0.5 * hu, -0.98 * hu, 0.35 * hu),
+ (0.4 * hu, 0.4 * hu, 0.22 * hu), "headphone", "detail", "meso", (0, 0, 0), 0.7, []),
+ ("hp-cup-r", "Ear cup R", "sphere", (-0.5 * hu, -0.98 * hu, 0.35 * hu),
+ (0.4 * hu, 0.4 * hu, 0.22 * hu), "headphone", "detail", "meso", (0, 0, 0), 0.7, []),
+ ])
+ for pid, name, prim, off, scale, mat, role, level, rot, imp, feats in face_parts:
+ tree.append(_cnode(pid, name, prim, "head", off, scale,
material=mat, role=role, level=level, rotation=rot, importance=imp,
local_features=feats))
+
+ if include_accessories:
+ # Chest decal is parented to torso; its offset was authored relative to torso's OLD
+ # seed position (torso_center_y) back when this template flattened everything, so
+ # convert it into torso's real local frame (anchored at torso_top_pt) here.
+ decal_old_world = (0.0, torso_center_y + 0.1 * hu, 0.78 * hu)
+ decal_local = _rel(decal_old_world, "chest")
+ tree.append(_cnode(
+ "shirt-decal", "Chest graphic", "plane-card", "chest", decal_local,
+ (1.5 * hu, 0.9 * hu, 1.0), material="shirt-decal", role="decal", level="micro",
+ importance=0.7,
+ ))
+
+ # ---- eyes: a visible eyeball sphere plus a recessed cavity carved via SDF subtract, not a
+ # flat patch (US-004). Naming/roles deliberately avoid the token "socket": that token is
+ # also in validate_sculpt_spec.py's ATTACHMENT_ROLES (ball-and-socket limb joints), so
+ # reusing it here would additionally force an unrelated attachment contract onto a part
+ # that has no start/end line to attach -- "cavity" trips the recessed-feature gate just as
+ # well without that collision. Offsets are already local to head. ----
+ for side, eye_x in (("l", 0.19 * hu), ("r", -0.19 * hu)):
+ eye_local = (eye_x, 0.03 * hu, 0.40 * hu)
+ cavity_local = (eye_x, 0.03 * hu, 0.43 * hu)
+ tree.append(_cnode(
+ f"eye-{side}", f"Eye {side.upper()}", "sphere", "head", eye_local,
+ (0.11 * hu, 0.11 * hu, 0.11 * hu), material="eye", role="detail", level="micro",
+ importance=0.5,
+ ))
+ tree.append(_cnode(
+ f"eye-cavity-{side}", f"Eye cavity {side.upper()}", "sphere", "head", cavity_local,
+ (0.18 * hu, 0.18 * hu, 0.18 * hu), material="skin", role="cavity", level="micro",
+ importance=0.4, sdf=_eye_socket_sdf(hu),
+ topology_rationale=(
+ "The eye reads as a recessed concave cavity carved out of the head volume with a "
+ "boolean subtraction (US-004), not a flat decal or shaded patch."
+ ),
+ ))
+
+ # ---- arms: shoulder -> elbow -> wrist -> hand, laid out as absolute joint coordinates,
+ # then each segment is parented on the PREVIOUS segment (torso -> upper-arm -> forearm ->
+ # hand) and its attachment endpoints are converted into that parent's local space. ----
+ arm_lean = 0.20
+ arm_total = torso_h * 0.95
+ upper_arm_len = arm_total * 0.55
+ forearm_len = arm_total * 0.45
+ shoulder_y = torso_top_y - 0.08 * hu
+ for side, sign in (("l", 1), ("r", -1)):
+ sx = shoulder_x * sign
+ lean = arm_lean * sign
+ shoulder_pt = (sx, shoulder_y, 0.05 * hu)
+ elbow_pt = (
+ shoulder_pt[0] + math.sin(lean) * upper_arm_len,
+ shoulder_pt[1] - math.cos(lean) * upper_arm_len,
+ shoulder_pt[2],
+ )
+ wrist_pt = (
+ elbow_pt[0] + math.sin(lean * 0.6) * forearm_len,
+ elbow_pt[1] - math.cos(lean * 0.6) * forearm_len,
+ elbow_pt[2],
+ )
+ hand_len = 0.32 * hu
+ hand_center = (
+ wrist_pt[0] + math.sin(lean * 0.6) * hand_len * 0.5,
+ wrist_pt[1] - math.cos(lean * 0.6) * hand_len * 0.5,
+ wrist_pt[2],
+ )
+ clavicle_id = f"clavicle-{side}"
+ upper_arm_id = f"upper-arm-{side}"
+ forearm_id = f"forearm-{side}"
+ hand_id = f"hand-{side}"
+
+ # ---- clavicle: sternum -> shoulder joint. Without it the upper arm parents straight to
+ # the chest, so a shoulder cannot shrug or roll forward and the arm's rotation origin
+ # sits inside the chest volume rather than on the joint. It also gives the arm chain a
+ # real root that moves with the ribcage, which is what a shoulder does.
+ clavicle_root_pt = (sign * shoulder_x * 0.16, shoulder_y + 0.02 * hu, 0.03 * hu)
+ tree.append(_cnode(
+ clavicle_id, f"Clavicle {side.upper()}", "capsule", "chest",
+ _rel(clavicle_root_pt, "chest"),
+ (shoulder_x * 0.84, 0.34 * hu, 0.34 * hu), material="skin", role="support",
+ level="meso", importance=0.6,
+ # Thick, and tapering OUTWARD to the shoulder joint. This is the trapezius/deltoid
+ # mass, and it is what produces the neck-to-shoulder slope: it starts narrow beside
+ # the neck and ends wide at the joint. At the old 0.09 hu radius the clavicle was a
+ # 0.05-wide stick, invisible inside the chest, and the chest's flat top had to be the
+ # shoulder instead -- which is exactly what made the silhouette a cliff.
+ attachment=_limb_attachment(_rel(clavicle_root_pt, "chest"), _rel(shoulder_pt, "chest"),
+ 0.11 * hu, 0.17 * hu, socket=f"chest-clavicle-{side}",
+ contact_type="rigid-weld"),
+ ))
+ world_anchor[clavicle_id] = clavicle_root_pt
+
+ tree.append(_cnode(
+ upper_arm_id, f"Upper arm {side.upper()}", "capsule", clavicle_id,
+ _rel(shoulder_pt, clavicle_id),
+ (0.32 * hu, upper_arm_len, 0.32 * hu), material="shirt", role="arm", level="meso",
+ importance=0.7,
+ attachment=_limb_attachment(_rel(shoulder_pt, clavicle_id), _rel(elbow_pt, clavicle_id),
+ 0.16 * hu, 0.13 * hu, socket=f"clavicle-shoulder-{side}"),
+ ))
+ world_anchor[upper_arm_id] = shoulder_pt
+ tree.append(_cnode(
+ forearm_id, f"Forearm {side.upper()}", "capsule", upper_arm_id, _rel(elbow_pt, upper_arm_id),
+ (0.26 * hu, forearm_len, 0.26 * hu), material="skin", role="arm", level="meso",
+ importance=0.65,
+ attachment=_limb_attachment(_rel(elbow_pt, upper_arm_id), _rel(wrist_pt, upper_arm_id),
+ 0.12 * hu, 0.09 * hu, socket=f"upper-arm-elbow-{side}",
+ contact_type="hinge-joint"),
+ ))
+ world_anchor[forearm_id] = elbow_pt
+ tree.append(_cnode(
+ hand_id, f"Hand {side.upper()}", "box", forearm_id, _rel(hand_center, forearm_id),
+ (0.22 * hu, hand_len, 0.13 * hu), material="skin", role="hand", level="meso",
+ importance=0.55,
+ ))
+ world_anchor[hand_id] = hand_center
+ # ---- digits: five per hand, three phalanges each, chained proximal -> middle -> distal.
+ # This replaces the old `--fingers` flag, which added ONE box labelled "fingers" plus one
+ # box labelled "thumb" -- a mitten, not a hand, and opt-in at that. A humanoid that cannot
+ # curl a finger is not finished, so digits are now baseline with no flag.
+ #
+ # Four fingers march down off the distal palm edge; the thumb branches from near the wrist
+ # and travels MEDIALLY (toward the body) rather than down, which is what opposes it. The
+ # medial direction is -sign: for the left hand (sign=+1, +x side of the body) the inside
+ # is -x. Getting that backwards puts both thumbs on the outside.
+ knuckle_row_y = hand_center[1] - hand_len * 0.42
+ digit_layout = (
+ # name, x offset (hu), phalanx lengths (hu), radius (hu), medial thumb?
+ ("thumb", -0.10 * sign, (0.075, 0.055, 0.040), 0.032, True),
+ ("index", -0.075 * sign, (0.105, 0.072, 0.048), 0.028, False),
+ ("middle", -0.025 * sign, (0.115, 0.080, 0.050), 0.029, False),
+ ("ring", 0.025 * sign, (0.105, 0.072, 0.046), 0.027, False),
+ ("little", 0.070 * sign, (0.080, 0.058, 0.038), 0.024, False),
+ )
+ for digit_name, x_offset, lengths, radius, is_thumb in digit_layout:
+ # The thumb starts near the wrist and runs inward; the fingers start at the knuckle
+ # row and run down the same lean the forearm already has.
+ if is_thumb:
+ joint = (hand_center[0] + x_offset * hu,
+ hand_center[1] - hand_len * 0.06,
+ hand_center[2] + 0.02 * hu)
+ step = (-0.72 * sign, -0.62, 0.30) # medial, down, forward
+ else:
+ joint = (hand_center[0] + x_offset * hu, knuckle_row_y, hand_center[2] + 0.01 * hu)
+ step = (math.sin(lean * 0.6), -math.cos(lean * 0.6), 0.0)
+
+ parent_id = hand_id
+ for index, length in enumerate(lengths):
+ phalanx_id = f"{digit_name}-{side}-{index + 1}"
+ tip = (joint[0] + step[0] * length * hu,
+ joint[1] + step[1] * length * hu,
+ joint[2] + step[2] * length * hu)
+ tree.append(_cnode(
+ phalanx_id,
+ f"{digit_name.capitalize()} {side.upper()} phalanx {index + 1}",
+ "capsule", parent_id, _rel(joint, parent_id),
+ (radius * 2 * hu, length * hu, radius * 2 * hu),
+ material="skin", role="finger", level="micro",
+ importance=0.3 if index == 0 else 0.2,
+ attachment=_limb_attachment(
+ _rel(joint, parent_id), _rel(tip, parent_id),
+ radius * hu, radius * 0.82 * hu,
+ socket=f"{parent_id}-{digit_name}-{index + 1}",
+ contact_type="hinge-joint" if index else "rigid-weld",
+ ),
+ ))
+ world_anchor[phalanx_id] = joint
+ parent_id = phalanx_id
+ joint = tip
+
+ # ---- legs: hip -> knee -> ankle -> foot, same pattern (pelvis -> thigh -> shin -> foot). ----
+ for side, sign in (("l", 1), ("r", -1)):
+ lx = hip_x * sign
+ hip_pt = (lx, hip_joint_y, 0.02 * hu)
+ knee_pt = (lx, knee_joint_y, 0.02 * hu)
+ ankle_pt = (lx, ankle_joint_y, 0.0)
+ foot_center = (lx, foot_y, 0.16 * hu)
+ thigh_id = f"thigh-{side}"
+ shin_id = f"shin-{side}"
+ tree.append(_cnode(
+ thigh_id, f"Thigh {side.upper()}", "capsule", "pelvis", _rel(hip_pt, "pelvis"),
+ (0.38 * hu, thigh_len, 0.38 * hu), material="pants", role="leg", level="meso",
+ importance=0.75,
+ attachment=_limb_attachment(_rel(hip_pt, "pelvis"), _rel(knee_pt, "pelvis"),
+ 0.2 * hu, 0.16 * hu, socket=f"pelvis-hip-{side}"),
+ ))
+ world_anchor[thigh_id] = hip_pt
+ tree.append(_cnode(
+ shin_id, f"Shin {side.upper()}", "capsule", thigh_id, _rel(knee_pt, thigh_id),
+ (0.28 * hu, shin_len, 0.28 * hu), material="pants", role="leg", level="meso",
+ importance=0.7,
+ attachment=_limb_attachment(_rel(knee_pt, thigh_id), _rel(ankle_pt, thigh_id),
+ 0.14 * hu, 0.1 * hu, socket=f"thigh-knee-{side}",
+ contact_type="hinge-joint"),
+ ))
+ world_anchor[shin_id] = knee_pt
+ tree.append(_cnode(
+ f"foot-{side}", f"Foot {side.upper()}", "box", shin_id, _rel(foot_center, shin_id),
+ (0.24 * hu, 0.16 * hu, 0.44 * hu), material="shoes", role="foot", level="meso",
+ importance=0.5,
+ ))
return tree
@@ -366,16 +818,23 @@ def _shade_hex(hex_color: str, factor: float) -> str:
return f"#{r:02x}{g:02x}{b:02x}"
-CHARACTER_MATERIALS = [
+CHARACTER_BASE_MATERIALS = [
{"id": "hidden", "baseColor": "#000000", "roughness": {"base": 1.0, "variation": 0.0}, "opacity": {"base": 0.0}},
{"id": "skin", "baseColor": "#e8b98f", "roughness": {"base": 0.55, "variation": 0.08}},
{"id": "hair", "baseColor": "#171310", "roughness": {"base": 0.42, "variation": 0.1}},
{"id": "shirt", "baseColor": "#20202a", "roughness": {"base": 0.85, "variation": 0.12}},
+ {"id": "pants", "baseColor": "#2b2d33", "roughness": {"base": 0.75, "variation": 0.1}},
+ {"id": "shoes", "baseColor": "#171512", "roughness": {"base": 0.55, "variation": 0.08}},
+ {"id": "eye", "baseColor": "#f2eee4", "roughness": {"base": 0.2, "variation": 0.03}},
+ {"id": "lips", "baseColor": "#c98070", "roughness": {"base": 0.5, "variation": 0.05}},
+]
+# Accessories are opt-in (apply_character_template's include_accessories) -- a chest decal,
+# glasses, and headphones are one reference person's traits, not general humanoid anatomy.
+CHARACTER_ACCESSORY_MATERIALS = [
{"id": "shirt-decal", "baseColor": "#d24a20", "roughness": {"base": 0.7, "variation": 0.05}},
{"id": "glasses-frame", "baseColor": "#111114", "roughness": {"base": 0.35, "variation": 0.05}},
{"id": "glasses-lens", "baseColor": "#a9c6d8", "roughness": {"base": 0.08, "variation": 0.02}},
{"id": "headphone", "baseColor": "#0e0e10", "roughness": {"base": 0.5, "variation": 0.08}},
- {"id": "lips", "baseColor": "#c98070", "roughness": {"base": 0.5, "variation": 0.05}},
]
@@ -383,18 +842,18 @@ def make_character_build_passes() -> list:
base = make_pre_spec_assessment # noqa: reference to keep import graph obvious
passes = [
{"id": "blockout", "goal": "Match head-unit proportions and pose silhouette.",
- "componentRefs": ["root"], "acceptance": ["Bust proportions and 3/4 pose read correctly without materials."]},
+ "componentRefs": ["root"], "acceptance": ["Humanoid proportions and pose read correctly without materials."]},
{"id": "proportion-lock", "goal": "Lock head/torso/limb head-unit ratios and pose angles.",
- "componentRefs": ["root", "head", "torso"], "acceptance": ["Head-unit ratios match anatomy; silhouette matches reference."]},
- {"id": "feature-placement", "goal": "Place facial features, hair, glasses, headphones to landmarks.",
- "componentRefs": ["head", "hair", "glasses-frame-l", "hp-band"],
- "acceptance": ["Eyeline/nose/mouth on landmark lines; glasses and headphones placed as in reference."]},
+ "componentRefs": ["root", "head", "chest"], "acceptance": ["Head-unit ratios match anatomy; silhouette matches reference."]},
+ {"id": "feature-placement", "goal": "Place facial features, hair, and any enabled accessories to landmarks.",
+ "componentRefs": ["head", "hair", "eye-l", "eye-r"],
+ "acceptance": ["Eyeline/nose/mouth on landmark lines; eyes read as recessed, not flat patches; enabled accessories placed as in reference."]},
{"id": "material-pass", "goal": "Match skin/hair/cloth/metal color and roughness.",
- "componentRefs": ["root"], "acceptance": ["Skin, hair, shirt, decal, glasses, headphone materials match reference palette."]},
+ "componentRefs": ["root"], "acceptance": ["Skin, hair, shirt, pants, shoe, and any enabled accessory materials match reference palette."]},
{"id": "lighting-pass", "goal": "Soft key from reference direction plus rim.",
"componentRefs": ["root"], "acceptance": ["Readable under neutral light; reference-matched lighting added."]},
{"id": "interaction-pass", "goal": "Rig-ready pivots and sockets.",
- "componentRefs": ["root"], "acceptance": ["Head/neck/arm pivots and face socket exposed."]},
+ "componentRefs": ["root"], "acceptance": ["Head/neck/shoulder/elbow/hip/knee pivots and sockets exposed."]},
{"id": "optimization-pass", "goal": "Protect runtime performance.",
"componentRefs": ["root"], "acceptance": ["Triangle/draw-call budget documented."]},
]
@@ -402,29 +861,284 @@ def make_character_build_passes() -> list:
return passes
-def make_character_feature_targets() -> list:
+def make_character_feature_targets(include_accessories: bool = False) -> list:
+ outfit_refs = ["shirt-decal", "headphone", "glasses-frame-l"] if include_accessories else ["chest", "pants", "shoes"]
return [
{"id": "anatomy-proportion", "name": "Head-unit proportions and pose", "tier": "critical",
"passIds": ["blockout", "proportion-lock"], "minimumScore": 0.78, "mustPass": True,
- "componentRefs": ["root", "head", "torso"], "evidenceRefs": ["full-object"]},
- {"id": "face-landmark-placement", "name": "Face landmarks + glasses placement", "tier": "critical",
+ "componentRefs": ["root", "head", "chest"], "evidenceRefs": ["full-object"]},
+ {"id": "face-landmark-placement", "name": "Face landmarks incl. recessed eye sockets", "tier": "critical",
"passIds": ["feature-placement"], "minimumScore": 0.75, "mustPass": True,
- "componentRefs": ["head", "glasses-frame-l"], "evidenceRefs": ["full-object"]},
- {"id": "pose-silhouette", "name": "Pose and bust silhouette", "tier": "critical",
+ "componentRefs": ["head", "eye-l", "eye-cavity-l", "nose"], "evidenceRefs": ["full-object"]},
+ {"id": "pose-silhouette", "name": "Pose and full-body silhouette", "tier": "critical",
"passIds": ["blockout", "proportion-lock"], "minimumScore": 0.75, "mustPass": True,
- "componentRefs": ["root", "arm-l"], "evidenceRefs": ["full-object"]},
+ "componentRefs": ["root", "upper-arm-l", "thigh-l"], "evidenceRefs": ["full-object"]},
{"id": "outfit-and-palette", "name": "Outfit + accessories + palette", "tier": "important",
"passIds": ["material-pass"], "minimumScore": 0.7, "mustPass": False,
- "componentRefs": ["shirt-decal", "headphone", "glasses-frame-l"], "evidenceRefs": ["full-object"]},
+ "componentRefs": outfit_refs, "evidenceRefs": ["full-object"]},
]
-def apply_character_template(spec: dict, anatomy: dict | None = None) -> dict:
+# Components that are body SEGMENTS and therefore become bones, but carry no
+# `attachment` block to derive a segment from (they are not capsules/cylinders).
+# Everything else without an attachment block -- brows, nose, mouth, hair, eyes,
+# eye cavities, lenses, decals -- rides its parent bone and is deliberately NOT a
+# bone: a brow does not articulate.
+_RIG_STRUCTURAL_LEAVES = {"pelvis", "head", "hand-l", "hand-r", "foot-l", "foot-r"}
+
+_RIG_CHAINS = (
+ # Digits are checked BEFORE the arm prefixes. They do not collide today, but a future
+ # "hand-thumb-*" id would match "hand-" first and land in the wrong chain.
+ (("thumb-", "index-", "middle-", "ring-", "little-"), "digit"),
+ (("clavicle-", "upper-arm-", "forearm-", "hand-"), "arm"),
+ (("thigh-", "shin-", "foot-"), "leg"),
+ (("neck", "head"), "head"),
+ (("chest", "abdomen", "pelvis"), "spine"),
+)
+
+
+def _rig_chain_of(component_id: str) -> str:
+ for prefixes, chain in _RIG_CHAINS:
+ for prefix in prefixes:
+ if component_id == prefix or component_id.startswith(prefix):
+ return chain
+ return "prop"
+
+
+def derive_character_rig(component_tree: list) -> dict:
+ """Derive a PLAN_1.5 §6 `RigSpec` from the component tree instead of authoring one.
+
+ Deriving rather than authoring is the point: a hand-written skeleton and a
+ hand-written component tree drift the moment either is edited, and nothing
+ detects the drift. Everything below comes from data the tree already carries.
+
+ Three decisions that are choices rather than facts, recorded here because the
+ next person cannot re-derive them from the code alone:
+
+ 1. **Every position is MODEL space, and a bone's tip is its child's joint.**
+ `attachment.localEnd` looks like the obvious tip and is NOT used, because it
+ is right for limbs and wrong for the spine: a limb component's origin IS its
+ proximal joint, but the torso's origin is its centre, so reading localEnd
+ there produced a spine bone running from the chest DOWN past the pelvis --
+ which would have pulled leg vertices onto the torso's weight. PLAN_1.5 §6's
+ "tipPos defaults to the child's jointPos" is the right rule but is
+ meaningless parent-local (a parent's tip and its child's joint sit in
+ different frames), so everything is accumulated into one space first.
+
+ 2. **`pelvis` is the single bone root, with `torso` parented to it.** A
+ `RigSpec` requires exactly one root, and the component tree parents BOTH
+ `torso` and `pelvis` to `"root"` (they are siblings there). Hips-as-root is
+ the standard humanoid convention and it is the one that makes rotating the
+ pelvis bend the whole figure. This makes the bone hierarchy deliberately
+ differ from the pivot hierarchy at exactly one edge, which PLAN_1.5 §8
+ ("bones and pivots coexist") explicitly permits.
+
+ 3. **A leaf bone continues its parent's direction** for its own `scale.y`,
+ rather than being given an invented orientation. Known simplification: a
+ foot therefore points down the shin rather than forward. That is wrong
+ anatomically and right for weighting, and it is derived rather than
+ guessed -- flagged so a real foot orientation can replace it deliberately.
+ """
+ by_id = {c["id"]: c for c in component_tree if isinstance(c, dict) and c.get("id")}
+
+ def is_bone(component: dict) -> bool:
+ return bool(component.get("attachment")) or component["id"] in _RIG_STRUCTURAL_LEAVES
+
+ bone_ids = [cid for cid, c in by_id.items() if is_bone(c)]
+
+ def bone_parent(component_id: str) -> str | None:
+ # Walk up the component tree until a component that is itself a bone is
+ # found, so a bone parented through a non-bone (a detail) still attaches
+ # to the nearest real segment rather than falling out of the hierarchy.
+ parent = by_id.get(component_id, {}).get("parent")
+ while parent and parent != "root":
+ if parent in bone_ids:
+ return parent
+ parent = by_id.get(parent, {}).get("parent")
+ if component_id == "pelvis":
+ return None # the single root
+ return None
+
+ children = {cid: [] for cid in bone_ids}
+ for _cid in bone_ids:
+ _parent = bone_parent(_cid)
+ if _parent in children:
+ children[_parent].append(_cid)
+
+ # A branching bone's tip is its SPINE-WARD child's joint. `pelvis` has three bone children
+ # (abdomen + both thighs) and `chest` has three (neck + both arms), so §6's single-child
+ # default does not apply and rig_spec.resolve_tip_positions() would reject them; naming the
+ # spine-ward child is an explicit choice rather than picking an arbitrary one.
+ _SPINE_WARD = {
+ "chest": "neck", "abdomen": "chest", "pelvis": "abdomen",
+ # A hand has five bone children since US-003, so it needs a named tip too. The hand's
+ # axis runs to the middle finger, so that digit's proximal phalanx is the anatomical
+ # choice rather than whichever digit happens to sort first.
+ "hand-l": "middle-l-1", "hand-r": "middle-r-1",
+ }
+
+ # No joint override is needed any more. It used to be, because the single `torso` component
+ # was anchored at its CENTRE, so reading its own position as a joint produced a spine bone
+ # running from the chest DOWN past the pelvis. Splitting the spine into abdomen + chest and
+ # anchoring each at its PROXIMAL end -- exactly how limbs were already authored -- makes a
+ # component's origin its own joint everywhere, so `hip_top()` and the torso exception are
+ # gone. Getting the anatomy right removed the special case rather than adding one.
+ def joint_of(component_id: str) -> list:
+ return model_pos(component_id)
+
+ def explicit_tip(component_id: str) -> list | None:
+ return None
+
+ def model_pos(component_id: str) -> list:
+ """Accumulate parent-local offsets into MODEL space.
+
+ Summing offsets instead of composing matrices is exact under TWO preconditions, and
+ both are checked rather than assumed, because a silent violation would move every
+ descendant joint without anything failing:
+
+ 1. **No cascading non-uniform scale.** Holds because pivot Groups always carry identity
+ scale now (WS-E); the component's dimensions live in its geometry.
+ 2. **No rotation on any ancestor.** A rotated ancestor rotates its children's offsets,
+ which a sum cannot represent. This holds at BIND POSE and is exactly what applying
+ `anatomy.pose.jointAngles` would break — hence the fail-closed check below, and
+ hence `apply_character_pose()` must run AFTER this function, never before.
+ """
+ total = [0.0, 0.0, 0.0]
+ cursor = component_id
+ while cursor and cursor != "root":
+ component = by_id.get(cursor)
+ if not component:
+ break
+ transform = component.get("transform") or {}
+ rotation = transform.get("rotation") or [0.0, 0.0, 0.0]
+ if any(abs(float(v)) > 1e-9 for v in rotation):
+ raise ValueError(
+ f"cannot derive a rig through rotated component {cursor!r} "
+ f"(rotation={rotation}): a bone's joint is accumulated by summing "
+ f"parent-local offsets, which is only valid at bind pose. Derive the rig "
+ f"BEFORE applying pose rotations."
+ )
+ position = transform.get("position") or [0.0, 0.0, 0.0]
+ for i in range(3):
+ total[i] += float(position[i])
+ cursor = component.get("parent")
+ return total
+
+ def segment(component_id: str) -> tuple[list, list]:
+ component = by_id[component_id]
+ joint = joint_of(component_id)
+ override = explicit_tip(component_id)
+ if override is not None:
+ return joint, override
+ kids = children.get(component_id, [])
+ preferred = _SPINE_WARD.get(component_id)
+ if preferred and preferred in kids:
+ return joint, joint_of(preferred)
+ if len(kids) == 1:
+ return joint, joint_of(kids[0]) # the §6 default, now well-defined
+ transform = component.get("transform") or {}
+ position = joint
+ length = float((transform.get("scale") or [0.0, 0.0, 0.0])[1])
+ parent = bone_parent(component_id)
+ direction = [0.0, -1.0, 0.0]
+ if parent: # decision 3
+ p_start, p_end = segment(parent)
+ delta = [p_end[i] - p_start[i] for i in range(3)]
+ norm = sum(d * d for d in delta) ** 0.5
+ if norm > 1e-9:
+ direction = [d / norm for d in delta]
+ return position, [round(position[i] + direction[i] * length, 5) for i in range(3)]
+
+ bones = []
+ for cid in bone_ids:
+ joint, tip = segment(cid)
+ bones.append({
+ "id": cid,
+ "parent": bone_parent(cid),
+ "jointPos": [round(v, 5) for v in joint],
+ "tipPos": [round(v, 5) for v in tip],
+ "component": cid,
+ "role": "skinned",
+ "chain": _rig_chain_of(cid),
+ })
+ bones.sort(key=lambda b: (b["parent"] is not None, b["id"]))
+ return {"version": "1.0", "bindPose": "A", "forward": "+Z", "bones": bones}
+
+
+# `anatomy.pose.jointAngles` uses anatomical sides: "left" is the CHARACTER's left, which the
+# component tree spells `-l`. On a front-facing reference that is the viewer's right.
+_POSE_JOINT_TO_COMPONENT = {
+ "neck": "neck",
+ "leftShoulder": "upper-arm-l", "rightShoulder": "upper-arm-r",
+ "leftElbow": "forearm-l", "rightElbow": "forearm-r",
+ "leftWrist": "hand-l", "rightWrist": "hand-r",
+ "leftHip": "thigh-l", "rightHip": "thigh-r",
+ "leftKnee": "shin-l", "rightKnee": "shin-r",
+ "leftAnkle": "foot-l", "rightAnkle": "foot-r",
+}
+
+
+def apply_character_pose(component_tree: list, anatomy: dict | None) -> list[str]:
+ """Apply `anatomy.pose.jointAngles` as component rotations. Returns the joints applied.
+
+ Why this is worth having even though skinning (WS-C) is unfinished: posing a hierarchy of
+ RIGID segments needs no skeleton at all. It needs a real parent chain that propagates
+ rotation, which the template now has and which has been measured on executed geometry.
+ Skinning buys smooth deformation ACROSS a joint; it is not what makes a limb move. So a
+ reference pose (a contrapposto, an arm resting on a sword) is reachable now, and treating
+ pose as blocked on skinning was wrong.
+
+ Before this, `pose.jointAngles` was declared in two places and consumed in none -- the same
+ "accepted but silently unused" state `anatomy.proportions` was in before `_hu_ratio()`.
+
+ MUST run AFTER `derive_character_rig()`. That function accumulates joints by summing
+ parent-local offsets, which is only valid while every ancestor rotation is identity -- i.e.
+ at bind pose. It now raises rather than silently mis-deriving if called on a posed tree, so
+ the ordering is enforced, not merely documented. The rig stays bind-pose data, which is what
+ a skeleton is.
+ """
+ pose = ((anatomy or {}).get("pose") or {})
+ angles = pose.get("jointAngles") or {}
+ if not angles:
+ return []
+ by_id = {c["id"]: c for c in component_tree if isinstance(c, dict) and c.get("id")}
+ applied: list[str] = []
+ for joint, component_id in _POSE_JOINT_TO_COMPONENT.items():
+ value = angles.get(joint)
+ if not (isinstance(value, list) and len(value) == 3):
+ continue
+ if not any(abs(float(v)) > 1e-9 for v in value):
+ continue
+ component = by_id.get(component_id)
+ if component is None:
+ continue
+ transform = component.setdefault("transform", {})
+ transform["rotation"] = [float(v) for v in value]
+ applied.append(f"{joint}->{component_id}")
+ return applied
+
+
+def apply_character_template(
+ spec: dict,
+ anatomy: dict | None = None,
+ include_accessories: bool = False,
+) -> dict:
"""Swap in the humanoid componentTree, character materials, build passes, and feature
targets. Object specs are untouched; only called when primaryDomain is character/hybrid."""
- spec["componentTree"] = make_character_component_tree(anatomy)
+ spec["componentTree"] = make_character_component_tree(anatomy, include_accessories)
+ # Derived, never authored -- see derive_character_rig()'s docstring. Kept in step with
+ # the component tree by construction, so the skeleton cannot drift away from the parts.
+ spec["rig"] = derive_character_rig(spec["componentTree"])
+ # Strictly after the rig: a skeleton is bind-pose data, and derive_character_rig() now
+ # raises if handed a posed tree rather than mis-deriving it quietly.
+ posed = apply_character_pose(spec["componentTree"], anatomy)
+ if posed:
+ spec["rig"]["posedJoints"] = posed
+ object_class = spec.setdefault("preSpecAssessment", {}).setdefault("objectClass", {})
+ object_class["primaryDomain"] = "character"
existing = {m.get("id"): m for m in spec.get("materials", []) if isinstance(m, dict)}
- for mat in CHARACTER_MATERIALS:
+ character_materials = CHARACTER_BASE_MATERIALS + (CHARACTER_ACCESSORY_MATERIALS if include_accessories else [])
+ for mat in character_materials:
merged = dict(existing.get("base", {}))
merged.update(mat)
merged.setdefault("name", mat["id"])
@@ -447,7 +1161,7 @@ def apply_character_template(spec: dict, anatomy: dict | None = None) -> dict:
all_ids = [c["id"] for c in spec["componentTree"] if isinstance(c, dict) and c.get("id")]
for build_pass in spec["buildPasses"]:
build_pass["componentRefs"] = all_ids
- spec["featureReviewTargets"] = make_character_feature_targets()
+ spec["featureReviewTargets"] = make_character_feature_targets(include_accessories)
pipeline = spec.setdefault("sculptPipeline", {})
pipeline["passOrder"] = [p["id"] for p in spec["buildPasses"]]
pipeline["currentPass"] = "blockout"
@@ -1558,6 +2272,8 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No
}
if local_spec_search is not None:
spec["localSpecSearch"] = local_spec_search
+ if assessment_payload and isinstance(assessment_payload.get("pipelineRouting"), dict):
+ spec["pipelineRouting"] = assessment_payload["pipelineRouting"]
inject_geometry_rules(spec, target_name)
return spec
@@ -1572,6 +2288,9 @@ def main(argv: list[str]) -> int:
parser.add_argument("--force", action="store_true", help="Overwrite output file")
parser.add_argument("--character", action="store_true",
help="Use the humanoid character template (auto-enabled when the assessment primaryDomain is character/hybrid)")
+ parser.add_argument("--accessories", action="store_true",
+ help="Character template only: add the opt-in accessory set (glasses, headphones, chest "
+ "decal). Off by default so the baseline humanoid carries no reference-person traits.")
parser.add_argument("--cs2", action="store_true",
help="Use the CS2 weapon-skin finish profile (image-first; auto-enabled when the assessment objectClass.cs2 is true)")
parser.add_argument("--finish-style", choices=CS2_FINISH_STYLES, default=None,
@@ -1609,7 +2328,33 @@ def main(argv: list[str]) -> int:
oc = pre.get("objectClass", {}) if isinstance(pre, dict) else {}
domain = oc.get("primaryDomain") if isinstance(oc, dict) else None
cs2_marker = bool(oc.get("cs2")) if isinstance(oc, dict) else False
- if args.cs2 or cs2_marker or manifest is not None:
+ incoming_routing = assessment.get("pipelineRouting") if isinstance(assessment, dict) else None
+ incoming_classification = incoming_routing.get("classification") if isinstance(incoming_routing, dict) else None
+ explicit_track = "character-v1.5" if args.character or domain in {"character", "hybrid"} else None
+ if explicit_track is None and (args.cs2 or cs2_marker):
+ explicit_track = "weapon-v1.4"
+ legacy_cs2 = manifest is not None and not isinstance(manifest.get("pipelineRouting"), dict)
+ if manifest is not None and isinstance(manifest.get("pipelineRouting"), dict):
+ incoming_classification = manifest["pipelineRouting"].get("classification")
+ if args.character and (args.cs2 or manifest is not None) and incoming_classification is None:
+ incoming_classification = {
+ "kind": "weapon",
+ "confidence": 1.0,
+ "evidenceRefs": ["pipeline-routing:explicit:weapon-v1.4"],
+ "provider": "pipeline-routing-cli",
+ "version": "1",
+ }
+ routing = None
+ if explicit_track is not None or incoming_classification is not None or legacy_cs2:
+ routing = resolve_pipeline_routing(
+ explicit_track=explicit_track,
+ classification=incoming_classification,
+ legacy_cs2=legacy_cs2,
+ )
+ spec["pipelineRouting"] = routing
+ if routing["status"] != "resolved":
+ parser.error("pipeline routing requires input: " + "; ".join(routing["conflicts"]))
+ if routing is not None and routing["track"] == "weapon-v1.4":
finish_style = args.finish_style
if finish_style is None and isinstance(assessment, dict):
oc = assessment.get("preSpecAssessment", {}).get("objectClass", {})
@@ -1628,11 +2373,11 @@ def main(argv: list[str]) -> int:
)
if manifest:
apply_cs2_manifest_evidence(spec, manifest)
- elif args.character or domain in {"character", "hybrid"}:
+ elif routing is not None and routing["track"] == "character-v1.5":
anatomy = None
if isinstance(assessment, dict) and isinstance(assessment.get("preSpecAssessment"), dict):
anatomy = assessment["preSpecAssessment"].get("anatomy")
- apply_character_template(spec, anatomy)
+ apply_character_template(spec, anatomy, include_accessories=args.accessories)
payload = json.dumps(spec, indent=2, ensure_ascii=False) + "\n"
if args.out:
diff --git a/forge/stage2_spec/validate_sculpt_spec.py b/forge/stage2_spec/validate_sculpt_spec.py
old mode 100755
new mode 100644
index 2df7e8a..3734814
--- a/forge/stage2_spec/validate_sculpt_spec.py
+++ b/forge/stage2_spec/validate_sculpt_spec.py
@@ -11,7 +11,18 @@ from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage3_build"))
from feature_acceptance_policy import feature_gate_failures, feature_review_policy
+from sdf_primitives import validate_sdf_descriptor
+from subdivision import (
+ ATTACHMENT_CYLINDER_SUBDIVISION_SOURCE_FACES,
+ MAX_SUBDIVISION_ITERATIONS,
+ MAX_SUBDIVISION_QUAD_FACES,
+ resolve_instanced_cluster_base,
+ SUBDIVISION_SOURCE_FACE_ESTIMATES,
+)
+from visual_hull import validate_visual_hull_descriptor
+from pipeline_routing import resolve_pipeline_routing, validate_pipeline_routing
REQUIRED_TOP_LEVEL = {
@@ -51,6 +62,17 @@ VALID_TOPOLOGY_CLASSES = {
"surface-relief",
"fiber-strand",
"material-only",
+ "implicit",
+ # Plan 1.5: a zero-thickness, two-sided surface -- a wing membrane, a cape, a leaf,
+ # a fin. None of the other seven classes fit: it is not a volume (assembled-solid /
+ # continuous-sculpt / implicit all describe solids), and it is not relief carved into
+ # a host surface (surface-relief / conforming-shell). Before this class existed such a
+ # part had to be routed through `implicit`, but an SDF is a distance field to a
+ # *volume boundary* and cannot represent true zero thickness -- it is forced to
+ # thicken the membrane into a thin solid. This is the same field-representation limit
+ # TRELLIS.2's O-Voxel format removes; see docs/RESEARCH_TRELLIS2_TO_IMG2THREEJS.md
+ # section 1.1 and section 4. See validate_open_shell_topology below for what this forbids.
+ "open-shell",
}
CS2_ROUTES = {"reference-projection", "authored-texture", "procedural-finish"}
CS2_EXACTNESS_TIERS = {"image-only", "metadata-assisted", "exact-texture"}
@@ -66,6 +88,190 @@ TOPOLOGY_ALLOWED_HINT = {
}
+# Plan 1.5 — the recessed-feature gate (the US-004 defect: "the eye reads as a patch, not
+# a recessed socket"). This is a spec-authoring failure, not a measurement failure, and it
+# is undetectable downstream: a silhouette gate cannot see an interior concavity (a dimple
+# inside the outline changes no silhouette in any view), and a dark-pixel ratio on a
+# concave feature measures cavity SHADING, not material (the reference ear reads 14.3%
+# "dark" from shading gradient alone, peaking at luminance 60-79, versus the wing's 32.9%
+# near-black from actual material). So this class of defect has to be caught in the schema.
+#
+# How a component declares "recessed": we extend the existing free-text `role` field
+# (already token-matched by ATTACHMENT_ROLES / component_requires_attachment below) rather
+# than invent a parallel boolean field. A spec author names the part's role with one of
+# these tokens (`role: "eye-socket"`, `"ear-canal"`, `"mouth-cavity"`, `"nostril"`, ...);
+# `component.name`/`id` are checked too since components are commonly named after the
+# feature they are. This was chosen over (a) a new `concave: true` field, which would be a
+# second place to encode the same fact `role` already carries and would need its own
+# authoring discipline, and (b) reusing `topologyClass` itself, which describes HOW a part
+# is built, not WHAT it represents -- the whole point of this gate is to compare the two.
+#
+# Token design, revised after review — plain "socket" collides with a DIFFERENT, load-
+# bearing meaning already in this file: ATTACHMENT_ROLES (below) uses bare "socket" for an
+# attachment POINT (`attachment.parentSocket`, `actionProfile.sockets[]`), e.g. a handle's
+# hilt socket. That is a real, common authoring case and is not a concavity, so bare
+# "socket" is deliberately NOT a recessed-feature token. Instead we match the specific
+# compound "eyesocket" as a normalized substring (hyphens/spaces/underscores stripped, so
+# `role: "eye-socket"`, `"eye_socket"`, and `"eye socket"` all match) -- narrower than a
+# bare word, so it cannot fire on a plain attachment socket. "hollow" and "concave" are
+# real words but too easily legitimate outside a cavity context ("hollow tube", "concave
+# lens" are both real, non-recessed parts), so they are matched against `role` ONLY, never
+# against `name`/`id`, keeping them out of reach of incidental part-naming collisions.
+# "dimple" was dropped entirely: a dimple is shallow by definition, so it is the wrong word
+# to hold to a depth-requiring rule (below) in the first place.
+#
+# THE CONTRACT, spelled out because the rule below is now strict (allow-list: implicit +
+# subtract, nothing else) and that strictness needs to be a stated trade, not a trap:
+# the token IS the declaration. If a component's role/name/id calls it a cavity, canal, or
+# recess, this rule holds it to building a REAL one. A shallow decorative relief -- a 0.2mm
+# panel line, a knurl pattern -- is not a cavity; do not name it one. Rename it instead
+# (e.g. `panel-relief`, `groove-relief`) and it is untouched by this gate, free to be
+# `surface-relief` or any other topologyClass. That is the legitimate way out, and
+# `test_shallow_relief_panel_without_a_cavity_token_is_accepted` in
+# forge/tests/test_recessed_and_open_shell_topology.py proves it actually works.
+RECESSED_FEATURE_TOKENS = {"cavity", "canal", "recess", "recessed", "nostril"}
+RECESSED_FEATURE_COMPOUND_PHRASES = {"eyesocket"}
+RECESSED_FEATURE_ROLE_ONLY_TOKENS = {"hollow", "concave"}
+# A recessed feature is real concavity: it must be carved out of a volume (`implicit` +
+# an SDF `subtract` operation -- see sdf_primitives.VALID_SDF_OPERATIONS). This is
+# deliberately an ALLOW-list (state the one right shape), not a deny-list (enumerate every
+# wrong one), after review found that a deny-list of {"surface-relief", "plane-card"} still
+# let a THIRD route to the exact same US-004 defect through: `topologyClass:
+# "assembled-solid"` + a convex sphere primitive is not surface-relief, is not plane-card,
+# and never reaches the subtract check below (which was scoped to `implicit`) -- yet it is
+# exactly a convex ball sitting where a recess belongs, and `assembled-solid` + sphere is
+# the MOST likely authoring mistake of the three, since assembled-solid is the common
+# default and a sphere is the obvious eye shape. A deny-list has to predict every wrong
+# answer and a fourth route always remains possible; an allow-list only has to state the
+# right one, so it closes all of them at once.
+RECESSED_FEATURE_REQUIRED_TOPOLOGY = "implicit"
+
+
+def component_role_tokens(component: dict[str, Any]) -> set[str]:
+ """Same tokenization ATTACHMENT_ROLES matching uses: lowercase, split on non-alphanumerics,
+ across role/name/id so a part authored as e.g. `id: "left-eye-socket"` is caught even if
+ `role` itself is generic or absent. Fields are joined with a literal space, which also
+ acts as the token separator, so a word split across two fields (role="fake eye", name=
+ "socket-thing") can never merge into one token here."""
+ role = str(component.get("role") or "")
+ name = str(component.get("name") or "")
+ component_id = str(component.get("id") or "")
+ return set(re.findall(r"[a-z0-9]+", f"{role} {name} {component_id}".lower()))
+
+
+def _normalize_identity_field(value: Any) -> str:
+ return re.sub(r"[\s_-]+", "", str(value or "").lower())
+
+
+def component_recessed_feature_matches(component: dict[str, Any]) -> set[str]:
+ """Return which recessed-feature signal(s) fired, for both the boolean gate and the
+ error message. Compound phrases are checked per-field (role, name, id separately, never
+ concatenated) so a phrase can never assemble itself across a field boundary."""
+ matches = component_role_tokens(component) & RECESSED_FEATURE_TOKENS
+ normalized_fields = (
+ _normalize_identity_field(component.get("role")),
+ _normalize_identity_field(component.get("name")),
+ _normalize_identity_field(component.get("id")),
+ )
+ matches |= {
+ phrase
+ for phrase in RECESSED_FEATURE_COMPOUND_PHRASES
+ if any(phrase in field for field in normalized_fields)
+ }
+ role_tokens = set(re.findall(r"[a-z0-9]+", str(component.get("role") or "").lower()))
+ matches |= role_tokens & RECESSED_FEATURE_ROLE_ONLY_TOKENS
+ return matches
+
+
+def component_is_recessed_feature(component: dict[str, Any]) -> bool:
+ return bool(component_recessed_feature_matches(component))
+
+
+def validate_recessed_feature_topology(component_id: str, component: dict[str, Any], errors: list[str]) -> None:
+ matches = component_recessed_feature_matches(component)
+ if not matches:
+ return
+ topology_class = component.get("topologyClass")
+ primitive = component.get("primitive")
+ if topology_class != RECESSED_FEATURE_REQUIRED_TOPOLOGY:
+ errors.append(
+ f"component {component_id!r} is authored as a recessed feature (role/name/id matches "
+ f"{', '.join(sorted(matches))!r}) but is "
+ f"topologyClass={topology_class!r} primitive={primitive!r} -- a recessed feature must be real "
+ "concavity carved OUT of a volume, not this shape or relief (a convex primitive, a flat "
+ "plane-card, and a surface-relief bump are all the same US-004 defect: an eye that reads as a "
+ "patch, not a recess) -- reclassify as topologyClass 'implicit' with a geometryDescriptor.sdf "
+ "whose operations include 'subtract' to carve the cavity out of the parent volume "
+ "(see forge/_shared/sdf_primitives.py VALID_SDF_OPERATIONS)"
+ )
+ return
+ # A rule should verify what it advises: the message above tells the author to use
+ # `implicit` + a `subtract` operation, so `implicit` alone is not enough -- an implicit
+ # component built ONLY from union/smooth-union operations is a bulge sticking OUT of its
+ # parent, not a cavity carved INTO it. That is the same US-004 defect (an eye that reads
+ # as a patch, not a recess) wearing a different disguise, and this gate would otherwise
+ # wave it through. `subtract` must be PRESENT among the operations, not the only one --
+ # a socket legitimately built by smooth-unioning two shapes and then subtracting the
+ # result is fine. If `geometryDescriptor.sdf` itself is missing, skip: the
+ # `topologyClass 'implicit' requires geometryDescriptor.sdf` check elsewhere already
+ # covers that structural case, so this stays free of a duplicate/confusing error.
+ descriptor = component.get("geometryDescriptor")
+ sdf = descriptor.get("sdf") if isinstance(descriptor, dict) else None
+ if isinstance(sdf, dict):
+ operations = sdf.get("operations")
+ operation_types = (
+ [operation.get("type") for operation in operations if isinstance(operation, dict)]
+ if isinstance(operations, list)
+ else []
+ )
+ if "subtract" not in operation_types:
+ found = ", ".join(sorted({str(item) for item in operation_types})) or "none"
+ errors.append(
+ f"component {component_id!r} is authored as a recessed feature (role/name/id matches "
+ f"{', '.join(sorted(matches))!r}) and is topologyClass 'implicit', but its "
+ f"geometryDescriptor.sdf.operations contain no 'subtract' operation (found: {found}) -- "
+ "a recessed feature must be carved OUT of a volume; building it only from "
+ "union/smooth-union operations produces a bulge sticking OUT, not a cavity, which is "
+ "the same US-004 defect (an eye that reads as a patch, not a recess) in disguise. Add a "
+ "'subtract' operation that removes volume from the parent shape "
+ "(see forge/_shared/sdf_primitives.py VALID_SDF_OPERATIONS)"
+ )
+
+
+# Plan 1.5 — open-shell may not pair with a closed SDF: an SDF is a distance field to a
+# volume boundary and has no way to express zero thickness, so combining `topologyClass:
+# "open-shell"` with `geometryDescriptor.sdf` would silently thicken the membrane into a
+# thin solid, defeating the reason open-shell exists. A double-sided material is required
+# for the same reason a one-sided membrane renders invisible from behind: Three.js
+# backface-culls a single-sided material, and an open-shell part is, by definition, seen
+# from both sides.
+def validate_open_shell_topology(
+ component_id: str,
+ component: dict[str, Any],
+ materials_by_id: dict[str, dict[str, Any]],
+ errors: list[str],
+) -> None:
+ if component.get("topologyClass") != "open-shell":
+ return
+ descriptor = component.get("geometryDescriptor")
+ if isinstance(descriptor, dict) and "sdf" in descriptor:
+ errors.append(
+ f"component {component_id!r} topologyClass 'open-shell' cannot combine with "
+ "geometryDescriptor.sdf -- an SDF is a closed distance field and cannot represent zero "
+ "thickness, so it would silently thicken the membrane into a thin solid; drop the sdf "
+ "descriptor and build the open-shell surface directly (e.g. plane-card, curve-sweep, or "
+ "extrude)"
+ )
+ material_id = component.get("material")
+ material = materials_by_id.get(material_id) if isinstance(material_id, str) else None
+ if not isinstance(material, dict) or material.get("doubleSided") is not True:
+ errors.append(
+ f"component {component_id!r} topologyClass 'open-shell' is a zero-thickness two-sided "
+ f"surface but its material {material_id!r} does not set doubleSided: true -- a one-sided "
+ "membrane renders invisible from behind; set materials[].doubleSided = true on its material"
+ )
+
+
# Plan 1.3 G.1 — spec-level flatness gate (the karambit-blade defect signature).
# The robust discriminator is SEMANTIC, not a fragile geometric curvature estimate:
# `continuous-sculpt` asserts "a continuous volumetric 3D form", so pairing it with a
@@ -454,6 +660,28 @@ def validate_cs2_contract(spec: dict[str, Any], errors: list[str], warnings: lis
errors.append("procedural-finish cannot claim exact-texture")
+def validate_pipeline_routing_contract(spec: dict[str, Any], errors: list[str]) -> None:
+ routing = spec.get("pipelineRouting")
+ legacy_cs2 = routing is None and spec.get("cs2Intake") is not None
+ if routing is None:
+ if spec.get("cs2Intake") is None:
+ return
+ routing = resolve_pipeline_routing(legacy_cs2=True)
+ routing_errors = validate_pipeline_routing(routing)
+ errors.extend(routing_errors)
+ if not isinstance(routing, dict) or routing.get("status") != "resolved":
+ errors.append("pipelineRouting must be resolved before validation")
+ return
+ routing_track = routing.get("track")
+ object_class = spec.get("preSpecAssessment", {}).get("objectClass", {})
+ if routing_track == "character-v1.5" and spec.get("cs2Intake") is not None:
+ errors.append("character-v1.5 routing cannot carry cs2Intake")
+ if routing_track == "character-v1.5" and object_class.get("primaryDomain") not in {"character", "hybrid"}:
+ errors.append("character-v1.5 routing requires the character template")
+ if routing_track == "weapon-v1.4" and not legacy_cs2 and object_class.get("cs2") is not True:
+ errors.append("weapon-v1.4 routing requires the CS2 weapon template")
+
+
def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> set[str]:
material_ids: set[str] = set()
for index, material in enumerate(spec.get("materials", [])):
@@ -474,6 +702,9 @@ def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[s
value = material.get(field)
if value is not None and not isinstance(value, str):
errors.append(f"material {material_id!r} {field} must be a string")
+ double_sided = material.get("doubleSided")
+ if double_sided is not None and not isinstance(double_sided, bool):
+ errors.append(f"material {material_id!r} doubleSided must be boolean")
for field in ("albedo", "ambientOcclusion"):
value = material.get(field)
if value is not None and not isinstance(value, dict):
@@ -550,6 +781,42 @@ def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[s
return material_ids
+def validate_material_pipeline_contract(spec: dict[str, Any], material_ids: set[str], errors: list[str], warnings: list[str]) -> None:
+ """Validate the optional v1.5 material-reference hand-off.
+
+ Legacy specs remain valid. Once ``materialPipeline`` is present, every
+ analyzed region must point at a real spec material and retain evidence.
+ """
+ pipeline = spec.get("materialPipeline")
+ if pipeline is None:
+ return
+ if not isinstance(pipeline, dict):
+ errors.append("materialPipeline must be an object")
+ return
+ if pipeline.get("schemaVersion") != 1:
+ errors.append("materialPipeline.schemaVersion must be 1")
+ status = pipeline.get("status")
+ if status not in {"proceed", "probe"}:
+ errors.append("materialPipeline.status must be proceed or probe")
+ regions = pipeline.get("regions")
+ if not isinstance(regions, list) or not regions:
+ errors.append("materialPipeline.regions must be a non-empty array")
+ return
+ for index, region in enumerate(regions):
+ if not isinstance(region, dict):
+ errors.append(f"materialPipeline.regions[{index}] must be an object")
+ continue
+ material_id = region.get("specMaterialId")
+ if material_id not in material_ids:
+ errors.append(f"materialPipeline region {region.get('regionId')!r} references unknown material {material_id!r}")
+ for field in ("componentId", "regionId", "profileId"):
+ if not isinstance(region.get(field), str) or not region[field].strip():
+ errors.append(f"materialPipeline.regions[{index}].{field} is required")
+ registry = pipeline.get("registry")
+ if not isinstance(registry, str) or not registry.strip():
+ errors.append("materialPipeline.registry is required")
+ elif not registry.endswith("material-reference.json"):
+ warnings.append("quality: materialPipeline.registry does not point to material-reference.json")
def validate_dimensions(component_id: str, dimensions: Any, errors: list[str]) -> None:
if dimensions is None:
return
@@ -586,6 +853,121 @@ def validate_geometry_descriptor(component_id: str, descriptor: Any, errors: lis
stack = descriptor.get("deformationStack")
if stack is not None and not isinstance(stack, list):
errors.append(f"component {component_id!r} geometryDescriptor.deformationStack must be an array")
+ subdivide = descriptor.get("subdivide")
+ if subdivide is not None:
+ if not isinstance(subdivide, dict):
+ errors.append(f"component {component_id!r} geometryDescriptor.subdivide must be an object")
+ elif "iterations" in subdivide:
+ iterations = subdivide["iterations"]
+ label = f"component {component_id!r} geometryDescriptor.subdivide.iterations"
+ if not isinstance(iterations, int) or isinstance(iterations, bool) or iterations < 0:
+ errors.append(f"{label} must be a non-negative integer")
+ elif iterations > MAX_SUBDIVISION_ITERATIONS:
+ errors.append(f"{label} must not exceed {MAX_SUBDIVISION_ITERATIONS}")
+ decimate = descriptor.get("decimate")
+ if decimate is not None:
+ label = f"component {component_id!r} geometryDescriptor.decimate"
+ if not isinstance(decimate, dict):
+ errors.append(f"{label} must be an object")
+ else:
+ ratio = decimate.get("targetRatio")
+ if isinstance(ratio, bool) or not isinstance(ratio, (int, float)):
+ errors.append(f"{label}.targetRatio must be a number")
+ elif not 0.0 < float(ratio) < 1.0:
+ # 1.0 is rejected rather than treated as a no-op: asking to keep everything is
+ # almost always a mistaken ratio, and paying for a quadric pass that removes
+ # nothing is worse than being told.
+ errors.append(f"{label}.targetRatio must be greater than 0 and less than 1")
+ uv_strategy = str(descriptor.get("uvStrategy") or "")
+ if "unwrap" in uv_strategy.lower() or "authored" in uv_strategy.lower():
+ # Decimation keeps `position` and recomputes normals; a quadric collapse has no
+ # correct answer for an authored UV at the merged vertex, so the seam would move.
+ errors.append(
+ f"{label} cannot combine with an authored/unwrapped uvStrategy "
+ f"({uv_strategy!r}); decimation keeps position only and drops UVs"
+ )
+ if "sdf" in descriptor:
+ validate_sdf_descriptor(component_id, descriptor["sdf"], errors)
+ if "visualHull" in descriptor:
+ validate_visual_hull_descriptor(component_id, descriptor["visualHull"], errors)
+ if "sdf" in descriptor and "visualHull" in descriptor:
+ errors.append(f"component {component_id!r} geometryDescriptor cannot combine sdf and visualHull")
+ if "visualHull" in descriptor and "subdivide" in descriptor:
+ errors.append(f"component {component_id!r} geometryDescriptor.visualHull cannot combine with subdivide")
+
+
+def attachment_emits_cylinder(attachment: Any) -> bool:
+ if not isinstance(attachment, dict):
+ return False
+ start = attachment.get("localStart")
+ end = attachment.get("localEnd")
+ start_vector = start if as_number_list(start, 3) else [0, 0, 0]
+ end_vector = end if as_number_list(end, 3) else [0, 1, 0]
+ return sum((float(end_vector[index]) - float(start_vector[index])) ** 2 for index in range(3)) > 0.0001**2
+
+
+def emitted_subdivision_primitive(primitive: str, topology_class: Any, descriptor: dict[str, Any]) -> str:
+ if topology_class == "implicit":
+ return "implicit sdf"
+ return resolve_instanced_cluster_base(primitive, descriptor, VALID_PRIMITIVES)
+
+
+def validate_subdivision_budget(
+ component_id: str,
+ primitive: Any,
+ topology_class: Any,
+ descriptor: Any,
+ attachment: Any,
+ errors: list[str],
+) -> None:
+ if not isinstance(primitive, str) or not isinstance(descriptor, dict):
+ return
+ subdivide = descriptor.get("subdivide")
+ if not isinstance(subdivide, dict):
+ return
+ iterations = subdivide.get("iterations")
+ if (
+ not isinstance(iterations, int)
+ or isinstance(iterations, bool)
+ or iterations < 1
+ or iterations > MAX_SUBDIVISION_ITERATIONS
+ ):
+ return
+ emitted_primitive = emitted_subdivision_primitive(primitive, topology_class, descriptor)
+ if emitted_primitive == "implicit sdf":
+ errors.append(
+ f"component {component_id!r} geometryDescriptor.subdivide.iterations cannot statically budget "
+ "emitted primitive 'implicit sdf'; subdivision is unsupported for this generator path"
+ )
+ return
+ if emitted_primitive == "plane-card":
+ errors.append(
+ f"component {component_id!r} geometryDescriptor.subdivide.iterations plane-card subdivision topology is unsupported "
+ "because generated PlaneGeometry has open boundary edges"
+ )
+ return
+ uses_attachment_cylinder = attachment_emits_cylinder(attachment)
+ if emitted_primitive == "torus" and not uses_attachment_cylinder:
+ errors.append(
+ f"component {component_id!r} geometryDescriptor.subdivide.iterations torus subdivision topology is unsupported "
+ "because generated TorusGeometry has an open weld seam"
+ )
+ return
+ source_faces = ATTACHMENT_CYLINDER_SUBDIVISION_SOURCE_FACES if uses_attachment_cylinder else SUBDIVISION_SOURCE_FACE_ESTIMATES.get(emitted_primitive)
+ if source_faces is None:
+ errors.append(
+ f"component {component_id!r} geometryDescriptor.subdivide.iterations cannot statically budget "
+ f"emitted primitive {emitted_primitive!r}; subdivision is unsupported for this generator path"
+ )
+ return
+ projected_faces = source_faces * (4**iterations)
+ if projected_faces > MAX_SUBDIVISION_QUAD_FACES:
+ source_label = "attachment cylinder" if uses_attachment_cylinder else f"primitive {emitted_primitive!r}"
+ errors.append(
+ f"component {component_id!r} geometryDescriptor.subdivide.iterations would produce "
+ f"{projected_faces} quad faces for {source_label}, exceeding "
+ f"the maximum {MAX_SUBDIVISION_QUAD_FACES}"
+ )
def validate_bool_object(value: Any, label: str, errors: list[str]) -> None:
@@ -825,6 +1207,11 @@ def validate_components(
warnings: list[str],
) -> None:
components = spec.get("componentTree", [])
+ materials_by_id = {
+ material.get("id"): material
+ for material in spec.get("materials", [])
+ if isinstance(material, dict) and isinstance(material.get("id"), str)
+ }
ids: set[str] = set()
parent_refs: list[tuple[str, str]] = []
for index, component in enumerate(components):
@@ -843,6 +1230,9 @@ def validate_components(
errors.append(
f"component {component_id!r} primitive must be one of: {', '.join(sorted(VALID_PRIMITIVES))}"
)
+ # Plan 1.5: recessed-feature gate runs unconditionally (not schema-version gated like
+ # topologyClass below) -- a flat patch faking a socket is a defect at any schema version.
+ validate_recessed_feature_topology(component_id, component, errors)
if requires_topology_classification(spec):
topology_class = component.get("topologyClass")
topology_rationale = component.get("topologyRationale")
@@ -883,6 +1273,12 @@ def validate_components(
severity, message = flatness_risk(component_id, component)
if severity == "HIGH":
warnings.append(message)
+ if topology_class == "implicit":
+ descriptor = component.get("geometryDescriptor")
+ if not isinstance(descriptor, dict) or "sdf" not in descriptor:
+ errors.append(f"component {component_id!r} topologyClass 'implicit' requires geometryDescriptor.sdf")
+ if topology_class == "open-shell":
+ validate_open_shell_topology(component_id, component, materials_by_id, errors)
level = component.get("level")
if level is not None and level not in VALID_COMPONENT_LEVELS:
errors.append(f"component {component_id!r} level must be macro, meso, or micro")
@@ -900,6 +1296,14 @@ def validate_components(
if material and material not in material_ids:
errors.append(f"component {component_id!r} references unknown material {material!r}")
validate_geometry_descriptor(component_id, component.get("geometryDescriptor"), errors)
+ validate_subdivision_budget(
+ component_id,
+ primitive,
+ component.get("topologyClass"),
+ component.get("geometryDescriptor"),
+ component.get("attachment"),
+ errors,
+ )
material_layers = component.get("materialLayers")
if material_layers is not None:
validate_string_array(material_layers, f"component {component_id!r} materialLayers", errors)
@@ -1883,6 +2287,158 @@ def validate_character_track(spec: dict[str, Any], errors: list[str], warnings:
)
+# PLAN_1.5 §5.2 Half A — the Joint Admission Gate. Pure semantics and arithmetic, which is why it
+# folds into this file rather than becoming a new module: §5.2 says so explicitly, and warns that
+# `forge/stage4_review/geometry_integrity.py` already owns that name. Half B
+# (INSIDE_VOLUME / UNIFORM_BONE_SCALE / NO_PRE_ROTATION) needs real geometry and belongs to a Node
+# script at stage 4, not here.
+SYMMETRY_PARITY_TOLERANCE = 0.05
+POOL_FLOOR_MIN_BONES = 4
+# §5.2 states PROPORTION_LIMIT as "bone length against the head-unit template (e.g. femur <= 2.5
+# HU)". READING CHOSEN: the rig carries no head unit — demanding `anatomy.proportions` would reject
+# the default `--character` template, which has no anatomy block at all — so the limit is expressed
+# as a fraction of the skeleton's own height. That is scale-free and needs no external input. On a
+# 6.78-head figure the plan's 2.5 HU is 2.5/6.78 = 37% of height, so 0.40 sits just above it.
+PROPORTION_LIMIT_FRACTION = 0.40
+
+
+def _mirror_partner(bone_id: str) -> str | None:
+ """`upper-arm-l` -> `upper-arm-r`, `thumb-l-1` -> `thumb-r-1`. None when not a left id.
+
+ Digit ids carry the side in the MIDDLE (`thumb-l-1`), so matching only a trailing `-l` would
+ silently skip all thirty phalanges — the majority of the skeleton.
+ """
+ if bone_id.endswith("-l"):
+ return bone_id[:-2] + "-r"
+ if "-l-" in bone_id:
+ return bone_id.replace("-l-", "-r-", 1)
+ return None
+
+
+def validate_rig_admission(
+ spec: dict[str, Any], errors: list[str], warnings: list[str]
+) -> None:
+ """The five Half-A checks. Runs only when a `rig` is present, so the pivot track is a no-op.
+
+ SYMMETRY_PARITY **snaps** rather than rejects, per §5.2's "On fail" column — an asymmetric
+ pair is a fixable authoring slip, not a broken skeleton. The other four reject.
+ """
+ rig = spec.get("rig")
+ if not isinstance(rig, dict):
+ return
+ bones = [b for b in (rig.get("bones") or []) if isinstance(b, dict) and b.get("id")]
+ if not bones:
+ return
+ by_id = {b["id"]: b for b in bones}
+
+ def joint(bone: dict[str, Any]) -> list[float]:
+ return [float(v) for v in (bone.get("jointPos") or [0.0, 0.0, 0.0])]
+
+ def tip(bone: dict[str, Any]) -> list[float]:
+ return [float(v) for v in (bone.get("tipPos") or [0.0, 0.0, 0.0])]
+
+ def length(bone: dict[str, Any]) -> float:
+ j, t = joint(bone), tip(bone)
+ return sum((t[i] - j[i]) ** 2 for i in range(3)) ** 0.5
+
+ # ---- NAME_UNIQUENESS ----
+ ids = [b["id"] for b in bones]
+ duplicates = sorted({i for i in ids if ids.count(i) > 1})
+ if duplicates:
+ errors.append(f"NAME_UNIQUENESS: duplicate bone id(s) {duplicates}")
+ roots = [b for b in bones if b.get("parent") in (None, "")]
+ if len(roots) != 1:
+ errors.append(
+ f"NAME_UNIQUENESS: exactly one root bone required (parent: null), found {len(roots)}"
+ + (f" ({sorted(b['id'] for b in roots)})" if roots else "")
+ )
+ for bone in bones:
+ parent = bone.get("parent")
+ if parent and parent not in by_id:
+ errors.append(
+ f"NAME_UNIQUENESS: bone {bone['id']!r} has unresolved parent {parent!r}"
+ )
+
+ # ---- POOL_FLOOR ----
+ if len(bones) < POOL_FLOOR_MIN_BONES:
+ errors.append(
+ f"POOL_FLOOR: the skeleton resolves only {len(bones)} bone(s); the weight function "
+ f"keeps four influences per vertex, so fewer than {POOL_FLOOR_MIN_BONES} leaves slots "
+ f"structurally unfillable"
+ )
+
+ # ---- SYMMETRY_PARITY (snap, do not reject) ----
+ for bone in bones:
+ partner_id = _mirror_partner(bone["id"])
+ if not partner_id or partner_id not in by_id:
+ continue
+ left, right = joint(bone), joint(by_id[partner_id])
+ mirrored = [-left[0], left[1], left[2]]
+ delta = max(abs(right[i] - mirrored[i]) for i in range(3))
+ if delta > SYMMETRY_PARITY_TOLERANCE:
+ by_id[partner_id]["jointPos"] = [round(v, 5) for v in mirrored]
+ left_tip = tip(bone)
+ by_id[partner_id]["tipPos"] = [round(v, 5) for v in
+ (-left_tip[0], left_tip[1], left_tip[2])]
+ warnings.append(
+ f"SYMMETRY_PARITY: {partner_id!r} was {delta:.4f} off the mirror of "
+ f"{bone['id']!r} (tolerance {SYMMETRY_PARITY_TOLERANCE}); snapped to the "
+ f"mirrored coordinate rather than rejected"
+ )
+
+ # ---- MONOTONIC_CHAIN ----
+ # §5.2 words this as "cumulative length along a limb chain must increase monotonically; no
+ # bone may fold back through its parent". READING CHOSEN: the operative clause is the second.
+ #
+ # I first implemented the first clause as euclidean distance from the root joint to each tip,
+ # and it REJECTED the correct 49-bone template on ten bones — which is the strongest possible
+ # evidence that a check is mis-specified rather than the model being wrong. The reason is
+ # anatomy: a clavicle reaches 0.70 up at the shoulder, then the upper arm hangs DOWN so its
+ # tip lands at 0.49, back toward the hips. Distance-from-root is legitimately non-monotonic
+ # for any chain that goes out then down. (Read as arc length the clause is trivially true,
+ # since bone lengths are positive, so that cannot be the intent either.)
+ #
+ # So this compares DIRECTION. A bone folds back only when it points substantially opposite
+ # its parent. The threshold is generous on purpose: a thumb sits near 90 degrees to the palm
+ # and must pass, while a genuinely inverted bone sits near 180 and must not.
+ MONOTONIC_CHAIN_OPPOSED_DOT = -0.5 # ~120 degrees apart
+
+ def direction(bone: dict[str, Any]) -> list[float] | None:
+ j, t = joint(bone), tip(bone)
+ delta = [t[i] - j[i] for i in range(3)]
+ norm = sum(d * d for d in delta) ** 0.5
+ return [d / norm for d in delta] if norm > 1e-9 else None
+
+ for bone in bones:
+ parent_id = bone.get("parent")
+ parent = by_id.get(parent_id) if parent_id else None
+ if not parent or parent.get("chain") != bone.get("chain"):
+ continue # a limb leaving the spine is a branch, not a continuation
+ child_dir, parent_dir = direction(bone), direction(parent)
+ if not child_dir or not parent_dir:
+ continue
+ dot = sum(child_dir[i] * parent_dir[i] for i in range(3))
+ if dot < MONOTONIC_CHAIN_OPPOSED_DOT:
+ errors.append(
+ f"MONOTONIC_CHAIN: bone {bone['id']!r} points {dot:.3f} against its parent "
+ f"{parent_id!r} (limit {MONOTONIC_CHAIN_OPPOSED_DOT}) — it folds back through "
+ f"its parent instead of extending the chain"
+ )
+
+ # ---- PROPORTION_LIMIT ----
+ ys = [v for bone in bones for v in (joint(bone)[1], tip(bone)[1])]
+ skeleton_height = max(ys) - min(ys) if ys else 0.0
+ if skeleton_height > 0:
+ limit = skeleton_height * PROPORTION_LIMIT_FRACTION
+ for bone in bones:
+ if length(bone) > limit:
+ errors.append(
+ f"PROPORTION_LIMIT: bone {bone['id']!r} is {length(bone):.4f} long, over "
+ f"{PROPORTION_LIMIT_FRACTION:.0%} of the skeleton's {skeleton_height:.4f} "
+ f"height ({limit:.4f})"
+ )
+
+
def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:
errors: list[str] = []
warnings: list[str] = []
@@ -1909,7 +2465,9 @@ def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:
validate_look_dev_targets(spec, errors, warnings)
evidence_ids = validate_evidence(spec, errors, warnings)
material_ids = validate_materials(spec, errors, warnings)
+ validate_material_pipeline_contract(spec, material_ids, errors, warnings)
validate_cs2_contract(spec, errors, warnings)
+ validate_pipeline_routing_contract(spec, errors)
validate_cs2_view_dependent_environment(spec, errors)
validate_components(spec, material_ids, evidence_ids, errors, warnings)
lod_plan = spec.get("lodPlan")
@@ -1921,6 +2479,7 @@ def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:
validate_quality_depth(spec, errors, warnings)
validate_detail_inventory(spec, errors, warnings)
validate_character_track(spec, errors, warnings)
+ validate_rig_admission(spec, errors, warnings)
if suitability == "pass" and spec.get("risks"):
warnings.append("suitability is pass but risks are present; confirm they are acceptable")
return errors, warnings
diff --git a/forge/stage3_build/decimate.py b/forge/stage3_build/decimate.py
new file mode 100644
index 0000000..3e5823a
--- /dev/null
+++ b/forge/stage3_build/decimate.py
@@ -0,0 +1,272 @@
+#!/usr/bin/env python3
+"""Mesh decimation by quadric error metric, so an lodPlan can be produced rather than only declared.
+
+`lodPlan` is validated in three places in this repository and generated in none. A validated
+declaration is a promise about tiers that nothing ever built; `measure_geometry_integrity` reports
+`lodPlanValid` and the tiers behind it do not exist.
+
+Quadric error metrics (Garland & Heckbert 1997): every vertex accumulates the squared-distance-to-plane
+form of the faces around it, as a symmetric 4x4. Collapsing an edge costs the quadric sum evaluated at
+the merged position, so the cheapest collapse is the one that moves the surface least. Collapses are
+taken in cost order, and each one refreshes the costs of the edges it touched.
+
+Two collapses are refused outright, because both produce a mesh that still passes a triangle count but
+is no longer a surface:
+
+* a collapse that would FLIP a face -- the neighbouring normal reversing means the surface folded
+ through itself, exactly the defect `self_intersection.py` exists to catch, and creating it here
+ while reporting a successful decimation would be the pipeline sabotaging its own gate;
+* a collapse on a BOUNDARY edge -- an open border erodes inward and the silhouette visibly retreats,
+ which is the classic "the LOD is smaller than the original" artefact.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy.
+"""
+
+from __future__ import annotations
+
+import argparse
+import heapq
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+DEFAULT_TARGET_RATIO = 0.5
+MIN_TRIANGLES = 4
+
+
+def _triangles(indices: Any) -> list[tuple[int, int, int]]:
+ if indices and isinstance(indices[0], (list, tuple)):
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
+ return [
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
+ for i in range(0, len(indices) - 2, 3)
+ ]
+
+
+def _plane(p0, p1, p2) -> tuple[float, float, float, float] | None:
+ e1 = [p1[i] - p0[i] for i in range(3)]
+ e2 = [p2[i] - p0[i] for i in range(3)]
+ n = [
+ e1[1] * e2[2] - e1[2] * e2[1],
+ e1[2] * e2[0] - e1[0] * e2[2],
+ e1[0] * e2[1] - e1[1] * e2[0],
+ ]
+ length = math.sqrt(sum(component * component for component in n))
+ if length <= 1e-12:
+ return None
+ n = [component / length for component in n]
+ return n[0], n[1], n[2], -(n[0] * p0[0] + n[1] * p0[1] + n[2] * p0[2])
+
+
+def _quadric(plane: tuple[float, float, float, float]) -> list[float]:
+ a, b, c, d = plane
+ # Upper triangle of the symmetric 4x4, in row-major order.
+ return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d]
+
+
+def _add(q1: list[float], q2: list[float]) -> list[float]:
+ return [x + y for x, y in zip(q1, q2)]
+
+
+def _error(q: list[float], v: list[float]) -> float:
+ x, y, z = v
+ return (
+ q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x
+ + q[4] * y * y + 2 * q[5] * y * z + 2 * q[6] * y
+ + q[7] * z * z + 2 * q[8] * z
+ + q[9]
+ )
+
+
+def decimate(
+ mesh: dict[str, Any],
+ target_ratio: float = DEFAULT_TARGET_RATIO,
+) -> dict[str, Any]:
+ vertices = [list(v) for v in mesh["vertices"]]
+ faces = _triangles(mesh["indices"])
+ if not faces:
+ raise ValueError("mesh has no triangles")
+ if not 0.0 < target_ratio <= 1.0:
+ raise ValueError("target_ratio must be in (0, 1]")
+
+ original_count = len(faces)
+ target_count = max(MIN_TRIANGLES, int(original_count * target_ratio))
+
+ alive = [True] * len(faces)
+ vertex_faces: list[set[int]] = [set() for _ in vertices]
+ for index, face in enumerate(faces):
+ for vertex in face:
+ vertex_faces[vertex].add(index)
+
+ quadrics = [[0.0] * 10 for _ in vertices]
+ for index, face in enumerate(faces):
+ plane = _plane(*(vertices[i] for i in face))
+ if plane is None:
+ alive[index] = False
+ continue
+ q = _quadric(plane)
+ for vertex in face:
+ quadrics[vertex] = _add(quadrics[vertex], q)
+
+ edge_faces: dict[tuple[int, int], int] = {}
+ for index, face in enumerate(faces):
+ a, b, c = face
+ for u, v in ((a, b), (b, c), (c, a)):
+ key = (u, v) if u < v else (v, u)
+ edge_faces[key] = edge_faces.get(key, 0) + 1
+ boundary = {edge for edge, count in edge_faces.items() if count == 1}
+
+ def cost(u: int, v: int) -> tuple[float, list[float]]:
+ # Midpoint rather than the quadric-optimal position: solving the 3x3 needs an inverse that is
+ # singular on flat regions, and the midpoint keeps the collapse on the original surface, which
+ # matters more here than the last few percent of accuracy.
+ merged = [(vertices[u][i] + vertices[v][i]) / 2 for i in range(3)]
+ return _error(_add(quadrics[u], quadrics[v]), merged), merged
+
+ heap: list[tuple[float, int, int]] = []
+ for (u, v) in edge_faces:
+ if (u, v) in boundary:
+ continue
+ heapq.heappush(heap, (cost(u, v)[0], u, v))
+
+ removed = 0
+ refused_flip = 0
+ refused_boundary = len(boundary)
+ live_faces = sum(1 for flag in alive if flag)
+
+ while heap and live_faces > target_count:
+ _, u, v = heapq.heappop(heap)
+ if not vertex_faces[u] or not vertex_faces[v]:
+ continue
+ if u == v:
+ continue
+ shared = vertex_faces[u] & vertex_faces[v]
+ if not any(alive[index] for index in shared):
+ continue
+ _, merged = cost(u, v)
+
+ # Would any surviving face flip? Compare each affected face's normal before and after.
+ flips = False
+ for index in (vertex_faces[u] | vertex_faces[v]) - shared:
+ if not alive[index]:
+ continue
+ face = faces[index]
+ before = _plane(*(vertices[i] for i in face))
+ after_points = [merged if i in (u, v) else vertices[i] for i in face]
+ after = _plane(*after_points)
+ if before is None or after is None:
+ flips = True
+ break
+ if before[0] * after[0] + before[1] * after[1] + before[2] * after[2] < 0.0:
+ flips = True
+ break
+ if flips:
+ refused_flip += 1
+ continue
+
+ vertices[u] = merged
+ quadrics[u] = _add(quadrics[u], quadrics[v])
+ for index in shared:
+ if alive[index]:
+ alive[index] = False
+ live_faces -= 1
+ removed += 1
+ for index in list(vertex_faces[v]):
+ if not alive[index]:
+ continue
+ faces[index] = tuple(u if i == v else i for i in faces[index]) # type: ignore[assignment]
+ vertex_faces[u].add(index)
+ vertex_faces[v] = set()
+
+ for index in list(vertex_faces[u]):
+ if not alive[index]:
+ continue
+ for w in faces[index]:
+ if w != u:
+ heapq.heappush(heap, (cost(u, w)[0], u, w))
+
+ kept = [faces[index] for index in range(len(faces)) if alive[index]]
+ used = sorted({vertex for face in kept for vertex in face})
+ remap = {old: new for new, old in enumerate(used)}
+ out_vertices = [vertices[old] for old in used]
+ out_indices: list[int] = []
+ for face in kept:
+ out_indices.extend(remap[vertex] for vertex in face)
+
+ return {
+ "vertices": out_vertices,
+ "indices": out_indices,
+ "originalTriangleCount": original_count,
+ "triangleCount": len(kept),
+ "targetTriangleCount": target_count,
+ "achievedRatio": round(len(kept) / original_count, 6),
+ "collapsesRefusedForFlip": refused_flip,
+ "boundaryEdgesProtected": refused_boundary,
+ # Reported because a decimation that stops short is not a failure but IS something the caller
+ # must know: on a mesh whose collapses would all flip a face, the honest outcome is fewer
+ # triangles removed, not a folded mesh that hits the number.
+ "reachedTarget": len(kept) <= target_count,
+ }
+
+
+def build_lod_plan(
+ mesh: dict[str, Any],
+ ratios: list[float],
+ distances: list[float],
+) -> dict[str, Any]:
+ """Generate the tiers `lodPlan` has only ever declared.
+
+ Tiers must have strictly increasing distance and strictly decreasing triangle count -- that is what
+ `_has_reduced_lod_tiers` in geometry_integrity.py already enforces, so a plan generated here has to
+ satisfy the validator that until now had nothing real to validate.
+ """
+ if len(ratios) != len(distances):
+ raise ValueError("ratios and distances must be the same length")
+ tiers = []
+ meshes = []
+ for ratio, distance in sorted(zip(ratios, distances), key=lambda pair: pair[1]):
+ result = decimate(mesh, ratio)
+ tiers.append({"distance": distance, "triangleCount": result["triangleCount"]})
+ meshes.append(result)
+ for earlier, later in zip(tiers, tiers[1:]):
+ if later["triangleCount"] >= earlier["triangleCount"]:
+ raise ValueError(
+ f"tier at distance {later['distance']} has {later['triangleCount']} triangles, not "
+ f"fewer than {earlier['triangleCount']} at {earlier['distance']}; the requested "
+ "ratios do not produce a monotonic plan"
+ )
+ return {"lodPlan": tiers, "meshes": meshes}
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Decimate a mesh by quadric error metric.")
+ parser.add_argument("mesh", type=Path)
+ parser.add_argument("--ratio", type=float, default=DEFAULT_TARGET_RATIO)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ mesh = json.loads(args.mesh.read_text())
+ if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
+ mesh = mesh["meshes"][0]
+ result = decimate(mesh, args.ratio)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(
+ f"{result['originalTriangleCount']} -> {result['triangleCount']} triangles "
+ f"(ratio {result['achievedRatio']}), {result['collapsesRefusedForFlip']} collapses "
+ f"refused to avoid folding the surface"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage3_build/generate_threejs_factory.py b/forge/stage3_build/generate_threejs_factory.py
old mode 100755
new mode 100644
index df6e3f9..2bbd6fb
--- a/forge/stage3_build/generate_threejs_factory.py
+++ b/forge/stage3_build/generate_threejs_factory.py
@@ -10,7 +10,33 @@ import sys
from pathlib import Path
from typing import Any
+_FORGE_ROOT = Path(__file__).resolve().parent.parent
+sys.path[:0] = [str(_FORGE_ROOT), str(_FORGE_ROOT / "_shared"), str(_FORGE_ROOT / "stage2_spec")]
from orchestrate_passes import pass_specific_gaps
+from subdivision import (
+ ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS,
+ ATTACHMENT_CYLINDER_RADIAL_SEGMENTS,
+ CAPSULE_CAP_SEGMENTS,
+ CAPSULE_RADIAL_SEGMENTS,
+ CONE_HEIGHT_SEGMENTS,
+ CONE_SUBDIVISION_TOP_RADIUS,
+ CYLINDER_HEIGHT_SEGMENTS,
+ CYLINDER_RADIAL_SEGMENTS,
+ DEFAULT_TESSELLATION_TIER,
+ MAX_SUBDIVISION_ITERATIONS,
+ MAX_SUBDIVISION_QUAD_FACES,
+ PLANE_HEIGHT_SEGMENTS,
+ PLANE_WIDTH_SEGMENTS,
+ SPHERE_HEIGHT_SEGMENTS,
+ SPHERE_WIDTH_SEGMENTS,
+ resolve_instanced_cluster_base,
+ segments_for_spec,
+ TESSELLATION_TIERS,
+ TORUS_RADIAL_SEGMENTS,
+ TORUS_TUBULAR_SEGMENTS,
+)
+from validate_sculpt_spec import validate_spec
+from visual_hull import MAX_VISUAL_HULL_TRIANGLES
VALID_PRIMITIVES = {
@@ -59,6 +85,50 @@ def load_spec(path: Path) -> dict[str, Any]:
return payload
+def strict_quality_failures(spec: dict[str, Any]) -> tuple[list[str], list[str], list[str]]:
+ """Return normal validation output plus the failures that block production codegen."""
+ errors, warnings = validate_spec(spec)
+ failures = list(errors)
+ failures.extend(
+ f"strict quality failure: {warning.removeprefix('quality: ').strip()}"
+ for warning in warnings
+ if warning.startswith("quality:")
+ )
+ return errors, warnings, failures
+
+
+def blocked_report(
+ spec_path: Path,
+ failures: list[str],
+ warnings: list[str],
+ pass_id: str | None,
+) -> dict[str, Any]:
+ """Build a machine-readable fail-closed report without touching the factory output."""
+ return {
+ "status": "BLOCKED",
+ "phase": "strict-quality",
+ "gate": "strict-quality",
+ "artifact": str(spec_path),
+ "metric": {
+ "failureCount": len(failures),
+ "qualityWarningCount": sum(1 for warning in warnings if warning.startswith("quality:")),
+ },
+ "cause": failures,
+ "warnings": warnings,
+ "requestedPass": pass_id,
+ "nextAction": "refine-spec: author a subject-specific ObjectSculptSpec, then rerun strict-quality",
+ }
+
+
+def emit_blocked(report: dict[str, Any], report_path: Path | None) -> None:
+ payload = json.dumps(report, indent=2, ensure_ascii=False)
+ if report_path is not None:
+ report_path = report_path.expanduser().resolve()
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ report_path.write_text(payload + "\n", encoding="utf-8")
+ print(payload, file=sys.stderr)
+
+
def pass_order(spec: dict[str, Any]) -> list[str]:
ids: list[str] = []
for item in spec.get("buildPasses", []):
@@ -239,7 +309,7 @@ _DEFAULT_BLADE_SPEC = {
[0.50, 0.084, -0.108], [0.63, 0.078, -0.095], [0.74, 0.055, -0.055],
[0.82, 0.028, -0.020], [0.88, 0.000, 0.000],
],
- "thickness": 0.05, "grindFrac": 0.55, "swedgeFromTipFrac": 0.34, "spineFlat": 0.30,
+ "thickness": 0.05, "grindFrac": 0.55, "swedgeFromTipFrac": 0.34,
}
_DEFAULT_LATHE_PROFILE = {"points": [[0.3, -0.5], [0.15, 0.0], [0.3, 0.5]], "segments": 24}
_DEFAULT_TUBE_PATH = {"points": [[0.0, -0.5, 0.0], [0.0, 0.5, 0.0]], "radius": 0.05, "closed": False}
@@ -254,26 +324,1002 @@ _DEFAULT_CURVE_SWEEP = {
}
-def geometry_for(primitive: str, component: dict[str, Any] | None = None) -> str:
+_VISUAL_HULL_HELPER_SOURCE = """type VisualHullVector = readonly [number, number, number];
+type VisualHullAxis = 'front' | 'side' | 'top';
+type VisualHullView = {
+ readonly axis: VisualHullAxis;
+ readonly confidence: number;
+ readonly mask: readonly string[];
+};
+type VisualHullDescriptor = {
+ readonly projection: 'orthographic';
+ readonly boundsSpace: 'component-local';
+ readonly bounds: { readonly min: VisualHullVector; readonly max: VisualHullVector };
+ readonly resolution: number;
+ readonly triangleBudget: number;
+ readonly views: readonly VisualHullView[];
+ readonly hiddenRegions?: readonly string[];
+};
+const MAX_VISUAL_HULL_TRIANGLES = __MAX_VISUAL_HULL_TRIANGLES__;
+
+class VisualHullGeometryBudgetError extends Error {
+ readonly triangleBudget: number;
+ readonly emittedTriangles: number;
+
+ constructor(triangleBudget: number, emittedTriangles: number) {
+ super(`visual hull emitted ${emittedTriangles} triangles, exceeding budget ${triangleBudget}`);
+ this.name = 'VisualHullGeometryBudgetError';
+ this.triangleBudget = triangleBudget;
+ this.emittedTriangles = emittedTriangles;
+ }
+}
+
+class VisualHullOccupancyError extends Error {
+ readonly occupiedVoxelCount: number;
+ readonly emittedTriangles: number;
+
+ constructor(occupiedVoxelCount: number, emittedTriangles: number) {
+ super('visual hull silhouettes produced no bounded occupied surface');
+ this.name = 'VisualHullOccupancyError';
+ this.occupiedVoxelCount = occupiedVoxelCount;
+ this.emittedTriangles = emittedTriangles;
+ }
+}
+
+function visualHullMaskContains(view: VisualHullView, horizontal: number, vertical: number): boolean {
+ const height = view.mask.length;
+ const width = view.mask[0].length;
+ const column = Math.max(0, Math.min(width - 1, Math.floor(horizontal * width)));
+ const row = Math.max(0, Math.min(height - 1, Math.floor((1 - vertical) * height)));
+ return view.mask[row][column] === '1';
+}
+
+function buildVisualHullGeometry(descriptor: VisualHullDescriptor): THREE.BufferGeometry {
+ const resolution = descriptor.resolution;
+ const min = new THREE.Vector3(...descriptor.bounds.min);
+ const max = new THREE.Vector3(...descriptor.bounds.max);
+ const step = max.clone().sub(min).multiplyScalar(1 / resolution);
+ const indexAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;
+ const occupied = new Uint8Array(resolution * resolution * resolution);
+ let occupiedVoxelCount = 0;
+ const contains = (x: number, y: number, z: number): boolean => (
+ x >= 0 && y >= 0 && z >= 0 && x < resolution && y < resolution && z < resolution && occupied[indexAt(x, y, z)] === 1
+ );
+ for (let z = 0; z < resolution; z += 1) {
+ for (let y = 0; y < resolution; y += 1) {
+ for (let x = 0; x < resolution; x += 1) {
+ const horizontalX = (x + 0.5) / resolution;
+ const verticalY = (y + 0.5) / resolution;
+ const horizontalZ = (z + 0.5) / resolution;
+ let inside = true;
+ for (const view of descriptor.views) {
+ switch (view.axis) {
+ case 'front':
+ inside = inside && visualHullMaskContains(view, horizontalX, verticalY);
+ break;
+ case 'side':
+ inside = inside && visualHullMaskContains(view, horizontalZ, verticalY);
+ break;
+ case 'top':
+ inside = inside && visualHullMaskContains(view, horizontalX, horizontalZ);
+ break;
+ }
+ if (!inside) break;
+ }
+ if (inside) {
+ occupied[indexAt(x, y, z)] = 1;
+ occupiedVoxelCount += 1;
+ }
+ }
+ }
+ }
+ if (occupiedVoxelCount === 0) throw new VisualHullOccupancyError(0, 0);
+ const positions: number[] = [];
+ const indices: number[] = [];
+ const vertices = new Map<string, number>();
+ const vertexAt = (x: number, y: number, z: number): number => {
+ const key = `${x},${y},${z}`;
+ const existing = vertices.get(key);
+ if (existing !== undefined) return existing;
+ const vertex = positions.length / 3;
+ positions.push(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);
+ vertices.set(key, vertex);
+ return vertex;
+ };
+ const addFace = (a: number, b: number, c: number, d: number): void => {
+ indices.push(a, b, c, a, c, d);
+ const emittedTriangles = indices.length / 3;
+ if (emittedTriangles > descriptor.triangleBudget || emittedTriangles > MAX_VISUAL_HULL_TRIANGLES) {
+ throw new VisualHullGeometryBudgetError(descriptor.triangleBudget, emittedTriangles);
+ }
+ };
+ for (let z = 0; z < resolution; z += 1) {
+ for (let y = 0; y < resolution; y += 1) {
+ for (let x = 0; x < resolution; x += 1) {
+ if (!contains(x, y, z)) continue;
+ if (!contains(x - 1, y, z)) addFace(vertexAt(x, y, z), vertexAt(x, y, z + 1), vertexAt(x, y + 1, z + 1), vertexAt(x, y + 1, z));
+ if (!contains(x + 1, y, z)) addFace(vertexAt(x + 1, y, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y, z + 1));
+ if (!contains(x, y - 1, z)) addFace(vertexAt(x, y, z), vertexAt(x + 1, y, z), vertexAt(x + 1, y, z + 1), vertexAt(x, y, z + 1));
+ if (!contains(x, y + 1, z)) addFace(vertexAt(x, y + 1, z), vertexAt(x, y + 1, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y + 1, z));
+ if (!contains(x, y, z - 1)) addFace(vertexAt(x, y, z), vertexAt(x, y + 1, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y, z));
+ if (!contains(x, y, z + 1)) addFace(vertexAt(x, y, z + 1), vertexAt(x + 1, y, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x, y + 1, z + 1));
+ }
+ }
+ }
+ if (indices.length === 0) throw new VisualHullOccupancyError(occupiedVoxelCount, 0);
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ geometry.setIndex(indices);
+ const uv: number[] = [];
+ for (let index = 0; index < positions.length; index += 3) {
+ uv.push((positions[index] - min.x) / (max.x - min.x), (positions[index + 1] - min.y) / (max.y - min.y));
+ }
+ geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ geometry.computeVertexNormals();
+ geometry.userData.visualHull = {
+ method: 'orthographic-silhouette-intersection',
+ observedAxes: descriptor.views.map((view) => view.axis),
+ viewConfidence: descriptor.views.map((view) => ({ axis: view.axis, confidence: view.confidence })),
+ hiddenRegions: descriptor.hiddenRegions ?? ['Unobserved depth detail remains underconstrained by silhouette intersection.'],
+ lowConfidence: {
+ hiddenRegions: true,
+ reason: 'Silhouette intersection constrains the exterior envelope, not unseen surface detail.',
+ },
+ };
+ return geometry;
+}"""
+
+
+_DECIMATE_HELPER_SOURCE = '''// Quadric-error decimation (Garland & Heckbert 1997), ported from
+// forge/stage3_build/decimate.py so it can run on geometry that only exists at runtime.
+//
+// WHY IT RUNS HERE RATHER THAN OFFLINE: the Python version reads a mesh file, and this
+// factory does not produce one -- an implicit surface is polygonised in the browser from
+// its descriptor, so there is no mesh to decimate until the page is running. Baking a
+// vertex array into this file instead would contradict the whole point of a code-only
+// procedural model.
+//
+// WHY IT RUNS BEFORE BINDING: a quadric collapse merges two vertices into one, and
+// skinIndex/skinWeight would have to be interpolated across that merge to stay correct.
+// The generated bind pass recomputes weights from `position` afterwards, so decimating
+// first means the weights are simply computed on the surviving vertices and no
+// interpolation of skinning data ever has to happen.
+//
+// LIMITATION, stated rather than discovered later: only `position` survives. UVs are
+// dropped and normals are recomputed, so this must not be applied to geometry carrying
+// authored UVs. Its intended input is polygonizeSdf output, which is position + index
+// + computed normals and therefore loses nothing.
+//
+// Two collapses are refused, exactly as in the Python original, because both produce a
+// mesh that passes a triangle count while no longer being a surface:
+// * one that would FLIP a face -- the neighbouring normal reversing means the surface
+// folded through itself, which is the defect self_intersection.py exists to catch;
+// * one on a BOUNDARY edge -- an open border erodes inward and the silhouette visibly
+// retreats, the classic "the LOD is smaller than the original" artefact.
+function decimateGeometry(source: THREE.BufferGeometry, targetRatio: number): THREE.BufferGeometry {
+ const MIN_TRIANGLES = 4;
+ const position = source.getAttribute('position');
+ if (!position || !(targetRatio > 0) || targetRatio >= 1) return source;
+
+ const vertices: number[][] = [];
+ for (let i = 0; i < position.count; i++) {
+ vertices.push([position.getX(i), position.getY(i), position.getZ(i)]);
+ }
+ const index = source.getIndex();
+ const faces: number[][] = [];
+ if (index) {
+ for (let i = 0; i + 2 < index.count; i += 3) {
+ faces.push([index.getX(i), index.getX(i + 1), index.getX(i + 2)]);
+ }
+ } else {
+ for (let i = 0; i + 2 < position.count; i += 3) faces.push([i, i + 1, i + 2]);
+ }
+ if (!faces.length) return source;
+
+ const originalCount = faces.length;
+ const targetCount = Math.max(MIN_TRIANGLES, Math.floor(originalCount * targetRatio));
+ if (originalCount <= targetCount) return source;
+
+ const planeOf = (a: number[], b: number[], c: number[]): number[] | null => {
+ const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ const e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
+ const n = [
+ e1[1] * e2[2] - e1[2] * e2[1],
+ e1[2] * e2[0] - e1[0] * e2[2],
+ e1[0] * e2[1] - e1[1] * e2[0],
+ ];
+ const len = Math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
+ if (len <= 1e-12) return null;
+ const u = [n[0] / len, n[1] / len, n[2] / len];
+ return [u[0], u[1], u[2], -(u[0] * a[0] + u[1] * a[1] + u[2] * a[2])];
+ };
+ // Upper triangle of the symmetric 4x4, row-major -- same 10-element layout as the Python side.
+ const quadricOf = (p: number[]): number[] => {
+ const [a, b, c, d] = p;
+ return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
+ };
+ const addQuadric = (q1: number[], q2: number[]): number[] => q1.map((x, i) => x + q2[i]);
+ const quadricError = (q: number[], v: number[]): number => {
+ const [x, y, z] = v;
+ return (
+ q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x +
+ q[4] * y * y + 2 * q[5] * y * z + 2 * q[6] * y +
+ q[7] * z * z + 2 * q[8] * z + q[9]
+ );
+ };
+
+ const alive = faces.map(() => true);
+ const vertexFaces: Set<number>[] = vertices.map(() => new Set<number>());
+ faces.forEach((face, i) => face.forEach((v) => vertexFaces[v].add(i)));
+
+ const quadrics: number[][] = vertices.map(() => new Array(10).fill(0));
+ faces.forEach((face, i) => {
+ const p = planeOf(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
+ if (!p) { alive[i] = false; return; }
+ const q = quadricOf(p);
+ face.forEach((v) => { quadrics[v] = addQuadric(quadrics[v], q); });
+ });
+
+ const edgeFaces = new Map<string, number>();
+ const edgeKey = (u: number, v: number) => (u < v ? u + ':' + v : v + ':' + u);
+ faces.forEach((face) => {
+ const [a, b, c] = face;
+ for (const [u, v] of [[a, b], [b, c], [c, a]]) {
+ const k = edgeKey(u, v);
+ edgeFaces.set(k, (edgeFaces.get(k) ?? 0) + 1);
+ }
+ });
+ const boundary = new Set<string>();
+ edgeFaces.forEach((count, k) => { if (count === 1) boundary.add(k); });
+
+ const midpointOf = (u: number, v: number): number[] =>
+ [0, 1, 2].map((i) => (vertices[u][i] + vertices[v][i]) / 2);
+ // Midpoint rather than the quadric-optimal position: solving the 3x3 needs an inverse that
+ // is singular on flat regions, and the midpoint keeps the collapse on the original surface.
+ const costOf = (u: number, v: number): number =>
+ quadricError(addQuadric(quadrics[u], quadrics[v]), midpointOf(u, v));
+
+ // Binary heap keyed on collapse cost; entries are stale-checked on pop rather than updated
+ // in place, the same lazy-deletion approach heapq gets in the Python original.
+ const heap: { cost: number; u: number; v: number }[] = [];
+ const heapPush = (entry: { cost: number; u: number; v: number }) => {
+ heap.push(entry);
+ let i = heap.length - 1;
+ while (i > 0) {
+ const parent = (i - 1) >> 1;
+ if (heap[parent].cost <= heap[i].cost) break;
+ [heap[parent], heap[i]] = [heap[i], heap[parent]];
+ i = parent;
+ }
+ };
+ const heapPop = () => {
+ const top = heap[0];
+ const last = heap.pop()!;
+ if (heap.length) {
+ heap[0] = last;
+ let i = 0;
+ for (;;) {
+ const l = 2 * i + 1, r = 2 * i + 2;
+ let small = i;
+ if (l < heap.length && heap[l].cost < heap[small].cost) small = l;
+ if (r < heap.length && heap[r].cost < heap[small].cost) small = r;
+ if (small === i) break;
+ [heap[small], heap[i]] = [heap[i], heap[small]];
+ i = small;
+ }
+ }
+ return top;
+ };
+
+ edgeFaces.forEach((_count, k) => {
+ if (boundary.has(k)) return;
+ const [u, v] = k.split(':').map(Number);
+ heapPush({ cost: costOf(u, v), u, v });
+ });
+
+ let liveFaces = alive.reduce((n, flag) => n + (flag ? 1 : 0), 0);
+ while (heap.length && liveFaces > targetCount) {
+ const { u, v } = heapPop();
+ if (u === v || !vertexFaces[u].size || !vertexFaces[v].size) continue;
+ const shared = new Set<number>();
+ vertexFaces[u].forEach((i) => { if (vertexFaces[v].has(i)) shared.add(i); });
+ let anyAlive = false;
+ shared.forEach((i) => { if (alive[i]) anyAlive = true; });
+ if (!anyAlive) continue;
+ const merged = midpointOf(u, v);
+
+ let flips = false;
+ const affected = new Set<number>();
+ vertexFaces[u].forEach((i) => { if (!shared.has(i)) affected.add(i); });
+ vertexFaces[v].forEach((i) => { if (!shared.has(i)) affected.add(i); });
+ for (const i of affected) {
+ if (!alive[i] || flips) continue;
+ const face = faces[i];
+ const before = planeOf(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
+ const pts = face.map((w) => (w === u || w === v ? merged : vertices[w]));
+ const after = planeOf(pts[0], pts[1], pts[2]);
+ if (!before || !after) { flips = true; break; }
+ if (before[0] * after[0] + before[1] * after[1] + before[2] * after[2] < 0) { flips = true; break; }
+ }
+ if (flips) continue;
+
+ vertices[u] = merged;
+ quadrics[u] = addQuadric(quadrics[u], quadrics[v]);
+ shared.forEach((i) => { if (alive[i]) { alive[i] = false; liveFaces -= 1; } });
+ Array.from(vertexFaces[v]).forEach((i) => {
+ if (!alive[i]) return;
+ faces[i] = faces[i].map((w) => (w === v ? u : w));
+ vertexFaces[u].add(i);
+ });
+ vertexFaces[v] = new Set<number>();
+ Array.from(vertexFaces[u]).forEach((i) => {
+ if (!alive[i]) return;
+ faces[i].forEach((w) => { if (w !== u) heapPush({ cost: costOf(u, w), u, v: w }); });
+ });
+ }
+
+ const kept = faces.filter((_face, i) => alive[i]);
+ const used = Array.from(new Set(kept.flat())).sort((a, b) => a - b);
+ const remap = new Map<number, number>();
+ used.forEach((old, next) => remap.set(old, next));
+ const outPositions: number[] = [];
+ used.forEach((old) => outPositions.push(vertices[old][0], vertices[old][1], vertices[old][2]));
+ const outIndices: number[] = [];
+ kept.forEach((face) => face.forEach((w) => outIndices.push(remap.get(w)!)));
+
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(outPositions, 3));
+ geometry.setIndex(outIndices);
+ geometry.computeVertexNormals();
+ geometry.userData.decimation = {
+ originalTriangleCount: originalCount,
+ triangleCount: kept.length,
+ targetTriangleCount: targetCount,
+ // Reported because stopping short is not a failure but IS something the caller must know:
+ // on a mesh whose remaining collapses would all flip a face, the honest outcome is fewer
+ // triangles removed, not a folded mesh that hits the number.
+ reachedTarget: kept.length <= targetCount,
+ };
+ return geometry;
+}'''
+
+
+_SDF_HELPER_SOURCE = """type SdfVector = readonly [number, number, number];
+type SdfTransform = { position?: SdfVector; translation?: SdfVector; rotation?: SdfVector; scale?: SdfVector };
+type SdfPrimitive = {
+ readonly id: string;
+ readonly type: 'sphere' | 'capsule' | 'box' | 'cone' | 'ellipsoid';
+ readonly center?: SdfVector;
+ readonly radius?: number | SdfVector;
+ readonly height?: number;
+ readonly size?: SdfVector;
+ readonly dimensions?: SdfVector;
+ readonly radii?: SdfVector;
+ readonly transform?: SdfTransform;
+};
+type SdfOperation = {
+ readonly id?: string;
+ readonly output?: string;
+ readonly type: 'smooth-union' | 'subtract' | 'intersect';
+ readonly left: string;
+ readonly right: string;
+ readonly radius?: number;
+};
+type SdfDescriptor = {
+ readonly primitives: readonly SdfPrimitive[];
+ readonly operations?: readonly SdfOperation[];
+ readonly resolution: number;
+ readonly bounds?: { readonly min: SdfVector; readonly max: SdfVector };
+};
+type SdfFunction = (point: THREE.Vector3) => number;
+
+function sdfSphere(point: THREE.Vector3, radius: number): number {
+ return point.length() - radius;
+}
+
+function sdfCapsule(point: THREE.Vector3, radius: number, height: number): number {
+ const halfHeight = height * 0.5;
+ const y = Math.max(-halfHeight, Math.min(halfHeight, point.y));
+ return point.distanceTo(new THREE.Vector3(0, y, 0)) - radius;
+}
+
+function sdfBox(point: THREE.Vector3, size: SdfVector): number {
+ const q = new THREE.Vector3(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z))
+ .sub(new THREE.Vector3(size[0] * 0.5, size[1] * 0.5, size[2] * 0.5));
+ return q.clone().max(new THREE.Vector3()).length() + Math.min(Math.max(q.x, q.y, q.z), 0);
+}
+
+function sdfCone(point: THREE.Vector3, radius: number, height: number): number {
+ const halfHeight = height * 0.5;
+ const taper = radius * (1 - (point.y + halfHeight) / height);
+ return Math.max(Math.hypot(point.x, point.z) - Math.max(0, taper), Math.abs(point.y) - halfHeight);
+}
+
+function sdfEllipsoid(point: THREE.Vector3, radii: SdfVector): number {
+ const scaled = new THREE.Vector3(point.x / radii[0], point.y / radii[1], point.z / radii[2]);
+ return (scaled.length() - 1) * Math.min(radii[0], radii[1], radii[2]);
+}
+
+function sdfRadii(primitive: SdfPrimitive): SdfVector {
+ const radius = primitive.radius;
+ if (primitive.radii) return primitive.radii;
+ if (typeof radius === 'number') return [radius, radius, radius];
+ return radius ?? [0.5, 0.5, 0.5];
+}
+
+function smin(left: number, right: number, radius: number): number {
+ const blend = Math.max(radius - Math.abs(left - right), 0) / radius;
+ return Math.min(left, right) - blend * blend * radius * 0.25;
+}
+
+function sdfLocalPoint(point: THREE.Vector3, primitive: SdfPrimitive): { point: THREE.Vector3; scale: number } {
+ const transform = primitive.transform;
+ const translation = transform?.position ?? transform?.translation ?? primitive.center ?? [0, 0, 0];
+ const rotation = transform?.rotation ?? [0, 0, 0];
+ const scale = transform?.scale ?? [1, 1, 1];
+ const local = point.clone().sub(new THREE.Vector3(translation[0], translation[1], translation[2]));
+ const inverseRotation = new THREE.Quaternion()
+ .setFromEuler(new THREE.Euler(rotation[0], rotation[1], rotation[2]))
+ .invert();
+ local.applyQuaternion(inverseRotation);
+ local.set(local.x / scale[0], local.y / scale[1], local.z / scale[2]);
+ return { point: local, scale: Math.min(scale[0], scale[1], scale[2]) };
+}
+
+function sdfPrimitive(point: THREE.Vector3, primitive: SdfPrimitive): number {
+ const local = sdfLocalPoint(point, primitive);
+ let distance: number;
+ switch (primitive.type) {
+ case 'sphere':
+ distance = sdfSphere(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.5);
+ break;
+ case 'capsule':
+ distance = sdfCapsule(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.25, primitive.height ?? 1);
+ break;
+ case 'box':
+ distance = sdfBox(local.point, primitive.size ?? primitive.dimensions ?? [1, 1, 1]);
+ break;
+ case 'cone':
+ distance = sdfCone(local.point, typeof primitive.radius === 'number' ? primitive.radius : 0.5, primitive.height ?? 1);
+ break;
+ case 'ellipsoid':
+ distance = sdfEllipsoid(local.point, sdfRadii(primitive));
+ break;
+ }
+ return distance * local.scale;
+}
+
+function sdfSample(descriptor: SdfDescriptor): SdfFunction {
+ const nodes = new Map<string, SdfFunction>();
+ for (const primitive of descriptor.primitives) nodes.set(primitive.id, (point) => sdfPrimitive(point, primitive));
+ let result = descriptor.primitives.length > 0 ? nodes.get(descriptor.primitives[0].id) : undefined;
+ for (let index = 0; index < (descriptor.operations?.length ?? 0); index += 1) {
+ const operation = descriptor.operations?.[index];
+ if (!operation) continue;
+ const left = nodes.get(operation.left);
+ const right = nodes.get(operation.right);
+ if (!left || !right) continue;
+ let combined: SdfFunction;
+ switch (operation.type) {
+ case 'smooth-union':
+ combined = (point) => smin(left(point), right(point), operation.radius ?? 0.1);
+ break;
+ case 'subtract':
+ combined = (point) => Math.max(left(point), -right(point));
+ break;
+ case 'intersect':
+ combined = (point) => Math.max(left(point), right(point));
+ break;
+ }
+ nodes.set(operation.id ?? operation.output ?? `operation-${index}`, combined);
+ result = combined;
+ }
+ return result ?? (() => Infinity);
+}
+
+function polygonizeSdf(descriptor: SdfDescriptor): THREE.BufferGeometry {
+ const resolution = Math.max(4, Math.min(64, Math.floor(descriptor.resolution)));
+ const defaultBounds: { readonly min: SdfVector; readonly max: SdfVector } = { min: [-2, -2, -2], max: [2, 2, 2] };
+ const bounds = descriptor.bounds ?? defaultBounds;
+ const min = new THREE.Vector3(bounds.min[0], bounds.min[1], bounds.min[2]);
+ const step = new THREE.Vector3(
+ (bounds.max[0] - bounds.min[0]) / resolution,
+ (bounds.max[1] - bounds.min[1]) / resolution,
+ (bounds.max[2] - bounds.min[2]) / resolution,
+ );
+ const field = new Float32Array(resolution * resolution * resolution);
+ const sample = sdfSample(descriptor);
+ const indexAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;
+ for (let z = 0; z < resolution; z += 1) {
+ for (let y = 0; y < resolution; y += 1) {
+ for (let x = 0; x < resolution; x += 1) {
+ field[indexAt(x, y, z)] = sample(new THREE.Vector3(
+ min.x + (x + 0.5) * step.x,
+ min.y + (y + 0.5) * step.y,
+ min.z + (z + 0.5) * step.z,
+ ));
+ }
+ }
+ }
+ const positions: number[] = [];
+ const indices: number[] = [];
+ const vertices = new Map<string, number>();
+ const vertexAt = (x: number, y: number, z: number): number => {
+ const key = `${x},${y},${z}`;
+ const existing = vertices.get(key);
+ if (existing !== undefined) return existing;
+ const vertex = positions.length / 3;
+ positions.push(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);
+ vertices.set(key, vertex);
+ return vertex;
+ };
+ const addFace = (a: number, b: number, c: number, d: number): void => {
+ indices.push(a, b, c, a, c, d);
+ };
+ const inside = (x: number, y: number, z: number): boolean => (
+ x >= 0 && y >= 0 && z >= 0 && x < resolution && y < resolution && z < resolution && field[indexAt(x, y, z)] <= 0
+ );
+ for (let z = 0; z < resolution; z += 1) {
+ for (let y = 0; y < resolution; y += 1) {
+ for (let x = 0; x < resolution; x += 1) {
+ if (!inside(x, y, z)) continue;
+ if (!inside(x - 1, y, z)) addFace(vertexAt(x, y, z), vertexAt(x, y, z + 1), vertexAt(x, y + 1, z + 1), vertexAt(x, y + 1, z));
+ if (!inside(x + 1, y, z)) addFace(vertexAt(x + 1, y, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y, z + 1));
+ if (!inside(x, y - 1, z)) addFace(vertexAt(x, y, z), vertexAt(x + 1, y, z), vertexAt(x + 1, y, z + 1), vertexAt(x, y, z + 1));
+ if (!inside(x, y + 1, z)) addFace(vertexAt(x, y + 1, z), vertexAt(x, y + 1, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y + 1, z));
+ if (!inside(x, y, z - 1)) addFace(vertexAt(x, y, z), vertexAt(x, y + 1, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y, z));
+ if (!inside(x, y, z + 1)) addFace(vertexAt(x, y, z + 1), vertexAt(x + 1, y, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x, y + 1, z + 1));
+ }
+ }
+ }
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ geometry.setIndex(indices);
+ geometry.computeVertexNormals();
+ return geometry;
+}"""
+
+
+_SUBDIVISION_HELPER_SOURCE = """type SubdivisionFace = number[];
+type SubdivisionEdge = {
+ a: number;
+ b: number;
+ faces: number[];
+};
+type SubdivisionUvChannel = {
+ name: string;
+ faces: THREE.Vector2[][];
+};
+const MAX_SUBDIVISION_QUAD_FACES = __MAX_SUBDIVISION_QUAD_FACES__;
+const MAX_SUBDIVISION_ITERATIONS = __MAX_SUBDIVISION_ITERATIONS__;
+
+class SubdivisionInputError extends Error {
+ readonly iterations: unknown;
+
+ constructor(iterations: unknown) {
+ super(`subdivision iterations must be an integer from 0 to ${MAX_SUBDIVISION_ITERATIONS}`);
+ this.name = 'SubdivisionInputError';
+ this.iterations = iterations;
+ }
+}
+
+class SubdivisionGeometryBudgetError extends Error {
+ readonly sourceFaceCount: number;
+ readonly projectedQuadFaceCount: number;
+
+ constructor(sourceFaceCount: number, projectedQuadFaceCount: number) {
+ super(`subdivision would produce ${projectedQuadFaceCount} quad faces from ${sourceFaceCount} source faces`);
+ this.name = 'SubdivisionGeometryBudgetError';
+ this.sourceFaceCount = sourceFaceCount;
+ this.projectedQuadFaceCount = projectedQuadFaceCount;
+ }
+}
+
+class SubdivisionTopologyError extends Error {
+ readonly reason: string;
+
+ constructor(reason: string) {
+ super(reason);
+ this.name = 'SubdivisionTopologyError';
+ this.reason = reason;
+ }
+}
+
+function subdivideCatmullClark(source: THREE.BufferGeometry, iterations: number): THREE.BufferGeometry {
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > MAX_SUBDIVISION_ITERATIONS) {
+ throw new SubdivisionInputError(iterations);
+ }
+ if (iterations === 0) return source;
+ const position = source.getAttribute('position');
+ if (!position) {
+ source.computeVertexNormals();
+ return source;
+ }
+
+ const sourcePositions: THREE.Vector3[] = [];
+ const sourceVertexByKey = new Map<string, number>();
+ const sourceUvChannels: SubdivisionUvChannel[] = [];
+ for (const name of ['uv', 'uv2']) {
+ const attribute = source.getAttribute(name);
+ if (attribute && attribute.itemSize >= 2) sourceUvChannels.push({ name, faces: [] });
+ }
+ const vertexIndexAt = (attributeIndex: number): number => {
+ const x = position.getX(attributeIndex);
+ const y = position.getY(attributeIndex);
+ const z = position.getZ(attributeIndex);
+ const key = `${Math.round(x * 1000000)},${Math.round(y * 1000000)},${Math.round(z * 1000000)}`;
+ const existing = sourceVertexByKey.get(key);
+ if (existing !== undefined) return existing;
+ const vertexIndex = sourcePositions.length;
+ sourcePositions.push(new THREE.Vector3(x, y, z));
+ sourceVertexByKey.set(key, vertexIndex);
+ return vertexIndex;
+ };
+ const sourceIndex = source.getIndex();
+ const sourceVertexCount = sourceIndex?.count ?? position.count;
+ const sourceTriangles: SubdivisionFace[] = [];
+ const sourceTriangleAttributeIndices: number[][] = [];
+ for (let index = 0; index + 2 < sourceVertexCount; index += 3) {
+ const attributeA = sourceIndex ? sourceIndex.getX(index) : index;
+ const attributeB = sourceIndex ? sourceIndex.getX(index + 1) : index + 1;
+ const attributeC = sourceIndex ? sourceIndex.getX(index + 2) : index + 2;
+ const a = vertexIndexAt(attributeA);
+ const b = vertexIndexAt(attributeB);
+ const c = vertexIndexAt(attributeC);
+ if (a !== b && b !== c && c !== a) {
+ sourceTriangles.push([a, b, c]);
+ sourceTriangleAttributeIndices.push([attributeA, attributeB, attributeC]);
+ }
+ }
+
+ const triangleNormal = (face: SubdivisionFace): THREE.Vector3 => {
+ const a = sourcePositions[face[0]];
+ const b = sourcePositions[face[1]];
+ const c = sourcePositions[face[2]];
+ return new THREE.Vector3().subVectors(b, a).cross(new THREE.Vector3().subVectors(c, a)).normalize();
+ };
+ const edgeKey = (a: number, b: number): string => (a < b ? `${a}:${b}` : `${b}:${a}`);
+ const triangleEdges = new Map<string, number[]>();
+ for (let triangleIndex = 0; triangleIndex < sourceTriangles.length; triangleIndex += 1) {
+ const triangle = sourceTriangles[triangleIndex];
+ for (let vertexIndex = 0; vertexIndex < triangle.length; vertexIndex += 1) {
+ const a = triangle[vertexIndex];
+ const b = triangle[(vertexIndex + 1) % triangle.length];
+ const key = edgeKey(a, b);
+ const entries = triangleEdges.get(key) ?? [];
+ entries.push(triangleIndex);
+ triangleEdges.set(key, entries);
+ }
+ }
+
+ const pairedTriangles = new Set<number>();
+ let faces: SubdivisionFace[] = [];
+ let faceAttributeIndices: number[][] = [];
+ for (const triangleIndices of triangleEdges.values()) {
+ if (triangleIndices.length !== 2) continue;
+ const leftIndex = triangleIndices[0];
+ const rightIndex = triangleIndices[1];
+ if (pairedTriangles.has(leftIndex) || pairedTriangles.has(rightIndex)) continue;
+ const left = sourceTriangles[leftIndex];
+ const right = sourceTriangles[rightIndex];
+ if (triangleNormal(left).dot(triangleNormal(right)) < 0.999999) continue;
+ const leftAttributes = sourceTriangleAttributeIndices[leftIndex];
+ const rightAttributes = sourceTriangleAttributeIndices[rightIndex];
+ const directedEdges: Array<{ start: number; end: number; attributeIndex: number }> = [
+ { start: left[0], end: left[1], attributeIndex: leftAttributes[0] },
+ { start: left[1], end: left[2], attributeIndex: leftAttributes[1] },
+ { start: left[2], end: left[0], attributeIndex: leftAttributes[2] },
+ { start: right[0], end: right[1], attributeIndex: rightAttributes[0] },
+ { start: right[1], end: right[2], attributeIndex: rightAttributes[1] },
+ { start: right[2], end: right[0], attributeIndex: rightAttributes[2] },
+ ];
+ const boundaryEdges = directedEdges.filter(
+ (edge, edgeIndex) => !directedEdges.some(
+ (candidate, candidateIndex) => (
+ candidateIndex !== edgeIndex && candidate.start === edge.end && candidate.end === edge.start
+ ),
+ ),
+ );
+ if (boundaryEdges.length !== 4) continue;
+ const face: number[] = [];
+ const attributeIndices: number[] = [];
+ let edge = boundaryEdges[0];
+ let closesFace = false;
+ while (face.length < 4) {
+ face.push(edge.start);
+ attributeIndices.push(edge.attributeIndex);
+ if (face.length === 4) {
+ closesFace = edge.end === face[0];
+ break;
+ }
+ const nextEdge = boundaryEdges.find((candidate) => candidate.start === edge.end);
+ if (!nextEdge) break;
+ edge = nextEdge;
+ }
+ if (face.length === 4 && closesFace) {
+ faces.push(face);
+ faceAttributeIndices.push(attributeIndices);
+ pairedTriangles.add(leftIndex);
+ pairedTriangles.add(rightIndex);
+ }
+ }
+ for (let triangleIndex = 0; triangleIndex < sourceTriangles.length; triangleIndex += 1) {
+ if (!pairedTriangles.has(triangleIndex)) {
+ faces.push(sourceTriangles[triangleIndex]);
+ faceAttributeIndices.push(sourceTriangleAttributeIndices[triangleIndex]);
+ }
+ }
+ if (faces.length === 0) {
+ source.computeVertexNormals();
+ return source;
+ }
+
+ for (const channel of sourceUvChannels) {
+ const attribute = source.getAttribute(channel.name);
+ if (!attribute) continue;
+ channel.faces = faceAttributeIndices.map((indices) => (
+ indices.map((attributeIndex) => new THREE.Vector2(attribute.getX(attributeIndex), attribute.getY(attributeIndex)))
+ ));
+ }
+
+ const sourceFaceCount = faces.length;
+ const projectedQuadFaceCount = sourceFaceCount * 4 ** iterations;
+ if (projectedQuadFaceCount > MAX_SUBDIVISION_QUAD_FACES) {
+ throw new SubdivisionGeometryBudgetError(sourceFaceCount, projectedQuadFaceCount);
+ }
+ let vertices = sourcePositions;
+ let uvChannels = sourceUvChannels;
+ for (let iteration = 0; iteration < iterations; iteration += 1) {
+ const facePoints = faces.map((face) => {
+ const point = new THREE.Vector3();
+ for (const vertexIndex of face) point.add(vertices[vertexIndex]);
+ return point.multiplyScalar(1 / face.length);
+ });
+ const vertexFaces: number[][] = Array.from({ length: vertices.length }, () => []);
+ const vertexEdges: number[][] = Array.from({ length: vertices.length }, () => []);
+ const faceEdges: number[][] = faces.map(() => []);
+ const edges: SubdivisionEdge[] = [];
+ const edgeIndices = new Map<string, number>();
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
+ const face = faces[faceIndex];
+ for (const vertexIndex of face) vertexFaces[vertexIndex].push(faceIndex);
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
+ const a = face[vertexIndex];
+ const b = face[(vertexIndex + 1) % face.length];
+ const key = edgeKey(a, b);
+ let edgeIndex = edgeIndices.get(key);
+ if (edgeIndex === undefined) {
+ edgeIndex = edges.length;
+ edges.push({ a: Math.min(a, b), b: Math.max(a, b), faces: [] });
+ edgeIndices.set(key, edgeIndex);
+ }
+ edges[edgeIndex].faces.push(faceIndex);
+ vertexEdges[a].push(edgeIndex);
+ vertexEdges[b].push(edgeIndex);
+ faceEdges[faceIndex].push(edgeIndex);
+ }
+ }
+ for (const edge of edges) {
+ if (edge.faces.length > 2) {
+ throw new SubdivisionTopologyError(`non-manifold edge ${edge.a}:${edge.b} has ${edge.faces.length} incident faces`);
+ }
+ if (edge.faces.length === 1) {
+ throw new SubdivisionTopologyError(`open boundary edge ${edge.a}:${edge.b} has 1 incident face`);
+ }
+ }
+ for (let vertexIndex = 0; vertexIndex < vertices.length; vertexIndex += 1) {
+ const incidentFaces = vertexFaces[vertexIndex];
+ if (incidentFaces.length < 2) continue;
+ const connectedFaces = new Set<number>();
+ const pendingFaces = [incidentFaces[0]];
+ while (pendingFaces.length > 0) {
+ const faceIndex = pendingFaces.pop();
+ if (faceIndex === undefined || connectedFaces.has(faceIndex)) continue;
+ connectedFaces.add(faceIndex);
+ for (const edgeIndex of vertexEdges[vertexIndex]) {
+ const edge = edges[edgeIndex];
+ if (edge.faces.length !== 2 || !edge.faces.includes(faceIndex)) continue;
+ const adjacentFace = edge.faces[0] === faceIndex ? edge.faces[1] : edge.faces[0];
+ if (!connectedFaces.has(adjacentFace)) pendingFaces.push(adjacentFace);
+ }
+ }
+ if (connectedFaces.size !== incidentFaces.length) {
+ throw new SubdivisionTopologyError(`vertex ${vertexIndex} has a disconnected incident face fan`);
+ }
+ }
+
+ const nextVertices: THREE.Vector3[] = [];
+ for (let vertexIndex = 0; vertexIndex < vertices.length; vertexIndex += 1) {
+ const vertex = vertices[vertexIndex];
+ const incidentFaces = vertexFaces[vertexIndex];
+ const incidentEdges = vertexEdges[vertexIndex];
+ if (incidentFaces.length === 0 || incidentEdges.length === 0) {
+ nextVertices.push(vertex.clone());
+ continue;
+ }
+ const faceAverage = new THREE.Vector3();
+ for (const faceIndex of incidentFaces) faceAverage.add(facePoints[faceIndex]);
+ faceAverage.multiplyScalar(1 / incidentFaces.length);
+ const edgeAverage = new THREE.Vector3();
+ for (const edgeIndex of incidentEdges) {
+ const edge = edges[edgeIndex];
+ edgeAverage.add(vertices[edge.a].clone().add(vertices[edge.b]).multiplyScalar(0.5));
+ }
+ edgeAverage.multiplyScalar(1 / incidentEdges.length);
+ nextVertices.push(
+ vertex.clone()
+ .multiplyScalar(incidentFaces.length - 3)
+ .add(faceAverage)
+ .addScaledVector(edgeAverage, 2)
+ .multiplyScalar(1 / incidentFaces.length),
+ );
+ }
+
+ const nextUvChannels = uvChannels.map((channel) => {
+ const nextFaces: THREE.Vector2[][] = [];
+ for (const faceValues of channel.faces) {
+ const faceValue = new THREE.Vector2();
+ for (const value of faceValues) faceValue.add(value);
+ faceValue.multiplyScalar(1 / faceValues.length);
+ for (let vertexIndex = 0; vertexIndex < faceValues.length; vertexIndex += 1) {
+ const value = faceValues[vertexIndex];
+ const nextValue = faceValues[(vertexIndex + 1) % faceValues.length];
+ const previousValue = faceValues[(vertexIndex + faceValues.length - 1) % faceValues.length];
+ nextFaces.push([
+ value.clone(),
+ value.clone().add(nextValue).multiplyScalar(0.5),
+ faceValue.clone(),
+ previousValue.clone().add(value).multiplyScalar(0.5),
+ ]);
+ }
+ }
+ return { name: channel.name, faces: nextFaces };
+ });
+
+ const edgePointIndices: number[] = [];
+ for (const edge of edges) {
+ const point = vertices[edge.a].clone().add(vertices[edge.b]);
+ if (edge.faces.length >= 2) {
+ point.add(facePoints[edge.faces[0]]).add(facePoints[edge.faces[1]]).multiplyScalar(0.25);
+ } else {
+ point.multiplyScalar(0.5);
+ }
+ edgePointIndices.push(nextVertices.length);
+ nextVertices.push(point);
+ }
+ const facePointIndices: number[] = [];
+ for (const point of facePoints) {
+ facePointIndices.push(nextVertices.length);
+ nextVertices.push(point);
+ }
+ const nextFaces: number[][] = [];
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
+ const face = faces[faceIndex];
+ const faceEdgeIndices = faceEdges[faceIndex];
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
+ const previousEdgeIndex = (vertexIndex + faceEdgeIndices.length - 1) % faceEdgeIndices.length;
+ nextFaces.push([
+ face[vertexIndex],
+ edgePointIndices[faceEdgeIndices[vertexIndex]],
+ facePointIndices[faceIndex],
+ edgePointIndices[faceEdgeIndices[previousEdgeIndex]],
+ ]);
+ }
+ }
+ vertices = nextVertices;
+ uvChannels = nextUvChannels;
+ faces = nextFaces;
+ }
+
+ const topologyPositions: number[] = [];
+ for (const vertex of vertices) topologyPositions.push(vertex.x, vertex.y, vertex.z);
+ const topologyIndices: number[] = [];
+ for (const face of faces) {
+ for (let vertexIndex = 1; vertexIndex + 1 < face.length; vertexIndex += 1) {
+ topologyIndices.push(face[0], face[vertexIndex], face[vertexIndex + 1]);
+ }
+ }
+ const topologyGeometry = new THREE.BufferGeometry();
+ topologyGeometry.setAttribute('position', new THREE.Float32BufferAttribute(topologyPositions, 3));
+ topologyGeometry.setIndex(topologyIndices);
+ topologyGeometry.computeVertexNormals();
+
+ let geometry = topologyGeometry;
+ if (uvChannels.length > 0) {
+ const normals = topologyGeometry.getAttribute('normal');
+ const positions: number[] = [];
+ const normalValues: number[] = [];
+ const indices: number[] = [];
+ const seamUvValues: Array<{ name: string; values: number[] }> = uvChannels.map((channel) => ({ name: channel.name, values: [] }));
+ for (let faceIndex = 0; faceIndex < faces.length; faceIndex += 1) {
+ const face = faces[faceIndex];
+ const cornerIndices: number[] = [];
+ const faceStart = positions.length / 3;
+ for (let vertexIndex = 0; vertexIndex < face.length; vertexIndex += 1) {
+ const topologyIndex = face[vertexIndex];
+ const vertex = vertices[topologyIndex];
+ positions.push(vertex.x, vertex.y, vertex.z);
+ normalValues.push(normals.getX(topologyIndex), normals.getY(topologyIndex), normals.getZ(topologyIndex));
+ for (let channelIndex = 0; channelIndex < uvChannels.length; channelIndex += 1) {
+ const value = uvChannels[channelIndex].faces[faceIndex][vertexIndex];
+ seamUvValues[channelIndex].values.push(value.x, value.y);
+ }
+ cornerIndices.push(faceStart + vertexIndex);
+ }
+ for (let vertexIndex = 1; vertexIndex + 1 < cornerIndices.length; vertexIndex += 1) {
+ indices.push(cornerIndices[0], cornerIndices[vertexIndex], cornerIndices[vertexIndex + 1]);
+ }
+ }
+ geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normalValues, 3));
+ geometry.setIndex(indices);
+ for (const channel of seamUvValues) {
+ geometry.setAttribute(channel.name, new THREE.Float32BufferAttribute(channel.values, 2));
+ }
+ }
+ geometry.userData.subdivision = {
+ method: 'catmull-clark-style',
+ sourceFaceCount,
+ quadFaceCount: faces.length,
+ iterations,
+ };
+ return geometry;
+}"""
+
+
+def capped_sdf(sdf: dict[str, Any], segments: dict[str, int]) -> dict[str, Any]:
+ """Clamp an SDF descriptor's sampling grid to the tessellation tier's ceiling.
+
+ Lowering the grid is the only lever an implicit surface has: it has no segment counts.
+ The author's value is kept when it is already at or below the ceiling, so a deliberately
+ coarse field is never made denser by the tier.
+ """
+ ceiling = segments.get("SDF_MAX_RESOLUTION")
+ resolution = sdf.get("resolution")
+ if not isinstance(ceiling, int) or not isinstance(resolution, int) or isinstance(resolution, bool):
+ return sdf
+ if resolution <= ceiling:
+ return sdf
+ return {**sdf, "resolution": ceiling}
+
+
+def geometry_for(
+ primitive: str,
+ component: dict[str, Any] | None = None,
+ subdivision_requested: bool = False,
+ segments: dict[str, int] | None = None,
+) -> str:
+ """Emit the geometry construction for one primitive.
+
+ `segments` is the resolved tessellation table (see `_shared/subdivision.py`).
+ It defaults to the `hero` tier, which is the module-level constants, so a
+ caller that does not pass one gets exactly the output it got before tiers
+ existed.
+ """
+ seg = segments if segments is not None else TESSELLATION_TIERS[DEFAULT_TESSELLATION_TIER]
if primitive == "box":
- return "new THREE.BoxGeometry(1, 1, 1, 12, 12, 12)"
+ n = seg["BOX_SEGMENTS"]
+ return f"new THREE.BoxGeometry(1, 1, 1, {n}, {n}, {n})"
if primitive in {"sphere", "ellipsoid"}:
- return "new THREE.SphereGeometry(0.5, 64, 40)"
+ return f"new THREE.SphereGeometry(0.5, {seg['SPHERE_WIDTH_SEGMENTS']}, {seg['SPHERE_HEIGHT_SEGMENTS']})"
if primitive == "cylinder":
- return "new THREE.CylinderGeometry(0.5, 0.5, 1, 48, 16)"
+ return f"new THREE.CylinderGeometry(0.5, 0.5, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CYLINDER_HEIGHT_SEGMENTS']})"
if primitive == "cone":
- return "new THREE.ConeGeometry(0.5, 1, 48, 16)"
+ if subdivision_requested:
+ return f"new THREE.CylinderGeometry(0.5, {CONE_SUBDIVISION_TOP_RADIUS}, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CYLINDER_HEIGHT_SEGMENTS']})"
+ return f"new THREE.ConeGeometry(0.5, 1, {seg['CYLINDER_RADIAL_SEGMENTS']}, {seg['CONE_HEIGHT_SEGMENTS']})"
if primitive == "capsule":
- return "new THREE.CapsuleGeometry(0.35, 0.7, 16, 32)"
+ return f"buildWatertightCapsule(0.35, 0.7, {seg['CAPSULE_CAP_SEGMENTS']}, {seg['CAPSULE_RADIAL_SEGMENTS']}, 1)"
if primitive == "torus":
# Tube thickness is ring-relative (fraction of the 0.45 base radius) so a
# component can be a slim bike tyre or a fat donut without changing scale.
desc = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
tube_ratio = desc.get("torusTubeRatio")
tube = 0.45 * float(tube_ratio) if isinstance(tube_ratio, (int, float)) and tube_ratio > 0 else 0.08
- return f"new THREE.TorusGeometry(0.45, {round(tube, 4)}, 24, 96)"
+ return f"new THREE.TorusGeometry(0.45, {round(tube, 4)}, {seg['TORUS_TUBULAR_SEGMENTS']}, {seg['TORUS_RADIAL_SEGMENTS']})"
if primitive == "plane-card":
- return "new THREE.PlaneGeometry(1, 1, 24, 24)"
+ return f"new THREE.PlaneGeometry(1, 1, {seg['PLANE_WIDTH_SEGMENTS']}, {seg['PLANE_HEIGHT_SEGMENTS']})"
descriptor = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
if primitive == "extrude":
profile = descriptor.get("profile2D") if isinstance(descriptor.get("profile2D"), dict) else _DEFAULT_EXTRUDE_PROFILE
@@ -294,17 +1340,438 @@ def geometry_for(primitive: str, component: dict[str, Any] | None = None) -> str
# An instanced cluster's *geometry* is its base shape; the instancing itself is applied
# by the repetition-system emitter (THREE.InstancedMesh). Resolve the base primitive from
# the descriptor (default box); guard against self-reference so we never recurse.
- base = descriptor.get("baseGeometry") if isinstance(descriptor.get("baseGeometry"), str) else "box"
- if base in ("instanced-cluster", "") or base not in VALID_PRIMITIVES:
- base = "box"
- return geometry_for(base, component)
+ base = resolve_instanced_cluster_base(primitive, descriptor, VALID_PRIMITIVES)
+ return geometry_for(base, component, subdivision_requested, seg)
raise GeometryNotImplementedError(primitive)
+def decimate_ratio(component: dict[str, Any]) -> float | None:
+ """Read `geometryDescriptor.decimate.targetRatio`, or None when decimation is not asked for.
+
+ Opt-in per component rather than derived from the tessellation tier, because the two
+ solve different halves of the same problem: a tier dials the density of primitives that
+ HAVE segment counts, and decimation is the only lever for geometry that does not -- an
+ implicit surface's density comes from its sampling grid, which is quantised, so the tier
+ can only get near a budget while a ratio can land on it. Running it on every mesh instead
+ would put a quadric collapse on the page-load path for shapes whose density is already
+ exactly what was asked for.
+ """
+ descriptor = component.get("geometryDescriptor")
+ if not isinstance(descriptor, dict):
+ return None
+ decimate = descriptor.get("decimate")
+ if not isinstance(decimate, dict):
+ return None
+ ratio = decimate.get("targetRatio")
+ if isinstance(ratio, bool) or not isinstance(ratio, (int, float)):
+ return None
+ if not 0.0 < float(ratio) < 1.0:
+ return None
+ return float(ratio)
+
+
+def subdivision_iterations(component: dict[str, Any]) -> int:
+ descriptor = component.get("geometryDescriptor")
+ if not isinstance(descriptor, dict):
+ return 0
+ subdivide = descriptor.get("subdivide")
+ if not isinstance(subdivide, dict):
+ return 0
+ iterations = subdivide.get("iterations")
+ if (
+ not isinstance(iterations, int)
+ or isinstance(iterations, bool)
+ or iterations < 1
+ or iterations > MAX_SUBDIVISION_ITERATIONS
+ ):
+ return 0
+ return iterations
+
+
+def component_uses_dense_height_maps(component: dict[str, Any]) -> bool:
+ return (
+ component.get("denseMesh") is True
+ or component.get("geometryDensity") == "dense"
+ or component.get("topologyClass") in {"dense", "implicit"}
+ or subdivision_iterations(component) > 0
+ )
+
+
+BONE_TRACK_DOMAINS = {"character", "hybrid"}
+
+
+def rig_is_bone_track(spec: dict[str, Any]) -> bool:
+ """PLAN_1.5 §8: route on the EXISTING `objectClass.primaryDomain`, no new routing field.
+
+ `object` stays on the pivot track, which §8 says is "not replaced" and stays the default.
+ So this returns False for it and `emit_rig_hierarchy()` emits nothing whatsoever -- an
+ object spec's generated source must remain byte-identical to its pre-plan output.
+ """
+ object_class = (spec.get("preSpecAssessment") or {}).get("objectClass") or {}
+ if object_class.get("primaryDomain") not in BONE_TRACK_DOMAINS:
+ return False
+ rig = spec.get("rig")
+ return isinstance(rig, dict) and bool(rig.get("bones"))
+
+
+def emit_rig_hierarchy(spec: dict[str, Any]) -> list[str]:
+ """Emit the bone hierarchy from `spec["rig"]` — PLAN_1.5 WS-C, first slice.
+
+ Bones ONLY: no `SkinnedMesh`, no `bind()`. Keeping those in a later slice is deliberate,
+ because it means this change cannot alter any existing demo's rendered output — on the
+ pivot track it emits nothing, and on the bone track it only ADDS a hierarchy that nothing
+ is yet bound to. `root.userData.rig.bound` is `false` to say so out loud.
+
+ Two things that are easy to get wrong here:
+
+ - `jointPos` in the spec is **model space** (see `derive_character_rig`'s docstring). A
+ `THREE.Bone`'s position is parent-local, so each bone's offset is its own joint minus its
+ parent's joint; the root keeps its model-space joint unchanged.
+ - Bones are emitted **parents first**. The spec's bone list is sorted by `(has-parent, id)`,
+ so `foot-l` precedes `shin-l` alphabetically — emitting in list order would parent a bone
+ to one that does not exist yet. This walks the tree rather than trusting list order.
+ """
+ if not rig_is_bone_track(spec):
+ return []
+
+ bones = [b for b in spec["rig"]["bones"] if isinstance(b, dict) and b.get("id")]
+ by_id = {b["id"]: b for b in bones}
+
+ ordered: list[dict[str, Any]] = []
+ seen: set[str] = set()
+
+ def visit(bone: dict[str, Any]) -> None:
+ parent = bone.get("parent")
+ if parent and parent in by_id and parent not in seen:
+ visit(by_id[parent])
+ if bone["id"] not in seen:
+ seen.add(bone["id"])
+ ordered.append(bone)
+
+ for bone in bones:
+ visit(bone)
+
+ def bone_var(bone_id: str) -> str:
+ return f"bone_{re.sub(r'[^A-Za-z0-9]', '_', bone_id)}"
+
+ lines = [
+ "",
+ " // PLAN_1.5 WS-C slice 1: bone hierarchy from spec.rig. Model-space joints are",
+ " // converted to parent-local offsets here. Nothing is bound yet (rig.bound === false).",
+ " const bones: Record<string, THREE.Bone> = {};",
+ " const boneOrder: string[] = [];",
+ ]
+ for bone in ordered:
+ bone_id = bone["id"]
+ joint = bone.get("jointPos") or [0.0, 0.0, 0.0]
+ parent = bone.get("parent")
+ var = bone_var(bone_id)
+ if parent and parent in by_id:
+ parent_joint = by_id[parent].get("jointPos") or [0.0, 0.0, 0.0]
+ offset = [float(joint[i]) - float(parent_joint[i]) for i in range(3)]
+ else:
+ offset = [float(joint[i]) for i in range(3)]
+ lines.extend([
+ f" const {var} = new THREE.Bone();",
+ f" {var}.name = {json.dumps(bone_id)};",
+ f" {var}.position.set({vector(offset, [0.0, 0.0, 0.0])});",
+ (f" {bone_var(parent)}.add({var});" if parent and parent in by_id
+ else f" root.add({var});"),
+ f" bones[{json.dumps(bone_id)}] = {var};",
+ f" boneOrder.push({json.dumps(bone_id)});",
+ ])
+ lines.extend([
+ " // The bones are now in REST position. updateMatrixWorld() before constructing the",
+ " // Skeleton is load-bearing: calculateInverses() reads each bone's CURRENT world matrix,",
+ " // and those inverses are what cancel the rest pose during skinning. Constructed before",
+ " // this call it captures identity matrices, the rest pose never cancels, and every",
+ " // vertex is displaced by its bone's offset at rest. Measured, not assumed --",
+ " // scratchpad/bind_experiment.mjs read (0, 3, 0) for a vertex authored at (0, 2, 0).",
+ " root.updateMatrixWorld(true);",
+ " const skeleton = new THREE.Skeleton(boneOrder.map((id) => bones[id]));",
+ " const boneIndexOf = new Map<string, number>(boneOrder.map((id, i) => [id, i]));",
+ ])
+ lines.extend(_rig_weight_function_lines(spec, ordered))
+ lines.extend(_rig_pose_lines(spec, ordered, bone_var))
+ lines.append(" root.userData.rig = { bones, skeleton, boneOrder, boneIndexOf, "
+ "skinAttributes: skinnedMeshNames, bound: skinnedMeshNames.length > 0 "
+ "&& boundCount === skinnedMeshNames.length, "
+ "frustumCulled: false, "
+ "cullingNote: 'skinned meshes set frustumCulled = false; bone motion does not "
+ "update a SkinnedMesh boundingSphere, so a consumer that needs culling must "
+ "recompute bounds per frame' };")
+ return lines
+
+
+def _rig_pose_lines(
+ spec: dict[str, Any],
+ ordered: list[dict[str, Any]],
+ bone_var: Any,
+) -> list[str]:
+ """Move the authored pose from the component pivots onto the BONES.
+
+ `apply_character_pose` writes `component.transform.rotation`, which drives the component's
+ pivot `Group`. Once a body segment is a `SkinnedMesh` its geometry has been baked to model
+ space and reparented to `root`, so the pivot no longer reaches it — the pose has to be
+ re-expressed as bone rotations or it disappears from the render.
+
+ That substitution is exact rather than approximate because a bone's origin IS its
+ component's pivot origin: `derive_character_rig` takes each `jointPos` from the component's
+ proximal end, which is what the spine split in `make_character_component_tree` exists to
+ guarantee, and the bone parent chain mirrors the component parent chain. Same origin, same
+ parent frame, same euler order — so the same euler triple produces the same rotation.
+
+ **Applied after `bind()`, never before.** These rotations are the pose, not the bind pose;
+ setting them before the `Skeleton` is constructed would bake the pose in as rest and nothing
+ would deform.
+ """
+ posed = _posed_bone_rotations(spec, ordered)
+ if not posed:
+ return []
+ lines = [
+ "",
+ " // The authored pose, moved from the pivots onto the bones (see _rig_pose_lines). Set",
+ " // AFTER bind() so that the rest pose -- not this one -- is what the skeleton's inverse",
+ " // bind matrices cancel.",
+ ]
+ for bone_id, _component_id, values in posed:
+ lines.append(f" {bone_var(bone_id)}.rotation.set({vector(values, [0.0, 0.0, 0.0])});")
+ lines.extend([
+ " root.updateMatrixWorld(true);",
+ " skeleton.update();",
+ ])
+ return lines
+
+
+def _posed_bone_rotations(
+ spec: dict[str, Any],
+ ordered: list[dict[str, Any]],
+) -> list[tuple[str, str, list[float]]]:
+ """Every bone whose component carries an authored pose, as `(bone id, component id, euler)`.
+
+ One source for the three places that need it: resting the pivots for the bake, restoring them
+ afterwards, and rotating the bones. Deriving it three times is how the pose ends up applied
+ twice in one of them.
+ """
+ by_component = {c.get("id"): c for c in spec.get("componentTree", []) if isinstance(c, dict)}
+ posed: list[tuple[str, str, list[float]]] = []
+ for bone in ordered:
+ component_id = str(bone.get("component") or bone["id"])
+ rotation = ((by_component.get(component_id) or {}).get("transform") or {}).get("rotation")
+ values = [float(v) for v in (rotation or [0.0, 0.0, 0.0])[:3]]
+ if any(abs(v) > 1e-9 for v in values):
+ posed.append((bone["id"], component_id, values))
+ return posed
+
+
+def _rig_weight_function_lines(spec: dict[str, Any], ordered: list[dict[str, Any]]) -> list[str]:
+ """Emit the PLAN_1.5 §4 weight function ONCE, plus the per-mesh skin attributes it feeds.
+
+ Ported from `forge/stage5_rig/emit_rig.py`, which measured `max |Σw − 1| = 2.98e-8` on real
+ executed geometry. Ported rather than rewritten on purpose: a second implementation of a
+ weight function is exactly what WS-C's "a grep must find no second weight function"
+ acceptance criterion exists to prevent.
+
+ Two things are deliberate:
+
+ - **The envelope radius is computed in Python**, by `derive_envelope_radius` (PLAN_1.5 §4.3),
+ and emitted as a literal. Doing it here reuses the one implementation instead of
+ transcribing the formula into TypeScript, where it could drift.
+ - **The attributes are written but nothing is bound yet.** `skinIndex`/`skinWeight` on a
+ plain `THREE.Mesh` are inert — nothing renders differently — so this slice cannot change
+ any existing output. It also means the emitted function IS called, which matters because
+ both the showcase tsconfig and the test harness compile with `--noUnusedLocals`: an
+ emitted-but-uncalled helper is a hard tsc error, so WS-C.2 genuinely cannot land on its
+ own without this half.
+ """
+ # stage5_rig was deliberately standalone "until WS-C integration" per its own docstring.
+ # This is that integration, so importing its derivation is the intended coupling rather than
+ # transcribing the §4.3 formula into a second place where it could drift.
+ from stage5_rig.rig_spec import derive_envelope_radius # noqa: PLC0415
+
+ by_component = {c.get("id"): c for c in spec.get("componentTree", []) if isinstance(c, dict)}
+ envelope: dict[str, float] = {}
+ for bone in ordered:
+ component = by_component.get(bone.get("component") or bone["id"]) or {}
+ scale = (component.get("transform") or {}).get("scale") or [0.0, 0.0, 0.0]
+ width, depth = float(scale[0]), float(scale[2])
+ if width <= 0 or depth <= 0:
+ width = depth = 0.05
+ envelope[bone["id"]] = round(derive_envelope_radius(width, depth), 6)
+
+ joints = {b["id"]: [float(v) for v in b["jointPos"]] for b in ordered}
+ tips = {b["id"]: [float(v) for v in b["tipPos"]] for b in ordered}
+
+ # The bake below reads `mesh.matrixWorld`, and by this point the pivots already carry the
+ # authored pose -- so baking as-is would freeze the POSE into the geometry while the bones sit
+ # at rest, and the two would disagree by exactly the pose. The pivots are therefore returned to
+ # rest for the duration of the bake and restored afterwards, so that what lands in the vertex
+ # data is the rest pose the skeleton's inverse bind matrices were computed from.
+ posed = _posed_bone_rotations(spec, ordered)
+ if posed:
+ rest_pose_comment = (
+ " // Pivots back to REST for the bake: the geometry that lands in the buffer must be\n"
+ " // the same rest pose the skeleton's inverse bind matrices cancel, not the pose."
+ )
+ rest_pose_lines = [
+ f" nodes[{json.dumps(component_id)}]?.rotation.set(0, 0, 0);"
+ for _bone_id, component_id, _values in posed
+ ]
+ restore_pose_lines = [
+ "",
+ " // Pose restored on the pivots. The skinned meshes no longer hang off them -- they",
+ " // were reparented to `root` -- so this drives only the non-skinned descendants",
+ " // (ear shells, eye cavities), which have no bone of their own and would otherwise",
+ " // stay at rest while the head they sit on turns. The bones get the same rotations",
+ " // applied separately, so nothing is posed twice.",
+ *[
+ f" nodes[{json.dumps(component_id)}]?.rotation.set("
+ f"{vector(values, [0.0, 0.0, 0.0])});"
+ for _bone_id, component_id, values in posed
+ ],
+ " root.updateMatrixWorld(true);",
+ ]
+ else:
+ rest_pose_comment = " // No component carries an authored pose, so there is nothing to rest."
+ rest_pose_lines = []
+ restore_pose_lines = []
+
+ return [
+ "",
+ " // ---- PLAN_1.5 §4 weight function: ONE function over the complete bone set. No",
+ " // mesh-id or vertex-index branching -- only positions, segment endpoints and the",
+ " // envelope radius derived per §4.3. Ported from forge/stage5_rig/emit_rig.py, which",
+ " // measured max |sum(w) - 1| = 2.98e-8 on executed geometry.",
+ f" const BONE_JOINT: Record<string, number[]> = {json.dumps(joints)};",
+ f" const BONE_TIP: Record<string, number[]> = {json.dumps(tips)};",
+ f" const BONE_ENVELOPE: Record<string, number> = {json.dumps(envelope)};",
+ " const _closest = new THREE.Vector3();",
+ " const distanceToSegment = (p: THREE.Vector3, s: number[], e: number[]): number => {",
+ " const ab = [e[0] - s[0], e[1] - s[1], e[2] - s[2]];",
+ " const ap = [p.x - s[0], p.y - s[1], p.z - s[2]];",
+ " const abLenSq = ab[0] * ab[0] + ab[1] * ab[1] + ab[2] * ab[2];",
+ " const t = abLenSq > 1e-12",
+ " ? THREE.MathUtils.clamp((ap[0] * ab[0] + ap[1] * ab[1] + ap[2] * ab[2]) / abLenSq, 0, 1)",
+ " : 0;",
+ " _closest.set(s[0] + ab[0] * t, s[1] + ab[1] * t, s[2] + ab[2] * t);",
+ " return p.distanceTo(_closest);",
+ " };",
+ " const computeVertexWeights = (p: THREE.Vector3) => {",
+ " const scored = boneOrder.map((id) => {",
+ " const d = distanceToSegment(p, BONE_JOINT[id], BONE_TIP[id]);",
+ " const u = d / BONE_ENVELOPE[id];",
+ " const falloff = Math.max(0, 1 - u * u);",
+ " return { id, d, w: falloff * falloff };",
+ " });",
+ " scored.sort((a, b) => b.w - a.w);",
+ " const kept = scored.slice(0, 4);",
+ " const total = kept.reduce((sum, c) => sum + c.w, 0);",
+ " const indices = [0, 0, 0, 0];",
+ " const weights = [0, 0, 0, 0];",
+ " if (total > 0) {",
+ " for (let slot = 0; slot < kept.length; slot++) {",
+ " indices[slot] = boneIndexOf.get(kept[slot].id) ?? 0;",
+ " weights[slot] = kept[slot].w / total;",
+ " }",
+ " return { indices, weights, fallback: false };",
+ " }",
+ " // Mandatory zero-sum fallback (PLAN_1.5 §4 / ADR-8). Without it three.js's own",
+ " // normalizeSkinWeights() rewrites an all-zero vertex to (1,0,0,0) against bone 0",
+ " // regardless of distance, which spikes stray vertices toward the hips. Instead:",
+ " // ignore the envelope and pin weight 1.0 to the absolutely nearest bone.",
+ " let nearest = boneOrder[0];",
+ " let nearestDistance = Infinity;",
+ " for (const id of boneOrder) {",
+ " const d = distanceToSegment(p, BONE_JOINT[id], BONE_TIP[id]);",
+ " if (d < nearestDistance) { nearestDistance = d; nearest = id; }",
+ " }",
+ " indices[0] = boneIndexOf.get(nearest) ?? 0;",
+ " weights[0] = 1;",
+ " return { indices, weights, fallback: true };",
+ " };",
+ "",
+ " // ---- Bake to model space, weight, and bind.",
+ " //",
+ " // The arrangement below was chosen by measurement, not derivation, because the same",
+ " // geometry can be skinned four plausible ways and three of them are wrong. With a",
+ " // vertex authored at model-space (0, 2, 0) fully weighted to a bone at (0, 1, 0) and",
+ " // that bone rotated +90 degrees about X (correct answer: (0, 1, 1)):",
+ " //",
+ " // pivot transform kept, bind identity -> rest pose already wrong, no deformation",
+ " // pivot transform kept, bind matrixWorld -> (0, 1.5, 0.5): HALF the correct swing,",
+ " // because the pivot applies on top of skinning",
+ " // geometry baked, pivot bypassed -> (0, 1, 1): correct",
+ " // no pivot at all -> (0, 1, 1): correct, and identical",
+ " //",
+ " // The last two agreeing is the finding: what matters is that the mesh's own world",
+ " // transform is identity and its geometry lives in the skeleton's space. So each skinned",
+ " // mesh gets its world matrix folded into its vertex data and is reparented to `root`",
+ " // with an identity transform. Meshes are leaves -- components are added to their pivot",
+ " // Group, never to another mesh -- so reparenting one moves nothing else.",
+ rest_pose_comment,
+ *rest_pose_lines,
+ " root.updateMatrixWorld(true);",
+ " const skinnedMeshNames: string[] = [];",
+ " let boundCount = 0;",
+ " for (const boneId of boneOrder) {",
+ " const mesh = meshes[boneId];",
+ " if (!mesh) continue;",
+ " const position = mesh.geometry.getAttribute('position');",
+ " if (!position) continue;",
+ " mesh.updateWorldMatrix(true, false);",
+ " mesh.geometry.applyMatrix4(mesh.matrixWorld);",
+ " root.add(mesh);",
+ " mesh.position.set(0, 0, 0);",
+ " mesh.quaternion.identity();",
+ " mesh.scale.set(1, 1, 1);",
+ " mesh.updateMatrixWorld(true);",
+ " // Vertices are model-space now, which is the space the weight function measures in,",
+ " // so no per-vertex matrix multiply is needed any more.",
+ " const count = position.count;",
+ " const skinIndices = new Uint16Array(count * 4);",
+ " const skinWeights = new Float32Array(count * 4);",
+ " const vertex = new THREE.Vector3();",
+ " for (let v = 0; v < count; v++) {",
+ " vertex.fromBufferAttribute(position, v);",
+ " const { indices, weights } = computeVertexWeights(vertex);",
+ " for (let slot = 0; slot < 4; slot++) {",
+ " skinIndices[v * 4 + slot] = indices[slot];",
+ " skinWeights[v * 4 + slot] = weights[slot];",
+ " }",
+ " }",
+ " mesh.geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(skinIndices, 4));",
+ " mesh.geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeights, 4));",
+ " skinnedMeshNames.push(boneId);",
+ " const skinned = mesh as THREE.SkinnedMesh;",
+ " if (!skinned.isSkinnedMesh) continue;",
+ " // bindMode is left at its default (AttachedBindMode). The bones live under `root`",
+ " // rather than under any one mesh because a single Skeleton is shared by every skinned",
+ " // mesh and cannot be parented under all of them; with root and each mesh at identity",
+ " // the bone world matrices are the same either way.",
+ " skinned.bind(skeleton, new THREE.Matrix4());",
+ " // A SkinnedMesh's boundingSphere is computed from its REST vertex data and is not",
+ " // recomputed when bones move, so a posed limb that swings outside its rest bounds gets",
+ " // culled and vanishes -- worse, it vanishes only from certain camera angles, which",
+ " // reads as a geometry bug rather than a culling one. Disabling the test outright is",
+ " // chosen over recomputing bounds every frame because these are small, always-onscreen",
+ " // character parts where the test saves nothing. Recorded in userData.rig so a consumer",
+ " // that DOES need culling knows it has to supply its own bounds.",
+ " skinned.frustumCulled = false;",
+ " boundCount += 1;",
+ " }",
+ *restore_pose_lines,
+ ]
+
+
def generate(spec: dict[str, Any], pass_id: str) -> str:
+ errors, _warnings = validate_spec(spec)
+ if errors:
+ raise ValueError(f"spec validation failed: {'; '.join(errors)}")
target = str(spec.get("targetName") or "Procedural Object")
type_name = pascal_case(target)
function_name = f"create{type_name}Model"
+ # Resolved once per generate() so every primitive in one model agrees on density.
+ seg = segments_for_spec(spec)
reconstruction_evidence = {
"itemFamily": spec.get("itemFamily"),
"subtype": spec.get("subtype"),
@@ -358,7 +1825,189 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
# projects commonly build with noUnusedLocals, and an always-emitted
# buildLatheGeometry/buildTubeGeometry fails that build the moment a spec (or a
# pass, since blockout only includes macro components) doesn't use them.
- used_primitives = {str(component.get("primitive")) for component in components}
+ def _calls_geometry_for(component: dict[str, Any]) -> bool:
+ # A component whose geometry actually comes from polygonizeSdf() (implicit
+ # SDF) or buildVisualHullGeometry() never calls geometry_for() for its OWN
+ # `primitive` field at all -- that field is descriptive metadata only on
+ # those two paths. Exclude them here so a primitive-specific helper (e.g.
+ # buildWatertightCapsule) isn't emitted-but-unused merely because some OTHER
+ # component happens to share that primitive label while actually building via
+ # SDF/visual-hull -- an always-emitted, never-called helper fails a build with
+ # `--noUnusedLocals` (found via implicit_character_torso_limb.json, whose one
+ # component is `primitive: "capsule"` + `topologyClass: "implicit"`).
+ descriptor = component.get("geometryDescriptor")
+ geometry_descriptor = descriptor if isinstance(descriptor, dict) else {}
+ is_implicit = component.get("topologyClass") == "implicit" and isinstance(geometry_descriptor.get("sdf"), dict)
+ is_visual_hull = isinstance(geometry_descriptor.get("visualHull"), dict)
+ return not is_implicit and not is_visual_hull
+
+ used_primitives = {
+ str(component.get("primitive")) for component in components if _calls_geometry_for(component)
+ }
+ implicit_components = [
+ component
+ for component in components
+ if component.get("topologyClass") == "implicit"
+ and isinstance(component.get("geometryDescriptor"), dict)
+ and isinstance(component["geometryDescriptor"].get("sdf"), dict)
+ ]
+ visual_hull_components = [
+ component
+ for component in components
+ if isinstance(component.get("geometryDescriptor"), dict)
+ and isinstance(component["geometryDescriptor"].get("visualHull"), dict)
+ ]
+ has_subdivision = any(subdivision_iterations(component) > 0 for component in components)
+ has_decimation = any(decimate_ratio(component) is not None for component in components)
+ if visual_hull_components:
+ lines.extend(
+ _VISUAL_HULL_HELPER_SOURCE.replace(
+ "__MAX_VISUAL_HULL_TRIANGLES__",
+ str(MAX_VISUAL_HULL_TRIANGLES),
+ ).splitlines()
+ )
+ lines.append("")
+ if implicit_components:
+ lines.extend(_SDF_HELPER_SOURCE.splitlines())
+ lines.append("")
+ if has_decimation:
+ lines.extend(_DECIMATE_HELPER_SOURCE.splitlines())
+ lines.append("")
+ if has_subdivision:
+ lines.extend(
+ _SUBDIVISION_HELPER_SOURCE.replace(
+ "__MAX_SUBDIVISION_QUAD_FACES__",
+ str(MAX_SUBDIVISION_QUAD_FACES),
+ ).replace(
+ "__MAX_SUBDIVISION_ITERATIONS__",
+ str(MAX_SUBDIVISION_ITERATIONS),
+ ).splitlines()
+ )
+ lines.append("")
+ if "capsule" in used_primitives:
+ lines.extend(
+ [
+ "// THREE.CapsuleGeometry duplicates every UV-seam vertex (measured: 194 boundary",
+ "// edges on the default radius/segments below) -- same benign pattern as box/",
+ "// cylinder/sphere/torus, all of which weld cleanly to 0 given a CORRECT weld.",
+ "// (A naive vertex-only mergeVertices() reports 64 'non-manifold' edges here, but",
+ "// that is a counting artifact, not a real defect: it double-counts a handful of",
+ "// near-pole triangles that become degenerate once two of their three corners",
+ "// coincide -- confirmed by replicating subdivideCatmullClark's own degenerate-",
+ "// triangle-aware vertex identity, which finds a perfectly ordinary 2-manifold.)",
+ "// A capsule is the primary shape for skinned limbs/torso (PLAN_1.5), and skinning",
+ "// weight computation is O(vertices x bones), so fewer, guaranteed-simple vertices",
+ "// is worth having regardless -- authored as a deterministic, closed-by-",
+ "// construction mesh instead: shared pole vertices, and",
+ "// the radial index taken `% radialSegments` so the seam is never a duplicate",
+ "// vertex in the first place, rather than something to weld away afterward.",
+ "// Adapted from forge/stage5_rig/emit_rig.py's buildWatertightCapsule (verified",
+ "// there: 0 boundary edges, 0 non-manifold edges, deterministic across repeated",
+ "// runs) -- ported here rather than imported because this factory and the rig",
+ "// emitter are separate generated-output surfaces with no shared runtime module;",
+ "// see forge/tests/test_primitive_watertightness.py for the measured proof, and",
+ "// coordinate with the rig owner before changing either copy independently.",
+ "function buildWatertightCapsule(",
+ " radius: number,",
+ " cylLength: number,",
+ " capSegments: number,",
+ " radialSegments: number,",
+ " heightSegments: number,",
+ "): THREE.BufferGeometry {",
+ " const positions: number[] = [];",
+ " const indices: number[] = [];",
+ " const uvs: number[] = [];",
+ " const halfCyl = cylLength / 2;",
+ " const totalSpan = 2 * (Math.PI / 2 * radius) + Math.max(0, cylLength);",
+ " const vOf = (fromBottom: number) => (totalSpan > 0 ? fromBottom / totalSpan : 0);",
+ "",
+ " const bottomPoleIndex = positions.length / 3;",
+ " positions.push(0, -halfCyl - radius, 0);",
+ " uvs.push(0.5, vOf(0));",
+ "",
+ " const ringStarts: number[] = [];",
+ " const ringV: number[] = [];",
+ " for (let ring = 1; ring <= capSegments; ring += 1) {",
+ " const phi = (Math.PI / 2) * (ring / capSegments);",
+ " const y = -halfCyl - radius * Math.cos(phi);",
+ " const r = radius * Math.sin(phi);",
+ " const start = positions.length / 3;",
+ " ringStarts.push(start);",
+ " ringV.push(vOf(radius * phi));",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
+ " positions.push(r * Math.cos(theta), y, r * Math.sin(theta));",
+ " uvs.push(radial / radialSegments, vOf(radius * phi));",
+ " }",
+ " }",
+ "",
+ " const cylinderRingStarts: number[] = [];",
+ " if (cylLength > 0) {",
+ " for (let step = 1; step <= heightSegments; step += 1) {",
+ " const y = -halfCyl + (cylLength * step) / heightSegments;",
+ " const start = positions.length / 3;",
+ " cylinderRingStarts.push(start);",
+ " const v = vOf(radius * (Math.PI / 2) + halfCyl + y);",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
+ " positions.push(radius * Math.cos(theta), y, radius * Math.sin(theta));",
+ " uvs.push(radial / radialSegments, v);",
+ " }",
+ " }",
+ " }",
+ "",
+ " const topRingStarts: number[] = [];",
+ " for (let ring = capSegments - 1; ring >= 1; ring -= 1) {",
+ " const phi = (Math.PI / 2) * (ring / capSegments);",
+ " const y = halfCyl + radius * Math.cos(phi);",
+ " const r = radius * Math.sin(phi);",
+ " const start = positions.length / 3;",
+ " topRingStarts.push(start);",
+ " const v = vOf(radius * (Math.PI / 2) + Math.max(0, cylLength) + radius * (Math.PI / 2 - phi));",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const theta = (radial / radialSegments) * Math.PI * 2;",
+ " positions.push(r * Math.cos(theta), y, r * Math.sin(theta));",
+ " uvs.push(radial / radialSegments, v);",
+ " }",
+ " }",
+ "",
+ " const topPoleIndex = positions.length / 3;",
+ " positions.push(0, halfCyl + radius, 0);",
+ " uvs.push(0.5, vOf(totalSpan));",
+ "",
+ " const firstBottomRing = ringStarts[0];",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const next = (radial + 1) % radialSegments;",
+ " indices.push(bottomPoleIndex, firstBottomRing + radial, firstBottomRing + next);",
+ " }",
+ "",
+ " const allRings = [...ringStarts, ...cylinderRingStarts, ...topRingStarts];",
+ " for (let i = 0; i < allRings.length - 1; i += 1) {",
+ " const a = allRings[i];",
+ " const b = allRings[i + 1];",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const next = (radial + 1) % radialSegments;",
+ " indices.push(a + radial, a + next, b + next);",
+ " indices.push(a + radial, b + next, b + radial);",
+ " }",
+ " }",
+ "",
+ " const lastRing = allRings[allRings.length - 1];",
+ " for (let radial = 0; radial < radialSegments; radial += 1) {",
+ " const next = (radial + 1) % radialSegments;",
+ " indices.push(topPoleIndex, lastRing + next, lastRing + radial);",
+ " }",
+ "",
+ " const geometry = new THREE.BufferGeometry();",
+ " geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));",
+ " geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));",
+ " geometry.setIndex(indices);",
+ " geometry.computeVertexNormals();",
+ " return geometry;",
+ "}",
+ "",
+ ]
+ )
if "extrude" in used_primitives:
lines.extend(
[
@@ -547,7 +2196,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" ? '#' + hex.slice(1).split('').map((part) => part + part).join('')",
" : hex;",
" const value = /^#[0-9a-f]{6}$/i.test(normalized) ? Number.parseInt(normalized.slice(1), 16) : 0x8a7a5f;",
- " return [(value >> 16) & 255, (value >> 8) & 255, value & 255];",
+ " return [clampAlbedoChannel((value >> 16) & 255), clampAlbedoChannel((value >> 8) & 255), clampAlbedoChannel(value & 255)];",
"}",
"",
"function materialPalette(spec: SculptMaterialSpec): string[] {",
@@ -562,6 +2211,28 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" return Math.max(0, Math.min(1, value));",
"}",
"",
+ "function clampAlbedoChannel(value: number): number {",
+ " return Math.max(30, Math.min(240, Math.round(value)));",
+ "}",
+ "",
+ "function clampPbrF0(value: number): number {",
+ " return Math.max(0.02, Math.min(1, value));",
+ "}",
+ "",
+ "function clampPbrIor(value: number): number {",
+ " return Math.max(1, Math.min(2.5, value));",
+ "}",
+ "",
+ "function clampPbrMetalness(value: number): number {",
+ " return value >= 0.5 ? 1 : 0;",
+ "}",
+ "",
+ "function clampedAlbedoColor(spec: SculptMaterialSpec): THREE.Color {",
+ " const source = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';",
+ " const [red, green, blue] = hexToRgb(source);",
+ " return new THREE.Color(red / 255, green / 255, blue / 255);",
+ "}",
+ "",
"function smoothCurve(value: number): number {",
" return value * value * (3 - 2 * value);",
"}",
@@ -660,7 +2331,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
"function parseRgba(value: string): [number, number, number] {",
" const match = /rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/.exec(value);",
" if (!match) return [138, 122, 95];",
- " return [Number(match[1]), Number(match[2]), Number(match[3])];",
+ " return [clampAlbedoChannel(Number(match[1])), clampAlbedoChannel(Number(match[2])), clampAlbedoChannel(Number(match[3]))];",
"}",
"",
"// Analytical per-pixel gradient sample. The extraction schema's colorGradient carries",
@@ -916,16 +2587,16 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" };",
"}",
"",
- "function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions): THREE.MeshPhysicalMaterial {",
+ "function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions, denseComponent = false): THREE.MeshPhysicalMaterial {",
" const textures = makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);",
" const material = new THREE.MeshPhysicalMaterial({",
- " color: textures ? 0xffffff : new THREE.Color(typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F'),",
+ " color: textures ? 0xffffff : clampedAlbedoColor(spec),",
" roughness: textures ? 1 : clamp01(readLayerNumber(spec.roughness, ['base'], 0.76)),",
- " metalness: clamp01(readLayerNumber(spec.metalness, ['base'], 0.0)),",
+ " metalness: clampPbrMetalness(readLayerNumber(spec.metalness, ['base'], 0.0)),",
" clearcoat: clamp01(readLayerNumber(spec.clearcoat, ['base', 'amount'], 0)),",
" clearcoatRoughness: clamp01(readLayerNumber(spec.clearcoatRoughness, ['base'], 0.25)),",
" transmission: clamp01(readLayerNumber(spec.transmission, ['base', 'amount'], 0)),",
- " ior: Math.max(1, readLayerNumber(spec.ior, ['base', 'value'], 1.5)),",
+ " ior: clampPbrIor(readLayerNumber(spec.ior, ['base', 'value'], 1.5)),",
" thickness: Math.max(0, readLayerNumber(spec.thickness, ['base', 'amount'], 0)),",
" attenuationDistance: Math.max(0.001, readLayerNumber(spec.attenuationDistance, ['base', 'value'], Infinity)),",
" attenuationColor: new THREE.Color(typeof spec.attenuationColor === 'string' ? spec.attenuationColor : '#ffffff'),",
@@ -933,10 +2604,10 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" sheenColor: new THREE.Color(typeof spec.sheenColor === 'string' ? spec.sheenColor : '#ffffff'),",
" sheenRoughness: clamp01(readLayerNumber(spec.sheenRoughness, ['base'], 1.0)),",
" iridescence: clamp01(readLayerNumber(spec.iridescence, ['base', 'amount'], 0)),",
- " iridescenceIOR: Math.max(1, readLayerNumber(spec.iridescenceIOR, ['base', 'value'], 1.3)),",
+ " iridescenceIOR: clampPbrIor(readLayerNumber(spec.iridescenceIOR, ['base', 'value'], 1.3)),",
" anisotropy: clamp01(readLayerNumber(spec.anisotropy, ['base', 'amount'], 0)),",
" anisotropyRotation: readLayerNumber(spec.anisotropy, ['rotation'], 0),",
- " specularIntensity: clamp01(readLayerNumber(spec.specularIntensity, ['base'], 1.0)),",
+ " specularIntensity: clampPbrF0(readLayerNumber(spec.specularF0 ?? spec.f0 ?? spec.specularIntensity, ['base', 'value'], 1.0)),",
" specularColor: new THREE.Color(typeof spec.specularColor === 'string' ? spec.specularColor : '#ffffff'),",
" emissive: new THREE.Color(typeof spec.emissive === 'string' ? spec.emissive : '#000000'),",
" emissiveIntensity: Math.max(0, readLayerNumber(spec.emissiveIntensity, ['base'], 1.0)),",
@@ -945,6 +2616,12 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" alphaTest: Math.max(0, readLayerNumber(spec.alpha, ['cutoff', 'alphaTest'], 0)),",
" wireframe: options.wireframe ?? false,",
" side: spec.doubleSided === true ? THREE.DoubleSide : THREE.FrontSide,",
+ # Faceted shading is a look, not an optimisation: three.js implements it by giving every
+ # face its own normals, which needs unshared vertices, so the geometry has to be
+ # non-indexed and the vertex count triples (3 per face). It is opt-in per material for
+ # that reason -- turning it on globally would silently spend the budget the
+ # `performanceBudget.targetTriangles` tier just bought back.
+ " flatShading: spec.flatShading === true,",
" });",
" if (textures) {",
" material.map = textures.albedo;",
@@ -954,23 +2631,30 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" material.aoMap = textures.ao;",
" material.aoMap.channel = 0;",
" material.aoMapIntensity = readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35);",
+ " const denseMesh = denseComponent || spec.denseMesh === true || spec.geometryDensity === 'dense' || spec.topologyClass === 'dense';",
" const bumpScale = Math.max(0, readLayerNumber(spec.bump, ['amplitude', 'strength'], 0));",
- " if (bumpScale > 0) {",
+ " const effectiveBumpScale = denseMesh ? Math.max(0.05, bumpScale) : bumpScale;",
+ " if (effectiveBumpScale > 0) {",
" material.bumpMap = textures.height;",
- " material.bumpScale = bumpScale;",
+ " material.bumpScale = effectiveBumpScale;",
" }",
" const displacementScale = Math.max(0, readLayerNumber(spec.displacement, ['amplitude', 'strength'], 0));",
- " if (displacementScale > 0) {",
+ " const effectiveDisplacementScale = denseMesh ? Math.max(0.005, displacementScale) : displacementScale;",
+ " if (effectiveDisplacementScale > 0) {",
" material.displacementMap = textures.height;",
- " material.displacementScale = displacementScale;",
- " material.displacementBias = -displacementScale * 0.5;",
+ " material.displacementScale = effectiveDisplacementScale;",
+ " material.displacementBias = -effectiveDisplacementScale * 0.5;",
" }",
" }",
" material.envMapIntensity = readLayerNumber(spec, ['envMapIntensity'], 0.8);",
" material.userData.sculptMaterial = spec;",
" material.userData.proceduralMapsIndependent = true;",
+ " material.userData.pbrConstraints = { albedoRange: [30, 240], binaryMetalness: true, f0Range: [0.02, 1], iorRange: [1, 2.5] };",
" material.userData.pbrTextureSource = textures?.source ?? 'flat-fallback';",
" material.userData.referencePbr = spec.referencePbr ?? null;",
+ " material.userData.referenceMaterialId = spec.referenceMaterialId ?? spec.materialReference?.profileId ?? null;",
+ " material.userData.materialEvidence = spec.materialEvidence ?? null;",
+ " material.userData.validationViews = spec.materialReference?.validationViews ?? [];",
" material.needsUpdate = true;",
" return material;",
"}",
@@ -1024,6 +2708,8 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" const root = new THREE.Group();",
f" root.name = {json.dumps(target)};",
f" root.userData.reconstructionEvidence = {json_literal(reconstruction_evidence)};",
+ f" root.userData.materialPipeline = {json_literal(spec.get('materialPipeline', {}))};",
+ f" root.userData.materialReferenceRegistry = {json_literal(spec.get('materialReference', spec.get('materialPipeline', {}).get('registry') if isinstance(spec.get('materialPipeline'), dict) else None))};",
"",
" const materialMap: Record<string, THREE.Material> = {};",
]
@@ -1049,6 +2735,15 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
]
)
+ # Components that get a bone need to be SkinnedMesh from the moment they are constructed --
+ # a plain THREE.Mesh cannot be promoted to one after the fact. On the pivot track this set is
+ # empty, so every component stays a THREE.Mesh and the emitted output is unchanged.
+ skinned_ids = (
+ {str(b.get("component") or b.get("id"))
+ for b in spec["rig"]["bones"] if isinstance(b, dict) and b.get("id")}
+ if rig_is_bone_track(spec) else set()
+ )
+
for index, component in enumerate(components):
component_id = str(component.get("id") or f"component-{index}")
component_var = local_var("mesh", component_id, index)
@@ -1065,8 +2760,80 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
attachment_var = local_var("attachment", component_id, index)
endpoint_var = local_var("endpoint", component_id, index)
material_id = str(component.get("material") or next(iter(materials.keys()), "base"))
+ component_material = materials.get(material_id)
+ material_expression = (
+ f"createSculptMaterial({json.dumps(material_id)}, {json_literal(component_material)}, options, true)"
+ if component_uses_dense_height_maps(component) and component_material is not None
+ else f"materialMap[{json.dumps(material_id)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }})"
+ )
parent = component.get("parent") or "root"
name = str(component.get("name") or component_id)
+ descriptor = component.get("geometryDescriptor")
+ geometry_descriptor = descriptor if isinstance(descriptor, dict) else {}
+ sdf = descriptor.get("sdf") if isinstance(descriptor, dict) else None
+ visual_hull = descriptor.get("visualHull") if isinstance(descriptor, dict) else None
+ is_implicit = component.get("topologyClass") == "implicit" and isinstance(sdf, dict)
+ is_visual_hull = isinstance(visual_hull, dict)
+ iterations = subdivision_iterations(component)
+ effective_primitive = resolve_instanced_cluster_base(primitive, geometry_descriptor, VALID_PRIMITIVES)
+ if is_visual_hull:
+ base_geometry_lines = [f" const geometry = buildVisualHullGeometry({json_literal(visual_hull)});"]
+ elif is_implicit:
+ # An SDF's density comes from its sampling grid, not from segment counts, so the
+ # tessellation tier has to reach it separately or it stays the one uncapped source
+ # of triangles in a budgeted model. Marching-cubes output grows with the SURFACE it
+ # crosses, so triangles scale as O(N^2), not O(N^3) -- measured on a capsule field:
+ # N 64 -> 96 -> 128 gave 3,432 -> 7,840 -> 13,960 crossing cells, matching N^2
+ # (1.78, 2.25, 1.78 against predicted 1.78, 2.25, 1.78). Halving N therefore buys
+ # back about 4x, which is why a cap rather than a rewrite is enough here.
+ base_geometry_lines = [
+ f" const geometry = polygonizeSdf({json_literal(capped_sdf(sdf, seg))});"
+ ]
+ else:
+ geometry_expression = (
+ "new THREE.BoxGeometry(1, 1, 1)"
+ if iterations > 0 and effective_primitive == "box"
+ else geometry_for(primitive, component, iterations > 0, seg)
+ )
+ base_geometry_lines = [
+ f" const geometry = {endpoint_var}",
+ f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, {seg['ATTACHMENT_CYLINDER_RADIAL_SEGMENTS']}, {seg['ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS']})",
+ f" : {geometry_expression};",
+ ]
+ if iterations > 0:
+ geometry_lines = [
+ f" const {component_var}Geometry = (() => {{",
+ *base_geometry_lines,
+ f" return subdivideCatmullClark(geometry, {iterations});",
+ " })();",
+ ]
+ elif is_visual_hull:
+ geometry_lines = [f" const {component_var}Geometry = buildVisualHullGeometry({json_literal(visual_hull)});"]
+ elif is_implicit:
+ geometry_lines = [
+ f" const {component_var}Geometry = polygonizeSdf({json_literal(capped_sdf(sdf, seg))});"
+ ]
+ else:
+ geometry_lines = [
+ f" const {component_var}Geometry = {endpoint_var}",
+ f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, {seg['ATTACHMENT_CYLINDER_RADIAL_SEGMENTS']}, {seg['ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS']})",
+ f" : {geometry_for(primitive, component, False, seg)};",
+ ]
+ ratio = decimate_ratio(component)
+ if ratio is not None:
+ # Renaming the dense result and binding the decimated one to the name everything
+ # downstream already uses keeps this a single insertion: mesh construction, the
+ # skin-weight pass and every gate go on reading `<component>Geometry`, and the
+ # decimation lands before any of them. In particular it lands before the bind pass
+ # recomputes skinIndex/skinWeight from `position`, so no skinning data is ever
+ # carried across a vertex merge.
+ dense_var = f"{component_var}GeometryDense"
+ geometry_lines[0] = geometry_lines[0].replace(
+ f"const {component_var}Geometry =", f"const {dense_var} =", 1
+ )
+ geometry_lines.append(
+ f" const {component_var}Geometry = decimateGeometry({dense_var}, {ratio});"
+ )
lines.extend(
[
"",
@@ -1074,25 +2841,42 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
f" const {endpoint_var} = makeAttachmentEndpoint({attachment_var});",
f" const {node_var} = new THREE.Group();",
f" {node_var}.name = {json.dumps(name + '__pivot')};",
+ # PLAN_1.5 WS-E: the hierarchy transform (this pivot Group) never carries
+ # non-uniform scale. A part's shape dimensions are baked directly into its
+ # geometry (see `{component_var}Geometry.scale(...)` below) instead of onto
+ # this node, so a non-uniform component cannot distort a child parented
+ # under it. Position/rotation still cascade normally through the Group chain.
+ f" {node_var}.scale.set(1, 1, 1);",
f" if ({endpoint_var}) {{",
f" {node_var}.position.copy({endpoint_var}.start);",
- f" {node_var}.rotation.set(0, 0, 0);",
- f" {node_var}.scale.set(1, 1, 1);",
+ # The pivot sits AT the joint and the limb's own direction lives on the mesh
+ # inside it (mesh.quaternion = endpoint.quaternion), so rotating this node
+ # rotates the limb about its joint -- which is exactly what a pose is. This used
+ # to be forced to (0,0,0), which silently discarded every authored rotation on
+ # precisely the components that articulate: every capsule/cylinder limb carries
+ # an attachment block and so takes this branch. `anatomy.pose.jointAngles` had
+ # no observable effect until this line stopped zeroing it.
+ f" {node_var}.rotation.set({vector(transform.get('rotation'), [0, 0, 0])});",
" } else {",
f" {node_var}.position.set({vector(transform.get('position'), [0, 0, 0])});",
f" {node_var}.rotation.set({vector(transform.get('rotation'), [0, 0, 0])});",
- f" {node_var}.scale.set({scale_vector(component, transform)});",
" }",
f" {node_var}.userData.sculptComponent = {json.dumps(component, ensure_ascii=False)};",
f" {node_var}.userData.actionProfile = {json.dumps(action_profile, ensure_ascii=False)};",
f" (nodes[{json.dumps(str(parent))}] ?? root).add({node_var});",
f" nodes[{json.dumps(component_id)}] = {node_var};",
- f" const {component_var}Geometry = {endpoint_var}",
- f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, 32, 12)",
- f" : {geometry_for(primitive, component)};",
- f" const {component_var} = new THREE.Mesh(",
+ *geometry_lines,
+ # Attachment geometry (the endpoint branch above) already derives its exact
+ # radius/length from the measured endpoints, so it is not re-scaled here.
+ # Every other primitive is authored unit-sized in geometry_for(); its real
+ # dimensions are applied to the vertex data now, not to the pivot's .scale.
+ f" if (!{endpoint_var}) {{",
+ f" {component_var}Geometry.scale({scale_vector(component, transform)});",
+ " }",
+ f" const {component_var} = new THREE."
+ f"{'SkinnedMesh' if component_id in skinned_ids else 'Mesh'}(",
f" {component_var}Geometry,",
- f" materialMap[{json.dumps(material_id)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }})",
+ f" {material_expression}",
" );",
f" {component_var}.name = {json.dumps(name)};",
f" if ({endpoint_var}) {{",
@@ -1169,8 +2953,17 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
f" // repetition system: {system.get('id') or rep_var} (InstancedMesh, {mode}, count={count}, level={level})",
" {",
f" const parent = nodes[{json.dumps(parent_id)}] ?? root;",
- f" const geo = {geometry_for(primitive, {})};",
+ f" const geo = {geometry_for(primitive, {}, False, seg)};",
f" const mat = materialMap[{json.dumps(rep_material)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }});",
+ " // Contract (PLAN_1.5 WS-E): instanceScale is ABSOLUTE, in the parent pivot's",
+ " // local units -- it is never multiplied by the parent component's own declared",
+ " // dimensional scale. This falls out of the same fix as componentTree: the pivot",
+ " // Group this cluster is parented to always carries identity scale (dimensions are",
+ " // baked into that component's OWN geometry, not exposed on the Group), so an",
+ " // instanced fastener/tooth/spoke sized [0.05, 0.05, 0.05] renders at exactly that",
+ " // size regardless of how non-uniformly its host component is shaped, and a",
+ " // `radial` ring's placement stays circular instead of being squashed into an",
+ " // ellipse by a non-uniform host.",
f" const scl = [{vector(scale, [0.1, 0.1, 0.1])}];",
f" const axis = new THREE.Vector3({vector(axis, [0, 0, 1])}).normalize();",
f" const radius = {float(radius) if isinstance(radius, (int, float)) else 0.0};",
@@ -1200,6 +2993,8 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
]
)
+ lines.extend(emit_rig_hierarchy(spec))
+
look_dev_targets = spec.get("lookDevTargets", {})
lighting_from_photo = spec.get("lightingFromPhoto", [])
lines.extend(
@@ -1364,9 +3159,33 @@ def main(argv: list[str]) -> int:
help="Build pass to generate. Defaults to the current unlocked sculptPipeline pass.",
)
parser.add_argument("--force", action="store_true")
+ parser.add_argument(
+ "--allow-nonstrict",
+ action="store_true",
+ help="Test-fixture escape hatch only; emits non-production code and cannot be used with --pass-id.",
+ )
+ parser.add_argument(
+ "--blocked-report",
+ type=Path,
+ help="Write the machine-readable BLOCKED report when strict-quality prevents generation.",
+ )
args = parser.parse_args(argv)
- spec = load_spec(args.spec.expanduser().resolve())
+ spec_path = args.spec.expanduser().resolve()
+ spec = load_spec(spec_path)
+ _errors, warnings, strict_failures = strict_quality_failures(spec)
+ if strict_failures and not args.allow_nonstrict:
+ emit_blocked(
+ blocked_report(spec_path, strict_failures, warnings, args.pass_id),
+ args.blocked_report,
+ )
+ return 2
+ if args.allow_nonstrict and args.pass_id:
+ parser.error("--allow-nonstrict is test-only and cannot be combined with --pass-id")
+ if _errors:
+ parser.error(f"spec validation failed: {'; '.join(_errors)}")
+ if args.allow_nonstrict:
+ print("WARNING: generating a non-production test-fixture factory (--allow-nonstrict)", file=sys.stderr)
pass_id = args.pass_id or unlocked_pass(spec)
try:
assert_pass_unlocked(spec, pass_id)
diff --git a/forge/stage3_build/morph_targets.py b/forge/stage3_build/morph_targets.py
new file mode 100644
index 0000000..9cc6e1e
--- /dev/null
+++ b/forge/stage3_build/morph_targets.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Morph targets: position deltas for expression, and correctives for what skinning cannot do.
+
+Nothing in this repository emitted morph targets, which closes off two things a character needs.
+
+The obvious one is facial expression. Bones can drive a jaw, but a blink, a sneer or a brow raise is
+surface motion with no skeleton behind it, and Three.js supports it natively through
+`morphAttributes.position` -- a morph target is just a second position buffer, so this needs no new
+runtime machinery at all.
+
+The less obvious one matters more for a rigged character: CORRECTIVE shapes. Linear blend skinning
+always loses volume as a joint closes -- an elbow at 120 degrees pinches, a shoulder collapses -- and
+no weight assignment fixes it, because the artefact is in the interpolation, not in the weights. The
+repair is a shape that fades in as the joint bends and puts the volume back.
+
+Deltas, not absolute positions. Three.js `morphAttributes` with `morphTargetsRelative` expects
+offsets from the base, storing an absolute copy of every vertex per target multiplies memory by the
+number of targets, and a delta array is mostly zeros and compresses to nothing.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+DEFAULT_EPSILON = 1e-6
+
+
+def make_morph_target(
+ base_vertices: list[list[float]],
+ target_vertices: list[list[float]],
+ name: str,
+ epsilon: float = DEFAULT_EPSILON,
+) -> dict[str, Any]:
+ """Delta between two vertex arrays that must correspond one-to-one.
+
+ A mismatched count is refused rather than zip-truncated. Silently pairing the first N vertices of
+ two different meshes produces a morph that looks like a plausible deformation and is nonsense,
+ and nothing downstream can tell.
+ """
+ if len(base_vertices) != len(target_vertices):
+ raise ValueError(
+ f"morph target {name!r} has {len(target_vertices)} vertices but the base has "
+ f"{len(base_vertices)}; targets must share the base's vertex order"
+ )
+ deltas: list[list[float]] = []
+ moved = 0
+ largest = 0.0
+ for base, target in zip(base_vertices, target_vertices):
+ delta = [target[axis] - base[axis] for axis in range(3)]
+ magnitude = math.sqrt(sum(component * component for component in delta))
+ if magnitude > epsilon:
+ moved += 1
+ largest = max(largest, magnitude)
+ else:
+ delta = [0.0, 0.0, 0.0]
+ deltas.append([round(component, 6) for component in delta])
+ return {
+ "name": name,
+ "deltas": deltas,
+ "movedVertexCount": moved,
+ "vertexCount": len(base_vertices),
+ "maxDisplacement": round(largest, 6),
+ # A target that moves nothing is almost always a mistake upstream -- the wrong file, or a pose
+ # that failed to apply -- and it costs a full vertex buffer at runtime to achieve nothing.
+ "isNoOp": moved == 0,
+ }
+
+
+def build_morph_set(
+ base: dict[str, Any],
+ targets: list[dict[str, Any]],
+ epsilon: float = DEFAULT_EPSILON,
+) -> dict[str, Any]:
+ base_vertices = base.get("vertices")
+ if not isinstance(base_vertices, list) or not base_vertices:
+ raise ValueError("base mesh must have vertices")
+ built = [
+ make_morph_target(base_vertices, target["vertices"], str(target.get("name", f"morph{i}")), epsilon)
+ for i, target in enumerate(targets)
+ ]
+ return {
+ "base": str(base.get("name", "base")),
+ "vertexCount": len(base_vertices),
+ "morphTargetsRelative": True,
+ "targets": built,
+ "noOpTargets": [target["name"] for target in built if target["isNoOp"]],
+ "totalMovedVertices": sum(target["movedVertexCount"] for target in built),
+ "note": (
+ "deltas are relative to the base; set mesh.morphTargetsRelative = true in Three.js or "
+ "every target will be interpreted as an absolute position and the mesh will collapse "
+ "toward the origin"
+ ),
+ }
+
+
+def corrective_from_bend(
+ base_vertices: list[list[float]],
+ joint: list[float],
+ axis: list[float],
+ radius: float,
+ volume_gain: float = 0.12,
+) -> list[list[float]]:
+ """A generated corrective: push the surface out radially near a joint.
+
+ This is the shape that compensates for the volume linear blend skinning loses as a joint closes.
+ It is a plausible default, not a simulation: real correctives are sculpted against the actual bent
+ pose. It exists so a rig has something to blend in rather than nothing, and callers who have a
+ real bent pose should use `make_morph_target` with it instead.
+ """
+ length = math.sqrt(sum(component * component for component in axis))
+ if length <= 1e-12:
+ raise ValueError("axis must be non-zero")
+ unit = [component / length for component in axis]
+ moved: list[list[float]] = []
+ for vertex in base_vertices:
+ offset = [vertex[i] - joint[i] for i in range(3)]
+ along = sum(offset[i] * unit[i] for i in range(3))
+ radial = [offset[i] - along * unit[i] for i in range(3)]
+ radial_length = math.sqrt(sum(component * component for component in radial))
+ distance = math.sqrt(sum(component * component for component in offset))
+ if distance > radius or radial_length <= 1e-9:
+ moved.append(list(vertex))
+ continue
+ # Cosine falloff so the corrective blends to zero at the edge of its radius instead of ending
+ # in a hard ring, which would read as a crease of its own.
+ falloff = 0.5 * (1.0 + math.cos(math.pi * distance / radius))
+ scale = volume_gain * falloff
+ moved.append([vertex[i] + radial[i] / radial_length * scale for i in range(3)])
+ return moved
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [
+ f"base: {result['base']} ({result['vertexCount']} vertices)",
+ f"targets: {len(result['targets'])}, moved vertices total: {result['totalMovedVertices']}",
+ ]
+ for target in result["targets"]:
+ lines.append(
+ f" {target['name']}: {target['movedVertexCount']} moved, "
+ f"max displacement {target['maxDisplacement']}"
+ )
+ if result["noOpTargets"]:
+ lines.append(
+ f"NO-OP targets {result['noOpTargets']}: these move nothing and cost a full vertex "
+ "buffer each; check the source pose actually applied"
+ )
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Build morph-target deltas from posed meshes.")
+ parser.add_argument("base", type=Path)
+ parser.add_argument("--target", action="append", default=[], type=Path)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ base = json.loads(args.base.read_text())
+ targets = [json.loads(path.read_text()) for path in args.target]
+ result = build_morph_set(base, targets)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
+ return 1 if result["noOpTargets"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage3_build/orchestrate_passes.py b/forge/stage3_build/orchestrate_passes.py
index 3d67090..cd1d555 100755
--- a/forge/stage3_build/orchestrate_passes.py
+++ b/forge/stage3_build/orchestrate_passes.py
@@ -347,6 +347,23 @@ def material_pass_gaps(spec: dict[str, Any]) -> list[str]:
gaps.append("no material defines roughness variation or normal/bump/displacement response")
if not any(material_has_locality(item) for item in materials):
gaps.append("no material defines local overrides, AO, dirt, wear, stains, moss, chips, or scratches")
+ material_pipeline = spec.get("materialPipeline")
+ if material_pipeline is not None:
+ if not isinstance(material_pipeline, dict) or material_pipeline.get("status") != "proceed":
+ gaps.append("materialPipeline must be wired and have status=proceed before material-pass")
+ else:
+ regions = material_pipeline.get("regions", [])
+ if not isinstance(regions, list) or not regions:
+ gaps.append("materialPipeline.regions must contain analyzed material regions")
+ else:
+ gaps.extend(
+ f"material region {region.get('regionId')!r} is not accepted ({region.get('status')!r})"
+ for region in regions
+ if isinstance(region, dict) and region.get("status") != "proceed"
+ )
+ gate = spec.get("materialGate")
+ if gate is not None and (not isinstance(gate, dict) or gate.get("passed") is not True):
+ gaps.append("materialGate.passed must be true after crop/render comparison")
if quality_first_enabled(spec):
for material in materials:
if material.get("qualityTier") == "utility":
diff --git a/forge/stage3_build/uv_unwrap.py b/forge/stage3_build/uv_unwrap.py
new file mode 100644
index 0000000..e3cb2b0
--- /dev/null
+++ b/forge/stage3_build/uv_unwrap.py
@@ -0,0 +1,622 @@
+#!/usr/bin/env python3
+"""UV unwrapping: chart segmentation, least-squares conformal mapping, and packing.
+
+Nothing in this repository produced UVs. That is not a cosmetic gap -- it is the missing link that
+makes the whole material track unreachable. Without a UV layout there is nowhere to bake a projected
+photograph, so `bake_projected_texture.py` can only ever emit a descriptor; and there is nowhere to
+bake a normal or an ambient-occlusion map either. The pipeline's own guidance calls
+projection-first texturing the single biggest fidelity lever, and it has been resting on a step that
+did not exist.
+
+Three analytic stages, no machine learning anywhere:
+
+1. CHART SEGMENTATION by normal similarity. A single chart over a closed surface is impossible
+ without a cut, and a conformal map of a highly curved region has unbounded area distortion, so the
+ surface is grown into near-planar regions first.
+
+2. LSCM (Lévy et al. 2002). Each triangle is flattened into its own plane, and the conformal
+ condition -- that the map is locally a rotation and scale, never a shear -- becomes two linear
+ equations per triangle. Two pinned vertices fix the remaining translation/rotation/scale freedom.
+ The overdetermined system is solved in the least-squares sense by conjugate gradient on the normal
+ equations, which needs only sparse mat-vec products and therefore no third-party linear algebra.
+
+ LSCM preserves ANGLES, not AREAS. A conformal map of a region with real Gaussian curvature must
+ distort area somewhere; that is a theorem, not an implementation shortcoming. `areaDistortion` is
+ reported per chart so the caller can see how much, and segmentation is what keeps it bounded.
+
+3. PACKING into the unit square by a skyline heuristic. This is a heuristic, and it is reported as
+ `packingEfficiency` rather than claimed as optimal -- rectangle packing is NP-hard.
+
+LSCM requires each chart to be a topological disk. Normal-based growing does not guarantee that, so
+each chart's Euler characteristic is checked and non-disk charts are REPORTED rather than silently
+flattened into a tangle. A fold-over would otherwise look like a valid layout right up until the bake.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+# Measured on a real 4162-vertex organic skull, sweeping the threshold and counting inverted
+# triangles: 50 deg -> 40 flips, 35 -> 2, 25 -> 0, 18 -> 2, 12 -> 13. 25 is the widest setting that
+# folded nothing, and wider charts mean fewer seams, so it is the default. Hard-surface subjects
+# tolerate more; the flag exists for that.
+DEFAULT_CHART_ANGLE_DEGREES = 25.0
+DEFAULT_CG_ITERATIONS = 400
+DEFAULT_CG_TOLERANCE = 1e-8
+DEFAULT_CHART_PADDING = 0.004
+MIN_TRIANGLE_AREA = 1e-12
+
+
+# ---------------------------------------------------------------------------
+# Mesh helpers
+# ---------------------------------------------------------------------------
+
+def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
+ if indices and isinstance(indices[0], (list, tuple)):
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
+ return [
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
+ for i in range(0, len(indices) - 2, 3)
+ ]
+
+
+def _sub(a: list[float], b: list[float]) -> list[float]:
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+
+
+def _cross(a: list[float], b: list[float]) -> list[float]:
+ return [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+ ]
+
+
+def _dot(a: list[float], b: list[float]) -> float:
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+
+
+def _norm(a: list[float]) -> float:
+ return math.sqrt(_dot(a, a))
+
+
+def _face_normal(vertices: list[list[float]], face: tuple[int, int, int]) -> tuple[list[float], float]:
+ p0, p1, p2 = (vertices[i] for i in face)
+ n = _cross(_sub(p1, p0), _sub(p2, p0))
+ length = _norm(n)
+ if length <= MIN_TRIANGLE_AREA:
+ return [0.0, 0.0, 0.0], 0.0
+ return [n[0] / length, n[1] / length, n[2] / length], length / 2.0
+
+
+# ---------------------------------------------------------------------------
+# 1. Chart segmentation
+# ---------------------------------------------------------------------------
+
+def segment_charts(
+ vertices: list[list[float]],
+ faces: list[tuple[int, int, int]],
+ angle_threshold_degrees: float = DEFAULT_CHART_ANGLE_DEGREES,
+) -> list[list[int]]:
+ """Grow near-planar regions across shared edges.
+
+ Growth is compared against the SEED's normal rather than the neighbour's. Comparing against the
+ neighbour lets a chart creep around a cylinder one tolerable step at a time until its two ends
+ face opposite directions, which is exactly the runaway a threshold is supposed to prevent.
+ """
+ cos_limit = math.cos(math.radians(angle_threshold_degrees))
+ normals = [_face_normal(vertices, face)[0] for face in faces]
+
+ edge_faces: dict[tuple[int, int], list[int]] = {}
+ for index, (a, b, c) in enumerate(faces):
+ for u, v in ((a, b), (b, c), (c, a)):
+ key = (u, v) if u < v else (v, u)
+ edge_faces.setdefault(key, []).append(index)
+
+ neighbours: list[list[int]] = [[] for _ in faces]
+ for shared in edge_faces.values():
+ if len(shared) != 2:
+ continue
+ first, second = shared
+ neighbours[first].append(second)
+ neighbours[second].append(first)
+
+ unassigned = set(range(len(faces)))
+ charts: list[list[int]] = []
+ while unassigned:
+ seed = min(unassigned)
+ seed_normal = normals[seed]
+ chart = [seed]
+ unassigned.discard(seed)
+ queue = [seed]
+ while queue:
+ current = queue.pop()
+ for neighbour in neighbours[current]:
+ if neighbour not in unassigned:
+ continue
+ if _dot(seed_normal, normals[neighbour]) < cos_limit:
+ continue
+ unassigned.discard(neighbour)
+ chart.append(neighbour)
+ queue.append(neighbour)
+ charts.append(sorted(chart))
+ return charts
+
+
+def _chart_adjacency(faces: list[tuple[int, int, int]], chart: list[int]) -> dict[int, list[int]]:
+ """Face adjacency restricted to one chart."""
+ edge_faces: dict[tuple[int, int], list[int]] = {}
+ for index in chart:
+ a, b, c = faces[index]
+ for u, v in ((a, b), (b, c), (c, a)):
+ edge_faces.setdefault((u, v) if u < v else (v, u), []).append(index)
+ adjacency: dict[int, list[int]] = {index: [] for index in chart}
+ for shared in edge_faces.values():
+ if len(shared) != 2:
+ continue
+ first, second = shared
+ adjacency[first].append(second)
+ adjacency[second].append(first)
+ return adjacency
+
+
+def _split_chart(faces: list[tuple[int, int, int]], chart: list[int]) -> tuple[list[int], list[int]]:
+ """Break a chart into a connected half and the remainder, by breadth-first growth.
+
+ Breadth-first rather than by a cutting plane: a plane can slice a chart into pieces that are not
+ connected, and a disconnected piece is not a disk either, so the recursion would not terminate on
+ the thing it was called to fix.
+ """
+ adjacency = _chart_adjacency(faces, chart)
+ target = max(1, len(chart) // 2)
+ start = chart[0]
+ taken = [start]
+ seen = {start}
+ queue = [start]
+ while queue and len(taken) < target:
+ current = queue.pop(0)
+ for neighbour in adjacency[current]:
+ if neighbour in seen:
+ continue
+ seen.add(neighbour)
+ taken.append(neighbour)
+ queue.append(neighbour)
+ if len(taken) >= target:
+ break
+ remainder = [index for index in chart if index not in seen]
+ return sorted(taken), sorted(remainder)
+
+
+def enforce_disk_charts(
+ faces: list[tuple[int, int, int]],
+ charts: list[list[int]],
+ max_charts: int = 4096,
+) -> tuple[list[list[int]], int]:
+ """Subdivide until every chart is a topological disk.
+
+ Reporting a non-disk chart is not enough. LSCM returns UVs for one regardless, and they fold over
+ -- measured on a real 4162-vertex skull, seven non-disk charts drove worst-case area distortion to
+ 171300 and produced twelve inverted triangles. A single triangle is always a disk, so this
+ terminates; `max_charts` only bounds pathological input.
+ """
+ resolved: list[list[int]] = []
+ pending = [list(chart) for chart in charts]
+ splits = 0
+ while pending:
+ chart = pending.pop()
+ if len(resolved) + len(pending) >= max_charts:
+ resolved.append(chart)
+ continue
+ if len(chart) <= 1 or chart_is_disk(faces, chart):
+ resolved.append(chart)
+ continue
+ first, second = _split_chart(faces, chart)
+ # A split that fails to shrink the chart would loop forever; keep it and let it be reported.
+ if not first or not second:
+ resolved.append(chart)
+ continue
+ splits += 1
+ pending.extend((first, second))
+ return sorted(resolved), splits
+
+
+def chart_is_disk(faces: list[tuple[int, int, int]], chart: list[int]) -> bool:
+ """Euler characteristic V - E + F == 1 identifies a disk.
+
+ A chart that closes into a tube or a sphere has no valid flattening at all, and LSCM will happily
+ return one anyway -- overlapping, folded, and indistinguishable from a good layout in the numbers.
+ """
+ verts: set[int] = set()
+ edges: set[tuple[int, int]] = set()
+ for index in chart:
+ a, b, c = faces[index]
+ verts.update((a, b, c))
+ for u, v in ((a, b), (b, c), (c, a)):
+ edges.add((u, v) if u < v else (v, u))
+ return len(verts) - len(edges) + len(chart) == 1
+
+
+# ---------------------------------------------------------------------------
+# 2. LSCM
+# ---------------------------------------------------------------------------
+
+def _local_coordinates(
+ vertices: list[list[float]], face: tuple[int, int, int]
+) -> tuple[tuple[float, float], tuple[float, float], tuple[float, float]] | None:
+ """Isometrically flatten one triangle into its own plane."""
+ p0, p1, p2 = (vertices[i] for i in face)
+ e1 = _sub(p1, p0)
+ length = _norm(e1)
+ if length <= MIN_TRIANGLE_AREA:
+ return None
+ axis_x = [component / length for component in e1]
+ e2 = _sub(p2, p0)
+ x2 = _dot(e2, axis_x)
+ perpendicular = [e2[i] - x2 * axis_x[i] for i in range(3)]
+ y2 = _norm(perpendicular)
+ if y2 <= MIN_TRIANGLE_AREA:
+ return None
+ return (0.0, 0.0), (length, 0.0), (x2, y2)
+
+
+def _conjugate_gradient(
+ rows: list[list[tuple[int, float]]],
+ rhs: list[float],
+ unknowns: int,
+ iterations: int,
+ tolerance: float,
+) -> list[float]:
+ """Least squares by CG on the normal equations, with only sparse mat-vecs.
+
+ Never forms M^T M. That matrix is dense enough to be the memory wall this whole approach exists to
+ avoid, and CG only ever needs its product with a vector.
+ """
+
+ def multiply(x: list[float]) -> list[float]:
+ return [sum(value * x[column] for column, value in row) for row in rows]
+
+ def multiply_transpose(y: list[float]) -> list[float]:
+ out = [0.0] * unknowns
+ for row, weight in zip(rows, y):
+ for column, value in row:
+ out[column] += value * weight
+ return out
+
+ x = [0.0] * unknowns
+ residual = multiply_transpose(rhs)
+ direction = list(residual)
+ residual_norm = sum(value * value for value in residual)
+ if residual_norm <= tolerance:
+ return x
+ for _ in range(iterations):
+ md = multiply(direction)
+ denominator = sum(value * value for value in md)
+ if denominator <= 1e-30:
+ break
+ step = residual_norm / denominator
+ for i in range(unknowns):
+ x[i] += step * direction[i]
+ residual = [a - step * b for a, b in zip(residual, multiply_transpose(md))]
+ new_norm = sum(value * value for value in residual)
+ if new_norm <= tolerance:
+ break
+ beta = new_norm / residual_norm
+ residual_norm = new_norm
+ direction = [r + beta * d for r, d in zip(residual, direction)]
+ return x
+
+
+def lscm(
+ vertices: list[list[float]],
+ faces: list[tuple[int, int, int]],
+ chart: list[int],
+ iterations: int = DEFAULT_CG_ITERATIONS,
+ tolerance: float = DEFAULT_CG_TOLERANCE,
+) -> dict[int, tuple[float, float]]:
+ """Flatten one chart, returning UV per original vertex index."""
+ chart_vertices = sorted({v for index in chart for v in faces[index]})
+ position = {v: i for i, v in enumerate(chart_vertices)}
+ if len(chart_vertices) < 3:
+ return {v: (0.0, 0.0) for v in chart_vertices}
+
+ # Pin the two most distant vertices. Pinning adjacent ones leaves the solve nearly free to rotate
+ # and scale, and CG then wanders instead of converging.
+ pin_a, pin_b, best = chart_vertices[0], chart_vertices[1], -1.0
+ for i, vi in enumerate(chart_vertices):
+ for vj in chart_vertices[i + 1:]:
+ distance = _norm(_sub(vertices[vi], vertices[vj]))
+ if distance > best:
+ best, pin_a, pin_b = distance, vi, vj
+ if best <= MIN_TRIANGLE_AREA:
+ return {v: (0.0, 0.0) for v in chart_vertices}
+
+ pinned = {pin_a: (0.0, 0.0), pin_b: (best, 0.0)}
+ free = [v for v in chart_vertices if v not in pinned]
+ column_of = {v: i for i, v in enumerate(free)}
+ unknowns = 2 * len(free)
+ if unknowns == 0:
+ return dict(pinned)
+
+ rows: list[list[tuple[int, float]]] = []
+ rhs: list[float] = []
+ for index in chart:
+ face = faces[index]
+ local = _local_coordinates(vertices, face)
+ if local is None:
+ continue
+ (x1, y1), (x2, y2), (x3, y3) = local
+ area = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0
+ if area <= MIN_TRIANGLE_AREA:
+ continue
+ scale = 1.0 / math.sqrt(2.0 * area)
+ w = [
+ ((x3 - x2) * scale, (y3 - y2) * scale),
+ ((x1 - x3) * scale, (y1 - y3) * scale),
+ ((x2 - x1) * scale, (y2 - y1) * scale),
+ ]
+ # Sum_j W_j * U_j = 0 over the complex plane, split into its real and imaginary parts.
+ real_row: list[tuple[int, float]] = []
+ imaginary_row: list[tuple[int, float]] = []
+ real_rhs = 0.0
+ imaginary_rhs = 0.0
+ for corner, vertex in enumerate(face):
+ wr, wi = w[corner]
+ if vertex in pinned:
+ pu, pv = pinned[vertex]
+ real_rhs -= wr * pu - wi * pv
+ imaginary_rhs -= wi * pu + wr * pv
+ else:
+ column = column_of[vertex]
+ real_row.append((column, wr))
+ real_row.append((len(free) + column, -wi))
+ imaginary_row.append((column, wi))
+ imaginary_row.append((len(free) + column, wr))
+ rows.append(real_row)
+ rhs.append(real_rhs)
+ rows.append(imaginary_row)
+ rhs.append(imaginary_rhs)
+
+ solution = _conjugate_gradient(rows, rhs, unknowns, iterations, tolerance)
+ uv = dict(pinned)
+ for vertex in free:
+ column = column_of[vertex]
+ uv[vertex] = (solution[column], solution[len(free) + column])
+ return uv
+
+
+# ---------------------------------------------------------------------------
+# Distortion
+# ---------------------------------------------------------------------------
+
+def chart_distortion(
+ vertices: list[list[float]],
+ faces: list[tuple[int, int, int]],
+ chart: list[int],
+ uv: dict[int, tuple[float, float]],
+) -> dict[str, float]:
+ """Worst per-triangle area scaling, normalised so a perfect map scores 1.0.
+
+ Reported as a ratio of the WORST triangle to the chart's median, not as an absolute UV area: an
+ absolute number changes with the arbitrary global scale of the layout and would make two identical
+ unwraps at different scales look different.
+ """
+ ratios: list[float] = []
+ flipped = 0
+ for index in chart:
+ face = faces[index]
+ _, area3d = _face_normal(vertices, face)
+ if area3d <= MIN_TRIANGLE_AREA:
+ continue
+ (u1, v1), (u2, v2), (u3, v3) = (uv[v] for v in face)
+ signed = ((u2 - u1) * (v3 - v1) - (u3 - u1) * (v2 - v1)) / 2.0
+ if signed <= 0:
+ flipped += 1
+ area2d = abs(signed)
+ if area2d <= MIN_TRIANGLE_AREA:
+ continue
+ ratios.append(area2d / area3d)
+ if not ratios:
+ return {"areaDistortion": float("inf"), "flippedTriangles": flipped}
+ ratios.sort()
+ median = ratios[len(ratios) // 2]
+ if median <= 0:
+ return {"areaDistortion": float("inf"), "flippedTriangles": flipped}
+ worst = max(max(ratios) / median, median / max(min(ratios), 1e-30))
+ return {"areaDistortion": round(worst, 6), "flippedTriangles": flipped}
+
+
+# ---------------------------------------------------------------------------
+# 3. Packing
+# ---------------------------------------------------------------------------
+
+def pack_charts(
+ chart_uvs: list[dict[int, tuple[float, float]]],
+ padding: float = DEFAULT_CHART_PADDING,
+) -> tuple[list[dict[int, tuple[float, float]]], float]:
+ """Skyline packing of chart bounding boxes into the unit square.
+
+ A heuristic, and reported as one. Charts are normalised to preserve their relative scale so a
+ small chart does not get blown up to the same texel density as a large one -- uniform texel
+ density is the property a bake actually needs.
+ """
+ boxes = []
+ for uv in chart_uvs:
+ if not uv:
+ boxes.append((0.0, 0.0, 0.0, 0.0))
+ continue
+ us = [p[0] for p in uv.values()]
+ vs = [p[1] for p in uv.values()]
+ boxes.append((min(us), min(vs), max(us) - min(us), max(vs) - min(vs)))
+
+ largest = max((max(w, h) for _, _, w, h in boxes), default=0.0)
+ if largest <= 0:
+ return [dict(uv) for uv in chart_uvs], 0.0
+
+ order = sorted(range(len(boxes)), key=lambda i: -boxes[i][3])
+ placed: list[dict[int, tuple[float, float]]] = [dict() for _ in chart_uvs]
+ cursor_x = 0.0
+ cursor_y = 0.0
+ shelf_height = 0.0
+ used_area = 0.0
+
+ for index in order:
+ min_u, min_v, width, height = boxes[index]
+ scale = 1.0 / (largest * (len(boxes) ** 0.5 + 1))
+ w = width * scale
+ h = height * scale
+ if cursor_x + w + padding > 1.0:
+ cursor_x = 0.0
+ cursor_y += shelf_height + padding
+ shelf_height = 0.0
+ shelf_height = max(shelf_height, h)
+ for vertex, (u, v) in chart_uvs[index].items():
+ placed[index][vertex] = (
+ cursor_x + (u - min_u) * scale,
+ cursor_y + (v - min_v) * scale,
+ )
+ cursor_x += w + padding
+ used_area += w * h
+
+ total_height = cursor_y + shelf_height
+ efficiency = used_area / max(total_height, 1e-9) if total_height > 0 else 0.0
+ return placed, round(min(efficiency, 1.0), 6)
+
+
+# ---------------------------------------------------------------------------
+# Public entry point
+# ---------------------------------------------------------------------------
+
+def unwrap(mesh: dict[str, Any], angle_threshold_degrees: float = DEFAULT_CHART_ANGLE_DEGREES) -> dict[str, Any]:
+ vertices = mesh.get("vertices")
+ indices = mesh.get("indices")
+ if not isinstance(vertices, list) or not vertices:
+ raise ValueError("mesh.vertices must be a non-empty array")
+ if not isinstance(indices, list) or len(indices) < 3:
+ raise ValueError("mesh.indices must describe at least one triangle")
+
+ faces = _triangles(indices)
+ charts = segment_charts(vertices, faces, angle_threshold_degrees)
+ charts, topology_splits = enforce_disk_charts(faces, charts)
+
+ uv_all: list[tuple[float, float]] = [(0.0, 0.0)] * len(vertices)
+ chart_uvs: list[dict[int, tuple[float, float]]] = []
+ reports: list[dict[str, Any]] = []
+ non_disk: list[int] = []
+
+ for number, chart in enumerate(charts):
+ is_disk = chart_is_disk(faces, chart)
+ if not is_disk:
+ non_disk.append(number)
+ uv = lscm(vertices, faces, chart)
+ chart_uvs.append(uv)
+ distortion = chart_distortion(vertices, faces, chart, uv)
+ reports.append({
+ "chart": number,
+ "faceCount": len(chart),
+ "vertexCount": len(uv),
+ "isDisk": is_disk,
+ **distortion,
+ })
+
+ packed, efficiency = pack_charts(chart_uvs)
+ # A vertex on a chart seam belongs to more than one chart. Writing whichever chart lands last is
+ # what produces a visible seam artefact, so the split is reported instead of hidden: the caller
+ # must duplicate those vertices before baking.
+ seam_vertices: set[int] = set()
+ seen: dict[int, int] = {}
+ for number, uv in enumerate(packed):
+ for vertex, coordinate in uv.items():
+ if vertex in seen and seen[vertex] != number:
+ seam_vertices.add(vertex)
+ seen[vertex] = number
+ uv_all[vertex] = coordinate
+
+ # Weighted by face count, and reported as a distribution rather than a single worst case. The max
+ # alone is not a usable quality signal here: sweeping the segmentation threshold on a real skull
+ # produced 2299 -> 93609 -> 6595 -> 378 -> 15.85, which is not a trend, it is one sliver chart
+ # dominating a max while the other two hundred charts stayed fine. A layout is good or bad by how
+ # much of its SURFACE maps well.
+ weighted: list[float] = []
+ for report in reports:
+ if math.isfinite(report["areaDistortion"]):
+ weighted.extend([report["areaDistortion"]] * report["faceCount"])
+ weighted.sort()
+
+ def percentile(fraction: float) -> float | None:
+ if not weighted:
+ return None
+ return round(weighted[min(len(weighted) - 1, int(fraction * len(weighted)))], 6)
+
+ finite = [report["areaDistortion"] for report in reports if math.isfinite(report["areaDistortion"])]
+ return {
+ "areaDistortionMedian": percentile(0.5),
+ "areaDistortionP95": percentile(0.95),
+ "uv": [[round(u, 6), round(v, 6)] for u, v in uv_all],
+ "chartCount": len(charts),
+ "charts": reports,
+ "nonDiskCharts": non_disk,
+ "topologySplits": topology_splits,
+ "packingEfficiency": efficiency,
+ "worstAreaDistortion": round(max(finite), 6) if finite else None,
+ "totalFlippedTriangles": sum(report["flippedTriangles"] for report in reports),
+ "seamVertexCount": len(seam_vertices),
+ "seamVertices": sorted(seam_vertices)[:64],
+ "notes": [
+ "LSCM preserves angles, not areas; area distortion over a curved chart is unavoidable "
+ "and is bounded by segmentation, not by the solver",
+ "packing is a skyline heuristic, not an optimal packing",
+ "vertices listed in seamVertices carry more than one UV and must be duplicated before a bake",
+ ],
+ }
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [
+ f"charts: {result['chartCount']}",
+ f"packing efficiency: {result['packingEfficiency']}",
+ f"area distortion: median {result['areaDistortionMedian']}, "
+ f"p95 {result['areaDistortionP95']}, worst {result['worstAreaDistortion']} "
+ "(read the median and p95; the max is one sliver chart away from meaningless)",
+ f"flipped triangles: {result['totalFlippedTriangles']}",
+ f"seam vertices: {result['seamVertexCount']}",
+ ]
+ if result["nonDiskCharts"]:
+ lines.append(
+ f"NON-DISK charts {result['nonDiskCharts']}: these have no valid flattening and their "
+ "UVs will fold over; cut them before baking"
+ )
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Unwrap a mesh into a UV layout.")
+ parser.add_argument("mesh", type=Path, help="JSON file with vertices and indices")
+ parser.add_argument("--angle", type=float, default=DEFAULT_CHART_ANGLE_DEGREES)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ mesh = json.loads(args.mesh.read_text())
+ if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
+ mesh = mesh["meshes"][0]
+ result = unwrap(mesh, args.angle)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
+ # Fold-overs and non-disk charts are the two states where the layout is unusable rather than
+ # merely imperfect, so they are the only ones that fail the run.
+ return 1 if result["totalFlippedTriangles"] or result["nonDiskCharts"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage3_build/visual_hull.py b/forge/stage3_build/visual_hull.py
new file mode 100644
index 0000000..4a5c56b
--- /dev/null
+++ b/forge/stage3_build/visual_hull.py
@@ -0,0 +1,357 @@
+"""Visual-hull descriptor validation, and the space carving it describes.
+
+Until now this module only VALIDATED a `visualHull` descriptor; nothing carved one. A schema without
+an implementation reads downstream as a shipped capability, and the pipeline's own docs cite visual
+hull as a way to constrain hidden geometry it never actually constrained. `carve_visual_hull` closes
+that: it consumes exactly the descriptor `validate_visual_hull_descriptor` accepts and returns a real
+mesh.
+
+What a visual hull can and cannot do, stated here because the caller must not over-read the result:
+it is the INTERSECTION OF SILHOUETTE CONES, so it is an upper bound on the true shape. It can never
+represent a concavity that does not break the silhouette from some supplied view -- an eye socket, the
+inside of a cupped ear, the hollow of a bowl. With two views it is the intersection of two prisms,
+which is loose; the third axis is unconstrained and the result extrudes along it. `carve_visual_hull`
+reports `unconstrainedAxes` and `limitations` for exactly this reason: a hull is evidence about the
+silhouette, not about the surface.
+
+Image conventions, fixed here so a caller can match them:
+ front columns follow +x left-to-right, rows follow -y top-to-bottom
+ side columns follow +z left-to-right, rows follow -y top-to-bottom
+ top columns follow +x left-to-right, rows follow +z top-to-bottom
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+
+MAX_VISUAL_HULL_RESOLUTION = 32
+MAX_VISUAL_HULL_TRIANGLES = 400_000
+MIN_VISUAL_HULL_MASK_DIMENSION = 4
+MAX_VISUAL_HULL_MASK_DIMENSION = 256
+VALID_VISUAL_HULL_AXES = {"front", "side", "top"}
+_DESCRIPTOR_FIELDS = {"projection", "boundsSpace", "bounds", "resolution", "triangleBudget", "views", "hiddenRegions"}
+_VIEW_FIELDS = {"axis", "confidence", "mask"}
+
+
+def _is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _validate_vector(value: Any, label: str, errors: list[str]) -> None:
+ if not isinstance(value, list) or len(value) != 3:
+ errors.append(f"{label} must be [number, number, number]")
+ return
+ for index, item in enumerate(value):
+ if not _is_number(item):
+ errors.append(f"{label}[{index}] must be numeric")
+ elif not math.isfinite(float(item)):
+ errors.append(f"{label}[{index}] must be finite")
+
+
+def _validate_mask(value: Any, label: str, errors: list[str]) -> None:
+ if not isinstance(value, list) or not value:
+ errors.append(f"{label} must be a non-empty array of binary strings")
+ return
+ if len(value) < MIN_VISUAL_HULL_MASK_DIMENSION or len(value) > MAX_VISUAL_HULL_MASK_DIMENSION:
+ errors.append(
+ f"{label} height must be from {MIN_VISUAL_HULL_MASK_DIMENSION} to {MAX_VISUAL_HULL_MASK_DIMENSION}"
+ )
+ width: int | None = None
+ foreground = 0
+ for index, row in enumerate(value):
+ row_label = f"{label}[{index}]"
+ if not isinstance(row, str) or not row:
+ errors.append(f"{row_label} must be a non-empty binary string")
+ continue
+ if any(bit not in {"0", "1"} for bit in row):
+ errors.append(f"{row_label} must contain only '0' and '1'")
+ if width is None:
+ width = len(row)
+ elif len(row) != width:
+ errors.append(f"{label} rows must all have the same width")
+ foreground += row.count("1")
+ if width is not None and (width < MIN_VISUAL_HULL_MASK_DIMENSION or width > MAX_VISUAL_HULL_MASK_DIMENSION):
+ errors.append(
+ f"{label} width must be from {MIN_VISUAL_HULL_MASK_DIMENSION} to {MAX_VISUAL_HULL_MASK_DIMENSION}"
+ )
+ if foreground == 0:
+ errors.append(f"{label} must contain at least one foreground pixel")
+
+
+def validate_visual_hull_descriptor(component_id: str, descriptor: Any, errors: list[str]) -> None:
+ label = f"component {component_id!r} geometryDescriptor.visualHull"
+ if not isinstance(descriptor, dict):
+ errors.append(f"{label} must be an object")
+ return
+ for field in descriptor:
+ if field not in _DESCRIPTOR_FIELDS:
+ errors.append(f"{label}.{field} is not supported")
+ if descriptor.get("projection") != "orthographic":
+ errors.append(f"{label}.projection must be 'orthographic'")
+ if descriptor.get("boundsSpace") != "component-local":
+ errors.append(f"{label}.boundsSpace must be 'component-local'")
+ bounds = descriptor.get("bounds")
+ if not isinstance(bounds, dict):
+ errors.append(f"{label}.bounds must be an object")
+ else:
+ minimum = bounds.get("min")
+ maximum = bounds.get("max")
+ _validate_vector(minimum, f"{label}.bounds.min", errors)
+ _validate_vector(maximum, f"{label}.bounds.max", errors)
+ if isinstance(minimum, list) and isinstance(maximum, list) and len(minimum) == len(maximum) == 3:
+ for index, (minimum_value, maximum_value) in enumerate(zip(minimum, maximum)):
+ if _is_number(minimum_value) and _is_number(maximum_value) and minimum_value >= maximum_value:
+ errors.append(f"{label}.bounds.min[{index}] must be less than bounds.max[{index}]")
+ resolution = descriptor.get("resolution")
+ if not isinstance(resolution, int) or isinstance(resolution, bool) or resolution < MIN_VISUAL_HULL_MASK_DIMENSION:
+ errors.append(f"{label}.resolution must be an integer from {MIN_VISUAL_HULL_MASK_DIMENSION} to {MAX_VISUAL_HULL_RESOLUTION}")
+ elif resolution > MAX_VISUAL_HULL_RESOLUTION:
+ errors.append(f"{label}.resolution must not exceed {MAX_VISUAL_HULL_RESOLUTION}")
+ triangle_budget = descriptor.get("triangleBudget")
+ if not isinstance(triangle_budget, int) or isinstance(triangle_budget, bool) or triangle_budget < 1:
+ errors.append(f"{label}.triangleBudget must be a positive integer")
+ elif triangle_budget > MAX_VISUAL_HULL_TRIANGLES:
+ errors.append(f"{label}.triangleBudget must not exceed {MAX_VISUAL_HULL_TRIANGLES}")
+ elif isinstance(resolution, int) and not isinstance(resolution, bool) and resolution >= MIN_VISUAL_HULL_MASK_DIMENSION:
+ worst_case_triangles = resolution**3 * 12
+ if triangle_budget < worst_case_triangles:
+ errors.append(
+ f"{label}.triangleBudget requires at least {worst_case_triangles} triangles for resolution {resolution}"
+ )
+ views = descriptor.get("views")
+ if not isinstance(views, list) or len(views) < 2:
+ errors.append(f"{label}.views must contain at least two views")
+ elif len(views) > len(VALID_VISUAL_HULL_AXES):
+ errors.append(f"{label}.views must not contain more than {len(VALID_VISUAL_HULL_AXES)} views")
+ axes: set[str] = set()
+ if isinstance(views, list):
+ for index, view in enumerate(views):
+ view_label = f"{label}.views[{index}]"
+ if not isinstance(view, dict):
+ errors.append(f"{view_label} must be an object")
+ continue
+ for field in view:
+ if field not in _VIEW_FIELDS:
+ errors.append(f"{view_label}.{field} is not supported")
+ axis = view.get("axis")
+ if axis not in VALID_VISUAL_HULL_AXES:
+ errors.append(f"{view_label}.axis must be one of: {', '.join(sorted(VALID_VISUAL_HULL_AXES))}")
+ elif axis in axes:
+ errors.append(f"{label}.views must use distinct axes")
+ else:
+ axes.add(axis)
+ confidence = view.get("confidence")
+ if not _is_number(confidence) or not 0 <= float(confidence) <= 1:
+ errors.append(f"{view_label}.confidence must be a number from 0 to 1")
+ _validate_mask(view.get("mask"), f"{view_label}.mask", errors)
+ hidden_regions = descriptor.get("hiddenRegions")
+ if hidden_regions is not None and (
+ not isinstance(hidden_regions, list)
+ or not all(isinstance(region, str) and region.strip() for region in hidden_regions)
+ ):
+ errors.append(f"{label}.hiddenRegions must be an array of non-empty strings")
+
+
+# ---------------------------------------------------------------------------
+# Space carving
+# ---------------------------------------------------------------------------
+
+# Which world axis each view's image column and row follow, and whether that axis runs backwards.
+# Keeping this as data rather than branches means a new view axis is one table row, and means the
+# convention documented in the module docstring is the convention the code actually uses.
+_VIEW_AXES: dict[str, tuple[int, bool, int, bool]] = {
+ # axis: (column world axis, column reversed, row world axis, row reversed)
+ "front": (0, False, 1, True),
+ "side": (2, False, 1, True),
+ "top": (0, False, 2, False),
+}
+# The world axis each view leaves unconstrained -- the direction its camera looks along.
+_VIEW_FREE_AXIS = {"front": 2, "side": 0, "top": 1}
+_AXIS_NAMES = ("x", "y", "z")
+
+
+def _mask_lookup(mask: list[str]) -> tuple[int, int, list[str]]:
+ return len(mask[0]), len(mask), mask
+
+
+def _sample_mask(mask: list[str], column: float, row: float) -> bool:
+ """Nearest-texel test. Returns False outside the mask rather than raising.
+
+ Out-of-range means the voxel projects off the edge of that view's image, which is evidence the
+ voxel is NOT in the silhouette -- treating it as background is the conservative reading and keeps
+ the hull an upper bound rather than letting unseen space leak into the result.
+ """
+ width, height, rows = _mask_lookup(mask)
+ x = int(column * width)
+ y = int(row * height)
+ if x < 0 or y < 0 or x >= width or y >= height:
+ return False
+ return rows[y][x] == "1"
+
+
+def carve_visual_hull(descriptor: dict[str, Any]) -> dict[str, Any]:
+ """Intersect the supplied silhouette cones on a voxel grid and emit the boundary surface.
+
+ A voxel survives only if it lands on foreground in EVERY view. That is the definition of the
+ visual hull, and it is why one bad mask erases the model rather than degrading it -- the caller
+ should check `occupiedVoxelCount` before trusting a mesh, which is why it is reported.
+ """
+ errors: list[str] = []
+ validate_visual_hull_descriptor("carve", descriptor, errors)
+ if errors:
+ raise ValueError("; ".join(errors))
+
+ bounds = descriptor["bounds"]
+ low = [float(v) for v in bounds["min"]]
+ high = [float(v) for v in bounds["max"]]
+ resolution = int(descriptor["resolution"])
+ views = descriptor["views"]
+ step = [(high[axis] - low[axis]) / resolution for axis in range(3)]
+
+ def centre(index: int, axis: int) -> float:
+ return low[axis] + (index + 0.5) * step[axis]
+
+ occupied: set[tuple[int, int, int]] = set()
+ for ix in range(resolution):
+ cx = centre(ix, 0)
+ for iy in range(resolution):
+ cy = centre(iy, 1)
+ for iz in range(resolution):
+ cz = centre(iz, 2)
+ point = (cx, cy, cz)
+ inside = True
+ for view in views:
+ column_axis, column_flip, row_axis, row_flip = _VIEW_AXES[view["axis"]]
+ span_c = high[column_axis] - low[column_axis]
+ span_r = high[row_axis] - low[row_axis]
+ u = (point[column_axis] - low[column_axis]) / span_c
+ v = (point[row_axis] - low[row_axis]) / span_r
+ if column_flip:
+ u = 1.0 - u
+ if row_flip:
+ v = 1.0 - v
+ if not _sample_mask(view["mask"], u, v):
+ inside = False
+ break
+ if inside:
+ occupied.add((ix, iy, iz))
+
+ vertices, indices = _boundary_surface(occupied, low, step, resolution)
+
+ covered_axes = {_VIEW_FREE_AXIS[view["axis"]] for view in views}
+ unconstrained = [_AXIS_NAMES[axis] for axis in range(3) if axis not in covered_axes]
+ triangle_count = len(indices) // 3
+ budget = int(descriptor["triangleBudget"])
+
+ limitations = [
+ "a visual hull is the intersection of silhouette cones: it is an upper bound on the true "
+ "shape and can never contain a concavity that no supplied view sees as background",
+ ]
+ if len(views) < 3:
+ limitations.append(
+ f"only {len(views)} views supplied, so the hull extrudes along "
+ f"{', '.join(unconstrained) or 'no'} and is loose in that direction"
+ )
+
+ return {
+ "vertices": vertices,
+ "indices": indices,
+ "triangleCount": triangle_count,
+ # Reported for context only. There is deliberately no budget-overrun verdict here: the
+ # descriptor validator already requires triangleBudget >= resolution**3 * 12, the worst case
+ # for this grid, so a carve cannot exceed it and a boolean saying so could never be False.
+ # A check that cannot fail is worse than no check -- it reads as coverage that isn't there.
+ "triangleBudget": budget,
+ "resolution": resolution,
+ "occupiedVoxelCount": len(occupied),
+ "totalVoxelCount": resolution**3,
+ "occupiedFraction": round(len(occupied) / max(1, resolution**3), 6),
+ "viewAxes": [view["axis"] for view in views],
+ "unconstrainedAxes": unconstrained,
+ "limitations": limitations,
+ }
+
+
+def _boundary_surface(
+ occupied: set[tuple[int, int, int]],
+ low: list[float],
+ step: list[float],
+ resolution: int,
+) -> tuple[list[list[float]], list[int]]:
+ """Emit only the faces between an occupied voxel and empty space.
+
+ Emitting all six faces of every voxel would produce a mesh with interior walls, which is not a
+ surface: every shared face would be a duplicated, oppositely-wound pair and the result would fail
+ the watertightness gate for reasons that have nothing to do with the carve. Corners are welded
+ through a cache so the output is a closed 2-manifold.
+ """
+ vertex_ids: dict[tuple[int, int, int], int] = {}
+ vertices: list[list[float]] = []
+
+ def corner(gx: int, gy: int, gz: int) -> int:
+ key = (gx, gy, gz)
+ found = vertex_ids.get(key)
+ if found is not None:
+ return found
+ index = len(vertices)
+ vertex_ids[key] = index
+ vertices.append([low[0] + gx * step[0], low[1] + gy * step[1], low[2] + gz * step[2]])
+ return index
+
+ indices: list[int] = []
+ # (axis, direction) -> the four grid corners of that face, wound so the normal points outward.
+ faces = {
+ (0, 1): ((1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1)),
+ (0, -1): ((0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)),
+ (1, 1): ((0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)),
+ (1, -1): ((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1)),
+ (2, 1): ((0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)),
+ (2, -1): ((0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)),
+ }
+
+ for (ix, iy, iz) in sorted(occupied):
+ for (axis, direction), offsets in faces.items():
+ neighbour = [ix, iy, iz]
+ neighbour[axis] += direction
+ if tuple(neighbour) in occupied:
+ continue
+ quad = [corner(ix + dx, iy + dy, iz + dz) for dx, dy, dz in offsets]
+ indices.extend([quad[0], quad[1], quad[2], quad[0], quad[2], quad[3]])
+ return vertices, indices
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Carve a visual hull from a descriptor JSON.")
+ parser.add_argument("descriptor", type=Path, help="JSON file holding the visualHull descriptor")
+ parser.add_argument("--out", type=Path, help="write the carved mesh JSON here")
+ parser.add_argument("--json", action="store_true", help="print the full result as JSON")
+ args = parser.parse_args(argv)
+ try:
+ descriptor = json.loads(args.descriptor.read_text())
+ result = carve_visual_hull(descriptor)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(
+ f"carved {result['occupiedVoxelCount']}/{result['totalVoxelCount']} voxels "
+ f"({result['occupiedFraction']:.4f}) into {result['triangleCount']} triangles "
+ f"from views {result['viewAxes']}"
+ )
+ for line in result["limitations"]:
+ print(f" note: {line}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/_fit_divine_eye.py b/forge/stage4_review/_fit_divine_eye.py
new file mode 100644
index 0000000..93b2f3d
--- /dev/null
+++ b/forge/stage4_review/_fit_divine_eye.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from collections.abc import Callable, Mapping, Sequence
+
+
+def _approval_state(
+ result: Mapping[str, object],
+ input_error: Callable[[str, str], ValueError],
+ field: str,
+) -> tuple[list[str], str | None, str | None, bool]:
+ hard_gates = result.get("hardGateFailures", [])
+ if not isinstance(hard_gates, list) or not all(isinstance(tag, str) for tag in hard_gates):
+ raise input_error(f"{field}.hardGateFailures", "must be a list of strings")
+ action = result.get("action")
+ verdict = result.get("verdict")
+ if action is not None and not isinstance(action, str):
+ raise input_error(f"{field}.action", "must be a string")
+ if verdict is not None and not isinstance(verdict, str):
+ raise input_error(f"{field}.verdict", "must be a string")
+ approved = not hard_gates and action in (None, "continue") and verdict in (None, "pass")
+ return hard_gates, action, verdict, approved
+
+
+def is_approved_divine_eye_result(
+ result: Mapping[str, object],
+ input_error: Callable[[str, str], ValueError],
+ field: str,
+) -> bool:
+ return _approval_state(result, input_error, field)[3]
+
+
+def normalize_history(
+ results: Sequence[Mapping[str, object]],
+ fidelity: Callable[[Mapping[str, object]], float],
+ input_error: Callable[[str, str], ValueError],
+) -> list[dict[str, object]]:
+ if isinstance(results, str | bytes) or not isinstance(results, Sequence):
+ raise input_error("results", "must be a sequence of mappings")
+ history: list[dict[str, object]] = []
+ accepted_fidelity: float | None = None
+ for index, result in enumerate(results):
+ if not isinstance(result, Mapping):
+ raise input_error(f"results[{index}]", "must be a mapping")
+ score = fidelity(result)
+ hard_gates, action, verdict, approved = _approval_state(result, input_error, f"results[{index}]")
+ pending_review = not approved
+ reverted = accepted_fidelity is not None and score < accepted_fidelity
+ entry = {
+ "fidelity": score,
+ "defectTags": hard_gates.copy(),
+ "hardGateFailures": hard_gates.copy(),
+ "reverted": reverted,
+ "pendingReview": pending_review,
+ "divineEye": deepcopy(dict(result)),
+ }
+ if action is not None:
+ entry["divineEyeAction"] = action
+ if verdict is not None:
+ entry["divineEyeVerdict"] = verdict
+ history.append(entry)
+ if approved and (accepted_fidelity is None or score > accepted_fidelity):
+ accepted_fidelity = score
+ return history
diff --git a/forge/stage4_review/attachment_anchor.py b/forge/stage4_review/attachment_anchor.py
new file mode 100644
index 0000000..755cafa
--- /dev/null
+++ b/forge/stage4_review/attachment_anchor.py
@@ -0,0 +1,349 @@
+#!/usr/bin/env python3
+"""Attachment Anchor Gate: does every worn/held item actually relate to what it hangs from?
+
+Two production defects share one root cause. A conical hat that should sit behind the
+character's shoulders rendered at hip height, off to one side. A charm that should hang from
+the butt of a staff rendered detached, four units away and below the ground plane. Measured:
+the hat's bounding box spanned y 1.107-4.064 while the shoulder joint sat at y 3.829; the charm
+sat 0.389 from the staff surface with no connecting geometry at all. Both were authored as
+children of the model ROOT rather than of the thing they are attached to, so nothing tied
+their world position to their anchor, and nothing checked it afterward. No gate in this repo
+relates a worn or held item to what it is worn on or held by -- `ATTACHMENT_ROLES` in
+validate_sculpt_spec.py is a DIFFERENT contract (limbs/branches/handles that must EMBED into
+their parent's geometry, via `attachment.parentSocket`/`localStart`/`localEnd`); it has nothing
+to say about a rigid item that merely has to sit near a bone or component it is not welded to.
+
+Five checks. The first four run over the spec alone; the fifth only runs when the caller
+supplies measured world positions (e.g. from a runtime parts manifest), because that is the
+only way to catch a hat that is correctly *declared* but wrongly *placed*.
+
+ ANCHOR_DECLARED every worn/held/hung component must name an anchor.
+ ANCHOR_RESOLVES the named anchor must be a real component, or (with a rig) a real bone.
+ ANCHOR_NOT_ROOT the anchor must not be the model ROOT -- the literal bug both defects
+ shared: parenting to root means the item's transform carries no
+ relationship at all to the body part it belongs to.
+ ANCHOR_NOT_CYCLIC following anchors must not loop, and an item must not anchor to itself.
+ ANCHOR_PROXIMITY (measured positions only) the item's measured position must sit within
+ its anchor's declared or defaulted `maxOffset`.
+
+A component missing from the measured positions is never silently treated as passing --
+it is reported in `unmeasuredAttachments`, because "0 violations" from a check that never
+ran on anything is the exact failure mode that let both defects ship.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+# Vocabulary for "this component IS a worn/held/hung attachment" -- deliberately small and
+# disjoint from ATTACHMENT_ROLES in validate_sculpt_spec.py, which flags a component that
+# needs an EMBEDDING contract (a limb welding into its parent's geometry). This gate is about
+# an item's world-position relationship to what it hangs from, not about a geometry weld, so
+# the vocabularies must not collide: "arm"/"leg"/"branch" belong to the other gate, not here.
+ANCHOR_ATTACHMENT_TOKENS = {"attachment", "accessory", "worn", "held", "prop", "equipment"}
+
+# ANCHOR_PROXIMITY default #1: when the anchor is a component with a `dimensions` block, the
+# allowed drift is a fraction of the anchor's own largest declared extent -- a small anchor
+# (a staff) tolerates only a small absolute offset, a large one (a torso) tolerates more. This
+# is what makes the charm regression fire without an authored `maxOffset`: a 0.1-wide staff
+# caps drift at 0.025, far under the charm's real 0.389 detachment.
+ANCHOR_PROXIMITY_SIZE_FRACTION = 0.25
+_EXTENT_FIELDS = ("width", "height", "depth", "length")
+
+# ANCHOR_PROXIMITY default #2: when the anchor supplies no extents at all (a bone, or a
+# component with no `dimensions`), fall back to this constant. Chosen to be small relative to
+# the unit-scale specs this repo authors (compare PROPORTION_LIMIT_FRACTION in
+# validate_sculpt_spec.py, which reasons the same way over a different quantity).
+DEFAULT_MAX_OFFSET = 0.3
+
+
+def _is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _is_xyz(value: Any) -> bool:
+ return isinstance(value, (list, tuple)) and len(value) == 3 and all(_is_number(v) for v in value)
+
+
+def _distance(a: list[float], b: list[float]) -> float:
+ return sum((float(a[i]) - float(b[i])) ** 2 for i in range(3)) ** 0.5
+
+
+def _is_attachment_component(component: dict[str, Any]) -> bool:
+ """A component counts as a worn/held/hung attachment when it already declares
+ `attachment.anchor`, or when role/category/kind names it with the small vocabulary above.
+ The second path exists so ANCHOR_DECLARED has something to fire on: a component authored
+ as `role: "worn"` with no anchor at all must still be caught, not silently ignored because
+ it never reached the "has an anchor" branch."""
+ attachment = component.get("attachment")
+ if isinstance(attachment, dict) and isinstance(attachment.get("anchor"), str) and attachment["anchor"].strip():
+ return True
+ for field in ("role", "category", "kind"):
+ value = component.get(field)
+ if isinstance(value, str) and value.strip().lower() in ANCHOR_ATTACHMENT_TOKENS:
+ return True
+ return False
+
+
+def _anchor_id(component: dict[str, Any]) -> str | None:
+ attachment = component.get("attachment")
+ if isinstance(attachment, dict):
+ anchor = attachment.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ return anchor
+ return None
+
+
+def _find_cycle(start: str, anchor_of: dict[str, str]) -> list[str] | None:
+ """Walk the anchor-of-anchor chain from `start`. Returns the cyclic segment (in order,
+ NOT including the repeated closing node) the first time a node repeats, or None if the
+ chain runs off the edge of the attachment graph (into a bone, a plain component, or a
+ dangling id -- none of which are keys in `anchor_of`, so the `while` below simply stops)."""
+ path: list[str] = []
+ current = start
+ while current in anchor_of:
+ if current in path:
+ return path[path.index(current):]
+ path.append(current)
+ current = anchor_of[current]
+ return None
+
+
+def _anchor_extent(anchor_component: dict[str, Any] | None) -> float | None:
+ """Largest declared extent on the anchor's `dimensions` block, or None if it has none.
+ `radius` is doubled to a diameter so it is comparable to width/height/depth/length."""
+ if not isinstance(anchor_component, dict):
+ return None
+ dimensions = anchor_component.get("dimensions")
+ if not isinstance(dimensions, dict):
+ return None
+ values = [float(dimensions[f]) for f in _EXTENT_FIELDS if _is_number(dimensions.get(f))]
+ if _is_number(dimensions.get("radius")):
+ values.append(float(dimensions["radius"]) * 2.0)
+ return max(values) if values else None
+
+
+def _max_offset_for(component: dict[str, Any], anchor_component: dict[str, Any] | None) -> tuple[float, str]:
+ """Return (limit, rule) so a proximity failure can say WHICH rule produced the number
+ instead of a bare threshold. Priority: declared `maxOffset` > anchor-size default >
+ constant fallback."""
+ attachment = component.get("attachment") if isinstance(component.get("attachment"), dict) else {}
+ declared = attachment.get("maxOffset")
+ if _is_number(declared):
+ return float(declared), "declared attachment.maxOffset"
+ extent = _anchor_extent(anchor_component)
+ if extent is not None:
+ limit = extent * ANCHOR_PROXIMITY_SIZE_FRACTION
+ return limit, (
+ f"default: {ANCHOR_PROXIMITY_SIZE_FRACTION:.0%} of anchor's largest declared extent "
+ f"({extent:.4f})"
+ )
+ return DEFAULT_MAX_OFFSET, f"default: constant fallback ({DEFAULT_MAX_OFFSET}); anchor declares no extents"
+
+
+def analyze_attachments(spec: dict[str, Any], *, measured: dict[str, list[float]] | None = None) -> dict[str, Any]:
+ """Run the attachment-anchor gate over `spec`'s component tree, optionally cross-checked
+ against `measured` (world positions keyed by component or bone id, e.g. from a runtime
+ parts manifest). See module docstring for the five checks.
+
+ Returns a dict with `errors`, `warnings`, per-attachment `attachments` records (component,
+ anchor, anchorKind, distance, maxOffset, offsetRule, withinLimit -- the last four are None
+ until a measured position resolves them), `unmeasuredAttachments`, `attachmentCount`, and
+ `passed` (True iff `errors` is empty).
+ """
+ errors: list[str] = []
+ warnings: list[str] = []
+
+ components = [
+ c for c in (spec.get("componentTree") or []) if isinstance(c, dict) and isinstance(c.get("id"), str)
+ ]
+ by_id = {c["id"]: c for c in components}
+ rig = spec.get("rig")
+ bones = (
+ [b for b in (rig.get("bones") or []) if isinstance(b, dict) and isinstance(b.get("id"), str)]
+ if isinstance(rig, dict) else []
+ )
+ bones_by_id = {b["id"]: b for b in bones}
+
+ # Root identity, both trees. A malformed multi-root component tree is
+ # validate_sculpt_spec.py's problem (NAME_UNIQUENESS), not this gate's -- we only need
+ # SOME root id to test ANCHOR_NOT_ROOT against, so ambiguity does not stop the gate.
+ tree_roots = [c["id"] for c in components if not c.get("parent")]
+ tree_root_id = tree_roots[0] if tree_roots else None
+ rig_roots = [b["id"] for b in bones if not b.get("parent")]
+ rig_root_id = rig_roots[0] if rig_roots else None
+
+ attachment_components = [c for c in components if _is_attachment_component(c)]
+ anchor_of: dict[str, str] = {}
+ records: list[dict[str, Any]] = []
+
+ for component in attachment_components:
+ cid = component["id"]
+ anchor = _anchor_id(component)
+ record: dict[str, Any] = {
+ "component": cid,
+ "anchor": anchor,
+ "anchorKind": None,
+ "distance": None,
+ "maxOffset": None,
+ "offsetRule": None,
+ "withinLimit": None,
+ }
+ if anchor is None:
+ errors.append(
+ f"ANCHOR_DECLARED: attachment {cid!r} is worn/held/hung but declares no attachment.anchor"
+ )
+ records.append(record)
+ continue
+
+ anchor_of[cid] = anchor
+ if anchor in by_id:
+ record["anchorKind"] = "component"
+ elif anchor in bones_by_id:
+ record["anchorKind"] = "bone"
+ else:
+ errors.append(
+ f"ANCHOR_RESOLVES: attachment {cid!r} anchors to {anchor!r}, which matches no "
+ f"existing component" + (" or bone" if isinstance(rig, dict) else "") + " in this spec"
+ )
+ records.append(record)
+ continue
+
+ is_root = (
+ (record["anchorKind"] == "component" and anchor == tree_root_id)
+ or (record["anchorKind"] == "bone" and anchor == rig_root_id)
+ )
+ if is_root:
+ errors.append(
+ f"ANCHOR_NOT_ROOT: attachment {cid!r} anchors directly to the model ROOT ({anchor!r}) "
+ f"-- parenting a worn/held item to root leaves its transform unrelated to the body "
+ f"part it belongs to; this is the exact defect behind both the misplaced hat and "
+ f"the detached charm"
+ )
+ records.append(record)
+
+ # ---- ANCHOR_NOT_CYCLIC -- self-anchor is the length-1 case of this same walk. ----
+ reported_cycles: set[frozenset[str]] = set()
+ for start in anchor_of:
+ cycle = _find_cycle(start, anchor_of)
+ if not cycle:
+ continue
+ key = frozenset(cycle)
+ if key in reported_cycles:
+ continue
+ reported_cycles.add(key)
+ if len(cycle) == 1:
+ errors.append(f"ANCHOR_NOT_CYCLIC: attachment {cycle[0]!r} anchors to itself")
+ else:
+ chain = " -> ".join([*cycle, cycle[0]])
+ errors.append(f"ANCHOR_NOT_CYCLIC: attachment anchor cycle detected: {chain}")
+
+ # ---- ANCHOR_PROXIMITY -- only when the caller supplies measured world positions. ----
+ unmeasured: list[str] = []
+ if measured is not None:
+ for record in records:
+ if record["anchorKind"] is None:
+ continue # ANCHOR_DECLARED/ANCHOR_RESOLVES already failed; no anchor to measure against
+ cid = record["component"]
+ anchor = record["anchor"]
+ item_pos = measured.get(cid)
+ anchor_pos = measured.get(anchor)
+ if not _is_xyz(item_pos) or not _is_xyz(anchor_pos):
+ # Never silently skip: a component the caller forgot to measure is reported,
+ # not swept into "0 violations" the way both real defects went unnoticed.
+ unmeasured.append(cid)
+ warnings.append(
+ f"ANCHOR_PROXIMITY: attachment {cid!r} has no measured world position (or its "
+ f"anchor {anchor!r} has none); proximity was not verified"
+ )
+ continue
+ anchor_component = by_id.get(anchor) if record["anchorKind"] == "component" else None
+ max_offset, rule = _max_offset_for(by_id[cid], anchor_component)
+ distance = _distance(item_pos, anchor_pos)
+ record["distance"] = distance
+ record["maxOffset"] = max_offset
+ record["offsetRule"] = rule
+ record["withinLimit"] = distance <= max_offset
+ if distance > max_offset:
+ errors.append(
+ f"ANCHOR_PROXIMITY: attachment {cid!r} measures {distance:.4f} from anchor "
+ f"{anchor!r}, exceeding maxOffset {max_offset:.4f} ({rule})"
+ )
+
+ return {
+ "errors": errors,
+ "warnings": warnings,
+ "attachments": records,
+ "unmeasuredAttachments": unmeasured,
+ "attachmentCount": len(attachment_components),
+ "passed": not errors,
+ }
+
+
+def _load_json(path: Path) -> dict[str, Any]:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _parse_measured(raw: str) -> dict[str, list[float]]:
+ """`--measured` accepts either inline JSON text or a path to a JSON file: a handful of
+ positions is convenient to type inline, but a real runtime parts manifest is a file."""
+ candidate = Path(raw)
+ text = candidate.read_text(encoding="utf-8") if candidate.is_file() else raw
+ data = json.loads(text)
+ if not isinstance(data, dict):
+ raise ValueError("--measured must decode to a JSON object of id -> [x, y, z]")
+ return data
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [f"attachments: {result['attachmentCount']}"]
+ for record in result["attachments"]:
+ bits = [f"component={record['component']!r}", f"anchor={record['anchor']!r}"]
+ if record["distance"] is not None:
+ bits.append(f"distance={record['distance']:.4f}")
+ bits.append(f"maxOffset={record['maxOffset']:.4f}")
+ bits.append(f"rule={record['offsetRule']}")
+ bits.append("within-limit" if record["withinLimit"] else "OVER-LIMIT")
+ lines.append(" " + " ".join(bits))
+ if result["unmeasuredAttachments"]:
+ lines.append(f"unmeasured: {', '.join(result['unmeasuredAttachments'])}")
+ for message in result["errors"]:
+ lines.append(f"ERROR: {message}")
+ for message in result["warnings"]:
+ lines.append(f"WARNING: {message}")
+ lines.append("verdict: " + ("PASS" if result["passed"] else "FAIL"))
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("spec", type=Path, help="sculpt-spec JSON path")
+ parser.add_argument(
+ "--measured",
+ help="JSON object (inline text or a file path) of id -> [x, y, z] world positions",
+ )
+ parser.add_argument("--json", action="store_true", help="print JSON instead of a summary")
+ args = parser.parse_args(argv)
+
+ try:
+ spec = _load_json(args.spec)
+ measured = _parse_measured(args.measured) if args.measured is not None else None
+ result = analyze_attachments(spec, measured=measured)
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(_format_summary(result))
+ return 0 if result["passed"] else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/compare_region_passes.py b/forge/stage4_review/compare_region_passes.py
new file mode 100644
index 0000000..9f44d6b
--- /dev/null
+++ b/forge/stage4_review/compare_region_passes.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""Compare browser-captured GLB/procedural diagnostic passes.
+
+This is a deterministic companion to the agent/vision review. It never converts a
+global pixel score into a likeness claim. Per-region scores are keyed by the GLB
+semantic-ID pass when that pass exists; otherwise the output explicitly says that
+region scoring is unavailable.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))
+from extract_pbr_evidence import load_image # type: ignore[import-not-found]
+
+PASS_IDS = ("beauty", "alpha-silhouette", "semantic-id", "depth", "normal", "roughness-material-id")
+
+
+def _resolve(manifest_path: Path, value: str) -> Path:
+ path = Path(value).expanduser()
+ return path if path.is_absolute() else manifest_path.parent / path
+
+
+def _load(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
+ width, height, pixels, warnings = load_image(path)
+ if warnings:
+ # Warnings are not fatal; the result records paths and metrics only.
+ pass
+ return width, height, pixels
+
+
+def _aligned_pixels(
+ reference: tuple[int, int, list[tuple[int, int, int, int]]],
+ render: tuple[int, int, list[tuple[int, int, int, int]]],
+) -> list[tuple[tuple[int, int, int, int], tuple[int, int, int, int]]]:
+ rw, rh, rp = reference
+ ww, wh, wp = render
+ if (rw, rh) != (ww, wh):
+ raise ValueError(f"pass dimensions differ: reference={rw}x{rh}, render={ww}x{wh}")
+ return list(zip(rp, wp))
+
+
+def _mask_from_id(pixels: list[tuple[int, int, int, int]], color: tuple[int, int, int]) -> list[bool]:
+ return [(r, g, b) == color for r, g, b, _a in pixels]
+
+
+def _similarity(
+ pairs: list[tuple[tuple[int, int, int, int], tuple[int, int, int, int]]],
+ mask: list[bool] | None = None,
+) -> dict[str, Any]:
+ selected = [pair for index, pair in enumerate(pairs) if mask is None or mask[index]]
+ if not selected:
+ return {"pixels": 0, "similarity": None, "meanAbsoluteError": None}
+ error = sum(
+ abs(reference[channel] - render[channel])
+ for reference, render in selected
+ for channel in range(3)
+ ) / (len(selected) * 3 * 255.0)
+ return {
+ "pixels": len(selected),
+ "similarity": round(max(0.0, 1.0 - error), 6),
+ "meanAbsoluteError": round(error * 255.0, 4),
+ }
+
+
+def _iou(reference_mask: list[bool], render_mask: list[bool], mask: list[bool] | None = None) -> dict[str, Any]:
+ indices = range(len(reference_mask)) if mask is None else (i for i, value in enumerate(mask) if value)
+ intersection = union = 0
+ for index in indices:
+ reference = reference_mask[index]
+ render = render_mask[index]
+ if reference or render:
+ union += 1
+ if reference and render:
+ intersection += 1
+ return {"intersection": intersection, "union": union, "iou": round(intersection / union, 6) if union else 1.0}
+
+
+def compare_capture(manifest_path: Path, capture_id: str) -> dict[str, Any]:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ capture = next(item for item in manifest.get("captures", []) if item.get("id") == capture_id)
+ reference = capture.get("reference")
+ if not isinstance(reference, dict):
+ raise ValueError("capture has no GLB reference record")
+ reference_passes = reference.get("passes")
+ render_passes = capture.get("passes")
+ if not isinstance(reference_passes, dict) or not isinstance(render_passes, dict):
+ raise ValueError("capture is missing v2 pass records")
+
+ profile_path = manifest.get("renderProfile", {}).get("path")
+ profile: dict[str, Any] = {}
+ if profile_path:
+ profile = json.loads(_resolve(manifest_path, profile_path).read_text(encoding="utf-8"))
+ region_colors: dict[str, tuple[int, int, int]] = {}
+ for region in profile.get("regions", []):
+ if not isinstance(region, dict) or not isinstance(region.get("idColor"), list) or len(region["idColor"]) != 3:
+ continue
+ region_colors[str(region["id"])] = tuple(int(value) for value in region["idColor"])
+
+ loaded: dict[str, tuple[tuple[int, int, list[tuple[int, int, int, int]]], tuple[int, int, list[tuple[int, int, int, int]]]]] = {}
+ for pass_id in PASS_IDS:
+ ref_record = reference_passes.get(pass_id, {})
+ render_record = render_passes.get(pass_id, {})
+ if ref_record.get("status") != "recorded" or render_record.get("status") != "recorded":
+ continue
+ loaded[pass_id] = (
+ _load(_resolve(manifest_path, str(ref_record["path"]))),
+ _load(_resolve(manifest_path, str(render_record["path"]))),
+ )
+
+ semantic_masks: dict[str, list[bool]] = {}
+ if "semantic-id" in loaded:
+ reference_semantic = loaded["semantic-id"][0][2]
+ semantic_masks = {region: _mask_from_id(reference_semantic, color) for region, color in region_colors.items()}
+
+ results: dict[str, Any] = {}
+ for pass_id, (reference_image, render_image) in loaded.items():
+ pairs = _aligned_pixels(reference_image, render_image)
+ if pass_id == "alpha-silhouette":
+ reference_mask = [alpha > 0 and (red or green or blue) > 0 for red, green, blue, alpha in reference_image[2]]
+ render_mask = [alpha > 0 and (red or green or blue) > 0 for red, green, blue, alpha in render_image[2]]
+ global_result: dict[str, Any] = _iou(reference_mask, render_mask)
+ per_region = {region: _iou(reference_mask, render_mask, mask) for region, mask in semantic_masks.items()}
+ elif pass_id == "semantic-id":
+ global_result = {"pixels": len(pairs), "exactMatch": round(sum(ref[:3] == out[:3] for ref, out in pairs) / len(pairs), 6) if pairs else None}
+ per_region = {
+ region: {"pixels": sum(mask), "exactMatch": round(sum(ref[:3] == out[:3] for index, (ref, out) in enumerate(pairs) if mask[index]) / sum(mask), 6) if sum(mask) else None}
+ for region, mask in semantic_masks.items()
+ }
+ else:
+ global_result = _similarity(pairs)
+ per_region = {region: _similarity(pairs, mask) for region, mask in semantic_masks.items()}
+ results[pass_id] = {"global": global_result, "perRegion": per_region}
+
+ return {
+ "schemaVersion": 1,
+ "captureId": capture_id,
+ "comparisonBasis": "browser-rendered-glb-vs-browser-rendered-procedural",
+ "passesCompared": sorted(results),
+ "regionEvidence": "semantic-id-reference-pass" if semantic_masks else "unavailable",
+ "results": results,
+ "blockedClaims": [] if semantic_masks else ["per-region scores are unavailable until semantic-id pass has region colors"],
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, required=True)
+ parser.add_argument("--capture-id", default="hero")
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args(argv)
+ try:
+ result = compare_capture(args.manifest.expanduser().resolve(), args.capture_id)
+ args.out.expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
+ args.out.expanduser().resolve().write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if not result["blockedClaims"] else 1
+ except Exception as exc: # noqa: BLE001
+ print(json.dumps({"passed": False, "error": str(exc)}, ensure_ascii=False))
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(__import__("sys").argv[1:]))
diff --git a/forge/stage4_review/correction_loop.py b/forge/stage4_review/correction_loop.py
index 4428496..22df69a 100644
--- a/forge/stage4_review/correction_loop.py
+++ b/forge/stage4_review/correction_loop.py
@@ -15,7 +15,7 @@ A caller that loops::
history.append(one_more_iteration())
can NEVER run more than ``max_iter`` iterations. The HARD_CEILING condition
-(priority 6) fires purely on ``len(history) >= max_iter`` and cannot be bypassed
+(priority 8) fires purely on ``len(history) >= max_iter`` and cannot be bypassed
by any other state — not even a monotonically-improving-but-never-reaching-target
loop. This is the single most important property of this module; do not weaken it.
"""
@@ -24,6 +24,7 @@ from __future__ import annotations
import argparse
import json
+import math
import sys
@@ -32,7 +33,9 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
Args:
history: list of per-iteration dicts in chronological order, each
- ``{"fidelity": float in [0,1], "defectTags": list[str], "reverted": bool}``.
+ ``{"fidelity": float in [0,1], "defectTags": list[str], "reverted": bool}``,
+ with optional Divine Eye ``hardGateFailures: list[str]`` and
+ ``pendingReview: bool`` routing metadata.
``reverted`` means that iteration's correction lowered the score and
was auto-reverted.
target_fidelity: fidelity at/above which the model is considered good enough.
@@ -45,6 +48,9 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
Stop conditions are evaluated in strict priority order; the first match wins.
"""
+ _validate_config(target_fidelity, max_iter, min_delta)
+ _validate_history(history)
+
# 1. EMPTY — nothing has happened yet.
if not history:
return {
@@ -56,15 +62,34 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
last = history[-1]
prev = history[-2] if len(history) >= 2 else None
- # 2. SUCCESS — target met and no open defects.
- if last["fidelity"] >= target_fidelity and not last["defectTags"]:
+ hard_gates, action, verdict, pending_review, fidelity = _routing_state(last)
+
+ # 2. HARD GATE — a Divine Eye hard failure needs code correction.
+ if hard_gates:
+ return {
+ "stop": True,
+ "action": "refine-code",
+ "reason": f"hard gate failure: {hard_gates[0]}",
+ }
+
+ # 3. PENDING REVIEW — preserve the Divine Eye evaluator's non-continue routing.
+ if pending_review:
+ route = action if action in ("refine-code", "refine-spec") else "request-input"
+ return {
+ "stop": True,
+ "action": route,
+ "reason": f"pending Divine Eye review: {action or verdict}",
+ }
+
+ # 4. SUCCESS — target met and no open defects.
+ if fidelity >= target_fidelity and not last["defectTags"]:
return {
"stop": True,
"action": "continue",
"reason": "fidelity target met, no open defects",
}
- # 3. REPEATED_DEFECT — a defect tag survived two consecutive iterations.
+ # 5. REPEATED_DEFECT — a defect tag survived two consecutive iterations.
if prev is not None:
shared = set(last["defectTags"]) & set(prev["defectTags"])
if shared:
@@ -75,16 +100,13 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
"reason": f"same defect survived 2 consecutive fixes: {tag}",
}
- # 4. OSCILLATION — repeated reverts, or a direction flip over the last 3 scores.
- reverts = sum(1 for h in history if h.get("reverted"))
+ # 6. OSCILLATION — two trailing reverted iterations.
+ reverts = 0
+ for entry in reversed(history):
+ if not entry.get("reverted"):
+ break
+ reverts += 1
oscillating = reverts >= 2
- if not oscillating and len(history) >= 3:
- f0, f1, f2 = (h["fidelity"] for h in history[-3:])
- d1 = f1 - f0
- d2 = f2 - f1
- # strictly down-then-up or up-then-down (both deltas non-zero, opposite signs)
- if (d1 < 0 and d2 > 0) or (d1 > 0 and d2 < 0):
- oscillating = True
if oscillating:
return {
"stop": True,
@@ -92,11 +114,11 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
"reason": "oscillating/thrashing",
}
- # 5. PLATEAU — progress stalled below target.
+ # 7. PLATEAU — progress stalled below target.
if (
prev is not None
- and (last["fidelity"] - prev["fidelity"]) < min_delta
- and last["fidelity"] < target_fidelity
+ and (fidelity - _routing_state(prev)[4]) < min_delta
+ and fidelity < target_fidelity
):
return {
"stop": True,
@@ -104,7 +126,7 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
"reason": "progress plateaued below target (Δ<min_delta)",
}
- # 6. HARD_CEILING — non-bypassable termination guarantee.
+ # 8. HARD_CEILING — non-bypassable termination guarantee.
if len(history) >= max_iter:
return {
"stop": True,
@@ -112,7 +134,7 @@ def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
"reason": "hit MAX_ITER ceiling",
}
- # 7. Otherwise — keep going.
+ # 9. Otherwise — keep going.
return {
"stop": False,
"action": "continue-iterating",
@@ -126,9 +148,77 @@ def budget_exceeded(spent_tokens, budget):
Returns True when the token budget is spent. The caller uses this to
HALT-and-ask-the-user; it never silently continues.
"""
+ if not _is_finite_number(spent_tokens) or spent_tokens < 0:
+ raise ValueError("spent_tokens must be a finite non-negative number")
+ if isinstance(budget, bool) or not isinstance(budget, int) or budget < 0:
+ raise ValueError("budget must be a non-negative integer")
return spent_tokens >= budget
+def _validate_history(history):
+ if not isinstance(history, list):
+ raise ValueError("history must be a JSON list")
+ for index, entry in enumerate(history):
+ if not isinstance(entry, dict):
+ raise ValueError(f"history[{index}] must be an object")
+ fidelity = entry.get("fidelity")
+ if isinstance(fidelity, bool) or not isinstance(fidelity, int | float) or not math.isfinite(fidelity) or not 0.0 <= fidelity <= 1.0:
+ raise ValueError(f"history[{index}].fidelity must be a finite number in [0, 1]")
+ _validate_tags(entry.get("defectTags"), f"history[{index}].defectTags")
+ _routing_state(entry, index)
+ if not isinstance(entry.get("reverted"), bool):
+ raise ValueError(f"history[{index}].reverted must be a boolean")
+ return history
+
+
+def _validate_tags(tags, field):
+ if not isinstance(tags, list) or not all(isinstance(tag, str) for tag in tags):
+ raise ValueError(f"{field} must be a list of strings")
+
+
+def _routing_state(entry, index=None):
+ prefix = f"history[{index}]" if index is not None else "history entry"
+ if "pendingReview" in entry and not isinstance(entry["pendingReview"], bool):
+ raise ValueError(f"{prefix}.pendingReview must be a boolean")
+ provenance = entry.get("divineEye")
+ if provenance is not None and not isinstance(provenance, dict):
+ raise ValueError(f"{prefix}.divineEye must be an object")
+ source = provenance if provenance is not None else entry
+ fidelity = source.get("fidelity") if provenance is not None else entry.get("fidelity")
+ if isinstance(fidelity, bool) or not isinstance(fidelity, int | float) or not math.isfinite(fidelity) or not 0.0 <= fidelity <= 1.0:
+ raise ValueError(f"{prefix}.divineEye.fidelity must be a finite number in [0, 1]")
+ if provenance is not None and entry["fidelity"] != fidelity:
+ raise ValueError(f"{prefix}.fidelity conflicts with divineEye provenance")
+ hard_gates = source.get("hardGateFailures", [])
+ _validate_tags(hard_gates, f"{prefix}.hardGateFailures")
+ action = source.get("action") if provenance is not None else entry.get("divineEyeAction")
+ verdict = source.get("verdict") if provenance is not None else entry.get("divineEyeVerdict")
+ if action is not None and not isinstance(action, str):
+ raise ValueError(f"{prefix}.divineEyeAction must be a string")
+ if verdict is not None and not isinstance(verdict, str):
+ raise ValueError(f"{prefix}.divineEyeVerdict must be a string")
+ pending_review = bool(entry.get("pendingReview", False)) or action not in (None, "continue") or verdict not in (None, "pass") or bool(hard_gates)
+ if provenance is not None:
+ expected = {"hardGateFailures": hard_gates, "divineEyeAction": action, "divineEyeVerdict": verdict, "pendingReview": pending_review}
+ for key, value in expected.items():
+ if key in entry and entry[key] != value:
+ raise ValueError(f"{prefix}.{key} conflicts with divineEye provenance")
+ return hard_gates, action, verdict, pending_review, fidelity
+
+
+def _validate_config(target_fidelity, max_iter, min_delta):
+ if not _is_finite_number(target_fidelity) or not 0.0 <= target_fidelity <= 1.0:
+ raise ValueError("target_fidelity must be a finite number in [0, 1]")
+ if isinstance(max_iter, bool) or not isinstance(max_iter, int) or max_iter <= 0:
+ raise ValueError("max_iter must be a positive integer")
+ if not _is_finite_number(min_delta) or min_delta < 0.0:
+ raise ValueError("min_delta must be finite and non-negative")
+
+
+def _is_finite_number(value):
+ return not isinstance(value, bool) and isinstance(value, int | float) and math.isfinite(value)
+
+
def main(argv):
parser = argparse.ArgumentParser(
description="Bounded correction-loop stop policy (§3.6)."
@@ -143,8 +233,6 @@ def main(argv):
args = parser.parse_args(argv)
with open(args.history, "r", encoding="utf-8") as fh:
history = json.load(fh)
- if not isinstance(history, list):
- raise ValueError("history JSON must be a list")
decision = decide(
history,
diff --git a/forge/stage4_review/diagnose_render.py b/forge/stage4_review/diagnose_render.py
index 7c6a1d3..9e7e5c9 100644
--- a/forge/stage4_review/diagnose_render.py
+++ b/forge/stage4_review/diagnose_render.py
@@ -63,17 +63,22 @@ COLOR_DELTA_E_THRESHOLD = 20.0 # generous vs. the JND (~2-3) to tolerate render
MASK_GRID_SIZE = 224
-def load_mask(png_path: Path, size: int = MASK_GRID_SIZE) -> list[bool]:
- """Returns a flat row-major boolean grid of length size*size (foreground=True)."""
+def mask_is_inverted(warnings: list[str]) -> bool:
+ """Return whether foreground extraction fell back to whole-frame coverage."""
+ return any("tiny" in str(warning).lower() for warning in warnings)
+
+
+def load_mask(png_path: Path, size: int = MASK_GRID_SIZE) -> tuple[list[bool], list[str]]:
+ """Return the resized foreground mask and extraction warnings."""
width, height, pixels, _warnings = load_image(png_path)
- mask, _diag, _warn = build_foreground_mask(width, height, pixels)
+ mask, _diag, mask_warnings = build_foreground_mask(width, height, pixels)
resized: list[bool] = []
for y in range(size):
sy = min(height - 1, int(y * height / size))
for x in range(size):
sx = min(width - 1, int(x * width / size))
resized.append(mask[sy * width + sx])
- return resized
+ return resized, mask_warnings
def silhouette_iou(reference_mask: list[bool], render_mask: list[bool]) -> float:
@@ -84,7 +89,7 @@ def silhouette_iou(reference_mask: list[bool], render_mask: list[bool]) -> float
union += 1
if ref and render:
intersection += 1
- return intersection / union if union else 1.0
+ return intersection / union if union else 0.0
def bbox_of(mask: list[bool], size: int = MASK_GRID_SIZE) -> tuple[int, int, int, int]:
@@ -178,8 +183,12 @@ def run_tier1(
spec_path: Path | None = None,
pass_id: str | None = None,
) -> dict[str, Any]:
- reference_mask = load_mask(reference_path)
- render_mask = load_mask(render_path)
+ reference_mask, reference_mask_warnings = load_mask(reference_path)
+ render_mask, render_mask_warnings = load_mask(render_path)
+ mask_warnings = (
+ [f"reference: {w}" for w in reference_mask_warnings]
+ + [f"render: {w}" for w in render_mask_warnings]
+ )
iou = silhouette_iou(reference_mask, render_mask)
reference_bbox = bbox_of(reference_mask)
@@ -194,6 +203,12 @@ def run_tier1(
"bilateralSymmetryError": round(symmetry, 4),
}
failures: list[str] = []
+ if mask_is_inverted(reference_mask_warnings) or mask_is_inverted(render_mask_warnings):
+ failures.append(
+ "silhouette evidence is unusable: the foreground mask fell back to whole-frame "
+ "coverage (subject under 3.5% of the frame), so IoU and proportion are not "
+ "measuring the subject; re-capture with the subject filling more of the frame"
+ )
if iou < SILHOUETTE_IOU_THRESHOLD:
failures.append(f"silhouette IoU {iou:.3f} is below threshold {SILHOUETTE_IOU_THRESHOLD}")
if proportions["aspect_ratio_delta"] > ASPECT_RATIO_DELTA_THRESHOLD:
@@ -230,6 +245,7 @@ def run_tier1(
"passed": not failures,
"checks": checks,
"failures": failures,
+ "maskWarnings": mask_warnings,
"renderHash": render_hash(render_path),
"passId": pass_id,
}
diff --git a/forge/stage4_review/divine_eye.py b/forge/stage4_review/divine_eye.py
index 4abca71..16c5459 100644
--- a/forge/stage4_review/divine_eye.py
+++ b/forge/stage4_review/divine_eye.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""The Divine Eye (đôi mắt thần) — deterministic multi-signal render↔reference evaluator.
+"""The Divine Eye — deterministic multi-signal render↔reference evaluator.
Plan 1.3 Phase 3 core (§3.1 ensemble, §3.3 combination + self-uncertainty). This is
the single authority the correction loop asks "how close is this render to the
@@ -41,6 +41,7 @@ from diagnose_render import ( # noqa: E402
bbox_of,
bilateral_symmetry_error,
load_mask,
+ mask_is_inverted,
proportion_delta,
silhouette_iou,
)
@@ -64,6 +65,12 @@ ASPECT_SOFT_MAX = 0.05 # aspect-ratio delta allowed for a reconstruction-mo
RECON_OBJ_MIN = 0.48 # objectness ≥ this rescues an IoU-only hard reject → probe (recon mode).
# Separates same-object-different-framing (real pairs ~0.53–0.58) from a
# genuinely different shape (~0.43). Rescue only ever downgrades reject→probe.
+# RESOLUTION CEILING, and it is a hard limit on what this module can ever report.
+# Every signal below -- SSIM, tonal, blowout, flat, edge overlap -- is computed on these grids, so a
+# feature a few pixels wide in a 1920px reference is not scored badly, it is ABSENT before any
+# comparison happens. No threshold tuning recovers it. per_feature.py cannot compensate either: it
+# consumes a scores dict and never opens an image, so its critical-feature gate is sound and starved.
+# Feature-scale fidelity needs zoom patches instead: grimoire/review/divine_eye_microscope.md.
LUMA_SIZE = 64 # SSIM / tonal / blowout / flat work on this downsampled luma grid
EDGE_SIZE = 96 # edge overlap grid
HUE_ZONE_DELTA_E = 2.3 # per-band CIEDE2000 "same hue zone" tolerance (Context Part 2.2)
@@ -234,7 +241,7 @@ def edge_overlap(a: list[float], b: list[float], size: int) -> float:
union += 1
if ea[i] and eb[i]:
inter += 1
- return inter / union if union else 1.0
+ return inter / union if union else 0.0
def _blown_fraction(luma: list[float], hi: float = 0.95) -> float:
@@ -274,8 +281,8 @@ def tonal_parity(ref: list[float], ren: list[float], bins: int = 16) -> float:
def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:
"""Run all deterministic signals and combine into a verdict + routing action."""
- ref_mask = load_mask(reference_png)
- ren_mask = load_mask(render_png)
+ ref_mask, ref_mask_warnings = load_mask(reference_png)
+ ren_mask, ren_mask_warnings = load_mask(render_png)
ref_luma = load_luma(reference_png, LUMA_SIZE)
ren_luma = load_luma(render_png, LUMA_SIZE)
ref_edge = load_luma(reference_png, EDGE_SIZE)
@@ -327,6 +334,11 @@ def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:
# HARD gates: a fail is an immediate reject with a specific numeric reason.
hard_failures: list[str] = []
+ if mask_is_inverted(ref_mask_warnings) or mask_is_inverted(ren_mask_warnings):
+ hard_failures.append(
+ "foreground mask fell back to whole-frame coverage; silhouette, scale and aspect "
+ "signals are not measuring the subject"
+ )
if iou < IOU_HARD_MIN:
hard_failures.append(f"silhouette IoU {iou:.3f} < {IOU_HARD_MIN}")
if scale_delta > SCALE_HARD_MAX:
@@ -392,6 +404,10 @@ def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:
"fidelity": round(fidelity, 4),
"fidelityTarget": FIDELITY_TARGET,
"hardGateFailures": hard_failures,
+ "maskWarnings": (
+ [f"reference: {w}" for w in ref_mask_warnings]
+ + [f"render: {w}" for w in ren_mask_warnings]
+ ),
"disagreementSpread": round(spread, 4),
"signals": {
"silhouetteIoU": round(iou, 4),
diff --git a/forge/stage4_review/fit_params.py b/forge/stage4_review/fit_params.py
new file mode 100644
index 0000000..9f06ad9
--- /dev/null
+++ b/forge/stage4_review/fit_params.py
@@ -0,0 +1,381 @@
+#!/usr/bin/env python3
+"""Deterministic bounded analysis-by-synthesis fitting."""
+
+from __future__ import annotations
+
+import argparse
+from copy import deepcopy
+import json
+import math
+import sys
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final, Literal
+
+if __package__:
+ from ._fit_divine_eye import is_approved_divine_eye_result, normalize_history
+else:
+ from _fit_divine_eye import is_approved_divine_eye_result, normalize_history
+
+MAX_DIMENSIONS: Final = 15
+FitStatus = Literal["max-iterations", "max-evaluations", "plateau", "oscillation"]
+ParameterVector = tuple[float, ...]
+Bounds = tuple[tuple[float, float], ...]
+Objective = Callable[[ParameterVector], float]
+RenderForParameters = Callable[[ParameterVector], str | Path]
+DivineEyeEvaluator = Callable[[Path, Path], Mapping[str, object]]
+
+
+@dataclass(frozen=True, slots=True)
+class FitInputError(ValueError):
+ field: str
+ detail: str
+
+ def __str__(self) -> str:
+ return f"invalid fit input {self.field}: {self.detail}"
+
+
+@dataclass(frozen=True, slots=True)
+class NonFiniteScoreError(ValueError):
+ value_repr: str
+
+ def __str__(self) -> str:
+ return f"objective returned non-finite score {self.value_repr}"
+
+
+@dataclass(frozen=True, slots=True)
+class FitConfig:
+ max_iterations: int = 40
+ max_evaluations: int = 500
+ min_improvement: float = 1e-9
+ plateau_iterations: int = 3
+ oscillation_flips: int = 2
+ seed: int | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class FitTelemetry:
+ iteration: int
+ evaluations: int
+ best_score: float
+ improved: bool
+ step_sizes: ParameterVector
+
+
+@dataclass(frozen=True, slots=True)
+class FitResult:
+ parameters: ParameterVector
+ best_score: float
+ status: FitStatus
+ iterations: int
+ evaluations: int
+ seed: int | None
+ history: tuple[FitTelemetry, ...]
+
+ def to_correction_history(self, defect_tags: Sequence[str] = ()) -> list[dict[str, float | bool | list[str]]]:
+ tags = list(defect_tags)
+ for index, record in enumerate(self.history):
+ if not 0.0 <= record.best_score <= 1.0:
+ raise FitInputError(f"history[{index}].best_score", "must be within [0, 1] for fidelity")
+ return [
+ {"fidelity": record.best_score, "defectTags": tags.copy(), "reverted": False}
+ for record in self.history
+ ]
+
+ def to_json(self) -> dict[str, object]:
+ return {
+ "parameters": list(self.parameters),
+ "bestScore": self.best_score,
+ "bestObjectiveScore": self.best_score,
+ "status": self.status,
+ "iterations": self.iterations,
+ "evaluations": self.evaluations,
+ "seed": self.seed,
+ "history": [
+ {
+ "iteration": record.iteration,
+ "evaluations": record.evaluations,
+ "bestScore": record.best_score,
+ "bestObjectiveScore": record.best_score,
+ "improved": record.improved,
+ "stepSizes": list(record.step_sizes),
+ }
+ for record in self.history
+ ],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class DivineEyeFitResult:
+ fit_result: FitResult
+ best_raw_fidelity: float | None
+ divine_eye_results: tuple[dict[str, object], ...]
+ correction_history: tuple[dict[str, object], ...]
+
+ def to_json(self) -> dict[str, object]:
+ return {
+ "fitResult": self.fit_result.to_json(),
+ "bestObjectiveScore": self.fit_result.best_score,
+ "bestRawFidelity": self.best_raw_fidelity,
+ "divineEyeResults": deepcopy(self.divine_eye_results),
+ "correctionHistory": deepcopy(self.correction_history),
+ }
+
+
+def divine_eye_fidelity(result: Mapping[str, object]) -> float:
+ if not isinstance(result, Mapping):
+ raise FitInputError("Divine Eye result", "must be a mapping")
+ score = result.get("fidelity")
+ if score is None:
+ raise FitInputError("Divine Eye result", "missing fidelity")
+ if isinstance(score, bool) or not isinstance(score, int | float) or not math.isfinite(score) or not 0.0 <= score <= 1.0:
+ raise FitInputError("Divine Eye result.fidelity", "must be a finite number in [0, 1]")
+ return float(score)
+
+
+def divine_eye_correction_history(
+ results: Sequence[Mapping[str, object]],
+) -> list[dict[str, object]]:
+ """Normalize unmodified Divine Eye results into correction-loop history."""
+ return normalize_history(results, divine_eye_fidelity, FitInputError)
+
+
+def _divine_eye_objective_score(result: Mapping[str, object]) -> float:
+ fidelity = divine_eye_fidelity(result)
+ return fidelity if is_approved_divine_eye_result(result, FitInputError, "Divine Eye result") else -1.0
+
+
+def fit_against_divine_eye(
+ initial: Sequence[float],
+ bounds: Sequence[Sequence[float]],
+ render_for_parameters: RenderForParameters,
+ reference_png: str | Path,
+ evaluator: DivineEyeEvaluator | None = None,
+ config: FitConfig = FitConfig(),
+) -> DivineEyeFitResult:
+ if not callable(render_for_parameters):
+ raise FitInputError("render_for_parameters", "must be callable")
+ evaluator = _default_divine_eye_evaluator if evaluator is None else evaluator
+ if not callable(evaluator):
+ raise FitInputError("evaluator", "must be callable")
+ reference_path = Path(reference_png)
+ results: list[Mapping[str, object]] = []
+
+ def objective(parameters: ParameterVector) -> float:
+ render_path = render_for_parameters(parameters)
+ evaluated = evaluator(reference_path, Path(render_path))
+ if not isinstance(evaluated, Mapping):
+ raise FitInputError("Divine Eye result", "must be a mapping")
+ result = deepcopy(dict(evaluated))
+ result.setdefault("hardGateFailures", [])
+ result["fitCandidateParameters"] = list(parameters)
+ result["fitReferencePng"] = str(reference_path)
+ result["fitRenderPath"] = str(render_path)
+ results.append(result)
+ return _divine_eye_objective_score(result)
+
+ fit_result = fit(initial, bounds, objective, config)
+ history = divine_eye_correction_history(results)
+ best_raw_fidelity = _selected_raw_fidelity(fit_result.parameters, results)
+ return DivineEyeFitResult(fit_result, best_raw_fidelity, tuple(deepcopy(dict(result)) for result in results), tuple(history))
+
+
+def _selected_raw_fidelity(parameters: ParameterVector, results: Sequence[Mapping[str, object]]) -> float | None:
+ candidate = list(parameters)
+ scores = [divine_eye_fidelity(result) for result in results if result["fitCandidateParameters"] == candidate and is_approved_divine_eye_result(result, FitInputError, "Divine Eye result")]
+ return max(scores, default=None)
+
+
+def _default_divine_eye_evaluator(reference_png: Path, render_png: Path) -> Mapping[str, object]:
+ if __package__:
+ from .divine_eye import evaluate
+ else:
+ from divine_eye import evaluate
+ return evaluate(reference_png, render_png)
+
+
+def fit(initial: Sequence[float], bounds: Sequence[Sequence[float]], objective: Objective, config: FitConfig = FitConfig()) -> FitResult:
+ if not callable(objective):
+ raise FitInputError("objective", "must be callable")
+ parameters, normalized_bounds = _normalize_inputs(initial, bounds)
+ _validate_config(config)
+ current_score = _finite_score(objective(parameters))
+ evaluations = 1
+ step_sizes = tuple((upper - lower) / 4.0 for lower, upper in normalized_bounds)
+ history: list[FitTelemetry] = [FitTelemetry(0, evaluations, current_score, False, step_sizes)]
+ plateau_count = 0
+ direction_by_coordinate: dict[int, int] = {}
+ direction_flips = 0
+ for iteration in range(1, config.max_iterations + 1):
+ iteration_start = current_score
+ improved = False
+ iteration_directions: dict[int, int] = {}
+ for index, (lower, upper) in enumerate(normalized_bounds):
+ coordinate_start = parameters[index]
+ candidate_parameters = parameters
+ candidate_score = current_score
+ candidate_direction = 0
+ for direction in (-1, 1):
+ value = min(upper, max(lower, coordinate_start + direction * step_sizes[index]))
+ if value == coordinate_start:
+ continue
+ if evaluations >= config.max_evaluations:
+ if candidate_direction:
+ parameters, current_score = candidate_parameters, candidate_score
+ history.append(FitTelemetry(iteration, evaluations, current_score, True, step_sizes))
+ return _result(parameters, current_score, "max-evaluations", iteration, evaluations, config, history)
+ return _result(parameters, current_score, "max-evaluations", iteration - 1, evaluations, config, history)
+ proposal = _replace_coordinate(parameters, index, value)
+ proposal_score = _finite_score(objective(proposal))
+ evaluations += 1
+ if proposal_score > candidate_score:
+ candidate_parameters = proposal
+ candidate_score = proposal_score
+ candidate_direction = direction
+ if candidate_direction:
+ iteration_directions[index] = candidate_direction
+ parameters = candidate_parameters
+ current_score = candidate_score
+ improved = True
+ net_gain = current_score - iteration_start
+ if net_gain < config.min_improvement:
+ plateau_count += 1
+ flips = sum(direction_by_coordinate.get(index) not in (None, direction) for index, direction in iteration_directions.items())
+ direction_flips = direction_flips + 1 if flips else 0
+ direction_by_coordinate = iteration_directions
+ else:
+ plateau_count = direction_flips = 0
+ direction_by_coordinate = {}
+ history.append(FitTelemetry(iteration, evaluations, current_score, improved, step_sizes))
+ if direction_flips >= config.oscillation_flips:
+ return _result(parameters, current_score, "oscillation", iteration, evaluations, config, history)
+ if plateau_count >= config.plateau_iterations:
+ return _result(parameters, current_score, "plateau", iteration, evaluations, config, history)
+ if not improved:
+ step_sizes = tuple(step / 2.0 for step in step_sizes)
+ return _result(parameters, current_score, "max-iterations", config.max_iterations, evaluations, config, history)
+
+
+def _result(
+ parameters: ParameterVector,
+ best_score: float,
+ status: FitStatus,
+ iterations: int,
+ evaluations: int,
+ config: FitConfig,
+ history: list[FitTelemetry],
+) -> FitResult:
+ return FitResult(parameters, best_score, status, iterations, evaluations, config.seed, tuple(history))
+
+
+def _normalize_inputs(initial: Sequence[float], bounds: Sequence[Sequence[float]]) -> tuple[ParameterVector, Bounds]:
+ if isinstance(initial, str | bytes) or not isinstance(initial, Sequence):
+ raise FitInputError("initial", "must be a sequence of parameters")
+ if isinstance(bounds, str | bytes) or not isinstance(bounds, Sequence):
+ raise FitInputError("bounds", "must be a sequence of bound pairs")
+ parameters = tuple(_finite_parameter(value, f"initial[{index}]") for index, value in enumerate(initial))
+ if not 1 <= len(parameters) <= MAX_DIMENSIONS:
+ raise FitInputError("initial", f"must contain 1..{MAX_DIMENSIONS} parameters")
+ if len(bounds) != len(parameters):
+ raise FitInputError("bounds", "must have one pair per parameter")
+ normalized_bounds: list[tuple[float, float]] = []
+ for index, pair in enumerate(bounds):
+ if isinstance(pair, str | bytes) or not isinstance(pair, Sequence):
+ raise FitInputError(f"bounds[{index}]", "must be a two-value sequence")
+ if len(pair) != 2:
+ raise FitInputError(f"bounds[{index}]", "must contain [lower, upper]")
+ lower = _finite_parameter(pair[0], f"bounds[{index}][0]")
+ upper = _finite_parameter(pair[1], f"bounds[{index}][1]")
+ if lower >= upper:
+ raise FitInputError(f"bounds[{index}]", "lower must be smaller than upper")
+ if not lower <= parameters[index] <= upper:
+ raise FitInputError(f"initial[{index}]", "must be within its bounds")
+ normalized_bounds.append((lower, upper))
+ return parameters, tuple(normalized_bounds)
+
+
+def _finite_parameter(value: float, field: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
+ raise FitInputError(field, "must be a finite non-boolean number")
+ return float(value)
+
+
+def _finite_score(score: float) -> float:
+ if isinstance(score, bool) or not isinstance(score, int | float) or not math.isfinite(score):
+ raise NonFiniteScoreError(repr(score))
+ return float(score)
+
+
+def _replace_coordinate(values: ParameterVector, index: int, value: float) -> ParameterVector:
+ return tuple(value if position == index else current for position, current in enumerate(values))
+
+
+def _validate_config(config: FitConfig) -> None:
+ if not isinstance(config, FitConfig):
+ raise FitInputError("config", "must be a FitConfig")
+ if not all(_is_positive_integer(value) for value in (config.max_iterations, config.max_evaluations, config.plateau_iterations, config.oscillation_flips)):
+ raise FitInputError("config", "iteration, evaluation, plateau, and oscillation limits must be positive")
+ if (
+ isinstance(config.min_improvement, bool)
+ or not isinstance(config.min_improvement, int | float)
+ or config.min_improvement < 0.0
+ or not math.isfinite(config.min_improvement)
+ ):
+ raise FitInputError("config.min_improvement", "must be a finite non-negative number")
+ if config.seed is not None and (isinstance(config.seed, bool) or not isinstance(config.seed, int)):
+ raise FitInputError("config.seed", "must be an integer or null")
+
+
+def _is_positive_integer(value: int) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
+
+
+def _quadratic_objective(target: ParameterVector) -> Objective:
+ return lambda values: 1.0 - sum((value - target[index]) ** 2 for index, value in enumerate(values))
+
+
+def _cli_config(raw: Mapping[str, object]) -> FitConfig:
+ names = {"maxIterations": "max_iterations", "maxEvaluations": "max_evaluations", "minImprovement": "min_improvement", "plateauIterations": "plateau_iterations", "oscillationFlips": "oscillation_flips", "seed": "seed"}
+ unknown = sorted(set(raw) - set(names))
+ if unknown:
+ raise FitInputError("config", f"unknown key(s): {', '.join(unknown)}")
+ values = {names[key]: value for key, value in raw.items() if key in names}
+ return FitConfig(**values)
+
+
+def main(argv: Sequence[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--input", required=True, type=Path, help="quadratic objective JSON input")
+ parser.add_argument("--json", action="store_true", help="emit JSON result")
+ args = parser.parse_args(argv)
+ try:
+ raw = json.loads(args.input.read_text(encoding="utf-8"))
+ if not isinstance(raw, dict):
+ raise FitInputError("input", "must be a JSON object")
+ expected = {"initial", "bounds", "target", "config"}
+ if set(raw) != expected:
+ raise FitInputError("input", f"must contain exactly {sorted(expected)}; missing={sorted(expected - set(raw))} unknown={sorted(set(raw) - expected)}")
+ initial = raw.get("initial")
+ bounds = raw.get("bounds")
+ target = raw.get("target")
+ config_raw = raw.get("config")
+ if not isinstance(initial, list) or not isinstance(bounds, list) or not isinstance(target, list):
+ raise FitInputError("input", "initial, bounds, and target must be arrays")
+ if not isinstance(config_raw, dict):
+ raise FitInputError("config", "must be an object")
+ target_parameters, _ = _normalize_inputs(target, bounds)
+ result = fit(initial, bounds, _quadratic_objective(target_parameters), _cli_config(config_raw))
+ except (FitInputError, NonFiniteScoreError, OSError, json.JSONDecodeError) as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ payload = result.to_json()
+ if args.json:
+ print(json.dumps(payload, sort_keys=True))
+ else:
+ print(f"{payload['status']} score={payload['bestScore']} evaluations={payload['evaluations']}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/geometry_integrity.py b/forge/stage4_review/geometry_integrity.py
index f2adb7a..31e4ffe 100644
--- a/forge/stage4_review/geometry_integrity.py
+++ b/forge/stage4_review/geometry_integrity.py
@@ -1,12 +1,20 @@
from __future__ import annotations
+import sys
from collections import Counter
from itertools import combinations
+from math import isfinite
+from pathlib import Path
from typing import Any, TypeAlias
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from self_intersection import analyze_mesh # noqa: E402
+
SEAM_MIN_OVERLAP = 0.02
SEAM_MAX_OVERLAP = 0.05
SEAM_SOURCE = "grimoire/build/geometry_patterns.md"
+DEFAULT_TRIANGLE_BUDGET = 50_000
+NORMAL_DOT_THRESHOLD = 0.0
EdgeKey: TypeAlias = tuple[tuple[float, ...], tuple[float, ...]]
@@ -90,6 +98,96 @@ def _blade_thickness(mesh: dict[str, Any]) -> dict[str, Any]:
"reported": bool(values)}
+def _triangle_count(mesh: dict[str, Any]) -> int | None:
+ if isinstance(mesh.get("triangleCount"), (int, float)) and not isinstance(mesh["triangleCount"], bool):
+ return max(0, int(mesh["triangleCount"]))
+ indices = mesh.get("indices")
+ if isinstance(indices, list):
+ return len(indices) if indices and isinstance(indices[0], (list, tuple)) else len(indices) // 3
+ return None
+
+
+def _has_reduced_lod_tiers(lod_plan: Any) -> bool:
+ if not isinstance(lod_plan, list) or len(lod_plan) < 2:
+ return False
+ previous_distance: float | None = None
+ previous_triangles: int | None = None
+ for tier in lod_plan:
+ if not isinstance(tier, dict):
+ return False
+ distance = tier.get("distance")
+ triangles = tier.get("triangleCount")
+ if (
+ not isinstance(distance, (int, float))
+ or isinstance(distance, bool)
+ or not isfinite(distance)
+ or not isinstance(triangles, int)
+ or isinstance(triangles, bool)
+ or triangles < 1
+ ):
+ return False
+ if previous_distance is not None and distance <= previous_distance:
+ return False
+ if previous_triangles is not None and triangles >= previous_triangles:
+ return False
+ previous_distance = float(distance)
+ previous_triangles = triangles
+ return True
+
+
+def _normal_consistency(mesh: dict[str, Any]) -> dict[str, Any] | None:
+ normals = mesh.get("normals")
+ if not isinstance(normals, list) or not isinstance(mesh.get("vertices"), list):
+ return None
+ if len(normals) != len(mesh["vertices"]):
+ return {"checked": False, "consistent": False, "reason": "normal count does not match vertex count"}
+ indices = mesh.get("indices")
+ triangles = indices if isinstance(indices, list) and indices and isinstance(indices[0], (list, tuple)) else (
+ [indices[i:i + 3] for i in range(0, len(indices), 3)] if isinstance(indices, list) else []
+ )
+ if not triangles:
+ return None
+ flips = 0
+ checked = 0
+ invalid_normals = 0
+ for triangle in triangles:
+ if len(triangle) != 3:
+ continue
+ try:
+ a, b, c = (mesh["vertices"][int(index)] for index in triangle)
+ edge_a = [float(b[i]) - float(a[i]) for i in range(3)]
+ edge_b = [float(c[i]) - float(a[i]) for i in range(3)]
+ face = [
+ edge_a[1] * edge_b[2] - edge_a[2] * edge_b[1],
+ edge_a[2] * edge_b[0] - edge_a[0] * edge_b[2],
+ edge_a[0] * edge_b[1] - edge_a[1] * edge_b[0],
+ ]
+ length = sum(value * value for value in face) ** 0.5
+ if length <= 1e-12:
+ continue
+ face = [value / length for value in face]
+ average = [
+ sum(float(mesh["normals"][int(index)][axis]) for index in triangle) / 3
+ for axis in range(3)
+ ]
+ normal_length = sum(value * value for value in average) ** 0.5
+ if normal_length <= 1e-12:
+ invalid_normals += 1
+ continue
+ dot = sum(face[axis] * average[axis] for axis in range(3)) / normal_length
+ checked += 1
+ flips += dot < NORMAL_DOT_THRESHOLD
+ except (IndexError, TypeError, ValueError):
+ return {"checked": False, "consistent": False, "reason": "invalid vertex/normal data"}
+ return {
+ "checked": checked > 0,
+ "consistent": flips == 0 and invalid_normals == 0,
+ "checkedTriangles": checked,
+ "flippedTriangles": flips,
+ "invalidNormalTriangles": invalid_normals,
+ }
+
+
def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:
meshes = payload.get("meshes") or payload.get("components") or []
if isinstance(meshes, dict):
@@ -98,6 +196,14 @@ def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:
raise ValueError("built geometry meshes/components must be an array or object")
reports: list[dict[str, Any]] = []
failures: list[str] = []
+ issues: list[dict[str, Any]] = []
+ performance = payload.get("performanceBudget") if isinstance(payload.get("performanceBudget"), dict) else {}
+ triangle_budget = performance.get("triangleBudget", payload.get("triangleBudget", DEFAULT_TRIANGLE_BUDGET))
+ if not isinstance(triangle_budget, (int, float)) or isinstance(triangle_budget, bool) or triangle_budget <= 0:
+ triangle_budget = DEFAULT_TRIANGLE_BUDGET
+ lod_plan = payload.get("lodPlan")
+ lod_plan_valid = _has_reduced_lod_tiers(lod_plan)
+ total_triangles = 0
for index, mesh in enumerate(meshes):
if not isinstance(mesh, dict):
continue
@@ -107,12 +213,56 @@ def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:
else:
item.update({"boundaryEdges": None, "nonManifoldEdges": None, "note": "mesh topology not supplied"})
role = str(mesh.get("role") or "").lower()
+ triangles = _triangle_count(mesh)
+ item["triangleCount"] = triangles
+ if triangles is not None:
+ total_triangles += triangles
+ normals = _normal_consistency(mesh)
+ if normals is not None:
+ item["normalConsistency"] = normals
+ if normals.get("consistent") is False:
+ message = f"{item['id']}: inconsistent face/vertex normals"
+ failures.append(message)
+ issues.append({"severity": "error", "code": "normal-consistency", "mesh": item["id"], "message": message})
+ elif isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):
+ message = f"{item['id']}: normals are required for watertight geometry validation"
+ failures.append(message)
+ item["normalConsistency"] = {"checked": False, "consistent": False, "reason": "normals missing"}
+ issues.append({"severity": "error", "code": "normal-missing", "mesh": item["id"], "message": message})
if role == "blade" or "blade" in str(item["id"]).lower():
item["thickness"] = _blade_thickness(mesh)
if item["thickness"]["constantGrind"] or item["thickness"]["missingDistalTaper"]:
failures.append(f"{item['id']}: blade has constant thickness or missing distal taper")
- if item["realization"] == "separate-geometry" and item.get("boundaryEdges", 0) not in (0, None):
- failures.append(f"{item['id']}: openEdges={item['boundaryEdges']} (separate geometry)")
+ if item.get("boundaryEdges", 0) not in (0, None):
+ message = f"{item['id']}: openEdges={item['boundaryEdges']} ({item['realization']})"
+ failures.append(message)
+ issues.append({"severity": "error", "code": "watertight", "mesh": item["id"], "message": message})
+ if item.get("nonManifoldEdges", 0):
+ message = f"{item['id']}: nonManifoldEdges={item['nonManifoldEdges']}"
+ failures.append(message)
+ issues.append({"severity": "error", "code": "non-manifold", "mesh": item["id"], "message": message})
+ # Both checks above are TOPOLOGICAL, and a surface pushed through its own far side changes no
+ # connectivity at all -- it reports 0 open edges, 0 non-manifold edges, and an identical edge
+ # count to the clean mesh. That is not a hypothetical: it is how a punched-through skull shipped.
+ # The geometric check belongs right here, beside the two it complements, or it is a CLI nobody
+ # remembers to run.
+ if isinstance(mesh.get("vertices"), list) and isinstance(mesh.get("indices"), list):
+ probe = analyze_mesh(mesh)
+ item["selfIntersection"] = {
+ key: probe[key]
+ for key in (
+ "selfIntersecting", "insideVertexCount", "undecidedVertexCount",
+ "sampledVertexCount", "totalVertexCount", "samplingStride",
+ )
+ if key in probe
+ }
+ if probe.get("selfIntersecting"):
+ message = (
+ f"{item['id']}: selfIntersecting, {probe.get('insideVertexCount')} of "
+ f"{probe.get('sampledVertexCount')} sampled vertices lie inside their own surface"
+ )
+ failures.append(message)
+ issues.append({"severity": "error", "code": "self-intersection", "mesh": item["id"], "message": message})
reports.append(item)
seams: list[dict[str, Any]] = []
for first, second in combinations([item for item in meshes if isinstance(item, dict)], 2):
@@ -128,4 +278,17 @@ def measure_geometry_integrity(payload: dict[str, Any]) -> dict[str, Any]:
seams.append(seam)
if overlap < SEAM_MIN_OVERLAP:
failures.append(f"seam {seam['a']}↔{seam['b']}: overlap={overlap:.3f} < {SEAM_MIN_OVERLAP:.2f}")
- return {"passed": not failures, "source": SEAM_SOURCE, "minimumSeamOverlap": SEAM_MIN_OVERLAP, "maximumDocumentedSeamOverlap": SEAM_MAX_OVERLAP, "meshes": reports, "seams": seams, "failures": failures}
+ if total_triangles > triangle_budget:
+ message = f"triangle budget exceeded: {total_triangles} > {int(triangle_budget)}"
+ failures.append(message)
+ issues.append({"severity": "error", "code": "triangle-budget", "message": message, "triangles": total_triangles, "budget": int(triangle_budget)})
+ if not lod_plan_valid:
+ lod_message = "triangle budget exceeded without LOD tiers with increasing distance and decreasing triangleCount"
+ failures.append(lod_message)
+ code = "lod-required" if not isinstance(lod_plan, list) or not lod_plan else "lod-invalid"
+ issues.append({"severity": "error", "code": code, "message": lod_message})
+ return {"passed": not failures, "source": SEAM_SOURCE, "minimumSeamOverlap": SEAM_MIN_OVERLAP,
+ "maximumDocumentedSeamOverlap": SEAM_MAX_OVERLAP, "triangleBudget": int(triangle_budget),
+ "triangleCount": total_triangles, "lodPlanPresent": isinstance(lod_plan, list) and bool(lod_plan),
+ "lodPlanValid": lod_plan_valid,
+ "meshes": reports, "seams": seams, "failures": failures, "issues": issues}
diff --git a/forge/stage4_review/joint_loops.py b/forge/stage4_review/joint_loops.py
new file mode 100644
index 0000000..d17cab1
--- /dev/null
+++ b/forge/stage4_review/joint_loops.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+"""Does the mesh carry enough edge loops at each joint to survive being bent?
+
+A skinned joint with too few rings of geometry across it collapses when it flexes: the elbow pinches
+into a crease, the knee loses its volume, the shoulder creases into a fold. No amount of weight
+tuning fixes it, because there is simply nothing there to deform -- the vertices needed to describe a
+bent surface do not exist.
+
+The usual answer to this in a mesh-generation pipeline is retopology, and the honest industry position
+is that automatic remeshing does NOT reliably produce deformation-grade topology; people still
+retopologize by hand. But that constraint belongs to pipelines that receive a finished mesh. A
+procedural generator writes its own topology, so it can place loops at joints BY CONSTRUCTION and
+never need to repair them afterwards. This module is the gate that makes that a requirement rather
+than a hope.
+
+Method: for each joint, take the vertices within a radius of it, project them onto the bone axis, and
+count how many distinct bands along that axis they occupy. Bands, not raw vertex count: ten thousand
+vertices in two rings still cannot bend, and counting vertices would call that mesh dense and pass it.
+
+The gate deliberately does not try to identify true quad edge loops. Recovering loop structure from a
+triangle soup is fragile, and the property that actually matters for deformation -- enough
+independently movable rings across the joint -- is exactly what band counting measures.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+MIN_LOOPS_PER_JOINT = 3
+DEFAULT_RADIUS_SCALE = 0.35
+BAND_TOLERANCE = 0.5
+
+
+def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
+ if indices and isinstance(indices[0], (list, tuple)):
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
+ return [
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
+ for i in range(0, len(indices) - 2, 3)
+ ]
+
+
+def _sub(a, b):
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+
+
+def _dot(a, b):
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+
+
+def _norm(a):
+ return math.sqrt(_dot(a, a))
+
+
+def count_loops_at_joint(
+ vertices: list[list[float]],
+ joint: list[float],
+ axis_start: list[float],
+ axis_end: list[float],
+ radius: float,
+ band_tolerance: float = BAND_TOLERANCE,
+) -> dict[str, Any]:
+ """Count distinct vertex bands along the bone axis within `radius` of the joint.
+
+ `band_tolerance` is a fraction of the mean gap between consecutive projections: two vertices
+ closer together than that are the same ring. Using an absolute epsilon instead would make the
+ count depend on the model's units, so the same character at two scales would score differently.
+ """
+ direction = _sub(axis_end, axis_start)
+ length = _norm(direction)
+ if length <= 1e-12:
+ return {"loops": 0, "vertexCount": 0, "reason": "bone has zero length"}
+ axis = [component / length for component in direction]
+
+ # An AXIAL window, not a sphere around the joint. A sphere drops rings simply because the limb is
+ # thick -- on a tube of radius 0.5 spanning a bone of length 2, the rings either side of the joint
+ # sit 0.707 away and a 0.7 sphere excludes every one of them, scoring a perfectly bendable joint
+ # as having a single loop. Thickness has nothing to do with whether a joint can bend; what matters
+ # is how many bands sit ALONG the bone near the joint. The radial cap only keeps unrelated
+ # geometry that happens to run parallel from being counted.
+ radial_cap = radius * 2.0
+ projections: list[float] = []
+ for vertex in vertices:
+ offset = _sub(vertex, joint)
+ along = _dot(offset, axis)
+ if abs(along) > radius:
+ continue
+ radial = math.sqrt(max(0.0, _dot(offset, offset) - along * along))
+ if radial > radial_cap:
+ continue
+ projections.append(along)
+ if len(projections) < 2:
+ return {"loops": len(projections), "vertexCount": len(projections)}
+
+ projections.sort()
+ span = projections[-1] - projections[0]
+ if span <= 1e-12:
+ return {"loops": 1, "vertexCount": len(projections)}
+ mean_gap = span / max(1, len(projections) - 1)
+ threshold = mean_gap * band_tolerance
+
+ loops = 1
+ previous = projections[0]
+ for value in projections[1:]:
+ if value - previous > threshold:
+ loops += 1
+ previous = value
+ return {"loops": loops, "vertexCount": len(projections), "axialSpan": round(span, 6)}
+
+
+def analyze_joint_loops(
+ meshes: list[dict[str, Any]],
+ bones: list[dict[str, Any]],
+ min_loops: int = MIN_LOOPS_PER_JOINT,
+ radius_scale: float = DEFAULT_RADIUS_SCALE,
+) -> dict[str, Any]:
+ """Check every bone's joint against the pooled surface of all supplied meshes.
+
+ Pooled rather than per mesh: a joint often sits where two components meet, and asking each mesh
+ separately would let a joint pass because one half of it happens to be dense while the other has
+ nothing there at all.
+ """
+ pooled: list[list[float]] = []
+ for mesh in meshes:
+ vertices = mesh.get("vertices")
+ if isinstance(vertices, list):
+ pooled.extend(vertices)
+ if not pooled:
+ raise ValueError("no vertices supplied")
+
+ reports: list[dict[str, Any]] = []
+ failures: list[str] = []
+ for bone in bones:
+ joint = bone.get("jointPos")
+ tip = bone.get("tipPos")
+ if not isinstance(joint, list) or not isinstance(tip, list):
+ continue
+ bone_length = _norm(_sub(tip, joint))
+ radius = bone_length * radius_scale
+ measured = count_loops_at_joint(pooled, joint, joint, tip, radius)
+ record = {
+ "bone": str(bone.get("id")),
+ "radius": round(radius, 6),
+ "minLoops": min_loops,
+ **measured,
+ }
+ record["passes"] = measured["loops"] >= min_loops
+ if not record["passes"]:
+ failures.append(
+ f"{record['bone']}: {measured['loops']} loop(s) within {record['radius']} of the "
+ f"joint, needs {min_loops}; this joint will crease rather than bend"
+ )
+ reports.append(record)
+
+ return {
+ "joints": reports,
+ "failures": failures,
+ "jointCount": len(reports),
+ "failingJointCount": len(failures),
+ "passed": not failures,
+ "note": (
+ "loops are counted as distinct vertex bands along the bone axis, not as recovered quad "
+ "loops; a dense joint with only two bands still cannot bend and is reported as such"
+ ),
+ }
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [f"joints checked: {result['jointCount']}"]
+ for record in result["joints"]:
+ flag = "ok" if record["passes"] else "TOO FEW LOOPS"
+ lines.append(
+ f" [{flag}] {record['bone']} loops={record['loops']} "
+ f"vertices={record['vertexCount']} radius={record['radius']}"
+ )
+ lines.append("verdict: PASS" if result["passed"] else "verdict: GATE FAILURE")
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Check edge-loop density at rig joints.")
+ parser.add_argument("meshes", type=Path, help="JSON with a meshes array, or a single mesh")
+ parser.add_argument("--bones", type=Path, required=True)
+ parser.add_argument("--min-loops", type=int, default=MIN_LOOPS_PER_JOINT)
+ parser.add_argument("--radius-scale", type=float, default=DEFAULT_RADIUS_SCALE)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ payload = json.loads(args.meshes.read_text())
+ meshes = payload["meshes"] if isinstance(payload, dict) and isinstance(payload.get("meshes"), list) else [payload]
+ result = analyze_joint_loops(
+ meshes, json.loads(args.bones.read_text()), args.min_loops, args.radius_scale
+ )
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
+ return 0 if result["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/make_comparison_sheet.py b/forge/stage4_review/make_comparison_sheet.py
index 5843d98..e95177d 100755
--- a/forge/stage4_review/make_comparison_sheet.py
+++ b/forge/stage4_review/make_comparison_sheet.py
@@ -18,6 +18,9 @@ import tempfile
import zlib
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -128,6 +131,12 @@ def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
try:
return read_png(path)
except Exception as direct_error:
+ jpeg_bytes = path.read_bytes()
+ if is_jpeg(jpeg_bytes):
+ try:
+ return decode_jpeg(jpeg_bytes)[:3]
+ except UnsupportedJpeg:
+ pass
sips = shutil.which("sips")
if not sips:
raise ValueError(f"could not decode {path.name} as PNG and sips is unavailable: {direct_error}") from direct_error
@@ -212,6 +221,10 @@ def blit(
canvas[target_y * width + target_x] = image[y * image_w + x]
+# WHOLE-IMAGE ONLY. This composites the full reference beside the full render, at which scale a
+# few-pixel tear is invisible to a human reviewer and to a VLM alike -- so a sheet that "looks right"
+# is not evidence about small features. Feature crops belong here eventually; until then treat this
+# as a macro-tier artifact. See grimoire/review/divine_eye_microscope.md.
def create_sheet(
reference: Path,
render: Path,
diff --git a/forge/stage4_review/material_comparator.py b/forge/stage4_review/material_comparator.py
new file mode 100644
index 0000000..a472cbd
--- /dev/null
+++ b/forge/stage4_review/material_comparator.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python3
+"""Deterministic per-material crop comparison and mismatch classification."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge" / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+from color_metrics import delta_e_rgb # noqa: E402
+
+
+GRID = 48
+
+
+def _grid(path: Path) -> tuple[list[tuple[int, int, int]], list[bool], dict[str, Any]]:
+ width, height, pixels, warnings = load_image(path)
+ mask, diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
+ values: list[tuple[int, int, int]] = []
+ selected: list[bool] = []
+ for y in range(GRID):
+ sy = min(height - 1, int((y + 0.5) * height / GRID))
+ for x in range(GRID):
+ sx = min(width - 1, int((x + 0.5) * width / GRID))
+ index = sy * width + sx
+ red, green, blue, _alpha = pixels[index]
+ values.append((red, green, blue))
+ selected.append(mask[index])
+ return values, selected, {
+ "width": width,
+ "height": height,
+ "foregroundCoverage": round(sum(selected) / max(1, len(selected)), 4),
+ "warnings": warnings + mask_warnings,
+ "readback": True,
+ "diagnostics": diagnostics,
+ }
+
+
+def _mean(values: list[tuple[int, int, int]], selected: list[bool]) -> tuple[int, int, int]:
+ kept = [value for value, use in zip(values, selected) if use] or values
+ return tuple(round(sum(value[channel] for value in kept) / len(kept)) for channel in range(3)) # type: ignore[return-value]
+
+
+def _luma(rgb: tuple[int, int, int]) -> float:
+ return (rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722) / 255.0
+
+
+def _features(values: list[tuple[int, int, int]], selected: list[bool]) -> dict[str, float]:
+ luma = [_luma(value) for value in values]
+ kept = [value for value, use in zip(luma, selected) if use] or luma
+ average = sum(kept) / max(1, len(kept))
+ variance = sum((value - average) ** 2 for value in kept) / max(1, len(kept))
+ horizontal = 0.0
+ vertical = 0.0
+ count_h = count_v = 0
+ for y in range(GRID):
+ for x in range(GRID):
+ index = y * GRID + x
+ if x:
+ horizontal += abs(luma[index] - luma[index - 1])
+ count_h += 1
+ if y:
+ vertical += abs(luma[index] - luma[index - GRID])
+ count_v += 1
+ horizontal /= max(1, count_h)
+ vertical /= max(1, count_v)
+ anisotropy = max(horizontal, vertical) / max(1e-6, min(horizontal, vertical))
+ return {
+ "meanLuma": average,
+ "lumaVariance": variance,
+ "horizontalGradient": horizontal,
+ "verticalGradient": vertical,
+ "anisotropyProxy": min(4.0, anisotropy),
+ }
+
+
+def _similarity(a: float, b: float, scale: float) -> float:
+ return max(0.0, min(1.0, 1.0 - abs(a - b) / max(1e-6, scale)))
+
+
+def _expected_mismatch(expected: dict[str, Any] | None, features: dict[str, float]) -> list[str]:
+ if not expected:
+ return []
+ mismatches: list[str] = []
+ prior = expected.get("renderPrior", expected)
+ anisotropy_value = prior.get("anisotropy", 0.0) if isinstance(prior, dict) else 0.0
+ anisotropy = anisotropy_value.get("default", 0.0) if isinstance(anisotropy_value, dict) else anisotropy_value
+ if isinstance(anisotropy, (int, float)) and anisotropy > 0.5 and features["anisotropyProxy"] < 1.25:
+ mismatches.append("wrong-anisotropy")
+ roughness_value = prior.get("roughness", 0.5) if isinstance(prior, dict) else 0.5
+ roughness = roughness_value.get("default", 0.5) if isinstance(roughness_value, dict) else roughness_value
+ if isinstance(roughness, (int, float)):
+ # A roughness prior is only a cue here; image evidence cannot prove a scalar.
+ if roughness < 0.2 and features["lumaVariance"] < 0.003:
+ mismatches.append("highlight-response-too-flat")
+ if roughness > 0.8 and features["lumaVariance"] > 0.08:
+ mismatches.append("highlight-response-too-sharp")
+ return mismatches
+
+
+def compare_material_crops(
+ reference: Path,
+ render: Path,
+ *,
+ material_id: str | None = None,
+ expected: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ reference_values, reference_mask, reference_meta = _grid(reference)
+ render_values, render_mask, render_meta = _grid(render)
+ reference_mean = _mean(reference_values, reference_mask)
+ render_mean = _mean(render_values, render_mask)
+ delta_e = delta_e_rgb(reference_mean, render_mean)
+ reference_features = _features(reference_values, reference_mask)
+ render_features = _features(render_values, render_mask)
+ scores = {
+ "baseColor": _similarity(delta_e, 0.0, 50.0),
+ "meanLuma": _similarity(reference_features["meanLuma"], render_features["meanLuma"], 0.45),
+ "microstructure": _similarity(reference_features["lumaVariance"], render_features["lumaVariance"], 0.12),
+ "directionalResponse": _similarity(reference_features["anisotropyProxy"], render_features["anisotropyProxy"], 2.0),
+ }
+ scores["overall"] = round(
+ scores["baseColor"] * 0.40
+ + scores["meanLuma"] * 0.20
+ + scores["microstructure"] * 0.25
+ + scores["directionalResponse"] * 0.15,
+ 4,
+ )
+ mismatches: list[str] = []
+ if delta_e > 20:
+ mismatches.append("wrong-base-color")
+ if scores["meanLuma"] < 0.72:
+ mismatches.append("wrong-exposure-or-value")
+ if scores["microstructure"] < 0.62:
+ mismatches.append("wrong-roughness-or-microstructure")
+ mismatches.extend(_expected_mismatch(expected, render_features))
+ if expected and expected.get("family") in {"metal", "glass", "gemstone"} and render_features["lumaVariance"] < 0.002:
+ mismatches.append("missing-environment-response")
+ unique_mismatches = list(dict.fromkeys(mismatches))
+ return {
+ "schemaVersion": 1,
+ "kind": "img2threejs.material-comparison",
+ "materialId": material_id,
+ "reference": {"path": str(reference.resolve()), "meanRgb": reference_mean, "features": reference_features, **reference_meta},
+ "render": {"path": str(render.resolve()), "meanRgb": render_mean, "features": render_features, **render_meta},
+ "metrics": {"deltaE00": round(delta_e, 3), "scores": scores},
+ "mismatches": unique_mismatches,
+ "passed": scores["overall"] >= 0.7 and not {"wrong-base-color", "missing-environment-response"} & set(unique_mismatches),
+ "nextAction": "continue" if scores["overall"] >= 0.7 and not unique_mismatches else "refine-code",
+ "limitation": "Deterministic crop metrics are evidence; material identity still requires vision review for ambiguous cases.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--reference", type=Path, required=True)
+ parser.add_argument("--render", type=Path, required=True)
+ parser.add_argument("--material-id")
+ parser.add_argument("--expected", type=Path)
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args(argv)
+ try:
+ expected = json.loads(args.expected.read_text(encoding="utf-8")) if args.expected else None
+ result = compare_material_crops(args.reference, args.render, material_id=args.material_id, expected=expected)
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps({"passed": result["passed"], "overall": result["metrics"]["scores"]["overall"], "mismatches": result["mismatches"]}, indent=2))
+ return 0 if result["passed"] else 2
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/material_feedback.py b/forge/stage4_review/material_feedback.py
new file mode 100644
index 0000000..f7e5719
--- /dev/null
+++ b/forge/stage4_review/material_feedback.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Apply bounded, material-scoped feedback from crop comparison results."""
+
+from __future__ import annotations
+
+import argparse
+import copy
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge" / "stage4_review"))
+from correction_loop import decide # noqa: E402
+sys.path.insert(0, str(ROOT / "forge"))
+from materials.reference import load_reference # noqa: E402
+
+
+def _prior_bounds(material: dict[str, Any], property_name: str, registry: dict[str, Any]) -> tuple[float, float]:
+ profile_id = material.get("referenceMaterialId")
+ profile = next((item for item in registry.get("materials", []) if item.get("id") == profile_id), None)
+ prior = profile.get("renderPrior", {}).get(property_name) if isinstance(profile, dict) else None
+ if isinstance(prior, dict) and isinstance(prior.get("range"), list):
+ return float(prior["range"][0]), float(prior["range"][1])
+ return (0.0, 1.0)
+
+
+def _base(value: Any, fallback: float = 0.0) -> float:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, dict) and isinstance(value.get("base"), (int, float)):
+ return float(value["base"])
+ return fallback
+
+
+def propose_patch(material: dict[str, Any], comparison: dict[str, Any], registry: dict[str, Any]) -> dict[str, Any]:
+ mismatches = set(comparison.get("mismatches", []))
+ changes: dict[str, Any] = {}
+ reasons: list[str] = []
+ if "wrong-roughness-or-microstructure" in mismatches or "highlight-response-too-flat" in mismatches:
+ low, high = _prior_bounds(material, "roughness", registry)
+ current = _base(material.get("roughness"), (low + high) / 2)
+ value = min(high, current + 0.08)
+ changes["roughness"] = {"base": round(value, 4), "variation": _base(material.get("roughness"), 0.0) * 0.0}
+ reasons.append("increase roughness within the profile prior")
+ if "highlight-response-too-sharp" in mismatches:
+ low, high = _prior_bounds(material, "roughness", registry)
+ current = _base(material.get("roughness"), (low + high) / 2)
+ changes["roughness"] = {"base": round(max(low, current - 0.08), 4), "variation": 0.0}
+ reasons.append("reduce roughness within the profile prior")
+ if "missing-environment-response" in mismatches:
+ changes["needsEnvironment"] = True
+ reasons.append("require a stable PMREM environment for conductor/transmissive response")
+ if "wrong-base-color" in mismatches:
+ target = comparison.get("render", {}).get("meanRgb")
+ reference = comparison.get("reference", {}).get("meanRgb")
+ if isinstance(reference, list) and len(reference) == 3:
+ changes["baseColor"] = "#%02X%02X%02X" % tuple(max(0, min(255, int(value))) for value in reference)
+ reasons.append("seed baseColor from the admitted reference crop; remove baked lighting in the next pass")
+ else:
+ reasons.append(f"base-color mismatch requires image evidence (render mean={target!r})")
+ if "wrong-anisotropy" in mismatches:
+ low, high = _prior_bounds(material, "anisotropy", registry)
+ current = _base(material.get("anisotropy"), (low + high) / 2)
+ changes["anisotropy"] = {"base": round(min(high, current + 0.1), 4), "variation": 0.0}
+ reasons.append("increase anisotropy and recapture a grazing view")
+ return {"changes": changes, "reasons": reasons, "requiresInput": not changes and bool(mismatches)}
+
+
+def apply_material_feedback(
+ spec: dict[str, Any],
+ material_id: str,
+ comparison: dict[str, Any],
+ *,
+ registry: dict[str, Any] | None = None,
+ history: list[dict[str, Any]] | None = None,
+ max_iter: int = 6,
+) -> dict[str, Any]:
+ registry = registry or load_reference()
+ material = next((item for item in spec.get("materials", []) if isinstance(item, dict) and item.get("id") == material_id), None)
+ if material is None:
+ raise ValueError(f"material {material_id!r} not found in spec")
+ scores = comparison.get("metrics", {}).get("scores", {})
+ iteration_history = list(history or spec.get("materialFeedbackHistory", []))
+ entry = {
+ "fidelity": float(scores.get("overall", 0.0)),
+ "defectTags": list(comparison.get("mismatches", [])),
+ "reverted": False,
+ "materialId": material_id,
+ "comparisonArtifact": comparison.get("kind", "material-comparison"),
+ }
+ iteration_history.append(entry)
+ decision = decide(iteration_history, target_fidelity=0.85, max_iter=max_iter, min_delta=0.02)
+ patch = propose_patch(material, comparison, registry) if not decision["stop"] or decision["action"] == "refine-code" else {"changes": {}, "reasons": []}
+ before = {key: copy.deepcopy(material.get(key)) for key in patch["changes"]}
+ for key, value in patch["changes"].items():
+ material[key] = value
+ after = {key: copy.deepcopy(material.get(key)) for key in patch["changes"]}
+ spec.setdefault("materialFeedbackHistory", []).append({
+ "materialId": material_id,
+ "comparison": copy.deepcopy(comparison),
+ "decision": decision,
+ "patch": patch,
+ "before": before,
+ "after": after,
+ })
+ return {
+ "decision": decision,
+ "patch": patch,
+ "materialId": material_id,
+ "historyLength": len(iteration_history),
+ "spec": spec,
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--spec", type=Path, required=True)
+ parser.add_argument("--comparison", type=Path, required=True)
+ parser.add_argument("--material-id", required=True)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--in-place", action="store_true")
+ parser.add_argument("--max-iter", type=int, default=6)
+ args = parser.parse_args(argv)
+ try:
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
+ comparison = json.loads(args.comparison.read_text(encoding="utf-8"))
+ result = apply_material_feedback(spec, args.material_id, comparison, max_iter=args.max_iter)
+ output = args.spec if args.in_place else args.out
+ if output is None:
+ raise ValueError("choose --in-place or --out")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(result["spec"], indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps({"decision": result["decision"], "patch": result["patch"], "out": str(output.resolve())}, indent=2))
+ return 0
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/material_gate.py b/forge/stage4_review/material_gate.py
new file mode 100644
index 0000000..2aa951e
--- /dev/null
+++ b/forge/stage4_review/material_gate.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Blocking acceptance gate for the wired material pipeline."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge"))
+from materials.compatibility import check_compatibility # noqa: E402
+
+
+def run_material_gate(
+ spec: dict[str, Any],
+ *,
+ analysis: dict[str, Any] | None = None,
+ comparisons: list[dict[str, Any]] | None = None,
+ view_plan: dict[str, Any] | None = None,
+ require_visual_evidence: bool = True,
+) -> dict[str, Any]:
+ failures: list[str] = []
+ warnings: list[str] = []
+ pipeline = spec.get("materialPipeline")
+ if not isinstance(pipeline, dict):
+ failures.append("spec is not wired to materialPipeline")
+ elif pipeline.get("status") != "proceed":
+ failures.append(f"materialPipeline status is {pipeline.get('status')!r}, not proceed")
+ if isinstance(pipeline, dict):
+ for item in pipeline.get("unresolvedNotObservedMaterials", []):
+ if isinstance(item, dict):
+ failures.append(
+ f"material {item.get('materialId')!r} is not observed: "
+ f"{item.get('reason', 'additional reference required')}"
+ )
+ if analysis is not None and analysis.get("status") != "proceed":
+ failures.append(f"material analysis status is {analysis.get('status')!r}, not proceed")
+ regions = pipeline.get("regions", []) if isinstance(pipeline, dict) else []
+ if not isinstance(regions, list) or not regions:
+ failures.append("no material regions are available for gating")
+ else:
+ for region in regions:
+ if not isinstance(region, dict):
+ failures.append("materialPipeline contains a malformed region")
+ continue
+ if region.get("status") != "proceed":
+ failures.append(f"region {region.get('regionId')!r} is not proceed")
+ comparison_records = comparisons or []
+ if require_visual_evidence and not comparison_records:
+ failures.append("no material crop comparison evidence was supplied")
+ for comparison in comparison_records:
+ if not comparison.get("passed"):
+ failures.append(
+ f"material comparison failed for {comparison.get('materialId')!r}: "
+ + ", ".join(comparison.get("mismatches", []))
+ )
+ if view_plan is not None:
+ views = view_plan.get("views", [])
+ if not isinstance(views, list) or len(views) < 4:
+ failures.append("material view plan must contain at least four camera azimuths/views")
+ captures = view_plan.get("captureValidation", [])
+ if require_visual_evidence and captures and any(not item.get("passed") for item in captures if isinstance(item, dict)):
+ failures.append("one or more saved material captures failed readback/coverage validation")
+ environment = view_plan.get("environment")
+ if not isinstance(environment, dict) or environment.get("required") is not True:
+ failures.append("controlled material views must require a stable environment")
+ compatibility = check_compatibility(spec)
+ failures.extend(f"compatibility: {item}" for item in compatibility["failures"])
+ warnings.extend(compatibility["warnings"])
+ return {
+ "schemaVersion": 1,
+ "kind": "img2threejs.material-gate",
+ "passed": not failures,
+ "failures": failures,
+ "warnings": warnings,
+ "comparisonCount": len(comparison_records),
+ "compatibility": compatibility,
+ "requiredEvidence": [
+ "materialPipeline.status=proceed",
+ "all material regions status=proceed",
+ "per-region crop comparison passed",
+ "multi-angle controlled view plan and screenshot readback",
+ "geometry/UV/skinning/collision/LOD material ID compatibility passed",
+ ],
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("--analysis", type=Path)
+ parser.add_argument("--comparison", type=Path, action="append", default=[])
+ parser.add_argument("--view-plan", type=Path)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument("--in-place", action="store_true", help="record materialGate on the spec")
+ parser.add_argument("--allow-no-visual-evidence", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ spec = json.loads(args.spec.read_text(encoding="utf-8"))
+ analysis = json.loads(args.analysis.read_text(encoding="utf-8")) if args.analysis else None
+ comparisons = [json.loads(path.read_text(encoding="utf-8")) for path in args.comparison]
+ view_plan = json.loads(args.view_plan.read_text(encoding="utf-8")) if args.view_plan else None
+ result = run_material_gate(
+ spec,
+ analysis=analysis,
+ comparisons=comparisons,
+ view_plan=view_plan,
+ require_visual_evidence=not args.allow_no_visual_evidence,
+ )
+ if args.in_place:
+ spec["materialGate"] = result
+ args.spec.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps({"passed": result["passed"], "failures": result["failures"], "out": str(args.out.resolve())}, indent=2))
+ return 0 if result["passed"] else 2
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/material_views.py b/forge/stage4_review/material_views.py
new file mode 100644
index 0000000..db43185
--- /dev/null
+++ b/forge/stage4_review/material_views.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python3
+"""Build deterministic material camera/crop/microscope review plans.
+
+The forge cannot invent a browser screenshot, but it can make the required
+camera contract explicit and validate every crop before a renderer or vision
+provider consumes it. A showcase/browser adapter uses the emitted plan to
+capture the same views across iterations.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge" / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image, write_png_rgb # noqa: E402
+
+
+DEFAULT_AZIMUTHS = (0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0)
+DEFAULT_VALIDATION_VIEWS = (
+ "albedo-unlit", "neutral-studio", "grazing", "environment-reflection", "reference-beauty"
+)
+
+
+def _norm(value: float) -> float:
+ return round(float(value) % 360.0, 3)
+
+
+def build_view_plan(
+ component_id: str,
+ region_id: str,
+ *,
+ validation_views: list[str] | None = None,
+ azimuths: tuple[float, ...] = DEFAULT_AZIMUTHS,
+ elevation: float = 8.0,
+ zoom: float = 2.5,
+ target: tuple[float, float, float] = (0.0, 0.0, 0.0),
+ required_transmission: bool = False,
+) -> dict[str, Any]:
+ views = list(validation_views or DEFAULT_VALIDATION_VIEWS)
+ if required_transmission and "backlight-transmission" not in views:
+ views.append("backlight-transmission")
+ captures: list[dict[str, Any]] = []
+ for view_name in views:
+ for azimuth in azimuths:
+ captures.append({
+ "id": f"{region_id}-{view_name}-{int(_norm(azimuth)):03d}",
+ "componentId": component_id,
+ "regionId": region_id,
+ "view": view_name,
+ "camera": {
+ "azimuthDegrees": _norm(azimuth),
+ "elevationDegrees": elevation,
+ "rollDegrees": 0.0,
+ "target": list(target),
+ "zoom": zoom,
+ },
+ "cropPolicy": {
+ "mode": "visible-footprint",
+ "paddingFraction": 0.12,
+ "minCoverage": 0.03,
+ "maxCoverage": 0.92,
+ "microscope": view_name in {"grazing", "environment-reflection", "backlight-transmission"},
+ },
+ })
+ return {
+ "schemaVersion": 1,
+ "kind": "img2threejs.material-view-plan",
+ "componentId": component_id,
+ "regionId": region_id,
+ "environment": {
+ "required": True,
+ "prefilter": "PMREMGenerator",
+ "workingColorSpace": "LinearSRGBColorSpace",
+ "displayColorSpace": "SRGBColorSpace",
+ "toneMapping": "ACESFilmicToneMapping",
+ "exposure": 1.0,
+ "stableHash": "img2threejs-material-neutral-studio-v1",
+ },
+ "views": captures,
+ "captureRequirements": [
+ "save PNG/JPEG to workspace",
+ "read the saved image back before scoring",
+ "record renderer version, environment hash and camera transform",
+ "compare the full visible component footprint, not an isolated hidden surface",
+ ],
+ }
+
+
+def crop_visible_footprint(source: Path, bbox: dict[str, Any], output: Path, padding_fraction: float = 0.12) -> dict[str, Any]:
+ width, height, pixels, warnings = load_image(source)
+ required = ("x", "y", "width", "height")
+ if not isinstance(bbox, dict) or not all(isinstance(bbox.get(key), (int, float)) for key in required):
+ raise ValueError("visible-footprint bbox requires x, y, width and height")
+ x, y, box_width, box_height = (float(bbox[key]) for key in required)
+ if bbox.get("normalized") is True:
+ x, box_width = x * width, box_width * width
+ y, box_height = y * height, box_height * height
+ pad_x = box_width * max(0.0, padding_fraction)
+ pad_y = box_height * max(0.0, padding_fraction)
+ x0 = max(0, math.floor(x - pad_x))
+ y0 = max(0, math.floor(y - pad_y))
+ x1 = min(width, math.ceil(x + box_width + pad_x))
+ y1 = min(height, math.ceil(y + box_height + pad_y))
+ crop_width, crop_height = x1 - x0, y1 - y0
+ if crop_width < 8 or crop_height < 8:
+ raise ValueError("visible footprint crop is too small")
+ rgb = bytearray()
+ for row in range(y0, y1):
+ for column in range(x0, x1):
+ red, green, blue, alpha = pixels[row * width + column]
+ rgb.extend((red, green, blue) if alpha >= 16 else (0, 0, 0))
+ write_png_rgb(output, crop_width, crop_height, bytes(rgb))
+ mask, diagnostics, mask_warnings = build_foreground_mask(crop_width, crop_height, [(*rgb[i:i + 3], 255) for i in range(0, len(rgb), 3)])
+ coverage = sum(mask) / max(1, len(mask))
+ if coverage < 0.03:
+ raise ValueError("visible footprint crop contains too little foreground")
+ return {
+ "path": str(output.resolve()),
+ "bbox": {"x": x0, "y": y0, "width": crop_width, "height": crop_height},
+ "coverage": round(coverage, 4),
+ "diagnostics": diagnostics,
+ "warnings": warnings + mask_warnings,
+ "readback": {"width": crop_width, "height": crop_height, "pixels": crop_width * crop_height},
+ }
+
+
+def validate_capture(path: Path, *, min_width: int = 64, min_height: int = 64) -> dict[str, Any]:
+ width, height, pixels, warnings = load_image(path)
+ mask, diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
+ coverage = sum(mask) / max(1, len(mask))
+ failures: list[str] = []
+ if width < min_width or height < min_height:
+ failures.append(f"capture is {width}x{height}; minimum is {min_width}x{min_height}")
+ if coverage < 0.03:
+ failures.append("capture foreground coverage is below 3%")
+ return {
+ "path": str(path.resolve()),
+ "readable": True,
+ "width": width,
+ "height": height,
+ "foregroundCoverage": round(coverage, 4),
+ "diagnostics": diagnostics,
+ "warnings": warnings + mask_warnings,
+ "passed": not failures,
+ "failures": failures,
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--component-id", required=True)
+ parser.add_argument("--region-id", required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument("--validation-view", action="append", dest="validation_views")
+ parser.add_argument("--transmission", action="store_true")
+ parser.add_argument("--capture", type=Path, action="append", default=[])
+ args = parser.parse_args(argv)
+ try:
+ result = build_view_plan(
+ args.component_id,
+ args.region_id,
+ validation_views=args.validation_views,
+ required_transmission=args.transmission,
+ )
+ if args.capture:
+ result["captureValidation"] = [validate_capture(path) for path in args.capture]
+ result["capturePassed"] = all(item["passed"] for item in result["captureValidation"])
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps({"out": str(args.out.resolve()), "views": len(result["views"]), "capturePassed": result.get("capturePassed", True)}, indent=2))
+ return 0 if result.get("capturePassed", True) else 2
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/mesh_reference_compare.py b/forge/stage4_review/mesh_reference_compare.py
new file mode 100644
index 0000000..ff715e7
--- /dev/null
+++ b/forge/stage4_review/mesh_reference_compare.py
@@ -0,0 +1,362 @@
+#!/usr/bin/env python3
+"""
+Compare a candidate mesh against a reference mesh, band by band, and say WHERE it is wrong.
+
+This exists because every silhouette comparison in this project so far has measured something other
+than what it claimed. The ground plane sat inside the foreground mask; the capture clipped both
+subjects at the frame edge so their aspect ratios agreed by construction; and three separate attempts
+sliced both models into height bands measured down from the top of the bounding box -- where this
+model's top is a single ear tip and the reference's is two ears side by side, so every band below was
+offset and the numbers described the misalignment rather than the shapes.
+
+Three decisions follow from that history:
+
+FEET, NOT BBOX TOP. Both meshes are translated so their lowest point is 0 and scaled so their height
+is 1. The ground is a landmark both subjects genuinely share; the top of the bounding box is whatever
+happens to poke up highest, which is exactly the thing that differs.
+
+PERCENTILES, NOT EXTREMES. A staff is long, thin and contributes very few vertices, but it dominates
+any min/max width. The 5th-95th percentile of each band reports the BODY, which is what proportion
+work needs; the raw extent is still reported alongside so a genuine prop difference stays visible.
+
+CENTROID OFFSET, NOT ONLY WIDTH. Two bands can be the same width and still be in different places.
+Reporting the lateral and depth centroid of each band catches a limb that is the right size and the
+wrong side -- a defect a width-only comparison passes silently.
+
+Reads .glb (uncompressed) with the standard library only, per this package's no-dependency rule.
+
+Usage:
+ mesh_reference_compare.py REFERENCE.glb CANDIDATE.glb [--bands N] [--json]
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import struct
+import sys
+from pathlib import Path
+
+GLB_MAGIC = 0x46546C67
+CHUNK_JSON = 0x4E4F534A
+CHUNK_BIN = 0x004E4942
+FLOAT32 = 5126
+COMPONENTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}
+
+
+def read_glb_positions(path: Path) -> list[tuple[float, float, float]]:
+ """Every POSITION vertex in the file, in node-transformed world space.
+
+ Node transforms are applied because a mesh parked under a translated or scaled node would
+ otherwise be compared in the wrong place — and that failure looks like a proportion error.
+ """
+ data = path.read_bytes()
+ magic, _version, _length = struct.unpack_from("<III", data, 0)
+ if magic != GLB_MAGIC:
+ sys.exit(f"{path} is not a GLB")
+
+ offset, gltf, binary = 12, None, None
+ while offset < len(data):
+ chunk_len, chunk_type = struct.unpack_from("<II", data, offset)
+ body = data[offset + 8: offset + 8 + chunk_len]
+ if chunk_type == CHUNK_JSON:
+ gltf = json.loads(body)
+ elif chunk_type == CHUNK_BIN:
+ binary = body
+ offset += 8 + chunk_len + (-chunk_len % 4)
+
+ if gltf is None or binary is None:
+ sys.exit(f"{path}: missing JSON or BIN chunk")
+ required = gltf.get("extensionsRequired", [])
+ if any("draco" in e.lower() or "meshopt" in e.lower() for e in required):
+ sys.exit(f"{path}: compressed ({required}); this reader handles uncompressed GLB only")
+
+ views, accessors = gltf.get("bufferViews", []), gltf.get("accessors", [])
+
+ def read_accessor(index: int) -> list[tuple[float, float, float]]:
+ acc = accessors[index]
+ if acc.get("componentType") != FLOAT32 or acc.get("type") != "VEC3":
+ sys.exit(f"{path}: POSITION accessor {index} is not float32 VEC3")
+ view = views[acc["bufferView"]]
+ start = view.get("byteOffset", 0) + acc.get("byteOffset", 0)
+ stride = view.get("byteStride") or 12
+ out = []
+ for i in range(acc["count"]):
+ out.append(struct.unpack_from("<3f", binary, start + i * stride))
+ return out
+
+ # Full 4x4 composition, because the two shortcuts here were both wrong.
+ #
+ # The first version handled only translation and uniform scale and IGNORED node rotation
+ # entirely -- a rotated limb would have been measured in the wrong place with no complaint. The
+ # second refused any node carrying a `matrix`, which is exactly how three.js's GLTFExporter
+ # writes this project's own model, so the candidate could not be read at all. Composing real
+ # matrices removes both special cases.
+ nodes = gltf.get("nodes", [])
+ meshes = gltf.get("meshes", [])
+ points: list[tuple[float, float, float]] = []
+
+ def local_matrix(node: dict) -> list[float]:
+ if "matrix" in node:
+ return list(node["matrix"]) # glTF stores column-major
+ tx, ty, tz = node.get("translation", [0.0, 0.0, 0.0])
+ qx, qy, qz, qw = node.get("rotation", [0.0, 0.0, 0.0, 1.0])
+ sx, sy, sz = node.get("scale", [1.0, 1.0, 1.0])
+ xx, yy, zz = qx * qx, qy * qy, qz * qz
+ xy, xz, yz = qx * qy, qx * qz, qy * qz
+ wx, wy, wz = qw * qx, qw * qy, qw * qz
+ return [
+ (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0.0,
+ (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0.0,
+ (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0.0,
+ tx, ty, tz, 1.0,
+ ]
+
+ def multiply(a: list[float], b: list[float]) -> list[float]:
+ out = [0.0] * 16
+ for col in range(4):
+ for row in range(4):
+ out[col * 4 + row] = sum(a[k * 4 + row] * b[col * 4 + k] for k in range(4))
+ return out
+
+ def apply(m: list[float], x: float, y: float, z: float) -> tuple[float, float, float]:
+ return (
+ m[0] * x + m[4] * y + m[8] * z + m[12],
+ m[1] * x + m[5] * y + m[9] * z + m[13],
+ m[2] * x + m[6] * y + m[10] * z + m[14],
+ )
+
+ IDENTITY = [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0]
+
+ def walk(node_index: int, parent: list[float]) -> None:
+ node = nodes[node_index]
+ world = multiply(parent, local_matrix(node))
+ if "mesh" in node:
+ for prim in meshes[node["mesh"]]["primitives"]:
+ pos = prim.get("attributes", {}).get("POSITION")
+ if pos is None:
+ continue
+ for x, y, z in read_accessor(pos):
+ points.append(apply(world, x, y, z))
+ for child in node.get("children", []):
+ walk(child, world)
+
+ scene = gltf.get("scenes", [{}])[gltf.get("scene", 0)]
+ for root in scene.get("nodes", range(len(nodes))):
+ walk(root, IDENTITY)
+ if not points:
+ sys.exit(f"{path}: no POSITION data found")
+ return points
+
+
+def percentile(values: list[float], q: float) -> float:
+ if not values:
+ return 0.0
+ ordered = sorted(values)
+ k = (len(ordered) - 1) * q
+ lo = int(k)
+ hi = min(lo + 1, len(ordered) - 1)
+ return ordered[lo] + (ordered[hi] - ordered[lo]) * (k - lo)
+
+
+def normalise(points: list[tuple[float, float, float]]) -> list[tuple[float, float, float]]:
+ """Feet to 0, height to 1, and centred laterally on the body's own median.
+
+ Centring on the MEDIAN x rather than the bbox centre matters for the same reason percentiles
+ matter for width: one long horizontal prop drags a bbox centre sideways, and every centroid
+ offset below would then be measured against a datum the body is not standing on.
+ """
+ ys = [p[1] for p in points]
+ y0, y1 = min(ys), max(ys)
+ height = y1 - y0
+ if height <= 0:
+ sys.exit("degenerate mesh: zero height")
+ mx = percentile([p[0] for p in points], 0.5)
+ mz = percentile([p[2] for p in points], 0.5)
+ return [((p[0] - mx) / height, (p[1] - y0) / height, (p[2] - mz) / height) for p in points]
+
+
+def width_curve(points: list[tuple[float, float, float]], slices: int = 160) -> list[float]:
+ """Percentile width at every height, smoothed — the curve landmarks are read off."""
+ buckets: list[list[float]] = [[] for _ in range(slices)]
+ for x, y, _z in points:
+ buckets[min(slices - 1, int(y * slices))].append(x)
+ raw = [percentile(b, 0.95) - percentile(b, 0.05) if len(b) >= 20 else 0.0 for b in buckets]
+ smoothed = []
+ for i in range(slices):
+ window = raw[max(0, i - 2): min(slices, i + 3)]
+ smoothed.append(sum(window) / len(window))
+ return smoothed
+
+
+def find_landmarks(points: list[tuple[float, float, float]]) -> dict[str, float]:
+ """Locate the waist and the neck as the narrowest points of the body's width curve.
+
+ Equal-percentage bands only correspond between two subjects when the subjects share proportions.
+ These two do not -- one is far more compact than the other -- so band 75 is the head on one and
+ the upper chest on the other, and a deviation table built that way describes the mismatch rather
+ than the shapes. Three earlier comparisons in this project failed exactly there.
+
+ A standing figure's width curve has two reliable minima: the waist between hips and ribs, and the
+ neck between shoulders and skull. Both are found as the narrowest slice inside a generous search
+ window rather than at a fixed height, so they track the subject instead of assuming it.
+ """
+ curve = width_curve(points)
+ n = len(curve)
+
+ def narrowest(lo: float, hi: float) -> float:
+ segment = [(curve[i], i) for i in range(int(n * lo), int(n * hi)) if curve[i] > 0]
+ if not segment:
+ return (lo + hi) / 2
+ return min(segment)[1] / n
+
+ waist = narrowest(0.35, 0.68)
+
+ def neck_above(waist_h: float) -> float:
+ """The first true pinch ABOVE the waist, not merely the smallest slice in a fixed window.
+
+ A fixed 0.62-0.90 window picked the waist twice on this project's own model: its narrowest
+ slice sits at 0.61, inside that window, so waist and neck were reported 0.006 apart and every
+ band between them collapsed. Requiring a clear margin above the waist and an actual local
+ minimum -- narrower than the curve a few slices either side -- finds the pinch below the skull
+ instead of re-finding the one below the ribs.
+ """
+ start = int(n * min(0.92, waist_h + 0.08))
+ best, best_width = None, None
+ for i in range(start, int(n * 0.94)):
+ if curve[i] <= 0:
+ continue
+ lo_i, hi_i = max(0, i - 3), min(n - 1, i + 3)
+ if curve[i] <= curve[lo_i] and curve[i] <= curve[hi_i]:
+ if best_width is None or curve[i] < best_width:
+ best, best_width = i, curve[i]
+ return (best / n) if best is not None else min(0.92, waist_h + 0.15)
+
+ return {"ground": 0.0, "waist": waist, "neck": neck_above(waist), "top": 1.0}
+
+
+def landmark_bands(points: list[tuple[float, float, float]], per_segment: int) -> list[dict]:
+ """Band between anatomical landmarks, so band k means the same body region in both meshes."""
+ marks = find_landmarks(points)
+ edges: list[float] = []
+ for lo, hi in (("ground", "waist"), ("waist", "neck"), ("neck", "top")):
+ a, b = marks[lo], marks[hi]
+ edges.extend(a + (b - a) * i / per_segment for i in range(per_segment))
+ edges.append(1.0)
+
+ profile = []
+ for i in range(len(edges) - 1):
+ lo, hi = edges[i], edges[i + 1]
+ bucket = [p for p in points if lo <= p[1] < hi]
+ if len(bucket) < 20:
+ profile.append({"band": i, "points": len(bucket), "lo": lo, "hi": hi})
+ continue
+ xs = [p[0] for p in bucket]
+ zs = [p[2] for p in bucket]
+ profile.append({
+ "band": i, "points": len(bucket), "lo": lo, "hi": hi,
+ "width": percentile(xs, 0.95) - percentile(xs, 0.05),
+ "depth": percentile(zs, 0.95) - percentile(zs, 0.05),
+ "centroidX": percentile(xs, 0.5), "centroidZ": percentile(zs, 0.5),
+ })
+ return profile, marks
+
+
+def band_profile(points: list[tuple[float, float, float]], bands: int) -> list[dict]:
+ buckets: list[list[tuple[float, float, float]]] = [[] for _ in range(bands)]
+ for p in points:
+ idx = min(bands - 1, int(p[1] * bands))
+ buckets[idx].append(p)
+ profile = []
+ for i, bucket in enumerate(buckets):
+ if len(bucket) < 20:
+ profile.append({"band": i, "points": len(bucket)})
+ continue
+ xs = [p[0] for p in bucket]
+ zs = [p[2] for p in bucket]
+ profile.append({
+ "band": i,
+ "points": len(bucket),
+ "width": percentile(xs, 0.95) - percentile(xs, 0.05),
+ "depth": percentile(zs, 0.95) - percentile(zs, 0.05),
+ "widthFull": max(xs) - min(xs),
+ "centroidX": percentile(xs, 0.5),
+ "centroidZ": percentile(zs, 0.5),
+ })
+ return profile
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("reference", type=Path)
+ parser.add_argument("candidate", type=Path)
+ parser.add_argument("--bands", type=int, default=20)
+ parser.add_argument("--json", action="store_true")
+ parser.add_argument("--align", choices=("height", "landmarks"), default="landmarks",
+ help="landmarks (default) bands between the waist and neck it "
+ "finds in each mesh; height bands by raw percentage and "
+ "only corresponds when both subjects share proportions")
+ args = parser.parse_args()
+
+ ref_pts = normalise(read_glb_positions(args.reference))
+ cand_pts = normalise(read_glb_positions(args.candidate))
+ if args.align == "landmarks":
+ ref, ref_marks = landmark_bands(ref_pts, max(2, args.bands // 3))
+ cand, cand_marks = landmark_bands(cand_pts, max(2, args.bands // 3))
+ else:
+ ref, cand = band_profile(ref_pts, args.bands), band_profile(cand_pts, args.bands)
+ ref_marks = cand_marks = None
+
+ rows, errors = [], []
+ for r, c in zip(ref, cand):
+ if "width" not in r or "width" not in c:
+ continue
+ row = {
+ "band": r["band"],
+ "lowPct": round(r["band"] / args.bands * 100),
+ "highPct": round((r["band"] + 1) / args.bands * 100),
+ "refWidth": round(r["width"], 4), "candWidth": round(c["width"], 4),
+ "refDepth": round(r["depth"], 4), "candDepth": round(c["depth"], 4),
+ "widthDelta": round(c["width"] - r["width"], 4),
+ "depthDelta": round(c["depth"] - r["depth"], 4),
+ "centroidXDelta": round(c["centroidX"] - r["centroidX"], 4),
+ "centroidZDelta": round(c["centroidZ"] - r["centroidZ"], 4),
+ }
+ rows.append(row)
+ errors.append(abs(row["widthDelta"]) + abs(row["depthDelta"]))
+
+ score = sum(errors) / (2 * len(errors)) if errors else 0.0
+ report = {
+ "reference": str(args.reference), "candidate": str(args.candidate),
+ "bands": args.bands, "meanBandError": round(score, 5), "rows": rows,
+ "note": "0 = feet, 100 = top. Widths are 5-95 percentile, normalised by subject height, "
+ "so a thin prop cannot dominate. Both meshes are aligned on the ground plane, not "
+ "on the bounding-box top.",
+ }
+
+ if args.json:
+ print(json.dumps(report, indent=2))
+ return
+
+ if ref_marks:
+ print(f"landmarks reference: waist {ref_marks['waist']:.3f} neck {ref_marks['neck']:.3f}")
+ print(f"landmarks candidate: waist {cand_marks['waist']:.3f} neck {cand_marks['neck']:.3f}")
+ print(f"reference: {args.reference.name}")
+ print(f"candidate: {args.candidate.name}")
+ print(f"\n{'band':>10}{'ref w':>9}{'cand w':>9}{'Δw':>8}{'ref d':>9}{'cand d':>9}{'Δd':>8}"
+ f"{'Δcx':>8}{'Δcz':>8}")
+ for row in rows:
+ print(f"{row['lowPct']:>4}-{row['highPct']:<5}"
+ f"{row['refWidth']:>9.3f}{row['candWidth']:>9.3f}{row['widthDelta']:>+8.3f}"
+ f"{row['refDepth']:>9.3f}{row['candDepth']:>9.3f}{row['depthDelta']:>+8.3f}"
+ f"{row['centroidXDelta']:>+8.3f}{row['centroidZDelta']:>+8.3f}")
+ print(f"\nmean band error = {score:.5f}")
+ worst = sorted(rows, key=lambda r: -(abs(r["widthDelta"]) + abs(r["depthDelta"])))[:5]
+ print("\nworst bands:")
+ for row in worst:
+ print(f" {row['lowPct']:>3}-{row['highPct']:<4} Δw {row['widthDelta']:+.3f} "
+ f"Δd {row['depthDelta']:+.3f} Δcx {row['centroidXDelta']:+.3f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/forge/stage4_review/multi_pass.py b/forge/stage4_review/multi_pass.py
new file mode 100644
index 0000000..edaffa4
--- /dev/null
+++ b/forge/stage4_review/multi_pass.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Manifest helpers for the v2 browser multi-pass evidence contract."""
+
+from __future__ import annotations
+
+import hashlib
+from pathlib import Path
+from typing import Any, Callable
+
+
+PASS_IDS = (
+ "beauty",
+ "alpha-silhouette",
+ "semantic-id",
+ "depth",
+ "normal",
+ "roughness-material-id",
+)
+
+
+def default_pass_records(prefix: str) -> dict[str, dict[str, Any]]:
+ prefix = prefix.rstrip("/")
+ return {
+ pass_id: {"path": f"{prefix}/{pass_id}.png", "status": "pending"}
+ for pass_id in PASS_IDS
+ }
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def record_pass(
+ manifest_path: Path,
+ pass_record: dict[str, Any],
+ image_path: Path,
+ probe: Callable[[Path], dict[str, Any]],
+) -> dict[str, Any]:
+ image_path = image_path.expanduser().resolve()
+ if not image_path.is_file():
+ raise ValueError(f"pass image does not exist: {image_path}")
+ image = probe(image_path)
+ if not image.get("type") or not image.get("width") or not image.get("height"):
+ raise ValueError(f"pass image is not readable: {image_path}")
+ try:
+ relative = image_path.relative_to(manifest_path.parent.resolve()).as_posix()
+ except ValueError:
+ relative = str(image_path)
+ pass_record.update(
+ {
+ "path": relative,
+ "status": "recorded",
+ "image": image,
+ "sha256": _sha256(image_path),
+ }
+ )
+ return pass_record
+
+
+def validate_pass_records(
+ manifest_path: Path,
+ records: Any,
+ probe: Callable[[Path], dict[str, Any]],
+ *,
+ require_complete: bool,
+ label: str,
+) -> list[str]:
+ errors: list[str] = []
+ if not isinstance(records, dict):
+ if require_complete:
+ errors.append(f"{label} pass records are missing")
+ return errors
+ for pass_id in PASS_IDS:
+ record = records.get(pass_id)
+ if not isinstance(record, dict):
+ if require_complete:
+ errors.append(f"{label} pass is missing: {pass_id}")
+ continue
+ if record.get("status") != "recorded":
+ if require_complete:
+ errors.append(f"{label} pass is not recorded: {pass_id}")
+ continue
+ value = record.get("path")
+ if not value:
+ errors.append(f"{label} pass has no path: {pass_id}")
+ continue
+ path_value = Path(value).expanduser()
+ path = path_value if path_value.is_absolute() else manifest_path.parent / path_value
+ if not path.is_file():
+ errors.append(f"{label} pass file is missing: {path}")
+ continue
+ image = probe(path)
+ if not image.get("type") or not image.get("width") or not image.get("height"):
+ errors.append(f"{label} pass is unreadable: {path}")
+ expected_hash = record.get("sha256")
+ if expected_hash and expected_hash != _sha256(path):
+ errors.append(f"{label} pass hash changed: {path}")
+ return errors
diff --git a/forge/stage4_review/pairwise_penetration.py b/forge/stage4_review/pairwise_penetration.py
new file mode 100644
index 0000000..8c9ac5c
--- /dev/null
+++ b/forge/stage4_review/pairwise_penetration.py
@@ -0,0 +1,376 @@
+#!/usr/bin/env python3
+"""Does one part pass through another?
+
+`self_intersection.py` catches a surface folded through ITS OWN volume. It says nothing about two
+separate meshes occupying the same space, and that is a different, equally common defect: an arm
+inside a torso, a staff through a hat, a strap sunk into a shoulder. Each mesh is individually
+flawless, so every per-mesh gate passes, and the model is still broken.
+
+Method: ray parity again, but across meshes. Sample vertices of A, count crossings of B's triangles
+along a fixed direction; odd means the vertex is inside B. As in the sibling module, a grazing hit is
+reported as UNDECIDED rather than rounded into a verdict, and the sampling budget is reported so a
+clean result over a strided sample is never mistaken for a clean result over the whole mesh.
+
+Touching is not penetrating. A hand gripping a staff shares a surface, and a gate that flagged that
+would be useless on exactly the models it is meant to check, so `allowedPairs` exists for parts that
+are supposed to be in contact and `penetrationDepth` distinguishes a skim from a part buried inside
+another.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+MAX_SAMPLED_VERTICES = 2000
+EPSILON = 1e-9
+# Three fixed, mutually non-parallel directions. Deterministic on purpose: a `random` direction makes
+# a gate that disagrees with itself between runs, and an intermittent gate gets switched off.
+_DIRECTIONS = (
+ (0.5773502691896258, 0.5773502691896258, 0.5773502691896258),
+ (-0.8017837257372732, 0.5345224838248488, 0.2672612419124244),
+ (0.2672612419124244, -0.8017837257372732, 0.5345224838248488),
+)
+GRAZING_LIMIT = 1e-7
+
+
+def _triangles(indices: Any) -> list[tuple[int, int, int]]:
+ if indices and isinstance(indices[0], (list, tuple)):
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
+ return [
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
+ for i in range(0, len(indices) - 2, 3)
+ ]
+
+
+def _bounds(vertices: list[list[float]]) -> tuple[list[float], list[float]]:
+ low = [min(v[axis] for v in vertices) for axis in range(3)]
+ high = [max(v[axis] for v in vertices) for axis in range(3)]
+ return low, high
+
+
+def _boxes_overlap(a: tuple[list[float], list[float]], b: tuple[list[float], list[float]]) -> bool:
+ return all(a[0][axis] <= b[1][axis] and b[0][axis] <= a[1][axis] for axis in range(3))
+
+
+GRID_CELLS = 48
+
+
+class _DirectionIndex:
+ """Triangles bucketed by their footprint on the plane perpendicular to one ray direction.
+
+ Without this the test is every sample against every triangle. That is fine on a twelve-triangle
+ fixture and hopeless on a real model: 2000 samples x 8300 triangles x 3 directions is 50 million
+ ray-triangle tests for ONE ordered pair, and an eight-mesh audit has fifty-six of them. Measured
+ on the actual character, the brute-force version did not finish in ten minutes. Because every
+ sample shares the same direction, the projection basis and the buckets are built once per pair and
+ reused, so each sample only tests the triangles whose footprint covers it.
+ """
+
+ def __init__(self, direction, vertices, faces):
+ dx, dy, dz = direction
+ # Any vector not parallel to the direction gives a usable basis; picking the axis the
+ # direction is *least* aligned with keeps the cross product well conditioned.
+ smallest = min(range(3), key=lambda axis: abs(direction[axis]))
+ helper = [0.0, 0.0, 0.0]
+ helper[smallest] = 1.0
+ ux = helper[1] * dz - helper[2] * dy
+ uy = helper[2] * dx - helper[0] * dz
+ uz = helper[0] * dy - helper[1] * dx
+ length = math.sqrt(ux * ux + uy * uy + uz * uz)
+ self.u = (ux / length, uy / length, uz / length)
+ self.v = (
+ dy * self.u[2] - dz * self.u[1],
+ dz * self.u[0] - dx * self.u[2],
+ dx * self.u[1] - dy * self.u[0],
+ )
+ self.faces = faces
+ self.vertices = vertices
+
+ boxes = []
+ min_a = min_b = float("inf")
+ max_a = max_b = float("-inf")
+ for face in faces:
+ aa = [self._project(vertices[i]) for i in face]
+ lo_a = min(p[0] for p in aa)
+ hi_a = max(p[0] for p in aa)
+ lo_b = min(p[1] for p in aa)
+ hi_b = max(p[1] for p in aa)
+ boxes.append((lo_a, hi_a, lo_b, hi_b))
+ min_a, max_a = min(min_a, lo_a), max(max_a, hi_a)
+ min_b, max_b = min(min_b, lo_b), max(max_b, hi_b)
+
+ self.min_a, self.min_b = min_a, min_b
+ self.span_a = max(max_a - min_a, 1e-9)
+ self.span_b = max(max_b - min_b, 1e-9)
+ self.buckets: dict[tuple[int, int], list[int]] = {}
+ for index, (lo_a, hi_a, lo_b, hi_b) in enumerate(boxes):
+ for cell_a in range(self._cell(lo_a, min_a, self.span_a), self._cell(hi_a, min_a, self.span_a) + 1):
+ for cell_b in range(self._cell(lo_b, min_b, self.span_b), self._cell(hi_b, min_b, self.span_b) + 1):
+ self.buckets.setdefault((cell_a, cell_b), []).append(index)
+
+ def _project(self, point) -> tuple[float, float]:
+ return (
+ point[0] * self.u[0] + point[1] * self.u[1] + point[2] * self.u[2],
+ point[0] * self.v[0] + point[1] * self.v[1] + point[2] * self.v[2],
+ )
+
+ @staticmethod
+ def _cell(value: float, low: float, span: float) -> int:
+ # Clamped, never rejected. A point landing one cell past the end -- which is exactly where the
+ # vertex defining the projection's maximum sits -- would otherwise return no candidates and a
+ # confident "outside".
+ return max(0, min(GRID_CELLS - 1, int((value - low) / span * GRID_CELLS)))
+
+ def candidates(self, point) -> list[int]:
+ a, b = self._project(point)
+ return self.buckets.get(
+ (self._cell(a, self.min_a, self.span_a), self._cell(b, self.min_b, self.span_b)), []
+ )
+
+
+def _crossings(
+ origin: tuple[float, float, float],
+ direction: tuple[float, float, float],
+ vertices: list[list[float]],
+ faces: list[tuple[int, int, int]],
+ index: "_DirectionIndex | None" = None,
+) -> tuple[int, bool]:
+ """Möller-Trumbore parity. Returns (crossings, reliable)."""
+ ox, oy, oz = origin
+ dx, dy, dz = direction
+ crossings = 0
+ reliable = True
+ candidate_faces = faces if index is None else [faces[i] for i in index.candidates(origin)]
+ for a, b, c in candidate_faces:
+ p0, p1, p2 = vertices[a], vertices[b], vertices[c]
+ e1 = (p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2])
+ e2 = (p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2])
+ px = dy * e2[2] - dz * e2[1]
+ py = dz * e2[0] - dx * e2[2]
+ pz = dx * e2[1] - dy * e2[0]
+ determinant = e1[0] * px + e1[1] * py + e1[2] * pz
+ if abs(determinant) < GRAZING_LIMIT:
+ # Edge-on: the intersection is numerically meaningless, so the whole ray is untrusted.
+ reliable = False
+ continue
+ inverse = 1.0 / determinant
+ tx, ty, tz = ox - p0[0], oy - p0[1], oz - p0[2]
+ u = (tx * px + ty * py + tz * pz) * inverse
+ if u < -EPSILON or u > 1.0 + EPSILON:
+ continue
+ qx = ty * e1[2] - tz * e1[1]
+ qy = tz * e1[0] - tx * e1[2]
+ qz = tx * e1[1] - ty * e1[0]
+ v = (dx * qx + dy * qy + dz * qz) * inverse
+ if v < -EPSILON or u + v > 1.0 + EPSILON:
+ continue
+ distance = (e2[0] * qx + e2[1] * qy + e2[2] * qz) * inverse
+ if distance <= EPSILON:
+ continue
+ # A hit exactly on a shared edge belongs to two triangles and would be counted twice.
+ if abs(u) < 1e-7 or abs(v) < 1e-7 or abs(u + v - 1.0) < 1e-7:
+ reliable = False
+ crossings += 1
+ return crossings, reliable
+
+
+def build_indices(vertices, faces) -> list[_DirectionIndex]:
+ """One acceleration structure per ray direction, built once and reused across every sample."""
+ return [_DirectionIndex(direction, vertices, faces) for direction in _DIRECTIONS]
+
+
+def point_inside(
+ point: tuple[float, float, float],
+ vertices: list[list[float]],
+ faces: list[tuple[int, int, int]],
+ indices: list[_DirectionIndex] | None = None,
+) -> str:
+ """'inside', 'outside', or 'undecided' by majority over three fixed ray directions."""
+ votes = []
+ for position, direction in enumerate(_DIRECTIONS):
+ crossings, reliable = _crossings(
+ point, direction, vertices, faces, indices[position] if indices else None
+ )
+ if reliable:
+ votes.append(crossings % 2 == 1)
+ if len(votes) < 2:
+ return "undecided"
+ inside_votes = sum(1 for vote in votes if vote)
+ if inside_votes * 2 == len(votes):
+ return "undecided"
+ return "inside" if inside_votes * 2 > len(votes) else "outside"
+
+
+def _sample_points(vertices: list[list[float]], faces: list[tuple[int, int, int]]) -> list[list[float]]:
+ """Vertices, plus edge midpoints and face centroids.
+
+ Vertices alone are not enough, and the failure is not exotic. A bar driven through a block has
+ every one of its corners OUTSIDE the block and every corner of the block outside the bar -- the
+ two surfaces interpenetrate entirely across faces, and a vertex-only test reports a clean pass on
+ a model with a pole through its chest. Midpoints and centroids put samples on the parts of the
+ surface that are actually inside the other mesh.
+
+ This is still SAMPLING, not exact surface intersection: a part thin enough to thread between the
+ samples goes unseen. Detecting that needs an edge-versus-triangle test on every pair of faces,
+ which is a different cost class. The limit is stated in the result rather than left implied.
+ """
+ points = [list(vertex) for vertex in vertices]
+ seen_edges: set[tuple[int, int]] = set()
+ for a, b, c in faces:
+ for u, v in ((a, b), (b, c), (c, a)):
+ key = (u, v) if u < v else (v, u)
+ if key in seen_edges:
+ continue
+ seen_edges.add(key)
+ points.append([(vertices[u][i] + vertices[v][i]) / 2 for i in range(3)])
+ points.append([(vertices[a][i] + vertices[b][i] + vertices[c][i]) / 3 for i in range(3)])
+ return points
+
+
+def analyze_pair(
+ a: dict[str, Any],
+ b: dict[str, Any],
+ max_samples: int = MAX_SAMPLED_VERTICES,
+) -> dict[str, Any]:
+ a_vertices, b_vertices = a["vertices"], b["vertices"]
+ b_faces = _triangles(b["indices"])
+ a_samples = _sample_points(a_vertices, _triangles(a["indices"]))
+ a_box, b_box = _bounds(a_vertices), _bounds(b_vertices)
+ name_a, name_b = str(a.get("name", "a")), str(b.get("name", "b"))
+ if not _boxes_overlap(a_box, b_box):
+ # Cheap rejection, and reported as such: "0 inside" from a test that never ran and "0 inside"
+ # from a test that ran are different claims.
+ return {
+ "a": name_a, "b": name_b, "boundsOverlap": False, "penetrating": False,
+ "insideVertexCount": 0, "undecidedVertexCount": 0,
+ "sampledVertexCount": 0, "totalVertexCount": len(a_samples), "samplingStride": 0,
+ "penetrationDepth": 0.0,
+ }
+
+ b_indices = build_indices(b_vertices, b_faces)
+ stride = max(1, math.ceil(len(a_samples) / max_samples))
+ inside = 0
+ undecided = 0
+ sampled = 0
+ deepest = 0.0
+ worst_points: list[list[float]] = []
+ for index in range(0, len(a_samples), stride):
+ vertex = a_samples[index]
+ sampled += 1
+ verdict = point_inside((vertex[0], vertex[1], vertex[2]), b_vertices, b_faces, b_indices)
+ if verdict == "undecided":
+ undecided += 1
+ continue
+ if verdict != "inside":
+ continue
+ inside += 1
+ # Depth measured to B's bounding box rather than to its surface: a surface distance needs a
+ # full closest-point query per vertex, and the box distance already separates a skimming
+ # contact from a part sitting well inside another, which is the decision being made.
+ depth = min(
+ min(vertex[axis] - b_box[0][axis], b_box[1][axis] - vertex[axis])
+ for axis in range(3)
+ )
+ if depth > deepest:
+ deepest = depth
+ if len(worst_points) < 8:
+ worst_points.append([round(component, 4) for component in vertex])
+
+ return {
+ "a": name_a, "b": name_b, "boundsOverlap": True,
+ "penetrating": inside > 0,
+ "insideVertexCount": inside,
+ "undecidedVertexCount": undecided,
+ "sampledVertexCount": sampled,
+ "totalVertexCount": len(a_samples),
+ "samplingStride": stride,
+ "penetrationDepth": round(deepest, 6),
+ "samplePoints": worst_points,
+ "samplingLimitation": (
+ "samples are vertices, edge midpoints and face centroids; a part thin enough to thread "
+ "between them is not detected, which needs an edge-versus-triangle test"
+ ),
+ }
+
+
+def analyze_meshes(
+ meshes: list[dict[str, Any]],
+ allowed_pairs: list[list[str]] | None = None,
+ max_samples: int = MAX_SAMPLED_VERTICES,
+) -> dict[str, Any]:
+ """Every ordered pair, minus the pairs declared as legitimately in contact."""
+ allowed = {frozenset(pair) for pair in (allowed_pairs or [])}
+ usable = [m for m in meshes if isinstance(m.get("vertices"), list) and m.get("vertices")
+ and isinstance(m.get("indices"), list) and len(m["indices"]) >= 3]
+ skipped = [str(m.get("name", "?")) for m in meshes if m not in usable]
+
+ pairs: list[dict[str, Any]] = []
+ failures: list[str] = []
+ for i, first in enumerate(usable):
+ for second in usable[i + 1:]:
+ names = frozenset((str(first.get("name", "a")), str(second.get("name", "b"))))
+ if names in allowed:
+ continue
+ # Both directions: A's vertices can all sit outside B while B's sit inside A, whenever one
+ # part is much smaller than the other.
+ for source, target in ((first, second), (second, first)):
+ result = analyze_pair(source, target, max_samples)
+ if result["penetrating"]:
+ failures.append(
+ f"{result['a']} penetrates {result['b']}: {result['insideVertexCount']} of "
+ f"{result['sampledVertexCount']} sampled vertices are inside it, depth "
+ f"{result['penetrationDepth']}"
+ )
+ if result["boundsOverlap"]:
+ pairs.append(result)
+
+ return {
+ "pairs": pairs,
+ "failures": failures,
+ "penetrating": bool(failures),
+ "meshCount": len(usable),
+ "skippedMeshes": skipped,
+ "allowedPairs": [sorted(pair) for pair in allowed],
+ "passed": not failures,
+ }
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [f"meshes: {result['meshCount']}, pairs with overlapping bounds: {len(result['pairs'])}"]
+ if result["skippedMeshes"]:
+ lines.append(f"skipped (no usable geometry): {result['skippedMeshes']}")
+ for failure in result["failures"]:
+ lines.append(f" [PENETRATION] {failure}")
+ lines.append("verdict: PASS" if result["passed"] else "verdict: GATE FAILURE")
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Detect one part passing through another.")
+ parser.add_argument("meshes", type=Path)
+ parser.add_argument("--allow", action="append", default=[],
+ help="a pair permitted to touch, as 'nameA,nameB' (repeatable)")
+ parser.add_argument("--max-samples", type=int, default=MAX_SAMPLED_VERTICES)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ payload = json.loads(args.meshes.read_text())
+ meshes = payload["meshes"] if isinstance(payload, dict) and isinstance(payload.get("meshes"), list) else [payload]
+ allowed = [pair.split(",") for pair in args.allow]
+ result = analyze_meshes(meshes, allowed, args.max_samples)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
+ return 0 if result["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/per_feature.py b/forge/stage4_review/per_feature.py
index 857981e..668ce03 100644
--- a/forge/stage4_review/per_feature.py
+++ b/forge/stage4_review/per_feature.py
@@ -59,6 +59,11 @@ def is_gating(target):
def evaluate_features(feature_targets, feature_scores):
"""Evaluate every declared feature independently.
+ SCOPE: this function never opens an image. It gates on a scores dict somebody else produced, so
+ it is only as sharp as the measurement upstream -- and divine_eye.py measures on a 64x64 luma
+ grid, where a few-pixel feature does not exist. The tier machinery here is correct; feeding it
+ feature-scale numbers is the missing half. See grimoire/review/divine_eye_microscope.md.
+
Returns a dict:
{"passed": bool, "action": str,
"features": [{"id","tier","score","threshold",
diff --git a/forge/stage4_review/render_bridge.py b/forge/stage4_review/render_bridge.py
new file mode 100644
index 0000000..09bcc9a
--- /dev/null
+++ b/forge/stage4_review/render_bridge.py
@@ -0,0 +1,556 @@
+#!/usr/bin/env python3
+"""Deterministic manifest and evidence controller for browser Three.js renders.
+
+This module does not render a model. It creates a camera batch, validates saved
+screenshots, records provenance, and delegates deterministic image checks to the
+existing review gates. A browser adapter (Chrome MCP or Playwright) must produce
+the actual Three.js pixels.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+STAGE1 = Path(__file__).resolve().parents[1] / "stage1_intake"
+sys.path.insert(0, str(STAGE1))
+from probe_image import probe # noqa: E402
+from probe_glb import probe_glb # noqa: E402
+
+REVIEW_DIR = Path(__file__).resolve().parent
+sys.path.insert(0, str(REVIEW_DIR))
+from multi_pass import PASS_IDS, default_pass_records, record_pass, validate_pass_records # noqa: E402
+
+
+CAPTURE_PLAN: tuple[dict[str, Any], ...] = (
+ {"id": "hero", "role": "reference-match", "azimuthDegrees": 0, "elevationDegrees": 0},
+ {"id": "orbit-plus35", "role": "orbit", "azimuthDegrees": 35, "elevationDegrees": 0},
+ {"id": "orbit-minus35", "role": "orbit", "azimuthDegrees": -35, "elevationDegrees": 0},
+ {"id": "profile", "role": "orbit", "azimuthDegrees": 78, "elevationDegrees": 0},
+ {"id": "rear", "role": "orbit", "azimuthDegrees": 180, "elevationDegrees": 0},
+ {"id": "head-hero", "role": "head-closeup", "azimuthDegrees": 0, "elevationDegrees": 0},
+ {"id": "head-threequarter", "role": "head-closeup", "azimuthDegrees": 35, "elevationDegrees": 0},
+)
+
+
+def sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def read_manifest(path: Path) -> dict[str, Any]:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(value, dict):
+ raise ValueError("manifest root must be an object")
+ return value
+
+
+def write_manifest(path: Path, manifest: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ temporary.replace(path)
+
+
+def manifest_path(manifest_path_value: Path, value: str) -> Path:
+ candidate = Path(value).expanduser()
+ return candidate if candidate.is_absolute() else (manifest_path_value.parent / candidate).resolve()
+
+
+def portable_path(manifest_path_value: Path, value: Path) -> str:
+ resolved = value.expanduser().resolve()
+ try:
+ return resolved.relative_to(manifest_path_value.parent.resolve()).as_posix()
+ except ValueError:
+ return str(resolved)
+
+
+def now_utc() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def init_manifest(
+ reference: Path | None,
+ runtime_url: str,
+ output: Path,
+ viewport: tuple[int, int],
+ device_pixel_ratio: float,
+ output_dir: str,
+ reference_glb: Path | None = None,
+ reference_browser_url: str | None = None,
+ render_profile: Path | None = None,
+) -> dict[str, Any]:
+ if (reference is None) == (reference_glb is None):
+ raise ValueError("provide exactly one of reference image or reference GLB")
+
+ if reference_glb is not None:
+ reference_glb = reference_glb.expanduser().resolve()
+ reference_probe: dict[str, Any] = probe_glb(reference_glb)
+ if reference_probe.get("referenceReadiness") != "pass":
+ raise ValueError(f"reference GLB is not usable: {reference_glb}")
+ reference_record: dict[str, Any] = {
+ "kind": "glb",
+ "path": portable_path(output, reference_glb),
+ "sha256": reference_probe["sha256"],
+ "probe": reference_probe,
+ "comparisonBasis": "browser-rendered-glb",
+ "renderRequired": True,
+ }
+ if reference_browser_url:
+ reference_record["browserUrl"] = reference_browser_url
+ else:
+ assert reference is not None
+ reference = reference.expanduser().resolve()
+ if not reference.is_file():
+ raise ValueError(f"reference does not exist: {reference}")
+ reference_probe = probe(reference)
+ if not reference_probe.get("type") or not reference_probe.get("width"):
+ raise ValueError(f"reference is not a readable image: {reference}")
+ reference_record = {
+ "kind": "image",
+ "path": portable_path(output, reference),
+ "sha256": sha256(reference),
+ "image": reference_probe,
+ "comparisonBasis": "source-image",
+ "renderRequired": False,
+ }
+
+ captures = []
+ for item in CAPTURE_PLAN:
+ captures.append(
+ {
+ **item,
+ "target": [0, 0, 0],
+ "near": 0.01,
+ "far": 100,
+ "path": f"{output_dir.rstrip('/')}/{item['id']}.png",
+ "status": "pending",
+ "passes": default_pass_records(f"{output_dir.rstrip('/')}/{item['id']}"),
+ }
+ )
+ if reference_record["kind"] == "glb":
+ for item in captures:
+ item["reference"] = {
+ "path": f"reference/{item['id']}.png",
+ "status": "pending",
+ "passes": default_pass_records(f"reference/{item['id']}"),
+ }
+ manifest: dict[str, Any] = {
+ "schemaVersion": 1,
+ "createdAt": now_utc(),
+ "runtime": {
+ "url": runtime_url,
+ "route": runtime_url.split("#", 1)[-1] if "#" in runtime_url else runtime_url,
+ "viewport": list(viewport),
+ "devicePixelRatio": device_pixel_ratio,
+ "renderer": "WebGLRenderer",
+ "threeVersion": "project-pinned",
+ "readySignal": "window.__IMG2THREEJS_READY__",
+ "captureContract": "window.__IMG2THREEJS_CAPTURE__",
+ },
+ "reference": reference_record,
+ "captures": captures,
+ "evidence": {
+ "browser": None,
+ "diagnostics": [],
+ "comparisonSheet": None,
+ },
+ }
+ if render_profile is not None:
+ profile_path = render_profile.expanduser().resolve()
+ if not profile_path.is_file():
+ raise ValueError(f"render profile does not exist: {profile_path}")
+ from validate_render_profile import validate_file # noqa: PLC0415
+
+ profile_validation = validate_file(profile_path)
+ if not profile_validation["passed"]:
+ raise ValueError(f"render profile is invalid: {profile_validation['errors']}")
+ manifest["fidelityTrack"] = "glb-mediated-v2"
+ manifest["renderProfile"] = {
+ "path": portable_path(output, profile_path),
+ "sha256": sha256(profile_path),
+ "schemaVersion": "render-profile.v2",
+ "sharedBy": ["glb-reference", "procedural"],
+ }
+ return manifest
+
+
+def find_capture(manifest: dict[str, Any], capture_id: str) -> dict[str, Any]:
+ for capture in manifest.get("captures", []):
+ if isinstance(capture, dict) and capture.get("id") == capture_id:
+ return capture
+ raise ValueError(f"capture id not found: {capture_id}")
+
+
+def record_capture(
+ manifest_path_value: Path,
+ manifest: dict[str, Any],
+ capture_id: str,
+ screenshot: Path,
+ ready_signal: Any = True,
+ console_errors: list[str] | None = None,
+ browser_snapshot: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ screenshot = screenshot.expanduser().resolve()
+ if not screenshot.is_file():
+ raise ValueError(f"screenshot does not exist: {screenshot}")
+ image = probe(screenshot)
+ if not image.get("type") or not image.get("width") or not image.get("height"):
+ raise ValueError(f"screenshot is not readable: {screenshot}")
+ errors = list(console_errors or [])
+ capture = find_capture(manifest, capture_id)
+ capture["path"] = portable_path(manifest_path_value, screenshot)
+ capture["status"] = "recorded"
+ capture["recordedAt"] = now_utc()
+ capture["readySignal"] = ready_signal
+ capture["screenshotSha256"] = sha256(screenshot)
+ capture["image"] = image
+ capture["consoleErrors"] = errors
+ if browser_snapshot is not None:
+ capture["browserSnapshot"] = browser_snapshot
+ return capture
+
+
+def record_reference_capture(
+ manifest_path_value: Path,
+ manifest: dict[str, Any],
+ capture_id: str,
+ screenshot: Path,
+ ready_signal: Any = True,
+ console_errors: list[str] | None = None,
+) -> dict[str, Any]:
+ """Record a browser screenshot of the GLB reference baseline.
+
+ The GLB itself is never treated as pixel evidence. The reference must first
+ be loaded by the same Three.js route (or an explicit reference mode of it).
+ """
+ reference = manifest.get("reference")
+ if not isinstance(reference, dict) or reference.get("kind") != "glb":
+ raise ValueError("reference captures are only valid for a GLB reference manifest")
+ screenshot = screenshot.expanduser().resolve()
+ if not screenshot.is_file():
+ raise ValueError(f"screenshot does not exist: {screenshot}")
+ image = probe(screenshot)
+ if not image.get("type") or not image.get("width") or not image.get("height"):
+ raise ValueError(f"screenshot is not readable: {screenshot}")
+ capture = find_capture(manifest, capture_id)
+ record = capture.setdefault("reference", {})
+ record.update(
+ {
+ "path": portable_path(manifest_path_value, screenshot),
+ "status": "recorded",
+ "recordedAt": now_utc(),
+ "readySignal": ready_signal,
+ "screenshotSha256": sha256(screenshot),
+ "image": image,
+ "consoleErrors": list(console_errors or []),
+ }
+ )
+ return record
+
+
+def record_capture_pass(
+ manifest_path_value: Path,
+ manifest: dict[str, Any],
+ capture_id: str,
+ pass_id: str,
+ image_path: Path,
+ *,
+ reference: bool = False,
+) -> dict[str, Any]:
+ if pass_id not in PASS_IDS:
+ raise ValueError(f"unknown render pass: {pass_id}")
+ capture = find_capture(manifest, capture_id)
+ target: dict[str, Any]
+ if reference:
+ target = capture.setdefault("reference", {})
+ else:
+ target = capture
+ records = target.setdefault("passes", {})
+ record = records.setdefault(pass_id, {})
+ result = record_pass(manifest_path_value, record, image_path, probe)
+ result["recordedAt"] = now_utc()
+ return result
+
+
+def validate_manifest(path: Path, require_complete: bool = False) -> dict[str, Any]:
+ manifest = read_manifest(path)
+ errors: list[str] = []
+ warnings: list[str] = []
+ if manifest.get("schemaVersion") != 1:
+ errors.append("schemaVersion must be 1")
+ v2 = manifest.get("fidelityTrack") == "glb-mediated-v2"
+ if v2:
+ profile = manifest.get("renderProfile")
+ if not isinstance(profile, dict) or not profile.get("path"):
+ errors.append("GLB-mediated-v2 manifest requires renderProfile.path")
+ else:
+ profile_path = manifest_path(path, str(profile["path"]))
+ if not profile_path.is_file():
+ errors.append(f"render profile is missing: {profile_path}")
+ else:
+ if profile.get("sha256") and profile["sha256"] != sha256(profile_path):
+ errors.append(f"render profile hash changed: {profile_path}")
+ from validate_render_profile import validate_file # noqa: PLC0415
+
+ profile_result = validate_file(profile_path)
+ errors.extend(f"render profile: {error}" for error in profile_result["errors"])
+ warnings.extend(f"render profile: {warning}" for warning in profile_result["warnings"])
+ runtime = manifest.get("runtime")
+ if not isinstance(runtime, dict) or not runtime.get("url"):
+ errors.append("runtime.url is required")
+ reference = manifest.get("reference")
+ if not isinstance(reference, dict) or not reference.get("path") or reference.get("kind") not in {"image", "glb"}:
+ errors.append("reference.path is required")
+ else:
+ reference_path = manifest_path(path, str(reference["path"]))
+ if not reference_path.is_file():
+ errors.append(f"reference file is missing: {reference_path}")
+ elif reference.get("sha256") and reference["sha256"] != sha256(reference_path):
+ errors.append(f"reference hash changed: {reference_path}")
+ if reference.get("kind") == "glb":
+ try:
+ current_probe = probe_glb(reference_path)
+ if current_probe.get("referenceReadiness") != "pass":
+ errors.append("reference GLB is no longer usable")
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"reference GLB probe failed: {exc}")
+
+ captures = manifest.get("captures")
+ if not isinstance(captures, list) or not captures:
+ errors.append("captures must be a non-empty list")
+ captures = []
+ ids: set[str] = set()
+ recorded = 0
+ for capture in captures:
+ if not isinstance(capture, dict) or not capture.get("id"):
+ errors.append("every capture needs an id")
+ continue
+ capture_id = str(capture["id"])
+ if capture_id in ids:
+ errors.append(f"duplicate capture id: {capture_id}")
+ ids.add(capture_id)
+ if reference.get("kind") == "glb":
+ baseline = capture.get("reference")
+ if not isinstance(baseline, dict) or baseline.get("status") != "recorded":
+ if require_complete:
+ errors.append(f"GLB reference baseline is not recorded: {capture_id}")
+ elif baseline.get("path"):
+ baseline_path = manifest_path(path, str(baseline["path"]))
+ if not baseline_path.is_file():
+ errors.append(f"GLB reference baseline is missing: {baseline_path}")
+ elif baseline.get("screenshotSha256") and baseline["screenshotSha256"] != sha256(baseline_path):
+ errors.append(f"GLB reference baseline hash changed: {baseline_path}")
+ if baseline.get("consoleErrors"):
+ errors.append(f"browser console errors recorded for GLB baseline: {capture_id}")
+ errors.extend(
+ validate_pass_records(
+ path,
+ baseline.get("passes"),
+ probe,
+ require_complete=require_complete and v2,
+ label=f"GLB reference {capture_id}",
+ )
+ )
+ if capture.get("status") != "recorded":
+ if require_complete:
+ errors.append(f"capture is not recorded: {capture_id}")
+ continue
+ recorded += 1
+ screenshot_value = capture.get("path")
+ if not screenshot_value:
+ errors.append(f"recorded capture has no path: {capture_id}")
+ continue
+ screenshot = manifest_path(path, str(screenshot_value))
+ if not screenshot.is_file():
+ errors.append(f"screenshot file is missing: {screenshot}")
+ continue
+ image = probe(screenshot)
+ if not image.get("type") or not image.get("width"):
+ errors.append(f"screenshot is unreadable: {screenshot}")
+ if capture.get("screenshotSha256") and capture["screenshotSha256"] != sha256(screenshot):
+ errors.append(f"screenshot hash changed: {screenshot}")
+ if capture.get("consoleErrors"):
+ errors.append(f"browser console errors recorded for: {capture_id}")
+ errors.extend(
+ validate_pass_records(
+ path,
+ capture.get("passes"),
+ probe,
+ require_complete=require_complete and v2,
+ label=f"procedural {capture_id}",
+ )
+ )
+ if recorded == 0:
+ warnings.append("no browser screenshots recorded yet")
+ result = {
+ "passed": not errors,
+ "errors": errors,
+ "warnings": warnings,
+ "recordedCaptures": recorded,
+ "fidelityTrack": manifest.get("fidelityTrack", "legacy"),
+ "requiredPasses": list(PASS_IDS) if v2 else [],
+ }
+ return result
+
+
+def diagnose(path: Path, output: Path) -> dict[str, Any]:
+ manifest = read_manifest(path)
+ hero = find_capture(manifest, "hero")
+ reference_record = manifest.get("reference", {})
+ reference_path = manifest_path(path, str(reference_record["path"]))
+ hero_path = manifest_path(path, str(hero["path"]))
+ if hero.get("status") != "recorded":
+ raise ValueError("hero capture must be recorded before diagnostics")
+
+ review_dir = Path(__file__).resolve().parent
+ sys.path.insert(0, str(review_dir))
+ from diagnose_render import run_tier1 # noqa: PLC0415
+ from diagnose_render_multi_angle import analyze_angles # noqa: PLC0415
+
+ orbit_paths = []
+ for capture in manifest.get("captures", []):
+ if isinstance(capture, dict) and capture.get("role") == "orbit" and capture.get("status") == "recorded":
+ orbit_paths.append(manifest_path(path, str(capture["path"])))
+ if reference_record.get("kind") == "glb":
+ hero_reference = hero.get("reference")
+ if not isinstance(hero_reference, dict) or hero_reference.get("status") != "recorded":
+ raise ValueError("GLB reference hero baseline must be recorded before diagnostics")
+ comparison_reference_path = manifest_path(path, str(hero_reference["path"]))
+ else:
+ comparison_reference_path = reference_path
+ result = {
+ "manifest": str(path.resolve()),
+ "reference": str(reference_path),
+ "comparisonReference": str(comparison_reference_path),
+ "comparisonBasis": reference_record.get("comparisonBasis"),
+ "hero": run_tier1(comparison_reference_path, hero_path),
+ "multiAngle": analyze_angles(hero_path, orbit_paths),
+ "generatedAt": now_utc(),
+ }
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ evidence = manifest.setdefault("evidence", {})
+ evidence.setdefault("diagnostics", []).append(portable_path(path, output))
+ write_manifest(path, manifest)
+ return result
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+
+ init = commands.add_parser("init", help="create a deterministic character camera-batch manifest")
+ reference_group = init.add_mutually_exclusive_group(required=True)
+ reference_group.add_argument("--reference", type=Path, help="source image reference")
+ reference_group.add_argument("--reference-glb", type=Path, help="GLB reference mesh; it must be browser-rendered before comparison")
+ init.add_argument("--runtime-url", required=True)
+ init.add_argument("--out", type=Path, required=True)
+ init.add_argument("--viewport", default="620x1000", help="CSS viewport, e.g. 620x1000")
+ init.add_argument("--device-pixel-ratio", type=float, default=1.0)
+ init.add_argument("--output-dir", default="captures")
+ init.add_argument("--reference-browser-url", help="browser-visible URL/path for the GLB reference mode")
+ init.add_argument("--render-profile", type=Path, help="validated render-profile.v2 shared by GLB and procedural routes")
+
+ record = commands.add_parser("record", help="record a browser-produced screenshot into the manifest")
+ record.add_argument("--manifest", type=Path, required=True)
+ record.add_argument("--capture-id", required=True)
+ record.add_argument("--screenshot", type=Path, required=True)
+ record.add_argument("--ready-signal", default=True)
+ record.add_argument("--console-error", action="append", default=[])
+
+ record_reference = commands.add_parser("record-reference", help="record a browser-rendered GLB baseline screenshot")
+ record_reference.add_argument("--manifest", type=Path, required=True)
+ record_reference.add_argument("--capture-id", required=True)
+ record_reference.add_argument("--screenshot", type=Path, required=True)
+ record_reference.add_argument("--ready-signal", default=True)
+ record_reference.add_argument("--console-error", action="append", default=[])
+
+ record_pass_parser = commands.add_parser("record-pass", help="record one browser-produced diagnostic pass")
+ record_pass_parser.add_argument("--manifest", type=Path, required=True)
+ record_pass_parser.add_argument("--capture-id", required=True)
+ record_pass_parser.add_argument("--pass-id", choices=PASS_IDS, required=True)
+ record_pass_parser.add_argument("--image", type=Path, required=True)
+ record_pass_parser.add_argument("--reference", action="store_true", help="record the GLB baseline pass")
+
+ validate = commands.add_parser("validate", help="validate files and hashes in a manifest")
+ validate.add_argument("--manifest", type=Path, required=True)
+ validate.add_argument("--require-complete", action="store_true")
+
+ diagnostic = commands.add_parser("diagnose", help="run Tier-1 and multi-angle diagnostics")
+ diagnostic.add_argument("--manifest", type=Path, required=True)
+ diagnostic.add_argument("--out", type=Path, required=True)
+
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "init":
+ try:
+ width_text, height_text = args.viewport.lower().split("x", 1)
+ viewport = (int(width_text), int(height_text))
+ except ValueError as exc:
+ raise ValueError("--viewport must look like WIDTHxHEIGHT") from exc
+ output = args.out.expanduser().resolve()
+ write_manifest(
+ output,
+ init_manifest(
+ args.reference,
+ args.runtime_url,
+ output,
+ viewport,
+ args.device_pixel_ratio,
+ args.output_dir,
+ reference_glb=args.reference_glb,
+ reference_browser_url=args.reference_browser_url,
+ render_profile=args.render_profile,
+ ),
+ )
+ print(json.dumps({"manifest": str(output), "captures": len(CAPTURE_PLAN)}, indent=2))
+ return 0
+ manifest_path_value = args.manifest.expanduser().resolve()
+ manifest = read_manifest(manifest_path_value)
+ if args.command == "record":
+ record_capture(manifest_path_value, manifest, args.capture_id, Path(args.screenshot), args.ready_signal, args.console_error)
+ write_manifest(manifest_path_value, manifest)
+ print(json.dumps(find_capture(manifest, args.capture_id), indent=2, ensure_ascii=False))
+ return 0
+ if args.command == "record-reference":
+ record_reference_capture(manifest_path_value, manifest, args.capture_id, Path(args.screenshot), args.ready_signal, args.console_error)
+ write_manifest(manifest_path_value, manifest)
+ print(json.dumps(find_capture(manifest, args.capture_id).get("reference"), indent=2, ensure_ascii=False))
+ return 0
+ if args.command == "record-pass":
+ result = record_capture_pass(
+ manifest_path_value,
+ manifest,
+ args.capture_id,
+ args.pass_id,
+ args.image,
+ reference=args.reference,
+ )
+ write_manifest(manifest_path_value, manifest)
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0
+ if args.command == "validate":
+ result = validate_manifest(manifest_path_value, args.require_complete)
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["passed"] else 1
+ if args.command == "diagnose":
+ result = diagnose(manifest_path_value, args.out.expanduser().resolve())
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["hero"]["passed"] and not result["multiAngle"]["degenerate"] else 1
+ raise ValueError(f"unknown command: {args.command}")
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/self_intersection.py b/forge/stage4_review/self_intersection.py
new file mode 100644
index 0000000..d0eecfb
--- /dev/null
+++ b/forge/stage4_review/self_intersection.py
@@ -0,0 +1,592 @@
+#!/usr/bin/env python3
+"""Detect a surface that has folded through its own volume, on a mesh whose topology is valid.
+
+`geometry_integrity.mesh_edge_counts` counts `boundaryEdges` (an edge used by one triangle) and
+`nonManifoldEdges` (an edge used by more than two). Those are the only geometry facts any gate in
+this repository checks, and they are both topological. A real production defect walked straight
+through them: a character's eye-socket recess was pushed deeper than the skull's local half-depth,
+so the front surface passed THROUGH the back of the skull and emerged out the occiput. From behind
+there was a clean hole through the head. The mesh was still perfectly closed -- boundaryEdges 0,
+nonManifoldEdges 0 -- because pushing existing vertices around changes no connectivity at all. Every
+existing gate passed it.
+
+Self-intersection is a GEOMETRIC defect on a TOPOLOGICALLY VALID mesh. Edge counts cannot see it,
+by construction. This module is the check that can.
+
+Method: ray parity. Take a point on the surface, step a small epsilon along its outward direction,
+and ask whether that point -- which by definition should be just OUTSIDE the object -- is in fact
+inside the object's own volume. On a closed surface the answer is decided by counting how many of
+the mesh's own triangles a ray from that point crosses: odd means inside. A point that is supposed
+to be outside its own surface but measures inside can only mean the surface folded through itself
+there.
+
+Everything here is deterministic. No `random`, no sampling jitter, no wall-clock or hash-order
+dependence: the same mesh yields the same verdict and the same reported positions every run, which
+is what makes a gate's output reviewable.
+
+Pure Python 3.10+ stdlib. No numpy, no pip installs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from math import sqrt
+from pathlib import Path
+from typing import Any
+
+# A gate that quietly inspects a tenth of a mesh and then reports "clean" is worse than no gate, so
+# this budget is a cap on WORK, never on what the result claims: every result carries
+# sampledVertexCount / totalVertexCount / samplingStride so the coverage is on the face of it.
+MAX_SAMPLED_VERTICES = 4000
+
+# The offset distance is a fraction of the mesh's bounding-box diagonal rather than an absolute
+# number, because an absolute epsilon is wrong at every scale but one: 0.001 units is a huge step
+# across a 0.01-wide gem and invisible on a 1000-unit terrain. Tied to the diagonal it means the
+# same thing on both. 1e-3 of the diagonal clears floating-point noise on the surface the point came
+# from while staying far below any modelled feature.
+EPSILON_BBOX_FRACTION = 1e-3
+
+# Hits below this |dot(ray direction, face normal)| are edge-on: the intersection maths is dividing
+# by a near-zero determinant and the answer is numerically meaningless. Such a sample is reported
+# undecided rather than guessed at.
+GRAZING_COS_THRESHOLD = 1e-4
+
+# Same idea one step earlier: if the ray direction is this close to tangent to the surface AT the
+# sample, the ray skims its own neighbourhood and the parity it returns is not trustworthy.
+TANGENT_COS_THRESHOLD = 1e-3
+
+# A hit this close to a triangle's edge is shared with the neighbouring triangle, so it is either
+# double-counted or missed depending on rounding. Deliberately tight -- it should fire on genuine
+# degeneracy, not on ordinary hits.
+BARYCENTRIC_EDGE_TOLERANCE = 1e-9
+
+# Fixed, mutually non-parallel, and deliberately not axis-aligned: axis-aligned rays lie exactly in
+# the plane of the axis-aligned quads that box-derived geometry is full of, which is the single most
+# common way a parity count goes wrong. Three directions give a majority; one bad ray cannot decide
+# a sample on its own.
+_RAW_RAY_DIRECTIONS: tuple[tuple[float, float, float], ...] = (
+ (1.0, 0.37, 0.19),
+ (0.23, 1.0, -0.41),
+ (-0.47, 0.29, 1.0),
+)
+
+WORST_REGION_LIMIT = 8
+
+# Grid resolution per axis. Above this the bucket dictionary costs more to build than the triangle
+# tests it saves.
+GRID_MAX_RESOLUTION = 256
+
+# A triangle whose footprint covers more cells than this is filed once in an "everywhere" list and
+# tested against every sample, instead of being copied into thousands of buckets.
+GRID_OVERSIZED_CELL_LIMIT = 1024
+
+# Vertices are welded by rounded position at this precision, matching `geometry_integrity`'s own
+# vertex identity, so that seam-duplicated vertices sharing a position are treated as one point.
+WELD_PRECISION = 6
+
+Vector3 = tuple[float, float, float]
+
+
+def _normalize(vector: Vector3) -> Vector3 | None:
+ length = sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2])
+ if length <= 1e-15:
+ return None
+ return (vector[0] / length, vector[1] / length, vector[2] / length)
+
+
+RAY_DIRECTIONS: tuple[Vector3, ...] = tuple(
+ direction for direction in (_normalize(raw) for raw in _RAW_RAY_DIRECTIONS) if direction is not None
+)
+
+
+def _as_point(value: Any) -> Vector3:
+ if not isinstance(value, (list, tuple)) or len(value) < 3:
+ raise ValueError("vertices must contain 3D positions")
+ return (float(value[0]), float(value[1]), float(value[2]))
+
+
+def _triangles(indices: Any) -> list[tuple[int, int, int]]:
+ """Accept both index encodings `geometry_integrity` accepts: flat, or grouped in threes."""
+ if not isinstance(indices, list) or not indices:
+ raise ValueError("indices must be a non-empty array")
+ if isinstance(indices[0], (list, tuple)):
+ groups = indices
+ else:
+ if len(indices) % 3 != 0:
+ raise ValueError("flat triangle indices must be a multiple of three")
+ groups = [indices[i:i + 3] for i in range(0, len(indices), 3)]
+ triangles: list[tuple[int, int, int]] = []
+ for group in groups:
+ if not isinstance(group, (list, tuple)) or len(group) != 3:
+ raise ValueError("triangle indices must contain groups of three")
+ triangles.append((int(group[0]), int(group[1]), int(group[2])))
+ return triangles
+
+
+class _DirectionGrid:
+ """Triangles bucketed by their footprint in the plane perpendicular to one ray direction.
+
+ Testing every sample against every triangle is ~1.5e9 operations on a 30k-vertex / 50k-triangle
+ mesh, which is not a check anyone will run. All rays of a given pass share one direction, so the
+ problem collapses to two dimensions: project every triangle onto the plane perpendicular to that
+ direction, bucket it by the cells its 2D bounding box covers, and a sample only ever tests the
+ triangles filed in its own cell. The grid is built once per direction and reused for every
+ sample, so the build cost is amortised across the whole mesh.
+ """
+
+ def __init__(self, direction: Vector3, vertices: list[Vector3], triangles: list[tuple[int, int, int]]) -> None:
+ helper: Vector3 = (0.0, 0.0, 1.0) if abs(direction[2]) < 0.9 else (1.0, 0.0, 0.0)
+ axis_u = _normalize((
+ helper[1] * direction[2] - helper[2] * direction[1],
+ helper[2] * direction[0] - helper[0] * direction[2],
+ helper[0] * direction[1] - helper[1] * direction[0],
+ ))
+ if axis_u is None: # unreachable for a unit direction, but a None basis would be silent nonsense
+ raise ValueError("cannot build a basis for the ray direction")
+ axis_v = (
+ direction[1] * axis_u[2] - direction[2] * axis_u[1],
+ direction[2] * axis_u[0] - direction[0] * axis_u[2],
+ direction[0] * axis_u[1] - direction[1] * axis_u[0],
+ )
+ self._u = axis_u
+ self._v = axis_v
+ self.oversized: list[int] = []
+ self._cells: dict[tuple[int, int], list[int]] = {}
+
+ ux, uy, uz = axis_u
+ vx, vy, vz = axis_v
+ boxes: list[tuple[float, float, float, float]] = []
+ min_u = min_v = float("inf")
+ max_u = max_v = float("-inf")
+ for a, b, c in triangles:
+ pa, pb, pc = vertices[a], vertices[b], vertices[c]
+ au = pa[0] * ux + pa[1] * uy + pa[2] * uz
+ bu = pb[0] * ux + pb[1] * uy + pb[2] * uz
+ cu = pc[0] * ux + pc[1] * uy + pc[2] * uz
+ av = pa[0] * vx + pa[1] * vy + pa[2] * vz
+ bv = pb[0] * vx + pb[1] * vy + pb[2] * vz
+ cv = pc[0] * vx + pc[1] * vy + pc[2] * vz
+ lo_u, hi_u = min(au, bu, cu), max(au, bu, cu)
+ lo_v, hi_v = min(av, bv, cv), max(av, bv, cv)
+ boxes.append((lo_u, lo_v, hi_u, hi_v))
+ min_u = lo_u if lo_u < min_u else min_u
+ max_u = hi_u if hi_u > max_u else max_u
+ min_v = lo_v if lo_v < min_v else min_v
+ max_v = hi_v if hi_v > max_v else max_v
+
+ resolution = max(1, min(GRID_MAX_RESOLUTION, int(sqrt(len(triangles))) or 1))
+ span_u = max_u - min_u
+ span_v = max_v - min_v
+ self._resolution = resolution
+ self._min_u = min_u
+ self._min_v = min_v
+ # A zero span means the whole mesh projects to a line or a point along that axis; one cell
+ # wide is then the correct answer rather than a division by zero.
+ self._cell_u = span_u / resolution if span_u > 0.0 else 1.0
+ self._cell_v = span_v / resolution if span_v > 0.0 else 1.0
+
+ cells = self._cells
+ for index, (lo_u, lo_v, hi_u, hi_v) in enumerate(boxes):
+ cu0 = self._cell_index(lo_u, self._min_u, self._cell_u)
+ cu1 = self._cell_index(hi_u, self._min_u, self._cell_u)
+ cv0 = self._cell_index(lo_v, self._min_v, self._cell_v)
+ cv1 = self._cell_index(hi_v, self._min_v, self._cell_v)
+ if (cu1 - cu0 + 1) * (cv1 - cv0 + 1) > GRID_OVERSIZED_CELL_LIMIT:
+ self.oversized.append(index)
+ continue
+ for cu in range(cu0, cu1 + 1):
+ for cv in range(cv0, cv1 + 1):
+ cells.setdefault((cu, cv), []).append(index)
+
+ def _cell_index(self, value: float, origin: float, size: float) -> int:
+ cell = int((value - origin) / size)
+ if cell < 0:
+ return 0
+ if cell >= self._resolution:
+ return self._resolution - 1
+ return cell
+
+ def candidates(self, point: Vector3) -> list[int]:
+ """Triangles whose footprint covers this point's cell. Everything else cannot be hit."""
+ ux, uy, uz = self._u
+ vx, vy, vz = self._v
+ pu = point[0] * ux + point[1] * uy + point[2] * uz
+ pv = point[0] * vx + point[1] * vy + point[2] * vz
+ # Clamped exactly as insertion clamps, and for the same reason. A sample projecting onto the
+ # grid's outer edge -- the vertex that defines the maximum, plus its epsilon offset -- lands
+ # one cell past the end; treating that as "off the grid, nothing to test" silently drops
+ # every triangle in the boundary cell and returns a confident "outside". Clamping costs a
+ # few extra triangle tests for points that really are past the footprint, which is the right
+ # side to be wrong on.
+ cu = self._cell_index(pu, self._min_u, self._cell_u)
+ cv = self._cell_index(pv, self._min_v, self._cell_v)
+ cell = self._cells.get((cu, cv))
+ if cell is None:
+ return self.oversized
+ if not self.oversized:
+ return cell
+ return cell + self.oversized
+
+
+def _count_crossings(
+ origin: Vector3,
+ direction: Vector3,
+ grid: _DirectionGrid,
+ prepared: list[tuple[float, ...]],
+ excluded: set[int],
+ t_min: float,
+) -> tuple[int, bool]:
+ """Möller-Trumbore parity count. Returns (crossings, reliable).
+
+ `reliable` goes false the moment a candidate triangle is near enough to edge-on that the
+ determinant cannot be trusted, or a hit lands on a triangle edge where it belongs equally to two
+ triangles. Those cases are handed back to the caller as undecided; they are never rounded into a
+ verdict.
+ """
+ ox, oy, oz = origin
+ dx, dy, dz = direction
+ crossings = 0
+ for index in grid.candidates(origin):
+ if index in excluded:
+ continue
+ (ax, ay, az, e1x, e1y, e1z, e2x, e2y, e2z, normal_length) = prepared[index]
+ px = dy * e2z - dz * e2y
+ py = dz * e2x - dx * e2z
+ pz = dx * e2y - dy * e2x
+ det = e1x * px + e1y * py + e1z * pz
+ # det == dot(direction, e1 x e2), so |det| / |e1 x e2| is exactly the cosine between the ray
+ # and the face normal -- the edge-on test, for free, with no square root.
+ limit = GRAZING_COS_THRESHOLD * normal_length
+ if -limit < det < limit:
+ return 0, False
+ inv_det = 1.0 / det
+ tx = ox - ax
+ ty = oy - ay
+ tz = oz - az
+ u = (tx * px + ty * py + tz * pz) * inv_det
+ if u < -BARYCENTRIC_EDGE_TOLERANCE or u > 1.0 + BARYCENTRIC_EDGE_TOLERANCE:
+ continue
+ qx = ty * e1z - tz * e1y
+ qy = tz * e1x - tx * e1z
+ qz = tx * e1y - ty * e1x
+ v = (dx * qx + dy * qy + dz * qz) * inv_det
+ if v < -BARYCENTRIC_EDGE_TOLERANCE or u + v > 1.0 + BARYCENTRIC_EDGE_TOLERANCE:
+ continue
+ t = (e2x * qx + e2y * qy + e2z * qz) * inv_det
+ if t < t_min:
+ continue
+ if (
+ u < BARYCENTRIC_EDGE_TOLERANCE
+ or v < BARYCENTRIC_EDGE_TOLERANCE
+ or u + v > 1.0 - BARYCENTRIC_EDGE_TOLERANCE
+ ):
+ return 0, False
+ crossings += 1
+ return crossings, True
+
+
+def _error_result(name: str, message: str, total_vertices: int = 0) -> dict[str, Any]:
+ """Degenerate input is reported, not raised: one broken mesh must not abort a whole batch."""
+ return {
+ "name": name,
+ "analyzed": False,
+ "error": message,
+ "selfIntersecting": False,
+ "insideVertexCount": 0,
+ "undecidedVertexCount": 0,
+ "outsideVertexCount": 0,
+ "sampledVertexCount": 0,
+ "totalVertexCount": total_vertices,
+ "samplingStride": 0,
+ "triangleCount": 0,
+ "degenerateTriangleCount": 0,
+ "worstRegions": [],
+ "normalSource": None,
+ "normalFallbackCount": 0,
+ "epsilon": None,
+ }
+
+
+def analyze_mesh(
+ mesh: dict[str, Any],
+ *,
+ max_samples: int = MAX_SAMPLED_VERTICES,
+ epsilon: float | None = None,
+) -> dict[str, Any]:
+ """Report whether a mesh's surface passes through its own volume.
+
+ `mesh` takes the same shape `geometry_integrity` uses:
+ `{"vertices": [[x, y, z], ...], "indices": [...] or [[a, b, c], ...],
+ "normals": [[x, y, z], ...] (optional), "name": str (optional)}`.
+
+ `epsilon` is the distance the sample point is stepped along its outward direction. It defaults
+ to `EPSILON_BBOX_FRACTION` of the bounding-box diagonal so it scales with the model instead of
+ being an absolute number that is correct at exactly one scale.
+ """
+ name = str(mesh.get("name") or mesh.get("id") or "mesh")
+ raw_vertices = mesh.get("vertices")
+ if not isinstance(raw_vertices, list) or not raw_vertices:
+ return _error_result(name, "mesh has no vertices")
+ try:
+ vertices = [_as_point(vertex) for vertex in raw_vertices]
+ except (TypeError, ValueError) as exc:
+ return _error_result(name, f"invalid vertex data: {exc}", len(raw_vertices))
+ try:
+ triangles = _triangles(mesh.get("indices"))
+ except (TypeError, ValueError) as exc:
+ return _error_result(name, str(exc), len(vertices))
+ vertex_count = len(vertices)
+ if any(index < 0 or index >= vertex_count for triangle in triangles for index in triangle):
+ return _error_result(name, "triangle index out of range", vertex_count)
+
+ lo = [min(vertex[axis] for vertex in vertices) for axis in range(3)]
+ hi = [max(vertex[axis] for vertex in vertices) for axis in range(3)]
+ diagonal = sqrt(sum((hi[axis] - lo[axis]) ** 2 for axis in range(3)))
+ if diagonal <= 0.0:
+ return _error_result(name, "mesh has zero extent", vertex_count)
+ offset = float(epsilon) if epsilon is not None else EPSILON_BBOX_FRACTION * diagonal
+ if offset <= 0.0:
+ return _error_result(name, "epsilon must be positive", vertex_count)
+ # Hits closer than this are the surface the sample point is standing on, reached through
+ # floating-point noise rather than through a real second surface.
+ t_min = offset * 1e-3
+
+ prepared: list[tuple[float, ...]] = []
+ live: list[tuple[int, int, int]] = []
+ degenerate = 0
+ for a, b, c in triangles:
+ pa, pb, pc = vertices[a], vertices[b], vertices[c]
+ e1 = (pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2])
+ e2 = (pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])
+ cross = (
+ e1[1] * e2[2] - e1[2] * e2[1],
+ e1[2] * e2[0] - e1[0] * e2[2],
+ e1[0] * e2[1] - e1[1] * e2[0],
+ )
+ normal_length = sqrt(cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2])
+ if normal_length <= 0.0:
+ # A zero-area triangle bounds no volume and its plane is undefined; counting it would
+ # only corrupt the parity.
+ degenerate += 1
+ continue
+ prepared.append((pa[0], pa[1], pa[2], *e1, *e2, normal_length))
+ live.append((a, b, c))
+ if not live:
+ return _error_result(name, "mesh has no non-degenerate triangles", vertex_count)
+
+ # Fixed stride, never random: the same mesh must produce the same sample set every run.
+ stride = max(1, -(-vertex_count // max(1, int(max_samples))))
+ sampled = list(range(0, vertex_count, stride))
+
+ normals = mesh.get("normals")
+ use_supplied_normals = isinstance(normals, list) and len(normals) == vertex_count
+ normal_source = "vertexNormals" if use_supplied_normals else "centroid"
+ centroid = (
+ sum(vertex[0] for vertex in vertices) / vertex_count,
+ sum(vertex[1] for vertex in vertices) / vertex_count,
+ sum(vertex[2] for vertex in vertices) / vertex_count,
+ )
+
+ # Weld by rounded position rather than by index so that a seam-duplicated vertex sharing a
+ # position still masks the triangles that meet there. Without this, the surface the sample sits
+ # on gets counted as a crossing and every seam vertex reads as a false positive.
+ keys = [tuple(round(value, WELD_PRECISION) for value in vertex) for vertex in vertices]
+ sampled_keys = {keys[index] for index in sampled}
+ incident: dict[tuple[float, ...], set[int]] = {key: set() for key in sampled_keys}
+ for triangle_index, triangle in enumerate(live):
+ for corner in triangle:
+ bucket = incident.get(keys[corner])
+ if bucket is not None:
+ bucket.add(triangle_index)
+
+ grids = [_DirectionGrid(direction, vertices, live) for direction in RAY_DIRECTIONS]
+
+ inside_indices: list[int] = []
+ undecided = 0
+ normal_fallbacks = 0
+ for vertex_index in sampled:
+ vertex = vertices[vertex_index]
+ outward: Vector3 | None = None
+ if use_supplied_normals:
+ try:
+ outward = _normalize(_as_point(normals[vertex_index]))
+ except (TypeError, ValueError):
+ outward = None
+ if outward is None:
+ if use_supplied_normals:
+ # A zero-length or malformed normal on one vertex is not a reason to abandon the
+ # good normals on every other vertex; fall back for this vertex and say how often.
+ normal_fallbacks += 1
+ outward = _normalize((
+ vertex[0] - centroid[0],
+ vertex[1] - centroid[1],
+ vertex[2] - centroid[2],
+ ))
+ if outward is None:
+ # A vertex sitting exactly on the centroid has no outward direction to step along.
+ undecided += 1
+ continue
+ origin = (
+ vertex[0] + outward[0] * offset,
+ vertex[1] + outward[1] * offset,
+ vertex[2] + outward[2] * offset,
+ )
+ excluded = incident[keys[vertex_index]]
+ votes: list[bool] = []
+ reliable = True
+ for direction, grid in zip(RAY_DIRECTIONS, grids):
+ alignment = direction[0] * outward[0] + direction[1] * outward[1] + direction[2] * outward[2]
+ if -TANGENT_COS_THRESHOLD < alignment < TANGENT_COS_THRESHOLD:
+ reliable = False
+ break
+ # Cast into the outward hemisphere. An inward ray from a point that is legitimately
+ # just outside the surface re-crosses that same surface immediately, on triangles this
+ # pass has masked out, and the missing crossing flips the parity to a false positive.
+ ray = direction if alignment > 0.0 else (-direction[0], -direction[1], -direction[2])
+ crossings, ok = _count_crossings(origin, ray, grid, prepared, excluded, t_min)
+ if not ok:
+ reliable = False
+ break
+ votes.append(crossings % 2 == 1)
+ if not reliable:
+ undecided += 1
+ continue
+ inside_votes = sum(votes)
+ if inside_votes * 2 == len(votes):
+ # A tie has no majority, so there is no verdict to report.
+ undecided += 1
+ elif inside_votes * 2 > len(votes):
+ inside_indices.append(vertex_index)
+
+ # Spread the reported positions across the offending set instead of returning the first eight,
+ # which on a large defect would all come from one corner of one region. There is no severity
+ # ranking to apply to a boolean inside/outside verdict, so these are representative locations a
+ # human can navigate to, not a ranking.
+ region_stride = max(1, len(inside_indices) // WORST_REGION_LIMIT)
+ worst = [
+ {"vertexIndex": index, "position": list(vertices[index])}
+ for index in inside_indices[::region_stride][:WORST_REGION_LIMIT]
+ ]
+
+ return {
+ "name": name,
+ "analyzed": True,
+ "error": None,
+ "selfIntersecting": bool(inside_indices),
+ "insideVertexCount": len(inside_indices),
+ "undecidedVertexCount": undecided,
+ "outsideVertexCount": len(sampled) - len(inside_indices) - undecided,
+ "sampledVertexCount": len(sampled),
+ "totalVertexCount": vertex_count,
+ "samplingStride": stride,
+ "triangleCount": len(live),
+ "degenerateTriangleCount": degenerate,
+ "worstRegions": worst,
+ "normalSource": normal_source,
+ "normalFallbackCount": normal_fallbacks,
+ "epsilon": offset,
+ "rayDirectionCount": len(RAY_DIRECTIONS),
+ }
+
+
+def analyze_meshes(
+ meshes: list[dict[str, Any]],
+ *,
+ max_samples: int = MAX_SAMPLED_VERTICES,
+ epsilon: float | None = None,
+) -> dict[str, Any]:
+ """Run `analyze_mesh` over a list of meshes and aggregate the verdicts."""
+ reports: list[dict[str, Any]] = []
+ errors: list[str] = []
+ for index, mesh in enumerate(meshes):
+ if not isinstance(mesh, dict):
+ report = _error_result(f"mesh-{index}", "mesh entry is not an object")
+ else:
+ report = analyze_mesh(mesh, max_samples=max_samples, epsilon=epsilon)
+ if report["error"]:
+ errors.append(f"{report['name']}: {report['error']}")
+ reports.append(report)
+ return {
+ "selfIntersecting": any(report["selfIntersecting"] for report in reports),
+ "meshCount": len(reports),
+ "insideVertexCount": sum(report["insideVertexCount"] for report in reports),
+ "undecidedVertexCount": sum(report["undecidedVertexCount"] for report in reports),
+ "sampledVertexCount": sum(report["sampledVertexCount"] for report in reports),
+ "totalVertexCount": sum(report["totalVertexCount"] for report in reports),
+ "meshes": reports,
+ "errors": errors,
+ }
+
+
+def _load_meshes(path: Path) -> list[dict[str, Any]]:
+ payload = json.loads(path.read_text())
+ if isinstance(payload, list):
+ return payload
+ if isinstance(payload, dict):
+ meshes = payload.get("meshes")
+ if meshes is None:
+ meshes = payload.get("components")
+ if isinstance(meshes, dict):
+ return [dict(value, id=key) if isinstance(value, dict) else {"id": key} for key, value in meshes.items()]
+ if isinstance(meshes, list):
+ return meshes
+ if isinstance(payload.get("vertices"), list):
+ return [payload]
+ raise ValueError("input must be a mesh, an array of meshes, or an object with meshes/components")
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines: list[str] = []
+ for report in result["meshes"]:
+ if report["error"]:
+ lines.append(f" [ERROR] {report['name']}: {report['error']}")
+ continue
+ flag = "SELF-INTERSECTING" if report["selfIntersecting"] else "ok"
+ lines.append(
+ f" [{flag}] {report['name']} "
+ f"sampled={report['sampledVertexCount']}/{report['totalVertexCount']} "
+ f"(stride {report['samplingStride']}) "
+ f"inside={report['insideVertexCount']} undecided={report['undecidedVertexCount']} "
+ f"normals={report['normalSource']} epsilon={report['epsilon']:.6g}"
+ )
+ for region in report["worstRegions"]:
+ position = ", ".join(f"{value:.4f}" for value in region["position"])
+ lines.append(f" vertex {region['vertexIndex']} at ({position})")
+ if result["errors"]:
+ verdict = "ERROR"
+ elif result["selfIntersecting"]:
+ verdict = "SELF-INTERSECTION DETECTED"
+ else:
+ verdict = "no self-intersection"
+ lines.append(f"verdict: {verdict}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("meshes", type=Path, help="JSON file: a mesh, an array of meshes, or {meshes: [...]}")
+ parser.add_argument("--max-samples", type=int, default=MAX_SAMPLED_VERTICES)
+ parser.add_argument("--epsilon", type=float, default=None)
+ parser.add_argument("--json", action="store_true", help="print JSON instead of a summary")
+ args = parser.parse_args(argv)
+
+ try:
+ meshes = _load_meshes(args.meshes)
+ result = analyze_meshes(meshes, max_samples=args.max_samples, epsilon=args.epsilon)
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(_format_summary(result))
+ # An unreadable mesh is an error, not a clean bill of health, so it outranks the verdict.
+ if result["errors"]:
+ return 2
+ return 1 if result["selfIntersecting"] else 0
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/turntable_gate.py b/forge/stage4_review/turntable_gate.py
new file mode 100644
index 0000000..28a4dcf
--- /dev/null
+++ b/forge/stage4_review/turntable_gate.py
@@ -0,0 +1,415 @@
+#!/usr/bin/env python3
+"""Mandatory turntable coverage gate with interior-hole (background-enclosure) detection.
+
+``diagnose_render_multi_angle`` is reference-free and checks exactly one thing:
+does the silhouette AREA collapse when the object is orbited (the billboard
+test). That leaves two holes an area-only check cannot see through:
+
+1. **Coverage was never mandatory.** Reviews were historically captured from
+ the front only, so defects that exist solely off-axis survived multiple
+ review rounds -- a conical hat mounted at hip height instead of behind the
+ shoulders, a weapon passing through the body, a charm floating detached
+ below the ground plane. None of those are visible from the front. This
+ module makes a minimum set of orbit azimuths (front/right/back/left by
+ default) MANDATORY: a missing required angle is a gate FAILURE, not a
+ warning, because making the turntable mandatory is the entire point.
+
+2. **A hole through the model is invisible to an area test.** A character's
+ eye socket was pushed clean through the back of its skull; viewed from
+ behind there is a hole through the head. Silhouette AREA barely changes
+ (the head is still roughly the same size), so the existing area-collapse
+ check passes. But that hole is an enclosed BACKGROUND region trapped
+ INSIDE the silhouette -- trivially detectable with a flood fill, at zero
+ token cost. This module flood-fills the background from the image border
+ and flags any background pixel the fill never reaches: it is enclosed by
+ the foreground, i.e. a hole through the object.
+
+Important caveat: a legitimately holed subject exists (a ring, a door
+handle, the negative space between an arm and a torso). "holed" here means
+only "the silhouette encloses background at this angle" -- it is a defect
+just when the subject is NOT supposed to have a through-hole there. Callers
+that expect legitimate holes must pass ``allow_holes=True`` /
+``--allow-holes`` to keep that signal from failing the gate.
+
+Scope: like its sibling, this module only ANALYZES already-captured PNGs.
+Driving a renderer to produce the orbit captures is handled elsewhere.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import load_image, build_foreground_mask # noqa: E402
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from diagnose_render_multi_angle import analyze_angles, silhouette_area_fraction # noqa: E402
+
+
+# Front/right/back/left: the minimum orbit that can catch an off-axis-only
+# defect. Overridable by callers with unusual rigs (e.g. no rear access).
+REQUIRED_AZIMUTHS: tuple[float, ...] = (0.0, 90.0, 180.0, 270.0)
+DEFAULT_AZIMUTH_TOLERANCE = 5.0
+DEFAULT_COLLAPSE_RATIO = 0.15
+
+# A hole must clear BOTH floors to trip the gate: an absolute pixel count
+# (absorbs anti-aliasing speckle around edges -- a stray 1-2px background
+# pixel next to a jagged silhouette edge is not a hole through the model)
+# and a fraction of the silhouette area (so a huge, legitimate silhouette
+# with a tiny enclosed pocket of background isn't over-flagged either).
+INTERIOR_HOLE_PIXEL_FLOOR = 4
+INTERIOR_HOLE_FRACTION_THRESHOLD = 0.01
+
+
+def _normalize_azimuth(degrees: float) -> float:
+ """Map an azimuth in degrees onto [0, 360). Python's ``%`` already returns
+ a non-negative result against a positive divisor, so this also handles
+ negative input (e.g. -10 -> 350)."""
+ return degrees % 360.0
+
+
+def _circular_distance(a: float, b: float) -> float:
+ """Shortest distance in degrees between two azimuths around the circle,
+ so 359.5 and 0 are 0.5 degrees apart, not 359.5."""
+ diff = abs(_normalize_azimuth(a) - _normalize_azimuth(b)) % 360.0
+ return min(diff, 360.0 - diff)
+
+
+def _load_mask(png_path: Path) -> tuple[int, int, list[bool], bool]:
+ """Load a capture and build its foreground mask, reusing the same stage1
+ loader/segmenter ``silhouette_area_fraction`` uses, so area and hole
+ numbers are computed from the identical mask.
+
+ The fourth return value says whether the segmenter could actually isolate
+ the subject. ``build_foreground_mask`` has a documented fallback: when the
+ subject is not clearly separable from its background it warns "image is not
+ clearly isolated from background" and returns MOST PIXELS as foreground.
+ That is the right answer for its original caller, which wants a broad pixel
+ sample for material evidence, and completely wrong here — a mask covering
+ the whole frame makes the silhouette meaningless, the area ratio ~1.0 for
+ every angle, and the enclosed-background holes pure noise.
+
+ This is not hypothetical. Run against a real review turntable rendered on a
+ dark gradient background, the gate reported ``area=0.9966`` per angle and a
+ confident PASS while never once measuring the character. A gate that cannot
+ see its subject must say so, not pass. Its sibling module already hardens
+ the opposite fallback (a tiny mask being inverted to "all opaque"); this is
+ the same bug wearing the other face.
+ """
+ width, height, pixels, _warnings = load_image(Path(png_path))
+ mask, _diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
+ segmented = not any("not clearly isolated" in str(w).lower() for w in mask_warnings)
+ return width, height, mask, segmented
+
+
+def _analyze_holes(width: int, height: int, mask: list[bool]) -> dict[str, Any]:
+ """Flood-fill the BACKGROUND (mask == False) starting from every border
+ pixel, iteratively (an explicit stack, not recursion -- these are large
+ images and Python's recursion limit would blow on a recursive flood fill).
+ Any background pixel the fill never reaches is enclosed by the
+ foreground: an interior hole. A second iterative pass then walks the
+ unreached background pixels to size each individual hole component and
+ find the largest one's bounding box.
+ """
+ total = width * height
+ foreground_count = sum(1 for value in mask if value)
+
+ def index(x: int, y: int) -> int:
+ return y * width + x
+
+ # Pass 1: flood-fill background reachable from the border.
+ reached = [False] * total
+ stack: list[int] = []
+ for x in range(width):
+ for y in (0, height - 1):
+ i = index(x, y)
+ if not mask[i] and not reached[i]:
+ reached[i] = True
+ stack.append(i)
+ for y in range(height):
+ for x in (0, width - 1):
+ i = index(x, y)
+ if not mask[i] and not reached[i]:
+ reached[i] = True
+ stack.append(i)
+ while stack:
+ i = stack.pop()
+ x, y = i % width, i // width
+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
+ if 0 <= nx < width and 0 <= ny < height:
+ ni = index(nx, ny)
+ if not mask[ni] and not reached[ni]:
+ reached[ni] = True
+ stack.append(ni)
+
+ # Pass 2: every background pixel not reached from the border is part of
+ # some enclosed hole. Walk each connected component to size it and find
+ # the largest one's bounding box.
+ visited = [False] * total
+ total_hole_pixels = 0
+ largest_size = 0
+ largest_bbox = {"x": 0, "y": 0, "width": 0, "height": 0}
+ for start in range(total):
+ if mask[start] or reached[start] or visited[start]:
+ continue
+ comp_stack = [start]
+ visited[start] = True
+ size = 0
+ min_x = max_x = start % width
+ min_y = max_y = start // width
+ while comp_stack:
+ i = comp_stack.pop()
+ x, y = i % width, i // width
+ size += 1
+ min_x, max_x = min(min_x, x), max(max_x, x)
+ min_y, max_y = min(min_y, y), max(max_y, y)
+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
+ if 0 <= nx < width and 0 <= ny < height:
+ ni = index(nx, ny)
+ if not mask[ni] and not reached[ni] and not visited[ni]:
+ visited[ni] = True
+ comp_stack.append(ni)
+ total_hole_pixels += size
+ if size > largest_size:
+ largest_size = size
+ largest_bbox = {
+ "x": min_x,
+ "y": min_y,
+ "width": max_x - min_x + 1,
+ "height": max_y - min_y + 1,
+ }
+
+ interior_fraction = (total_hole_pixels / foreground_count) if foreground_count > 0 else 0.0
+ return {
+ "interiorHolePixelCount": total_hole_pixels,
+ "interiorHoleFraction": interior_fraction,
+ "largestHolePixelCount": largest_size,
+ "largestHoleBBox": largest_bbox,
+ }
+
+
+def analyze_turntable(
+ captures: list[tuple[float, Path]],
+ *,
+ required_azimuths: tuple[float, ...] = REQUIRED_AZIMUTHS,
+ azimuth_tolerance: float = DEFAULT_AZIMUTH_TOLERANCE,
+ collapse_ratio: float = DEFAULT_COLLAPSE_RATIO,
+ allow_holes: bool = False,
+) -> dict[str, Any]:
+ """Run the mandatory-coverage + interior-hole turntable gate.
+
+ ``captures`` is a list of ``(azimuth_degrees, png_path)`` pairs. Azimuths
+ are normalized into [0, 360) and matched to ``required_azimuths`` within
+ ``azimuth_tolerance`` degrees (circular, so 359.5 matches a required 0).
+ A required azimuth with no matching capture is a gate FAILURE.
+
+ The capture closest to azimuth 0 is used as the reference frame for the
+ area-collapse check (delegated to ``diagnose_render_multi_angle
+ .analyze_angles``); every other capture is an orbit angle compared
+ against it, mirroring that module's single-reference model.
+
+ Every capture, including the reference, is independently checked for an
+ interior hole (background enclosed by the silhouette).
+
+ ``holed`` (per-capture and top-level) always reports the raw detection
+ signal, regardless of ``allow_holes`` -- it documents what was actually
+ found. ``allow_holes`` only affects the final ``passed`` gate, per the
+ module docstring's caveat that an enclosed-background signal is a defect
+ only when the subject is not supposed to have a through-hole there.
+ """
+ if not captures:
+ raise ValueError("analyze_turntable requires at least one capture")
+
+ ordered = sorted(captures, key=lambda capture: _normalize_azimuth(capture[0]))
+
+ # Reference = capture closest to azimuth 0 ("front"). Found by index (not
+ # by tuple identity/equality) so duplicate (azimuth, path) pairs can't
+ # accidentally exclude the wrong entry.
+ reference_index = min(
+ range(len(ordered)), key=lambda i: _circular_distance(ordered[i][0], 0.0)
+ )
+ reference_azimuth, reference_path = ordered[reference_index]
+ orbit_captures = [capture for i, capture in enumerate(ordered) if i != reference_index]
+ orbit_paths = [path for _azimuth, path in orbit_captures]
+
+ area_result = analyze_angles(reference_path, orbit_paths, collapse_ratio)
+
+ # Stitch analyze_angles' per-orbit-angle results back onto their azimuths
+ # (same order as orbit_paths, since that's exactly what was passed in).
+ per_azimuth: dict[int, dict[str, Any]] = {
+ reference_index: {
+ "areaFraction": area_result["referenceAreaFraction"],
+ "ratio": 1.0,
+ "degenerate": False,
+ }
+ }
+ for i, orbit_result in zip((i for i in range(len(ordered)) if i != reference_index), area_result["angles"]):
+ per_azimuth[i] = {
+ "areaFraction": orbit_result["areaFraction"],
+ "ratio": orbit_result["ratio"],
+ "degenerate": orbit_result["degenerate"],
+ }
+
+ angles: list[dict[str, Any]] = []
+ any_holed = False
+ unsegmented: list[float] = []
+ for i, (azimuth, path) in enumerate(ordered):
+ width, height, mask, segmented = _load_mask(path)
+ hole_info = _analyze_holes(width, height, mask)
+ # Hole numbers computed over a whole-frame fallback mask are noise, so they are not allowed to
+ # set `holed` either way -- neither to fail the gate on garbage nor, worse, to pass it.
+ holed = segmented and (
+ hole_info["largestHolePixelCount"] > INTERIOR_HOLE_PIXEL_FLOOR
+ and hole_info["interiorHoleFraction"] > INTERIOR_HOLE_FRACTION_THRESHOLD
+ )
+ if holed:
+ any_holed = True
+ if not segmented:
+ unsegmented.append(azimuth)
+ record = {
+ "azimuth": azimuth,
+ "path": str(path),
+ "isReference": i == reference_index,
+ "segmented": segmented,
+ "holed": holed,
+ **hole_info,
+ **per_azimuth[i],
+ }
+ angles.append(record)
+
+ missing_azimuths: list[float] = []
+ for required in required_azimuths:
+ matched = any(
+ _circular_distance(azimuth, required) <= azimuth_tolerance
+ for azimuth, _path in captures
+ )
+ if not matched:
+ missing_azimuths.append(_normalize_azimuth(required))
+
+ covered = not missing_azimuths
+ degenerate = area_result["degenerate"]
+ # An unsegmentable capture blocks the gate regardless of `allow_holes`. `allow_holes` says "this
+ # subject is allowed to have a through-hole"; it does not say "evaluate this render blind". Passing
+ # here would be the exact defect this module was written to end, one layer further down.
+ passed = (
+ covered
+ and not degenerate
+ and not unsegmented
+ and (allow_holes or not any_holed)
+ )
+
+ return {
+ "angles": angles,
+ "referenceAzimuth": reference_azimuth,
+ "requiredAzimuths": list(required_azimuths),
+ "azimuthTolerance": azimuth_tolerance,
+ "missingAzimuths": missing_azimuths,
+ "covered": covered,
+ "collapseRatio": collapse_ratio,
+ "degenerate": degenerate,
+ "allowHoles": allow_holes,
+ "holed": any_holed,
+ "unsegmentedAzimuths": unsegmented,
+ "segmentationReliable": not unsegmented,
+ "passed": passed,
+ "note": (
+ "deterministic; zero token; mandatory azimuth coverage catches "
+ "off-axis-only defects, interior-hole flood fill catches "
+ "silhouette-enclosed background that an area-only check misses"
+ ),
+ }
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [
+ f"reference azimuth: {result['referenceAzimuth']}",
+ f"required azimuths: {result['requiredAzimuths']} "
+ f"(tolerance {result['azimuthTolerance']} deg)",
+ f"collapse ratio threshold: {result['collapseRatio']}",
+ f"allow holes: {result['allowHoles']}",
+ ]
+ if result["missingAzimuths"]:
+ lines.append(f"MISSING required azimuths: {result['missingAzimuths']}")
+ if result.get("unsegmentedAzimuths"):
+ lines.append(
+ f"UNSEGMENTED azimuths {result['unsegmentedAzimuths']}: the subject could not be "
+ "isolated from its background, so area and hole numbers on those frames are "
+ "meaningless. Re-render the turntable against a high-contrast or transparent "
+ "background before reading this gate's verdict."
+ )
+ for angle in result["angles"]:
+ flags = []
+ if not angle.get("segmented", True):
+ flags.append("UNSEGMENTED")
+ if angle["degenerate"]:
+ flags.append("DEGENERATE")
+ if angle["holed"]:
+ flags.append("HOLED")
+ flag = ",".join(flags) if flags else "ok"
+ tag = " (reference)" if angle["isReference"] else ""
+ lines.append(
+ f" [{flag}] azimuth={angle['azimuth']}{tag} {angle['path']} "
+ f"area={angle['areaFraction']:.4f} ratio={angle['ratio']:.4f} "
+ f"holePixels={angle['interiorHolePixelCount']} "
+ f"largestHole={angle['largestHolePixelCount']}"
+ )
+ verdict = "PASS" if result["passed"] else "GATE FAILURE"
+ lines.append(f"verdict: {verdict}")
+ return "\n".join(lines)
+
+
+def _parse_capture(raw: str) -> tuple[float, Path]:
+ if "=" not in raw:
+ raise ValueError(f"--capture expects azimuth=path, got {raw!r}")
+ azimuth_str, path_str = raw.split("=", 1)
+ return float(azimuth_str), Path(path_str)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--capture",
+ type=str,
+ action="append",
+ default=[],
+ help="azimuth=path.png (repeat for each turntable capture)",
+ )
+ parser.add_argument(
+ "--required",
+ type=float,
+ action="append",
+ default=None,
+ help=f"required azimuth in degrees (repeat; default {REQUIRED_AZIMUTHS})",
+ )
+ parser.add_argument("--azimuth-tolerance", type=float, default=DEFAULT_AZIMUTH_TOLERANCE)
+ parser.add_argument("--collapse-ratio", type=float, default=DEFAULT_COLLAPSE_RATIO)
+ parser.add_argument("--allow-holes", action="store_true")
+ parser.add_argument("--json", action="store_true", help="print JSON instead of a summary")
+ args = parser.parse_args(argv)
+
+ try:
+ captures = [_parse_capture(raw) for raw in args.capture]
+ required_azimuths = tuple(args.required) if args.required else REQUIRED_AZIMUTHS
+ result = analyze_turntable(
+ captures,
+ required_azimuths=required_azimuths,
+ azimuth_tolerance=args.azimuth_tolerance,
+ collapse_ratio=args.collapse_ratio,
+ allow_holes=args.allow_holes,
+ )
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(_format_summary(result))
+ return 0 if result["passed"] else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/validate_render_profile.py b/forge/stage4_review/validate_render_profile.py
new file mode 100644
index 0000000..1a02043
--- /dev/null
+++ b/forge/stage4_review/validate_render_profile.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Validate the shared GLB/procedural browser render profile.
+
+The validator is intentionally dependency-free and stricter than the descriptive
+JSON Schema: the same profile must be usable by both routes, and the six diagnostic
+passes plus the one-feedback-group ordering are mandatory for v2.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+
+PASS_IDS = (
+ "beauty",
+ "alpha-silhouette",
+ "semantic-id",
+ "depth",
+ "normal",
+ "roughness-material-id",
+)
+REGION_IDS = ("face", "kasa", "scarf", "tunic", "staff", "tail", "feet", "materials")
+FEEDBACK_GROUPS = ("camera", "silhouette", "face", "clothing", "accessory", "materials", "lighting")
+TONE_MAPPINGS = {"NoToneMapping", "ACESFilmicToneMapping", "AgXToneMapping", "NeutralToneMapping"}
+
+
+def _is_vec(value: Any, length: int) -> bool:
+ return isinstance(value, list) and len(value) == length and all(isinstance(item, (int, float)) for item in value)
+
+
+def validate_profile(profile: dict[str, Any]) -> dict[str, Any]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ if profile.get("schemaVersion") != "render-profile.v2":
+ errors.append("schemaVersion must be render-profile.v2")
+ if profile.get("kind") != "threejs-render-profile":
+ errors.append("kind must be threejs-render-profile")
+ if profile.get("authority") != "browser-threejs":
+ errors.append("authority must be browser-threejs")
+
+ renderer = profile.get("renderer")
+ if not isinstance(renderer, dict):
+ errors.append("renderer must be an object")
+ else:
+ required = {
+ "backend",
+ "colorManagementEnabled",
+ "workingColorSpace",
+ "outputColorSpace",
+ "toneMapping",
+ "toneMappingExposure",
+ "viewport",
+ "devicePixelRatio",
+ "antialias",
+ }
+ for key in sorted(required - renderer.keys()):
+ errors.append(f"renderer.{key} is required")
+ if renderer.get("backend") != "WebGLRenderer":
+ errors.append("renderer.backend must be WebGLRenderer")
+ if renderer.get("colorManagementEnabled") is not True:
+ errors.append("renderer.colorManagementEnabled must be true")
+ if renderer.get("workingColorSpace") != "Linear-sRGB":
+ errors.append("renderer.workingColorSpace must be Linear-sRGB")
+ if renderer.get("outputColorSpace") != "SRGBColorSpace":
+ errors.append("renderer.outputColorSpace must be SRGBColorSpace")
+ if renderer.get("toneMapping") not in TONE_MAPPINGS:
+ errors.append("renderer.toneMapping is not a supported Three.js profile value")
+ if not isinstance(renderer.get("toneMappingExposure"), (int, float)) or renderer.get("toneMappingExposure", 0) <= 0:
+ errors.append("renderer.toneMappingExposure must be > 0")
+ viewport = renderer.get("viewport")
+ if not _is_vec(viewport, 2) or any(int(value) != value or value <= 0 for value in viewport):
+ errors.append("renderer.viewport must be [positive integer width, positive integer height]")
+ if not isinstance(renderer.get("devicePixelRatio"), (int, float)) or renderer.get("devicePixelRatio", 0) <= 0:
+ errors.append("renderer.devicePixelRatio must be > 0")
+ if not isinstance(renderer.get("antialias"), bool):
+ errors.append("renderer.antialias must be boolean")
+
+ environment = profile.get("environment")
+ if not isinstance(environment, dict):
+ errors.append("environment must be an object")
+ else:
+ if environment.get("kind") not in {"none", "pmrem-hdr", "pmrem-equirectangular", "pmrem-cubemap"}:
+ errors.append("environment.kind must identify a PMREM or none")
+ if not isinstance(environment.get("source"), str):
+ errors.append("environment.source is required")
+ if not isinstance(environment.get("intensity"), (int, float)) or environment.get("intensity", -1) < 0:
+ errors.append("environment.intensity must be >= 0")
+ if environment.get("kind", "").startswith("pmrem") and environment.get("prefilter") != "PMREMGenerator":
+ warnings.append("PMREM environment should record prefilter=PMREMGenerator")
+
+ camera = profile.get("camera")
+ if not isinstance(camera, dict):
+ errors.append("camera must be an object")
+ else:
+ if camera.get("projection") not in {"perspective", "orthographic"}:
+ errors.append("camera.projection must be perspective or orthographic")
+ for key in ("position", "target"):
+ if not _is_vec(camera.get(key), 3):
+ errors.append(f"camera.{key} must be a numeric vec3")
+ if not isinstance(camera.get("near"), (int, float)) or camera.get("near", 0) <= 0:
+ errors.append("camera.near must be > 0")
+ if not isinstance(camera.get("far"), (int, float)) or camera.get("far", 0) <= camera.get("near", 0):
+ errors.append("camera.far must be greater than camera.near")
+
+ background = profile.get("background")
+ if not isinstance(background, dict) or background.get("kind") not in {"solid", "transparent", "scene"}:
+ errors.append("background.kind must be solid, transparent, or scene")
+
+ passes = profile.get("passes")
+ pass_ids = [item.get("id") for item in passes] if isinstance(passes, list) and all(isinstance(item, dict) for item in passes) else []
+ if set(pass_ids) != set(PASS_IDS) or len(pass_ids) != len(PASS_IDS):
+ errors.append(f"passes must contain exactly: {', '.join(PASS_IDS)}")
+ else:
+ for item in passes:
+ if item.get("required") is not True:
+ errors.append(f"pass {item.get('id')} must be required")
+ if item.get("id") == "beauty" and item.get("colorSpace") != "SRGBColorSpace":
+ errors.append("beauty pass must use SRGBColorSpace")
+ if item.get("id") != "beauty" and item.get("colorSpace") != "NoColorSpace":
+ errors.append(f"diagnostic pass {item.get('id')} must use NoColorSpace")
+
+ regions = profile.get("regions")
+ region_ids = [item.get("id") for item in regions] if isinstance(regions, list) and all(isinstance(item, dict) for item in regions) else []
+ missing_regions = [region for region in REGION_IDS if region not in region_ids]
+ if missing_regions:
+ errors.append(f"regions missing required IDs: {', '.join(missing_regions)}")
+
+ feedback = profile.get("feedbackGroups")
+ feedback_ids = [item.get("id") for item in feedback] if isinstance(feedback, list) and all(isinstance(item, dict) for item in feedback) else []
+ if feedback_ids != list(FEEDBACK_GROUPS):
+ errors.append("feedbackGroups must be ordered camera, silhouette, face, clothing, accessory, materials, lighting")
+ else:
+ for index, item in enumerate(feedback, start=1):
+ if item.get("order") != index:
+ errors.append(f"feedback group {item.get('id')} must have order {index}")
+
+ return {"passed": not errors, "errors": errors, "warnings": warnings, "passIds": pass_ids, "regionIds": region_ids, "feedbackGroups": feedback_ids}
+
+
+def validate_file(path: Path) -> dict[str, Any]:
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ return {"passed": False, "errors": [f"cannot read JSON: {exc}"], "warnings": []}
+ if not isinstance(value, dict):
+ return {"passed": False, "errors": ["profile root must be an object"], "warnings": []}
+ result = validate_profile(value)
+ result["path"] = str(path.resolve())
+ return result
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("profile", type=Path)
+ args = parser.parse_args(argv)
+ result = validate_file(args.profile.expanduser().resolve())
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(__import__("sys").argv[1:]))
diff --git a/forge/stage4_review/vlm_gate.py b/forge/stage4_review/vlm_gate.py
index 0244744..4e68144 100644
--- a/forge/stage4_review/vlm_gate.py
+++ b/forge/stage4_review/vlm_gate.py
@@ -174,10 +174,15 @@ def main(argv: list[str]) -> int:
try:
eye = json.loads(args.eye.read_text(encoding="utf-8"))
sampler = None
+ preloaded = None
if args.samples:
preloaded = json.loads(args.samples.read_text(encoding="utf-8"))
+ if not isinstance(preloaded, list) or not preloaded:
+ raise ValueError("--samples must contain a non-empty JSON list")
+ if not all(isinstance(sample, dict) for sample in preloaded):
+ raise ValueError("--samples entries must be JSON objects")
sampler = lambda i: preloaded[i % len(preloaded)] # noqa: E731
- result = gate(eye, sampler, n_samples=len(json.loads(args.samples.read_text())) if args.samples else 3,
+ result = gate(eye, sampler, n_samples=len(preloaded) if preloaded else 3,
criteria_min=args.criteria_min, geometry_class=args.geometry_class)
except Exception as exc: # noqa: BLE001
print(f"error: {exc}", file=sys.stderr)
diff --git a/forge/stage5_rig/NOTES.md b/forge/stage5_rig/NOTES.md
new file mode 100644
index 0000000..16b5c61
--- /dev/null
+++ b/forge/stage5_rig/NOTES.md
@@ -0,0 +1,149 @@
+# Milestone 0 findings that don't belong in the gate report
+
+These are things discovered while building the Milestone 0 rig emitter
+(`forge/stage5_rig/`) that are true regardless of Milestone 0's pass/fail
+result, and that matter to whoever does rig *integration* later. Read-only
+findings — nothing here changes any file outside `forge/stage5_rig/` or
+`forge/tests/test_rig_milestone0.py`.
+
+## `THREE.CapsuleGeometry`'s raw seam is a real defect; the "66 non-manifold after weld" figure was not
+
+> **CORRECTED 2026-07-30 (credit: worker-flatten).** The paragraph below
+> originally claimed that even a "correct" weld of `THREE.CapsuleGeometry`
+> left 66 non-manifold edges, and used that to argue the primitive needed a
+> hand-built replacement rather than a better weld. That specific claim was
+> wrong — it was a measurement artifact of `BufferGeometryUtils.mergeVertices`,
+> not a real topology defect. I reproduced worker-flatten's finding
+> independently (see below) before editing this file, rather than taking the
+> correction on faith. The **raw boundary-edge finding (194 edges) is still
+> real and still verified** — only the "non-manifold after weld" half of the
+> story was wrong.
+
+**What's actually true, verified directly:** the exact capsule call the
+pipeline used to emit (`new THREE.CapsuleGeometry(0.35, 0.7, 16, 32)`, from
+`CAPSULE_CAP_SEGMENTS = 16` / `CAPSULE_RADIAL_SEGMENTS = 32` — see "Update on
+the real pipeline" below for what's changed since) has a genuine UV-seam
+defect in its raw, unwelded form:
+
+| Method | vertices | triangles | boundary edges | non-manifold edges |
+|---|---|---|---|---|
+| as-is, unwelded | 2178 | 4160 | **194** | 0 |
+| position-only + `BufferGeometryUtils.mergeVertices(geometry, 1e-5)` | 2050 | 4160 | 0 | 66 *(artifact — see below)* |
+| position-key dedup + **drop degenerate triangles** (no `mergeVertices`) | 2050 | 4096 (64 dropped) | 0 | **0** |
+
+**Root cause of the "66" artifact:** `mergeVertices` re-indexes vertices by
+position but does not drop triangles that become degenerate (two or more
+corners collapsed to the same vertex) after that re-indexing. A degenerate
+triangle `(a, a, b)` contributes the undirected edge `(a, b)` to the tally
+**twice**, silently turning a legitimate 2-incidence (ordinary, non-manifold)
+edge into an apparent 4 — which a naive `count > 2` check flags as
+non-manifold even though the actual geometry, once the degenerate triangles
+are also dropped, is a perfectly ordinary closed 2-manifold. There are
+exactly 64 such degenerate triangles for this configuration — the "64
+dropped" figure in the corrected row above, which I measured myself and
+which matches worker-flatten's number exactly. This is
+stable across weld tolerances from `1e-4` down to `1e-10` (ruling out a
+tolerance-size explanation), and matches independently between two different
+implementations (mine, replicated here; worker-flatten's, done separately in
+`generate_threejs_factory.py`'s context) with the exact same numbers.
+
+**So the raw-boundary finding (194 edges) stands, but the conclusion drawn
+from it does not fully stand:** `THREE.CapsuleGeometry` is fixable with an
+ordinary weld — it just needs a weld that also drops degenerate triangles,
+which `mergeVertices` alone does not do. A hand-built watertight primitive
+(what Milestone 0 uses; see below) is *a* valid fix, but it was not, as I
+originally implied, the *only* practical one.
+
+**Correction to my prior report to team-lead (kept for the record, still
+accurate on its own terms):** I previously wrote that
+`createRiggedDragon.ts:422-432`'s position-only `rawGeometry` strip-then-merge
+pattern exists "exactly because" of the UV-seam attribute-matching problem
+below. That was an inference from reading the code's *shape*, not something
+the code itself states, and team-lead is right that it postdates a different
+purpose (copying vertices out of a `MarchingCubes` result before a
+scale/translate). What IS independently verified, not inferred, is that
+`mergeVertices` only merges vertices where **every** attribute matches within
+tolerance — I confirmed this by running `mergeVertices` on the *untouched*
+geometry (all attributes intact) and getting the same 194 boundary edges, no
+change, versus a real change once stripped to position-only. Whether the
+dragon file's author had that same reasoning in mind is not established
+either way.
+
+**Reproduce (all three rows above, in one run):**
+```bash
+cd img2threejs-showcase
+node --input-type=module -e "
+import * as THREE from 'three';
+import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
+function edgeStats(idxArr, triCount) {
+ const edges = new Map();
+ for (let o = 0; o < triCount; o++) {
+ const tri = [idxArr[o*3], idxArr[o*3+1], idxArr[o*3+2]];
+ for (let e = 0; e < 3; e++) {
+ const u = tri[e], v = tri[(e+1)%3];
+ const k = u < v ? u+':'+v : v+':'+u;
+ edges.set(k, (edges.get(k) ?? 0) + 1);
+ }
+ }
+ return { boundary: [...edges.values()].filter(c=>c===1).length, nonManifold: [...edges.values()].filter(c=>c>2).length };
+}
+const raw = new THREE.CapsuleGeometry(0.35, 0.7, 16, 32);
+console.log('raw:', edgeStats(raw.index.array, raw.index.count/3));
+const posOnly = new THREE.BufferGeometry();
+posOnly.setAttribute('position', raw.getAttribute('position').clone());
+posOnly.setIndex(raw.index.clone());
+const merged = mergeVertices(posOnly, 1e-5);
+console.log('mergeVertices (artifact):', edgeStats(merged.index.array, merged.index.count/3));
+const pos = raw.getAttribute('position');
+const keyOf = (i) => Math.round(pos.getX(i)*1e5)+':'+Math.round(pos.getY(i)*1e5)+':'+Math.round(pos.getZ(i)*1e5);
+const remap = new Int32Array(pos.count); const seen = new Map(); let next = 0;
+for (let i = 0; i < pos.count; i++) { const k = keyOf(i); if (!seen.has(k)) seen.set(k, next++); remap[i] = seen.get(k); }
+let dropped = 0; const kept = [];
+for (let o = 0; o < raw.index.count/3; o++) {
+ const a = remap[raw.index.array[o*3]], b = remap[raw.index.array[o*3+1]], c = remap[raw.index.array[o*3+2]];
+ if (a===b||b===c||a===c) { dropped++; continue; }
+ kept.push(a,b,c);
+}
+console.log('dedup + drop-degenerate (correct):', edgeStats(kept, kept.length/3), 'dropped', dropped);
+"
+```
+
+**What Milestone 0 uses, and why it's still a reasonable choice even though
+`THREE.CapsuleGeometry` turned out to be fixable:**
+`forge/stage5_rig/emit_rig.py`'s `buildWatertightCapsule()` builds its own
+grid from scratch — pole vertices shared once (not duplicated per fan
+triangle), radial index taken `mod radialSegments` so the seam column never
+exists as separate vertices in the first place. That's watertight by
+construction rather than by a weld step (0 boundary / 0 non-manifold at every
+configuration tried, no tolerance parameter to get wrong), which is still a
+simpler property to depend on for a kill test than "call `mergeVertices`,
+then remember it needs a degenerate-triangle-dropping pass too, on top of
+being position-only." It is not a drop-in replacement for
+`THREE.CapsuleGeometry` as used generally by the pipeline (arbitrary
+placement/orientation via `component.geometryDescriptor`), and I have not
+attempted to make it one.
+
+**Update on the real pipeline:** at the time this was first written,
+`generate_threejs_factory.py:1025` emitted the raw, unwelded
+`THREE.CapsuleGeometry` call directly, so the 194-boundary-edge defect was
+live in real output. `worker-flatten` has since ported an adapted copy of
+`buildWatertightCapsule` into `generate_threejs_factory.py` for the general
+"capsule" primitive (see `forge/tests/test_primitive_watertightness.py`), so
+that specific defect is fixed in the real pipeline as of this writing — this
+section is now a historical record of the investigation, not an open
+blocker. Decision on keeping two independently-verified copies of the
+builder (mine here, worker-flatten's in the factory) rather than a shared
+runtime module: see the message thread with worker-flatten, 2026-07-30 —
+`stage5_rig` is deliberately standalone until WS-C integration, and the two
+copies have legitimate purpose-specific differences (UV attribute, normals
+timing).
+
+## Gate (b) needs the mesh to actually carry geometry near the joint
+
+Documented in the gate report proper (message to team-lead), not repeated
+here in full: the first version of `buildWatertightCapsule()` had exactly one
+quad band for the whole cylindrical shaft, so no vertex existed anywhere near
+an interior joint's pivot. Fixed by adding `heightSegments`, derived from the
+smallest envelope radius in play (`RING_RESOLUTION_DIVISOR = 3.0` rings per
+radius) rather than a hardcoded ring count, so resolution scales if the
+capsule or the bone spacing changes.
diff --git a/forge/stage5_rig/__init__.py b/forge/stage5_rig/__init__.py
new file mode 100644
index 0000000..2404a91
--- /dev/null
+++ b/forge/stage5_rig/__init__.py
@@ -0,0 +1,6 @@
+"""Milestone 0 rig kill test — standalone, not wired into the main pipeline.
+
+See docs/PLAN_1.5_ANIMATION_READY_RIGS.md. This package intentionally does not
+import from or get imported by generate_threejs_factory.py: integration is a
+later milestone. Everything here is pure Python 3.10+ stdlib.
+"""
diff --git a/forge/stage5_rig/emit_rig.py b/forge/stage5_rig/emit_rig.py
new file mode 100644
index 0000000..5d1c126
--- /dev/null
+++ b/forge/stage5_rig/emit_rig.py
@@ -0,0 +1,420 @@
+"""Milestone 0 rig emitter: RigSpec -> standalone TypeScript.
+
+Turns a hand-written RigSpec (forge/stage5_rig/rig_spec.py) plus a small side
+channel of component bounding-box extents into a self-contained .ts module
+that builds a real THREE.Bone hierarchy + THREE.Skeleton, skins a single
+capsule mesh with the weight function from PLAN_1.5 §4, and binds it.
+
+Standalone on purpose. Does NOT import from or get called by
+generate_threejs_factory.py — integration is a later milestone, and that file
+is dirty in this checkout.
+
+MILESTONE-0 SCOPE NOTE: the geometry this emitter builds is a synthetic
+watertight capsule constructed directly from the bone chain span, not a
+subject-derived mesh from the real pipeline (stage1/stage2 output). Wiring
+this weight function to real emitted geometry is future work; this file only
+answers "can a generator emit a working skinned rig from a spec at all."
+
+MILESTONE-0 SIMPLIFICATION: the capsule builder assumes the bone chain is a
+single straight line along local +Y/-Y (matching the capsule's own
+construction axis). Off-axis or branching chains are out of scope here.
+
+Pure Python 3.10+ stdlib. No pip installs, no string.Template brace-escaping
+footguns — plain token replacement is used instead of str.format()/f-strings
+against the JS/TS body, because that body is full of literal `{`/`}`.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from typing import Optional
+
+from .rig_spec import BoneSpec, RigSpec, derive_envelope_radius, validate_rig_spec
+
+_TEMPLATE = r"""// AUTO-GENERATED by forge/stage5_rig/emit_rig.py — Milestone 0 rig kill test.
+// Do not hand-edit; regenerate from the RigSpec instead.
+import * as THREE from 'three';
+
+// ---------------------------------------------------------------------------
+// RigSpec-derived constants. Every number below traces to the hand-written
+// RigSpec and the derived-not-proposed envelope radius formula (PLAN_1.5 §4.3).
+// ---------------------------------------------------------------------------
+export const BONE_IDS = __BONE_IDS_JSON__;
+export const PARENT = __PARENT_JSON__;
+export const JOINT_POS = __JOINT_POS_JSON__;
+export const TIP_POS = __TIP_POS_JSON__;
+export const ENVELOPE_RADIUS = __ENVELOPE_RADIUS_JSON__;
+export const OVERLAP_FACTOR = __OVERLAP_FACTOR__;
+
+const CAPSULE_RADIUS = __CAPSULE_RADIUS__;
+const CAPSULE_CYL_LENGTH = __CAPSULE_CYL_LENGTH__;
+const CAPSULE_CENTER_Y = __CAPSULE_CENTER_Y__;
+const CAP_SEGMENTS = __CAP_SEGMENTS__;
+const RADIAL_SEGMENTS = __RADIAL_SEGMENTS__;
+const HEIGHT_SEGMENTS = __HEIGHT_SEGMENTS__;
+
+// ---------------------------------------------------------------------------
+// Watertight-by-construction capsule: shared pole vertices, modulo-wrapped
+// radial rings (no UV-seam vertex duplication). [email protected]'s own
+// THREE.CapsuleGeometry was measured (during design of this emitter) to leave
+// ~98 boundary edges even after BufferGeometryUtils.mergeVertices on a
+// position-only copy of it, because its radial seam column is a genuine
+// second set of vertex indices at (numerically, not exactly) the same
+// position that a 1e-5 weld does not always collapse cleanly at the poles.
+// Building the grid so the seam never exists (radial index taken mod
+// RADIAL_SEGMENTS) sidesteps that fragility entirely and is exact, not
+// tolerance-dependent.
+//
+// heightSegments subdivides the CYLINDRICAL band into multiple rings (not
+// just the two equators). Without this, a single quad band spans the whole
+// cylinder and no vertex sits anywhere near an interior bone's pivot, which
+// silently defeats a pose-sweep gate: rotating a joint whose bone segment
+// lies entirely inside that one quad band only swings a rigid cap, never
+// actually samples deformation near the joint. heightSegments is chosen by
+// the caller (see emit_typescript()) from the derived envelope radius, not
+// hardcoded here.
+// ---------------------------------------------------------------------------
+function buildWatertightCapsule(radius, cylLength, capSegments, radialSegments, heightSegments) {
+ const positions = [];
+ const indices = [];
+ const halfCyl = cylLength / 2;
+
+ const bottomPoleIndex = positions.length / 3;
+ positions.push(0, -halfCyl - radius, 0);
+
+ const ringStarts = [];
+ for (let ring = 1; ring <= capSegments; ring++) {
+ const phi = (Math.PI / 2) * (ring / capSegments);
+ const y = -halfCyl - radius * Math.cos(phi);
+ const r = radius * Math.sin(phi);
+ const start = positions.length / 3;
+ ringStarts.push(start);
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const theta = (radial / radialSegments) * Math.PI * 2;
+ positions.push(r * Math.cos(theta), y, r * Math.sin(theta));
+ }
+ }
+
+ // Cylinder rings: heightSegments steps from the bottom equator (already the
+ // last entry of ringStarts, at y=-halfCyl) up to and including the top
+ // equator (y=+halfCyl). This is what puts real geometry along the whole
+ // shaft, not just at its two ends.
+ const cylinderRingStarts = [];
+ if (cylLength > 0) {
+ for (let step = 1; step <= heightSegments; step++) {
+ const y = -halfCyl + (cylLength * step) / heightSegments;
+ const start = positions.length / 3;
+ cylinderRingStarts.push(start);
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const theta = (radial / radialSegments) * Math.PI * 2;
+ positions.push(radius * Math.cos(theta), y, radius * Math.sin(theta));
+ }
+ }
+ }
+ const topEquatorStart = cylLength > 0
+ ? cylinderRingStarts[cylinderRingStarts.length - 1]
+ : ringStarts[ringStarts.length - 1];
+
+ const topRingStarts = [];
+ for (let ring = capSegments - 1; ring >= 1; ring--) {
+ const phi = (Math.PI / 2) * (ring / capSegments);
+ const y = halfCyl + radius * Math.cos(phi);
+ const r = radius * Math.sin(phi);
+ const start = positions.length / 3;
+ topRingStarts.push(start);
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const theta = (radial / radialSegments) * Math.PI * 2;
+ positions.push(r * Math.cos(theta), y, r * Math.sin(theta));
+ }
+ }
+
+ const topPoleIndex = positions.length / 3;
+ positions.push(0, halfCyl + radius, 0);
+
+ const firstBottomRing = ringStarts[0];
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const next = (radial + 1) % radialSegments;
+ indices.push(bottomPoleIndex, firstBottomRing + radial, firstBottomRing + next);
+ }
+
+ const allRings = [...ringStarts, ...cylinderRingStarts, ...topRingStarts];
+ for (let i = 0; i < allRings.length - 1; i++) {
+ const a = allRings[i];
+ const b = allRings[i + 1];
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const next = (radial + 1) % radialSegments;
+ indices.push(a + radial, a + next, b + next);
+ indices.push(a + radial, b + next, b + radial);
+ }
+ }
+
+ const lastRing = allRings[allRings.length - 1];
+ for (let radial = 0; radial < radialSegments; radial++) {
+ const next = (radial + 1) % radialSegments;
+ indices.push(topPoleIndex, lastRing + next, lastRing + radial);
+ }
+
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(positions), 3));
+ geometry.setIndex(indices);
+ return geometry;
+}
+
+// ---------------------------------------------------------------------------
+// PLAN_1.5 §4 weight function — the ONE function, evaluated over the
+// complete bone set, for every mesh. No mesh-id / vertex-index branching:
+// only positions, the segment endpoints, and the derived envelope radius.
+// ---------------------------------------------------------------------------
+const _closestScratch = new THREE.Vector3();
+function closestPointOnSegment(p, s, e, out) {
+ const abx = e[0] - s[0];
+ const aby = e[1] - s[1];
+ const abz = e[2] - s[2];
+ const apx = p.x - s[0];
+ const apy = p.y - s[1];
+ const apz = p.z - s[2];
+ const abLenSq = abx * abx + aby * aby + abz * abz;
+ const t = abLenSq > 1e-12
+ ? THREE.MathUtils.clamp((apx * abx + apy * aby + apz * abz) / abLenSq, 0, 1)
+ : 0;
+ out.set(s[0] + abx * t, s[1] + aby * t, s[2] + abz * t);
+ return out;
+}
+
+function distanceToSegment(p, s, e) {
+ closestPointOnSegment(p, s, e, _closestScratch);
+ return p.distanceTo(_closestScratch);
+}
+
+/** Returns { indices: number[4], weights: number[4], fallback: boolean }. */
+function computeVertexWeights(p, boneIndexOf) {
+ const scored = BONE_IDS.map((id) => {
+ const d = distanceToSegment(p, JOINT_POS[id], TIP_POS[id]);
+ const u = d / ENVELOPE_RADIUS[id];
+ const w = Math.max(0, 1 - u * u) ** 2;
+ return { id, d, w };
+ });
+ scored.sort((a, b) => b.w - a.w);
+ const kept = scored.slice(0, 4);
+ const total = kept.reduce((sum, c) => sum + c.w, 0);
+
+ const indices = [0, 0, 0, 0];
+ const weights = [0, 0, 0, 0];
+
+ if (total > 0) {
+ for (let slot = 0; slot < 4; slot++) {
+ if (slot < kept.length) {
+ indices[slot] = boneIndexOf.get(kept[slot].id);
+ weights[slot] = kept[slot].w / total;
+ }
+ }
+ return { indices, weights, fallback: false };
+ }
+
+ // Mandatory zero-sum fallback (PLAN_1.5 §4 / ADR-8): every kept weight is
+ // zero (vertex outside every envelope). three.js's own
+ // normalizeSkinWeights() would otherwise rewrite this to (1,0,0,0) against
+ // bone 0 regardless of distance. Instead: find the absolutely nearest bone
+ // ignoring R_b and pin weight 1.0 to it.
+ let nearestId = BONE_IDS[0];
+ let nearestDistance = Infinity;
+ for (const id of BONE_IDS) {
+ const d = distanceToSegment(p, JOINT_POS[id], TIP_POS[id]);
+ if (d < nearestDistance) {
+ nearestDistance = d;
+ nearestId = id;
+ }
+ }
+ indices[0] = boneIndexOf.get(nearestId);
+ weights[0] = 1;
+ return { indices, weights, fallback: true };
+}
+
+export function createRigMilestone0() {
+ const bones = {};
+ for (const id of BONE_IDS) {
+ bones[id] = new THREE.Bone();
+ bones[id].name = id;
+ }
+ let root = null;
+ for (const id of BONE_IDS) {
+ const parentId = PARENT[id];
+ const j = JOINT_POS[id];
+ if (parentId === null) {
+ root = bones[id];
+ bones[id].position.set(j[0], j[1], j[2]);
+ } else {
+ const pj = JOINT_POS[parentId];
+ bones[id].position.set(j[0] - pj[0], j[1] - pj[1], j[2] - pj[2]);
+ bones[parentId].add(bones[id]);
+ }
+ }
+
+ const geometry = buildWatertightCapsule(CAPSULE_RADIUS, CAPSULE_CYL_LENGTH, CAP_SEGMENTS, RADIAL_SEGMENTS, HEIGHT_SEGMENTS);
+ geometry.translate(0, CAPSULE_CENTER_Y, 0);
+
+ const boneIndexOf = new Map(BONE_IDS.map((id, i) => [id, i]));
+ const position = geometry.getAttribute('position');
+ const skinIndices = new Uint16Array(position.count * 4);
+ const skinWeights = new Float32Array(position.count * 4);
+ const fallbackVertices = [];
+ const point = new THREE.Vector3();
+ for (let vertex = 0; vertex < position.count; vertex++) {
+ point.fromBufferAttribute(position, vertex);
+ const { indices, weights, fallback } = computeVertexWeights(point, boneIndexOf);
+ for (let slot = 0; slot < 4; slot++) {
+ skinIndices[vertex * 4 + slot] = indices[slot];
+ skinWeights[vertex * 4 + slot] = weights[slot];
+ }
+ if (fallback) fallbackVertices.push(vertex);
+ }
+ geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(skinIndices, 4));
+ geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeights, 4));
+ geometry.computeVertexNormals();
+ geometry.computeBoundingBox();
+ geometry.computeBoundingSphere();
+
+ const mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshBasicMaterial());
+ mesh.name = 'rig-milestone0-arm';
+ // AttachedBindMode (the default) requires the skeleton to share the mesh's
+ // world space, which requires the root bone to be a child of the mesh, not
+ // a sibling. Learned from createRiggedDragon.ts (`body.add(bones.root)`).
+ mesh.add(root);
+ const skeleton = new THREE.Skeleton(BONE_IDS.map((id) => bones[id]));
+ mesh.bindMode = THREE.AttachedBindMode;
+ mesh.bind(skeleton);
+
+ return {
+ mesh,
+ skeleton,
+ bones,
+ meta: {
+ envelopeRadius: ENVELOPE_RADIUS,
+ jointPos: JOINT_POS,
+ tipPos: TIP_POS,
+ fallbackVertices,
+ },
+ };
+}
+"""
+
+
+def _fmt_num(value: float) -> str:
+ if float(value).is_integer():
+ return repr(float(value))
+ return repr(float(value))
+
+
+# PLAN_1.5 §4's weight function is continuous, so it must actually be SAMPLED
+# at a resolution finer than the smallest envelope radius in play, or a
+# pose-sweep gate can silently test nothing near a joint (see
+# emit_typescript()'s height_segments derivation below, and the Milestone 0
+# report for the concrete failure this caught: a single quad band spanning
+# the whole cylinder let the elbow's influenced region skip past the pivot
+# entirely). 3 is not tuned per RigSpec; it is a fixed, stated ratio applied
+# uniformly to whatever envelope radius the spec/components produce.
+RING_RESOLUTION_DIVISOR = 3.0
+
+
+def emit_typescript(
+ spec: RigSpec,
+ component_extents: dict[str, tuple[float, float]],
+ capsule_radius: float,
+ overlap_factor: float = 1.2,
+ cap_segments: int = 8,
+ radial_segments: int = 16,
+ height_segments: Optional[int] = None,
+) -> str:
+ """Emit the Milestone 0 TypeScript module for `spec`.
+
+ `height_segments` subdivides the capsule's cylindrical band lengthwise.
+ Left as None (the default), it is DERIVED — not hand-picked per spec —
+ from the smallest derived envelope radius in play, at
+ RING_RESOLUTION_DIVISOR rings per radius, so every bone's influence band
+ is guaranteed several rings of real geometry rather than risking a single
+ quad spanning past it. Pass an explicit value only to override for
+ testing.
+
+ Fails closed (raises ValueError) on:
+ - a RigSpec that does not pass validate_rig_spec()
+ - a bone chain that is not a straight vertical line (the milestone-0
+ capsule-construction simplification stated in this module's docstring)
+ - a bone referencing a component id missing from component_extents
+ """
+ errors = validate_rig_spec(spec)
+ if errors:
+ raise ValueError("RigSpec rejected by validate_rig_spec: " + "; ".join(errors))
+
+ tip_pos = spec.resolve_tip_positions()
+ joint_pos = {b.id: b.joint_pos for b in spec.bones}
+ parent = {b.id: b.parent for b in spec.bones}
+ bone_ids = [b.id for b in spec.bones]
+
+ envelope_radius: dict[str, float] = {}
+ by_id: dict[str, BoneSpec] = spec.bone_by_id()
+ for bone in spec.bones:
+ if bone.component is None:
+ raise ValueError(f"bone '{bone.id}' has no component; cannot derive envelope radius")
+ if bone.component not in component_extents:
+ raise ValueError(
+ f"bone '{bone.id}' references component '{bone.component}' "
+ f"which is not present in component_extents"
+ )
+ width, depth = component_extents[bone.component]
+ envelope_radius[bone.id] = derive_envelope_radius(width, depth, overlap_factor)
+
+ # Milestone-0 simplification check: every joint/tip position must lie on
+ # a single straight vertical (Y-axis) line, matching the capsule builder.
+ all_points = [joint_pos[b] for b in bone_ids] + [tip_pos[b] for b in bone_ids]
+ xs = {round(p[0], 9) for p in all_points}
+ zs = {round(p[2], 9) for p in all_points}
+ if len(xs) != 1 or len(zs) != 1:
+ raise ValueError(
+ "Milestone-0 capsule builder requires a straight chain along the Y axis "
+ "(constant x and z across every jointPos/tipPos); this RigSpec is not one. "
+ "This is a stated milestone-0 scope limit, not a general capability."
+ )
+
+ root_bone = spec.root()
+ chain_top_y = root_bone.joint_pos[1]
+ leaf_ids = [b.id for b in spec.bones if not spec.children_of(b.id)]
+ if len(leaf_ids) != 1:
+ raise ValueError(
+ f"Milestone-0 capsule builder requires exactly one leaf bone (a single "
+ f"linear chain), found {len(leaf_ids)}: {leaf_ids}"
+ )
+ chain_bottom_y = tip_pos[leaf_ids[0]][1]
+ total_length = abs(chain_top_y - chain_bottom_y)
+ cyl_length = total_length - 2 * capsule_radius
+ if cyl_length <= 0:
+ raise ValueError(
+ f"capsule_radius {capsule_radius} is too large for chain length {total_length}: "
+ f"cylindrical section would be non-positive ({cyl_length})"
+ )
+ center_y = (chain_top_y + chain_bottom_y) / 2
+
+ if height_segments is None:
+ target_ring_spacing = min(envelope_radius.values()) / RING_RESOLUTION_DIVISOR
+ height_segments = max(4, math.ceil(cyl_length / target_ring_spacing))
+
+ replacements = {
+ "__BONE_IDS_JSON__": json.dumps(bone_ids),
+ "__PARENT_JSON__": json.dumps(parent),
+ "__JOINT_POS_JSON__": json.dumps(joint_pos),
+ "__TIP_POS_JSON__": json.dumps(tip_pos),
+ "__ENVELOPE_RADIUS_JSON__": json.dumps(envelope_radius),
+ "__OVERLAP_FACTOR__": _fmt_num(overlap_factor),
+ "__CAPSULE_RADIUS__": _fmt_num(capsule_radius),
+ "__CAPSULE_CYL_LENGTH__": _fmt_num(cyl_length),
+ "__CAPSULE_CENTER_Y__": _fmt_num(center_y),
+ "__CAP_SEGMENTS__": str(int(cap_segments)),
+ "__RADIAL_SEGMENTS__": str(int(radial_segments)),
+ "__HEIGHT_SEGMENTS__": str(int(height_segments)),
+ }
+ source = _TEMPLATE
+ for token, value in replacements.items():
+ if token not in source:
+ raise AssertionError(f"template token {token} not found — template/replacement drift")
+ source = source.replace(token, value)
+ return source
diff --git a/forge/stage5_rig/geodesic_skinning.py b/forge/stage5_rig/geodesic_skinning.py
new file mode 100644
index 0000000..70876a6
--- /dev/null
+++ b/forge/stage5_rig/geodesic_skinning.py
@@ -0,0 +1,361 @@
+#!/usr/bin/env python3
+"""Skinning weights from geodesic distance through the model's own volume.
+
+The weight function this replaces measures EUCLIDEAN distance from a vertex to a bone segment. That
+is cheap and it is wrong in one specific, very visible way: straight-line distance does not care
+whether the path stays inside the model. An arm resting against the ribs is millimetres from the
+chest through the air, so the arm bone claims chest vertices, and raising the arm drags the chest with
+it. Every character whose limbs touch the body has this defect; it is not an edge case, it is the
+default pose.
+
+Geodesic voxel binding (Dionne & de Lasa, SCA 2013) fixes it by measuring distance THROUGH THE SOLID:
+voxelize the mesh, seed each bone's voxels, and propagate outward without ever crossing empty space.
+The arm-to-chest path is then forced around through the shoulder and is correctly long. It is a
+purely geometric method -- no training data, no time constants, no iteration parameters, no
+optimization at bind or pose time -- which is why it fits a pipeline that ships code rather than
+weights.
+
+Interior detection is by flood fill from OUTSIDE the bounding box rather than by a point-in-mesh test
+per voxel. Both are correct on a watertight mesh; the flood fill is one pass instead of one ray cast
+per voxel, and it degrades sanely on a mesh with small holes (the leak is bounded by the hole) rather
+than producing scattered wrong answers along a whole ray.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from collections import deque
+from pathlib import Path
+from typing import Any
+
+DEFAULT_RESOLUTION = 32
+MAX_RESOLUTION = 96
+MAX_INFLUENCES = 4
+# Measured on the arm-beside-torso fixture, where the geodesic field correctly reports 1.37 world
+# units to the spine and 4.45 to the arm: power 2 still leaves 8.6% arm influence on the far chest
+# corner, power 3 leaves 2.8%, power 4 leaves 0.9%. The residual is a property of THIS constant, not
+# of the distance field. Higher is tighter and lower is smoother across a joint, so 3 is the middle
+# that removes the visible cross-talk without pinching the elbow.
+DEFAULT_FALLOFF_POWER = 3.0
+UNREACHABLE = float("inf")
+
+# 26-connectivity with true step lengths: a face step is 1 voxel, an edge step sqrt(2), a corner
+# sqrt(3). Using 6-connectivity instead makes every distance a Manhattan distance, which biases
+# weights along the grid axes and shows up as boxy falloff on a diagonal limb.
+_NEIGHBOURS: list[tuple[int, int, int, float]] = [
+ (dx, dy, dz, math.sqrt(dx * dx + dy * dy + dz * dz))
+ for dx in (-1, 0, 1)
+ for dy in (-1, 0, 1)
+ for dz in (-1, 0, 1)
+ if (dx, dy, dz) != (0, 0, 0)
+]
+
+
+def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
+ if indices and isinstance(indices[0], (list, tuple)):
+ return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
+ return [
+ (int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
+ for i in range(0, len(indices) - 2, 3)
+ ]
+
+
+def _bounds(vertices: list[list[float]]) -> tuple[list[float], list[float]]:
+ low = [min(v[axis] for v in vertices) for axis in range(3)]
+ high = [max(v[axis] for v in vertices) for axis in range(3)]
+ return low, high
+
+
+class VoxelGrid:
+ """A padded occupancy grid over the mesh, with solid/empty classification."""
+
+ def __init__(self, vertices: list[list[float]], faces: list[tuple[int, int, int]], resolution: int):
+ low, high = _bounds(vertices)
+ extent = max(high[axis] - low[axis] for axis in range(3)) or 1.0
+ self.step = extent / resolution
+ # One voxel of padding on every side so the outside flood fill has somewhere to start; without
+ # it a mesh touching the bounding box would have no exterior seed on that face and its whole
+ # interior would be misread as outside.
+ self.low = [low[axis] - self.step for axis in range(3)]
+ self.dims = [
+ int(math.ceil((high[axis] - low[axis]) / self.step)) + 3 for axis in range(3)
+ ]
+ self.surface: set[tuple[int, int, int]] = set()
+ for face in faces:
+ self._rasterize(vertices, face)
+ self.solid = self._fill_interior()
+
+ def index_of(self, point: list[float]) -> tuple[int, int, int]:
+ return tuple( # type: ignore[return-value]
+ min(self.dims[axis] - 1, max(0, int((point[axis] - self.low[axis]) / self.step)))
+ for axis in range(3)
+ )
+
+ def _rasterize(self, vertices: list[list[float]], face: tuple[int, int, int]) -> None:
+ """Mark every voxel a triangle touches, by subdividing until steps are sub-voxel.
+
+ Barycentric sampling at a fixed rate would leave gaps in a triangle much larger than a voxel,
+ and a gap in the surface shell lets the interior flood fill leak out and erase the model.
+ """
+ p0, p1, p2 = (vertices[i] for i in face)
+ longest = max(
+ math.dist(p0, p1), math.dist(p1, p2), math.dist(p2, p0)
+ )
+ steps = max(1, int(math.ceil(longest / (self.step * 0.5))))
+ for i in range(steps + 1):
+ for j in range(steps + 1 - i):
+ a = i / steps
+ b = j / steps
+ c = 1.0 - a - b
+ point = [p0[k] * c + p1[k] * a + p2[k] * b for k in range(3)]
+ self.surface.add(self.index_of(point))
+
+ def _fill_interior(self) -> set[tuple[int, int, int]]:
+ outside: set[tuple[int, int, int]] = set()
+ start = (0, 0, 0)
+ if start in self.surface:
+ # Padding guarantees this cannot happen; if it ever does, treat everything as solid rather
+ # than silently returning an empty model.
+ return {
+ (x, y, z)
+ for x in range(self.dims[0])
+ for y in range(self.dims[1])
+ for z in range(self.dims[2])
+ }
+ queue = deque([start])
+ outside.add(start)
+ while queue:
+ x, y, z = queue.popleft()
+ for dx, dy, dz, _ in _NEIGHBOURS:
+ nx, ny, nz = x + dx, y + dy, z + dz
+ if not (0 <= nx < self.dims[0] and 0 <= ny < self.dims[1] and 0 <= nz < self.dims[2]):
+ continue
+ cell = (nx, ny, nz)
+ if cell in outside or cell in self.surface:
+ continue
+ outside.add(cell)
+ queue.append(cell)
+ solid = set(self.surface)
+ for x in range(self.dims[0]):
+ for y in range(self.dims[1]):
+ for z in range(self.dims[2]):
+ cell = (x, y, z)
+ if cell not in outside:
+ solid.add(cell)
+ return solid
+
+
+def _segment_voxels(grid: VoxelGrid, start: list[float], end: list[float]) -> set[tuple[int, int, int]]:
+ """Voxels a bone segment passes through, sampled at half-voxel steps."""
+ length = math.dist(start, end)
+ steps = max(1, int(math.ceil(length / (grid.step * 0.5))))
+ cells = set()
+ for i in range(steps + 1):
+ t = i / steps
+ point = [start[k] + (end[k] - start[k]) * t for k in range(3)]
+ cells.add(grid.index_of(point))
+ return cells
+
+
+def geodesic_field(grid: VoxelGrid, sources: set[tuple[int, int, int]]) -> dict[tuple[int, int, int], float]:
+ """Dijkstra over solid voxels from a set of sources, in voxel units.
+
+ Dijkstra rather than plain BFS because the 26-connected steps have three different lengths; BFS
+ would count a corner step (sqrt 3) the same as a face step and distort the field diagonally.
+ """
+ import heapq
+
+ distance: dict[tuple[int, int, int], float] = {}
+ heap: list[tuple[float, tuple[int, int, int]]] = []
+ for cell in sources:
+ if cell in grid.solid:
+ distance[cell] = 0.0
+ heap.append((0.0, cell))
+ heapq.heapify(heap)
+ while heap:
+ current, cell = heapq.heappop(heap)
+ if current > distance.get(cell, UNREACHABLE):
+ continue
+ x, y, z = cell
+ for dx, dy, dz, cost in _NEIGHBOURS:
+ neighbour = (x + dx, y + dy, z + dz)
+ if neighbour not in grid.solid:
+ continue
+ candidate = current + cost
+ if candidate < distance.get(neighbour, UNREACHABLE):
+ distance[neighbour] = candidate
+ heapq.heappush(heap, (candidate, neighbour))
+ return distance
+
+
+def bind(
+ mesh: dict[str, Any],
+ bones: list[dict[str, Any]],
+ resolution: int = DEFAULT_RESOLUTION,
+ falloff_power: float = DEFAULT_FALLOFF_POWER,
+ max_influences: int = MAX_INFLUENCES,
+) -> dict[str, Any]:
+ """Compute skin indices and weights for every vertex.
+
+ Each bone needs `id`, `jointPos` and `tipPos`. Weight falls off as 1/d**power in GEODESIC
+ distance, the top `max_influences` are kept and normalised, and a vertex no bone can reach through
+ the solid is reported rather than quietly pinned to the nearest bone in space -- being unreachable
+ usually means the mesh has a hole or a detached island, and that is worth knowing.
+ """
+ vertices = mesh.get("vertices")
+ indices = mesh.get("indices")
+ if not isinstance(vertices, list) or not vertices:
+ raise ValueError("mesh.vertices must be a non-empty array")
+ if not isinstance(indices, list) or len(indices) < 3:
+ raise ValueError("mesh.indices must describe at least one triangle")
+ if not bones:
+ raise ValueError("at least one bone is required")
+ if resolution > MAX_RESOLUTION:
+ raise ValueError(f"resolution must not exceed {MAX_RESOLUTION}")
+
+ faces = _triangles(indices)
+ grid = VoxelGrid(vertices, faces, resolution)
+
+ fields: list[dict[tuple[int, int, int], float]] = []
+ unreachable_bones: list[str] = []
+ for bone in bones:
+ sources = _segment_voxels(grid, bone["jointPos"], bone["tipPos"])
+ field = geodesic_field(grid, sources)
+ if not field:
+ unreachable_bones.append(str(bone.get("id")))
+ fields.append(field)
+
+ skin_indices: list[list[int]] = []
+ skin_weights: list[list[float]] = []
+ unreachable_vertices = 0
+ for vertex in vertices:
+ cell = grid.index_of(vertex)
+ scored: list[tuple[float, int]] = []
+ for bone_index, field in enumerate(fields):
+ distance = field.get(cell)
+ if distance is None:
+ continue
+ # A vertex sitting on the bone itself would divide by zero; clamp to half a voxel, the
+ # finest distinction this grid can represent anyway.
+ scored.append((1.0 / max(distance, 0.5) ** falloff_power, bone_index))
+ if not scored:
+ unreachable_vertices += 1
+ skin_indices.append([0] * max_influences)
+ weights = [0.0] * max_influences
+ weights[0] = 1.0
+ skin_weights.append(weights)
+ continue
+ scored.sort(reverse=True)
+ kept = scored[:max_influences]
+ total = sum(weight for weight, _ in kept)
+ row_indices = [0] * max_influences
+ row_weights = [0.0] * max_influences
+ for slot, (weight, bone_index) in enumerate(kept):
+ row_indices[slot] = bone_index
+ row_weights[slot] = weight / total
+ skin_indices.append(row_indices)
+ skin_weights.append(row_weights)
+
+ return {
+ "skinIndices": skin_indices,
+ "skinWeights": skin_weights,
+ "boneOrder": [str(bone.get("id")) for bone in bones],
+ "resolution": resolution,
+ "voxelStep": grid.step,
+ "solidVoxelCount": len(grid.solid),
+ "surfaceVoxelCount": len(grid.surface),
+ "unreachableVertexCount": unreachable_vertices,
+ "unreachableBones": unreachable_bones,
+ "maxWeightError": max(
+ abs(sum(row) - 1.0) for row in skin_weights
+ ) if skin_weights else 0.0,
+ }
+
+
+def euclidean_bind(
+ mesh: dict[str, Any],
+ bones: list[dict[str, Any]],
+ falloff_power: float = DEFAULT_FALLOFF_POWER,
+ max_influences: int = MAX_INFLUENCES,
+) -> dict[str, Any]:
+ """The straight-line binding this module replaces, kept so the difference can be MEASURED.
+
+ Without it the claim "geodesic stops weights leaking across a gap" is an assertion. With it a test
+ can bind the same mesh both ways and show the leak in one and not the other.
+ """
+
+ def point_to_segment(point: list[float], a: list[float], b: list[float]) -> float:
+ ab = [b[k] - a[k] for k in range(3)]
+ ap = [point[k] - a[k] for k in range(3)]
+ denominator = sum(component * component for component in ab)
+ t = 0.0 if denominator <= 1e-12 else max(0.0, min(1.0, sum(ap[k] * ab[k] for k in range(3)) / denominator))
+ closest = [a[k] + ab[k] * t for k in range(3)]
+ return math.dist(point, closest)
+
+ vertices = mesh["vertices"]
+ skin_indices: list[list[int]] = []
+ skin_weights: list[list[float]] = []
+ for vertex in vertices:
+ scored = [
+ (1.0 / max(point_to_segment(vertex, bone["jointPos"], bone["tipPos"]), 1e-6) ** falloff_power, index)
+ for index, bone in enumerate(bones)
+ ]
+ scored.sort(reverse=True)
+ kept = scored[:max_influences]
+ total = sum(weight for weight, _ in kept) or 1.0
+ row_indices = [0] * max_influences
+ row_weights = [0.0] * max_influences
+ for slot, (weight, bone_index) in enumerate(kept):
+ row_indices[slot] = bone_index
+ row_weights[slot] = weight / total
+ skin_indices.append(row_indices)
+ skin_weights.append(row_weights)
+ return {"skinIndices": skin_indices, "skinWeights": skin_weights,
+ "boneOrder": [str(bone.get("id")) for bone in bones]}
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [
+ f"bones: {len(result['boneOrder'])}",
+ f"grid: {result['resolution']} ({result['solidVoxelCount']} solid voxels)",
+ f"max |sum(w) - 1|: {result['maxWeightError']:.3e}",
+ ]
+ if result["unreachableVertexCount"]:
+ lines.append(
+ f"UNREACHABLE vertices: {result['unreachableVertexCount']} -- no bone reaches them through "
+ "the solid, which usually means a hole or a detached island in the mesh"
+ )
+ if result["unreachableBones"]:
+ lines.append(f"UNREACHABLE bones (outside the solid): {result['unreachableBones']}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Bind skin weights by geodesic voxel distance.")
+ parser.add_argument("mesh", type=Path, help="JSON with vertices and indices")
+ parser.add_argument("--bones", type=Path, required=True, help="JSON array of bones")
+ parser.add_argument("--resolution", type=int, default=DEFAULT_RESOLUTION)
+ parser.add_argument("--out", type=Path)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ mesh = json.loads(args.mesh.read_text())
+ if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
+ mesh = mesh["meshes"][0]
+ result = bind(mesh, json.loads(args.bones.read_text()), args.resolution)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ print(json.dumps(result, indent=2) if args.json else _format_summary(result))
+ return 1 if result["unreachableVertexCount"] or result["unreachableBones"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage5_rig/rig_spec.py b/forge/stage5_rig/rig_spec.py
new file mode 100644
index 0000000..3602547
--- /dev/null
+++ b/forge/stage5_rig/rig_spec.py
@@ -0,0 +1,174 @@
+"""RigSpec data model for the Milestone 0 rig kill test.
+
+This is the schema from docs/PLAN_1.5_ANIMATION_READY_RIGS.md §6, transcribed
+as-is (field names, optionality, semantics). It is NOT a competing schema —
+where the plan's TypeScript type left something ambiguous for a 3-bone case,
+the ambiguity and the reading chosen are called out explicitly below and in
+forge/tests/test_rig_milestone0.py.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+BindPose = Literal["T", "A"]
+Forward = Literal["+Z", "-Z"]
+Role = Literal["skinned", "attachment"]
+Chain = Literal["spine", "head", "arm", "leg", "tail", "wing", "digit", "prop"]
+
+
+@dataclass
+class Ellipsoid:
+ center: tuple[float, float, float]
+ axis: tuple[float, float, float]
+ semi_axes: tuple[float, float, float]
+
+
+@dataclass
+class IkSpec:
+ is_effector: bool
+ target_bone_id: Optional[str] = None
+ rotation_min: Optional[tuple[float, float, float]] = None
+ rotation_max: Optional[tuple[float, float, float]] = None
+
+
+@dataclass
+class BoneSpec:
+ """Mirrors PLAN_1.5 §6 `BoneSpec` field-for-field."""
+
+ id: str
+ parent: Optional[str]
+ joint_pos: tuple[float, float, float]
+ component: Optional[str]
+ role: Role
+ chain: Chain
+ # Optional. "Defaults to the child's jointPos" per the plan. That default
+ # is well-defined only when the bone has exactly one child. See
+ # RigSpec.resolve_tip_positions() for the reading chosen when a bone has
+ # zero children (a leaf) or more than one.
+ tip_pos: Optional[tuple[float, float, float]] = None
+ ellipsoids: list[Ellipsoid] = field(default_factory=list)
+ ik: Optional[IkSpec] = None
+
+
+@dataclass
+class RigSpec:
+ """Mirrors PLAN_1.5 §6 `RigSpec` field-for-field."""
+
+ version: str
+ bind_pose: BindPose
+ forward: Forward
+ bones: list[BoneSpec]
+
+ def bone_by_id(self) -> dict[str, BoneSpec]:
+ return {b.id: b for b in self.bones}
+
+ def children_of(self, bone_id: str) -> list[BoneSpec]:
+ return [b for b in self.bones if b.parent == bone_id]
+
+ def root(self) -> BoneSpec:
+ roots = [b for b in self.bones if b.parent is None]
+ if len(roots) != 1:
+ raise ValueError(
+ f"RigSpec must have exactly one root bone (parent: null), found {len(roots)}"
+ )
+ return roots[0]
+
+ def resolve_tip_positions(self) -> dict[str, tuple[float, float, float]]:
+ """Resolve every bone's segment end point.
+
+ READING CHOSEN (schema ambiguity, PLAN_1.5 §6):
+
+ The plan says tipPos "Defaults to the child's jointPos" but does not
+ say what happens for a bone with zero children (a leaf) or more than
+ one child. The minimal reading adopted here, applied uniformly and
+ fail-closed rather than silently guessing:
+
+ - exactly one child, no explicit tipPos -> default to that child's jointPos
+ - explicit tipPos given -> always wins, no defaulting
+ - zero children (leaf) and no tipPos -> REJECTED. A leaf skinned
+ bone has nothing to default from, so the spec author must supply
+ tipPos explicitly. This is a spec-authoring responsibility, not
+ something the emitter may invent (Pillar 2 — the emitter is
+ deterministic code, it does not propose geometry).
+ - more than one child and no tipPos -> REJECTED. "the child's
+ jointPos" is only well-defined for a single child; defaulting to
+ an arbitrary one would be a silent, unreproducible choice.
+ """
+ by_id = self.bone_by_id()
+ resolved: dict[str, tuple[float, float, float]] = {}
+ for bone in self.bones:
+ if bone.tip_pos is not None:
+ resolved[bone.id] = bone.tip_pos
+ continue
+ children = self.children_of(bone.id)
+ if len(children) == 1:
+ resolved[bone.id] = by_id[children[0].id].joint_pos
+ elif len(children) == 0:
+ raise ValueError(
+ f"bone '{bone.id}' is a leaf with no tipPos: leaf bones must "
+ "author tipPos explicitly (PLAN_1.5 §6 default only covers "
+ "the single-child case)"
+ )
+ else:
+ raise ValueError(
+ f"bone '{bone.id}' has {len(children)} children and no explicit "
+ "tipPos: the child-default is only well-defined for exactly one child"
+ )
+ return resolved
+
+
+def validate_rig_spec(spec: RigSpec) -> list[str]:
+ """Minimal semantic gate for Milestone 0 (a scaled-down stand-in for the
+ full Joint Admission Gate Half A in PLAN_1.5 §5.2 — WS-B is out of scope
+ here). Returns a list of error strings; empty list means valid.
+ Fail-closed: callers must treat a non-empty list as a hard rejection.
+ """
+ errors: list[str] = []
+
+ ids = [b.id for b in spec.bones]
+ if len(ids) != len(set(ids)):
+ dupes = sorted({i for i in ids if ids.count(i) > 1})
+ errors.append(f"NAME_UNIQUENESS: duplicate bone id(s) {dupes}")
+
+ roots = [b for b in spec.bones if b.parent is None]
+ if len(roots) != 1:
+ errors.append(f"exactly one root bone required (parent: null), found {len(roots)}")
+
+ id_set = set(ids)
+ for bone in spec.bones:
+ if bone.parent is not None and bone.parent not in id_set:
+ errors.append(f"bone '{bone.id}' has unresolved parent '{bone.parent}'")
+
+ if spec.version != "1.0":
+ errors.append(f"unsupported RigSpec version '{spec.version}', expected '1.0'")
+
+ if not errors:
+ try:
+ spec.resolve_tip_positions()
+ except ValueError as exc:
+ errors.append(str(exc))
+
+ return errors
+
+
+def derive_envelope_radius(
+ width: float,
+ depth: float,
+ overlap_factor: float = 1.2,
+) -> float:
+ """PLAN_1.5 §4.3 — envelope radius is DERIVED, never proposed.
+
+ R_b = 0.5 * max(W_component, D_component) * F
+
+ `width`/`depth` are the component bounding-box extents perpendicular to
+ the bone axis; `overlap_factor` is F (plan default 1.2).
+ """
+ if width <= 0 or depth <= 0:
+ raise ValueError(f"component extents must be positive, got width={width} depth={depth}")
+ if overlap_factor <= 0:
+ raise ValueError(f"overlap_factor must be positive, got {overlap_factor}")
+ return 0.5 * max(width, depth) * overlap_factor
diff --git a/forge/stage5_rig/validate_rig_payload.py b/forge/stage5_rig/validate_rig_payload.py
new file mode 100644
index 0000000..0f25abc
--- /dev/null
+++ b/forge/stage5_rig/validate_rig_payload.py
@@ -0,0 +1,195 @@
+#!/usr/bin/env python3
+"""Validate the code-only alpha skeleton/skinning payload.
+
+This is a structural gate, not a rigging model. It intentionally uses only Python's
+standard library and never downloads or executes UniRig checkpoints.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+
+EPSILON = 1e-6
+WEIGHT_TOLERANCE = 1e-4
+MAX_INFLUENCES = 4
+
+
+def finite_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value))
+
+
+def vector3(value: Any, label: str, errors: list[str]) -> tuple[float, float, float] | None:
+ if not isinstance(value, list) or len(value) != 3 or not all(finite_number(item) for item in value):
+ errors.append(f"{label} must be a finite length-3 vector")
+ return None
+ return float(value[0]), float(value[1]), float(value[2])
+
+
+def matrix16(value: Any, label: str, errors: list[str]) -> list[float] | None:
+ if isinstance(value, list) and len(value) == 16 and all(finite_number(item) for item in value):
+ flat = [float(item) for item in value]
+ elif isinstance(value, list) and len(value) == 4 and all(isinstance(row, list) and len(row) == 4 for row in value):
+ if not all(finite_number(item) for row in value for item in row):
+ errors.append(f"{label} must contain only finite numbers")
+ return None
+ flat = [float(item) for row in value for item in row]
+ else:
+ errors.append(f"{label} must be a finite 4x4 matrix or flat length-16 matrix")
+ return None
+ last_row = flat[12:16]
+ if any(abs(actual - expected) > WEIGHT_TOLERANCE for actual, expected in zip(last_row, (0.0, 0.0, 0.0, 1.0))):
+ errors.append(f"{label} must have affine last row [0, 0, 0, 1]")
+ column_scales = [math.sqrt(sum(flat[row * 4 + column] ** 2 for row in range(3))) for column in range(3)]
+ if any(scale <= EPSILON for scale in column_scales):
+ errors.append(f"{label} contains a zero-scale basis column")
+ return flat
+
+
+def distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
+ return math.sqrt(sum((left - right) ** 2 for left, right in zip(a, b)))
+
+
+def validate(payload: dict[str, Any]) -> dict[str, Any]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ if payload.get("schemaVersion") != 1:
+ errors.append("schemaVersion must be 1")
+
+ coordinate = payload.get("coordinateSystem")
+ if not isinstance(coordinate, dict):
+ errors.append("coordinateSystem is required")
+ else:
+ if coordinate.get("up") != "Y":
+ errors.append("coordinateSystem.up must be Y")
+ if coordinate.get("handedness") != "right":
+ errors.append("coordinateSystem.handedness must be right")
+ if not isinstance(coordinate.get("unit"), str) or not coordinate["unit"]:
+ errors.append("coordinateSystem.unit must be a non-empty string")
+
+ joints_raw = payload.get("joints")
+ parents = payload.get("parents")
+ names = payload.get("names")
+ matrices = payload.get("matrix_local")
+ joints: list[tuple[float, float, float]] = []
+ if not isinstance(joints_raw, list) or not joints_raw:
+ errors.append("joints must be a non-empty list")
+ else:
+ for index, value in enumerate(joints_raw):
+ parsed = vector3(value, f"joints[{index}]", errors)
+ if parsed is not None:
+ joints.append(parsed)
+
+ joint_count = len(joints_raw) if isinstance(joints_raw, list) else 0
+ if not isinstance(parents, list) or len(parents) != joint_count:
+ errors.append("parents must have one entry per joint")
+ parents = parents if isinstance(parents, list) else []
+ if not isinstance(names, list) or len(names) != joint_count:
+ errors.append("names must have one entry per joint")
+ names = names if isinstance(names, list) else []
+ if not isinstance(matrices, list) or len(matrices) != joint_count:
+ errors.append("matrix_local must have one matrix per joint")
+ matrices = matrices if isinstance(matrices, list) else []
+
+ if isinstance(names, list):
+ seen: set[str] = set()
+ for index, name in enumerate(names):
+ if not isinstance(name, str) or not name.strip():
+ errors.append(f"names[{index}] must be a non-empty string")
+ elif name in seen:
+ errors.append(f"duplicate joint name: {name}")
+ seen.add(name)
+
+ if parents and parents[0] is not None:
+ errors.append("parents[0] must be null for the single root")
+ for index, parent in enumerate(parents[1:], start=1):
+ if not isinstance(parent, int) or isinstance(parent, bool):
+ errors.append(f"parents[{index}] must be an integer parent index")
+ elif parent < 0 or parent >= index:
+ errors.append(f"parents[{index}] must satisfy 0 <= parent < child index")
+ elif index < len(joints) and parent < len(joints) and distance(joints[index], joints[parent]) <= EPSILON:
+ errors.append(f"joint {index} has zero-length parent bone {parent}")
+
+ for index, matrix in enumerate(matrices):
+ matrix16(matrix, f"matrix_local[{index}]", errors)
+
+ skin_indices = payload.get("skinIndex")
+ skin_weights = payload.get("skinWeight")
+ if not isinstance(skin_indices, list) or not isinstance(skin_weights, list):
+ errors.append("skinIndex and skinWeight are required packed arrays")
+ skin_indices = skin_indices if isinstance(skin_indices, list) else []
+ skin_weights = skin_weights if isinstance(skin_weights, list) else []
+ if len(skin_indices) != len(skin_weights):
+ errors.append("skinIndex and skinWeight must have the same vertex count")
+ vertex_count = min(len(skin_indices), len(skin_weights))
+ active_counts = [0] * joint_count
+ for vertex in range(vertex_count):
+ indices = skin_indices[vertex]
+ weights = skin_weights[vertex]
+ if not isinstance(indices, list) or len(indices) != MAX_INFLUENCES:
+ errors.append(f"skinIndex[{vertex}] must have exactly {MAX_INFLUENCES} slots")
+ continue
+ if not isinstance(weights, list) or len(weights) != MAX_INFLUENCES:
+ errors.append(f"skinWeight[{vertex}] must have exactly {MAX_INFLUENCES} slots")
+ continue
+ for slot, joint in enumerate(indices):
+ if not isinstance(joint, int) or isinstance(joint, bool) or joint < 0 or joint >= joint_count:
+ errors.append(f"skinIndex[{vertex}][{slot}] points outside the joint array")
+ if finite_number(weights[slot]) and float(weights[slot]) > EPSILON and isinstance(joint, int) and 0 <= joint < joint_count:
+ active_counts[joint] += 1
+ if not all(finite_number(weight) and float(weight) >= 0 for weight in weights):
+ errors.append(f"skinWeight[{vertex}] must contain finite non-negative values")
+ else:
+ total = sum(float(weight) for weight in weights)
+ if abs(total - 1.0) > WEIGHT_TOLERANCE:
+ errors.append(f"skinWeight[{vertex}] must sum to 1 (got {total:.6f})")
+ if total <= EPSILON:
+ errors.append(f"skinWeight[{vertex}] must influence at least one joint")
+
+ unweighted = [names[index] if index < len(names) else str(index) for index, count in enumerate(active_counts) if count == 0]
+ if unweighted:
+ warnings.append("joints with no active vertex influence: " + ", ".join(unweighted))
+
+ return {
+ "schemaVersion": 1,
+ "passed": not errors,
+ "errors": errors,
+ "warnings": warnings,
+ "summary": {
+ "jointCount": joint_count,
+ "vertexCount": vertex_count,
+ "maxInfluences": MAX_INFLUENCES,
+ "activeVertexCountByJoint": active_counts,
+ },
+ "evidenceBoundary": "structural payload only; runtime deformation and screenshot gates are separate",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--payload", type=Path, required=True)
+ parser.add_argument("--out", type=Path)
+ args = parser.parse_args(argv)
+ try:
+ payload = json.loads(args.payload.expanduser().read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("payload root must be an object")
+ result = validate(payload)
+ serialized = json.dumps(result, indent=2, ensure_ascii=False) + "\n"
+ if args.out:
+ args.out.expanduser().parent.mkdir(parents=True, exist_ok=True)
+ args.out.expanduser().write_text(serialized, encoding="utf-8")
+ print(serialized, end="")
+ return 0 if result["passed"] else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/tests/fixtures/implicit_character_torso_limb.json b/forge/tests/fixtures/implicit_character_torso_limb.json
new file mode 100644
index 0000000..44099c4
--- /dev/null
+++ b/forge/tests/fixtures/implicit_character_torso_limb.json
@@ -0,0 +1,60 @@
+{
+ "targetName": "Implicit Character Torso Limb",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [
+ {
+ "id": "skin"
+ }
+ ],
+ "componentTree": [
+ {
+ "id": "torso-limb",
+ "name": "Welded torso and raised arm",
+ "level": "macro",
+ "role": "body",
+ "primitive": "capsule",
+ "topologyClass": "implicit",
+ "topologyRationale": "The raised arm blends continuously into the torso with no visible seam.",
+ "geometryDescriptor": {
+ "sdf": {
+ "primitives": [
+ {
+ "id": "torso",
+ "type": "capsule",
+ "center": [0.0, 0.0, 0.0],
+ "radius": 0.38,
+ "height": 1.1
+ },
+ {
+ "id": "arm",
+ "type": "capsule",
+ "center": [0.42, 0.22, 0.0],
+ "radius": 0.17,
+ "height": 0.85
+ }
+ ],
+ "operations": [
+ {
+ "type": "smooth-union",
+ "left": "torso",
+ "right": "arm",
+ "radius": 0.16
+ }
+ ],
+ "resolution": 32
+ }
+ },
+ "parent": null,
+ "material": "skin",
+ "transform": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ "scale": [1.0, 1.0, 1.0]
+ }
+ }
+ ]
+}
diff --git a/forge/tests/fixtures/subdivision_cage.json b/forge/tests/fixtures/subdivision_cage.json
new file mode 100644
index 0000000..9217c25
--- /dev/null
+++ b/forge/tests/fixtures/subdivision_cage.json
@@ -0,0 +1,36 @@
+{
+ "targetName": "Subdivision Cage",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [
+ {
+ "id": "cage"
+ }
+ ],
+ "componentTree": [
+ {
+ "id": "rounded-cage",
+ "name": "Rounded quad cage",
+ "level": "macro",
+ "role": "body",
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "A closed six-quad box cage is smoothed into the rounded body volume.",
+ "geometryDescriptor": {
+ "subdivide": {
+ "iterations": 2
+ }
+ },
+ "parent": null,
+ "material": "cage",
+ "transform": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ "scale": [1.0, 1.0, 1.0]
+ }
+ }
+ ]
+}
diff --git a/forge/tests/fixtures/visual_hull_two_views.json b/forge/tests/fixtures/visual_hull_two_views.json
new file mode 100644
index 0000000..aba73da
--- /dev/null
+++ b/forge/tests/fixtures/visual_hull_two_views.json
@@ -0,0 +1,92 @@
+{
+ "targetName": "Two View Visual Hull",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [
+ {
+ "id": "clay"
+ }
+ ],
+ "componentTree": [
+ {
+ "id": "carved-body",
+ "name": "Front and side silhouette carved body",
+ "level": "macro",
+ "role": "body",
+ "primitive": "box",
+ "topologyClass": "continuous-sculpt",
+ "topologyRationale": "Front and side orthographic silhouettes constrain one continuous body volume.",
+ "geometryDescriptor": {
+ "visualHull": {
+ "projection": "orthographic",
+ "boundsSpace": "component-local",
+ "bounds": {
+ "min": [-1.0, -1.0, -1.0],
+ "max": [1.0, 1.0, 1.0]
+ },
+ "resolution": 16,
+ "triangleBudget": 50000,
+ "hiddenRegions": [
+ "Back-facing surface detail is not constrained by the two supplied silhouettes."
+ ],
+ "views": [
+ {
+ "axis": "front",
+ "confidence": 0.94,
+ "mask": [
+ "0000000000000000",
+ "0000011111100000",
+ "0001111111111000",
+ "0011111111111100",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0111111111111110",
+ "0011111111111100",
+ "0001111111111000",
+ "0000011111100000",
+ "0000000000000000"
+ ]
+ },
+ {
+ "axis": "side",
+ "confidence": 0.91,
+ "mask": [
+ "0000000000000000",
+ "0000001111000000",
+ "0000011111100000",
+ "0000111111110000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0001111111111000",
+ "0000111111110000",
+ "0000011111100000",
+ "0000001111000000",
+ "0000000000000000"
+ ]
+ }
+ ]
+ }
+ },
+ "parent": null,
+ "material": "clay",
+ "transform": {
+ "position": [0.0, 0.0, 0.0],
+ "rotation": [0.0, 0.0, 0.0],
+ "scale": [1.0, 1.0, 1.0]
+ }
+ }
+ ]
+}
diff --git a/forge/tests/showcase_test_support.py b/forge/tests/showcase_test_support.py
new file mode 100644
index 0000000..cd4669f
--- /dev/null
+++ b/forge/tests/showcase_test_support.py
@@ -0,0 +1,19 @@
+from __future__ import annotations
+
+import os
+import unittest
+from pathlib import Path
+
+
+def showcase_root() -> Path:
+ configured_root = os.environ.get("IMG2THREEJS_SHOWCASE_ROOT")
+ root = Path(configured_root).expanduser().resolve() if configured_root else None
+ if root is not None and (root / "package.json").is_file():
+ return root
+ message = (
+ "showcase TypeScript checks require IMG2THREEJS_SHOWCASE_ROOT pointing to an "
+ f"img2threejs-showcase checkout; received {root if root is not None else 'no configuration'}"
+ )
+ if os.environ.get("IMG2THREEJS_REQUIRE_SHOWCASE") == "1":
+ raise RuntimeError(message)
+ raise unittest.SkipTest(message)
diff --git a/forge/tests/test_analyze_texture.py b/forge/tests/test_analyze_texture.py
index ea6c17f..e7ba06e 100644
--- a/forge/tests/test_analyze_texture.py
+++ b/forge/tests/test_analyze_texture.py
@@ -7,10 +7,12 @@ import sys
import tempfile
import unittest
import zlib
+import io
+from contextlib import redirect_stderr
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))
-from analyze_texture import RECIPES, analyze # noqa: E402
+from analyze_texture import RECIPES, analyze, main # noqa: E402
PNG_SIG = b"\x89PNG\r\n\x1a\n"
@@ -113,6 +115,21 @@ class AnalyzeTextureTest(unittest.TestCase):
for name, rec in RECIPES.items():
self.assertTrue(keys <= set(rec), f"{name} missing keys")
+ def test_patch_target_requires_spec_and_material_id_together(self):
+ for args in (["missing.png", "--spec", "spec.json"], ["missing.png", "--material-id", "frame"]):
+ with self.subTest(args=args), redirect_stderr(io.StringIO()) as stderr:
+ with self.assertRaises(SystemExit) as raised:
+ main(args)
+ self.assertEqual(raised.exception.code, 2)
+ self.assertIn("--spec and --material-id must be used together", stderr.getvalue())
+
+ def test_in_place_requires_patch_target(self):
+ with redirect_stderr(io.StringIO()) as stderr:
+ with self.assertRaises(SystemExit) as raised:
+ main(["missing.png", "--in-place"])
+ self.assertEqual(raised.exception.code, 2)
+ self.assertIn("--in-place requires --spec and --material-id", stderr.getvalue())
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/forge/tests/test_attachment_anchor.py b/forge/tests/test_attachment_anchor.py
new file mode 100644
index 0000000..21402f3
--- /dev/null
+++ b/forge/tests/test_attachment_anchor.py
@@ -0,0 +1,170 @@
+"""Attachment Anchor Gate tests.
+
+One test per check, each built by mutating a single small valid fixture (a body with a
+head/shoulder/upper-back component set, a matching bone rig, and a hat attachment anchored
+to the upper back) so a passing baseline is proven before any failure mode is exercised.
+Two tests reproduce the real hat and charm defects from the module docstring with concrete
+measured positions, to prove ANCHOR_PROXIMITY actually catches them.
+"""
+
+from __future__ import annotations
+
+import copy
+import sys
+import unittest
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))
+
+from attachment_anchor import analyze_attachments # noqa: E402
+
+
+def _tags(errors: list[str]) -> set[str]:
+ return {message.split(":")[0] for message in errors}
+
+
+def _base_spec() -> dict[str, Any]:
+ """A body with head/shoulder/upper-back components, a bone rig, and a hat attachment
+ anchored to `upper-back` (a component, not a bone) with an explicit maxOffset."""
+ return {
+ "componentTree": [
+ {"id": "root", "name": "Body", "role": "body", "parent": None},
+ {"id": "head", "name": "Head", "role": "body", "parent": "root"},
+ {"id": "upper-back", "name": "Upper back", "role": "body", "parent": "root",
+ "dimensions": {"width": 0.6, "height": 0.5, "depth": 0.3}},
+ {"id": "shoulder-l", "name": "Left shoulder", "role": "body", "parent": "upper-back"},
+ {
+ "id": "hat", "name": "Conical hat", "role": "worn", "parent": "root",
+ "attachment": {"anchor": "upper-back", "maxOffset": 0.5},
+ },
+ ],
+ "rig": {
+ "bones": [
+ {"id": "root", "parent": None, "jointPos": [0.0, 0.0, 0.0]},
+ {"id": "spine", "parent": "root", "jointPos": [0.0, 1.0, 0.0]},
+ {"id": "shoulder-l", "parent": "spine", "jointPos": [0.3, 3.829, 0.0]},
+ ],
+ },
+ }
+
+
+class AttachmentAnchorGate(unittest.TestCase):
+ def test_base_fixture_passes(self) -> None:
+ result = analyze_attachments(_base_spec())
+ self.assertEqual(result["errors"], [])
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["attachmentCount"], 1)
+
+ def test_missing_anchor_fires_anchor_declared(self) -> None:
+ spec = copy.deepcopy(_base_spec())
+ hat = next(c for c in spec["componentTree"] if c["id"] == "hat")
+ del hat["attachment"]
+ result = analyze_attachments(spec)
+ self.assertEqual(_tags(result["errors"]), {"ANCHOR_DECLARED"})
+ self.assertFalse(result["passed"])
+
+ def test_dangling_anchor_fires_anchor_resolves(self) -> None:
+ spec = copy.deepcopy(_base_spec())
+ hat = next(c for c in spec["componentTree"] if c["id"] == "hat")
+ hat["attachment"]["anchor"] = "does-not-exist"
+ result = analyze_attachments(spec)
+ self.assertEqual(_tags(result["errors"]), {"ANCHOR_RESOLVES"})
+ self.assertFalse(result["passed"])
+
+ def test_anchor_at_root_fires_anchor_not_root(self) -> None:
+ spec = copy.deepcopy(_base_spec())
+ hat = next(c for c in spec["componentTree"] if c["id"] == "hat")
+ hat["attachment"]["anchor"] = "root"
+ result = analyze_attachments(spec)
+ self.assertEqual(_tags(result["errors"]), {"ANCHOR_NOT_ROOT"})
+ self.assertFalse(result["passed"])
+
+ def test_mutual_anchors_fire_anchor_not_cyclic(self) -> None:
+ spec = copy.deepcopy(_base_spec())
+ spec["componentTree"] += [
+ {
+ "id": "necklace", "name": "Necklace", "role": "worn", "parent": "root",
+ "attachment": {"anchor": "amulet"},
+ },
+ {
+ "id": "amulet", "name": "Amulet", "role": "worn", "parent": "root",
+ "attachment": {"anchor": "necklace"},
+ },
+ ]
+ result = analyze_attachments(spec)
+ # The pre-existing hat attachment is untouched and still valid, so only the new
+ # mutual pair should fire -- proving the check is scoped per attachment, not global.
+ self.assertEqual(_tags(result["errors"]), {"ANCHOR_NOT_CYCLIC"})
+ self.assertFalse(result["passed"])
+
+ def test_hat_regression_anchor_proximity_fires_with_matching_distance(self) -> None:
+ """Reproduces the real defect: shoulder joint at y 3.829, hat measured at y 2.5,
+ against an authored maxOffset of 0.8. The anchor is switched to the shoulder BONE
+ (not the `upper-back` component the base fixture uses), matching how the actual
+ defect was measured against a rig joint."""
+ spec = copy.deepcopy(_base_spec())
+ hat = next(c for c in spec["componentTree"] if c["id"] == "hat")
+ hat["attachment"] = {"anchor": "shoulder-l", "maxOffset": 0.8}
+ measured = {"shoulder-l": [0.3, 3.829, 0.0], "hat": [0.3, 2.5, 0.0]}
+ result = analyze_attachments(spec, measured=measured)
+ self.assertEqual(_tags(result["errors"]), {"ANCHOR_PROXIMITY"})
+ self.assertFalse(result["passed"])
+ record = next(r for r in result["attachments"] if r["component"] == "hat")
+ expected_distance = abs(3.829 - 2.5)
+ self.assertAlmostEqual(record["distance"], expected_distance, places=9)
+ self.assertEqual(record["maxOffset"], 0.8)
+ self.assertFalse(record["withinLimit"])
+
+ def test_charm_regression_anchor_proximity_fires_with_default_offset(self) -> None:
+ """Reproduces the detached-charm defect: no maxOffset was ever authored, so the
+ gate must derive one from the staff's own declared size (a thin 0.1-wide anchor)
+ and still catch a real 0.389 detachment against that default."""
+ spec = copy.deepcopy(_base_spec())
+ spec["componentTree"] += [
+ {"id": "staff", "name": "Staff", "role": "body", "parent": "root",
+ "dimensions": {"radius": 0.05}},
+ {
+ "id": "charm", "name": "Charm", "role": "held", "parent": "root",
+ "attachment": {"anchor": "staff"},
+ },
+ ]
+ measured = {"staff": [0.0, 0.0, 0.0], "charm": [0.0, 0.0, 0.389]}
+ result = analyze_attachments(spec, measured=measured)
+ charm_errors = {m for m in result["errors"] if "charm" in m}
+ self.assertTrue(any(m.startswith("ANCHOR_PROXIMITY") for m in charm_errors))
+ record = next(r for r in result["attachments"] if r["component"] == "charm")
+ self.assertAlmostEqual(record["distance"], 0.389, places=9)
+ # extent = radius * 2 = 0.1; default limit = 0.1 * 0.25 = 0.025, well under 0.389
+ self.assertAlmostEqual(record["maxOffset"], 0.025, places=9)
+ self.assertIn("default", record["offsetRule"])
+ self.assertFalse(record["withinLimit"])
+
+ def test_no_attachments_passes_and_reports_zero_count(self) -> None:
+ spec = copy.deepcopy(_base_spec())
+ spec["componentTree"] = [c for c in spec["componentTree"] if c["id"] != "hat"]
+ result = analyze_attachments(spec)
+ self.assertEqual(result["errors"], [])
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["attachmentCount"], 0)
+ self.assertEqual(result["unmeasuredAttachments"], [])
+
+ def test_component_absent_from_measured_lands_in_unmeasured(self) -> None:
+ spec = _base_spec()
+ # `measured` is supplied (so ANCHOR_PROXIMITY is in scope) but omits the hat itself --
+ # this must not be silently treated as a pass, distinguishing it from the
+ # zero-attachments case above (attachmentCount 1 here, not 0).
+ result = analyze_attachments(spec, measured={"upper-back": [0.0, 3.0, 0.0]})
+ self.assertEqual(result["attachmentCount"], 1)
+ self.assertEqual(result["unmeasuredAttachments"], ["hat"])
+ record = next(r for r in result["attachments"] if r["component"] == "hat")
+ self.assertIsNone(record["withinLimit"])
+ self.assertIsNone(record["distance"])
+ self.assertTrue(any("hat" in w and "ANCHOR_PROXIMITY" in w for w in result["warnings"]))
+ # Missing measurement is a visibility gap, not a structural defect, so it alone
+ # must not flip the gate to failing.
+ self.assertTrue(result["passed"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_camera_fitting.py b/forge/tests/test_camera_fitting.py
new file mode 100644
index 0000000..d97a97c
--- /dev/null
+++ b/forge/tests/test_camera_fitting.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""Contract tests for deterministic landmark camera fitting."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from dataclasses import dataclass
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from forge.stage1_intake import solve_camera_pose as camera_fit # noqa: E402
+from forge.stage1_intake import camera_fitting_types as camera_types # noqa: E402
+from forge.stage1_intake import camera_image_helpers as image_helpers # noqa: E402
+from forge.stage1_intake.camera_fitting_types import Point2, Point3 # noqa: E402
+
+
+@dataclass(frozen=True, slots=True)
+class FixtureCamera:
+ image_width: int
+ image_height: int
+ fov_degrees: float
+ yaw_degrees: float
+ pitch_degrees: float
+ roll_degrees: float
+ position: Point3
+
+
+@dataclass(frozen=True, slots=True)
+class FixtureCorrespondence:
+ name: str
+ world: Point3
+ observed: Point2
+
+
+@dataclass(frozen=True, slots=True)
+class KnownCameraCase:
+ true_camera: FixtureCamera
+ initial_camera: FixtureCamera
+ correspondences: tuple[FixtureCorrespondence, ...]
+
+
+WORLD_POINTS: tuple[Point3, ...] = (
+ (-0.55, -0.35, -0.20),
+ (0.45, -0.40, 0.10),
+ (-0.50, 0.35, 0.05),
+ (0.60, 0.30, -0.15),
+ (-0.15, -0.10, 0.45),
+ (0.25, 0.15, 0.35),
+ (-0.35, 0.05, -0.45),
+ (0.35, -0.15, -0.35),
+)
+
+GOLDEN_OBSERVATIONS: tuple[Point2, ...] = (
+ (578.7401654634278, 379.751871427244),
+ (808.3724977028866, 389.4016539586094),
+ (574.4757073869129, 218.67838466422444),
+ (833.1143917536056, 222.48567412558583),
+ (654.6053614640265, 323.6375569741955),
+ (757.573458961317, 254.25311289570504),
+ (624.651608536512, 290.53788687932575),
+ (775.5907395975036, 327.4459034756644),
+)
+
+def make_known_camera_case() -> KnownCameraCase:
+ true_camera = FixtureCamera(
+ image_width=1280,
+ image_height=720,
+ fov_degrees=42.0,
+ yaw_degrees=5.0,
+ pitch_degrees=-3.0,
+ roll_degrees=2.0,
+ position=(0.10, -0.05, 4.00),
+ )
+ initial_camera = FixtureCamera(
+ image_width=true_camera.image_width,
+ image_height=true_camera.image_height,
+ fov_degrees=40.0,
+ yaw_degrees=4.0,
+ pitch_degrees=-2.0,
+ roll_degrees=1.0,
+ position=(0.05, -0.02, 3.80),
+ )
+ correspondences = tuple(
+ FixtureCorrespondence(f"point-{index}", point, GOLDEN_OBSERVATIONS[index])
+ for index, point in enumerate(WORLD_POINTS)
+ )
+ return KnownCameraCase(true_camera, initial_camera, correspondences)
+
+
+class CameraFittingContractTest(unittest.TestCase):
+ def test_known_camera_converges_with_low_reprojection_error(self):
+ case = make_known_camera_case()
+
+ descriptor = camera_fit.fit_camera_to_correspondences(
+ case.correspondences,
+ initial_camera=case.initial_camera,
+ )
+
+ fit = descriptor["fit"]
+ self.assertEqual(fit["convergence"]["status"], "converged")
+ self.assertLess(fit["finalReprojectionError"], 1e-4)
+ self.assertLess(fit["finalReprojectionError"], fit["initialReprojectionError"])
+ parameters = fit["cameraParameters"]
+ self.assertAlmostEqual(parameters["fovDegrees"], case.true_camera.fov_degrees, delta=1e-5)
+ self.assertAlmostEqual(parameters["yawDegrees"], case.true_camera.yaw_degrees, delta=1e-5)
+ self.assertAlmostEqual(parameters["pitchDegrees"], case.true_camera.pitch_degrees, delta=1e-5)
+ self.assertAlmostEqual(parameters["rollDegrees"], case.true_camera.roll_degrees, delta=1e-5)
+ for actual, expected in zip(parameters["position"], case.true_camera.position, strict=True):
+ self.assertAlmostEqual(actual, expected, delta=1e-6)
+ self.assertEqual([item["name"] for item in fit["residuals"]], [item.name for item in case.correspondences])
+ for residual in fit["residuals"]:
+ self.assertLess(residual["errorPixels"], 1e-4)
+
+ def test_camera_fit_output_is_deterministic(self):
+ case = make_known_camera_case()
+
+ first = camera_fit.fit_camera_to_correspondences(case.correspondences, initial_camera=case.initial_camera)
+ second = camera_fit.fit_camera_to_correspondences(case.correspondences, initial_camera=case.initial_camera)
+
+ self.assertEqual(first, second)
+
+ def test_public_compatibility_exports_remain_available(self):
+ exported_names = {
+ "CONVERGED_RMS_PIXELS",
+ "FINITE_DIFFERENCE_STEPS",
+ "INITIAL_DAMPING",
+ "MAXIMUM_DAMPING",
+ "MAXIMUM_DAMPING_RETRIES",
+ "MAXIMUM_FOV_DEGREES",
+ "MAXIMUM_ITERATIONS",
+ "MINIMUM_CAMERA_DEPTH",
+ "MINIMUM_CORRESPONDENCES",
+ "MINIMUM_FOV_DEGREES",
+ "CameraFitDescriptor",
+ "CameraInitialization",
+ "DegenerateCorrespondencesError",
+ "InsufficientCorrespondencesError",
+ "InvalidCameraDimensionsError",
+ "InvalidInitialCameraError",
+ "LandmarkCorrespondence",
+ "NonFiniteCameraInputError",
+ "bmp_size",
+ "build_camera",
+ "clamp",
+ "detect_size",
+ "estimate_fov",
+ "fit_camera_to_correspondences",
+ "gif_size",
+ "jpeg_size",
+ "main",
+ "png_size",
+ "webp_size",
+ }
+
+ self.assertLessEqual(exported_names, set(camera_fit.__all__))
+ identity_exports = {
+ "CONVERGED_RMS_PIXELS": camera_types.CONVERGED_RMS_PIXELS,
+ "FINITE_DIFFERENCE_STEPS": camera_types.FINITE_DIFFERENCE_STEPS,
+ "INITIAL_DAMPING": camera_types.INITIAL_DAMPING,
+ "MAXIMUM_DAMPING": camera_types.MAXIMUM_DAMPING,
+ "MAXIMUM_FOV_DEGREES": camera_types.MAXIMUM_FOV_DEGREES,
+ "MINIMUM_CAMERA_DEPTH": camera_types.MINIMUM_CAMERA_DEPTH,
+ "MINIMUM_CORRESPONDENCES": camera_types.MINIMUM_CORRESPONDENCES,
+ "MINIMUM_FOV_DEGREES": camera_types.MINIMUM_FOV_DEGREES,
+ "CameraFitDescriptor": camera_types.CameraFitDescriptor,
+ "CameraInitialization": camera_types.CameraInitialization,
+ "DegenerateCorrespondencesError": camera_types.DegenerateCorrespondencesError,
+ "InsufficientCorrespondencesError": camera_types.InsufficientCorrespondencesError,
+ "InvalidCameraDimensionsError": camera_types.InvalidCameraDimensionsError,
+ "InvalidInitialCameraError": camera_types.InvalidInitialCameraError,
+ "LandmarkCorrespondence": camera_types.LandmarkCorrespondence,
+ "NonFiniteCameraInputError": camera_types.NonFiniteCameraInputError,
+ "bmp_size": image_helpers.bmp_size,
+ "build_camera": image_helpers.build_camera,
+ "clamp": image_helpers.clamp,
+ "detect_size": image_helpers.detect_size,
+ "estimate_fov": image_helpers.estimate_fov,
+ "gif_size": image_helpers.gif_size,
+ "jpeg_size": image_helpers.jpeg_size,
+ "png_size": image_helpers.png_size,
+ "webp_size": image_helpers.webp_size,
+ }
+ for name, expected in identity_exports.items():
+ self.assertIs(getattr(camera_fit, name), expected, name)
+ for name in ("build_camera", "detect_size", "estimate_fov", "fit_camera_to_correspondences", "main", "png_size"):
+ self.assertTrue(callable(getattr(camera_fit, name)), name)
+
+ def test_solver_termination_is_bounded_by_public_limits(self):
+ case = make_known_camera_case()
+ previous_iterations = camera_fit.MAXIMUM_ITERATIONS
+ previous_retries = camera_fit.MAXIMUM_DAMPING_RETRIES
+ camera_fit.MAXIMUM_ITERATIONS = 1
+ camera_fit.MAXIMUM_DAMPING_RETRIES = 1
+ try:
+ descriptor = camera_fit.fit_camera_to_correspondences(
+ case.correspondences,
+ initial_camera=case.initial_camera,
+ )
+ finally:
+ camera_fit.MAXIMUM_ITERATIONS = previous_iterations
+ camera_fit.MAXIMUM_DAMPING_RETRIES = previous_retries
+
+ convergence = descriptor["fit"]["convergence"]
+ self.assertLessEqual(convergence["iterations"], 1)
+ self.assertLessEqual(convergence["acceptedSteps"] + convergence["rejectedSteps"], 1)
+ self.assertIn(convergence["status"], {"converged", "stalled", "max-iterations"})
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_camera_fitting_cli.py b/forge/tests/test_camera_fitting_cli.py
new file mode 100644
index 0000000..0304a0e
--- /dev/null
+++ b/forge/tests/test_camera_fitting_cli.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Legacy CLI schema regression tests for camera fitting."""
+
+from __future__ import annotations
+
+import io
+import json
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from forge.stage1_intake import solve_camera_pose as camera_fit # noqa: E402
+
+
+MINIMAL_PNG_BYTES = (
+ b"\x89PNG\r\n\x1a\n"
+ b"\x00\x00\x00\rIHDR"
+ b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00"
+ b"\x90wS\xde"
+ b"\x00\x00\x00\x0cIDAT\x08\xd7c\xf8\xff\xff?\x00\x05\xfe\x02\xfeA\xbf\xb6\xcc"
+ b"\x00\x00\x00\x00IEND\xaeB`\x82"
+)
+
+
+class CameraFittingCliTest(unittest.TestCase):
+ def test_legacy_cli_emits_descriptor_and_writes_matching_out_file(self):
+ with tempfile.TemporaryDirectory() as directory:
+ image = Path(directory) / "reference.png"
+ out = Path(directory) / "camera.json"
+ image.write_bytes(MINIMAL_PNG_BYTES)
+ stdout = io.StringIO()
+
+ with redirect_stdout(stdout):
+ result = camera_fit.main([str(image), "--out", str(out)])
+
+ self.assertEqual(result, 0)
+ self.assertEqual(out.read_text(encoding="utf-8"), stdout.getvalue())
+ payload = json.loads(stdout.getvalue())
+ self.assertEqual(set(payload), {"referenceCamera"})
+ descriptor = payload["referenceCamera"]
+ self.assertEqual(
+ set(descriptor),
+ {
+ "version",
+ "sourceImage",
+ "solver",
+ "method",
+ "imageWidth",
+ "imageHeight",
+ "fovDegrees",
+ "aspect",
+ "orientation",
+ "position",
+ "confidence",
+ "limitations",
+ "note",
+ },
+ )
+ self.assertEqual(descriptor["version"], "1.0")
+ self.assertIsInstance(descriptor["sourceImage"], str)
+ self.assertEqual(Path(descriptor["sourceImage"]), image.resolve())
+ self.assertEqual(descriptor["solver"], "stage1_intake/solve_camera_pose.py")
+ self.assertEqual(descriptor["method"], "heuristic default-guess camera, not solved from image content; image dimensions give an exact aspect ratio, everything else is a starting point for agent refinement")
+ self.assertEqual(descriptor["imageWidth"], 1)
+ self.assertEqual(descriptor["imageHeight"], 1)
+ self.assertEqual(set(descriptor["fovDegrees"]), {"value", "source", "agentFill", "rationale"})
+ self.assertIsInstance(descriptor["fovDegrees"]["rationale"], str)
+ self.assertEqual(descriptor["fovDegrees"]["source"], "default-guess")
+ self.assertIs(descriptor["fovDegrees"]["agentFill"], True)
+ self.assertEqual(set(descriptor["aspect"]), {"value", "source", "agentFill"})
+ self.assertEqual(descriptor["aspect"], {"value": 1.0, "source": "image-dimensions", "agentFill": False})
+ self.assertEqual(descriptor["fovDegrees"]["value"], 35.0)
+ self.assertEqual(set(descriptor["orientation"]), {"yawDegrees", "pitchDegrees", "rollDegrees", "note"})
+ self.assertIsInstance(descriptor["orientation"]["note"], str)
+ for scalar_name in ("yawDegrees", "pitchDegrees", "rollDegrees"):
+ scalar = descriptor["orientation"][scalar_name]
+ self.assertEqual(set(scalar), {"value", "source", "agentFill"})
+ self.assertIsInstance(scalar["value"], float)
+ self.assertEqual(scalar["source"], "placeholder")
+ self.assertIs(scalar["agentFill"], True)
+ self.assertEqual(set(descriptor["position"]), {"hint", "distance", "note"})
+ self.assertIsInstance(descriptor["position"]["note"], str)
+ self.assertEqual(descriptor["position"]["hint"], [0.0, 0.0, 2.5])
+ self.assertEqual(set(descriptor["position"]["distance"]), {"value", "source", "agentFill"})
+ self.assertEqual(descriptor["position"]["distance"], {"value": 2.5, "source": "placeholder", "agentFill": True})
+ self.assertIsInstance(descriptor["confidence"], float)
+ self.assertIsInstance(descriptor["limitations"], list)
+ self.assertTrue(descriptor["limitations"])
+ for limitation in descriptor["limitations"]:
+ self.assertIsInstance(limitation, str)
+ self.assertIsInstance(descriptor["note"], str)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_camera_fitting_safety.py b/forge/tests/test_camera_fitting_safety.py
new file mode 100644
index 0000000..dc02f31
--- /dev/null
+++ b/forge/tests/test_camera_fitting_safety.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Safety contracts for camera-fitting input validation."""
+
+from __future__ import annotations
+
+import math
+import sys
+import unittest
+from dataclasses import dataclass
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from forge.stage1_intake import solve_camera_pose as camera_fit # noqa: E402
+from forge.stage1_intake.camera_fitting_types import Point2, Point3 # noqa: E402
+
+
+@dataclass(frozen=True, slots=True)
+class FixtureCamera:
+ image_width: int
+ image_height: int
+ fov_degrees: float
+ yaw_degrees: float
+ pitch_degrees: float
+ roll_degrees: float
+ position: Point3
+
+
+@dataclass(frozen=True, slots=True)
+class FixtureCorrespondence:
+ name: str
+ world: Point3
+ observed: Point2
+
+
+WORLD_POINTS: tuple[Point3, ...] = (
+ (-0.55, -0.35, -0.20),
+ (0.45, -0.40, 0.10),
+ (-0.50, 0.35, 0.05),
+ (0.60, 0.30, -0.15),
+ (-0.15, -0.10, 0.45),
+ (0.25, 0.15, 0.35),
+)
+
+OBSERVED_POINTS: tuple[Point2, ...] = (
+ (260.0, 280.0),
+ (390.0, 285.0),
+ (265.0, 185.0),
+ (405.0, 190.0),
+ (325.0, 250.0),
+ (370.0, 220.0),
+)
+
+
+def base_camera() -> FixtureCamera:
+ return FixtureCamera(
+ image_width=640,
+ image_height=480,
+ fov_degrees=38.0,
+ yaw_degrees=1.0,
+ pitch_degrees=-2.0,
+ roll_degrees=0.5,
+ position=(0.05, -0.05, 3.50),
+ )
+
+
+def base_correspondences() -> tuple[FixtureCorrespondence, ...]:
+ return tuple(
+ FixtureCorrespondence(f"point-{index}", point, OBSERVED_POINTS[index])
+ for index, point in enumerate(WORLD_POINTS)
+ )
+
+
+def camera_with_dimensions(image_width: int, image_height: int) -> FixtureCamera:
+ camera = base_camera()
+ return FixtureCamera(
+ image_width=image_width,
+ image_height=image_height,
+ fov_degrees=camera.fov_degrees,
+ yaw_degrees=camera.yaw_degrees,
+ pitch_degrees=camera.pitch_degrees,
+ roll_degrees=camera.roll_degrees,
+ position=camera.position,
+ )
+
+
+class CameraFittingSafetyTest(unittest.TestCase):
+ def test_rejects_fewer_than_six_correspondences(self):
+ correspondences = base_correspondences()[:5]
+
+ with self.assertRaises(camera_fit.InsufficientCorrespondencesError) as raised:
+ camera_fit.fit_camera_to_correspondences(correspondences, initial_camera=base_camera())
+
+ self.assertEqual(raised.exception.required, camera_fit.MINIMUM_CORRESPONDENCES)
+ self.assertEqual(raised.exception.actual, 5)
+
+ def test_rejects_degenerate_world_landmarks(self):
+ correspondences = tuple(
+ FixtureCorrespondence(f"line-{index}", (float(index), 0.0, 0.0), (100.0 + index, 200.0))
+ for index in range(camera_fit.MINIMUM_CORRESPONDENCES)
+ )
+
+ with self.assertRaises(camera_fit.DegenerateCorrespondencesError) as raised:
+ camera_fit.fit_camera_to_correspondences(correspondences, initial_camera=base_camera())
+
+ self.assertEqual(raised.exception.correspondence_count, camera_fit.MINIMUM_CORRESPONDENCES)
+
+ def test_rejects_non_finite_correspondence_inputs(self):
+ correspondences = list(base_correspondences())
+ first = correspondences[0]
+ correspondences[0] = FixtureCorrespondence(first.name, first.world, (math.nan, first.observed[1]))
+
+ with self.assertRaises(camera_fit.NonFiniteCameraInputError) as raised:
+ camera_fit.fit_camera_to_correspondences(tuple(correspondences), initial_camera=base_camera())
+
+ self.assertEqual(raised.exception.field, "correspondences[0].observed[0]")
+
+ def test_rejects_non_finite_initial_camera_inputs(self):
+ camera = base_camera()
+ initial_camera = FixtureCamera(
+ image_width=camera.image_width,
+ image_height=camera.image_height,
+ fov_degrees=math.inf,
+ yaw_degrees=camera.yaw_degrees,
+ pitch_degrees=camera.pitch_degrees,
+ roll_degrees=camera.roll_degrees,
+ position=camera.position,
+ )
+
+ with self.assertRaises(camera_fit.NonFiniteCameraInputError) as raised:
+ camera_fit.fit_camera_to_correspondences(base_correspondences(), initial_camera=initial_camera)
+
+ self.assertEqual(raised.exception.field, "initial_camera.fov_degrees")
+
+ def test_rejects_invalid_image_dimensions(self):
+ with self.assertRaises(camera_fit.InvalidCameraDimensionsError) as raised:
+ camera_fit.fit_camera_to_correspondences(
+ base_correspondences(),
+ initial_camera=camera_with_dimensions(0, 480),
+ )
+
+ self.assertEqual(raised.exception.image_width, 0)
+ self.assertEqual(raised.exception.image_height, 480)
+
+ def test_rejects_non_projectable_initial_camera(self):
+ camera = base_camera()
+ initial_camera = FixtureCamera(
+ image_width=camera.image_width,
+ image_height=camera.image_height,
+ fov_degrees=camera.fov_degrees,
+ yaw_degrees=camera.yaw_degrees,
+ pitch_degrees=camera.pitch_degrees,
+ roll_degrees=camera.roll_degrees,
+ position=(0.0, 0.0, -2.0),
+ )
+
+ with self.assertRaises(camera_fit.InvalidInitialCameraError) as raised:
+ camera_fit.fit_camera_to_correspondences(base_correspondences(), initial_camera=initial_camera)
+
+ self.assertEqual(raised.exception.correspondence_name, "point-0")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_character_rig_derivation.py b/forge/tests/test_character_rig_derivation.py
new file mode 100644
index 0000000..d848366
--- /dev/null
+++ b/forge/tests/test_character_rig_derivation.py
@@ -0,0 +1,203 @@
+"""The character rig is DERIVED from the component tree (PLAN_1.5 WS-A, spec half).
+
+These tests pin the defects that were actually found while building it, not just the happy
+path. The load-bearing one is `test_spine_bones_point_upward`: the first implementation read
+each bone's segment from `attachment.localStart`/`localEnd`, which is correct for a limb --
+whose component origin IS its proximal joint -- and wrong for the torso, whose origin is its
+centre. That produced a spine bone running from the chest DOWN to the neck attach point: a
+2 cm stub pointing the wrong way, which would have pulled leg vertices onto the torso's
+weight during skinning. Nothing else in the suite would have noticed.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+_FORGE = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(_FORGE))
+sys.path.insert(0, str(_FORGE / "stage2_spec"))
+
+from new_sculpt_spec import ( # noqa: E402
+ apply_character_pose,
+ derive_character_rig,
+ make_character_component_tree,
+)
+from stage5_rig.rig_spec import BoneSpec, RigSpec, validate_rig_spec # noqa: E402
+
+# The spine is five segments since US-001 split the single `torso` into abdomen + chest so the
+# figure can bend at the waist. Listing them in order means the contiguity test below checks
+# four joins instead of three.
+SPINE = ("pelvis", "abdomen", "chest", "neck", "head")
+
+
+def _as_rig_spec(rig: dict) -> RigSpec:
+ return RigSpec(
+ version=rig["version"],
+ bind_pose=rig["bindPose"],
+ forward=rig["forward"],
+ bones=[
+ BoneSpec(
+ id=b["id"],
+ parent=b["parent"],
+ joint_pos=tuple(b["jointPos"]),
+ component=b["component"],
+ role=b["role"],
+ chain=b["chain"],
+ tip_pos=tuple(b["tipPos"]),
+ )
+ for b in rig["bones"]
+ ],
+ )
+
+
+def _length(bone: BoneSpec) -> float:
+ return sum((bone.tip_pos[i] - bone.joint_pos[i]) ** 2 for i in range(3)) ** 0.5
+
+
+class CharacterRigDerivation(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.rig = derive_character_rig(make_character_component_tree())
+ cls.spec = _as_rig_spec(cls.rig)
+ cls.by_id = {b.id: b for b in cls.spec.bones}
+
+ def test_derived_rig_satisfies_the_rig_spec_gate(self) -> None:
+ self.assertEqual(validate_rig_spec(self.spec), [])
+
+ def test_single_root_is_the_pelvis(self) -> None:
+ """Hips-as-root, and since US-001 it needs no special case at all.
+
+ The spine used to be a single `torso` parented to "root" alongside the pelvis, so the
+ derivation had to pick one of two siblings as the bone root by hand. Now `abdomen` is
+ parented to `pelvis`, so the pelvis is the only root-parented body part and falls out of
+ the tree walk on its own.
+ """
+ self.assertEqual(self.spec.root().id, "pelvis")
+
+ def test_spine_bones_point_upward(self) -> None:
+ """The defect this whole module exists for. A spine bone whose tip sits BELOW its
+ joint is pointing at the floor."""
+ for bone_id in SPINE:
+ bone = self.by_id[bone_id]
+ self.assertGreater(
+ bone.tip_pos[1],
+ bone.joint_pos[1],
+ f"spine bone {bone_id!r} points DOWN: joint.y={bone.joint_pos[1]} "
+ f"tip.y={bone.tip_pos[1]} -- its joint must be its PROXIMAL end",
+ )
+
+ def test_spine_chain_is_contiguous(self) -> None:
+ """Each spine bone starts where its parent ended. Limb branch points legitimately do
+ NOT (a thigh leaves the pelvis at the hip socket, not at the spine's tip), so this is
+ asserted for the spine only rather than for every bone."""
+ for child, parent in zip(SPINE[1:], SPINE[:-1]):
+ gap = sum(
+ (self.by_id[child].joint_pos[i] - self.by_id[parent].tip_pos[i]) ** 2
+ for i in range(3)
+ ) ** 0.5
+ self.assertLess(gap, 1e-6, f"{parent} -> {child} leaves a {gap:.5f} gap")
+
+ def test_no_bone_is_degenerate(self) -> None:
+ degenerate = [b.id for b in self.spec.bones if _length(b) < 1e-6]
+ self.assertEqual(degenerate, [], f"zero-length bones cannot be posed: {degenerate}")
+
+ def test_limb_chains_are_fully_linked_per_side(self) -> None:
+ """Arms are four deep since US-002 added a clavicle; legs remain three."""
+ for chain in (
+ ("clavicle-l", "upper-arm-l", "forearm-l", "hand-l"),
+ ("clavicle-r", "upper-arm-r", "forearm-r", "hand-r"),
+ ("thigh-l", "shin-l", "foot-l"),
+ ("thigh-r", "shin-r", "foot-r"),
+ ):
+ for parent, child in zip(chain, chain[1:]):
+ self.assertEqual(self.by_id[child].parent, parent,
+ f"{child} should hang off {parent}")
+
+ def test_clavicles_are_arm_chain_bones_rooted_on_the_chest(self) -> None:
+ for side in ("l", "r"):
+ bone = self.by_id[f"clavicle-{side}"]
+ self.assertEqual(bone.parent, "chest")
+ self.assertEqual(bone.chain, "arm")
+ self.assertGreater(_length(bone), 1e-6)
+
+ def test_details_are_not_bones(self) -> None:
+ """A brow does not articulate. Only body segments become bones, so a detail riding
+ its parent must never acquire one."""
+ for detail in ("brow-l", "nose", "mouth", "hair", "eye-l", "eye-cavity-l",
+ "ear-l", "ear-r"):
+ self.assertNotIn(detail, self.by_id)
+
+ def test_left_and_right_limbs_are_mirrored_in_x(self) -> None:
+ for left, right in (("upper-arm-l", "upper-arm-r"), ("thigh-l", "thigh-r")):
+ self.assertAlmostEqual(
+ self.by_id[left].joint_pos[0], -self.by_id[right].joint_pos[0], places=5
+ )
+
+
+class CharacterPoseApplication(unittest.TestCase):
+ """`anatomy.pose.jointAngles` was declared in two places and consumed in none until now.
+
+ Posing a hierarchy of RIGID segments needs no skeleton — only a parent chain that
+ propagates rotation, which the template has. So these tests also pin the claim that a
+ reference pose is reachable without skinning.
+ """
+
+ POSE = {
+ "pose": {
+ "type": "contrapposto",
+ "jointAngles": {
+ "neck": [0.0, 0.22, 0.05],
+ "rightShoulder": [-0.35, 0.0, 0.30],
+ "leftElbow": [-0.30, 0.0, -0.55],
+ "leftHip": [0.0, 0.0, -0.08],
+ },
+ }
+ }
+
+ def test_no_anatomy_applies_no_pose(self) -> None:
+ tree = make_character_component_tree()
+ self.assertEqual(apply_character_pose(tree, None), [])
+ for component in tree:
+ rotation = (component.get("transform") or {}).get("rotation") or [0, 0, 0]
+ if component["id"] != "nose": # the one authored rotation in the template
+ self.assertTrue(all(abs(float(v)) < 1e-9 for v in rotation), component["id"])
+
+ def test_joint_angles_land_on_the_anatomically_correct_components(self) -> None:
+ """"left" is the CHARACTER's left, which the tree spells `-l` — on a front-facing
+ reference that is the viewer's right. Getting this backwards mirrors the pose."""
+ tree = make_character_component_tree()
+ applied = apply_character_pose(tree, self.POSE)
+ self.assertEqual(len(applied), 4)
+ by_id = {c["id"]: c for c in tree}
+ self.assertEqual(by_id["neck"]["transform"]["rotation"], [0.0, 0.22, 0.05])
+ self.assertEqual(by_id["upper-arm-r"]["transform"]["rotation"], [-0.35, 0.0, 0.30])
+ self.assertEqual(by_id["forearm-l"]["transform"]["rotation"], [-0.30, 0.0, -0.55])
+ self.assertEqual(by_id["thigh-l"]["transform"]["rotation"], [0.0, 0.0, -0.08])
+
+ def test_rig_is_derived_at_bind_pose_not_posed(self) -> None:
+ """A skeleton is bind-pose data. Derive first, pose second."""
+ tree = make_character_component_tree()
+ rig = derive_character_rig(tree)
+ chest_before = [b for b in rig["bones"] if b["id"] == "chest"][0]["jointPos"]
+ apply_character_pose(tree, self.POSE)
+ rig_again = derive_character_rig(make_character_component_tree())
+ chest_after = [b for b in rig_again["bones"] if b["id"] == "chest"][0]["jointPos"]
+ self.assertEqual(chest_before, chest_after)
+
+ def test_deriving_a_rig_from_a_posed_tree_fails_closed(self) -> None:
+ """The precondition behind `model_pos` — summing parent-local offsets is only valid
+ while every ancestor rotation is identity. Violating it silently would move every
+ descendant joint with nothing failing, so it raises instead."""
+ tree = make_character_component_tree()
+ apply_character_pose(tree, self.POSE)
+ with self.assertRaises(ValueError) as caught:
+ derive_character_rig(tree)
+ self.assertIn("bind pose", str(caught.exception))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_correction_loop.py b/forge/tests/test_correction_loop.py
index d1be4ab..844d1b1 100644
--- a/forge/tests/test_correction_loop.py
+++ b/forge/tests/test_correction_loop.py
@@ -5,22 +5,31 @@ Pure stdlib unittest. The termination guarantee (test_hard_ceiling_always_termin
and test_loop_cannot_exceed_max_iter) is the load-bearing property of this suite.
"""
+import io
+import json
+import math
import os
import sys
+import tempfile
import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "stage4_review"))
-from correction_loop import budget_exceeded, decide # noqa: E402
+from correction_loop import budget_exceeded, decide, main # noqa: E402
-def _it(fidelity, defect_tags=None, reverted=False):
+def _it(fidelity, defect_tags=None, reverted=False, hard_gate_failures=None):
"""Build one iteration record."""
- return {
+ record = {
"fidelity": fidelity,
"defectTags": list(defect_tags or []),
"reverted": reverted,
}
+ if hard_gate_failures is not None:
+ record["hardGateFailures"] = list(hard_gate_failures)
+ return record
class CorrectionLoopTest(unittest.TestCase):
@@ -40,6 +49,135 @@ class CorrectionLoopTest(unittest.TestCase):
d = decide([_it(0.95, ["visible-seam"])])
self.assertNotEqual(d["action"], "continue")
+ def test_success_requires_no_hard_gate_failures(self):
+ d = decide([_it(0.95, [], hard_gate_failures=["scale"])])
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "refine-code")
+ self.assertIn("hard gate", d["reason"])
+
+ def test_pending_review_blocks_success_and_preserves_routing(self):
+ cases = (("probe", "low-confidence", "request-input"), ("refine-code", "reject", "refine-code"), ("refine-spec", "withhold", "refine-spec"), ("continue", "reject", "request-input"))
+ for action, verdict, expected_action in cases:
+ with self.subTest(action=action, verdict=verdict):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "pendingReview": True, "divineEyeAction": action, "divineEyeVerdict": verdict}]
+ d = decide(history)
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], expected_action)
+ self.assertIn("pending Divine Eye review", d["reason"])
+
+ def test_non_approved_routing_overrides_forged_pending_false(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "pendingReview": False, "divineEyeAction": "probe", "divineEyeVerdict": "low-confidence"}]
+
+ d = decide(history)
+
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "request-input")
+
+ def test_nested_divine_eye_provenance_drives_pending_routing(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "divineEye": {"fidelity": 0.95, "action": "probe", "verdict": "low-confidence"}}]
+
+ d = decide(history)
+
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "request-input")
+
+ def test_nested_divine_eye_rejects_tampered_top_level_routing(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "pendingReview": False, "divineEye": {"fidelity": 0.95, "action": "probe", "verdict": "low-confidence"}}]
+
+ with self.assertRaises(ValueError) as raised:
+ decide(history)
+
+ self.assertIn("pendingReview conflicts", str(raised.exception))
+
+ def test_nested_divine_eye_rejects_tampered_top_level_fidelity(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "divineEye": {"fidelity": 0.5}}]
+
+ with self.assertRaises(ValueError) as raised:
+ decide(history)
+
+ self.assertIn("fidelity conflicts", str(raised.exception))
+
+ def test_decide_rejects_invalid_configuration_and_history_records(self):
+ valid_history = [_it(0.9, [])]
+ cases = (
+ ([], {"target_fidelity": math.nan}, "target_fidelity"),
+ ([], {"max_iter": True}, "max_iter"),
+ ([], {"max_iter": 1.5}, "max_iter"),
+ ([], {"min_delta": math.nan}, "min_delta"),
+ ([], {"min_delta": -0.1}, "min_delta"),
+ ([{"fidelity": math.nan, "defectTags": [], "reverted": False}], {}, "history[0].fidelity"),
+ ([{"fidelity": 0.9, "defectTags": [1], "reverted": False}], {}, "history[0].defectTags"),
+ ([{"fidelity": 0.9, "defectTags": [], "hardGateFailures": [1], "reverted": False}], {}, "history[0].hardGateFailures"),
+ ([{"fidelity": 0.9, "defectTags": [], "pendingReview": 1, "reverted": False}], {}, "history[0].pendingReview"),
+ ([{"fidelity": 0.9, "defectTags": [], "divineEyeAction": 1, "reverted": False}], {}, "history[0].divineEyeAction"),
+ ([{"fidelity": 0.9, "defectTags": [], "divineEyeVerdict": 1, "reverted": False}], {}, "history[0].divineEyeVerdict"),
+ ([{"fidelity": 0.9, "defectTags": [], "reverted": 1}], {}, "history[0].reverted"),
+ )
+ self.assertEqual(decide(valid_history)["action"], "continue")
+ for history, options, field in cases:
+ with self.subTest(field=field):
+ with self.assertRaises(ValueError) as raised:
+ decide(history, **options)
+ self.assertIn(field, str(raised.exception))
+
+ def test_cli_rejects_invalid_configuration_and_history_without_traceback(self):
+ cases = (
+ ({"history": [_it(0.9, [])]}, ["--target", "nan"], "target"),
+ ({"history": [_it(0.9, [])]}, ["--max-iter", "0"], "max_iter"),
+ ({"history": [_it(0.9, [])]}, ["--min-delta", "-0.1"], "min_delta"),
+ ({"history": [{"fidelity": 1.1, "defectTags": [], "reverted": False}]}, [], "history[0].fidelity"),
+ ({"history": [{"fidelity": 0.9, "defectTags": ["ok", 1], "reverted": False}]}, [], "history[0].defectTags"),
+ ({"history": [{"fidelity": 0.9, "defectTags": [], "hardGateFailures": [1], "reverted": False}]}, [], "history[0].hardGateFailures"),
+ ({"history": [{"fidelity": 0.9, "defectTags": [], "reverted": 1}]}, [], "history[0].reverted"),
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ for index, (payload, options, field) in enumerate(cases):
+ with self.subTest(field=field):
+ history_path = Path(directory) / f"invalid-{index}.json"
+ history_path.write_text(json.dumps(payload["history"]), encoding="utf-8")
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ exit_code = main(["--history", str(history_path), "--json", *options])
+ self.assertEqual(exit_code, 2)
+ self.assertIn(field, stdout.getvalue())
+ self.assertNotIn("Traceback", stdout.getvalue())
+
+ def test_cli_routes_forged_pending_false_probe_to_request_input(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "pendingReview": False, "divineEyeAction": "probe", "divineEyeVerdict": "low-confidence"}]
+ with tempfile.TemporaryDirectory() as directory:
+ history_path = Path(directory) / "pending-review.json"
+ history_path.write_text(json.dumps(history), encoding="utf-8")
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ exit_code = main(["--history", str(history_path), "--json"])
+
+ self.assertEqual(exit_code, 1)
+ self.assertIn("request-input", stdout.getvalue())
+
+ def test_cli_rejects_tampered_nested_divine_eye_routing(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "pendingReview": False, "divineEye": {"fidelity": 0.95, "action": "probe", "verdict": "low-confidence"}}]
+ with tempfile.TemporaryDirectory() as directory:
+ history_path = Path(directory) / "tampered-provenance.json"
+ history_path.write_text(json.dumps(history), encoding="utf-8")
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ exit_code = main(["--history", str(history_path), "--json"])
+
+ self.assertEqual(exit_code, 2)
+ self.assertIn("pendingReview conflicts", stdout.getvalue())
+
+ def test_cli_rejects_tampered_nested_divine_eye_fidelity(self):
+ history = [{"fidelity": 0.95, "defectTags": [], "reverted": False, "divineEye": {"fidelity": 0.5}}]
+ with tempfile.TemporaryDirectory() as directory:
+ history_path = Path(directory) / "tampered-fidelity.json"
+ history_path.write_text(json.dumps(history), encoding="utf-8")
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ exit_code = main(["--history", str(history_path), "--json"])
+
+ self.assertEqual(exit_code, 2)
+ self.assertIn("fidelity conflicts", stdout.getvalue())
+
def test_repeated_defect_stops_refine_spec(self):
history = [
_it(0.60, ["seam"]),
@@ -76,17 +214,41 @@ class CorrectionLoopTest(unittest.TestCase):
self.assertTrue(d["stop"])
self.assertIn("ceiling", d["reason"].lower())
- def test_oscillation_two_reverts_stops(self):
+ def test_oscillation_two_consecutive_reverts_stops(self):
history = [
- _it(0.50, [], reverted=True),
_it(0.50, [], reverted=False),
- _it(0.50, [], reverted=True),
+ _it(0.40, [], reverted=True),
+ _it(0.30, [], reverted=True),
]
d = decide(history)
self.assertTrue(d["stop"])
self.assertEqual(d["action"], "refine-spec")
self.assertEqual(d["reason"], "oscillating/thrashing")
+ def test_interrupted_reverts_do_not_oscillate(self):
+ history = [
+ _it(0.50, [], reverted=True),
+ _it(0.60, [], reverted=False),
+ _it(0.70, [], reverted=True),
+ ]
+
+ d = decide(history)
+
+ self.assertFalse(d["stop"])
+ self.assertEqual(d["action"], "continue-iterating")
+
+ def test_score_flip_without_reverts_does_not_oscillate(self):
+ history = [
+ _it(0.50, []),
+ _it(0.70, []),
+ _it(0.60, []),
+ ]
+
+ d = decide(history)
+
+ self.assertEqual(d["action"], "request-input")
+ self.assertEqual(d["reason"], "progress plateaued below target (Δ<min_delta)")
+
def test_loop_cannot_exceed_max_iter(self):
# Simulate a real caller loop. Even with monotonic tiny improvements,
# the body MUST execute at most max_iter times. A hard safety counter
@@ -108,6 +270,14 @@ class CorrectionLoopTest(unittest.TestCase):
self.assertTrue(budget_exceeded(101, 100))
self.assertFalse(budget_exceeded(99, 100))
+ def test_budget_exceeded_rejects_invalid_inputs(self):
+ cases = ((True, 1, "spent_tokens"), (-1, 1, "spent_tokens"), (math.nan, 1, "spent_tokens"), (1, True, "budget"), (1, -1, "budget"), (1, 1.5, "budget"))
+ for spent_tokens, budget, field in cases:
+ with self.subTest(field=field, value=spent_tokens if field == "spent_tokens" else budget):
+ with self.assertRaises(ValueError) as raised:
+ budget_exceeded(spent_tokens, budget)
+ self.assertIn(field, str(raised.exception))
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/forge/tests/test_decimation_wiring.py b/forge/tests/test_decimation_wiring.py
new file mode 100644
index 0000000..d89b1f9
--- /dev/null
+++ b/forge/tests/test_decimation_wiring.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Decimation has to reach generated geometry, and has to land before skin binding.
+
+`decimate.py` implemented Garland-Heckbert quadric collapse and then sat unreachable: it reads
+a mesh FILE, and this pipeline emits TypeScript that builds geometry in the browser, so there
+was no mesh for it to read. Its own docstring records the symptom — "`lodPlan` is validated in
+three places in this repository and generated in none".
+
+The port lives in the emitted runtime instead. What these tests pin:
+
+ 1. It is opt-in — a spec that does not ask for it gets no helper and no cost.
+ 2. The ratio actually reaches the emitted call.
+ 3. It runs BEFORE the bind pass. This is the load-bearing one: a quadric collapse merges two
+ vertices, and skinIndex/skinWeight would have to be interpolated across that merge to stay
+ correct. Because the bind pass recomputes weights from `position` afterwards, decimating
+ first means no skinning data is ever carried across a merge. Ordering it the other way
+ round would be silently wrong rather than loudly broken.
+ 4. UVs cannot be silently destroyed — decimation keeps position only.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path[:0] = [str(ROOT / "_shared"), str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+
+from generate_threejs_factory import decimate_ratio, generate # noqa: E402
+from validate_sculpt_spec import validate_spec # noqa: E402
+
+FIXTURE = ROOT / "tests" / "fixtures" / "implicit_character_torso_limb.json"
+
+
+def load_fixture() -> dict:
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+def with_decimation(ratio: object) -> dict:
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["decimate"] = {"targetRatio": ratio}
+ return spec
+
+
+class RatioReadingTest(unittest.TestCase):
+ def test_absent_descriptor_means_no_decimation(self) -> None:
+ self.assertIsNone(decimate_ratio({}))
+ self.assertIsNone(decimate_ratio({"geometryDescriptor": {}}))
+ self.assertIsNone(decimate_ratio({"geometryDescriptor": {"decimate": {}}}))
+
+ def test_out_of_range_ratios_are_ignored(self) -> None:
+ for bad in (0, 1, 1.5, -0.5, "0.5", True, None):
+ component = {"geometryDescriptor": {"decimate": {"targetRatio": bad}}}
+ self.assertIsNone(decimate_ratio(component), bad)
+
+ def test_a_usable_ratio_is_returned(self) -> None:
+ component = {"geometryDescriptor": {"decimate": {"targetRatio": 0.4}}}
+ self.assertEqual(decimate_ratio(component), 0.4)
+
+
+class EmissionTest(unittest.TestCase):
+ def test_helper_is_absent_when_nothing_asks_for_it(self) -> None:
+ """Opt-in matters: a quadric pass on page load is real work, not a free default."""
+ generated = generate(load_fixture(), "form-pass")
+ self.assertNotIn("function decimateGeometry", generated)
+ self.assertNotIn("decimateGeometry(", generated)
+
+ def test_helper_and_call_appear_with_the_requested_ratio(self) -> None:
+ generated = generate(with_decimation(0.4), "form-pass")
+ self.assertIn("function decimateGeometry", generated)
+ self.assertIn("decimateGeometry(", generated)
+ self.assertIn(", 0.4);", generated)
+
+ def test_decimation_is_emitted_before_the_skin_weight_pass(self) -> None:
+ """The whole reason for the ordering: weights are recomputed from the survivors.
+
+ If the call moved after the bind pass, skinIndex/skinWeight would be interpolated
+ across vertex merges instead — the exact failure this ordering avoids.
+ """
+ generated = generate(with_decimation(0.4), "form-pass")
+ call = generated.find("decimateGeometry(")
+ self.assertGreater(call, -1)
+ for marker in ("setAttribute('skinIndex'", "setAttribute('skinWeight'"):
+ where = generated.find(marker)
+ if where == -1:
+ continue
+ self.assertLess(call, where, f"decimation must precede {marker}")
+
+ def test_the_dense_source_is_kept_addressable(self) -> None:
+ """The pre-decimation geometry gets its own name rather than being inlined away."""
+ generated = generate(with_decimation(0.4), "form-pass")
+ self.assertIn("GeometryDense", generated)
+
+
+class ValidationTest(unittest.TestCase):
+ def test_a_sane_ratio_validates(self) -> None:
+ errors, _warnings = validate_spec(with_decimation(0.4))
+ self.assertEqual([e for e in errors if "decimate" in e], [])
+
+ def test_ratios_outside_the_open_unit_interval_are_rejected(self) -> None:
+ for bad in (0, 1, 1.5, -0.2):
+ errors, _warnings = validate_spec(with_decimation(bad))
+ self.assertTrue(
+ any("targetRatio must be greater than 0 and less than 1" in e for e in errors),
+ f"{bad} was accepted: {errors}",
+ )
+
+ def test_a_non_numeric_ratio_is_rejected(self) -> None:
+ errors, _warnings = validate_spec(with_decimation("half"))
+ self.assertTrue(any("targetRatio must be a number" in e for e in errors), errors)
+
+ def test_decimation_is_refused_on_authored_uvs(self) -> None:
+ """A quadric collapse has no correct UV for the merged vertex, so the seam would move."""
+ spec = with_decimation(0.4)
+ spec["componentTree"][0]["geometryDescriptor"]["uvStrategy"] = "authored unwrap"
+ errors, _warnings = validate_spec(spec)
+ self.assertTrue(any("drops UVs" in e for e in errors), errors)
+
+ def test_generated_uv_strategies_stay_allowed(self) -> None:
+ spec = with_decimation(0.4)
+ spec["componentTree"][0]["geometryDescriptor"]["uvStrategy"] = (
+ "generated procedural coordinates"
+ )
+ errors, _warnings = validate_spec(spec)
+ self.assertEqual([e for e in errors if "drops UVs" in e], [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_divine_eye.py b/forge/tests/test_divine_eye.py
index e2e84c5..0489442 100644
--- a/forge/tests/test_divine_eye.py
+++ b/forge/tests/test_divine_eye.py
@@ -21,6 +21,7 @@ from divine_eye import ( # noqa: E402
global_ssim,
tonal_parity,
)
+from diagnose_render import mask_is_inverted, silhouette_iou # noqa: E402
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
@@ -138,5 +139,30 @@ class DivineEyeIntegrationTest(unittest.TestCase):
self.assertEqual(r["verdict"], "pass")
+class DegenerateEvidenceTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp())
+
+ def test_empty_union_is_not_a_perfect_match(self):
+ self.assertEqual(silhouette_iou([False] * 16, [False] * 16), 0.0)
+
+ def test_edge_overlap_no_edges_is_not_free_evidence(self):
+ self.assertEqual(edge_overlap([0.5] * 64, [0.5] * 64, 8), 0.0)
+
+ def test_tiny_disjoint_subjects_are_hard_rejected(self):
+ ref = self.dir / "corner-a.png"
+ render = self.dir / "corner-b.png"
+ write_rgb_png(ref, 200, 200, block(10, 10, 40, 40))
+ write_rgb_png(render, 200, 200, block(160, 160, 190, 190, fg=(30, 30, 220)))
+ result = evaluate(ref, render)
+ self.assertTrue(result["hardGateFailures"])
+ self.assertTrue(result["maskWarnings"])
+ self.assertNotEqual(result["verdict"], "pass")
+
+ def test_mask_inversion_warning_is_explicit(self):
+ self.assertTrue(mask_is_inverted(["foreground mask is tiny; material extraction is unreliable"]))
+ self.assertFalse(mask_is_inverted(["image is not clearly isolated from background"]))
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/forge/tests/test_fit_params.py b/forge/tests/test_fit_params.py
new file mode 100644
index 0000000..f5f2eea
--- /dev/null
+++ b/forge/tests/test_fit_params.py
@@ -0,0 +1,499 @@
+#!/usr/bin/env python3
+"""Contract tests for WS4 deterministic analysis-by-synthesis fitting."""
+
+from __future__ import annotations
+
+import io
+import json
+import math
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from forge.stage4_review.fit_params import ( # noqa: E402
+ FitConfig,
+ DivineEyeFitResult,
+ FitInputError,
+ NonFiniteScoreError,
+ divine_eye_correction_history,
+ divine_eye_fidelity,
+ fit,
+ fit_against_divine_eye,
+ main,
+)
+
+
+def quadratic(target: tuple[float, ...]):
+ return lambda values: 1.0 - sum((value - target[index]) ** 2 for index, value in enumerate(values))
+
+
+class FitParamsTest(unittest.TestCase):
+ def test_seeded_metadata_and_result_are_deterministic(self):
+ config = FitConfig(seed=42, max_iterations=12, max_evaluations=100)
+
+ first = fit((0.0, 0.0), ((-1.0, 1.0), (-1.0, 1.0)), quadratic((0.5, -0.5)), config)
+ second = fit((0.0, 0.0), ((-1.0, 1.0), (-1.0, 1.0)), quadratic((0.5, -0.5)), config)
+
+ self.assertEqual(first, second)
+ self.assertEqual(first.seed, 42)
+
+ def test_best_score_history_is_monotonic_and_normalizes_for_correction_loop(self):
+ result = fit((0.0,), ((-1.0, 1.0),), quadratic((0.5,)), FitConfig(max_iterations=10, max_evaluations=100))
+
+ scores = [record.best_score for record in result.history]
+ self.assertEqual(scores, sorted(scores))
+ history = result.to_correction_history(defect_tags=("detail-gap",))
+ self.assertTrue(history)
+ self.assertEqual(set(history[0]), {"fidelity", "defectTags", "reverted"})
+ self.assertEqual(history[0]["defectTags"], ["detail-gap"])
+ self.assertFalse(history[0]["reverted"])
+
+ def test_stops_at_max_evaluations(self):
+ result = fit((0.0,), ((-1.0, 1.0),), quadratic((0.8,)), FitConfig(max_iterations=20, max_evaluations=2))
+
+ self.assertEqual(result.status, "max-evaluations")
+ self.assertLessEqual(result.evaluations, 2)
+
+ def test_budget_exhaustion_commits_evaluated_coordinate_improvement(self):
+ result = fit((0.0,), ((-1.0, 1.0),), lambda values: -values[0], FitConfig(max_evaluations=2))
+
+ self.assertEqual(result.status, "max-evaluations")
+ self.assertEqual(result.parameters, (-0.5,))
+ self.assertEqual(result.best_score, 0.5)
+ self.assertEqual(result.history[-1].iteration, 1)
+ self.assertTrue(result.history[-1].improved)
+
+ def test_fit_against_divine_eye_runs_evaluator_and_preserves_provenance(self):
+ scores = {"render-0.0.png": (0.5, []), "render--0.5.png": (0.2, ["scale"]), "render-0.5.png": (0.9, [])}
+ rendered: list[tuple[float, ...]] = []
+ evaluator_results: list[dict[str, object]] = []
+
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ rendered.append(parameters)
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(reference: Path, render: Path) -> dict[str, object]:
+ fidelity, gates = scores[render.name]
+ result = {"fidelity": fidelity, "hardGateFailures": gates.copy(), "action": "refine-code" if gates else "continue", "signals": {"source": render.name}, "reference": str(reference), "render": str(render)}
+ evaluator_results.append(result)
+ return result
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(max_iterations=1, max_evaluations=10))
+
+ self.assertIsInstance(result, DivineEyeFitResult)
+ self.assertEqual(result.fit_result.parameters, (0.5,))
+ self.assertEqual(result.fit_result.best_score, 0.9)
+ self.assertEqual(result.best_raw_fidelity, 0.9)
+ self.assertEqual(len(rendered), 3)
+ self.assertEqual(len(result.divine_eye_results), result.fit_result.evaluations)
+ self.assertEqual(result.correction_history[1]["hardGateFailures"], ["scale"])
+ self.assertEqual(result.correction_history[1]["divineEye"]["signals"], {"source": "render--0.5.png"})
+ self.assertEqual(result.divine_eye_results[1]["fitCandidateParameters"], [-0.5])
+ self.assertEqual(result.divine_eye_results[1]["fitReferencePng"], "reference.png")
+ self.assertEqual(result.divine_eye_results[1]["fitRenderPath"], "render--0.5.png")
+ self.assertEqual(result.to_json()["bestObjectiveScore"], 0.9)
+ self.assertEqual(result.to_json()["bestRawFidelity"], 0.9)
+ evaluator_results[1]["signals"]["source"] = "mutated"
+ self.assertEqual(result.divine_eye_results[1]["signals"], {"source": "render--0.5.png"})
+
+ def test_fit_against_divine_eye_snapshots_reused_evaluator_mapping(self):
+ scores = {"render-0.0.png": (0.5, []), "render--0.5.png": (0.2, ["scale"]), "render-0.5.png": (0.9, [])}
+ shared_result = {"fidelity": 0.0, "hardGateFailures": [], "signals": {"source": ""}}
+
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(_reference: Path, render: Path) -> dict[str, object]:
+ fidelity, gates = scores[render.name]
+ shared_result["fidelity"] = fidelity
+ shared_result["hardGateFailures"] = gates
+ shared_result["signals"]["source"] = render.name
+ return shared_result
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(max_iterations=1))
+
+ self.assertEqual([item["fidelity"] for item in result.divine_eye_results], [0.5, 0.2, 0.9])
+ self.assertEqual([item["divineEye"]["signals"]["source"] for item in result.correction_history], ["render-0.0.png", "render--0.5.png", "render-0.5.png"])
+ self.assertEqual(result.correction_history[1]["hardGateFailures"], ["scale"])
+ self.assertEqual([item["fitCandidateParameters"] for item in result.divine_eye_results], [[0.0], [-0.5], [0.5]])
+
+ def test_fit_against_divine_eye_normalizes_fidelity_only_result_without_mutation(self):
+ source_result = {"fidelity": 0.9}
+
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(_reference: Path, _render: Path) -> dict[str, object]:
+ return source_result
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(max_iterations=1))
+
+ self.assertEqual(source_result, {"fidelity": 0.9})
+ self.assertEqual(result.fit_result.best_score, 0.9)
+ self.assertEqual(result.best_raw_fidelity, 0.9)
+ self.assertTrue(all(item["hardGateFailures"] == [] for item in result.divine_eye_results))
+ self.assertTrue(all(item["hardGateFailures"] == [] for item in result.correction_history))
+
+ def test_fit_against_divine_eye_rejects_higher_fidelity_hard_gate_as_best(self):
+ scores = {"render-0.0.png": (0.85, []), "render--0.5.png": (0.90, ["scale"]), "render-0.5.png": (0.80, [])}
+
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(_reference: Path, render: Path) -> dict[str, object]:
+ fidelity, gates = scores[render.name]
+ return {"fidelity": fidelity, "hardGateFailures": gates, "render": str(render)}
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(max_iterations=1))
+
+ self.assertEqual(result.fit_result.parameters, (0.0,))
+ self.assertEqual(result.fit_result.best_score, 0.85)
+ self.assertEqual(result.best_raw_fidelity, 0.85)
+ self.assertEqual(result.divine_eye_results[1]["fidelity"], 0.90)
+ self.assertEqual(result.correction_history[1]["hardGateFailures"], ["scale"])
+
+ def test_fit_against_divine_eye_rejects_higher_fidelity_probe_as_best(self):
+ scores = {"render-0.0.png": (0.85, "continue", "pass"), "render--0.5.png": (0.95, "probe", "low-confidence"), "render-0.5.png": (0.80, "continue", "pass")}
+
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(_reference: Path, render: Path) -> dict[str, object]:
+ fidelity, action, verdict = scores[render.name]
+ return {"fidelity": fidelity, "action": action, "verdict": verdict}
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(max_iterations=1))
+
+ self.assertEqual(result.fit_result.parameters, (0.0,))
+ self.assertEqual(result.fit_result.best_score, 0.85)
+ self.assertEqual(result.best_raw_fidelity, 0.85)
+ self.assertEqual(result.divine_eye_results[1]["fidelity"], 0.95)
+ self.assertTrue(result.correction_history[1]["pendingReview"])
+
+ def test_fit_against_divine_eye_bounds_all_gated_runs_with_raw_provenance(self):
+ def render_for_parameters(parameters: tuple[float, ...]) -> Path:
+ return Path(f"render-{parameters[0]:.1f}.png")
+
+ def evaluator(_reference: Path, render: Path) -> dict[str, object]:
+ return {"fidelity": 0.90, "hardGateFailures": ["scale"], "render": str(render)}
+
+ result = fit_against_divine_eye((0.0,), ((-1.0, 1.0),), render_for_parameters, "reference.png", evaluator, FitConfig(plateau_iterations=1))
+
+ self.assertEqual(result.fit_result.status, "plateau")
+ self.assertEqual(result.fit_result.best_score, -1.0)
+ self.assertIsNone(result.best_raw_fidelity)
+ self.assertTrue(all(item["fidelity"] == 0.90 for item in result.divine_eye_results))
+ self.assertTrue(all(item["hardGateFailures"] == ["scale"] for item in result.correction_history))
+ self.assertEqual([item["fidelity"] for item in result.correction_history], [0.90, 0.90, 0.90])
+
+ def test_stops_on_plateau(self):
+ result = fit((0.0,), ((-1.0, 1.0),), lambda _values: 0.5, FitConfig(plateau_iterations=1))
+
+ self.assertEqual(result.status, "plateau")
+
+ def test_stops_on_direction_oscillation(self):
+ scores = {
+ (0.5, 0.5): 0.0,
+ (0.25, 0.5): 0.1,
+ (0.25, 0.25): 0.2,
+ (0.5, 0.25): 0.3,
+ (0.5, 0.0): 0.4,
+ (0.25, 0.0): 0.5,
+ }
+
+ def objective(values: tuple[float, ...]) -> float:
+ return scores.get(tuple(round(value, 3) for value in values), -1.0)
+
+ result = fit(
+ (0.5, 0.5),
+ ((0.0, 1.0), (0.0, 1.0)),
+ objective,
+ FitConfig(max_iterations=8, max_evaluations=100, min_improvement=1.0, plateau_iterations=4, oscillation_flips=2),
+ )
+
+ self.assertEqual(result.status, "oscillation")
+
+ def test_non_consecutive_direction_flips_do_not_oscillate(self):
+ scores = {
+ (0.5, 0.5): 0.0,
+ (0.25, 0.5): 0.1,
+ (0.25, 0.25): 0.2,
+ (0.5, 0.25): 0.3,
+ (0.5, 0.0): 0.5,
+ (0.25, 0.0): 0.6,
+ }
+
+ def objective(values: tuple[float, ...]) -> float:
+ return scores.get(tuple(round(value, 3) for value in values), -1.0)
+
+ result = fit(
+ (0.5, 0.5),
+ ((0.0, 1.0), (0.0, 1.0)),
+ objective,
+ FitConfig(max_iterations=6, max_evaluations=100, min_improvement=0.15, plateau_iterations=4, oscillation_flips=1),
+ )
+
+ self.assertNotEqual(result.status, "oscillation")
+
+ def test_one_unstable_iteration_with_multiple_reversals_does_not_oscillate(self):
+ scores = {
+ (0.5, 0.5, 0.5): 0.0,
+ (0.25, 0.5, 0.5): 0.1,
+ (0.25, 0.25, 0.5): 0.2,
+ (0.25, 0.25, 0.25): 0.3,
+ (0.5, 0.25, 0.25): 0.4,
+ (0.5, 0.5, 0.25): 0.5,
+ }
+
+ def objective(values: tuple[float, ...]) -> float:
+ return scores.get(tuple(round(value, 3) for value in values), -1.0)
+
+ result = fit(
+ (0.5, 0.5, 0.5),
+ ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0)),
+ objective,
+ FitConfig(max_iterations=6, max_evaluations=100, min_improvement=1.0, plateau_iterations=3, oscillation_flips=2),
+ )
+
+ self.assertNotEqual(result.status, "oscillation")
+
+ def test_smooth_quadratic_refinement_does_not_count_boundary_bracketing_as_oscillation(self):
+ result = fit(
+ (0.0,),
+ ((-1.0, 1.0),),
+ quadratic((0.2,)),
+ FitConfig(max_iterations=20, max_evaluations=200, oscillation_flips=2),
+ )
+
+ self.assertNotEqual(result.status, "oscillation")
+ self.assertGreater(result.best_score, 0.999)
+
+ def test_rejects_invalid_bounds_and_non_finite_scores(self):
+ with self.assertRaises(FitInputError):
+ fit((0.0,) * 16, ((-1.0, 1.0),) * 16, quadratic((0.0,) * 16))
+ with self.assertRaises(FitInputError):
+ fit((2.0,), ((-1.0, 1.0),), quadratic((0.0,)))
+ with self.assertRaises(NonFiniteScoreError):
+ fit((0.0,), ((-1.0, 1.0),), lambda _values: math.nan)
+
+ def test_direct_call_rejects_invalid_config_and_objective(self):
+ cases = (
+ (quadratic((0.0,)), None, "config"),
+ (quadratic((0.0,)), {}, "config"),
+ (None, FitConfig(), "objective"),
+ (0, FitConfig(), "objective"),
+ )
+
+ for objective, config, field in cases:
+ with self.subTest(field=field, value=objective if field == "objective" else config):
+ with self.assertRaises(FitInputError) as raised:
+ fit((0.0,), ((-1.0, 1.0),), objective, config)
+ self.assertEqual(raised.exception.field, field)
+
+ def test_fit_config_rejects_invalid_limits_minimum_improvement_and_seed(self):
+ cases = (
+ ("max_iterations", 0, "config"), ("max_iterations", True, "config"),
+ ("max_evaluations", 0, "config"), ("max_evaluations", True, "config"),
+ ("plateau_iterations", 0, "config"), ("plateau_iterations", True, "config"),
+ ("oscillation_flips", 0, "config"), ("oscillation_flips", True, "config"),
+ ("min_improvement", -0.1, "config.min_improvement"), ("min_improvement", math.nan, "config.min_improvement"),
+ ("min_improvement", math.inf, "config.min_improvement"),
+ ("seed", True, "config.seed"), ("seed", 1.5, "config.seed"), ("seed", "seed", "config.seed"),
+ )
+ for field, value, expected_field in cases:
+ with self.subTest(field=field, value=value):
+ with self.assertRaises(FitInputError) as raised:
+ fit((0.0,), ((-1.0, 1.0),), quadratic((0.0,)), FitConfig(**{field: value}))
+ self.assertEqual(raised.exception.field, expected_field)
+
+ def test_rejects_malformed_bounds_with_field_specific_input_errors(self):
+ for bounds, field in (([1], "bounds[0]"), ([[1]], "bounds[0]"), (["1,2"], "bounds[0]")):
+ with self.subTest(bounds=bounds):
+ with self.assertRaises(FitInputError) as raised:
+ fit((0.0,), bounds, quadratic((0.0,)))
+ self.assertEqual(raised.exception.field, field)
+
+ def test_cli_rejects_malformed_bounds_without_traceback(self):
+ with tempfile.TemporaryDirectory() as directory:
+ input_path = Path(directory) / "invalid-fit.json"
+ input_path.write_text(json.dumps({"initial": [0.0], "bounds": [[1]], "target": [0.5], "config": {}}), encoding="utf-8")
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ exit_code = main(["--input", str(input_path), "--json"])
+
+ self.assertEqual(exit_code, 2)
+ self.assertIn("bounds[0]", stderr.getvalue())
+ self.assertNotIn("Traceback", stderr.getvalue())
+
+ def test_cli_rejects_unknown_config_keys_without_traceback(self):
+ with tempfile.TemporaryDirectory() as directory:
+ input_path = Path(directory) / "unknown-config.json"
+ input_path.write_text(
+ json.dumps({"initial": [0.0], "bounds": [[-1.0, 1.0]], "target": [0.5], "config": {"maxEvaluatons": 5}}),
+ encoding="utf-8",
+ )
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ exit_code = main(["--input", str(input_path), "--json"])
+
+ self.assertEqual(exit_code, 2)
+ self.assertIn("maxEvaluatons", stderr.getvalue())
+ self.assertNotIn("Traceback", stderr.getvalue())
+
+ def test_cli_requires_exact_top_level_schema(self):
+ cases = (
+ ({"initial": [0.0], "bounds": [[-1.0, 1.0]], "target": [0.5], "config": {}, "extra": True}, "extra"),
+ ({"initial": [0.0], "bounds": [[-1.0, 1.0]], "target": [0.5]}, "config"),
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ for index, (payload, field) in enumerate(cases):
+ with self.subTest(field=field):
+ input_path = Path(directory) / f"schema-{index}.json"
+ input_path.write_text(json.dumps(payload), encoding="utf-8")
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ exit_code = main(["--input", str(input_path), "--json"])
+ self.assertEqual(exit_code, 2)
+ self.assertIn(field, stderr.getvalue())
+ self.assertNotIn("Traceback", stderr.getvalue())
+
+ def test_divine_eye_adapter_reads_fidelity_without_changing_gate_keys(self):
+ result = {"fidelity": 0.75, "hardGateFailures": ["scale"], "action": "refine-code"}
+
+ score = divine_eye_fidelity(result)
+
+ self.assertEqual(score, 0.75)
+ self.assertEqual(result["hardGateFailures"], ["scale"])
+ self.assertEqual(result["action"], "refine-code")
+
+ def test_divine_eye_adapter_rejects_invalid_fidelity(self):
+ for score in (-0.1, 1.1, math.nan, math.inf, True):
+ with self.subTest(score=score):
+ with self.assertRaises(FitInputError) as raised:
+ divine_eye_fidelity({"fidelity": score})
+ self.assertEqual(raised.exception.field, "Divine Eye result.fidelity")
+
+ def test_divine_eye_adapter_rejects_non_mapping_results(self):
+ for result in (None, "not-a-result", []):
+ with self.subTest(result=result):
+ with self.assertRaises(FitInputError) as raised:
+ divine_eye_fidelity(result)
+ self.assertEqual(raised.exception.field, "Divine Eye result")
+
+ def test_divine_eye_history_preserves_per_iteration_hard_gates_for_correction_loop(self):
+ from forge.stage4_review.correction_loop import decide
+
+ results = [
+ {"fidelity": 0.9, "hardGateFailures": ["scale"], "action": "refine-code"},
+ {"fidelity": 0.8, "hardGateFailures": [], "action": "continue"},
+ ]
+
+ history = divine_eye_correction_history(results)
+ decision = decide(history[:1])
+
+ self.assertEqual(history[0]["fidelity"], 0.9)
+ self.assertEqual(history[0]["defectTags"], ["scale"])
+ self.assertEqual(history[0]["hardGateFailures"], ["scale"])
+ self.assertFalse(history[0]["reverted"])
+ self.assertFalse(history[1]["reverted"])
+ self.assertEqual(history[0]["divineEye"], results[0])
+ self.assertEqual(results[0]["hardGateFailures"], ["scale"])
+ self.assertEqual(results[0]["action"], "refine-code")
+ self.assertTrue(decision["stop"])
+ self.assertEqual(decision["action"], "refine-code")
+
+ def test_divine_eye_history_compares_attempts_to_last_accepted_fidelity(self):
+ history = divine_eye_correction_history([
+ {"fidelity": 0.90},
+ {"fidelity": 0.80},
+ {"fidelity": 0.85},
+ ])
+
+ self.assertEqual([entry["reverted"] for entry in history], [False, True, True])
+
+ def test_divine_eye_history_preserves_pending_review_routing(self):
+ from forge.stage4_review.correction_loop import decide
+
+ history = divine_eye_correction_history([{"fidelity": 0.95, "action": "probe", "verdict": "low-confidence"}])
+
+ self.assertTrue(history[0]["pendingReview"])
+ self.assertEqual(history[0]["divineEyeAction"], "probe")
+ self.assertEqual(history[0]["divineEyeVerdict"], "low-confidence")
+ self.assertEqual(decide(history)["action"], "request-input")
+
+ def test_pending_high_fidelity_does_not_replace_approved_baseline(self):
+ history = divine_eye_correction_history([
+ {"fidelity": 0.95, "action": "probe", "verdict": "low-confidence"},
+ {"fidelity": 0.90, "action": "continue", "verdict": "pass"},
+ ])
+
+ self.assertEqual([entry["reverted"] for entry in history], [False, False])
+
+ def test_divine_eye_history_rejects_malformed_direct_inputs(self):
+ cases = ((None, "results"), ("not-results", "results"), ([None], "results[0]"), ([0], "results[0]"))
+ for results, field in cases:
+ with self.subTest(field=field, results=results):
+ with self.assertRaises(FitInputError) as raised:
+ divine_eye_correction_history(results)
+ self.assertEqual(raised.exception.field, field)
+
+ def test_hard_gated_result_does_not_replace_accepted_fidelity(self):
+ history = divine_eye_correction_history([
+ {"fidelity": 0.85},
+ {"fidelity": 0.90, "hardGateFailures": ["scale"]},
+ {"fidelity": 0.80},
+ ])
+
+ self.assertEqual([entry["reverted"] for entry in history], [False, False, True])
+
+ def test_divine_eye_history_copies_rich_provenance(self):
+ results = [{
+ "fidelity": 0.8,
+ "hardGateFailures": ["scale"],
+ "action": "refine-code",
+ "signals": {"ssim": 0.7},
+ "reference": "reference.png",
+ "render": "render.png",
+ }]
+
+ history = divine_eye_correction_history(results)
+ results[0]["hardGateFailures"].append("silhouette")
+ results[0]["signals"]["ssim"] = 0.1
+
+ self.assertEqual(history[0]["divineEye"], {
+ "fidelity": 0.8,
+ "hardGateFailures": ["scale"],
+ "action": "refine-code",
+ "signals": {"ssim": 0.7},
+ "reference": "reference.png",
+ "render": "render.png",
+ })
+
+ def test_cli_json_roundtrip(self):
+ payload = {
+ "initial": [0.0, 0.0],
+ "bounds": [[-1.0, 1.0], [-1.0, 1.0]],
+ "target": [0.5, -0.5],
+ "config": {"maxIterations": 8, "maxEvaluations": 100, "seed": 7},
+ }
+ with tempfile.TemporaryDirectory() as directory:
+ input_path = Path(directory) / "fit.json"
+ input_path.write_text(json.dumps(payload), encoding="utf-8")
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ exit_code = main(["--input", str(input_path), "--json"])
+
+ self.assertEqual(exit_code, 0)
+ result = json.loads(stdout.getvalue())
+ self.assertEqual(result["seed"], 7)
+ self.assertLessEqual(result["evaluations"], 100)
+ self.assertEqual(len(result["parameters"]), 2)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_geodesic_skinning.py b/forge/tests/test_geodesic_skinning.py
new file mode 100644
index 0000000..bbe25a4
--- /dev/null
+++ b/forge/tests/test_geodesic_skinning.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Tests for geodesic voxel binding, built around the defect it exists to remove.
+
+`test_euclidean_leaks_across_the_gap_and_geodesic_does_not` is the whole argument for this module. It
+binds ONE mesh with BOTH methods and compares them, because "geodesic distance stops weight leaking
+across a gap" is otherwise just a claim. The fixture is an arm hanging beside a torso with a real air
+gap, joined only at the shoulder -- the default pose of almost every character.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from geodesic_skinning import ( # noqa: E402
+ bind,
+ euclidean_bind,
+ geodesic_field,
+ VoxelGrid,
+ _segment_voxels,
+ _triangles,
+)
+
+
+def box(x0, x1, y0, y1, z0, z1):
+ vertices = [
+ [x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0],
+ [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1],
+ ]
+ quads = [
+ (0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
+ (2, 3, 7, 6), (1, 2, 6, 5), (0, 4, 7, 3),
+ ]
+ indices = []
+ for a, b, c, d in quads:
+ indices.extend([a, b, c, a, c, d])
+ return vertices, indices
+
+
+def merge(*meshes):
+ vertices: list[list[float]] = []
+ indices: list[int] = []
+ for verts, inds in meshes:
+ offset = len(vertices)
+ vertices.extend(verts)
+ indices.extend(index + offset for index in inds)
+ return vertices, indices
+
+
+def torso_with_hanging_arm():
+ """A torso, an arm beside it across a 0.4 air gap, and a shoulder bridge joining them at the top.
+
+ The gap matters: at the default resolution it is several voxels wide, so no geodesic path can cut
+ across it. Every route from the arm to the lower torso has to climb to the shoulder and back down,
+ which is exactly the anatomy that makes Euclidean binding fail.
+ """
+ torso = box(0.0, 2.0, 0.0, 4.0, 0.0, 1.0)
+ arm = box(2.4, 3.4, 0.0, 3.4, 0.0, 1.0)
+ shoulder = box(1.8, 2.6, 3.4, 4.0, 0.0, 1.0)
+ return merge(torso, arm, shoulder)
+
+
+SPINE = {"id": "spine", "jointPos": [1.0, 0.5, 0.5], "tipPos": [1.0, 3.5, 0.5]}
+ARM = {"id": "arm", "jointPos": [2.9, 3.2, 0.5], "tipPos": [2.9, 0.4, 0.5]}
+
+
+def arm_weight(result, vertex_index: int) -> float:
+ arm_bone = result["boneOrder"].index("arm")
+ total = 0.0
+ for slot, bone in enumerate(result["skinIndices"][vertex_index]):
+ if bone == arm_bone:
+ total += result["skinWeights"][vertex_index][slot]
+ return total
+
+
+class TheDefectThisFixes(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = torso_with_hanging_arm()
+ cls.mesh = {"vertices": cls.vertices, "indices": cls.indices}
+ # The lower-right corner of the torso: close to the arm bone in a straight line, far from it
+ # through the body. Vertex 1 of the torso box is [2, 0, 0].
+ cls.chest_index = 1
+ cls.geodesic = bind(cls.mesh, [SPINE, ARM], resolution=32)
+ cls.euclidean = euclidean_bind(cls.mesh, [SPINE, ARM])
+
+ def test_the_probe_vertex_really_is_euclidean_close_to_the_arm(self) -> None:
+ # If this were false the comparison below would prove nothing -- it would just be a vertex
+ # nowhere near the arm under either metric.
+ vertex = self.vertices[self.chest_index]
+ self.assertLess(abs(vertex[0] - ARM["jointPos"][0]), 1.0)
+
+ def test_the_distance_field_routes_around_the_shoulder(self) -> None:
+ """What this module actually computes, asserted directly.
+
+ The weights below are a POLICY applied to these distances, and a falloff constant can make a
+ correct field look wrong. So the field is pinned on its own: the straight line from the chest
+ corner to the arm bone is under 1 unit, while any path through the solid has to climb to the
+ shoulder and come back down, which is several times further.
+ """
+ grid = VoxelGrid(self.vertices, _triangles(self.indices), 32)
+ cell = grid.index_of(self.vertices[self.chest_index])
+ to_spine = geodesic_field(grid, _segment_voxels(grid, SPINE["jointPos"], SPINE["tipPos"]))[cell]
+ to_arm = geodesic_field(grid, _segment_voxels(grid, ARM["jointPos"], ARM["tipPos"]))[cell]
+ self.assertGreater(to_arm / to_spine, 3.0)
+ # And the arm really is close in a straight line, which is what makes Euclidean fail.
+ self.assertLess(abs(self.vertices[self.chest_index][0] - ARM["jointPos"][0]), 1.0)
+
+ def test_euclidean_leaks_across_the_gap_and_geodesic_does_not(self) -> None:
+ leaked = arm_weight(self.euclidean, self.chest_index)
+ contained = arm_weight(self.geodesic, self.chest_index)
+ # The comparison is the claim. An absolute threshold here would be measuring the falloff
+ # constant rather than the method: at the same distances, power 2 leaves 8.6% and power 4
+ # leaves 0.9%, and neither number says anything about whether the path crossed the gap.
+ self.assertGreater(leaked, 0.25)
+ self.assertLess(contained, leaked / 5.0)
+
+ def test_arm_vertices_still_belong_to_the_arm(self) -> None:
+ # The fix must not work by simply weakening the arm bone everywhere.
+ arm_corner = 8 + 1 # second vertex of the arm box: [3.4, 0, 0]
+ self.assertGreater(arm_weight(self.geodesic, arm_corner), 0.8)
+
+
+class WeightInvariants(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ vertices, indices = torso_with_hanging_arm()
+ cls.result = bind({"vertices": vertices, "indices": indices}, [SPINE, ARM], resolution=24)
+
+ def test_weights_are_normalised(self) -> None:
+ self.assertLess(self.result["maxWeightError"], 1e-9)
+
+ def test_every_vertex_gets_four_slots(self) -> None:
+ for row in self.result["skinWeights"]:
+ self.assertEqual(len(row), 4)
+ for row in self.result["skinIndices"]:
+ self.assertEqual(len(row), 4)
+
+ def test_no_negative_weights(self) -> None:
+ for row in self.result["skinWeights"]:
+ for weight in row:
+ self.assertGreaterEqual(weight, 0.0)
+
+ def test_solid_voxels_exceed_surface_voxels(self) -> None:
+ # Proves the interior flood fill actually filled something. If the surface shell leaked, the
+ # interior would be classified as outside and solid would collapse onto the shell.
+ self.assertGreater(self.result["solidVoxelCount"], self.result["surfaceVoxelCount"])
+
+
+class Voxelization(unittest.TestCase):
+ def test_a_solid_box_is_filled_not_hollow(self) -> None:
+ vertices, indices = box(0, 1, 0, 1, 0, 1)
+ grid = VoxelGrid(vertices, _triangles(indices), 16)
+ self.assertGreater(len(grid.solid), len(grid.surface))
+ # The centre of the box must be solid; if the flood fill leaked it would not be.
+ self.assertIn(grid.index_of([0.5, 0.5, 0.5]), grid.solid)
+
+ def test_the_gap_between_torso_and_arm_stays_empty(self) -> None:
+ # The single assumption the headline test rests on. If the voxelization bridged the gap the
+ # geodesic path would cut straight across and the comparison would silently become vacuous.
+ vertices, indices = torso_with_hanging_arm()
+ grid = VoxelGrid(vertices, _triangles(indices), 32)
+ self.assertNotIn(grid.index_of([2.2, 1.0, 0.5]), grid.solid)
+
+
+class Reporting(unittest.TestCase):
+ def test_a_detached_island_is_reported_not_silently_pinned(self) -> None:
+ # An unreachable vertex usually means a hole or a loose island. Pinning it to the nearest bone
+ # in space would hide exactly the thing worth knowing.
+ main_mesh = box(0, 1, 0, 1, 0, 1)
+ island = box(5, 6, 5, 6, 5, 6)
+ vertices, indices = merge(main_mesh, island)
+ bone = {"id": "b", "jointPos": [0.5, 0.2, 0.5], "tipPos": [0.5, 0.8, 0.5]}
+ result = bind({"vertices": vertices, "indices": indices}, [bone], resolution=24)
+ self.assertGreater(result["unreachableVertexCount"], 0)
+
+ def test_rejects_input_it_cannot_bind(self) -> None:
+ vertices, indices = box(0, 1, 0, 1, 0, 1)
+ with self.assertRaises(ValueError):
+ bind({"vertices": vertices, "indices": indices}, [])
+ with self.assertRaises(ValueError):
+ bind({"vertices": [], "indices": indices}, [SPINE])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_glb_reference.py b/forge/tests/test_glb_reference.py
new file mode 100644
index 0000000..7320813
--- /dev/null
+++ b/forge/tests/test_glb_reference.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+import json
+import struct
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+from forge.stage1_intake.probe_glb import probe_glb
+from forge.stage4_review.render_bridge import (
+ init_manifest,
+ record_capture,
+ record_reference_capture,
+ validate_manifest,
+ write_manifest,
+)
+
+PROFILE = Path(__file__).resolve().parents[2] / "docs" / "specs" / "render-profile.v2.example.json"
+
+
+def write_png(path: Path, width: int = 8, height: int = 8) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ signature = b"\x89PNG\r\n\x1a\n"
+
+ def chunk(kind: bytes, payload: bytes) -> bytes:
+ checksum = zlib.crc32(kind)
+ checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
+
+ rows = b"".join(b"\x00" + bytes([220, 80, 80]) * width for _ in range(height))
+ path.write_bytes(
+ signature
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(rows))
+ + chunk(b"IEND", b"")
+ )
+
+
+def write_triangle_glb(path: Path) -> None:
+ positions = struct.pack(
+ "<9f",
+ -1.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0,
+ )
+ document = {
+ "asset": {"version": "2.0", "generator": "test"},
+ "scene": 0,
+ "scenes": [{"nodes": [0]}],
+ "nodes": [{"name": "Root", "mesh": 0}],
+ "meshes": [{"name": "Triangle", "primitives": [{"attributes": {"POSITION": 0}}]}],
+ "materials": [{"name": "TestMaterial"}],
+ "buffers": [{"byteLength": len(positions)}],
+ "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": len(positions)}],
+ "accessors": [
+ {
+ "bufferView": 0,
+ "componentType": 5126,
+ "count": 3,
+ "type": "VEC3",
+ "min": [-1.0, 0.0, 0.0],
+ "max": [1.0, 1.0, 0.0],
+ }
+ ],
+ }
+ json_chunk = json.dumps(document, separators=(",", ":")).encode("utf-8")
+ json_chunk += b" " * ((4 - len(json_chunk) % 4) % 4)
+ bin_chunk = positions + b"\x00" * ((4 - len(positions) % 4) % 4)
+ total_length = 12 + 8 + len(json_chunk) + 8 + len(bin_chunk)
+ path.write_bytes(
+ struct.pack("<4sII", b"glTF", 2, total_length)
+ + struct.pack("<II", len(json_chunk), 0x4E4F534A)
+ + json_chunk
+ + struct.pack("<II", len(bin_chunk), 0x004E4942)
+ + bin_chunk
+ )
+
+
+class GlbReferenceProbeTest(unittest.TestCase):
+ def test_probe_extracts_reference_inventory_and_bounds(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "reference.glb"
+ write_triangle_glb(path)
+ result = probe_glb(path)
+ self.assertEqual(result["kind"], "glb-reference")
+ self.assertEqual(result["referenceReadiness"], "pass")
+ self.assertEqual(result["scene"]["meshCount"], 1)
+ self.assertEqual(result["scene"]["materialCount"], 1)
+ self.assertEqual(result["meshes"][0]["name"], "Triangle")
+ self.assertEqual(result["bounds"]["min"], [-1.0, 0.0, 0.0])
+ self.assertEqual(result["bounds"]["max"], [1.0, 1.0, 0.0])
+ self.assertEqual(result["semanticDecomposition"]["status"], "insufficient")
+ self.assertEqual(result["semanticDecomposition"]["reliableSemanticBoundary"], "multipart-glb-required")
+
+ def test_render_manifest_requires_browser_glb_baseline(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ glb = root / "reference.glb"
+ write_triangle_glb(glb)
+ manifest_path = root / "manifest.json"
+ manifest = init_manifest(
+ None,
+ "http://127.0.0.1:5173/#/character",
+ manifest_path,
+ (620, 1000),
+ 1.0,
+ "captures",
+ reference_glb=glb,
+ )
+ write_manifest(manifest_path, manifest)
+ incomplete = validate_manifest(manifest_path, require_complete=True)
+ self.assertFalse(incomplete["passed"])
+ self.assertTrue(any("GLB reference baseline" in error for error in incomplete["errors"]))
+
+ reference_shot = root / "reference" / "hero.png"
+ procedural_shot = root / "captures" / "hero.png"
+ write_png(reference_shot, 16, 16)
+ write_png(procedural_shot, 16, 16)
+ record_reference_capture(manifest_path, manifest, "hero", reference_shot)
+ record_capture(manifest_path, manifest, "hero", procedural_shot)
+ write_manifest(manifest_path, manifest)
+ complete = validate_manifest(manifest_path, require_complete=False)
+ self.assertTrue(complete["passed"])
+
+ def test_v2_manifest_declares_shared_profile_and_six_passes(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ glb = root / "reference.glb"
+ write_triangle_glb(glb)
+ manifest = init_manifest(
+ None,
+ "http://127.0.0.1:5173/#/character",
+ root / "manifest.json",
+ (620, 1000),
+ 1.0,
+ "captures",
+ reference_glb=glb,
+ render_profile=PROFILE,
+ )
+ self.assertEqual(manifest["fidelityTrack"], "glb-mediated-v2")
+ self.assertEqual(
+ list(manifest["captures"][0]["passes"]),
+ ["beauty", "alpha-silhouette", "semantic-id", "depth", "normal", "roughness-material-id"],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_hierarchy_scale.py b/forge/tests/test_hierarchy_scale.py
new file mode 100644
index 0000000..3bf62e1
--- /dev/null
+++ b/forge/tests/test_hierarchy_scale.py
@@ -0,0 +1,231 @@
+#!/usr/bin/env python3
+"""PLAN_1.5 WS-E kill test: a non-uniformly-scaled parent must not distort a child
+nested under it.
+
+Question this answers: does `generate_threejs_factory.py` still conflate a part's
+*shape dimensions* with its *place in the hierarchy*? Before WS-E, a component's
+declared scale was applied directly to the pivot `THREE.Group` (`node.scale.set(...)`),
+which is exactly the anti-pattern documented in
+`forge/stage2_spec/new_sculpt_spec.py` (search "FLATTENED to world space"): nesting a
+child under a non-uniformly-scaled parent Group would cascade that scale onto the
+child and distort it, which is why every character part was flattened onto a single
+hidden, unit-scaled root instead of a real parent chain. See
+docs/PLAN_1.5_ANIMATION_READY_RIGS.md, WS-E ("Proportion baked into geometry").
+
+This is a REAL-RUN test: it emits TypeScript from a hand-written two-component spec
+(a non-uniformly-scaled "torso" box parenting a unit "head" sphere), executes that
+emitted code with the showcase's real `three` via `tsc` + `node` (the same pattern
+`test_visual_hull.py` / `test_subdivision.py` already use — no esbuild bundling is
+needed because tsc compiles into a tempdir nested inside the showcase checkout, so
+`three` resolves from its node_modules), and measures the child's actual geometry
+and world transform. No hand-computed expectation is substituted for execution.
+
+Pure Python 3.10+ stdlib on this side. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+ROOT = Path(__file__).resolve().parent.parent
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate
+ from validate_sculpt_spec import validate_spec
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return generate, validate_spec
+
+
+generate, validate_spec = import_forge_modules()
+
+# A non-uniformly-scaled "torso" (box, scale [3, 1, 0.2] -- a flat wide slab, not a
+# cube) parenting a "head" (unit sphere) via a REAL parent reference, not "root".
+# Nothing in this repo's templates currently authors this shape of spec (every
+# existing template parents every part to "root" -- see new_sculpt_spec.py's
+# `_cnode(..., "root", ...)` calls) but the schema and the generator must both
+# support it once WS-E lands, which is exactly what this test exercises directly.
+NESTED_SCALE_SPEC = {
+ "targetName": "Nested Scale Rig",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [{"id": "clay"}],
+ "componentTree": [
+ {
+ "id": "torso",
+ "name": "Torso",
+ "level": "macro",
+ "role": "body",
+ "primitive": "box",
+ "parent": None,
+ "material": "clay",
+ "transform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [3.0, 1.0, 0.2]},
+ },
+ {
+ "id": "head",
+ "name": "Head",
+ "level": "macro",
+ "role": "body",
+ "primitive": "sphere",
+ "parent": "torso",
+ "material": "clay",
+ "transform": {"position": [0.3, 2.0, 0.3], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},
+ },
+ ],
+}
+
+
+def compile_generated_module(generated: str, work_dir: Path) -> tuple[subprocess.CompletedProcess[str], Path]:
+ source = work_dir / "hierarchy-scale.ts"
+ build_dir = work_dir / "build"
+ source.write_text(generated, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "npx", "tsc", "--target", "ES2020", "--module", "NodeNext", "--moduleResolution", "NodeNext",
+ "--strict", "--skipLibCheck", "--noUnusedLocals", "--noUnusedParameters",
+ "--outDir", str(build_dir), str(source),
+ ],
+ cwd=showcase_root(),
+ capture_output=True,
+ text=True,
+ )
+ return result, build_dir / "hierarchy-scale.js"
+
+
+# Rotate the parent 90 degrees about Y after the first measurement: the head's local
+# offset has nonzero X and Z (see NESTED_SCALE_SPEC above) so this is guaranteed to
+# move it, unlike a rotation axis the offset happens to sit on.
+_EVAL_SCRIPT = """
+import * as THREE from 'three';
+import { createNestedScaleRigModel } from './build/hierarchy-scale.js';
+
+const model = createNestedScaleRigModel();
+const torso = model.userData.sculptRuntime.nodes['torso'];
+const head = model.userData.sculptRuntime.nodes['head'];
+const headMesh = model.userData.sculptRuntime.meshes['head'];
+
+headMesh.geometry.computeBoundingBox();
+const localBox = headMesh.geometry.boundingBox;
+const localExtent = [
+ localBox.max.x - localBox.min.x,
+ localBox.max.y - localBox.min.y,
+ localBox.max.z - localBox.min.z,
+];
+
+model.updateMatrixWorld(true);
+const worldBoxBefore = new THREE.Box3().setFromObject(headMesh);
+const worldExtentBefore = [
+ worldBoxBefore.max.x - worldBoxBefore.min.x,
+ worldBoxBefore.max.y - worldBoxBefore.min.y,
+ worldBoxBefore.max.z - worldBoxBefore.min.z,
+];
+const worldPosBefore = new THREE.Vector3();
+head.getWorldPosition(worldPosBefore);
+
+torso.rotation.set(0, Math.PI / 2, 0);
+model.updateMatrixWorld(true);
+const worldPosAfter = new THREE.Vector3();
+head.getWorldPosition(worldPosAfter);
+
+console.log(JSON.stringify({
+ torsoScale: torso.scale.toArray(),
+ headScale: head.scale.toArray(),
+ localExtent,
+ worldExtentBefore,
+ worldPosBefore: worldPosBefore.toArray(),
+ worldPosAfter: worldPosAfter.toArray(),
+}));
+"""
+
+
+class HierarchyScaleTest(unittest.TestCase):
+ result: dict
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ errors, _warnings = validate_spec(NESTED_SCALE_SPEC)
+ if errors:
+ raise RuntimeError(f"FAIL CLOSED: fixture spec did not validate: {errors}")
+ generated = generate(NESTED_SCALE_SPEC, "blockout")
+
+ cls._tempdir_ctx = tempfile.TemporaryDirectory(dir=showcase_root())
+ work_dir = Path(cls._tempdir_ctx.name)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ if compile_result.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: tsc did not compile the emitted module: {compile_result.stderr}")
+
+ runtime = subprocess.run(
+ ["node", "--input-type=module", "--eval", _EVAL_SCRIPT],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ if runtime.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: node execution of the emitted module failed: {runtime.stderr}")
+ try:
+ cls.result = json.loads(runtime.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"FAIL CLOSED: result was not parseable JSON: {exc}\nstdout: {runtime.stdout!r}") from exc
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls._tempdir_ctx.cleanup()
+
+ def test_pivot_nodes_always_carry_identity_scale(self) -> None:
+ # WS-E: the hierarchy transform (the pivot Group) never carries a part's shape
+ # dimensions -- not even for "torso", whose authored scale [3, 1, 0.2] is
+ # sharply non-uniform. If this regresses to node.scale.set(componentScale),
+ # this assertion catches it directly.
+ self.assertEqual(self.result["torsoScale"], [1, 1, 1])
+ self.assertEqual(self.result["headScale"], [1, 1, 1])
+
+ def test_child_geometry_is_not_distorted_by_a_nonuniform_parent(self) -> None:
+ # "head" is an authored unit sphere (scale [1, 1, 1]). Its OWN local geometry
+ # must be a plain unit sphere (diameter 1 on every axis) regardless of what its
+ # parent "torso" declares.
+ for axis, extent in enumerate(self.result["localExtent"]):
+ self.assertAlmostEqual(extent, 1.0, places=3, msg=f"axis {axis}: local geometry is distorted")
+
+ def test_child_world_shape_is_undistorted_by_a_nonuniform_parent(self) -> None:
+ # This is the mutation check: torso's non-uniform scale [3, 1, 0.2] must not
+ # cascade onto head through the THREE.Group hierarchy. Reverting the WS-E fix
+ # (re-applying component scale to node.scale instead of to the geometry) makes
+ # torso's runtime Group.scale become [3, 1, 0.2]; since head is parented under
+ # torso, head's world bounding box would then measure roughly
+ # [3, 1, 0.2] instead of [1, 1, 1] -- an egg-shaped head. This assertion fails
+ # under that regression and passes under the fix.
+ for axis, extent in enumerate(self.result["worldExtentBefore"]):
+ self.assertAlmostEqual(extent, 1.0, places=2, msg=f"axis {axis}: world shape is distorted by parent scale")
+
+ def test_rotating_parent_moves_descendant(self) -> None:
+ # Definition of done #2: rotating a parent node must move its descendants --
+ # position/rotation still cascade through the Group chain exactly as before.
+ self.assertNotEqual(self.result["worldPosBefore"], self.result["worldPosAfter"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_humanoid_proportions.py b/forge/tests/test_humanoid_proportions.py
new file mode 100644
index 0000000..ce5dc6a
--- /dev/null
+++ b/forge/tests/test_humanoid_proportions.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""A reference-free humanoid must be expressible without fabricating anatomy.
+
+`validate_sculpt_spec.py` blocks a character spec until `anatomy.applies` is true, which is
+correct when a reference exists — a specific person's proportions are evidence. It also made
+"build me a stylized humanoid, no reference" impossible to state. `humanoid_proportions.py`
+supplies public figure-drawing canon for that case and labels it as canon.
+
+The properties worth pinning are the honesty ones: canon must never masquerade as measured
+evidence, and a head count the corpus does not actually cover must fail loudly rather than
+be interpolated into existence.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "_shared")]
+
+from humanoid_proportions import ( # noqa: E402
+ CANON_BY_HEADS,
+ PARTIAL_CANON_BY_HEADS,
+ SUPPORTED_HEADS,
+ apply_to_spec,
+ derive_anatomy,
+)
+from validate_sculpt_spec import is_number # noqa: E402
+
+
+class CanonTest(unittest.TestCase):
+ def test_eight_head_canon_satisfies_the_character_gate(self) -> None:
+ """The gate wants a positive torso OR legs head-unit ratio, plus a face landmark."""
+ anatomy = derive_anatomy(8)
+ self.assertIs(anatomy["applies"], True)
+ proportions = anatomy["proportions"]
+ self.assertTrue(
+ any(is_number(proportions.get(k)) and float(proportions[k]) > 0
+ for k in ("torso", "legs")),
+ proportions,
+ )
+ landmarks = anatomy["faceLandmarks"]
+ self.assertTrue(
+ any(is_number(landmarks.get(k)) and float(landmarks[k]) > 0
+ for k in ("eyeLine", "noseBase", "mouthLine")),
+ landmarks,
+ )
+
+ def test_the_classic_head_torso_legs_split_adds_up(self) -> None:
+ anatomy = derive_anatomy(8)
+ proportions = anatomy["proportions"]
+ self.assertEqual(proportions["torso"], 3.0)
+ self.assertEqual(proportions["legs"], 4.0)
+ # head (1) + torso (3) + legs (4) == styleHeads
+ self.assertEqual(1 + proportions["torso"] + proportions["legs"], 8)
+
+ def test_canon_is_labelled_as_canon_not_as_reference(self) -> None:
+ self.assertEqual(derive_anatomy(8)["source"], "canon-table")
+
+ def test_unsourced_landmarks_are_named_rather_than_invented(self) -> None:
+ anatomy = derive_anatomy(8)
+ self.assertTrue(anatomy["unsourced"])
+ for key in anatomy["unsourced"]:
+ self.assertNotIn(key, anatomy["proportions"], f"{key} is listed unsourced yet present")
+
+
+class IncompleteCanonTest(unittest.TestCase):
+ def test_a_head_count_without_a_hip_line_is_refused(self) -> None:
+ """4-head limb lengths are sourced; its hip line is not, so it must not be derived.
+
+ The corpus was asked directly for the 4-head hip line, torso span, leg span and
+ shoulder width and answered NOT IN SOURCES for all four.
+ """
+ self.assertIn(4, PARTIAL_CANON_BY_HEADS)
+ self.assertNotIn(4, CANON_BY_HEADS)
+ with self.assertRaises(ValueError) as caught:
+ derive_anatomy(4)
+ message = str(caught.exception)
+ self.assertIn("hipLineY", message)
+ self.assertIn("4", message)
+
+ def test_supported_heads_are_exactly_the_complete_tables(self) -> None:
+ self.assertEqual(set(SUPPORTED_HEADS), set(CANON_BY_HEADS))
+
+ def test_nonsense_head_counts_are_refused(self) -> None:
+ for bad in (0, -8, "8", True, None):
+ with self.assertRaises(ValueError):
+ derive_anatomy(bad)
+
+
+class SpecApplicationTest(unittest.TestCase):
+ def test_canon_is_refused_when_the_spec_names_a_reference(self) -> None:
+ """Otherwise a gate that demands evidence silently starts accepting a default."""
+ with self.assertRaises(ValueError) as caught:
+ apply_to_spec({"sourceImage": "warrior.png"}, 8)
+ self.assertIn("measure anatomy from it", str(caught.exception))
+
+ def test_canon_is_allowed_when_there_is_no_reference(self) -> None:
+ for spec in ({}, {"sourceImage": ""}, {"sourceImage": "/dev/null"}):
+ filled = apply_to_spec(dict(spec), 8)
+ self.assertIs(filled["preSpecAssessment"]["anatomy"]["applies"], True)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_humanoid_silhouette_profile.py b/forge/tests/test_humanoid_silhouette_profile.py
new file mode 100644
index 0000000..ea43e92
--- /dev/null
+++ b/forge/tests/test_humanoid_silhouette_profile.py
@@ -0,0 +1,273 @@
+"""Whole-silhouette assertions on the BUILT humanoid — the kind of check that was missing.
+
+Every other rig test in this suite is PER-PART: a bbox, a propagation delta, a weight sum. Those
+cannot see facts that only exist across the whole figure, and the first render proved it — 452
+tests were green while the model had a tabletop for a pelvis and a neck 40% the length of its
+torso. Every individual part was correct.
+
+So these tests measure the silhouette's width as a function of height, the same instrument used on
+the reference grey sculpt, and assert shape properties rather than dimensions:
+
+- a slab shows up as consecutive bands of IDENTICAL width (flat vertical sides);
+- a tabletop shows up as the hip band exceeding the torso above it;
+- a missing shoulder means the neck band jumps straight to full torso width with no intermediate.
+
+Reference figures, measured from the ZBrush grey sculpt of nguy-n-khoa-overview.jpg (848px tall):
+hair 0.136 w/h, neck 0.116, shoulders 0.229, widest 0.290.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+_TESTS = Path(__file__).resolve().parent
+_FORGE = _TESTS.parent
+for path in (_TESTS, _FORGE, _FORGE / "stage2_spec", _FORGE / "stage3_build"):
+ sys.path.insert(0, str(path))
+
+try:
+ from .showcase_test_support import showcase_root
+except ImportError:
+ from showcase_test_support import showcase_root
+
+from generate_threejs_factory import generate # noqa: E402
+
+BANDS = 20
+
+_VERTEX_PROBE = """
+import { %(factory)s } from './build/%(stem)s.js';
+import * as THREE from 'three';
+const m = %(factory)s(); m.updateMatrixWorld(true);
+const pts = [];
+m.traverse((o) => {
+ if (!o.isMesh || !o.geometry) return;
+ const mat = o.material;
+ const op = Array.isArray(mat) ? 1 : (mat && mat.opacity !== undefined ? mat.opacity : 1);
+ if (op === 0) return; // the invisible 1x1x1 root placeholder
+ const pos = o.geometry.getAttribute('position'); if (!pos) return;
+ const v = new THREE.Vector3();
+ for (let i = 0; i < pos.count; i++) {
+ v.fromBufferAttribute(pos, i).applyMatrix4(o.matrixWorld);
+ pts.push([v.x, v.y]);
+ }
+});
+console.log(JSON.stringify(pts));
+"""
+
+
+class HumanoidSilhouetteProfile(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.root = showcase_root() # skips with an actionable message when unset
+ cls.profile = cls._profile_for(None)
+
+ @classmethod
+ def _profile_for(cls, anatomy: dict | None) -> list[float | None]:
+ """Build the model for a given anatomy and return its width-by-height profile.
+
+ Parameterised by anatomy because a silhouette defect can be invisible at one set of
+ proportions and obvious at another — the shoulder cliff only appears on a narrow-shouldered
+ figure, so a test that only ever builds the default template cannot see it.
+ """
+ work_dir = Path(tempfile.mkdtemp())
+ argv = [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Silhouette Probe", "--character", "--out", str(work_dir / "character.json")]
+ if anatomy is not None:
+ assessment = work_dir / "assessment.json"
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_pre_spec_assessment.py"),
+ "Silhouette Probe", "--complexity", "complex", "--out", str(assessment)],
+ capture_output=True, text=True, check=True,
+ )
+ payload = json.loads(assessment.read_text())
+ pre = payload["preSpecAssessment"]
+ pre["anatomy"] = anatomy
+ pre.setdefault("objectClass", {})["primaryDomain"] = "character"
+ assessment.write_text(json.dumps(payload))
+ argv += ["--assessment", str(assessment)]
+ subprocess.run(argv, capture_output=True, text=True, check=True)
+ spec = json.loads((work_dir / "character.json").read_text())
+ generated = generate(spec, "blockout")
+ factory = re.search(r"export function (create\w+Model)", generated).group(1)
+
+ with tempfile.TemporaryDirectory(dir=cls.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(generated, work)
+ if compiled.returncode != 0:
+ raise AssertionError(f"tsc failed:\n{compiled.stderr[:2000]}")
+ run = subprocess.run(
+ ["node", "--max-old-space-size=2048", "--input-type=module", "--eval",
+ _VERTEX_PROBE % {"factory": factory, "stem": module_path.stem}],
+ cwd=work, capture_output=True, text=True,
+ )
+ if run.returncode != 0:
+ raise AssertionError(f"node failed:\n{run.stderr[:2000]}")
+ points = json.loads(run.stdout.strip().splitlines()[-1])
+
+ ys = [p[1] for p in points]
+ low, high = min(ys), max(ys)
+ height = high - low
+ cls.height = height
+ profile: list[float | None] = []
+ for band in range(BANDS):
+ y0 = high - height * (band + 1) / BANDS
+ y1 = high - height * band / BANDS
+ xs = [p[0] for p in points if y0 <= p[1] <= y1]
+ profile.append((max(xs) - min(xs)) / height if xs else None)
+ return profile
+
+ def test_the_profile_is_measurable(self) -> None:
+ self.assertGreater(self.height, 0)
+ self.assertTrue(all(w is not None for w in self.profile),
+ f"a band is empty, so the figure has a gap: {self.profile}")
+
+ def test_no_body_segment_is_a_slab(self) -> None:
+ """The tabletop test, done on the SPEC rather than the silhouette.
+
+ I first wrote this as "no three consecutive profile bands share a width", reasoning that a
+ box's flat vertical sides would show up as identical widths. Mutation-checking it proved
+ that WRONG: reverting the pelvis to a box still passed, because at 20 bands the thighs and
+ abdomen overlap the pelvis's bands and break the identical-width signature. That was dead
+ coverage — a test that looked like it guarded the defect and did not.
+
+ The defect is an aspect ratio, so measure the aspect ratio. The pelvis that rendered as a
+ tabletop was 0.455 wide by 0.123 tall: 3.7:1. No body segment should be that flat.
+ """
+ out = Path(tempfile.mkdtemp()) / "aspect.json"
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Aspect Probe", "--character", "--out", str(out)],
+ capture_output=True, text=True, check=True,
+ )
+ spec = json.loads(out.read_text())
+ for component in spec["componentTree"]:
+ if component.get("role") in (None, "detail", "hair", "decal", "panel"):
+ continue
+ scale = (component.get("transform") or {}).get("scale") or [1, 1, 1]
+ width, height, depth = (float(v) for v in scale)
+ if height <= 0:
+ continue
+ # `min(width, depth) / height`, not `max`. A slab has TWO large dimensions and one
+ # small — wide AND deep but short. A limb bone has ONE large and two small. Using
+ # `max` conflated them and flagged `clavicle-l` (0.271 x 0.095 x 0.095), which is a
+ # legitimately long thin bone. Measured with `min`: the tabletop pelvis scores 2.92,
+ # the corrected pelvis 1.25, and the clavicle 1.00.
+ slabness = min(width, depth) / height
+ self.assertLess(
+ slabness, 2.0,
+ f"{component['id']!r} is {width:.4f} x {height:.4f} x {depth:.4f} — both of its "
+ f"horizontal extents are {slabness:.2f}x its height, which reads as a slab",
+ )
+
+ # DELETED: an assertion that hips must not be wider than the torso above them.
+ #
+ # It failed on the DEFAULT template and it was the test that was wrong, twice over. Its band
+ # indices were hardcoded, so they do not survive a different `torso` ratio moving the pelvis
+ # into a different band. And more fundamentally the rule is not universally true: a pear-shaped
+ # figure legitimately has wider hips than chest, and the regret reference is measurably one —
+ # narrow shoulders (1.552 HU) against wide hips (1.712 HU). The actual defect was never
+ # "hips wider than torso"; it was "the pelvis is a flat slab", which
+ # test_no_three_consecutive_bands_share_a_width catches directly and without assuming a body
+ # type. Same failure mode as the first MONOTONIC_CHAIN: a check that rejects a legitimate case.
+
+ def test_the_neck_to_shoulder_transition_is_a_slope_not_a_cliff(self) -> None:
+ """Run against a NARROW-SHOULDERED anatomy, because that is where the cliff appears.
+
+ Asserted against the default template this test was dead coverage: mutation-checking it by
+ restoring the thin clavicle and the chest's wide flat top did NOT fail it, because at the
+ default shoulderWidth of 2.3 HU the chest is broad enough that band 3 lands between head
+ and torso anyway. The cliff only manifested at the regret reference's measured 1.552 HU.
+ A test has to exercise the configuration that produced the bug.
+ """
+ profile = self._profile_for({
+ "applies": True,
+ "styleHeads": 6.78,
+ "proportions": {"torso": 1.584, "legs": 3.384,
+ "shoulderWidth": 1.552, "hipWidth": 1.712},
+ })
+ head = max(w for w in profile[0:3] if w is not None)
+ torso = max(w for w in profile[4:7] if w is not None)
+ shoulder = profile[3]
+ self.assertIsNotNone(shoulder)
+ self.assertGreater(shoulder, head,
+ "the shoulder band is no wider than the head — no shoulder mass")
+ self.assertLess(shoulder, torso,
+ f"shoulder band {shoulder:.4f} already equals torso width {torso:.4f} — "
+ f"the silhouette jumps from neck to full width in one band")
+
+ def test_the_figure_tapers_toward_the_feet(self) -> None:
+ """Legs must narrow. A humanoid that is as wide at the ankles as at the hips is a tube."""
+ hips = max(self.profile[8:11])
+ ankles = self.profile[-1]
+ self.assertLess(ankles, hips * 0.75,
+ f"ankle band {ankles:.4f} against hips {hips:.4f} — the legs do not taper")
+
+ def test_no_component_emits_empty_geometry(self) -> None:
+ """A specified component whose mesh has no extent does not exist in the model.
+
+ This is the check that was missing, and it hid a real defect for the whole of US-004: both
+ eye cavities emitted EMPTY geometry. `polygonizeSdf` falls back to a
+ [-2,-2,-2]..[2,2,2] sampling box when the descriptor omits `bounds`, and at resolution 20
+ that makes each cell 0.2 across while the socket's shell radius is 0.0252 — the entire
+ sphere fell between samples and marching cubes emitted nothing. Meanwhile the spec said
+ `subtract`, the validator's recessed-feature gate was satisfied by exactly that, and the
+ whole suite was green. The eyes were "recessed sockets" in the spec and absent in the model.
+ """
+ probe = """
+import { %(factory)s } from './build/%(stem)s.js';
+import * as THREE from 'three';
+const m = %(factory)s(); m.updateMatrixWorld(true);
+const empty = [];
+for (const [id, mesh] of Object.entries(m.userData.sculptRuntime.meshes)) {
+ const b = new THREE.Box3().setFromObject(mesh);
+ if (b.isEmpty() || !Number.isFinite(b.min.x) || !Number.isFinite(b.max.x)) empty.push(id);
+}
+console.log(JSON.stringify({ empty, total: Object.keys(m.userData.sculptRuntime.meshes).length }));
+"""
+ work_dir = Path(tempfile.mkdtemp())
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Empty Probe", "--character", "--out", str(work_dir / "c.json")],
+ capture_output=True, text=True, check=True,
+ )
+ generated = generate(json.loads((work_dir / "c.json").read_text()), "blockout")
+ factory = re.search(r"export function (create\w+Model)", generated).group(1)
+ with tempfile.TemporaryDirectory(dir=self.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(generated, work)
+ self.assertEqual(compiled.returncode, 0, compiled.stderr)
+ run = subprocess.run(
+ ["node", "--input-type=module", "--eval",
+ probe % {"factory": factory, "stem": module_path.stem}],
+ cwd=work, capture_output=True, text=True,
+ )
+ self.assertEqual(run.returncode, 0, f"{run.stdout}\n{run.stderr}")
+ data = json.loads(run.stdout.strip().splitlines()[-1])
+
+ self.assertGreater(data["total"], 0, "no meshes at all — the probe measured nothing")
+ self.assertEqual(
+ data["empty"], [],
+ f"{len(data['empty'])} of {data['total']} components emit geometry with no extent, so "
+ f"they are specified but absent from the model: {data['empty']}",
+ )
+
+ def test_head_width_is_in_the_reference_range(self) -> None:
+ """Reference grey sculpt: the hair mass is 0.136 of figure height. A stylised head is
+ large, but a head half the figure's width is a different character."""
+ head = max(self.profile[0:3])
+ self.assertGreater(head, 0.08, f"head {head:.4f} is too narrow for a stylised figure")
+ self.assertLess(head, 0.22, f"head {head:.4f} is wider than any reference band")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_joint_admission_gate.py b/forge/tests/test_joint_admission_gate.py
new file mode 100644
index 0000000..3d75249
--- /dev/null
+++ b/forge/tests/test_joint_admission_gate.py
@@ -0,0 +1,167 @@
+"""PLAN_1.5 §5.2 Half A — the Joint Admission Gate's five semantic checks.
+
+Every check gets the real 49-bone template as its passing fixture and a deliberate mutation as its
+failing one, because a gate nobody has watched reject something is not a gate yet.
+
+Two readings are recorded here rather than left implicit, since neither is stated outright in the
+plan and both change what the gate does:
+
+- `MONOTONIC_CHAIN` compares DIRECTION, not distance from the root. Implemented as
+ distance-from-root it rejected the correct template on ten bones: a clavicle reaches up to the
+ shoulder and the upper arm then hangs back down toward the hips, so euclidean reach is
+ legitimately non-monotonic for any chain that goes out and then down.
+- `PROPORTION_LIMIT` is a fraction of the skeleton's own height rather than head units, because
+ the rig carries no head unit and requiring `anatomy.proportions` would reject the default
+ `--character` template outright.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+_FORGE = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(_FORGE / "stage2_spec"))
+
+from validate_sculpt_spec import ( # noqa: E402
+ POOL_FLOOR_MIN_BONES,
+ SYMMETRY_PARITY_TOLERANCE,
+ _mirror_partner,
+ validate_rig_admission,
+)
+
+
+def _tags(errors: list[str]) -> set[str]:
+ return {message.split(":")[0] for message in errors}
+
+
+class JointAdmissionGate(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ out = Path(tempfile.mkdtemp()) / "character.json"
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Gate Probe", "--character", "--out", str(out)],
+ capture_output=True, text=True, check=True,
+ )
+ cls.base = json.loads(out.read_text())
+
+ def _run(self, mutate=None) -> tuple[dict, set[str], list[str]]:
+ spec = copy.deepcopy(self.base)
+ if mutate:
+ mutate(spec)
+ errors: list[str] = []
+ warnings: list[str] = []
+ validate_rig_admission(spec, errors, warnings)
+ return spec, _tags(errors), warnings
+
+ def _bones(self, spec: dict) -> dict:
+ return {b["id"]: b for b in spec["rig"]["bones"]}
+
+ # ---- the passing fixture, shared by all five ----
+ def test_the_real_template_passes_every_check(self) -> None:
+ _, tags, warnings = self._run()
+ self.assertEqual(tags, set(), "the real 49-bone template must satisfy the gate")
+ self.assertEqual(warnings, [])
+
+ def test_pivot_track_is_a_no_op(self) -> None:
+ """No `rig` key means an object spec, which this gate must not touch at all."""
+ spec = copy.deepcopy(self.base)
+ spec.pop("rig")
+ errors: list[str] = []
+ warnings: list[str] = []
+ validate_rig_admission(spec, errors, warnings)
+ self.assertEqual((errors, warnings), ([], []))
+
+ # ---- NAME_UNIQUENESS ----
+ def test_name_uniqueness_rejects_a_duplicate_id(self) -> None:
+ _, tags, _ = self._run(lambda s: s["rig"]["bones"].append(dict(s["rig"]["bones"][3])))
+ self.assertIn("NAME_UNIQUENESS", tags)
+
+ def test_name_uniqueness_rejects_two_roots(self) -> None:
+ _, tags, _ = self._run(lambda s: s["rig"]["bones"][5].update(parent=None))
+ self.assertIn("NAME_UNIQUENESS", tags)
+
+ def test_name_uniqueness_rejects_a_dangling_parent(self) -> None:
+ _, tags, _ = self._run(lambda s: s["rig"]["bones"][7].update(parent="ghost"))
+ self.assertIn("NAME_UNIQUENESS", tags)
+
+ # ---- POOL_FLOOR ----
+ def test_pool_floor_rejects_a_skeleton_below_four_bones(self) -> None:
+ _, tags, _ = self._run(
+ lambda s: s["rig"].update(bones=s["rig"]["bones"][: POOL_FLOOR_MIN_BONES - 1]))
+ self.assertIn("POOL_FLOOR", tags)
+
+ # ---- MONOTONIC_CHAIN ----
+ def test_monotonic_chain_rejects_a_reversed_bone(self) -> None:
+ def reverse_forearm(spec: dict) -> None:
+ bones = self._bones(spec)
+ upper = bones["upper-arm-l"]
+ delta = [upper["tipPos"][i] - upper["jointPos"][i] for i in range(3)]
+ joint = bones["forearm-l"]["jointPos"]
+ bones["forearm-l"]["tipPos"] = [joint[i] - delta[i] for i in range(3)]
+
+ _, tags, _ = self._run(reverse_forearm)
+ self.assertIn("MONOTONIC_CHAIN", tags)
+
+ def test_monotonic_chain_accepts_a_thumb_at_right_angles_to_its_palm(self) -> None:
+ """The threshold is deliberately generous. A thumb sits near 90 degrees to the hand and
+ is not folded back; only a substantially inverted bone should fail."""
+ _, tags, _ = self._run()
+ self.assertNotIn("MONOTONIC_CHAIN", tags)
+
+ # ---- PROPORTION_LIMIT ----
+ def test_proportion_limit_rejects_an_oversized_bone(self) -> None:
+ def giant_femur(spec: dict) -> None:
+ bones = self._bones(spec)
+ joint = bones["thigh-l"]["jointPos"]
+ bones["thigh-l"]["tipPos"] = [joint[0], joint[1] - 3.0, joint[2]]
+
+ _, tags, _ = self._run(giant_femur)
+ self.assertIn("PROPORTION_LIMIT", tags)
+
+ # ---- SYMMETRY_PARITY: snaps, does NOT reject ----
+ def test_symmetry_parity_snaps_instead_of_rejecting(self) -> None:
+ def skew_right_arm(spec: dict) -> None:
+ bones = self._bones(spec)
+ bones["upper-arm-r"]["jointPos"] = [
+ bones["upper-arm-r"]["jointPos"][0] + 0.4, 0.9, 0.3]
+
+ spec, tags, warnings = self._run(skew_right_arm)
+ self.assertNotIn("SYMMETRY_PARITY", tags, "§5.2 says snap on fail, not reject")
+ self.assertTrue(any("SYMMETRY_PARITY" in w for w in warnings))
+ bones = self._bones(spec)
+ left = bones["upper-arm-l"]["jointPos"]
+ right = bones["upper-arm-r"]["jointPos"]
+ for axis, (expected, actual) in enumerate(zip([-left[0], left[1], left[2]], right)):
+ self.assertAlmostEqual(expected, actual, places=4,
+ msg=f"axis {axis} was not snapped to the mirror")
+
+ def test_symmetry_parity_handles_a_side_marker_in_the_middle_of_an_id(self) -> None:
+ """Digit ids carry the side in the middle (`thumb-l-1`). Matching only a trailing `-l`
+ would silently skip all thirty phalanges — most of the skeleton."""
+ self.assertEqual(_mirror_partner("upper-arm-l"), "upper-arm-r")
+ self.assertEqual(_mirror_partner("thumb-l-1"), "thumb-r-1")
+ self.assertIsNone(_mirror_partner("chest"))
+ self.assertIsNone(_mirror_partner("upper-arm-r"))
+
+ def skew_digit(spec: dict) -> None:
+ self._bones(spec)["thumb-r-2"]["jointPos"] = [0.1, 0.5, 0.5]
+
+ _, tags, warnings = self._run(skew_digit)
+ self.assertNotIn("SYMMETRY_PARITY", tags)
+ self.assertTrue(any("thumb-r-2" in w for w in warnings))
+
+ def test_symmetry_tolerance_is_the_documented_value(self) -> None:
+ self.assertEqual(SYMMETRY_PARITY_TOLERANCE, 0.05)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_joint_loops.py b/forge/tests/test_joint_loops.py
new file mode 100644
index 0000000..01d7b2e
--- /dev/null
+++ b/forge/tests/test_joint_loops.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""Tests for the joint edge-loop gate.
+
+The load-bearing one is `test_a_dense_two_ring_joint_still_fails`: ten thousand vertices arranged in
+two rings cannot bend, and a gate that counted vertices instead of bands would call that mesh dense
+and wave it through. Counting the wrong thing is the only way this gate can be useless, so that is
+what gets pinned.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import math
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from joint_loops import analyze_joint_loops, count_loops_at_joint # noqa: E402
+
+
+def limb(rings: int, segments: int = 12, radius: float = 0.5, length: float = 1.0):
+ """A tube along +y with `rings` rings of vertices, centred on the origin.
+
+ Length 1.0 against the 2.0-long ELBOW bone puts every ring inside the gate's axial window
+ (0.35 x bone length = 0.7). A longer tube parks its rings outside the window entirely, which the
+ gate correctly scores as zero loops -- a real defect, but a different one from "too few bands",
+ and not what these tests are measuring.
+ """
+ vertices = []
+ for ring in range(rings):
+ y = -length / 2 + length * ring / max(1, rings - 1)
+ for segment in range(segments):
+ angle = 2 * math.pi * segment / segments
+ vertices.append([radius * math.cos(angle), y, radius * math.sin(angle)])
+ return vertices
+
+
+ELBOW = {"id": "elbow", "jointPos": [0.0, 0.0, 0.0], "tipPos": [0.0, 2.0, 0.0]}
+
+
+class LoopCounting(unittest.TestCase):
+ def test_a_dense_two_ring_joint_still_fails(self) -> None:
+ # 600 vertices, two rings. Vertex count says "dense"; the joint cannot bend.
+ vertices = limb(rings=2, segments=300)
+ result = analyze_joint_loops([{"vertices": vertices}], [ELBOW])
+ self.assertEqual(result["joints"][0]["loops"], 2)
+ self.assertGreater(result["joints"][0]["vertexCount"], 100)
+ self.assertFalse(result["passed"])
+
+ def test_a_sparse_five_ring_joint_passes(self) -> None:
+ # 30 vertices, five rings. Far fewer vertices than the failing case above, and correct.
+ vertices = limb(rings=5, segments=6)
+ result = analyze_joint_loops([{"vertices": vertices}], [ELBOW])
+ self.assertGreaterEqual(result["joints"][0]["loops"], 3)
+ self.assertLess(result["joints"][0]["vertexCount"], 100)
+ self.assertTrue(result["passed"])
+
+ def test_loop_count_is_scale_invariant(self) -> None:
+ # The same character at two scales must score the same, or the threshold is measuring units.
+ small = limb(rings=5, segments=8, radius=0.5, length=2.0)
+ big = [[c * 100 for c in v] for v in small]
+ small_result = count_loops_at_joint(small, [0, 0, 0], [0, 0, 0], [0, 2, 0], 0.7)
+ big_result = count_loops_at_joint(big, [0, 0, 0], [0, 0, 0], [0, 200, 0], 70.0)
+ self.assertEqual(small_result["loops"], big_result["loops"])
+
+ def test_vertices_outside_the_radius_are_ignored(self) -> None:
+ near = limb(rings=4, segments=8, length=1.0)
+ far = [[0.0, 50.0 + i, 0.0] for i in range(20)]
+ with_far = count_loops_at_joint(near + far, [0, 0, 0], [0, 0, 0], [0, 2, 0], 0.8)
+ without = count_loops_at_joint(near, [0, 0, 0], [0, 0, 0], [0, 2, 0], 0.8)
+ self.assertEqual(with_far["loops"], without["loops"])
+
+
+class GateBehaviour(unittest.TestCase):
+ def test_failure_names_the_bone_and_says_what_happens(self) -> None:
+ result = analyze_joint_loops([{"vertices": limb(rings=2)}], [ELBOW])
+ self.assertEqual(result["failingJointCount"], 1)
+ self.assertIn("elbow", result["failures"][0])
+ self.assertIn("crease", result["failures"][0])
+
+ def test_meshes_are_pooled_so_a_seam_joint_is_not_half_measured(self) -> None:
+ # A joint where two components meet: each half alone has too few rings, together they are fine.
+ # Measuring per mesh would fail a joint that is actually correct.
+ lower = [[0.4 * math.cos(a), y, 0.4 * math.sin(a)]
+ for y in (-0.30, -0.15) for a in [i * math.pi / 4 for i in range(8)]]
+ upper = [[0.4 * math.cos(a), y, 0.4 * math.sin(a)]
+ for y in (0.15, 0.30) for a in [i * math.pi / 4 for i in range(8)]]
+ pooled = analyze_joint_loops([{"vertices": lower}, {"vertices": upper}], [ELBOW])
+ self.assertGreaterEqual(pooled["joints"][0]["loops"], 4)
+ self.assertTrue(pooled["passed"])
+
+ def test_zero_length_bone_is_reported_not_divided_by(self) -> None:
+ degenerate = {"id": "stub", "jointPos": [0.0, 0.0, 0.0], "tipPos": [0.0, 0.0, 0.0]}
+ result = analyze_joint_loops([{"vertices": limb(rings=5)}], [degenerate])
+ self.assertEqual(result["joints"][0]["loops"], 0)
+ self.assertFalse(result["passed"])
+
+ def test_no_vertices_raises(self) -> None:
+ with self.assertRaises(ValueError):
+ analyze_joint_loops([{"vertices": []}], [ELBOW])
+
+ def test_min_loops_is_configurable(self) -> None:
+ vertices = limb(rings=3, segments=8)
+ self.assertTrue(analyze_joint_loops([{"vertices": vertices}], [ELBOW], min_loops=3)["passed"])
+ self.assertFalse(analyze_joint_loops([{"vertices": vertices}], [ELBOW], min_loops=6)["passed"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_jpeg.py b/forge/tests/test_jpeg.py
new file mode 100644
index 0000000..d72eb67
--- /dev/null
+++ b/forge/tests/test_jpeg.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Tests for the pure-stdlib baseline JPEG decoder.
+
+The fixture is embedded rather than generated so these run identically on Linux
+CI, where the macOS `sips` converter this decoder replaces does not exist.
+"""
+
+from __future__ import annotations
+
+import base64
+import shutil
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "_shared"))
+sys.path.insert(0, str(ROOT / "stage1_intake"))
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
+
+# 32x32 baseline JPEG: left half red (200,30,40), right half blue (30,60,200).
+FIXTURE_B64 = (
+ "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAA"
+ "A6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAD/7QA4UGhvdG9zaG9wIDMu"
+ "MAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAIAAgAwEiAAIR"
+ "AQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAAB"
+ "fQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5"
+ "OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeo"
+ "qaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMB"
+ "AQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYS"
+ "QVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNU"
+ "VVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5"
+ "usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICAwICAwUDAwMF"
+ "BgUFBQUGCAYGBgYGCAoICAgICAgKCgoKCgoKCgwMDAwMDA4ODg4ODw8PDw8PDw8PD//bAEMBAgIC"
+ "BAQEBwQEBxALCQsQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ"
+ "EBAQEP/dAAQAAv/aAAwDAQACEQMRAD8A+R6KKK/Hz/VA4Oiiiv8AYw/xHP/Q+R6KKK/Hz/VA4Oii"
+ "iv8AYw/xHP/Z"
+)
+FIXTURE = base64.b64decode("".join(FIXTURE_B64.split()))
+
+
+class JpegDecoderTest(unittest.TestCase):
+ def test_is_jpeg_detects_signature(self):
+ self.assertTrue(is_jpeg(FIXTURE))
+ self.assertFalse(is_jpeg(b"\x89PNG\r\n\x1a\n"))
+ self.assertFalse(is_jpeg(b""))
+
+ def test_decodes_expected_dimensions(self):
+ width, height, pixels = decode_jpeg(FIXTURE)
+ self.assertEqual((width, height), (32, 32))
+ self.assertEqual(len(pixels), 32 * 32)
+ self.assertTrue(all(len(p) == 4 and p[3] == 255 for p in pixels))
+
+ def test_decodes_correct_colours(self):
+ # JPEG is lossy, so assert the hue is right rather than exact bytes.
+ width, _height, pixels = decode_jpeg(FIXTURE)
+ left = pixels[16 * width + 6]
+ right = pixels[16 * width + 26]
+ self.assertGreater(left[0], 150, f"left half should read red, got {left}")
+ self.assertLess(left[2], 100, f"left half should read red, got {left}")
+ self.assertGreater(right[2], 150, f"right half should read blue, got {right}")
+ self.assertLess(right[0], 100, f"right half should read blue, got {right}")
+
+ def test_chroma_upsampling_places_the_colour_boundary_correctly(self):
+ # The fixture is red|blue split exactly down the middle. Chroma is stored at
+ # half resolution, so an incorrect upsampling scale still yields "red on the
+ # left, blue on the right" while silently moving the boundary — sampling a
+ # point well inside each half cannot detect that. Assert the position.
+ width, _height, pixels = decode_jpeg(FIXTURE)
+ row = [pixels[16 * width + x] for x in range(width)]
+ red_majority = sum(1 for p in row if p[0] > p[2])
+ self.assertEqual(
+ red_majority, width // 2,
+ f"colour boundary is misplaced; {red_majority} red px of {width}",
+ )
+
+ def test_rejects_non_jpeg(self):
+ with self.assertRaises(ValueError):
+ decode_jpeg(b"\x89PNG\r\n\x1a\nnot a jpeg")
+
+ def test_progressive_raises_unsupported_not_garbage(self):
+ # Flip the SOF0 marker to SOF2 so the decoder must refuse explicitly rather
+ # than mis-decode; callers rely on UnsupportedJpeg to fall back cleanly.
+ index = FIXTURE.find(b"\xff\xc0")
+ self.assertGreater(index, 0, "fixture should contain a baseline SOF0 marker")
+ progressive = FIXTURE[:index] + b"\xff\xc2" + FIXTURE[index + 2:]
+ with self.assertRaises(UnsupportedJpeg):
+ decode_jpeg(progressive)
+
+
+class JpegPortabilityTest(unittest.TestCase):
+ """The reason this decoder exists: every load_image() shelled out to macOS
+ `sips` for non-PNG input, so a JPEG reference failed hard on Linux/Windows."""
+
+ MODULES = [
+ "extract_pbr_evidence",
+ "extract_landmarks",
+ "build_detail_inventory",
+ "delight_albedo",
+ "make_comparison_sheet",
+ ]
+
+ def test_every_load_image_reads_jpeg_without_sips(self):
+ directory = Path(tempfile.mkdtemp())
+ path = directory / "reference.jpg"
+ path.write_bytes(FIXTURE)
+
+ real_which = shutil.which
+ shutil.which = lambda *a, **k: None # simulate a machine with no sips
+ try:
+ for name in self.MODULES:
+ module = __import__(name)
+ with self.subTest(module=name):
+ result = module.load_image(path)
+ self.assertEqual(result[0], 32)
+ self.assertEqual(result[1], 32)
+ self.assertEqual(len(result[2]), 32 * 32)
+ finally:
+ shutil.which = real_which
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_material_pipeline.py b/forge/tests/test_material_pipeline.py
new file mode 100644
index 0000000..f3e2b02
--- /dev/null
+++ b/forge/tests/test_material_pipeline.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""End-to-end contracts for the nine-phase material pipeline."""
+
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "stage1_intake"))
+sys.path.insert(0, str(ROOT / "stage2_spec"))
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from materials.compatibility import check_compatibility # noqa: E402
+from materials.reference import build_assignment, load_reference, resolve_material # noqa: E402
+from material_region_analysis import analyze_manifest # noqa: E402
+from apply_material_analysis import apply_material_analysis # noqa: E402
+from material_comparator import compare_material_crops # noqa: E402
+from material_feedback import apply_material_feedback # noqa: E402
+from material_gate import run_material_gate # noqa: E402
+from material_views import build_view_plan, crop_visible_footprint, validate_capture # noqa: E402
+
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_png(path: Path, width: int, height: int, fn) -> None:
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ return len(data).to_bytes(4, "big") + kind + data + (zlib.crc32(kind + data) & 0xFFFFFFFF).to_bytes(4, "big")
+ rows = bytearray()
+ for y in range(height):
+ rows.append(0)
+ for x in range(width):
+ rows.extend(bytes(fn(x, y)))
+ header = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes((8, 2, 0, 0, 0))
+ path.write_bytes(PNG_SIGNATURE + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(bytes(rows))) + chunk(b"IEND", b""))
+
+
+class MaterialPipelineTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tmp = Path(tempfile.mkdtemp(prefix="img2threejs-material-pipeline-"))
+ self.registry = load_reference()
+ self.reference = self.tmp / "armor.png"
+ write_png(
+ self.reference,
+ 512,
+ 512,
+ lambda x, y: (246, 246, 246) if x < 64 or x >= 448 or y < 64 or y >= 448 else (
+ 24 + (x * 5 + y * 3) % 190,
+ 42 + (x * 7 + y * 11) % 150,
+ 80 + (x * 13 + y * 17) % 150,
+ ),
+ )
+
+ def test_phase_one_resolver_preserves_authority_and_ambiguity(self) -> None:
+ exact = resolve_material({"materialId": "coating.painted-metal", "confidence": 0.2}, self.registry)
+ self.assertEqual(exact["status"], "proceed")
+ self.assertEqual(exact["method"], "explicit-material-id")
+ assignment = build_assignment({"family": "coating", "subtype": "paint-over-metal", "finish": "gloss-or-satin", "confidence": 0.9}, {}, self.registry)
+ self.assertEqual(assignment["profileId"], "coating.painted-metal")
+ self.assertIn("roughness", assignment["renderPrior"])
+ ambiguous = resolve_material({"family": "metal", "confidence": 0.4}, self.registry)
+ self.assertIn(ambiguous["status"], {"request-input", "probe"})
+
+ def test_phases_two_to_nine_vertical_slice(self) -> None:
+ manifest = self.tmp / "regions.json"
+ manifest.write_text(json.dumps({
+ "referenceId": "armor-fixture",
+ "regions": [{
+ "componentId": "torso-armor",
+ "regionId": "paint",
+ "sourceImage": str(self.reference),
+ "bbox": {"x": 64, "y": 64, "width": 384, "height": 384},
+ "family": "coating",
+ "subtype": "paint-over-metal",
+ "finish": "gloss-or-satin",
+ "materialSpecId": "armor-paint",
+ }],
+ }, indent=2), encoding="utf-8")
+ analysis = analyze_manifest(manifest, self.tmp / "analysis-data")
+ self.assertEqual(analysis["status"], "proceed")
+ region = analysis["regions"][0]
+ self.assertEqual(region["assignment"]["profileId"], "coating.painted-metal")
+ self.assertTrue(Path(region["crop"]["path"]).exists())
+ self.assertTrue(region["referencePbr"]["maps"]["roughness"]["path"])
+
+ spec = {
+ "materials": [{"id": "armor-paint", "baseColor": "#20344A", "textureProjection": {"mode": "uv", "repeat": [1, 1]}}],
+ "componentTree": [{"id": "torso-armor", "material": "armor-paint", "uvContract": {"status": "unwrapped"}}],
+ "lodPlan": [{"id": "lod0", "materialIds": ["armor-paint"]}],
+ "rig": {"bones": [{"id": "torso", "component": "torso-armor"}]},
+ "collisionGroups": {"torso-armor": "box"},
+ }
+ spec = apply_material_analysis(spec, analysis)
+ self.assertEqual(spec["materialPipeline"]["status"], "proceed")
+ self.assertEqual(spec["materials"][0]["referenceMaterialId"], "coating.painted-metal")
+ compatibility = check_compatibility(spec)
+ self.assertTrue(compatibility["passed"], compatibility)
+
+ crop = Path(region["crop"]["path"])
+ render = self.tmp / "render.png"
+ render.write_bytes(crop.read_bytes())
+ comparison = compare_material_crops(crop, render, material_id="armor-paint", expected=region["assignment"])
+ self.assertTrue(comparison["passed"], comparison)
+ plan = build_view_plan("torso-armor", "paint", validation_views=["neutral-studio", "grazing", "environment-reflection"])
+ self.assertGreaterEqual(len(plan["views"]), 12)
+ crop_meta = crop_visible_footprint(crop, {"x": 0, "y": 0, "width": 384, "height": 384}, self.tmp / "microscope.png")
+ self.assertTrue(validate_capture(Path(crop_meta["path"]))["passed"])
+
+ feedback = apply_material_feedback(spec, "armor-paint", comparison)
+ self.assertEqual(feedback["decision"]["action"], "continue")
+ gate = run_material_gate(spec, analysis=analysis, comparisons=[comparison], view_plan=plan)
+ self.assertTrue(gate["passed"], gate)
+
+ def test_low_confidence_analysis_cannot_enter_without_override(self) -> None:
+ analysis = {
+ "status": "probe",
+ "registry": str(ROOT / ".." / "docs/materials/material-reference.json"),
+ "regions": [{"regionId": "paint", "status": "probe"}],
+ }
+ spec = {"materials": [], "componentTree": []}
+ with self.assertRaises(ValueError):
+ apply_material_analysis(spec, analysis)
+
+ def test_unobserved_material_keeps_pipeline_probe_even_when_visible_regions_pass(self) -> None:
+ manifest = self.tmp / "regions-with-unobserved.json"
+ manifest.write_text(json.dumps({
+ "referenceId": "armor-fixture-with-hidden-material",
+ "notObservedMaterials": [{"materialId": "hair.human", "status": "request-input"}],
+ "regions": [{
+ "componentId": "torso-armor",
+ "regionId": "paint",
+ "sourceImage": str(self.reference),
+ "bbox": {"x": 64, "y": 64, "width": 384, "height": 384},
+ "materialId": "coating.painted-metal",
+ "materialSpecId": "armor-paint",
+ "family": "coating",
+ "subtype": "paint-over-metal",
+ "finish": "gloss-or-satin",
+ }],
+ }, indent=2), encoding="utf-8")
+ analysis = analyze_manifest(manifest, self.tmp / "analysis-with-unobserved")
+ self.assertEqual(analysis["status"], "probe")
+ self.assertEqual(len(analysis["unresolvedNotObservedMaterials"]), 1)
+ spec = {"materials": [{"id": "armor-paint", "baseColor": "#20344A"}], "componentTree": []}
+ spec = apply_material_analysis(spec, analysis, allow_probe=True)
+ self.assertEqual(spec["materialPipeline"]["status"], "probe")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_material_reference.py b/forge/tests/test_material_reference.py
new file mode 100644
index 0000000..d332722
--- /dev/null
+++ b/forge/tests/test_material_reference.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""Contract tests for the machine-readable Three.js material reference library."""
+
+from __future__ import annotations
+
+import json
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+REFERENCE = ROOT / "docs" / "materials" / "material-reference.json"
+
+
+class MaterialReferenceContract(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.payload = json.loads(REFERENCE.read_text(encoding="utf-8"))
+ cls.materials = cls.payload["materials"]
+ cls.by_id = {item["id"]: item for item in cls.materials}
+ cls.source_records = cls.payload["sources"]
+ cls.sources = {item["id"] for item in cls.source_records}
+
+ def test_library_is_versioned_and_targets_threejs(self) -> None:
+ self.assertEqual(self.payload["schemaVersion"], 1)
+ self.assertEqual(self.payload["renderer"]["engine"], "three.js")
+ self.assertEqual(self.payload["renderer"]["workflow"], "metallic-roughness")
+
+ def test_material_ids_are_unique(self) -> None:
+ self.assertEqual(len(self.by_id), len(self.materials))
+
+ def test_core_material_families_are_covered(self) -> None:
+ families = {item["family"] for item in self.materials}
+ required = {
+ "skin", "hair", "fur", "fabric", "leather", "metal", "coating",
+ "plastic", "rubber", "wood", "stone", "ceramic", "glass", "gemstone",
+ }
+ self.assertFalse(required - families, f"missing material families: {sorted(required - families)}")
+
+ def test_every_recipe_is_explicitly_a_prior_with_image_cues(self) -> None:
+ for item in self.materials:
+ with self.subTest(material=item["id"]):
+ self.assertEqual(item["recipeBasis"], "inferred-starting-prior")
+ self.assertTrue(item["aliases"])
+ self.assertTrue(item["visualCues"])
+ self.assertTrue(item["confusableWith"])
+ self.assertTrue(item["validationViews"])
+ self.assertTrue(item["sourceRefs"])
+
+ def test_priors_stay_inside_documented_threejs_ranges(self) -> None:
+ legal = self.payload["legalRanges"]
+ for item in self.materials:
+ for property_name, prior in item["renderPrior"].items():
+ with self.subTest(material=item["id"], property=property_name):
+ self.assertIn(property_name, legal)
+ minimum, maximum = prior["range"]
+ default = prior["default"]
+ legal_min, legal_max = legal[property_name]
+ self.assertLessEqual(minimum, default)
+ self.assertLessEqual(default, maximum)
+ self.assertGreaterEqual(minimum, legal_min)
+ self.assertLessEqual(maximum, legal_max)
+
+ def test_source_references_resolve(self) -> None:
+ for item in self.materials:
+ with self.subTest(material=item["id"]):
+ missing = set(item["sourceRefs"]) - self.sources
+ self.assertFalse(missing, f"unresolved source refs: {sorted(missing)}")
+
+ def test_source_registry_is_traceable_and_unique(self) -> None:
+ self.assertEqual(len(self.sources), len(self.source_records))
+ for source in self.source_records:
+ with self.subTest(source=source["id"]):
+ self.assertTrue(source["url"].startswith("https://"))
+ self.assertTrue(source["notebookSourceId"])
+ self.assertTrue(source["authority"])
+
+ def test_deep_research_provenance_is_recorded(self) -> None:
+ research = self.payload["research"]
+ runs = research["deepResearchRuns"]
+ self.assertEqual({run["taskId"] for run in runs}, set(research["researchTaskIds"]))
+ for run in runs:
+ with self.subTest(task=run["taskId"]):
+ self.assertGreaterEqual(run["sourcesFound"], run["citedSourcesImported"])
+ self.assertGreater(run["citedSourcesImported"], 0)
+ self.assertEqual(research["sourceHierarchy"][0], "Three.js official documentation and source contracts")
+
+ def test_specialist_materials_carry_specialist_sources(self) -> None:
+ expectations = {
+ "skin.human": {"nvidia.faceworks", "activision.separable-sss"},
+ "hair.human": {"pbrt.hair"},
+ "fabric.woven-matte": {"khronos.sheen"},
+ "glass.clear": {"khronos.transmission", "khronos.volume"},
+ }
+ for material_id, required_sources in expectations.items():
+ with self.subTest(material=material_id):
+ self.assertTrue(required_sources.issubset(self.by_id[material_id]["sourceRefs"]))
+
+ def test_texture_contract_separates_colour_and_data_maps(self) -> None:
+ contract = self.payload["textureContract"]
+ colour = set(contract["colorMaps"])
+ data = set(contract["dataMaps"])
+ self.assertFalse(colour & data)
+ self.assertEqual(contract["colorMapColorSpace"], "SRGBColorSpace")
+ self.assertEqual(contract["dataMapColorSpace"], "NoColorSpace")
+ self.assertIn("roughnessMap", data)
+ self.assertIn("metalnessMap", data)
+ self.assertIn("map", colour)
+
+ def test_critical_model_invariants(self) -> None:
+ for material_id in ("metal.steel-polished", "metal.steel-brushed", "metal.copper", "metal.gold"):
+ self.assertEqual(self.by_id[material_id]["renderPrior"]["metalness"]["default"], 1.0)
+ for material_id in ("skin.human", "fabric.woven-matte", "plastic.glossy", "glass.clear"):
+ self.assertEqual(self.by_id[material_id]["renderPrior"]["metalness"]["default"], 0.0)
+ self.assertEqual(self.by_id["coating.painted-metal"]["renderPrior"]["metalness"]["default"], 0.0)
+ self.assertEqual(self.by_id["glass.clear"]["renderPrior"]["transmission"]["default"], 1.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_optional_vision_tooling.py b/forge/tests/test_optional_vision_tooling.py
new file mode 100644
index 0000000..151e5c2
--- /dev/null
+++ b/forge/tests/test_optional_vision_tooling.py
@@ -0,0 +1,50 @@
+from __future__ import annotations
+
+import importlib.util
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+MODULE_PATH = ROOT / "stage1_intake" / "run_vision_adapter.py"
+SPEC = importlib.util.spec_from_file_location("run_vision_adapter", MODULE_PATH)
+assert SPEC and SPEC.loader
+MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MODULE)
+
+
+class OptionalVisionToolingTests(unittest.TestCase):
+ def test_bridge_keeps_optional_runtime_outside_forge(self) -> None:
+ expected = ROOT.parent / "integrations" / "vision" / ".venv" / "bin" / "python"
+ self.assertEqual(MODULE.resolve_python(None), expected)
+ command = MODULE.build_command(expected, ["health"])
+ self.assertEqual(command[0], str(expected))
+ self.assertEqual(command[1], str(ROOT.parent / "integrations" / "vision" / "reference_vision.py"))
+ self.assertEqual(command[-1], "health")
+
+ def test_explicit_interpreter_override_is_resolved(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ candidate = Path(directory) / "python"
+ self.assertEqual(MODULE.resolve_python(str(candidate)), candidate.resolve())
+
+ def test_documentation_preserves_evidence_boundaries(self) -> None:
+ documentation = (ROOT.parent / "docs" / "integrations" / "reference_fidelity_tooling.md").read_text(
+ encoding="utf-8"
+ )
+ for phrase in (
+ "diagnostic only",
+ "relative prior only",
+ "Never accept an MCP-only scene edit",
+ "MCP diagnosis when needed",
+ ):
+ self.assertIn(phrase, documentation)
+
+ def test_optional_environment_declares_all_three_vision_routes(self) -> None:
+ project = (ROOT.parent / "integrations" / "vision" / "pyproject.toml").read_text(encoding="utf-8")
+ for dependency in ("mediapipe", "torch", "transformers"):
+ self.assertIn(f'"{dependency}', project)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_part_collision_morphs_lod.py b/forge/tests/test_part_collision_morphs_lod.py
new file mode 100644
index 0000000..8cc8cbd
--- /dev/null
+++ b/forge/tests/test_part_collision_morphs_lod.py
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+"""Tests for inter-part penetration, morph targets, and decimation.
+
+Each group pins the case that would otherwise ship silently:
+
+* penetration -- two individually flawless meshes occupying the same space, which every per-mesh gate
+ passes by construction;
+* morphs -- a target whose vertex order does not match the base, which zip-truncation would turn into
+ a plausible-looking nonsense deformation;
+* decimation -- a collapse that folds the surface, which still hits the triangle count and is exactly
+ the defect `self_intersection.py` exists to catch.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import math
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage3_build"))
+sys.path.insert(0, str(ROOT / "stage4_review"))
+sys.path.insert(0, str(ROOT / "tests"))
+
+from pairwise_penetration import analyze_meshes, analyze_pair, point_inside # noqa: E402
+from morph_targets import build_morph_set, corrective_from_bend, make_morph_target # noqa: E402
+from decimate import build_lod_plan, decimate # noqa: E402
+from geometry_integrity import mesh_edge_counts # noqa: E402
+from test_self_intersection import icosphere # noqa: E402
+
+
+def box(x0, x1, y0, y1, z0, z1, name="box"):
+ vertices = [
+ [x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0],
+ [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1],
+ ]
+ quads = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (2, 3, 7, 6), (1, 2, 6, 5), (0, 4, 7, 3)]
+ indices = []
+ for a, b, c, d in quads:
+ indices.extend([a, b, c, a, c, d])
+ return {"name": name, "vertices": vertices, "indices": indices}
+
+
+class InterPartPenetration(unittest.TestCase):
+ def test_a_bar_driven_through_a_block_is_caught(self) -> None:
+ block = box(0, 2, 0, 2, 0, 2, "torso")
+ bar = box(0.8, 1.2, -1, 3, 0.8, 1.2, "staff")
+ result = analyze_meshes([block, bar])
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("staff" in failure and "torso" in failure for failure in result["failures"]))
+
+ def test_each_mesh_alone_is_flawless_so_only_a_pair_test_can_see_this(self) -> None:
+ # The argument for the module: both meshes are closed and clean on their own.
+ for mesh in (box(0, 2, 0, 2, 0, 2), box(0.8, 1.2, -1, 3, 0.8, 1.2)):
+ counts = mesh_edge_counts(mesh["vertices"], mesh["indices"])
+ self.assertEqual(counts["boundaryEdges"], 0)
+ self.assertEqual(counts["nonManifoldEdges"], 0)
+
+ def test_separated_parts_pass_and_say_the_test_actually_ran(self) -> None:
+ result = analyze_meshes([box(0, 1, 0, 1, 0, 1, "a"), box(5, 6, 5, 6, 5, 6, "b")])
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["pairs"], [])
+
+ def test_allowed_pairs_exempt_parts_meant_to_touch(self) -> None:
+ # A hand gripping a staff shares space on purpose; without this the gate is useless on exactly
+ # the models it is for.
+ hand = box(0, 2, 0, 2, 0, 2, "hand")
+ staff = box(0.8, 1.2, -1, 3, 0.8, 1.2, "staff")
+ self.assertFalse(analyze_meshes([hand, staff])["passed"])
+ self.assertTrue(analyze_meshes([hand, staff], allowed_pairs=[["hand", "staff"]])["passed"])
+
+ def test_both_directions_are_checked(self) -> None:
+ # A small part fully inside a large one has no vertex of the large part inside it, so testing
+ # only one direction would miss it entirely.
+ big = box(0, 10, 0, 10, 0, 10, "big")
+ small = box(4, 5, 4, 5, 4, 5, "small")
+ result = analyze_meshes([big, small])
+ self.assertFalse(result["passed"])
+ self.assertTrue(any(pair["a"] == "small" and pair["penetrating"] for pair in result["pairs"]))
+
+ def test_point_inside_agrees_with_geometry(self) -> None:
+ cube = box(0, 1, 0, 1, 0, 1)
+ faces = [tuple(cube["indices"][i:i + 3]) for i in range(0, len(cube["indices"]), 3)]
+ self.assertEqual(point_inside((0.5, 0.5, 0.5), cube["vertices"], faces), "inside")
+ self.assertEqual(point_inside((5.0, 5.0, 5.0), cube["vertices"], faces), "outside")
+
+ def test_sampling_is_reported(self) -> None:
+ a = box(0, 2, 0, 2, 0, 2, "a")
+ b = box(1, 3, 1, 3, 1, 3, "b")
+ result = analyze_pair(a, b, max_samples=4)
+ self.assertIn("sampledVertexCount", result)
+ self.assertIn("totalVertexCount", result)
+ self.assertGreaterEqual(result["samplingStride"], 1)
+
+
+class MorphTargets(unittest.TestCase):
+ def test_mismatched_vertex_count_is_refused_not_truncated(self) -> None:
+ base = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]
+ shorter = [[0, 0, 0], [1, 0, 0]]
+ with self.assertRaises(ValueError) as caught:
+ make_morph_target(base, shorter, "smile")
+ self.assertIn("vertex order", str(caught.exception))
+
+ def test_deltas_are_relative_and_mostly_zero(self) -> None:
+ base = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]
+ target = [[0, 0, 0], [1, 0.5, 0], [0, 1, 0]]
+ result = make_morph_target(base, target, "raise")
+ self.assertEqual(result["deltas"][0], [0.0, 0.0, 0.0])
+ self.assertEqual(result["deltas"][1], [0.0, 0.5, 0.0])
+ self.assertEqual(result["movedVertexCount"], 1)
+
+ def test_a_target_that_moves_nothing_is_flagged(self) -> None:
+ base = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]
+ result = build_morph_set({"vertices": base}, [{"name": "dead", "vertices": base}])
+ self.assertEqual(result["noOpTargets"], ["dead"])
+
+ def test_relative_flag_is_declared_because_absolute_would_collapse_the_mesh(self) -> None:
+ base = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]
+ result = build_morph_set({"vertices": base}, [])
+ self.assertTrue(result["morphTargetsRelative"])
+ self.assertTrue(any("morphTargetsRelative" in note for note in [result["note"]]))
+
+ def test_corrective_pushes_the_surface_outward_near_the_joint_only(self) -> None:
+ # The joint sits ON the surface, not at the sphere's centre: from the centre every vertex of a
+ # unit sphere is exactly 1.0 away, so any radius below 1 touches nothing and any radius above
+ # touches everything, and the test would measure nothing either way.
+ vertices, _ = icosphere(2)
+ joint = [1.0, 0.0, 0.0]
+ moved = corrective_from_bend(vertices, joint, [0, 1, 0], radius=0.6, volume_gain=0.1)
+
+ def distance_to_joint(v):
+ return math.dist(v, joint)
+
+ near = [i for i, v in enumerate(vertices) if distance_to_joint(v) < 0.5]
+ far = [i for i, v in enumerate(vertices) if distance_to_joint(v) > 1.2]
+ self.assertTrue(near and far)
+ self.assertTrue(any(moved[i] != list(vertices[i]) for i in near))
+ for i in far:
+ self.assertEqual(moved[i], list(vertices[i]))
+
+
+class Decimation(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(3)
+
+ def test_triangle_count_actually_drops(self) -> None:
+ result = decimate({"vertices": self.vertices, "indices": self.indices}, 0.5)
+ self.assertLess(result["triangleCount"], result["originalTriangleCount"])
+ self.assertLessEqual(result["achievedRatio"], 0.75)
+
+ def test_decimated_mesh_is_still_a_closed_surface(self) -> None:
+ # The whole risk: hitting the triangle count while leaving a mesh that is no longer a surface.
+ result = decimate({"vertices": self.vertices, "indices": self.indices}, 0.5)
+ counts = mesh_edge_counts(result["vertices"], result["indices"])
+ self.assertEqual(counts["boundaryEdges"], 0)
+ self.assertEqual(counts["nonManifoldEdges"], 0)
+
+ def test_flip_refusals_are_counted_not_hidden(self) -> None:
+ result = decimate({"vertices": self.vertices, "indices": self.indices}, 0.2)
+ self.assertIn("collapsesRefusedForFlip", result)
+ self.assertIn("reachedTarget", result)
+
+ def test_indices_stay_in_range_after_remapping(self) -> None:
+ result = decimate({"vertices": self.vertices, "indices": self.indices}, 0.4)
+ self.assertTrue(result["indices"])
+ self.assertLess(max(result["indices"]), len(result["vertices"]))
+
+ def test_ratio_of_one_is_a_no_op(self) -> None:
+ result = decimate({"vertices": self.vertices, "indices": self.indices}, 1.0)
+ self.assertEqual(result["triangleCount"], result["originalTriangleCount"])
+
+ def test_invalid_ratio_raises(self) -> None:
+ with self.assertRaises(ValueError):
+ decimate({"vertices": self.vertices, "indices": self.indices}, 0.0)
+
+ def test_generated_lod_plan_satisfies_the_validator_it_was_only_declared_for(self) -> None:
+ plan = build_lod_plan(
+ {"vertices": self.vertices, "indices": self.indices},
+ ratios=[0.6, 0.3],
+ distances=[10.0, 40.0],
+ )
+ tiers = plan["lodPlan"]
+ self.assertEqual(len(tiers), 2)
+ self.assertLess(tiers[0]["distance"], tiers[1]["distance"])
+ self.assertGreater(tiers[0]["triangleCount"], tiers[1]["triangleCount"])
+
+ def test_non_monotonic_request_is_refused(self) -> None:
+ with self.assertRaises(ValueError):
+ build_lod_plan(
+ {"vertices": self.vertices, "indices": self.indices},
+ ratios=[0.3, 0.9],
+ distances=[10.0, 40.0],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_pipeline.py b/forge/tests/test_pipeline.py
index 9c6fa58..7bfcfa0 100644
--- a/forge/tests/test_pipeline.py
+++ b/forge/tests/test_pipeline.py
@@ -22,8 +22,13 @@ SCRIPTS = SKILL / "forge"
def run(script, *args):
+ command = [sys.executable, str(SCRIPTS / script), *map(str, args)]
+ # These tests exercise legacy codegen details using intentionally shallow fixtures.
+ # Production CLI calls must not use this explicit non-production escape hatch.
+ if script == "stage3_build/generate_threejs_factory.py" and "--pass-id" not in args:
+ command.append("--allow-nonstrict")
return subprocess.run(
- [sys.executable, str(SCRIPTS / script), *map(str, args)],
+ command,
capture_output=True, text=True,
)
@@ -239,8 +244,8 @@ class PipelineTest(unittest.TestCase):
# Recording a PASSING tier1 result (identical ref/render) unblocks it.
run("stage4_review/diagnose_render.py", "--reference", self.ref, "--render", self.ref,
- "--pass-id", "blockout", "--spec", self.spec,
- "--map-stripped-render", self.ref, "--in-place")
+ "--pass-id", "blockout", "--spec", self.spec, "--map-stripped-render", self.render,
+ "--in-place")
unblocked = run("stage3_build/orchestrate_passes.py", "check", self.spec, "--pass-id", "blockout")
self.assertEqual(unblocked.returncode, 0, unblocked.stderr)
@@ -267,6 +272,43 @@ class PipelineTest(unittest.TestCase):
"--pass-id", "lighting-pass")
self.assertNotEqual(locked.returncode, 0)
+ def test_generate_factory_blocks_strict_quality_before_writing_output(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "blocked-production-factory.ts"
+ report = self.dir / "blocked-report.json"
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SCRIPTS / "stage3_build/generate_threejs_factory.py"),
+ str(self.spec),
+ "--out",
+ str(out),
+ "--pass-id",
+ "blockout",
+ "--blocked-report",
+ str(report),
+ ],
+ capture_output=True,
+ text=True,
+ )
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("BLOCKED", result.stderr)
+ self.assertIn("strict-quality", result.stderr)
+ self.assertFalse(out.exists())
+ payload = json.loads(report.read_text())
+ self.assertEqual(payload["status"], "BLOCKED")
+ self.assertEqual(payload["gate"], "strict-quality")
+
+ def test_generate_factory_default_path_is_byte_stable(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ first = self.dir / "default-a.ts"
+ second = self.dir / "default-b.ts"
+ first_result = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", first)
+ second_result = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", second)
+ self.assertEqual(first_result.returncode, 0, first_result.stderr)
+ self.assertEqual(second_result.returncode, 0, second_result.stderr)
+ self.assertEqual(first.read_bytes(), second.read_bytes())
+
def test_generate_factory_emits_f3_f4_material_and_environment(self):
# Plan 1.3 F.3/F.4: previously-missing MeshPhysicalMaterial properties and the
# environment map must both appear in the generated code (codegen-output test,
@@ -284,6 +326,32 @@ class PipelineTest(unittest.TestCase):
self.assertIn("PMREMGenerator", ts)
self.assertIn("Environment(renderer: THREE.WebGLRenderer)", ts)
+ def test_generate_factory_emits_ws5_pbr_constraints_and_dense_maps(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "createObjectModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ for marker in ("clampAlbedoChannel", "clampPbrF0", "clampPbrIor", "clampPbrMetalness",
+ "binaryMetalness", "material.displacementMap = textures.height",
+ "material.normalMap = textures.normal"):
+ self.assertIn(marker, ts, f"missing WS5 generator rule: {marker}")
+ self.assertIn("clampAlbedoChannel(Number(match[1]))", ts)
+ self.assertIn("iridescenceIOR: clampPbrIor", ts)
+
+ def test_dense_component_enables_height_maps_when_shared_material_is_plain(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ component = spec["componentTree"][0]
+ component["geometryDensity"] = "dense"
+ spec["materials"][0].pop("geometryDensity", None)
+ spec["materials"][0].pop("denseMesh", None)
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ result = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("}, options, true)", out.read_text())
+
def test_generate_factory_emits_auto_framing(self):
# Plan 1.3 §3.2: auto-framing by bounding box is a prerequisite for the Divine
# Eye — an object framed unlike the reference makes every silhouette comparison
@@ -574,9 +642,10 @@ class PipelineTest(unittest.TestCase):
"--fidelity", "0.8", "--action", "continue",
"--summary", "Blockout silhouette acceptable.",
"--render-screenshot", self.render, "--comparison-image", cmp,
+ "--map-stripped-render", self.render,
"--ai-vision-score", "0.8", "--layer-scores-json", layers,
"--feature-reviews-json", freviews,
- "--camera-view", "front", "--map-stripped-render", self.render, "--in-place")
+ "--camera-view", "front", "--in-place")
self.assertEqual(r.returncode, 0, r.stderr)
spec = json.loads(self.spec.read_text())
self.assertTrue(len(spec.get("reviewHistory", [])) >= 1)
@@ -697,15 +766,47 @@ class PipelineTest(unittest.TestCase):
# ---- v1.2 character generator ----
def test_character_flag_builds_humanoid_tree(self):
+ # Plan 1.5: the default character template is a general humanoid, not a hardcoded bust
+ # of one reference person -- it must include a lower body and full arms, and must NOT
+ # include that person's specific traits (glasses/headphones/chest decal) unless the
+ # caller opts in with --accessories. See new_sculpt_spec.py make_character_component_tree.
run("stage2_spec/new_sculpt_spec.py", "Person", "--character", "--out", self.spec)
spec = json.loads(self.spec.read_text())
ids = {c["id"] for c in spec["componentTree"]}
- for part in ("root", "head", "torso", "neck", "hair", "glasses-frame-l", "arm-l"):
+ for part in (
+ "root", "head", "abdomen", "chest", "neck", "hair", # spine is two segments (US-001)
+ "pelvis", "thigh-l", "shin-l", "foot-l", # lower body
+ "upper-arm-l", "forearm-l", "hand-l", # full arm, not a single "arm-l" capsule
+ "eye-l", "eye-cavity-l", # eyes as recessed cavities, not brows alone
+ ):
self.assertIn(part, ids)
- # all parts flattened to root (no cascading non-uniform parent scale)
- for c in spec["componentTree"]:
- if c["id"] != "root":
- self.assertEqual(c["parent"], "root")
+ for accessory in ("glasses-frame-l", "hp-band", "shirt-decal"):
+ self.assertNotIn(accessory, ids)
+ # Plan 1.5 WS-E: now that a non-uniformly-scaled parent can no longer distort a
+ # nested child (generate_threejs_factory.py bakes dimensions into geometry, not the
+ # pivot Group's scale), the template authors a REAL parent chain instead of flattening
+ # every part onto "root". Anatomically sensible parents, not a flat list.
+ by_id = {c["id"]: c for c in spec["componentTree"]}
+ expected_parents = {
+ # US-001 split the single torso into abdomen + chest so the waist can flex, and
+ # parented the spine to the pelvis. The pelvis is now the only root-parented body
+ # part, which is also what made derive_character_rig's hand-picked bone root and its
+ # torso joint exception unnecessary.
+ "pelvis": "root", "abdomen": "pelvis", "chest": "abdomen",
+ "neck": "chest", "head": "neck",
+ # US-002 inserted a clavicle between chest and upper arm so the shoulder can shrug
+ # and the arm's rotation origin sits on the joint instead of inside the ribcage.
+ "clavicle-l": "chest", "upper-arm-l": "clavicle-l",
+ "forearm-l": "upper-arm-l", "hand-l": "forearm-l",
+ "thigh-l": "pelvis", "shin-l": "thigh-l", "foot-l": "shin-l",
+ "hair": "head", "eye-l": "head", "eye-cavity-l": "head",
+ }
+ for child_id, expected_parent in expected_parents.items():
+ self.assertEqual(by_id[child_id]["parent"], expected_parent,
+ f"{child_id} should be parented on {expected_parent!r}")
+ # not every part is nested this deep -- confirm the tree isn't secretly still flat
+ non_root_parents = {c["parent"] for c in spec["componentTree"] if c["id"] != "root"}
+ self.assertTrue(non_root_parents - {"root"}, "componentTree is still flattened onto root")
# distinct per-part colors (skin vs hair vs shirt), not a single fallback
colors = {m["id"]: m.get("color") for m in spec["materials"] if m["id"] in ("skin", "hair", "shirt")}
self.assertEqual(len({colors["skin"], colors["hair"], colors["shirt"]}), 3)
@@ -714,6 +815,36 @@ class PipelineTest(unittest.TestCase):
if m["id"] in ("skin", "hair", "shirt"):
self.assertGreaterEqual(len(m.get("colorVariation", {}).get("palette", [])), 2)
+ def test_character_accessories_flag_restores_bust_traits(self):
+ run("stage2_spec/new_sculpt_spec.py", "Person", "--character", "--accessories",
+ "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ ids = {c["id"] for c in spec["componentTree"]}
+ for accessory in ("glasses-frame-l", "hp-band", "shirt-decal"):
+ self.assertIn(accessory, ids)
+
+ def test_digits_are_baseline_not_a_flag(self):
+ """US-003 replaced the `--fingers` flag with real digits in the default template.
+
+ The flag added ONE box called "fingers-l" plus one called "thumb-l" — a mitten, opt-in.
+ A humanoid that cannot curl a finger is not finished, so five digits of three phalanges
+ each are now baseline and the flag is gone. This asserts both halves: the digits exist
+ without any flag, and the old mitten ids do not come back.
+ """
+ run("stage2_spec/new_sculpt_spec.py", "Person", "--character", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ ids = {c["id"] for c in spec["componentTree"]}
+ for side in ("l", "r"):
+ for digit in ("thumb", "index", "middle", "ring", "little"):
+ for phalanx in (1, 2, 3):
+ self.assertIn(f"{digit}-{side}-{phalanx}", ids)
+ self.assertNotIn("fingers-l", ids)
+ self.assertNotIn("thumb-l", ids)
+ by_id = {c["id"]: c for c in spec["componentTree"]}
+ self.assertEqual(by_id["middle-l-1"]["parent"], "hand-l")
+ self.assertEqual(by_id["middle-l-2"]["parent"], "middle-l-1")
+ self.assertEqual(by_id["middle-l-3"]["parent"], "middle-l-2")
+
def test_character_autodetect_from_domain(self):
run("stage2_spec/new_pre_spec_assessment.py", "Person", "--complexity", "complex", "--out", self.assessment)
a = json.loads(self.assessment.read_text())
diff --git a/forge/tests/test_pipeline_routing.py b/forge/tests/test_pipeline_routing.py
new file mode 100644
index 0000000..dd97b22
--- /dev/null
+++ b/forge/tests/test_pipeline_routing.py
@@ -0,0 +1,166 @@
+from __future__ import annotations
+
+import unittest
+import json
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+from forge._shared.pipeline_routing import resolve_pipeline_routing, validate_pipeline_routing
+from forge.stage2_spec.new_pre_spec_assessment import make_payload
+from forge.stage2_spec.new_sculpt_spec import make_spec
+from forge.stage2_spec.validate_sculpt_spec import validate_spec
+from forge.stage2_spec.validate_sculpt_spec import validate_pipeline_routing_contract
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[2]
+
+
+def classification(kind: str, confidence: float = 0.9) -> dict:
+ return {
+ "kind": kind,
+ "confidence": confidence,
+ "evidenceRefs": ["fixture:front"],
+ "provider": "fixture-classifier",
+ "version": "1",
+ }
+
+
+class PipelineRoutingTests(unittest.TestCase):
+ def test_classification_routes_reliable_weapon_and_character(self) -> None:
+ weapon = resolve_pipeline_routing(classification=classification("weapon"))
+ character = resolve_pipeline_routing(classification=classification("character"))
+
+ self.assertEqual(weapon["track"], "weapon-v1.4")
+ self.assertEqual(character["track"], "character-v1.5")
+ self.assertEqual(weapon["source"], "classification")
+ self.assertEqual(weapon["status"], "resolved")
+
+ def test_ambiguous_or_low_confidence_classification_fails_closed(self) -> None:
+ for kind, confidence in (("hybrid", 0.99), ("unknown", 0.99), ("weapon", 0.81)):
+ with self.subTest(kind=kind, confidence=confidence):
+ routing = resolve_pipeline_routing(classification=classification(kind, confidence))
+ self.assertEqual(routing["status"], "request-input")
+ self.assertTrue(routing["conflicts"])
+
+ def test_malformed_classification_fails_closed(self) -> None:
+ routing = resolve_pipeline_routing(classification={"kind": "weapon"})
+
+ self.assertEqual(routing["status"], "request-input")
+ self.assertEqual(routing["classification"]["kind"], "unknown")
+
+ def test_explicit_track_rejects_reliable_contradiction(self) -> None:
+ routing = resolve_pipeline_routing(
+ explicit_track="weapon-v1.4",
+ classification=classification("character"),
+ )
+
+ self.assertEqual(routing["status"], "request-input")
+ self.assertIn("contradicts", routing["conflicts"][0])
+
+ def test_explicit_track_normalizes_to_routing_metadata(self) -> None:
+ routing = resolve_pipeline_routing(explicit_track="character-v1.5")
+
+ self.assertEqual(routing["track"], "character-v1.5")
+ self.assertEqual(routing["source"], "explicit")
+ self.assertEqual(routing["status"], "resolved")
+ self.assertEqual(routing["classification"]["kind"], "character")
+
+ def test_legacy_cs2_routes_weapon_without_modern_classification(self) -> None:
+ routing = resolve_pipeline_routing(legacy_cs2=True)
+
+ self.assertEqual(routing["track"], "weapon-v1.4")
+ self.assertEqual(routing["source"], "legacy")
+ self.assertEqual(routing["status"], "resolved")
+
+ def test_legacy_cs2_does_not_override_an_explicit_character_track(self) -> None:
+ routing = resolve_pipeline_routing(
+ explicit_track="character-v1.5",
+ legacy_cs2=True,
+ )
+
+ self.assertEqual(routing["status"], "request-input")
+ self.assertIn("contradicts legacy CS2", routing["conflicts"][0])
+
+ def test_validator_accepts_resolved_and_rejects_malformed_contract(self) -> None:
+ self.assertEqual(validate_pipeline_routing(resolve_pipeline_routing(legacy_cs2=True)), [])
+ self.assertTrue(validate_pipeline_routing({"version": 1}))
+
+ def test_assessment_and_spec_preserve_resolved_routing(self) -> None:
+ assessment = make_payload("Hero", None, "moderate", is_character=True)
+ spec = make_spec("Hero", None, assessment)
+
+ self.assertEqual(assessment["pipelineRouting"]["track"], "character-v1.5")
+ self.assertEqual(spec["pipelineRouting"], assessment["pipelineRouting"])
+
+ def test_weapon_and_character_routing_select_their_own_templates(self) -> None:
+ for kind, expected_component in (("weapon", "blade"), ("character", "head")):
+ with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory:
+ assessment_path = Path(directory) / "assessment.json"
+ spec_path = Path(directory) / "spec.json"
+ assessment_path.write_text(json.dumps({
+ "preSpecAssessment": {"objectClass": {"primaryDomain": "object"}},
+ "pipelineRouting": resolve_pipeline_routing(classification=classification(kind)),
+ }))
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SKILL_ROOT / "forge/stage2_spec/new_sculpt_spec.py"),
+ "Target",
+ "--assessment",
+ str(assessment_path),
+ "--out",
+ str(spec_path),
+ ],
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ component_ids = {component["id"] for component in json.loads(spec_path.read_text())["componentTree"]}
+ self.assertIn(expected_component, component_ids)
+
+ def test_conflicting_cs2_and_character_flags_do_not_select_a_template(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(SKILL_ROOT / "forge/stage2_spec/new_sculpt_spec.py"),
+ "Target",
+ "--cs2",
+ "--character",
+ "--out",
+ str(Path(directory) / "spec.json"),
+ ],
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("pipeline routing requires input", result.stderr)
+
+ def test_validator_rejects_unresolved_or_wrong_template_routing(self) -> None:
+ spec = make_spec("Target", None)
+ spec["pipelineRouting"] = resolve_pipeline_routing(classification=classification("hybrid"))
+ unresolved_errors, _ = validate_spec(spec)
+
+ self.assertIn("pipelineRouting must be resolved before validation", unresolved_errors)
+
+ spec["pipelineRouting"] = resolve_pipeline_routing(classification=classification("character"))
+ template_errors, _ = validate_spec(spec)
+
+ self.assertIn("character-v1.5 routing requires the character template", template_errors)
+
+ def test_legacy_cs2_intake_derives_valid_routing_without_persisting_it(self) -> None:
+ errors: list[str] = []
+ spec = {"cs2Intake": {"itemFamily": "knife"}}
+
+ validate_pipeline_routing_contract(spec, errors)
+
+ self.assertEqual(errors, [])
+ self.assertNotIn("pipelineRouting", spec)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_primitive_watertightness.py b/forge/tests/test_primitive_watertightness.py
new file mode 100644
index 0000000..4651300
--- /dev/null
+++ b/forge/tests/test_primitive_watertightness.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+"""Measure boundary/non-manifold edges on every emitted primitive, real-executed.
+
+Nothing in the suite measured this before this file existed. See
+docs/PLAN_1.5_ANIMATION_READY_RIGS.md and the WS-E capsule fix in
+generate_threejs_factory.py.
+
+Two distinct properties are measured per primitive, both real-executed (tsc + node,
+same pattern as test_hierarchy_scale.py) rather than hand-computed:
+
+ - `raw`: boundary/non-manifold edges on the geometry's own index buffer, exactly
+ as emitted -- no welding, no dedup.
+ - `welded`: TRUE topology, identifying vertices by rounded position (the same
+ 1e-6-precision key subdivideCatmullClark's own `vertexIndexAt` uses) and
+ dropping any triangle that becomes degenerate under that identity -- exactly
+ what subdivideCatmullClark does before it ever builds an edge graph. This is
+ deliberately NOT a plain `BufferGeometryUtils.mergeVertices()` call: mergeVertices
+ re-indexes vertices but keeps every triangle reference, including ones that
+ become degenerate after the merge, and a degenerate triangle (a, a, b)
+ double-counts the surviving edge (a, b) -- producing a "non-manifold" reading
+ for topology that is actually a perfectly ordinary closed 2-manifold. This
+ exact mistake is why an earlier version of this file, and the report that
+ preceded it, wrongly concluded the raw capsule was non-manifold (see the
+ capsule finding below) -- corrected once the discrepancy between "mergeVertices
+ says non-manifold" and "the real subdivideCatmullClark completes without
+ throwing" was run down to its root cause instead of accepted at face value.
+
+Findings encoded as assertions here (each verified by running this exact
+tsc+node harness against the TRUE-topology method above, not by inspecting source
+or trusting a single measurement tool):
+
+ - box, cylinder, sphere, ellipsoid, torus, instanced-cluster (defaults to a box
+ base), extrude, curve-sweep, capsule: 0/0 once welded by true position identity.
+ Their raw boundary count is the normal, benign UV-seam duplication every
+ textured three.js primitive has; welding proves the underlying topology is
+ genuinely closed. capsule (built via buildWatertightCapsule, not
+ THREE.CapsuleGeometry) is additionally 0/0 even RAW, with no degenerate
+ triangles at all -- closed by construction, not by a weld.
+ - cone: 0/0 once welded -- but the ORIGINAL construction (heightSegments=16,
+ CYLINDER_HEIGHT_SEGMENTS) measured 2448 raw / 2160 welded boundary edges, with
+ ZERO degenerate triangles filtered -- a GENUINE topology defect, verified with
+ this exact rigorous method, unrelated to the capsule's degenerate-triangle
+ counting artifact. A tapering cone does not weld cleanly at 16 height segments
+ the way a constant-radius cylinder does. Fixed by giving cone its own
+ CONE_HEIGHT_SEGMENTS=1 (three.js's own default). The subdivision-requested
+ substitute geometry (a near-degenerate CylinderGeometry) is untouched.
+ - plane-card, tube, lathe (with the generator's default open profile): boundary
+ edges are EXPECTED and correct -- these are not closed solids by design (a flat
+ card, an open-ended pipe, and a lathed profile that never touches the axis at
+ either end all have a real physical edge).
+ - ground-blade: CONFIRMED, UNFIXED topology defect, found while building this
+ measurement (a fully custom-built BufferGeometry, not a three.js primitive) --
+ measures 6 real boundary edges under true topology (an actual open/unclosed
+ region; a 7th "non-manifold" edge from an earlier, mergeVertices-based
+ measurement was the same degenerate-triangle counting artifact as the capsule's
+ -- one harmless zero-area sliver triangle, correctly excluded here). Off the
+ humanoid character's component path (no ground-blade components), small,
+ reported to team-lead and left as-is by direction; pinned here as an
+ exact-count tripwire so it cannot silently get worse.
+
+Pure Python 3.10+ stdlib on this side. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+ROOT = Path(__file__).resolve().parent.parent
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate, VALID_PRIMITIVES
+ from validate_sculpt_spec import validate_spec
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return generate, validate_spec, VALID_PRIMITIVES
+
+
+generate, validate_spec, VALID_PRIMITIVES = import_forge_modules()
+PRIMITIVES = sorted(VALID_PRIMITIVES)
+
+# Every closed-solid primitive that MUST be watertight (0 boundary, 0 non-manifold)
+# after a position-only weld -- box/cylinder/sphere/ellipsoid/torus/instanced-cluster
+# via their normal, benign UV-seam duplication, capsule via true construction (RAW,
+# no weld needed).
+EXPECTED_WELDED_WATERTIGHT = {"box", "cylinder", "sphere", "ellipsoid", "torus", "instanced-cluster", "extrude", "curve-sweep", "capsule", "cone"}
+# capsule needs no weld at all: built closed by construction.
+EXPECTED_WATERTIGHT_EVEN_RAW = {"capsule"}
+# Inherently open shapes by design (a real edge is CORRECT, not a defect): a flat
+# card, a tube with no end caps (closed: false, the generator's default), and the
+# generator's default lathe profile (points [[0.3,-0.5],[0.15,0],[0.3,0.5]]) which
+# never touches the lathe axis at either end, i.e. an open vessel with no caps.
+EXPECTED_OPEN_BY_DESIGN = {"plane-card", "tube", "lathe"}
+# Confirmed, unfixed defects (see module docstring) -- pinned to their measured
+# values as a regression tripwire, not silently ignored. If a future fix changes
+# these numbers, update this dict together with the fix, do not just relax it.
+KNOWN_DEFECT_WELDED_COUNTS = {
+ # 6 real boundary edges (an actual open/unclosed region in this custom-built
+ # BufferGeometry) plus one harmless degenerate (zero-area) triangle, which the
+ # true-topology method correctly excludes rather than double-counting it into a
+ # false non-manifold reading (see module docstring).
+ "ground-blade": {"boundary": 6, "nonManifold": 0},
+}
+
+assert set(PRIMITIVES) == (
+ EXPECTED_WELDED_WATERTIGHT | EXPECTED_OPEN_BY_DESIGN | set(KNOWN_DEFECT_WELDED_COUNTS)
+), "every VALID_PRIMITIVES entry must be categorized in this test file"
+
+
+def _ground_blade_descriptor() -> dict:
+ # _DEFAULT_BLADE_SPEC used to carry a "spineFlat" key that buildGroundBladeGeometry's
+ # TS parameter type didn't declare, which failed `tsc --strict` on ANY spec using
+ # ground-blade with no explicit bladeSpec override (found while building this
+ # probe, since fixed by dropping the dead key from _DEFAULT_BLADE_SPEC). Kept as
+ # an explicit descriptor here anyway, for a stable probe shape independent of
+ # that module-level default.
+ return {
+ "bladeSpec": {
+ "stations": [[0.0, 0.08, -0.09], [0.5, 0.08, -0.1], [0.88, 0.0, 0.0]],
+ "thickness": 0.05,
+ "grindFrac": 0.55,
+ "swedgeFromTipFrac": 0.34,
+ }
+ }
+
+
+def build_probe_spec() -> dict:
+ components = [
+ {
+ "id": "root", "name": "Root", "level": "macro", "role": "body",
+ "primitive": "box", "parent": None, "material": "clay",
+ "transform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},
+ }
+ ]
+ for index, primitive in enumerate(PRIMITIVES):
+ component = {
+ "id": f"probe-{primitive}", "name": f"Probe {primitive}", "level": "macro", "role": "body",
+ "primitive": primitive, "parent": None, "material": "clay",
+ "transform": {"position": [float(index) * 3.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},
+ }
+ if primitive == "ground-blade":
+ component["geometryDescriptor"] = _ground_blade_descriptor()
+ components.append(component)
+ return {
+ "targetName": "Primitive Watertightness Probe",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [{"id": "clay"}],
+ "componentTree": components,
+ }
+
+
+def compile_generated_module(generated: str, work_dir: Path) -> tuple[subprocess.CompletedProcess[str], Path]:
+ source = work_dir / "primitive-watertightness.ts"
+ build_dir = work_dir / "build"
+ source.write_text(generated, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "npx", "tsc", "--target", "ES2020", "--module", "NodeNext", "--moduleResolution", "NodeNext",
+ "--strict", "--skipLibCheck", "--noUnusedLocals", "--noUnusedParameters",
+ "--outDir", str(build_dir), str(source),
+ ],
+ cwd=showcase_root(),
+ capture_output=True,
+ text=True,
+ )
+ return result, build_dir / "primitive-watertightness.js"
+
+
+_EVAL_SCRIPT = """
+import * as THREE from 'three';
+import { createPrimitiveWatertightnessProbeModel } from './build/primitive-watertightness.js';
+
+const primitives = __PRIMITIVES_JSON__;
+const model = createPrimitiveWatertightnessProbeModel();
+
+// RAW: boundary/non-manifold edges on the geometry's own index buffer, exactly as
+// emitted -- no welding, no dedup. This is where a UV seam's duplicate vertex shows
+// up as a "boundary" edge (benign, expected for a textured primitive).
+function rawEdgeStats(geometry) {
+ let index = geometry.index;
+ const position = geometry.getAttribute('position');
+ if (!index) {
+ const arr = [];
+ for (let i = 0; i < position.count; i++) arr.push(i);
+ index = new THREE.Uint32BufferAttribute(arr, 1);
+ }
+ const counts = new Map();
+ for (let offset = 0; offset + 2 < index.count; offset += 3) {
+ const tri = [index.getX(offset), index.getX(offset + 1), index.getX(offset + 2)];
+ for (let e = 0; e < 3; e++) {
+ const a = tri[e];
+ const b = tri[(e + 1) % 3];
+ if (a === b) continue;
+ const key = a < b ? a + ':' + b : b + ':' + a;
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ }
+ let boundary = 0;
+ let nonManifold = 0;
+ for (const c of counts.values()) {
+ if (c === 1) boundary += 1;
+ else if (c > 2) nonManifold += 1;
+ }
+ return { boundary, nonManifold };
+}
+
+// TRUE TOPOLOGY: identify vertices by ROUNDED POSITION (1e-6 precision -- the same
+// key subdivideCatmullClark's own vertexIndexAt() uses) and DROP any triangle that
+// becomes degenerate (two or more corners collapse to the same vertex) under that
+// identity, exactly like subdivideCatmullClark does, BEFORE counting edges.
+//
+// This is NOT the same as a plain three.js mergeVertices() weld, and the
+// difference matters: mergeVertices happily re-indexes vertices but keeps every
+// original triangle reference, including ones that become degenerate after the
+// merge. A degenerate triangle (a, a, b) contributes edges (a,a) [a self-loop,
+// ignored] and TWO instances of the SAME undirected edge (a,b) -- so if edge (a,b)
+// already has 2 legitimate incident triangles, one degenerate triangle silently
+// inflates its count to 4, reading as "non-manifold" when the true topology is a
+// perfectly ordinary closed 2-manifold. This is exactly what happened investigating
+// the raw capsule: a plain position-only mergeVertices() reported 64 non-manifold
+// edges, stable across weld tolerances from 1e-4 to 1e-10 (ruling out a tolerance
+// problem) -- but replicating subdivideCatmullClark's own degenerate-triangle-aware
+// vertex identity finds ZERO non-manifold edges, with the discarded-degenerate
+// count (64) matching the false non-manifold count exactly. Confirmed independently
+// by feeding a raw (pre-fix) THREE.CapsuleGeometry directly into the real,
+// unmodified subdivideCatmullClark(..., 1): it completes without throwing, which a
+// genuinely non-manifold input would not survive (see
+// test_generated_subdivision_rejects_non_manifold_edges, which DOES throw on a
+// hand-built 3-triangles-one-edge fixture).
+//
+// cone's defect is NOT of this kind -- re-verified with this exact method
+// (degenerateFiltered: 0, boundary: 2160 either way) -- it is a genuine topology
+// defect, unrelated to degenerate-triangle counting.
+function trueTopologyStats(geometry) {
+ const position = geometry.getAttribute('position');
+ const index = geometry.index;
+ const count = index ? index.count : position.count;
+ const byKey = new Map();
+ const remap = new Int32Array(position.count);
+ for (let i = 0; i < position.count; i += 1) {
+ const key = Math.round(position.getX(i) * 1e6) + ',' + Math.round(position.getY(i) * 1e6) + ',' + Math.round(position.getZ(i) * 1e6);
+ let id = byKey.get(key);
+ if (id === undefined) { id = byKey.size; byKey.set(key, id); }
+ remap[i] = id;
+ }
+ const triangles = [];
+ let degenerateFiltered = 0;
+ for (let offset = 0; offset + 2 < count; offset += 3) {
+ const ai = index ? index.getX(offset) : offset;
+ const bi = index ? index.getX(offset + 1) : offset + 1;
+ const ci = index ? index.getX(offset + 2) : offset + 2;
+ const a = remap[ai];
+ const b = remap[bi];
+ const c = remap[ci];
+ if (a !== b && b !== c && c !== a) triangles.push([a, b, c]);
+ else degenerateFiltered += 1;
+ }
+ const edgeCounts = new Map();
+ for (const [a, b, c] of triangles) {
+ for (const [u, v] of [[a, b], [b, c], [c, a]]) {
+ const key = u < v ? u + ':' + v : v + ':' + u;
+ edgeCounts.set(key, (edgeCounts.get(key) ?? 0) + 1);
+ }
+ }
+ let boundary = 0;
+ let nonManifold = 0;
+ for (const c of edgeCounts.values()) {
+ if (c === 1) boundary += 1;
+ else if (c > 2) nonManifold += 1;
+ }
+ return { boundary, nonManifold, degenerateFiltered };
+}
+
+const rows = {};
+for (const prim of primitives) {
+ const mesh = model.userData.sculptRuntime.meshes['probe-' + prim];
+ if (!mesh) { rows[prim] = { error: 'mesh not found' }; continue; }
+ const raw = rawEdgeStats(mesh.geometry);
+ const welded = trueTopologyStats(mesh.geometry);
+ rows[prim] = { raw, welded };
+}
+console.log(JSON.stringify(rows));
+"""
+
+
+class PrimitiveWatertightnessTest(unittest.TestCase):
+ result: dict
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ spec = build_probe_spec()
+ errors, _warnings = validate_spec(spec)
+ if errors:
+ raise RuntimeError(f"FAIL CLOSED: probe spec did not validate: {errors}")
+ generated = generate(spec, "blockout")
+
+ cls._tempdir_ctx = tempfile.TemporaryDirectory(dir=showcase_root())
+ work_dir = Path(cls._tempdir_ctx.name)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ if compile_result.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: tsc did not compile the emitted module: {compile_result.stderr}")
+
+ eval_script = _EVAL_SCRIPT.replace("__PRIMITIVES_JSON__", json.dumps(PRIMITIVES))
+ runtime = subprocess.run(
+ ["node", "--input-type=module", "--eval", eval_script],
+ cwd=work_dir, capture_output=True, text=True,
+ )
+ if runtime.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: node execution of the emitted module failed: {runtime.stderr}")
+ try:
+ cls.result = json.loads(runtime.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"FAIL CLOSED: result was not parseable JSON: {exc}\nstdout: {runtime.stdout!r}") from exc
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls._tempdir_ctx.cleanup()
+
+ def test_every_valid_primitive_was_measured(self) -> None:
+ for primitive in PRIMITIVES:
+ self.assertIn(primitive, self.result, f"{primitive} produced no mesh to measure")
+ self.assertNotIn("error", self.result[primitive], self.result[primitive])
+
+ def test_closed_solids_are_watertight_under_true_topology(self) -> None:
+ for primitive in sorted(EXPECTED_WELDED_WATERTIGHT):
+ with self.subTest(primitive=primitive):
+ welded = self.result[primitive]["welded"]
+ self.assertEqual(welded["boundary"], 0, f"{primitive}: {welded['boundary']} boundary edges under true topology")
+ self.assertEqual(welded["nonManifold"], 0, f"{primitive}: {welded['nonManifold']} non-manifold edges under true topology")
+
+ def test_capsule_is_watertight_even_without_welding(self) -> None:
+ # The whole point of buildWatertightCapsule: closed BY CONSTRUCTION, not by
+ # a tolerance-dependent weld pass applied afterward.
+ for primitive in sorted(EXPECTED_WATERTIGHT_EVEN_RAW):
+ with self.subTest(primitive=primitive):
+ raw = self.result[primitive]["raw"]
+ self.assertEqual(raw["boundary"], 0, f"{primitive}: {raw['boundary']} RAW boundary edges (expected watertight by construction)")
+ self.assertEqual(raw["nonManifold"], 0, f"{primitive}: {raw['nonManifold']} RAW non-manifold edges")
+
+ def test_open_by_design_primitives_have_a_real_boundary(self) -> None:
+ # These are not closed solids -- a card, an open pipe, an open lathed
+ # vessel. A boundary here is correct; asserting it stays NONZERO catches a
+ # future accidental cap/weld pass silently "fixing" something that was
+ # never broken (and would visually change these primitives' shape).
+ for primitive in sorted(EXPECTED_OPEN_BY_DESIGN):
+ with self.subTest(primitive=primitive):
+ self.assertGreater(
+ self.result[primitive]["welded"]["boundary"], 0,
+ f"{primitive}: expected a real open boundary (it is not a closed solid by design)",
+ )
+
+ def test_known_unfixed_defects_are_pinned_not_worse(self) -> None:
+ # ground-blade is a CONFIRMED, UNFIXED topology defect (see module
+ # docstring) -- reported to team-lead, left as-is by direction (off the
+ # humanoid character's component path). Pinned to its exact measured counts
+ # so it cannot silently regress further, and so a real fix is forced to
+ # touch this test rather than leave it stale.
+ for primitive, expected in sorted(KNOWN_DEFECT_WELDED_COUNTS.items()):
+ with self.subTest(primitive=primitive):
+ welded = self.result[primitive]["welded"]
+ self.assertEqual(welded["boundary"], expected["boundary"], f"{primitive}: boundary edge count changed -- update this test together with whatever changed it")
+ self.assertEqual(welded["nonManifold"], expected["nonManifold"], f"{primitive}: non-manifold edge count changed -- update this test together with whatever changed it")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_recessed_and_open_shell_topology.py b/forge/tests/test_recessed_and_open_shell_topology.py
new file mode 100644
index 0000000..6d289a5
--- /dev/null
+++ b/forge/tests/test_recessed_and_open_shell_topology.py
@@ -0,0 +1,493 @@
+#!/usr/bin/env python3
+"""Plan 1.5 schema gates: recessed features cannot be faked flat, and open-shell exists
+for zero-thickness two-sided surfaces.
+
+Covers two defect classes that a downstream review pass cannot catch:
+
+1. US-004 — "the eye reads as a patch, not a recessed socket." A silhouette gate cannot
+ see an interior concavity, and a dark-pixel ratio on a concave feature measures cavity
+ shading, not material. A component authored as a recessed feature (its role/name/id
+ contains a signal like "cavity", "canal", "nostril", the compound "eye-socket", or
+ "hollow"/"concave" specifically in `role`) must be rejected if it is topologyClass
+ "surface-relief" or a flat "plane-card" primitive, and accepted when built as real
+ concavity: topologyClass "implicit" with a geometryDescriptor.sdf "subtract" operation.
+ NOTE: bare "socket" is deliberately NOT a signal -- ATTACHMENT_ROLES already uses it for
+ attachment points (a handle's hilt socket), so this file pins that collision in
+ `test_bare_socket_attachment_point_is_not_treated_as_recessed` below.
+
+2. "open-shell" — a zero-thickness two-sided surface (wing membrane, cape, leaf, fin).
+ An SDF cannot represent zero thickness, so open-shell must not pair with
+ geometryDescriptor.sdf, and it must carry a double-sided material (doubleSided: true)
+ or it renders invisible from behind.
+"""
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+FIXTURE = ROOT / "tests" / "fixtures" / "implicit_character_torso_limb.json"
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from validate_sculpt_spec import (
+ ATTACHMENT_ROLES,
+ RECESSED_FEATURE_TOKENS,
+ VALID_TOPOLOGY_CLASSES,
+ component_is_recessed_feature,
+ component_recessed_feature_matches,
+ validate_spec,
+ )
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return (
+ ATTACHMENT_ROLES,
+ RECESSED_FEATURE_TOKENS,
+ VALID_TOPOLOGY_CLASSES,
+ component_is_recessed_feature,
+ component_recessed_feature_matches,
+ validate_spec,
+ )
+
+
+(
+ ATTACHMENT_ROLES,
+ RECESSED_FEATURE_TOKENS,
+ VALID_TOPOLOGY_CLASSES,
+ component_is_recessed_feature,
+ component_recessed_feature_matches,
+ validate_spec,
+) = import_forge_modules()
+
+
+def load_fixture() -> dict:
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+def base_spec(component: dict, material: dict | None = None) -> dict:
+ return {
+ "targetName": "Test",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [material or {"id": "skin"}],
+ "componentTree": [component],
+ }
+
+
+class RecessedFeatureGateTest(unittest.TestCase):
+ def test_role_name_id_tokens_are_detected(self) -> None:
+ self.assertTrue(component_is_recessed_feature({"role": "eye-socket"}))
+ self.assertTrue(component_is_recessed_feature({"name": "Left ear canal"}))
+ self.assertTrue(component_is_recessed_feature({"id": "mouth-cavity"}))
+ self.assertTrue(component_is_recessed_feature({"id": "left-nostril"}))
+ self.assertFalse(component_is_recessed_feature({"id": "left-eye", "role": "eye", "name": "Eye"}))
+ self.assertFalse(component_is_recessed_feature({"id": "wing-membrane", "role": "wing"}))
+
+ def test_bare_socket_attachment_point_is_not_treated_as_recessed(self) -> None:
+ """Pin the collision team-lead flagged: ATTACHMENT_ROLES already uses bare "socket"
+ for an attachment POINT (e.g. a hilt socket a handle plugs into), which is not a
+ concavity. This must stay false regardless of surrounding words, since "socket" was
+ deliberately dropped from RECESSED_FEATURE_TOKENS in favor of the narrower compound
+ "eyesocket"."""
+ self.assertIn("socket", ATTACHMENT_ROLES) # the collision this test guards against
+ self.assertFalse(component_is_recessed_feature({"role": "socket"}))
+ self.assertFalse(component_is_recessed_feature({"id": "hilt-socket", "role": "socket", "name": "Hilt socket"}))
+
+ def test_mutation_attachment_socket_component_is_not_rejected_by_rule_1(self) -> None:
+ """End-to-end version of the collision pin: a legitimately-authored attachment
+ socket (cylinder primitive, a real attachment block, role="socket") must validate
+ clean of Rule 1 -- it needs attachment metadata (a separate, pre-existing gate),
+ not implicit/subtract reclassification."""
+ spec = base_spec({
+ "id": "hilt-socket",
+ "name": "Hilt socket",
+ "level": "meso",
+ "role": "socket",
+ "primitive": "cylinder",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Machined cylindrical socket the hilt tang is inserted into.",
+ "parent": "handle",
+ "material": "skin",
+ "attachment": {
+ "parentId": "handle",
+ "parentSocket": "hilt-socket",
+ "localStart": [0.0, 0.0, 0.0],
+ "localEnd": [0.0, 0.2, 0.0],
+ "contactType": "insert",
+ "embedDepth": 0.05,
+ "gapTolerance": 0.002,
+ },
+ })
+ spec["componentTree"].append({
+ "id": "handle",
+ "role": "handle",
+ "primitive": "cylinder",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Grip handle the socket is machined into.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def test_hollow_and_concave_scoped_to_role_do_not_false_positive_on_name(self) -> None:
+ """"hollow tube" and "concave lens" are real, legitimately non-recessed parts.
+ hollow/concave are only recessed-feature signals when they appear in `role`, not
+ `name`/`id`, precisely so these don't get force-rejected into implicit/subtract."""
+ hollow_tube = base_spec({
+ "id": "hollow-tube",
+ "name": "Hollow tube",
+ "role": "pipe",
+ "primitive": "tube",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Thin-walled tube with baked knurl relief.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(hollow_tube)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ concave_lens = base_spec({
+ "id": "concave-lens",
+ "name": "Concave lens",
+ "role": "lens",
+ "primitive": "plane-card",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Flat lens card with a refraction-shader illusion of curvature.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(concave_lens)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def _implicit_eye_cavity(self, operations: list[dict]) -> dict:
+ return {
+ "id": "left-eye-cavity",
+ "role": "cavity",
+ "primitive": "sphere",
+ "topologyClass": "implicit",
+ "topologyRationale": "Carved from the head volume.",
+ "parent": None,
+ "material": "skin",
+ "geometryDescriptor": {
+ "sdf": {
+ "primitives": [
+ {"id": "head", "type": "sphere", "center": [0, 0, 0], "radius": 0.5},
+ {"id": "bulge", "type": "sphere", "center": [0.2, 0.1, 0.4], "radius": 0.12},
+ ],
+ "operations": operations,
+ "resolution": 32,
+ }
+ },
+ }
+
+ def test_mutation_implicit_recessed_feature_without_subtract_is_rejected(self) -> None:
+ """A rule must verify what it advises: `implicit` alone is not "real concavity" if
+ the SDF is built only from union/smooth-union -- that is a bulge sticking OUT, the
+ same US-004 defect (a fake eye) in a different disguise. This is the exact gap
+ team-lead found: the rule only checked topologyClass, not what the descriptor
+ actually built."""
+ spec = base_spec(self._implicit_eye_cavity([
+ {"type": "smooth-union", "left": "head", "right": "bulge", "radius": 0.05},
+ ]))
+ errors, _warnings = validate_spec(spec)
+ recessed_errors = [e for e in errors if "recessed feature" in e]
+ self.assertTrue(recessed_errors, f"expected a recessed-feature error, got: {errors}")
+ message = recessed_errors[0]
+ self.assertIn("left-eye-cavity", message)
+ self.assertIn("subtract", message)
+ self.assertIn("smooth-union", message) # names the actual operations found
+
+ def test_implicit_recessed_feature_with_subtract_present_alongside_other_ops_is_accepted(self) -> None:
+ """`subtract` must be PRESENT, not the ONLY operation -- a socket legitimately
+ composed of a smooth-union of two shapes then subtracted is fine."""
+ component = self._implicit_eye_cavity([
+ {"type": "smooth-union", "left": "head", "right": "bulge", "radius": 0.05, "id": "unioned"},
+ {"type": "subtract", "left": "unioned", "right": "bulge"},
+ ])
+ spec = base_spec(component)
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def test_implicit_recessed_feature_missing_sdf_defers_to_the_existing_implicit_check(self) -> None:
+ """If geometryDescriptor.sdf is missing entirely, Rule 1 must not also complain --
+ the pre-existing `topologyClass 'implicit' requires geometryDescriptor.sdf` check
+ already covers that case, and stacking a second, confusing error on top is worse
+ than one clear one."""
+ spec = base_spec({
+ "id": "left-eye-cavity",
+ "role": "cavity",
+ "primitive": "sphere",
+ "topologyClass": "implicit",
+ "topologyRationale": "Carved from the head volume.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+ self.assertTrue(any("requires geometryDescriptor.sdf" in e for e in errors), errors)
+
+ def test_mutation_assembled_solid_convex_sphere_recessed_feature_is_rejected(self) -> None:
+ """The third route to US-004, found in review: a deny-list of {surface-relief,
+ plane-card} still lets `topologyClass: "assembled-solid"` + a convex sphere through
+ -- not surface-relief, not plane-card, and the subtract check never even runs
+ because it was scoped to `implicit`. This is arguably the MOST likely authoring
+ mistake of the three (assembled-solid is the common default, sphere is the obvious
+ eye shape), which is why the rule is now an allow-list (must be implicit+subtract)
+ rather than a deny-list (must not be X or Y)."""
+ spec = base_spec({
+ "id": "eye-cavity",
+ "role": "cavity",
+ "primitive": "sphere",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Convex sphere standing in for the eye socket.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ recessed_errors = [e for e in errors if "recessed feature" in e]
+ self.assertTrue(recessed_errors, f"expected a recessed-feature error, got: {errors}")
+ message = recessed_errors[0]
+ self.assertIn("eye-cavity", message)
+ self.assertIn("assembled-solid", message)
+ self.assertIn("implicit", message)
+ self.assertIn("subtract", message)
+
+ def test_hollow_and_concave_in_role_do_fire(self) -> None:
+ spec = base_spec({
+ "id": "eye-hole",
+ "role": "hollow",
+ "primitive": "plane-card",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Flat patch depicting a hollow via a normal map.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertTrue(any("recessed feature" in e for e in errors), errors)
+
+ def test_mutation_flat_surface_relief_eye_socket_is_rejected(self) -> None:
+ """Construct the exact recorded defect (US-004): a flat plane-card patch tagged
+ surface-relief standing in for an eye socket. Must exit non-zero with an
+ actionable message naming the fix."""
+ spec = base_spec({
+ "id": "left-eye-socket",
+ "name": "Left eye socket",
+ "level": "meso",
+ "role": "eye-socket",
+ "primitive": "plane-card",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Flat patch depicting the eye via a normal map.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ recessed_errors = [e for e in errors if "recessed feature" in e]
+ self.assertTrue(recessed_errors, f"expected a recessed-feature error, got: {errors}")
+ message = recessed_errors[0]
+ self.assertIn("left-eye-socket", message)
+ self.assertIn("surface-relief", message)
+ self.assertIn("plane-card", message)
+ self.assertIn("implicit", message)
+ self.assertIn("subtract", message)
+
+ def test_mutation_flat_plane_card_eye_is_rejected_even_without_surface_relief_class(self) -> None:
+ spec = base_spec({
+ "id": "right-eye-socket",
+ "role": "eye-socket",
+ "primitive": "plane-card",
+ "topologyClass": "material-only",
+ "topologyRationale": "Flat card with an albedo texture standing in for the socket.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertTrue(any("recessed feature" in e for e in errors), errors)
+
+ def test_correctly_authored_socket_via_implicit_subtract_is_accepted(self) -> None:
+ spec = base_spec({
+ "id": "left-eye-socket",
+ "name": "Left eye socket",
+ "level": "meso",
+ "role": "eye-socket",
+ "primitive": "sphere",
+ "topologyClass": "implicit",
+ "topologyRationale": "Carved as a subtractive cavity from the head volume.",
+ "parent": None,
+ "material": "skin",
+ "geometryDescriptor": {
+ "sdf": {
+ "primitives": [
+ {"id": "head", "type": "sphere", "center": [0, 0, 0], "radius": 0.5},
+ {"id": "socket", "type": "sphere", "center": [0.2, 0.1, 0.4], "radius": 0.12},
+ ],
+ "operations": [
+ {"type": "subtract", "left": "head", "right": "socket"},
+ ],
+ "resolution": 32,
+ }
+ },
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def test_non_recessed_component_is_unaffected(self) -> None:
+ spec = base_spec({
+ "id": "torso",
+ "role": "body",
+ "primitive": "capsule",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Body shell carrying baked panel-line relief.",
+ "parent": None,
+ "material": "skin",
+ })
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def test_shallow_relief_panel_without_a_cavity_token_is_accepted(self) -> None:
+ """Pins the documented escape hatch: the allow-list is strict on purpose (the token
+ IS the declaration -- calling a part a cavity/canal/recess holds it to building a
+ real one), but a genuinely shallow decorative relief (a 0.2mm panel line, not
+ silhouette-relevant, not worth the SDF cost) is simply not a cavity and should not
+ be named one. Renaming it out of the recessed vocabulary (e.g. "panel-relief"
+ instead of "panel-recess") is the legitimate way out, and it must actually work: a
+ surface-relief plane-card panel with no cavity/canal/recess/nostril token, and
+ "hollow"/"concave" absent from role, must validate clean of Rule 1."""
+ spec = base_spec({
+ "id": "grip-panel-relief",
+ "name": "Grip panel relief",
+ "role": "panel-relief",
+ "primitive": "plane-card",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Shallow 0.2mm decorative panel line, not silhouette-relevant.",
+ "parent": None,
+ "material": "skin",
+ })
+ self.assertFalse(component_is_recessed_feature(spec["componentTree"][0]))
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+ def test_dimple_is_no_longer_a_recessed_feature_token(self) -> None:
+ """"dimple" is shallow by definition -- the wrong word for a rule that requires a
+ real carved cavity -- so it was dropped from RECESSED_FEATURE_TOKENS."""
+ self.assertNotIn("dimple", RECESSED_FEATURE_TOKENS)
+ self.assertFalse(component_is_recessed_feature({"role": "dimple", "name": "Dimple", "id": "cheek-dimple"}))
+
+
+class OpenShellTopologyTest(unittest.TestCase):
+ def test_open_shell_is_a_valid_topology_class(self) -> None:
+ self.assertIn("open-shell", VALID_TOPOLOGY_CLASSES)
+
+ def wing_component(self) -> dict:
+ return {
+ "id": "wing-membrane",
+ "name": "Wing membrane",
+ "level": "meso",
+ "role": "wing",
+ "primitive": "plane-card",
+ "topologyClass": "open-shell",
+ "topologyRationale": "Zero-thickness membrane spanning the wing struts.",
+ "parent": None,
+ "material": "wing-material",
+ }
+
+ def test_mutation_open_shell_without_double_sided_material_is_rejected(self) -> None:
+ spec = base_spec(self.wing_component(), material={"id": "wing-material"})
+ errors, _warnings = validate_spec(spec)
+ shell_errors = [e for e in errors if "open-shell" in e and "doubleSided" in e]
+ self.assertTrue(shell_errors, f"expected a doubleSided error, got: {errors}")
+ self.assertIn("wing-membrane", shell_errors[0])
+
+ def test_mutation_open_shell_paired_with_closed_sdf_is_rejected(self) -> None:
+ component = self.wing_component()
+ component["geometryDescriptor"] = {
+ "sdf": {
+ "primitives": [{"id": "p", "type": "sphere", "center": [0, 0, 0], "radius": 0.2}],
+ "operations": [],
+ "resolution": 16,
+ }
+ }
+ spec = base_spec(component, material={"id": "wing-material", "doubleSided": True})
+ errors, _warnings = validate_spec(spec)
+ shell_errors = [e for e in errors if "open-shell" in e and "sdf" in e]
+ self.assertTrue(shell_errors, f"expected an sdf-pairing error, got: {errors}")
+ self.assertIn("zero thickness", shell_errors[0])
+
+ def test_correctly_authored_open_shell_is_accepted(self) -> None:
+ spec = base_spec(self.wing_component(), material={"id": "wing-material", "doubleSided": True})
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("open-shell" in e for e in errors), errors)
+
+ def test_double_sided_must_be_boolean(self) -> None:
+ spec = base_spec(self.wing_component(), material={"id": "wing-material", "doubleSided": "yes"})
+ errors, _warnings = validate_spec(spec)
+ self.assertTrue(any("doubleSided must be boolean" in e for e in errors), errors)
+
+
+class RegressionSafetyTest(unittest.TestCase):
+ """The new rules must not regress any existing fixture."""
+
+ def test_implicit_character_torso_limb_fixture_still_validates_clean(self) -> None:
+ spec = load_fixture()
+ errors, _warnings = validate_spec(spec)
+ self.assertEqual(errors, [])
+
+ def test_real_character_template_eye_cavity_output_is_accepted(self) -> None:
+ """Contract check against worker-template's ACTUAL generated output (not an
+ assumption of it): `new_sculpt_spec.py --character` authors the eye socket as
+ `eye-cavity-{l,r}` with role="cavity", primitive=sphere, topologyClass=implicit --
+ real concavity via the field path, exactly what Rule 1 is meant to accept. It also
+ authors a SEPARATE `eye-{l,r}` component (role="detail", assembled-solid, sphere --
+ the convex eyeball sitting inside the cavity). team-lead flagged that the pair IS
+ the design: a rule tightened against the cavity must not start rejecting the
+ eyeball half too, since neither is optional -- one recesses, the other fills it.
+ This pins that contract so a future change on either side is caught here."""
+ with tempfile.TemporaryDirectory() as directory:
+ spec_path = Path(directory) / "spec.json"
+ result = subprocess.run(
+ [sys.executable, str(ROOT / "stage2_spec" / "new_sculpt_spec.py"),
+ "Person", "--character", "--out", str(spec_path)],
+ capture_output=True, text=True,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+
+ eye_cavities = [c for c in spec["componentTree"] if str(c.get("id", "")).startswith("eye-cavity")]
+ eyeballs = [
+ c for c in spec["componentTree"]
+ if str(c.get("id", "")).startswith("eye-") and not str(c.get("id", "")).startswith("eye-cavity")
+ ]
+ self.assertTrue(eye_cavities, "expected new_sculpt_spec.py --character to author eye-cavity components")
+ self.assertTrue(eyeballs, "expected new_sculpt_spec.py --character to author the eyeball detail components")
+ for component in eye_cavities:
+ self.assertTrue(component_is_recessed_feature(component), component)
+ self.assertEqual(component.get("topologyClass"), "implicit", component)
+ for component in eyeballs:
+ # The eyeball is legitimately convex and must NOT match the recessed signal --
+ # if it did, its assembled-solid/sphere shape would now be rejected by the
+ # allow-list, which would break correct, existing anatomy.
+ self.assertFalse(component_is_recessed_feature(component), component)
+
+ errors, _warnings = validate_spec(spec)
+ self.assertFalse(any("recessed feature" in e for e in errors), errors)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_release_metadata.py b/forge/tests/test_release_metadata.py
new file mode 100644
index 0000000..0b85f09
--- /dev/null
+++ b/forge/tests/test_release_metadata.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+SCRIPT = ROOT / "scripts" / "release_metadata.py"
+
+
+class ReleaseMetadataTests(unittest.TestCase):
+ def write_project(self, directory: Path) -> tuple[Path, Path]:
+ (directory / "SKILL.md").write_text("---\nversion: 1.4.1\n---\n", encoding="utf-8")
+ (directory / "README.md").write_text(
+ "[![Version](https://img.shields.io/badge/version-1.4.1-green.svg)](CHANGELOG.md)\n",
+ encoding="utf-8",
+ )
+ (directory / "CHANGELOG.md").write_text(
+ "# Changelog\n\nIntro.\n\n## [1.4.1] — 2026-07-26\n\n- Existing.\n\n"
+ "[1.4.1]: https://github.com/img2threejs/img2threejs/releases/tag/v1.4.1\n",
+ encoding="utf-8",
+ )
+ commits = directory / "commits.txt"
+ return directory, commits
+
+ def run_release(self, directory: Path, commits: Path, dry_run: bool = False) -> subprocess.CompletedProcess[str]:
+ command = [
+ "python3",
+ str(SCRIPT),
+ "--root",
+ str(directory),
+ "--commits-file",
+ str(commits),
+ "--date",
+ "2026-07-26",
+ "--repository-url",
+ "https://github.com/img2threejs/img2threejs",
+ ]
+ if dry_run:
+ command.append("--dry-run")
+ return subprocess.run(
+ command,
+ capture_output=True,
+ check=False,
+ text=True,
+ )
+
+ def test_minor_release_synchronizes_all_version_metadata(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ project, commits = self.write_project(Path(temporary_directory))
+ commits.write_text("feat: generic image intake\x1efix: image hash stability\x1e", encoding="utf-8")
+
+ result = self.run_release(project, commits)
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)["version"], "1.5.0")
+ self.assertIn("version: 1.5.0", (project / "SKILL.md").read_text(encoding="utf-8"))
+ self.assertIn("version-1.5.0-green.svg", (project / "README.md").read_text(encoding="utf-8"))
+ changelog = (project / "CHANGELOG.md").read_text(encoding="utf-8")
+ self.assertIn("## [1.5.0] — 2026-07-26", changelog)
+ self.assertIn("[1.5.0]: https://github.com/img2threejs/img2threejs/compare/v1.4.1...v1.5.0", changelog)
+
+ def test_non_releasable_commits_leave_metadata_unchanged(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ project, commits = self.write_project(Path(temporary_directory))
+ commits.write_text("docs: clarify usage\x1echore: refresh metadata\x1e", encoding="utf-8")
+ before = (project / "SKILL.md").read_text(encoding="utf-8")
+
+ result = self.run_release(project, commits)
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(json.loads(result.stdout)["release"])
+ self.assertEqual((project / "SKILL.md").read_text(encoding="utf-8"), before)
+
+ def test_dry_run_reports_the_next_version_without_writing_metadata(self) -> None:
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ project, commits = self.write_project(Path(temporary_directory))
+ commits.write_text("fix: image hash stability\x1e", encoding="utf-8")
+ before = (project / "CHANGELOG.md").read_text(encoding="utf-8")
+
+ result = self.run_release(project, commits, dry_run=True)
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)["version"], "1.4.2")
+ self.assertEqual((project / "CHANGELOG.md").read_text(encoding="utf-8"), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_render_bridge.py b/forge/tests/test_render_bridge.py
new file mode 100644
index 0000000..2726b40
--- /dev/null
+++ b/forge/tests/test_render_bridge.py
@@ -0,0 +1,75 @@
+import json
+import struct
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+from forge.stage4_review.render_bridge import (
+ init_manifest,
+ record_capture,
+ validate_manifest,
+ write_manifest,
+)
+
+
+def write_png(path: Path, width: int = 8, height: int = 8) -> None:
+ signature = b"\x89PNG\r\n\x1a\n"
+
+ def chunk(kind: bytes, payload: bytes) -> bytes:
+ checksum = zlib.crc32(kind)
+ checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
+
+ rows = b"".join(b"\x00" + bytes([220, 80, 80]) * width for _ in range(height))
+ path.write_bytes(
+ signature
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(rows))
+ + chunk(b"IEND", b"")
+ )
+
+
+class RenderBridgeTest(unittest.TestCase):
+ def test_init_emits_required_camera_batch(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ reference = root / "reference.png"
+ write_png(reference)
+ manifest_path = root / "manifest.json"
+ manifest = init_manifest(reference, "http://127.0.0.1:5173/#/character", manifest_path, (620, 1000), 1.0, "captures")
+ self.assertEqual(manifest["schemaVersion"], 1)
+ self.assertEqual({item["id"] for item in manifest["captures"]}, {
+ "hero", "orbit-plus35", "orbit-minus35", "profile", "rear", "head-hero", "head-threequarter"
+ })
+ self.assertEqual(manifest["reference"]["sha256"], __import__("hashlib").sha256(reference.read_bytes()).hexdigest())
+
+ def test_record_and_validate_preserve_screenshot_hash(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ reference = root / "reference.png"
+ screenshot = root / "captures" / "hero.png"
+ screenshot.parent.mkdir()
+ write_png(reference)
+ write_png(screenshot, 16, 16)
+ manifest_path = root / "manifest.json"
+ manifest = init_manifest(reference, "http://127.0.0.1:5173", manifest_path, (620, 1000), 1.0, "captures")
+ record_capture(manifest_path, manifest, "hero", screenshot, ready_signal=True)
+ write_manifest(manifest_path, manifest)
+ result = validate_manifest(manifest_path)
+ self.assertTrue(result["passed"])
+ saved = json.loads(manifest_path.read_text())
+ self.assertEqual(saved["captures"][0]["status"], "recorded")
+ self.assertEqual(saved["captures"][0]["image"]["width"], 16)
+
+ def test_validate_detects_changed_reference(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ reference = root / "reference.png"
+ write_png(reference)
+ manifest_path = root / "manifest.json"
+ write_manifest(manifest_path, init_manifest(reference, "http://127.0.0.1:5173", manifest_path, (1, 1), 1.0, "captures"))
+ reference.write_bytes(reference.read_bytes() + b"changed")
+ result = validate_manifest(manifest_path)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("hash changed" in error for error in result["errors"]))
diff --git a/forge/tests/test_render_profile.py b/forge/tests/test_render_profile.py
new file mode 100644
index 0000000..bebe08d
--- /dev/null
+++ b/forge/tests/test_render_profile.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from forge.stage4_review.validate_render_profile import validate_file, validate_profile
+
+
+PROFILE = Path(__file__).resolve().parents[2] / "docs" / "specs" / "render-profile.v2.example.json"
+
+
+class RenderProfileTest(unittest.TestCase):
+ def test_example_profile_passes(self) -> None:
+ result = validate_file(PROFILE)
+ self.assertTrue(result["passed"], result)
+ self.assertEqual(result["passIds"], [
+ "beauty",
+ "alpha-silhouette",
+ "semantic-id",
+ "depth",
+ "normal",
+ "roughness-material-id",
+ ])
+
+ def test_profile_rejects_wrong_color_space(self) -> None:
+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))
+ profile["renderer"]["outputColorSpace"] = "LinearSRGBColorSpace"
+ result = validate_profile(profile)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("outputColorSpace" in error for error in result["errors"]))
+
+ def test_profile_rejects_missing_pass(self) -> None:
+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))
+ profile["passes"] = profile["passes"][:-1]
+ result = validate_profile(profile)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("passes must contain exactly" in error for error in result["errors"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_repetition_system_scale.py b/forge/tests/test_repetition_system_scale.py
new file mode 100644
index 0000000..83ba5e1
--- /dev/null
+++ b/forge/tests/test_repetition_system_scale.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python3
+"""PLAN_1.5 WS-E follow-up: a repetitionSystems cluster parented to a non-uniformly
+scaled component must not inherit that component's shape.
+
+`generate_threejs_factory.py`'s repetition-system emitter parents its
+`THREE.InstancedMesh` directly onto the referenced component's pivot Group
+(`parent.add(cluster)`). Before the WS-E fix that Group carried the component's
+declared dimensional scale (`node.scale.set(component.transform.scale)`), so an
+instanced fastener/rivet/spoke was implicitly re-scaled by its host's shape, and a
+`radial` ring's placement (computed in the plane perpendicular to `placement.axis`)
+was squashed into an ellipse by a non-uniform host. After the fix the pivot Group's
+scale is always identity, so `instanceScale` and `placement.radius` are absolute,
+independent of the host's shape.
+
+This is a REAL-RUN test (tsc + node, same pattern as `test_hierarchy_scale.py` /
+`test_visual_hull.py`): a "plate" component (box, sharply non-uniform scale
+[4, 1, 0.3]) parents a `repetitionSystems` entry ("rivets", 8 instances, radial
+placement about the Y axis). Every instance's ACTUAL executed world transform is
+read back via `InstancedMesh.getMatrixAt` composed with `cluster.matrixWorld` --
+no hand-computed expectation is substituted for execution.
+
+Pure Python 3.10+ stdlib on this side. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+ROOT = Path(__file__).resolve().parent.parent
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate
+ from validate_sculpt_spec import validate_spec
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return generate, validate_spec
+
+
+generate, validate_spec = import_forge_modules()
+
+# A sharply non-uniform "plate" (box, scale [4, 1, 0.3]) parenting a radial ring of
+# 8 "rivets" (instanceScale [0.05, 0.05, 0.05], radius 1.0, axis +Y). The ring's
+# placement plane is perpendicular to axis +Y, i.e. the local XZ plane -- exactly
+# the plane the plate's X and Z scale factors (4 and 0.3) would squash if
+# instanceScale/placement were still relative to the host's declared scale.
+RIVETED_PLATE_SPEC = {
+ "targetName": "Riveted Plate",
+ "schemaVersion": "2.1",
+ "suitability": "pass",
+ "coordinateFrame": {},
+ "silhouette": {},
+ "proceduralStrategy": [],
+ "materials": [{"id": "clay"}],
+ "componentTree": [
+ {
+ "id": "plate",
+ "name": "Plate",
+ "level": "macro",
+ "role": "body",
+ "primitive": "box",
+ "parent": None,
+ "material": "clay",
+ "transform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [4.0, 1.0, 0.3]},
+ },
+ ],
+ "repetitionSystems": [
+ {
+ "id": "rivets",
+ "parent": "plate",
+ "level": "macro",
+ "count": 8,
+ "primitive": "sphere",
+ "material": "clay",
+ "instanceScale": [0.05, 0.05, 0.05],
+ "placement": {"mode": "radial", "axis": [0.0, 1.0, 0.0], "radius": 1.0, "startAngleDeg": 0.0},
+ },
+ ],
+}
+
+
+def compile_generated_module(generated: str, work_dir: Path) -> tuple[subprocess.CompletedProcess[str], Path]:
+ source = work_dir / "repetition-system-scale.ts"
+ build_dir = work_dir / "build"
+ source.write_text(generated, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "npx", "tsc", "--target", "ES2020", "--module", "NodeNext", "--moduleResolution", "NodeNext",
+ "--strict", "--skipLibCheck", "--noUnusedLocals", "--noUnusedParameters",
+ "--outDir", str(build_dir), str(source),
+ ],
+ cwd=showcase_root(),
+ capture_output=True,
+ text=True,
+ )
+ return result, build_dir / "repetition-system-scale.js"
+
+
+_EVAL_SCRIPT = """
+import * as THREE from 'three';
+import { createRivetedPlateModel } from './build/repetition-system-scale.js';
+
+const model = createRivetedPlateModel();
+const plate = model.userData.sculptRuntime.nodes['plate'];
+const cluster = plate.children.find((child) => child.name === 'rivets');
+if (!cluster) throw new Error("repetition cluster 'rivets' not found under plate");
+
+model.updateMatrixWorld(true);
+
+const localMatrix = new THREE.Matrix4();
+const combined = new THREE.Matrix4();
+const pos = new THREE.Vector3();
+const quat = new THREE.Quaternion();
+const scl = new THREE.Vector3();
+const distances = [];
+const scales = [];
+for (let i = 0; i < cluster.count; i += 1) {
+ cluster.getMatrixAt(i, localMatrix);
+ combined.multiplyMatrices(cluster.matrixWorld, localMatrix);
+ combined.decompose(pos, quat, scl);
+ distances.push(pos.length());
+ scales.push(scl.toArray());
+}
+
+console.log(JSON.stringify({
+ plateScale: plate.scale.toArray(),
+ instanceCount: cluster.count,
+ distances,
+ scales,
+}));
+"""
+
+
+class RepetitionSystemScaleTest(unittest.TestCase):
+ result: dict
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ errors, _warnings = validate_spec(RIVETED_PLATE_SPEC)
+ if errors:
+ raise RuntimeError(f"FAIL CLOSED: fixture spec did not validate: {errors}")
+ generated = generate(RIVETED_PLATE_SPEC, "blockout")
+
+ cls._tempdir_ctx = tempfile.TemporaryDirectory(dir=showcase_root())
+ work_dir = Path(cls._tempdir_ctx.name)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ if compile_result.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: tsc did not compile the emitted module: {compile_result.stderr}")
+
+ runtime = subprocess.run(
+ ["node", "--input-type=module", "--eval", _EVAL_SCRIPT],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ if runtime.returncode != 0:
+ raise RuntimeError(f"FAIL CLOSED: node execution of the emitted module failed: {runtime.stderr}")
+ try:
+ cls.result = json.loads(runtime.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"FAIL CLOSED: result was not parseable JSON: {exc}\nstdout: {runtime.stdout!r}") from exc
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls._tempdir_ctx.cleanup()
+
+ def test_cluster_found_all_instances_present(self) -> None:
+ self.assertEqual(self.result["instanceCount"], 8)
+
+ def test_host_pivot_scale_is_identity(self) -> None:
+ self.assertEqual(self.result["plateScale"], [1, 1, 1])
+
+ def test_instance_world_scale_equals_instance_scale_not_host_scale(self) -> None:
+ # Regression check: instanceScale [0.05, 0.05, 0.05] must reach the screen
+ # unmodified. Under the pre-fix behaviour it would have been multiplied by
+ # the plate's declared scale [4, 1, 0.3], measuring [0.2, 0.05, 0.015].
+ for index, scale in enumerate(self.result["scales"]):
+ for axis, value in enumerate(scale):
+ self.assertAlmostEqual(
+ value, 0.05, places=4,
+ msg=f"instance {index} axis {axis}: world scale {value} != instanceScale 0.05 "
+ "(looks like it inherited the host's declared scale)",
+ )
+
+ def test_radial_ring_stays_circular_under_a_nonuniform_host(self) -> None:
+ # This is the mutation check: under the pre-fix behaviour the plate's
+ # [4, 1, 0.3] scale would cascade onto the ring (which lies in the local XZ
+ # plane, perpendicular to placement.axis +Y), squashing distance-from-center
+ # from 0.5 up to 2.0 along X and down to 0.15 along Z depending on angle --
+ # an ellipse, not a ring. With the fix every instance sits at the same
+ # distance from center regardless of angle.
+ distances = self.result["distances"]
+ self.assertGreater(min(distances), 0.1, "ring collapsed toward the center")
+ self.assertAlmostEqual(
+ min(distances), max(distances), places=2,
+ msg=f"ring is not circular: distances range {min(distances)}..{max(distances)} (expected a constant radius)",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_rig_hierarchy_emission.py b/forge/tests/test_rig_hierarchy_emission.py
new file mode 100644
index 0000000..0cf6842
--- /dev/null
+++ b/forge/tests/test_rig_hierarchy_emission.py
@@ -0,0 +1,488 @@
+"""PLAN_1.5 WS-C slice 1 — the emitted bone hierarchy, measured on executed geometry.
+
+The load-bearing test is `test_bone_world_positions_round_trip_to_the_spec_joints`. The spec
+stores `jointPos` in MODEL space and a `THREE.Bone`'s position is PARENT-LOCAL, so the emitter
+subtracts the parent's joint. If that conversion is wrong in any frame, accumulating the offsets
+back down the chain lands somewhere else — and nothing else in the suite would notice, because
+the code would still compile and still produce sixteen correctly-named bones.
+
+`test_pivot_track_emits_no_rig` guards the other half of PLAN_1.5 §8: the pivot track is "not
+replaced", so an `object` spec must come out of the generator with no bone code at all.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+_TESTS = Path(__file__).resolve().parent
+_FORGE = _TESTS.parent
+for path in (_TESTS, _FORGE, _FORGE / "stage2_spec", _FORGE / "stage3_build"):
+ sys.path.insert(0, str(path))
+
+try:
+ from .showcase_test_support import showcase_root
+except ImportError:
+ from showcase_test_support import showcase_root
+
+from generate_threejs_factory import ( # noqa: E402
+ _posed_bone_rotations,
+ generate,
+ rig_is_bone_track,
+)
+
+
+class RigHierarchyEmission(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.root = showcase_root() # skips with an actionable message when unset
+ out = Path(tempfile.mkdtemp()) / "chr.json"
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Rig Probe", "--character", "--out", str(out)],
+ capture_output=True, text=True, check=True,
+ )
+ cls.spec = json.loads(out.read_text())
+ cls.generated = generate(cls.spec, "blockout")
+
+ def test_character_spec_is_on_the_bone_track(self) -> None:
+ self.assertTrue(rig_is_bone_track(self.spec))
+
+ def test_pivot_track_emits_no_rig(self) -> None:
+ """PLAN_1.5 §8: the pivot track is not replaced, so an object spec gets no bone code.
+
+ This generates a REAL object spec rather than flipping `primaryDomain` on the character
+ one. Doing that by hand is rejected outright — `validate_sculpt_spec` cross-checks
+ `pipelineRouting.track` against `primaryDomain` ("character-v1.5 routing requires the
+ character template"), so a hand-mangled hybrid tests a spec shape that cannot exist.
+ """
+ out = Path(tempfile.mkdtemp()) / "obj.json"
+ subprocess.run(
+ [sys.executable, str(_FORGE / "stage2_spec" / "new_sculpt_spec.py"),
+ "Pivot Probe", "--out", str(out)],
+ capture_output=True, text=True, check=True,
+ )
+ object_spec = json.loads(out.read_text())
+ self.assertFalse(rig_is_bone_track(object_spec))
+ source = generate(object_spec, "blockout")
+ self.assertNotIn("THREE.Bone", source)
+ self.assertNotIn("userData.rig", source)
+
+ def test_bones_are_emitted_parents_first(self) -> None:
+ """The spec's bone list is sorted by (has-parent, id), so `foot-l` precedes `shin-l`.
+ Emitting in list order would parent a bone to one that does not exist yet."""
+ declared: set[str] = set()
+ for line in self.generated.splitlines():
+ made = re.match(r"\s*const (bone_\w+) = new THREE\.Bone\(\)", line)
+ if made:
+ declared.add(made.group(1))
+ continue
+ added = re.match(r"\s*(bone_\w+)\.add\((bone_\w+)\)", line)
+ if added:
+ self.assertIn(added.group(1), declared, f"parent used before declaration: {line.strip()}")
+
+ def test_attachment_limbs_receive_their_authored_rotation(self) -> None:
+ """The endpoint branch used to force `node.rotation.set(0, 0, 0)`.
+
+ Every capsule/cylinder limb carries an `attachment` block and therefore takes that
+ branch, so zeroing there silently discarded every authored rotation on exactly the
+ components that articulate — `anatomy.pose.jointAngles` had no observable effect at all
+ until it stopped. Posing works because the pivot sits AT the joint while the limb's own
+ direction lives on the mesh inside it, so rotating the pivot rotates the limb about its
+ joint. Guarding the emitted source because a regression here is invisible: the model
+ still builds, still renders, and simply ignores the pose.
+ """
+ from new_sculpt_spec import apply_character_pose
+
+ spec = json.loads(json.dumps(self.spec))
+ applied = apply_character_pose(
+ spec["componentTree"],
+ {"pose": {"jointAngles": {"leftShoulder": [0.05, 0.0, -0.2],
+ "rightElbow": [-0.34, 0.0, 0.05]}}},
+ )
+ self.assertEqual(len(applied), 2)
+ source = generate(spec, "blockout")
+
+ posed = {c["id"]: (c.get("transform") or {}).get("rotation")
+ for c in spec["componentTree"]
+ if c.get("attachment")
+ and any(abs(float(v)) > 1e-9
+ for v in ((c.get("transform") or {}).get("rotation") or [0, 0, 0]))}
+ self.assertTrue(posed, "fixture must contain at least one posed attachment limb")
+ for component_id, rotation in posed.items():
+ literal = ", ".join(str(float(v)) for v in rotation)
+ self.assertIn(
+ f"rotation.set({literal})", source,
+ f"{component_id}: authored rotation {rotation} never reaches the emitted source",
+ )
+
+ def test_exactly_one_weight_function_is_emitted(self) -> None:
+ """WS-C.2's acceptance criterion is literally "a grep must find no second weight
+ function". Two copies is the defect the criterion exists to prevent, so this counts."""
+ self.assertEqual(self.generated.count("const computeVertexWeights ="), 1)
+ self.assertIn("new Map<string, number>", self.generated)
+ self.assertEqual(self.generated.count("boneOrder.indexOf"), 0,
+ "bone lookup must be a Map, not indexOf")
+ self.assertIn("fallback: true", self.generated,
+ "the zero-sum fallback (PLAN_1.5 §4 / ADR-8) must be present")
+
+ def test_skin_weights_are_normalised_and_in_range_on_executed_geometry(self) -> None:
+ """Measured, not asserted from the source. The fallback's reachability is what makes
+ `zeroSum == 0` meaningful: with 49 envelopes over ~31.7k vertices, any vertex outside
+ every envelope would otherwise sum to zero and three.js would silently pin it to bone 0.
+ """
+ probe = """
+import { %(factory)s } from './build/%(stem)s.js';
+const m = %(factory)s();
+const rig = m.userData.rig;
+let worstSum = 0, zeroSum = 0, outOfRange = 0, verts = 0;
+const boneCount = rig.boneOrder.length;
+for (const name of rig.skinAttributes) {
+ const g = m.userData.sculptRuntime.meshes[name].geometry;
+ const si = g.getAttribute('skinIndex'), sw = g.getAttribute('skinWeight');
+ if (!si || !sw) continue;
+ for (let v = 0; v < sw.count; v++) {
+ verts++; let s = 0;
+ for (let k = 0; k < 4; k++) {
+ const idx = si.getComponent(v, k); s += sw.getComponent(v, k);
+ if (idx < 0 || idx >= boneCount) outOfRange++;
+ }
+ if (s === 0) zeroSum++;
+ worstSum = Math.max(worstSum, Math.abs(s - 1));
+ }
+}
+console.log(JSON.stringify({ bound: rig.bound, boneCount, verts, worstSum, zeroSum, outOfRange }));
+"""
+ factory = re.search(r"export function (create\w+Model)", self.generated).group(1)
+ with tempfile.TemporaryDirectory(dir=self.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(self.generated, work)
+ self.assertEqual(compiled.returncode, 0, compiled.stderr)
+ run = subprocess.run(
+ ["node", "--input-type=module", "--eval",
+ probe % {"factory": factory, "stem": module_path.stem}],
+ cwd=work, capture_output=True, text=True,
+ )
+ self.assertEqual(run.returncode, 0, f"{run.stdout}\n{run.stderr}")
+ data = json.loads(run.stdout.strip().splitlines()[-1])
+
+ self.assertGreater(data["verts"], 0, "no skin attributes were written at all")
+ self.assertLess(data["worstSum"], 1e-5,
+ f"weights do not sum to 1: max error {data['worstSum']:.3e}")
+ self.assertEqual(data["zeroSum"], 0, "a zero-weight-sum vertex escaped the fallback")
+ self.assertEqual(data["outOfRange"], 0, "skinIndex out of range")
+ self.assertTrue(data["bound"],
+ "WS-C.3 binds every skinned mesh; rig.bound must say so")
+
+ def test_bone_world_positions_round_trip_to_the_spec_joints(self) -> None:
+ probe = """
+import { %(factory)s } from './build/%(stem)s.js';
+import * as THREE from 'three';
+const model = %(factory)s();
+const rig = model.userData.rig;
+model.updateMatrixWorld(true);
+const out = { bound: rig.bound, count: rig.boneOrder.length,
+ skeletonBones: rig.skeleton.bones.length, world: {}, parent: {} };
+for (const id of rig.boneOrder) {
+ const b = rig.bones[id];
+ out.world[id] = new THREE.Vector3().setFromMatrixPosition(b.matrixWorld).toArray();
+ out.parent[id] = b.parent && b.parent.isBone ? b.parent.name : null;
+}
+console.log(JSON.stringify(out));
+"""
+ factory = re.search(r"export function (create\w+Model)", self.generated).group(1)
+ with tempfile.TemporaryDirectory(dir=self.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(self.generated, work)
+ self.assertEqual(compiled.returncode, 0, compiled.stderr)
+ run = subprocess.run(
+ ["node", "--input-type=module", "--eval",
+ probe % {"factory": factory, "stem": module_path.stem}],
+ cwd=work, capture_output=True, text=True,
+ )
+ self.assertEqual(run.returncode, 0, f"{run.stdout}\n{run.stderr}")
+ data = json.loads(run.stdout.strip().splitlines()[-1])
+
+ by_id = {b["id"]: b for b in self.spec["rig"]["bones"]}
+ self.assertEqual(data["count"], len(by_id))
+ self.assertEqual(data["skeletonBones"], len(by_id))
+ self.assertTrue(data["bound"], "WS-C.3 binds the skinned meshes; say so in userData.rig")
+
+ # This round-trip is a REST-pose invariant. The generator applies the authored pose to the
+ # bones as its last act, so on a posed spec a bone's world position is its posed position,
+ # not its rest joint. What matters is specifically that no BONE's component is rotated --
+ # the fixture does rotate `nose`, but a micro detail with no bone cannot move a bone.
+ # Checked with the emitter's own predicate so the two cannot drift apart.
+ self.assertEqual(
+ _posed_bone_rotations(self.spec, self.spec["rig"]["bones"]), [],
+ "no bone's component may be posed, or the rest-pose round-trip below is vacuous")
+
+ for bone_id, world in data["world"].items():
+ joint = by_id[bone_id]["jointPos"]
+ error = max(abs(world[i] - joint[i]) for i in range(3))
+ self.assertLess(
+ error, 1e-6,
+ f"bone {bone_id!r} world position {world} does not round-trip to its "
+ f"model-space jointPos {joint} (error {error:.3e}) — the parent-local "
+ f"conversion is wrong",
+ )
+ self.assertEqual(data["parent"][bone_id], by_id[bone_id]["parent"])
+
+ def test_bone_rotation_deforms_its_own_mesh_and_not_a_distant_one(self) -> None:
+ """WS-C.3: the meshes are genuinely skeleton-driven, on executed geometry.
+
+ `rig.bound === true` does not prove this. A mesh can be bound and completely inert if the
+ skeleton's inverse bind matrices cancel the wrong pose — which is what a `Skeleton`
+ constructed before `updateMatrixWorld()` produces, since `calculateInverses()` reads the
+ bones' CURRENT world matrices and would capture identity. That failure compiles, binds,
+ reports `bound: true`, and renders a corpse.
+
+ The far-mesh half is the negative control. Without it this test passes just as well on a
+ model where every vertex is weighted to every bone, which is the other way skinning goes
+ wrong — the whole body billowing when one finger moves.
+ """
+ probe = """
+import { %(factory)s } from './build/%(stem)s.js';
+import * as THREE from 'three';
+const model = %(factory)s();
+model.updateMatrixWorld(true);
+const rig = model.userData.rig;
+const skinned = [];
+const skeletons = new Set();
+model.traverse((o) => {
+ if (o.isSkinnedMesh) { skinned.push(o); if (o.skeleton) skeletons.add(o.skeleton); }
+});
+const v = new THREE.Vector3();
+const sample = (mesh) => {
+ const pos = mesh.geometry.getAttribute('position');
+ const pts = [];
+ for (let i = 0; i < pos.count; i += 3) {
+ v.fromBufferAttribute(pos, i);
+ mesh.applyBoneTransform(i, v);
+ pts.push(mesh.localToWorld(v.clone()).toArray());
+ }
+ return pts;
+};
+const spread = (a, b) => {
+ let mx = 0;
+ for (let i = 0; i < a.length; i++) {
+ mx = Math.max(mx, Math.hypot(a[i][0]-b[i][0], a[i][1]-b[i][1], a[i][2]-b[i][2]));
+ }
+ return mx;
+};
+const byName = {};
+for (const mesh of skinned) byName[mesh.name] = mesh;
+
+// Rest-pose identity. With every bone rotation zeroed the bones are back in the pose the
+// Skeleton's inverse bind matrices were computed from, so skinning must be a NO-OP: each vertex
+// maps to exactly where the baked geometry already puts it. This is what catches a Skeleton
+// constructed before its bones' world matrices exist -- calculateInverses() then captures
+// identity, and every vertex is displaced by its bone's joint offset instead of staying put.
+const restRotations = {};
+for (const id of rig.boneOrder) {
+ const b = rig.bones[id];
+ restRotations[id] = [b.rotation.x, b.rotation.y, b.rotation.z];
+ b.rotation.set(0, 0, 0);
+}
+model.updateMatrixWorld(true); rig.skeleton.update();
+let restDrift = 0;
+let restChecked = 0;
+for (const mesh of skinned) {
+ const pos = mesh.geometry.getAttribute('position');
+ for (let i = 0; i < pos.count; i += 3) {
+ v.fromBufferAttribute(pos, i);
+ const raw = v.clone();
+ mesh.applyBoneTransform(i, v);
+ restDrift = Math.max(restDrift, raw.distanceTo(v));
+ restChecked += 1;
+ }
+}
+for (const id of rig.boneOrder) rig.bones[id].rotation.set(...restRotations[id]);
+model.updateMatrixWorld(true); rig.skeleton.update();
+
+const out = {
+ restDrift, restChecked,
+ bound: rig.bound,
+ skinnedCount: skinned.length,
+ skeletonCount: skeletons.size,
+ allParentedToRoot: skinned.every((o) => o.parent === model),
+ identityLocal: skinned.every((o) =>
+ o.position.lengthSq() < 1e-12
+ && o.scale.distanceToSquared(new THREE.Vector3(1, 1, 1)) < 1e-12),
+ anyCulled: skinned.filter((o) => o.frustumCulled).map((o) => o.name),
+ cullingRecorded: rig.frustumCulled === false && typeof rig.cullingNote === 'string',
+ names: Object.keys(byName),
+ probes: [],
+};
+for (const [boneId, ownName, farName] of %(cases)s) {
+ const bone = rig.bones[boneId], own = byName[ownName], far = byName[farName];
+ if (!bone || !own || !far) { out.probes.push({ boneId, missing: true }); continue; }
+ const beforeOwn = sample(own), beforeFar = sample(far);
+ const keep = bone.rotation.z;
+ bone.rotation.z = keep + 1.0;
+ model.updateMatrixWorld(true); rig.skeleton.update();
+ const ownDelta = spread(beforeOwn, sample(own));
+ const farDelta = spread(beforeFar, sample(far));
+ bone.rotation.z = keep;
+ model.updateMatrixWorld(true); rig.skeleton.update();
+ out.probes.push({ boneId, ownName, farName, ownDelta, farDelta });
+}
+console.log(JSON.stringify(out));
+"""
+ cases = [["upper-arm-l", "Upper arm L", "Shin R"], ["thigh-r", "Thigh R", "Forearm L"]]
+ factory = re.search(r"export function (create\w+Model)", self.generated).group(1)
+ with tempfile.TemporaryDirectory(dir=self.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(self.generated, work)
+ self.assertEqual(compiled.returncode, 0, compiled.stderr)
+ run = subprocess.run(
+ ["node", "--max-old-space-size=3072", "--input-type=module", "--eval",
+ probe % {"factory": factory, "stem": module_path.stem,
+ "cases": json.dumps(cases)}],
+ cwd=work, capture_output=True, text=True,
+ )
+ self.assertEqual(run.returncode, 0, f"{run.stdout}\n{run.stderr}")
+ data = json.loads(run.stdout.strip().splitlines()[-1])
+
+ bone_count = len(self.spec["rig"]["bones"])
+ self.assertTrue(data["bound"])
+ self.assertEqual(data["skinnedCount"], bone_count,
+ "every bone's component must be emitted as a THREE.SkinnedMesh")
+ self.assertEqual(data["skeletonCount"], 1,
+ f"all {bone_count} skinned meshes must share ONE Skeleton, "
+ f"found {data['skeletonCount']}")
+ self.assertTrue(data["allParentedToRoot"],
+ "skinned meshes are reparented to root so no pivot applies on top")
+ self.assertTrue(data["identityLocal"],
+ "a skinned mesh's own transform must be identity; its world matrix was "
+ "baked into the geometry")
+ # A SkinnedMesh keeps its REST boundingSphere, so a posed limb reaching outside it is culled
+ # and disappears from some camera angles only. The choice has to be discoverable too, or a
+ # consumer that needs culling silently gets none.
+ self.assertEqual(data["anyCulled"], [],
+ "these skinned meshes are still frustum-culled and can vanish when posed")
+ self.assertTrue(data["cullingRecorded"],
+ "userData.rig must record the culling decision and why")
+ self.assertGreater(data["restChecked"], 1000,
+ "the rest-pose check must actually sample vertices")
+ self.assertLess(
+ data["restDrift"], 1e-5,
+ f"at rest, skinning displaces vertices by up to {data['restDrift']:.4f} instead of "
+ f"leaving them where the baked geometry puts them — the Skeleton's inverse bind "
+ f"matrices do not match the pose the geometry was baked in",
+ )
+
+ self.assertEqual(len(data["probes"]), len(cases))
+ for probe_result in data["probes"]:
+ self.assertFalse(
+ probe_result.get("missing"),
+ f"probe {probe_result['boneId']!r} could not resolve its meshes; available: "
+ f"{sorted(data['names'])}",
+ )
+ self.assertGreater(
+ probe_result["ownDelta"], 1e-3,
+ f"rotating bone {probe_result['boneId']!r} moved its own mesh "
+ f"{probe_result['ownName']!r} by only {probe_result['ownDelta']:.3e} — the mesh "
+ f"is bound but inert",
+ )
+ self.assertLess(
+ probe_result["farDelta"], 1e-6,
+ f"rotating bone {probe_result['boneId']!r} also moved {probe_result['farName']!r} "
+ f"by {probe_result['farDelta']:.3e} — weights are leaking across the body",
+ )
+
+
+ def test_the_bake_is_pose_independent(self) -> None:
+ """A posed spec must bake the SAME rest geometry as an unposed one.
+
+ The bake folds each skinned mesh's world matrix into its vertex data, and at that moment
+ the pivots still carry the authored pose — so baking naively freezes the pose into the
+ buffer while the bones ALSO apply it, and the figure is posed twice. Nothing checked so far
+ can see that: `bound` is true, bones still deform their own meshes, weights still sum to 1,
+ and the rest-pose identity check still passes, because at bone-rest skinning is a no-op on
+ whatever geometry happens to be in the buffer — correct or not.
+
+ So compare the two builds directly. The raw baked geometry is what the pose must not reach;
+ if it is identical with and without a pose, the pose lives only on the bones.
+
+ The fixture is posed here rather than reusing the template's own pose because the character
+ template poses no bone at all (only `nose`, a boneless micro detail), which would make this
+ a no-op — a mutation that removed the rest-for-bake step passed against it.
+ """
+ posed_spec = json.loads(json.dumps(self.spec))
+ pose = {"upper-arm-l": [0.0, 0.0, 0.45], "shin-r": [0.35, 0.0, 0.0],
+ "neck": [0.0, 0.25, 0.0]}
+ applied = 0
+ for component in posed_spec["componentTree"]:
+ if component["id"] in pose:
+ component["transform"]["rotation"] = pose[component["id"]]
+ applied += 1
+ self.assertEqual(applied, len(pose), "fixture pose did not land on the intended components")
+ self.assertEqual(
+ {b for b, _c, _v in _posed_bone_rotations(posed_spec, posed_spec["rig"]["bones"])},
+ set(pose), "the posed components must all be bones, or this proves nothing")
+
+ probe = """
+import { %(factory)s } from './build/%(stem)s.js';
+const model = %(factory)s();
+model.updateMatrixWorld(true);
+const raw = {};
+model.traverse((o) => {
+ if (!o.isSkinnedMesh) return;
+ const pos = o.geometry.getAttribute('position');
+ const pts = [];
+ for (let i = 0; i < pos.count; i += 11) {
+ pts.push([+pos.getX(i).toFixed(6), +pos.getY(i).toFixed(6), +pos.getZ(i).toFixed(6)]);
+ }
+ raw[o.name] = pts;
+});
+console.log(JSON.stringify(raw));
+"""
+
+ def raw_geometry(spec: dict) -> dict:
+ generated = generate(spec, "blockout")
+ factory = re.search(r"export function (create\w+Model)", generated).group(1)
+ with tempfile.TemporaryDirectory(dir=self.root) as tmp:
+ work = Path(tmp)
+ from test_hierarchy_scale import compile_generated_module
+ compiled, module_path = compile_generated_module(generated, work)
+ self.assertEqual(compiled.returncode, 0, compiled.stderr)
+ run = subprocess.run(
+ ["node", "--max-old-space-size=3072", "--input-type=module", "--eval",
+ probe % {"factory": factory, "stem": module_path.stem}],
+ cwd=work, capture_output=True, text=True,
+ )
+ self.assertEqual(run.returncode, 0, f"{run.stdout}\n{run.stderr}")
+ return json.loads(run.stdout.strip().splitlines()[-1])
+
+ rest = raw_geometry(self.spec)
+ posed = raw_geometry(posed_spec)
+
+ self.assertEqual(sorted(rest), sorted(posed), "the two builds skinned different meshes")
+ self.assertGreater(sum(len(v) for v in rest.values()), 500,
+ "not enough vertices sampled for this comparison to mean anything")
+ worst_name, worst = "", 0.0
+ for name, points in rest.items():
+ for a, b in zip(points, posed[name]):
+ drift = max(abs(a[i] - b[i]) for i in range(3))
+ if drift > worst:
+ worst_name, worst = name, drift
+ self.assertLess(
+ worst, 1e-5,
+ f"posing the spec changed the BAKED geometry of {worst_name!r} by {worst:.5f} — the "
+ f"pose was frozen into the vertex buffer, so the bones will apply it a second time",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_rig_milestone0.py b/forge/tests/test_rig_milestone0.py
new file mode 100644
index 0000000..198aeed
--- /dev/null
+++ b/forge/tests/test_rig_milestone0.py
@@ -0,0 +1,404 @@
+#!/usr/bin/env python3
+"""Milestone 0 rig kill test.
+
+Question this answers: can a generator EMIT a working skinned rig from a
+RigSpec, or not? See docs/PLAN_1.5_ANIMATION_READY_RIGS.md.
+
+This is a REAL-RUN test only. It emits TypeScript from a hand-written RigSpec
+(forge/stage5_rig/emit_rig.py), executes that emitted code with the
+showcase's real `three` via a Node subprocess
+(img2threejs-showcase/scripts/rig-milestone0.mjs), and gates on numbers read
+back from the executed geometry. No mock, no hand-computed expectation. If
+the subprocess cannot run or does not produce a parseable result, this test
+fails closed and loudly (a missing showcase checkout, a missing `node`, or an
+unexecutable emit are all treated as a Milestone 0 FAIL, not a skip).
+
+Reproduce standalone:
+ node <showcase>/scripts/rig-milestone0.mjs <emitted.ts> --out result.json
+
+Pure Python 3.10+ stdlib on this side. No pip installs.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+FORGE_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(FORGE_ROOT))
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from showcase_test_support import showcase_root # noqa: E402
+from stage5_rig.emit_rig import emit_typescript # noqa: E402
+from stage5_rig.rig_spec import BoneSpec, RigSpec # noqa: E402
+
+
+def resolve_gate() -> tuple[str, Path, Path]:
+ """Locate `node` and the showcase gate script, or skip.
+
+ The showcase checkout owns `three` and the reference rig this milestone was benchmarked
+ against; it is deliberately not vendored into forge, and this test only reads from it. Its
+ location comes from IMG2THREEJS_SHOWCASE_ROOT like every other showcase-backed test — an
+ absolute path here passes on one machine and errors out on every other one, CI included.
+ `showcase_root()` still fails closed rather than skipping when IMG2THREEJS_REQUIRE_SHOWCASE=1.
+ """
+ root = showcase_root()
+ gate = root / "scripts" / "rig-milestone0.mjs"
+ if not gate.exists():
+ raise unittest.SkipTest(f"showcase checkout has no rig gate script at {gate}")
+ node = shutil.which("node")
+ if node is None:
+ raise unittest.SkipTest("executing the emitted rig needs `node` on PATH")
+ return node, gate, root
+
+# --- Gate thresholds (Milestone 0 brief) --------------------------------
+# (a) calibration reference: the hand-authored dragon achieves 2.98e-8.
+MAX_WEIGHT_ERROR_THRESHOLD = 1e-6
+
+
+def build_three_bone_arm_spec() -> RigSpec:
+ """shoulder -> elbow -> wrist, skinning a single capsule.
+
+ Schema ambiguity readings taken here (see rig_spec.py docstrings for the
+ general rule; this is the concrete instance):
+
+ - shoulder.tipPos and elbow.tipPos are both OMITTED and default to their
+ single child's jointPos (shoulder -> elbow's jointPos, elbow -> wrist's
+ jointPos), which is the unambiguous, plan-stated case.
+ - wrist is a leaf (no children). The plan's default ("child's jointPos")
+ has nothing to default from, so wrist.tipPos is authored explicitly
+ here — a 0.4-unit "hand" extension past the wrist joint. This is the
+ spec author's job, not the emitter's (Pillar 2): the emitter REJECTS
+ any leaf skinned bone missing an explicit tipPos rather than inventing
+ one.
+ """
+ return RigSpec(
+ version="1.0",
+ bind_pose="T",
+ forward="+Z",
+ bones=[
+ BoneSpec(
+ id="shoulder",
+ parent=None,
+ joint_pos=(0.0, 0.0, 0.0),
+ component="arm",
+ role="skinned",
+ chain="arm",
+ ),
+ BoneSpec(
+ id="elbow",
+ parent="shoulder",
+ joint_pos=(0.0, -1.0, 0.0),
+ component="arm",
+ role="skinned",
+ chain="arm",
+ ),
+ BoneSpec(
+ id="wrist",
+ parent="elbow",
+ joint_pos=(0.0, -2.0, 0.0),
+ tip_pos=(0.0, -2.4, 0.0),
+ component="arm",
+ role="skinned",
+ chain="arm",
+ ),
+ ],
+ )
+
+
+# Component bounding-box extents perpendicular to the bone axis (PLAN_1.5
+# §4.3 inputs W/D). READING CHOSEN: RigSpec.bones[].component normally
+# indexes into ObjectSculptSpec.components, which does not exist in this
+# standalone milestone (there is no full sculpt spec, only a hand-written
+# RigSpec plus one hand-specified capsule mesh). Rather than inventing a
+# competing schema field, this test supplies the same (width, depth)
+# information ObjectSculptSpec.components would have carried, as a plain
+# side-channel dict keyed by component id. All three bones share the one
+# capsule component, so all three get the same derived R_b.
+COMPONENT_EXTENTS = {
+ "arm": (0.6, 0.6), # capsule diameter 0.6 (radius 0.3) in both perpendicular axes
+}
+CAPSULE_RADIUS = 0.3
+
+
+class RigMilestone0(unittest.TestCase):
+ result: dict
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ node, gate_script, showcase = resolve_gate()
+
+ spec = build_three_bone_arm_spec()
+ source = emit_typescript(spec, COMPONENT_EXTENTS, CAPSULE_RADIUS)
+
+ cls._tempdir = tempfile.mkdtemp(prefix="rig-milestone0-")
+ entry_path = Path(cls._tempdir) / "rig-milestone0-arm.ts"
+ entry_path.write_text(source, encoding="utf-8")
+ out_path = Path(cls._tempdir) / "result.json"
+ cls.entry_path = entry_path
+ cls.out_path = out_path
+
+ proc = subprocess.run(
+ [node, str(gate_script), str(entry_path), "--out", str(out_path)],
+ cwd=str(showcase),
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+ cls.proc = proc
+ if proc.returncode != 0:
+ raise RuntimeError(
+ "FAIL CLOSED: rig-milestone0.mjs exited non-zero "
+ f"(code {proc.returncode}).\nstdout: {proc.stdout}\nstderr: {proc.stderr}"
+ )
+ if not out_path.exists():
+ raise RuntimeError(
+ "FAIL CLOSED: rig-milestone0.mjs exited 0 but wrote no result file.\n"
+ f"stdout: {proc.stdout}\nstderr: {proc.stderr}"
+ )
+ try:
+ cls.result = json.loads(out_path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(
+ f"FAIL CLOSED: result file was not parseable JSON: {exc}\n"
+ f"raw contents: {out_path.read_text(encoding='utf-8')!r}"
+ ) from exc
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ shutil.rmtree(cls._tempdir, ignore_errors=True)
+
+ def test_gate_a_weight_normalization(self) -> None:
+ measured = self.result["maxWeightError"]
+ print(f"\n[gate a] maxWeightError = {measured!r} (threshold < {MAX_WEIGHT_ERROR_THRESHOLD})")
+ self.assertLess(
+ measured,
+ MAX_WEIGHT_ERROR_THRESHOLD,
+ f"gate (a) FAIL: max skin-weight error {measured} >= {MAX_WEIGHT_ERROR_THRESHOLD}",
+ )
+
+ def test_gate_b_deformation_delta(self) -> None:
+ """Predicate per team-lead decision (2026-07-30), replacing the
+ original ">0 for every influenced vertex":
+
+ A point exactly ON the elbow's rotation axis is fixed by the
+ rotation, and also fixed by every other (unrotated) bone's identity
+ transform, so a linear blend of transforms that each fix the point
+ also fixes it — displacement exactly 0 there is correct skinning,
+ not a defect. Vertices within AXIS_EPSILON of the rotation axis are
+ therefore exempt from the ">0" check, but:
+
+ - the exempt count is measured and reported (axisExemptVertexCount)
+ rather than silently absorbed;
+ - if the exemption swallows every influenced vertex, that IS a
+ FAIL (it would mean nothing off-axis was ever influenced);
+ - the structural precondition (>=1 influenced vertex at all) is
+ still enforced first, upstream, by rig-milestone0.mjs itself
+ (see setUpClass — a rig with zero influenced vertices exits
+ non-zero before this test ever runs).
+
+ The rank correlation between displacement and axis distance is
+ logged for visibility but NOT gated — no calibrated threshold for
+ "strongly positive" exists yet (same rule the colour-signal gates
+ use).
+ """
+ influenced = self.result["influencedVertexCount"]
+ exempt = self.result["axisExemptVertexCount"]
+ epsilon = self.result["axisEpsilon"]
+ min_delta = self.result["minInfluencedDeformationDelta"]
+ zero_count = self.result["zeroDeltaVertexCount"]
+ correlation = self.result["displacementVsAxisDistanceSpearman"]
+ print(
+ f"\n[gate b] influencedVertexCount={influenced}, axisExemptVertexCount={exempt} "
+ f"(epsilon={epsilon}), minInfluencedDeformationDelta={min_delta!r}, "
+ f"zeroDeltaVertexCount={zero_count}, "
+ f"displacementVsAxisDistanceSpearman={correlation!r} (report-only, not gated)"
+ )
+ self.assertGreater(influenced, 0, "gate (b) FAIL: elbow has no influenced vertices to sweep")
+ self.assertLess(
+ exempt,
+ influenced,
+ f"gate (b) FAIL: all {influenced} influenced vertices are axis-exempt "
+ "(within epsilon of the rotation axis) — nothing off-axis was ever "
+ "influenced, so this pose-sweep tested nothing",
+ )
+ self.assertIsNotNone(
+ min_delta,
+ "gate (b) FAIL: no non-exempt influenced vertex to measure a deformation delta from",
+ )
+ self.assertGreater(
+ min_delta,
+ 0.0,
+ f"gate (b) FAIL: {zero_count} non-axis-exempt influenced vertex/vertices did not move "
+ "when the elbow rotated 0deg->90deg (bone rotates but mesh stays still)",
+ )
+
+ def test_gate_c_envelope_containment(self) -> None:
+ violations = self.result["envelopeViolations"]
+ checked = self.result["envelopeChecked"]
+ fallback = self.result["fallbackVertexCount"]
+ print(
+ f"\n[gate c] envelopeViolations={violations}/{checked} checked "
+ f"(fallbackVertexCount={fallback} excluded from this check)"
+ )
+ self.assertEqual(
+ violations,
+ 0,
+ f"gate (c) FAIL: {violations} (vertex, bone) pairs exceeded the derived "
+ "envelope radius R_b",
+ )
+
+ def test_gate_d_boundary_edges(self) -> None:
+ boundary = self.result["boundaryEdges"]
+ non_manifold = self.result["nonManifoldEdges"]
+ print(f"\n[gate d] boundaryEdges={boundary}, nonManifoldEdges={non_manifold}")
+ self.assertEqual(boundary, 0, f"gate (d) FAIL: {boundary} boundary edges after bind")
+ self.assertEqual(non_manifold, 0, f"gate (d) FAIL: {non_manifold} non-manifold edges after bind")
+
+
+class AxisExemptionSelfCheck(unittest.TestCase):
+ """Closes a coverage gap team-lead identified (2026-07-30): the derived
+ 3-bone-arm capsule always measures axisExemptVertexCount == 0, so the
+ exemption branch in gate (b) has never actually fired on that path. That
+ proves the counter reads zero when nothing qualifies; it does not prove
+ an on-axis vertex is correctly classified when one exists.
+
+ `node scripts/rig-milestone0.mjs --self-check` runs four hand-placed
+ synthetic cases (on the rotation axis; on the axis but offset along it;
+ 5e-7 from it; 2e-6 from it) through the SAME perpendicularDistanceFromAxis()
+ gate (b) uses (see scripts/rig-milestone0-axis.mjs) — not a
+ reimplementation, so a broken real predicate cannot pass by comparing
+ against a second broken copy of itself. This test asserts the
+ classifications from that JSON, plus an analytic cross-check of the
+ off-axis displacements against the closed-form 90-degree chord length
+ (distance * sqrt(2)) rather than against a recorded constant, so a wrong
+ implementation cannot pass by matching a number this test previously
+ happened to observe.
+
+ Deliberately does NOT touch RING_RESOLUTION_DIVISOR, N, or any capsule
+ geometry -- per team-lead's instruction, this is a synthetic case built
+ for exactly this purpose, not a perturbation of the derived tessellation.
+
+ NOTE (2026-07-30): the 'on-axis-offset-along-axis' case and the
+ analytic cross-check were folded in from a standalone
+ scripts/rig-milestone0-axis-exemption.test.mjs, which team-lead found
+ was never wired into any npm script or CI path (package.json's
+ test:review-apparatus lists explicit files, not a glob) -- so it always
+ passed by hand and never ran otherwise. That file has been deleted;
+ this class is now the one canonical, wired path for this coverage.
+ """
+
+ result: dict
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ node, gate_script, showcase = resolve_gate()
+
+ cls._tempdir = tempfile.mkdtemp(prefix="rig-milestone0-selfcheck-")
+ out_path = Path(cls._tempdir) / "self-check.json"
+ cls.out_path = out_path
+
+ proc = subprocess.run(
+ [node, str(gate_script), "--self-check", "--out", str(out_path)],
+ cwd=str(showcase),
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ cls.proc = proc
+ if proc.returncode != 0:
+ raise RuntimeError(
+ "FAIL CLOSED: rig-milestone0.mjs --self-check exited non-zero "
+ f"(code {proc.returncode}).\nstdout: {proc.stdout}\nstderr: {proc.stderr}"
+ )
+ if not out_path.exists():
+ raise RuntimeError(
+ "FAIL CLOSED: --self-check exited 0 but wrote no result file.\n"
+ f"stdout: {proc.stdout}\nstderr: {proc.stderr}"
+ )
+ try:
+ cls.result = json.loads(out_path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(
+ f"FAIL CLOSED: self-check result was not parseable JSON: {exc}\n"
+ f"raw contents: {out_path.read_text(encoding='utf-8')!r}"
+ ) from exc
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ shutil.rmtree(cls._tempdir, ignore_errors=True)
+
+ def _case(self, label: str) -> dict:
+ matches = [c for c in self.result["cases"] if c["label"] == label]
+ self.assertEqual(len(matches), 1, f"expected exactly one '{label}' case, found {len(matches)}")
+ return matches[0]
+
+ def test_on_axis_vertex_is_exempt_with_zero_displacement(self) -> None:
+ case = self._case("on-axis")
+ print(f"\n[self-check] on-axis: {case!r}")
+ self.assertLessEqual(case["distanceFromAxis"], self.result["axisEpsilon"])
+ self.assertTrue(case["exempt"], "a vertex exactly on the rotation axis must be exempt")
+ self.assertEqual(case["displacement"], 0, "a vertex exactly on the rotation axis must not move")
+
+ def test_on_axis_offset_along_axis_is_exempt(self) -> None:
+ """The strongest case: a vertex on the axis LINE but 0.5 away from
+ the pivot POINT. Distinguishes a correct implementation (measuring
+ perpendicular distance from the axis, which stays 0 anywhere along
+ it) from the plausible wrong one (measuring distance from the pivot
+ point, which would wrongly flag this vertex as off-axis)."""
+ case = self._case("on-axis-offset-along-axis")
+ print(f"\n[self-check] on-axis-offset-along-axis: {case!r}")
+ self.assertLessEqual(
+ case["distanceFromAxis"],
+ self.result["axisEpsilon"],
+ "a vertex 0.5 units along the axis from the pivot is still ON the axis "
+ "line and must be exempt -- if this fails, the implementation is measuring "
+ "distance from the pivot POINT rather than the axis LINE",
+ )
+ self.assertTrue(case["exempt"])
+ self.assertEqual(case["displacement"], 0, "a vertex on the rotation axis must not move, regardless of where along it")
+
+ def test_vertex_inside_epsilon_is_exempt(self) -> None:
+ case = self._case("inside-epsilon")
+ print(f"\n[self-check] inside-epsilon (5e-7): {case!r}")
+ self.assertLessEqual(case["distanceFromAxis"], self.result["axisEpsilon"])
+ self.assertTrue(case["exempt"], "a vertex 5e-7 from the axis (inside epsilon=1e-6) must be exempt")
+ self._assert_matches_analytic_chord_length(case)
+
+ def test_vertex_outside_epsilon_is_not_exempt_and_moves(self) -> None:
+ case = self._case("outside-epsilon")
+ print(f"\n[self-check] outside-epsilon (2e-6): {case!r}")
+ self.assertGreater(case["distanceFromAxis"], self.result["axisEpsilon"])
+ self.assertFalse(case["exempt"], "a vertex 2e-6 from the axis (outside epsilon=1e-6) must NOT be exempt")
+ self.assertGreater(
+ case["displacement"],
+ 0.0,
+ "a non-exempt vertex must actually deform under the pose sweep",
+ )
+ self._assert_matches_analytic_chord_length(case)
+
+ def _assert_matches_analytic_chord_length(self, case: dict) -> None:
+ """Cross-check against the closed form for a 90-degree rotation about
+ an axis at perpendicular distance d: chord length = d * sqrt(2).
+ Deliberately NOT compared against a previously-recorded constant --
+ that would only prove the code hasn't changed, not that it was right
+ to begin with."""
+ expected = case["distanceFromAxis"] * math.sqrt(2)
+ self.assertAlmostEqual(
+ case["displacement"],
+ expected,
+ delta=1e-9,
+ msg=f"displacement {case['displacement']} should match the analytic 90-degree "
+ f"chord length {expected} for distanceFromAxis={case['distanceFromAxis']}",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_sdf_primitives.py b/forge/tests/test_sdf_primitives.py
new file mode 100644
index 0000000..5b10eca
--- /dev/null
+++ b/forge/tests/test_sdf_primitives.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+"""Red contracts for implicit SDF descriptors and generated polygonizers."""
+
+from __future__ import annotations
+
+import json
+import math
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+FIXTURE = ROOT / "tests" / "fixtures" / "implicit_character_torso_limb.json"
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate
+ from validate_sculpt_spec import VALID_PRIMITIVES, validate_spec
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return generate, VALID_PRIMITIVES, validate_spec
+
+
+generate, VALID_PRIMITIVES, validate_spec = import_forge_modules()
+
+
+def load_fixture() -> dict:
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+class SdfPrimitiveContractTest(unittest.TestCase):
+ def test_accepts_implicit_topology_with_maximum_sdf_resolution(self) -> None:
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["geometryDescriptor"]["sdf"]["resolution"] = 64
+ errors, warnings = validate_spec(spec)
+
+ self.assertEqual(component["primitive"], "capsule")
+ self.assertIn(component["primitive"], VALID_PRIMITIVES)
+ self.assertEqual(component["topologyClass"], "implicit")
+ self.assertEqual(errors, [])
+ self.assertFalse(
+ any("topologyClass" in warning for warning in warnings),
+ warnings,
+ )
+
+ def test_rejects_invalid_sdf_primitive_operation_resolution_and_nonfinite_values(self) -> None:
+ cases = (
+ (
+ "primitive",
+ ("primitives", 0, "type"),
+ "not-a-primitive",
+ "geometryDescriptor.sdf.primitives[0].type",
+ "must be one of",
+ ),
+ (
+ "operation",
+ ("operations", 0, "type"),
+ "xor",
+ "geometryDescriptor.sdf.operations[0].type",
+ "must be one of",
+ ),
+ (
+ "resolution",
+ ("resolution",),
+ 65,
+ "geometryDescriptor.sdf.resolution",
+ "must not exceed 64",
+ ),
+ (
+ "nonfinite radius",
+ ("primitives", 0, "radius"),
+ math.inf,
+ "geometryDescriptor.sdf.primitives[0].radius",
+ "must be finite",
+ ),
+ )
+ for label, path, value, field_path, reason in cases:
+ with self.subTest(label=label):
+ spec = load_fixture()
+ sdf = spec["componentTree"][0]["geometryDescriptor"]["sdf"]
+ target = sdf
+ for key in path[:-1]:
+ target = target[key]
+ target[path[-1]] = value
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(field_path in error and reason in error for error in errors),
+ errors,
+ )
+
+ def test_rejects_unsupported_sdf_transform_fields(self) -> None:
+ spec = load_fixture()
+ primitive = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["primitives"][0]
+ primitive["transform"] = {"center": [0.0, 0.0, 0.0]}
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.sdf.primitives[0].transform.center" in error
+ and "is not supported" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_rejects_unsupported_sdf_primitive_fields(self) -> None:
+ spec = load_fixture()
+ primitive = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["primitives"][0]
+ primitive["position"] = [0.0, 0.0, 0.0]
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.sdf.primitives[0].position" in error
+ and "is not supported" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_rejects_sdf_operation_output_id_collisions(self) -> None:
+ cases = (
+ ("primitive", {"id": "torso"}),
+ ("prior operation", {"id": "blend"}),
+ )
+ for label, output in cases:
+ with self.subTest(label=label):
+ spec = load_fixture()
+ operations = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["operations"]
+ operations[0].update(output)
+ if label == "prior operation":
+ operations.append({"type": "intersect", "left": "blend", "right": "torso", "id": "blend"})
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any("geometryDescriptor.sdf.operations" in error and "duplicates" in error for error in errors),
+ errors,
+ )
+
+ def test_rejects_unsupported_sdf_operation_fields(self) -> None:
+ spec = load_fixture()
+ operation = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["operations"][0]
+ operation["blendWidth"] = 0.2
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.sdf.operations[0].blendWidth" in error
+ and "is not supported" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_rejects_conflicting_sdf_operation_id_and_output(self) -> None:
+ spec = load_fixture()
+ operation = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["operations"][0]
+ operation.update({"id": "blend", "output": "alternate-blend"})
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.sdf.operations[0].id" in error and "cannot both be set" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_rejects_collapsed_or_reversed_sdf_bounds(self) -> None:
+ cases = (
+ ("collapsed", [0.0, -1.0, -1.0], [0.0, 1.0, 1.0]),
+ ("reversed", [1.0, -1.0, -1.0], [0.0, 1.0, 1.0]),
+ )
+ for label, minimum, maximum in cases:
+ with self.subTest(label=label):
+ spec = load_fixture()
+ sdf = spec["componentTree"][0]["geometryDescriptor"]["sdf"]
+ sdf["bounds"] = {"min": minimum, "max": maximum}
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.sdf.bounds.min[0]" in error and "less than" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_rejects_sdf_descriptor_cardinality_over_limits(self) -> None:
+ cases = (("primitives", 33, 64), ("operations", 129, 128))
+ for field, multiplier, limit in cases:
+ with self.subTest(field=field):
+ spec = load_fixture()
+ sdf = spec["componentTree"][0]["geometryDescriptor"]["sdf"]
+ sdf[field] *= multiplier
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ f"geometryDescriptor.sdf.{field}" in error
+ and f"must not contain more than {limit}" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_generates_sdf_and_polygonizer_markers(self) -> None:
+ spec = load_fixture()
+ sdf = spec["componentTree"][0]["geometryDescriptor"]["sdf"]
+ generated = generate(spec, "blockout")
+
+ self.assertIn("function sdfCapsule", generated)
+ self.assertIn("function smin", generated)
+ self.assertIn("function polygonizeSdf", generated)
+ polygonizer_start = generated.index("function polygonizeSdf")
+ polygonizer_end = generated.index("return geometry;", polygonizer_start)
+ self.assertIn("computeVertexNormals()", generated[polygonizer_start:polygonizer_end])
+ for marker in (
+ '"type": "capsule"',
+ '"type": "smooth-union"',
+ '"resolution": 32',
+ '"radius": 0.16',
+ '"height": 1.1',
+ ):
+ self.assertIn(marker, generated)
+ self.assertIn(f"polygonizeSdf({json.dumps(sdf)})", generated)
+
+ def test_generates_inverse_quaternion_for_multi_axis_sdf_rotation(self) -> None:
+ spec = load_fixture()
+ primitive = spec["componentTree"][0]["geometryDescriptor"]["sdf"]["primitives"][0]
+ primitive["transform"] = {"rotation": [0.37, -0.61, 1.13]}
+
+ generated = generate(spec, "blockout")
+
+ self.assertIn("setFromEuler", generated)
+ self.assertIn(".invert()", generated)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_self_intersection.py b/forge/tests/test_self_intersection.py
new file mode 100644
index 0000000..c213f0e
--- /dev/null
+++ b/forge/tests/test_self_intersection.py
@@ -0,0 +1,438 @@
+#!/usr/bin/env python3
+"""Tests for the self-intersection gate, each proven by breaking an input on purpose.
+
+The centrepiece is `test_topology_gate_passes_the_mesh_this_gate_rejects`: it takes one mutated
+mesh and asserts BOTH that the new gate flags it AND that `geometry_integrity.mesh_edge_counts`
+still reports it as perfectly closed. That pairing is the whole argument for this module existing.
+Everything else here is scaffolding around it.
+
+The fixtures are built procedurally -- an icosphere by recursive subdivision, with midpoints welded
+through a cache so the result is a genuinely closed 2-manifold rather than a pile of loose
+triangles. Nothing is loaded from disk, so the fixtures cannot silently drift.
+
+Pure Python 3.10+ stdlib. No pip installs.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from geometry_integrity import mesh_edge_counts # noqa: E402
+from self_intersection import ( # noqa: E402
+ MAX_SAMPLED_VERTICES,
+ RAY_DIRECTIONS,
+ _DirectionGrid,
+ analyze_mesh,
+ analyze_meshes,
+ main,
+)
+
+
+def icosphere(subdivisions: int = 2) -> tuple[list[list[float]], list[int]]:
+ """A closed unit icosphere: subdivided icosahedron, midpoints welded via a cache."""
+ phi = (1.0 + 5.0 ** 0.5) / 2.0
+ raw = [
+ (-1, phi, 0), (1, phi, 0), (-1, -phi, 0), (1, -phi, 0),
+ (0, -1, phi), (0, 1, phi), (0, -1, -phi), (0, 1, -phi),
+ (phi, 0, -1), (phi, 0, 1), (-phi, 0, -1), (-phi, 0, 1),
+ ]
+ vertices: list[list[float]] = []
+ for point in raw:
+ length = sum(value * value for value in point) ** 0.5
+ vertices.append([value / length for value in point])
+ faces = [
+ (0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11),
+ (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6), (7, 1, 8),
+ (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9),
+ (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1),
+ ]
+ cache: dict[tuple[int, int], int] = {}
+
+ def midpoint(a: int, b: int) -> int:
+ key = (min(a, b), max(a, b))
+ if key not in cache:
+ point = [(vertices[a][axis] + vertices[b][axis]) / 2.0 for axis in range(3)]
+ length = sum(value * value for value in point) ** 0.5
+ cache[key] = len(vertices)
+ vertices.append([value / length for value in point])
+ return cache[key]
+
+ for _ in range(subdivisions):
+ next_faces: list[tuple[int, int, int]] = []
+ for a, b, c in faces:
+ ab, bc, ca = midpoint(a, b), midpoint(b, c), midpoint(c, a)
+ next_faces += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
+ faces = next_faces
+
+ indices: list[int] = []
+ for face in faces:
+ indices += list(face)
+ return vertices, indices
+
+
+def punch_through(
+ vertices: list[list[float]],
+ cap_height: float = 0.7,
+ push: float = 2.6,
+) -> list[list[float]]:
+ """The production defect, reproduced: push a polar cap inward past the far surface.
+
+ On a unit sphere the outward normal is the position itself, so pushing a cap along -normal by
+ 2.6 -- more than the sphere's diameter of 2 -- sends it through the centre and out the opposite
+ side. The result is a funnel of stretched triangles running clean through the volume, exactly
+ like an eye socket recessed deeper than the skull is thick. No index is touched, so the mesh's
+ connectivity, and therefore its topology, is untouched too.
+ """
+ moved: list[list[float]] = []
+ for vertex in vertices:
+ if vertex[2] >= cap_height:
+ moved.append([value - value * push for value in vertex])
+ else:
+ moved.append(list(vertex))
+ return moved
+
+
+class CleanMesh(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(2)
+
+ def test_closed_convex_mesh_is_clean(self) -> None:
+ result = analyze_mesh({"name": "icosphere", "vertices": self.vertices, "indices": self.indices})
+ self.assertTrue(result["analyzed"], result["error"])
+ self.assertFalse(result["selfIntersecting"])
+ self.assertEqual(result["insideVertexCount"], 0)
+ self.assertEqual(result["worstRegions"], [])
+ # Undecided samples are a fact about the ray casts, not a hiding place: on a clean convex
+ # sphere they must be a rounding error, not a way to reach a clean verdict by abstention.
+ self.assertLess(result["undecidedVertexCount"], result["sampledVertexCount"] // 20)
+ self.assertEqual(
+ result["outsideVertexCount"] + result["insideVertexCount"] + result["undecidedVertexCount"],
+ result["sampledVertexCount"],
+ )
+
+ def test_supplied_normals_are_used_and_reported(self) -> None:
+ # On a unit sphere the vertex normal is the position, so this is the exact normal set.
+ result = analyze_mesh({
+ "vertices": self.vertices,
+ "indices": self.indices,
+ "normals": [list(vertex) for vertex in self.vertices],
+ })
+ self.assertEqual(result["normalSource"], "vertexNormals")
+ self.assertEqual(result["normalFallbackCount"], 0)
+ self.assertFalse(result["selfIntersecting"])
+
+ def test_centroid_fallback_is_reported_when_normals_absent(self) -> None:
+ result = analyze_mesh({"vertices": self.vertices, "indices": self.indices})
+ self.assertEqual(result["normalSource"], "centroid")
+
+ def test_wrong_length_normals_fall_back_rather_than_trusting_them(self) -> None:
+ result = analyze_mesh({
+ "vertices": self.vertices,
+ "indices": self.indices,
+ "normals": [[0.0, 0.0, 1.0]],
+ })
+ self.assertEqual(result["normalSource"], "centroid")
+ self.assertFalse(result["selfIntersecting"])
+
+ def test_epsilon_scales_with_the_model(self) -> None:
+ big = [[value * 1000.0 for value in vertex] for vertex in self.vertices]
+ small = analyze_mesh({"vertices": self.vertices, "indices": self.indices})
+ large = analyze_mesh({"vertices": big, "indices": self.indices})
+ self.assertAlmostEqual(large["epsilon"] / small["epsilon"], 1000.0, places=6)
+ # The verdict is the point: an absolute epsilon would be wrong at one of these two scales.
+ self.assertFalse(small["selfIntersecting"])
+ self.assertFalse(large["selfIntersecting"])
+ self.assertEqual(large["insideVertexCount"], 0)
+
+
+class SelfIntersectionRegression(unittest.TestCase):
+ """The defect that got through every existing gate."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(2)
+ cls.broken = punch_through(cls.vertices)
+
+ def test_surface_pushed_through_the_far_side_is_caught(self) -> None:
+ result = analyze_mesh({"name": "punched", "vertices": self.broken, "indices": self.indices})
+ self.assertTrue(result["analyzed"], result["error"])
+ self.assertTrue(result["selfIntersecting"])
+ self.assertGreater(result["insideVertexCount"], 0)
+ self.assertTrue(result["worstRegions"])
+ for region in result["worstRegions"]:
+ self.assertEqual(len(region["position"]), 3)
+ self.assertIn("vertexIndex", region)
+
+ def test_topology_gate_passes_the_mesh_this_gate_rejects(self) -> None:
+ """The single load-bearing test: same mesh, old gate clean, new gate rejects.
+
+ Pushing vertices around changes no connectivity, so `mesh_edge_counts` reads the mutated
+ mesh as watertight and manifold -- 0 boundary edges, 0 non-manifold edges -- while the
+ surface is running straight through its own volume. This is why counting edges cannot
+ substitute for measuring geometry.
+ """
+ topology = mesh_edge_counts(self.broken, self.indices)
+ self.assertEqual(topology["boundaryEdges"], 0)
+ self.assertEqual(topology["nonManifoldEdges"], 0)
+
+ clean_topology = mesh_edge_counts(self.vertices, self.indices)
+ self.assertEqual(clean_topology["boundaryEdges"], 0)
+ self.assertEqual(clean_topology["nonManifoldEdges"], 0)
+ # Identical topology readings, opposite verdicts from this module.
+ self.assertEqual(topology["edgeCount"], clean_topology["edgeCount"])
+
+ self.assertFalse(
+ analyze_mesh({"vertices": self.vertices, "indices": self.indices})["selfIntersecting"]
+ )
+ self.assertTrue(
+ analyze_mesh({"vertices": self.broken, "indices": self.indices})["selfIntersecting"]
+ )
+
+ def test_aggregate_reports_the_offending_mesh(self) -> None:
+ result = analyze_meshes([
+ {"name": "clean", "vertices": self.vertices, "indices": self.indices},
+ {"name": "punched", "vertices": self.broken, "indices": self.indices},
+ ])
+ self.assertTrue(result["selfIntersecting"])
+ self.assertEqual(result["meshCount"], 2)
+ self.assertEqual(result["errors"], [])
+ by_name = {report["name"]: report for report in result["meshes"]}
+ self.assertFalse(by_name["clean"]["selfIntersecting"])
+ self.assertTrue(by_name["punched"]["selfIntersecting"])
+
+
+class ParityIsReal(unittest.TestCase):
+ """A parity test that never counts a crossing agrees with every clean mesh, for the wrong reason.
+
+ These two check the machinery itself rather than a verdict: that the ray really does count
+ crossings, and that the broad-phase grid really does hand it the triangles to count.
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(3)
+
+ def test_inverted_normals_put_every_sample_inside(self) -> None:
+ # Flipping the supplied normals steps each sample INWARD instead of outward, so the point
+ # under test is genuinely inside the sphere. Everything must read inside. If crossings were
+ # being missed, this would come back clean and expose the whole gate as vacuous.
+ result = analyze_mesh({
+ "vertices": self.vertices,
+ "indices": self.indices,
+ "normals": [[-value for value in vertex] for vertex in self.vertices],
+ })
+ self.assertTrue(result["selfIntersecting"])
+ self.assertGreater(result["insideVertexCount"], result["sampledVertexCount"] * 0.95)
+
+ def test_every_vertex_gets_broad_phase_candidates(self) -> None:
+ # Regression: the query used to bail out when a point projected one cell past the grid's
+ # end, which is exactly where the vertex defining the projection's maximum lands. It
+ # returned no candidates, so no crossings, so a confident "outside" for the samples at the
+ # silhouette's extremes.
+ triangles = [tuple(self.indices[i:i + 3]) for i in range(0, len(self.indices), 3)]
+ for direction in RAY_DIRECTIONS:
+ grid = _DirectionGrid(direction, [tuple(v) for v in self.vertices], triangles)
+ for vertex in self.vertices:
+ self.assertTrue(
+ grid.candidates(tuple(vertex)),
+ f"no candidate triangles for {vertex} along {direction}",
+ )
+
+
+class IndexEncodings(unittest.TestCase):
+ def test_flat_and_grouped_indices_agree(self) -> None:
+ vertices, flat = icosphere(2)
+ grouped = [flat[i:i + 3] for i in range(0, len(flat), 3)]
+ first = analyze_mesh({"vertices": vertices, "indices": flat})
+ second = analyze_mesh({"vertices": vertices, "indices": grouped})
+ self.assertEqual(first["triangleCount"], second["triangleCount"])
+ self.assertEqual(first["insideVertexCount"], second["insideVertexCount"])
+ self.assertEqual(first["undecidedVertexCount"], second["undecidedVertexCount"])
+ self.assertFalse(first["selfIntersecting"])
+
+ def test_both_encodings_catch_the_defect(self) -> None:
+ vertices, flat = icosphere(2)
+ broken = punch_through(vertices)
+ grouped = [flat[i:i + 3] for i in range(0, len(flat), 3)]
+ self.assertTrue(analyze_mesh({"vertices": broken, "indices": flat})["selfIntersecting"])
+ self.assertTrue(analyze_mesh({"vertices": broken, "indices": grouped})["selfIntersecting"])
+
+
+class SamplingHonesty(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(2)
+
+ def test_full_coverage_is_reported_as_stride_one(self) -> None:
+ result = analyze_mesh({"vertices": self.vertices, "indices": self.indices})
+ self.assertLess(len(self.vertices), MAX_SAMPLED_VERTICES)
+ self.assertEqual(result["samplingStride"], 1)
+ self.assertEqual(result["sampledVertexCount"], len(self.vertices))
+ self.assertEqual(result["totalVertexCount"], len(self.vertices))
+
+ def test_budget_exceeded_reports_a_real_stride(self) -> None:
+ budget = 50
+ result = analyze_mesh({"vertices": self.vertices, "indices": self.indices}, max_samples=budget)
+ self.assertGreater(len(self.vertices), budget)
+ self.assertGreater(result["samplingStride"], 1)
+ self.assertLessEqual(result["sampledVertexCount"], budget)
+ self.assertEqual(result["totalVertexCount"], len(self.vertices))
+ # The claim that matters: the result never pretends the whole mesh was inspected.
+ self.assertLess(result["sampledVertexCount"], result["totalVertexCount"])
+
+ def test_sampling_is_deterministic(self) -> None:
+ mesh = {"vertices": self.vertices, "indices": self.indices}
+ first = analyze_mesh(mesh, max_samples=137)
+ second = analyze_mesh(mesh, max_samples=137)
+ self.assertEqual(first["sampledVertexCount"], second["sampledVertexCount"])
+ self.assertEqual(first["insideVertexCount"], second["insideVertexCount"])
+ self.assertEqual(first["worstRegions"], second["worstRegions"])
+
+
+class DegenerateInput(unittest.TestCase):
+ def _expect_error(self, mesh: dict) -> dict:
+ result = analyze_mesh(mesh)
+ self.assertFalse(result["analyzed"])
+ self.assertTrue(result["error"])
+ self.assertFalse(result["selfIntersecting"])
+ return result
+
+ def test_empty_vertices(self) -> None:
+ self._expect_error({"vertices": [], "indices": [0, 1, 2]})
+
+ def test_missing_vertices(self) -> None:
+ self._expect_error({"indices": [0, 1, 2]})
+
+ def test_empty_indices(self) -> None:
+ vertices, _ = icosphere(0)
+ self._expect_error({"vertices": vertices, "indices": []})
+
+ def test_missing_indices(self) -> None:
+ vertices, _ = icosphere(0)
+ self._expect_error({"vertices": vertices})
+
+ def test_index_count_not_a_multiple_of_three(self) -> None:
+ vertices, indices = icosphere(0)
+ result = self._expect_error({"vertices": vertices, "indices": indices[:-1]})
+ self.assertIn("multiple of three", result["error"])
+
+ def test_grouped_indices_with_a_short_group(self) -> None:
+ vertices, indices = icosphere(0)
+ grouped = [indices[i:i + 3] for i in range(0, len(indices), 3)]
+ grouped[4] = grouped[4][:2]
+ self._expect_error({"vertices": vertices, "indices": grouped})
+
+ def test_index_out_of_range(self) -> None:
+ vertices, indices = icosphere(0)
+ broken = list(indices)
+ broken[0] = len(vertices) + 5
+ result = self._expect_error({"vertices": vertices, "indices": broken})
+ self.assertIn("out of range", result["error"])
+
+ def test_two_dimensional_vertex(self) -> None:
+ vertices, indices = icosphere(0)
+ vertices[0] = [0.0, 1.0]
+ self._expect_error({"vertices": vertices, "indices": indices})
+
+ def test_zero_extent_mesh(self) -> None:
+ result = self._expect_error({"vertices": [[0.0, 0.0, 0.0]] * 3, "indices": [0, 1, 2]})
+ self.assertIn("extent", result["error"])
+
+ def test_non_dict_mesh_entry_does_not_abort_the_batch(self) -> None:
+ vertices, indices = icosphere(1)
+ result = analyze_meshes(["not a mesh", {"name": "real", "vertices": vertices, "indices": indices}])
+ self.assertEqual(len(result["errors"]), 1)
+ self.assertEqual(result["meshCount"], 2)
+ self.assertTrue(result["meshes"][1]["analyzed"])
+
+
+class CommandLine(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.tmp = Path(tempfile.mkdtemp())
+ cls.vertices, cls.indices = icosphere(2)
+
+ def _write(self, name: str, payload) -> Path:
+ path = self.tmp / name
+ path.write_text(json.dumps(payload))
+ return path
+
+ def _run(self, argv: list[str]) -> tuple[int, str]:
+ stream = io.StringIO()
+ with contextlib.redirect_stdout(stream), contextlib.redirect_stderr(io.StringIO()):
+ code = main(argv)
+ return code, stream.getvalue()
+
+ def test_clean_mesh_exits_zero(self) -> None:
+ path = self._write("clean.json", {"meshes": [{"name": "clean", "vertices": self.vertices, "indices": self.indices}]})
+ code, output = self._run([str(path)])
+ self.assertEqual(code, 0)
+ self.assertIn("no self-intersection", output)
+
+ def test_self_intersecting_mesh_exits_one(self) -> None:
+ broken = punch_through(self.vertices)
+ path = self._write("broken.json", [{"name": "punched", "vertices": broken, "indices": self.indices}])
+ code, output = self._run([str(path)])
+ self.assertEqual(code, 1)
+ self.assertIn("SELF-INTERSECTION DETECTED", output)
+
+ def test_json_flag_emits_parseable_output(self) -> None:
+ path = self._write("single.json", {"name": "solo", "vertices": self.vertices, "indices": self.indices})
+ code, output = self._run([str(path), "--json"])
+ self.assertEqual(code, 0)
+ parsed = json.loads(output)
+ self.assertEqual(parsed["meshCount"], 1)
+ self.assertEqual(parsed["meshes"][0]["name"], "solo")
+ self.assertEqual(parsed["meshes"][0]["samplingStride"], 1)
+
+ def test_bad_mesh_exits_two(self) -> None:
+ path = self._write("bad.json", {"meshes": [{"name": "bad", "vertices": [], "indices": []}]})
+ code, _ = self._run([str(path)])
+ self.assertEqual(code, 2)
+
+ def test_missing_file_exits_two(self) -> None:
+ code, _ = self._run([str(self.tmp / "nope.json")])
+ self.assertEqual(code, 2)
+
+ def test_unusable_payload_exits_two(self) -> None:
+ path = self._write("scalar.json", 17)
+ code, _ = self._run([str(path)])
+ self.assertEqual(code, 2)
+
+ def test_max_samples_flag_is_honoured(self) -> None:
+ path = self._write("budget.json", {"name": "solo", "vertices": self.vertices, "indices": self.indices})
+ code, output = self._run([str(path), "--json", "--max-samples", "40"])
+ self.assertEqual(code, 0)
+ parsed = json.loads(output)
+ self.assertGreater(parsed["meshes"][0]["samplingStride"], 1)
+ self.assertLessEqual(parsed["meshes"][0]["sampledVertexCount"], 40)
+
+
+class Performance(unittest.TestCase):
+ def test_five_thousand_triangle_mesh_is_usable(self) -> None:
+ vertices, indices = icosphere(4) # 5120 triangles, 2562 vertices
+ self.assertEqual(len(indices) // 3, 5120)
+ started = time.perf_counter()
+ result = analyze_mesh({"vertices": vertices, "indices": indices})
+ elapsed = time.perf_counter() - started
+ self.assertFalse(result["selfIntersecting"])
+ self.assertEqual(result["sampledVertexCount"], 2562)
+ print(f"\n analyze_mesh: {len(indices) // 3} triangles, "
+ f"{result['sampledVertexCount']} samples in {elapsed:.2f}s")
+ # A gate nobody will wait for is a gate nobody will run.
+ self.assertLess(elapsed, 60.0)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_showcase_tsc_smoke.py b/forge/tests/test_showcase_tsc_smoke.py
new file mode 100644
index 0000000..dff8600
--- /dev/null
+++ b/forge/tests/test_showcase_tsc_smoke.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""Cleanup-safe showcase TypeScript smoke coverage for primitive-only factories."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+SKILL_ROOT = Path(__file__).resolve().parents[2]
+IMPLICIT_FIXTURE = SKILL_ROOT / "forge" / "tests" / "fixtures" / "implicit_character_torso_limb.json"
+VISUAL_HULL_FIXTURE = SKILL_ROOT / "forge" / "tests" / "fixtures" / "visual_hull_two_views.json"
+
+
+def run(script: str, *args: object) -> subprocess.CompletedProcess[str]:
+ command = [sys.executable, str(SKILL_ROOT / "forge" / script), *map(str, args)]
+ if script == "stage3_build/generate_threejs_factory.py" and "--pass-id" not in args:
+ command.append("--allow-nonstrict")
+ return subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ )
+
+
+class ShowcaseTscSmokeTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.showcase_root = showcase_root()
+ self.showcase_source = self.showcase_root / "src" / "__geometry_engine_smoke__.ts"
+ self.showcase_failure_source = self.showcase_root / "src" / "__geometry_engine_smoke_failure__.ts"
+
+ def _generate_primitive_only_factory(self, out: Path) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ spec_path = Path(directory) / "oak.json"
+ spec_result = run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", spec_path)
+ self.assertEqual(spec_result.returncode, 0, spec_result.stderr)
+
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ self.assertEqual(spec["componentTree"][0]["primitive"], "box")
+
+ generate_result = run("stage3_build/generate_threejs_factory.py", spec_path, "--out", out)
+ self.assertEqual(generate_result.returncode, 0, generate_result.stderr)
+
+ def _run_tsc(self) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["npx", "tsc", "--noEmit"],
+ cwd=self.showcase_root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ def test_showcase_smoke_source_is_removed_after_tsc_success_and_failure(self) -> None:
+ for should_fail in (False, True):
+ with self.subTest(compiler_failure=should_fail):
+ self.assertFalse(self.showcase_source.exists())
+ self.assertFalse(self.showcase_failure_source.exists())
+ try:
+ self._generate_primitive_only_factory(self.showcase_source)
+ self.assertTrue(self.showcase_source.exists())
+
+ if should_fail:
+ self.showcase_failure_source.write_text(
+ "export const broken: string = 1;\n",
+ encoding="utf-8",
+ )
+
+ tsc_result = self._run_tsc()
+ if should_fail:
+ self.assertNotEqual(tsc_result.returncode, 0, tsc_result.stderr)
+ else:
+ self.assertEqual(tsc_result.returncode, 0, tsc_result.stderr)
+ finally:
+ if self.showcase_source.exists():
+ self.showcase_source.unlink()
+ if self.showcase_failure_source.exists():
+ self.showcase_failure_source.unlink()
+
+ self.assertFalse(self.showcase_source.exists())
+ self.assertFalse(self.showcase_failure_source.exists())
+
+ def test_implicit_sdf_factory_typechecks_and_is_removed(self) -> None:
+ self.assertFalse(self.showcase_source.exists())
+ try:
+ generate_result = run("stage3_build/generate_threejs_factory.py", IMPLICIT_FIXTURE, "--out", self.showcase_source)
+ self.assertEqual(generate_result.returncode, 0, generate_result.stderr)
+ self.assertEqual(self._run_tsc().returncode, 0)
+ finally:
+ if self.showcase_source.exists():
+ self.showcase_source.unlink()
+
+ self.assertFalse(self.showcase_source.exists())
+
+ def test_visual_hull_factory_typechecks_and_is_removed(self) -> None:
+ self.assertFalse(self.showcase_source.exists())
+ try:
+ generate_result = run("stage3_build/generate_threejs_factory.py", VISUAL_HULL_FIXTURE, "--out", self.showcase_source)
+ self.assertEqual(generate_result.returncode, 0, generate_result.stderr)
+ self.assertEqual(self._run_tsc().returncode, 0)
+ finally:
+ if self.showcase_source.exists():
+ self.showcase_source.unlink()
+
+ self.assertFalse(self.showcase_source.exists())
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_structure_gates.py b/forge/tests/test_structure_gates.py
index 09c0b4c..407d98a 100644
--- a/forge/tests/test_structure_gates.py
+++ b/forge/tests/test_structure_gates.py
@@ -15,6 +15,54 @@ from append_review import main as append_review_main
from orchestrate_passes import ledger_disagreements, pass_order
+# The icosphere/punch_through fixtures live in the self-intersection suite. Reusing them keeps one
+# definition of "a mesh punched through itself" instead of two that can silently diverge.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_self_intersection import icosphere, punch_through # noqa: E402
+
+
+class SelfIntersectionWiring(unittest.TestCase):
+ """The gate is only worth having if the pipeline actually calls it.
+
+ `self_intersection.py` shipped as a standalone CLI, which means it runs when somebody remembers to
+ run it — and the defect it exists to catch survived eight review rounds precisely because nobody
+ remembered. These two tests pin the call site itself: a punched-through mesh must fail
+ `measure_geometry_integrity`, and a clean one must not.
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.vertices, cls.indices = icosphere(2)
+
+ def _payload(self, vertices, indices):
+ # Normals come from the CLEAN sphere, where the outward normal of a unit sphere is the position
+ # itself. Deriving them from the punched positions instead would point the pushed cap's normals
+ # backwards and the gate would be reading a fixture that no sculpt would ever produce.
+ # They are supplied at all because measure_geometry_integrity independently requires normals for
+ # watertight validation; without them the mesh fails for an unrelated reason and this test would
+ # pass while proving nothing.
+ normals = [list(v) for v in self.vertices]
+ return {"meshes": [{"id": "skull", "vertices": vertices, "indices": indices, "normals": normals}]}
+
+ def test_punched_through_mesh_fails_the_integrity_gate(self) -> None:
+ vertices = punch_through(self.vertices)
+ result = measure_geometry_integrity(self._payload(vertices, self.indices))
+ report = result["meshes"][0] if "meshes" in result else result["reports"][0]
+
+ self.assertTrue(report["selfIntersection"]["selfIntersecting"])
+ self.assertTrue(any("selfIntersecting" in f for f in result["failures"]))
+ # And the topological checks on the SAME mesh stay clean -- this is what makes the new call
+ # site load-bearing rather than redundant with the ones already there.
+ self.assertEqual(report["boundaryEdges"], 0)
+ self.assertEqual(report["nonManifoldEdges"], 0)
+
+ def test_clean_mesh_does_not_trip_the_new_failure(self) -> None:
+ result = measure_geometry_integrity(self._payload(list(self.vertices), self.indices))
+ report = result["meshes"][0] if "meshes" in result else result["reports"][0]
+ self.assertFalse(report["selfIntersection"]["selfIntersecting"])
+ self.assertFalse(any("selfIntersecting" in f for f in result["failures"]))
+
+
class StructureGateTest(unittest.TestCase):
def test_coincident_vertices_are_merged_for_edge_counts(self) -> None:
vertices = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0], [1, 0, 0], [0, 1, 0]]
@@ -28,6 +76,26 @@ class StructureGateTest(unittest.TestCase):
self.assertFalse(result["passed"])
self.assertEqual(result["meshes"][0]["boundaryEdges"], 3)
self.assertEqual(result["meshes"][1]["realization"], "map-only")
+ self.assertTrue(any(issue["code"] == "watertight" and issue["severity"] == "error" for issue in result["issues"]))
+
+ def test_open_integrated_geometry_is_also_watertight_error(self) -> None:
+ result = measure_geometry_integrity({"meshes": [{
+ "id": "body",
+ "realization": "integrated",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2],
+ }]})
+ self.assertFalse(result["passed"])
+ self.assertTrue(any(issue["code"] == "watertight" and issue["severity"] == "error" for issue in result["issues"]))
+
+ def test_non_manifold_edges_are_severity_tagged(self) -> None:
+ result = measure_geometry_integrity({"meshes": [{
+ "id": "body",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1]],
+ "indices": [0, 1, 2, 1, 0, 3, 0, 1, 4],
+ }]})
+ self.assertFalse(result["passed"])
+ self.assertTrue(any(issue["code"] == "non-manifold" and issue["severity"] == "error" for issue in result["issues"]))
def test_out_of_order_append_leaves_spec_unchanged(self) -> None:
with tempfile.TemporaryDirectory() as directory:
@@ -42,6 +110,76 @@ class StructureGateTest(unittest.TestCase):
spec = {"buildPasses": [{"id": "blockout"}, {"id": "material-pass"}], "reviewHistory": [{"passId": "material-pass", "action": "continue"}]}
self.assertTrue(any(item.startswith("material-pass:") for item in ledger_disagreements(spec, [])))
+ def test_triangle_budget_requires_lod_and_is_severity_tagged(self) -> None:
+ result = measure_geometry_integrity({
+ "triangleBudget": 1,
+ "meshes": [{
+ "id": "dense-body",
+ "realization": "integrated",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2, 0, 2, 1],
+ }],
+ })
+ self.assertFalse(result["passed"])
+ self.assertEqual(result["triangleCount"], 2)
+ self.assertTrue(any(issue["code"] == "triangle-budget" and issue["severity"] == "error" for issue in result["issues"]))
+ self.assertTrue(any(issue["code"] == "lod-required" and issue["severity"] == "error" for issue in result["issues"]))
+
+ def test_triangle_budget_rejects_lod_tiers_without_reduction(self) -> None:
+ result = measure_geometry_integrity({
+ "triangleBudget": 1,
+ "lodPlan": [
+ {"tier": "near", "distance": 0, "triangleCount": 2},
+ {"tier": "far", "distance": 30, "triangleCount": 2},
+ ],
+ "meshes": [{
+ "id": "dense-body",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2, 0, 2, 1],
+ }],
+ })
+ self.assertFalse(result["lodPlanValid"])
+ self.assertTrue(any(issue["code"] == "lod-invalid" and issue["severity"] == "error" for issue in result["issues"]))
+
+ def test_triangle_budget_accepts_lod_tiers_with_reduction(self) -> None:
+ result = measure_geometry_integrity({
+ "triangleBudget": 1,
+ "lodPlan": [
+ {"tier": "near", "distance": 0, "triangleCount": 2},
+ {"tier": "far", "distance": 30, "triangleCount": 1},
+ ],
+ "meshes": [{
+ "id": "dense-body",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2, 0, 2, 1],
+ }],
+ })
+ self.assertTrue(result["lodPlanValid"])
+ self.assertFalse(any(issue["code"] == "lod-invalid" for issue in result["issues"]))
+
+ def test_inconsistent_normals_are_reported(self) -> None:
+ result = measure_geometry_integrity({
+ "meshes": [{
+ "id": "body",
+ "realization": "integrated",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2],
+ "normals": [[0, 0, -1], [0, 0, -1], [0, 0, -1]],
+ }],
+ })
+ self.assertFalse(result["passed"])
+ self.assertTrue(any(issue["code"] == "normal-consistency" and issue["severity"] == "error" for issue in result["issues"]))
+
+ def test_zero_length_normals_are_reported(self) -> None:
+ result = measure_geometry_integrity({"meshes": [{
+ "id": "body",
+ "vertices": [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
+ "indices": [0, 1, 2],
+ "normals": [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
+ }]})
+ self.assertFalse(result["passed"])
+ self.assertEqual(result["meshes"][0]["normalConsistency"]["invalidNormalTriangles"], 1)
+
if __name__ == "__main__":
unittest.main()
diff --git a/forge/tests/test_subdivision.py b/forge/tests/test_subdivision.py
new file mode 100644
index 0000000..7c2f935
--- /dev/null
+++ b/forge/tests/test_subdivision.py
@@ -0,0 +1,930 @@
+#!/usr/bin/env python3
+"""Contracts for opt-in Catmull-Clark subdivision cages.
+
+Run runtime checks with:
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 tests/test_subdivision.py
+Set IMG2THREEJS_REQUIRE_SHOWCASE=1 to make missing showcase configuration fail in CI.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from showcase_test_support import showcase_root
+
+ROOT = Path(__file__).resolve().parent.parent
+FIXTURE = ROOT / "tests" / "fixtures" / "subdivision_cage.json"
+IMPLICIT_FIXTURE = ROOT / "tests" / "fixtures" / "implicit_character_torso_limb.json"
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "subdivision", "validate_sculpt_spec")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "_shared"), str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate
+ from subdivision import (
+ CAPSULE_CAP_SEGMENTS,
+ CAPSULE_RADIAL_SEGMENTS,
+ MAX_SUBDIVISION_ITERATIONS,
+ MAX_SUBDIVISION_QUAD_FACES,
+ PLANE_HEIGHT_SEGMENTS,
+ PLANE_WIDTH_SEGMENTS,
+ SPHERE_HEIGHT_SEGMENTS,
+ SPHERE_WIDTH_SEGMENTS,
+ SUBDIVISION_SOURCE_FACE_ESTIMATES,
+ TORUS_RADIAL_SEGMENTS,
+ TORUS_TUBULAR_SEGMENTS,
+ capsule_source_face_count,
+ )
+ from validate_sculpt_spec import validate_spec
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return (
+ generate,
+ validate_spec,
+ MAX_SUBDIVISION_ITERATIONS,
+ MAX_SUBDIVISION_QUAD_FACES,
+ SUBDIVISION_SOURCE_FACE_ESTIMATES,
+ CAPSULE_CAP_SEGMENTS,
+ CAPSULE_RADIAL_SEGMENTS,
+ PLANE_HEIGHT_SEGMENTS,
+ PLANE_WIDTH_SEGMENTS,
+ SPHERE_HEIGHT_SEGMENTS,
+ SPHERE_WIDTH_SEGMENTS,
+ TORUS_RADIAL_SEGMENTS,
+ TORUS_TUBULAR_SEGMENTS,
+ capsule_source_face_count,
+ )
+
+
+(
+ generate,
+ validate_spec,
+ MAX_SUBDIVISION_ITERATIONS,
+ MAX_SUBDIVISION_QUAD_FACES,
+ SUBDIVISION_SOURCE_FACE_ESTIMATES,
+ CAPSULE_CAP_SEGMENTS,
+ CAPSULE_RADIAL_SEGMENTS,
+ PLANE_HEIGHT_SEGMENTS,
+ PLANE_WIDTH_SEGMENTS,
+ SPHERE_HEIGHT_SEGMENTS,
+ SPHERE_WIDTH_SEGMENTS,
+ TORUS_RADIAL_SEGMENTS,
+ TORUS_TUBULAR_SEGMENTS,
+ capsule_source_face_count,
+) = import_forge_modules()
+
+
+def load_fixture() -> dict:
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+def load_implicit_fixture() -> dict:
+ return json.loads(IMPLICIT_FIXTURE.read_text(encoding="utf-8"))
+
+
+def compile_generated_module(
+ generated: str,
+ work_dir: Path,
+ export_subdivision_helper: bool = False,
+) -> tuple[subprocess.CompletedProcess[str], Path]:
+ source = work_dir / "subdivision.ts"
+ build_dir = work_dir / "build"
+ export_statement = (
+ "\nexport { subdivideCatmullClark, SubdivisionGeometryBudgetError, SubdivisionInputError, SubdivisionTopologyError };\n"
+ if export_subdivision_helper
+ else ""
+ )
+ source.write_text(generated + export_statement, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "npx",
+ "tsc",
+ "--target",
+ "ES2020",
+ "--module",
+ "NodeNext",
+ "--moduleResolution",
+ "NodeNext",
+ "--strict",
+ "--skipLibCheck",
+ "--noUnusedLocals",
+ "--noUnusedParameters",
+ "--outDir",
+ str(build_dir),
+ str(source),
+ ],
+ cwd=showcase_root(),
+ capture_output=True,
+ text=True,
+ )
+ return result, build_dir / "subdivision.js"
+
+
+class SubdivisionContractTest(unittest.TestCase):
+ def test_accepts_opt_in_subdivision_iterations(self) -> None:
+ for iterations in (0, 2, MAX_SUBDIVISION_ITERATIONS):
+ with self.subTest(iterations=iterations):
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["geometryDescriptor"]["subdivide"]["iterations"] = iterations
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertEqual(component["geometryDescriptor"]["subdivide"]["iterations"], iterations)
+ self.assertEqual(errors, [])
+
+ def test_accepts_empty_subdivide_as_a_no_op(self) -> None:
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["subdivide"] = {}
+
+ errors, _warnings = validate_spec(spec)
+ generated = generate(spec, "blockout")
+
+ self.assertEqual(errors, [])
+ self.assertNotIn("function subdivideCatmullClark", generated)
+
+ def test_rejects_negative_fractional_and_over_limit_iterations(self) -> None:
+ cases = (
+ ("boolean", True, "must be a non-negative integer"),
+ ("negative", -1, "must be a non-negative integer"),
+ ("fractional", 1.5, "must be a non-negative integer"),
+ ("over limit", MAX_SUBDIVISION_ITERATIONS + 1, f"must not exceed {MAX_SUBDIVISION_ITERATIONS}"),
+ )
+ for label, iterations, reason in cases:
+ with self.subTest(label=label):
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["subdivide"]["iterations"] = iterations
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.subdivide.iterations" in error and reason in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_generate_rejects_invalid_subdivision_iterations(self) -> None:
+ cases = (
+ (True, "must be a non-negative integer"),
+ (-1, "must be a non-negative integer"),
+ (1.5, "must be a non-negative integer"),
+ (MAX_SUBDIVISION_ITERATIONS + 1, f"must not exceed {MAX_SUBDIVISION_ITERATIONS}"),
+ )
+ for iterations, reason in cases:
+ with self.subTest(iterations=iterations):
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["subdivide"]["iterations"] = iterations
+
+ with self.assertRaisesRegex(ValueError, reason):
+ generate(spec, "blockout")
+
+ def test_generator_cli_rejects_invalid_subdivision_iterations(self) -> None:
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["subdivide"]["iterations"] = 1.5
+
+ with tempfile.TemporaryDirectory() as directory:
+ work_dir = Path(directory)
+ spec_path = work_dir / "invalid-subdivision.json"
+ output_path = work_dir / "model.ts"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / "stage3_build" / "generate_threejs_factory.py"),
+ str(spec_path),
+ "--out",
+ str(output_path),
+ "--allow-nonstrict",
+ ],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("geometryDescriptor.subdivide.iterations", result.stderr)
+ self.assertFalse(output_path.exists())
+
+ def test_generates_catmull_clark_helper_and_recomputes_normals(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ self.assertIn("function subdivideCatmullClark", generated)
+ self.assertIn("const nextFaces: number[][] = []", generated)
+ self.assertIn("nextFaces.push([", generated)
+ self.assertIn("subdivideCatmullClark(geometry", generated)
+ self.assertIn("subdivideCatmullClark(geometry, 2)", generated)
+ self.assertIn(f"const MAX_SUBDIVISION_QUAD_FACES = {MAX_SUBDIVISION_QUAD_FACES};", generated)
+ self.assertIn(f"const MAX_SUBDIVISION_ITERATIONS = {MAX_SUBDIVISION_ITERATIONS};", generated)
+ helper_start = generated.index("function subdivideCatmullClark")
+ helper_end = generated.index("return geometry;", helper_start)
+ self.assertIn("computeVertexNormals()", generated[helper_start:helper_end])
+
+ def test_generated_cage_reports_runtime_quad_growth(self) -> None:
+ self.assertTrue(showcase_root().exists(), showcase_root())
+ expected_counts = ((1, 24), (2, 96))
+ for iterations, expected_quad_count in expected_counts:
+ with self.subTest(iterations=iterations):
+ spec = load_fixture()
+ spec["componentTree"][0]["geometryDescriptor"]["subdivide"]["iterations"] = iterations
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import { createSubdivisionCageModel } from './build/subdivision.js'; "
+ "const model = createSubdivisionCageModel(); "
+ "const mesh = model.userData.sculptRuntime.meshes['rounded-cage']; "
+ "const uv = mesh.geometry.getAttribute('uv'); "
+ "console.log(JSON.stringify({ "
+ "subdivision: mesh.geometry.userData.subdivision, "
+ "positionCount: mesh.geometry.getAttribute('position').count, "
+ "uvCount: uv?.count ?? 0 "
+ "}));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertEqual(result["subdivision"]["sourceFaceCount"], 6)
+ self.assertEqual(result["subdivision"]["quadFaceCount"], expected_quad_count)
+ self.assertEqual(result["subdivision"]["iterations"], iterations)
+ self.assertGreater(result["uvCount"], 0)
+ self.assertEqual(result["uvCount"], result["positionCount"])
+
+ def test_generated_subdivision_propagates_uv2(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark } from './build/subdivision.js'; "
+ "const source = new THREE.BoxGeometry(1, 1, 1); "
+ "source.setAttribute('uv2', source.getAttribute('uv').clone()); "
+ "const geometry = subdivideCatmullClark(source, 1); "
+ "const uv = geometry.getAttribute('uv'); "
+ "const uv2 = geometry.getAttribute('uv2'); "
+ "const seamSets = (input) => { "
+ "const position = input.getAttribute('position'); "
+ "const inputUv = input.getAttribute('uv'); "
+ "const corners = new Map(); "
+ "for (let index = 0; index < position.count; index += 1) { "
+ "const key = `${position.getX(index)},${position.getY(index)},${position.getZ(index)}`; "
+ "const values = corners.get(key) ?? new Set(); "
+ "values.add(`${inputUv.getX(index)},${inputUv.getY(index)}`); "
+ "corners.set(key, values); "
+ "} "
+ "return Array.from(corners.values()) "
+ ".filter((values) => values.size > 1) "
+ ".map((values) => Array.from(values).sort()); "
+ "}; "
+ "const sourceSeams = seamSets(source); "
+ "const subdivisionSeams = seamSets(geometry); "
+ "const preservesSourceSeam = sourceSeams.some((sourceValues) => "
+ "subdivisionSeams.some((subdivisionValues) => "
+ "sourceValues.every((value) => subdivisionValues.includes(value)))); "
+ "const uvValues = new Set(Array.from(uv.array).map((value, index) => "
+ "index % 2 === 0 ? `${value},${uv.array[index + 1]}` : '')); "
+ "const hasExpectedInterpolation = uvValues.has('0.5,0') && uvValues.has('0.5,0.5'); "
+ "const usable = [uv, uv2].every((attribute) => attribute "
+ "&& attribute.count === geometry.getAttribute('position').count "
+ "&& Array.from(attribute.array).every(Number.isFinite)); "
+ "console.log(JSON.stringify({ "
+ "usable, "
+ "sourceSeamCount: sourceSeams.length, "
+ "subdivisionSeamCount: subdivisionSeams.length, "
+ "preservesSourceSeam, "
+ "hasExpectedInterpolation, "
+ "uvCount: uv?.count ?? 0, "
+ "uv2Count: uv2?.count ?? 0 "
+ "}));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["usable"])
+ self.assertGreater(result["sourceSeamCount"], 0)
+ self.assertGreater(result["subdivisionSeamCount"], 0)
+ self.assertTrue(result["preservesSourceSeam"])
+ self.assertTrue(result["hasExpectedInterpolation"])
+ self.assertEqual(result["uvCount"], result["uv2Count"])
+
+ def test_generated_subdivision_rejects_dense_geometry_over_budget(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark, SubdivisionGeometryBudgetError } from './build/subdivision.js'; "
+ "try { "
+ "subdivideCatmullClark(new THREE.SphereGeometry(0.5, 64, 40), 4); "
+ "console.log(JSON.stringify({ rejected: false })); "
+ "} catch (error) { "
+ "console.log(JSON.stringify({ "
+ "rejected: error instanceof SubdivisionGeometryBudgetError, "
+ "name: error instanceof Error ? error.name : '' "
+ "})); "
+ "}"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["rejected"])
+ self.assertEqual(result["name"], "SubdivisionGeometryBudgetError")
+
+ def test_generated_subdivision_rejects_invalid_runtime_iterations(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark, SubdivisionInputError } from './build/subdivision.js'; "
+ f"const values = [true, 1.5, -1, Number.NaN, {MAX_SUBDIVISION_ITERATIONS + 1}]; "
+ "const rejected = values.map((value) => { "
+ "try { subdivideCatmullClark(new THREE.BoxGeometry(1, 1, 1), value); return false; } "
+ "catch (error) { return error instanceof SubdivisionInputError; } "
+ "}); "
+ "const source = new THREE.BoxGeometry(1, 1, 1); "
+ "const zero = subdivideCatmullClark(source, 0); "
+ "console.log(JSON.stringify({ rejected, zeroIsNoOp: zero === source }));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(all(result["rejected"]))
+ self.assertTrue(result["zeroIsNoOp"])
+
+ def test_rejects_dense_primitive_subdivision_before_generation(self) -> None:
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "sphere"
+ component["geometryDescriptor"]["subdivide"]["iterations"] = MAX_SUBDIVISION_ITERATIONS
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.subdivide.iterations" in error
+ and "would produce" in error
+ and "sphere" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_static_budget_allows_runtime_safe_cylinder_and_cone_subdivision(self) -> None:
+ self.assertEqual(
+ SUBDIVISION_SOURCE_FACE_ESTIMATES["capsule"],
+ capsule_source_face_count(CAPSULE_CAP_SEGMENTS, CAPSULE_RADIAL_SEGMENTS),
+ )
+ self.assertGreaterEqual(
+ SUBDIVISION_SOURCE_FACE_ESTIMATES["sphere"],
+ 2 * SPHERE_WIDTH_SEGMENTS * (SPHERE_HEIGHT_SEGMENTS - 1),
+ )
+ self.assertGreaterEqual(
+ SUBDIVISION_SOURCE_FACE_ESTIMATES["torus"],
+ 2 * TORUS_TUBULAR_SEGMENTS * TORUS_RADIAL_SEGMENTS,
+ )
+ self.assertGreaterEqual(
+ SUBDIVISION_SOURCE_FACE_ESTIMATES["plane-card"],
+ 2 * PLANE_WIDTH_SEGMENTS * PLANE_HEIGHT_SEGMENTS,
+ )
+ for primitive, maximum_safe_iterations in (("cylinder", 3), ("cone", 3), ("capsule", 2)):
+ with self.subTest(primitive=primitive):
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = primitive
+ component["geometryDescriptor"]["subdivide"]["iterations"] = maximum_safe_iterations
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertEqual(errors, [])
+
+ component["geometryDescriptor"]["subdivide"]["iterations"] = maximum_safe_iterations + 1
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.subdivide.iterations" in error
+ and "would produce" in error
+ and primitive in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_generated_cylinder_and_cone_subdivision_execute_safely(self) -> None:
+ for primitive in ("cylinder", "cone", "capsule"):
+ with self.subTest(primitive=primitive):
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = primitive
+ component["geometryDescriptor"]["subdivide"]["iterations"] = 1
+
+ errors, _warnings = validate_spec(spec)
+ self.assertEqual(errors, [])
+ generated = generate(spec, "blockout")
+ if primitive == "cone":
+ self.assertIn("new THREE.CylinderGeometry(0.5, 0.0001, 1, 48, 16)", generated)
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import { createSubdivisionCageModel } from './build/subdivision.js'; "
+ "const model = createSubdivisionCageModel(); "
+ "const mesh = model.userData.sculptRuntime.meshes['rounded-cage']; "
+ "console.log(JSON.stringify({ "
+ "subdivision: mesh.geometry.userData.subdivision, "
+ "positionCount: mesh.geometry.getAttribute('position').count "
+ "}));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertEqual(result["subdivision"]["iterations"], 1)
+ self.assertLessEqual(
+ result["subdivision"]["sourceFaceCount"],
+ SUBDIVISION_SOURCE_FACE_ESTIMATES[primitive],
+ )
+ self.assertGreater(result["subdivision"]["quadFaceCount"], 0)
+ self.assertGreater(result["positionCount"], 0)
+
+ def test_non_subdivided_cone_preserves_cone_geometry_output(self) -> None:
+ # heightSegments is 1 here (CONE_HEIGHT_SEGMENTS), not 16 (CYLINDER_HEIGHT_SEGMENTS):
+ # a real ConeGeometry(0.5, 1, 48, 16) measured 2448 raw / 2160 welded boundary
+ # edges (a genuine topology defect, unlike box/cylinder/sphere/torus, which weld
+ # cleanly at their own segment counts) -- a TAPERING cone does not weld cleanly at
+ # 16 height segments the way a constant-radius cylinder does. heightSegments=1
+ # (three.js's own default) welds to 0/0, verified directly; see
+ # forge/tests/test_primitive_watertightness.py. The subdivision-requested
+ # substitute geometry below is untouched by this and still uses
+ # CYLINDER_HEIGHT_SEGMENTS -- it's a near-degenerate CylinderGeometry, not a
+ # literal cone, so it doesn't have the tapering defect in the first place.
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "cone"
+ del component["geometryDescriptor"]["subdivide"]
+
+ generated = generate(spec, "blockout")
+
+ self.assertIn("new THREE.ConeGeometry(0.5, 1, 48, 1)", generated)
+ self.assertNotIn("new THREE.CylinderGeometry(0.5, 0.0001, 1, 48, 16)", generated)
+
+ def test_default_instanced_cluster_subdivision_uses_closed_box_source(self) -> None:
+ for iterations in (1, MAX_SUBDIVISION_ITERATIONS):
+ with self.subTest(iterations=iterations):
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "instanced-cluster"
+ component["geometryDescriptor"] = {"subdivide": {"iterations": iterations}}
+
+ errors, _warnings = validate_spec(spec)
+ self.assertEqual(errors, [])
+ generated = generate(spec, "blockout")
+ self.assertIn("new THREE.BoxGeometry(1, 1, 1)", generated)
+ self.assertNotIn("new THREE.BoxGeometry(1, 1, 1, 12, 12, 12)", generated)
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import { createSubdivisionCageModel } from './build/subdivision.js'; "
+ "const model = createSubdivisionCageModel(); "
+ "const mesh = model.userData.sculptRuntime.meshes['rounded-cage']; "
+ "console.log(JSON.stringify(mesh.geometry.userData.subdivision));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertEqual(result["sourceFaceCount"], SUBDIVISION_SOURCE_FACE_ESTIMATES["box"])
+ self.assertEqual(result["quadFaceCount"], 6 * 4**iterations)
+
+ def test_rejects_attached_box_subdivision_over_attachment_cylinder_budget(self) -> None:
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["geometryDescriptor"]["subdivide"]["iterations"] = MAX_SUBDIVISION_ITERATIONS
+ component["attachment"] = {
+ "localStart": [0, 0, 0],
+ "localEnd": [0, 1, 0],
+ "baseRadius": 0.1,
+ "endRadius": 0.05,
+ }
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "geometryDescriptor.subdivide.iterations" in error
+ and "would produce" in error
+ and "attachment cylinder" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_torus_subdivision_is_rejected_before_generation(self) -> None:
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "torus"
+ component["geometryDescriptor"]["subdivide"]["iterations"] = 1
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "torus subdivision topology is unsupported" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ with tempfile.TemporaryDirectory() as directory:
+ work_dir = Path(directory)
+ spec_path = work_dir / "torus-subdivision.json"
+ output_path = work_dir / "model.ts"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / "stage3_build" / "generate_threejs_factory.py"),
+ str(spec_path),
+ "--out",
+ str(output_path),
+ "--allow-nonstrict",
+ ],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("torus subdivision topology is unsupported", result.stderr)
+ self.assertFalse(output_path.exists())
+
+ def test_plane_card_subdivision_is_rejected_before_generation(self) -> None:
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "plane-card"
+ component["geometryDescriptor"]["subdivide"]["iterations"] = 1
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "plane-card subdivision topology is unsupported" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ with tempfile.TemporaryDirectory() as directory:
+ work_dir = Path(directory)
+ spec_path = work_dir / "plane-card-subdivision.json"
+ output_path = work_dir / "model.ts"
+ spec_path.write_text(json.dumps(spec), encoding="utf-8")
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / "stage3_build" / "generate_threejs_factory.py"),
+ str(spec_path),
+ "--out",
+ str(output_path),
+ "--allow-nonstrict",
+ ],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("plane-card subdivision topology is unsupported", result.stderr)
+ self.assertFalse(output_path.exists())
+
+ def test_subdivision_preflight_covers_all_generator_paths(self) -> None:
+ for primitive in ("tube", "lathe", "extrude", "ground-blade", "curve-sweep"):
+ with self.subTest(primitive=primitive):
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = primitive
+ component["geometryDescriptor"]["subdivide"]["iterations"] = 1
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "cannot statically budget emitted primitive" in error
+ and primitive in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ spec = load_fixture()
+ component = spec["componentTree"][0]
+ component["primitive"] = "instanced-cluster"
+ component["geometryDescriptor"] = {"subdivide": {"iterations": 1}}
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertEqual(errors, [])
+
+ component["geometryDescriptor"]["baseGeometry"] = "tube"
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(
+ any(
+ "cannot statically budget emitted primitive" in error
+ and "tube" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ implicit_spec = load_implicit_fixture()
+ implicit_component = implicit_spec["componentTree"][0]
+ implicit_component["geometryDescriptor"]["subdivide"] = {"iterations": 1}
+ errors, _warnings = validate_spec(implicit_spec)
+
+ self.assertTrue(
+ any(
+ "cannot statically budget emitted primitive 'implicit sdf'" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ implicit_component["attachment"] = {
+ "localStart": [0, 0, 0],
+ "localEnd": [0, 1, 0],
+ "baseRadius": 0.1,
+ "endRadius": 0.05,
+ }
+ errors, _warnings = validate_spec(implicit_spec)
+
+ self.assertTrue(
+ any(
+ "cannot statically budget emitted primitive 'implicit sdf'" in error
+ for error in errors
+ ),
+ errors,
+ )
+
+ def test_generated_subdivision_rejects_non_manifold_edges(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark, SubdivisionTopologyError } from './build/subdivision.js'; "
+ "const source = new THREE.BufferGeometry(); "
+ "source.setAttribute('position', new THREE.Float32BufferAttribute(["
+ "0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1"
+ "], 3)); "
+ "source.setIndex([0, 1, 2, 1, 0, 3, 0, 1, 4]); "
+ "try { "
+ "subdivideCatmullClark(source, 1); "
+ "console.log(JSON.stringify({ rejected: false })); "
+ "} catch (error) { "
+ "console.log(JSON.stringify({ "
+ "rejected: error instanceof SubdivisionTopologyError, "
+ "name: error instanceof Error ? error.name : '' "
+ "})); "
+ "}"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["rejected"])
+ self.assertEqual(result["name"], "SubdivisionTopologyError")
+
+ def test_generated_subdivision_rejects_open_boundary_topology(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark, SubdivisionTopologyError } from './build/subdivision.js'; "
+ "const source = new THREE.BufferGeometry(); "
+ "source.setAttribute('position', new THREE.Float32BufferAttribute(["
+ "0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0"
+ "], 3)); "
+ "source.setIndex([0, 1, 2, 0, 2, 3]); "
+ "try { "
+ "subdivideCatmullClark(source, 1); "
+ "console.log(JSON.stringify({ rejected: false })); "
+ "} catch (error) { "
+ "console.log(JSON.stringify({ "
+ "rejected: error instanceof SubdivisionTopologyError, "
+ "name: error instanceof Error ? error.name : '', "
+ "reason: error instanceof SubdivisionTopologyError ? error.reason : '' "
+ "})); "
+ "}"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["rejected"])
+ self.assertEqual(result["name"], "SubdivisionTopologyError")
+ self.assertEqual(result["reason"], "open boundary edge 0:1 has 1 incident face")
+
+ def test_generated_subdivision_rejects_disconnected_incident_face_fans(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(
+ generated,
+ work_dir,
+ export_subdivision_helper=True,
+ )
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node",
+ "--input-type=module",
+ "--eval",
+ (
+ "import * as THREE from 'three'; "
+ "import { subdivideCatmullClark, SubdivisionTopologyError } from './build/subdivision.js'; "
+ "const source = new THREE.BufferGeometry(); "
+ "source.setAttribute('position', new THREE.Float32BufferAttribute(["
+ "0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0, 0, 0, -1, 0, 0, 0, -1"
+ "], 3)); "
+ "source.setIndex(["
+ "0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2, "
+ "0, 4, 5, 0, 5, 6, 0, 6, 4, 4, 6, 5"
+ "]); "
+ "try { "
+ "subdivideCatmullClark(source, 1); "
+ "console.log(JSON.stringify({ rejected: false })); "
+ "} catch (error) { "
+ "console.log(JSON.stringify({ "
+ "rejected: error instanceof SubdivisionTopologyError, "
+ "reason: error instanceof SubdivisionTopologyError ? error.reason : '' "
+ "})); "
+ "}"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["rejected"])
+ self.assertIn("disconnected incident face fan", result["reason"])
+
+ def test_primitive_only_factory_omits_subdivision_helper(self) -> None:
+ spec = copy.deepcopy(load_fixture())
+ del spec["componentTree"][0]["geometryDescriptor"]["subdivide"]
+
+ generated = generate(spec, "blockout")
+
+ self.assertNotIn("function subdivideCatmullClark", generated)
+ self.assertNotIn("subdivideCatmullClark(geometry", generated)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_tessellation_tiers.py b/forge/tests/test_tessellation_tiers.py
new file mode 100644
index 0000000..9ca6f8d
--- /dev/null
+++ b/forge/tests/test_tessellation_tiers.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+"""`performanceBudget.targetTriangles` must actually reach the emitted geometry.
+
+The field was in the schema and read by nothing — `validate_sculpt_spec.py` checked only
+that `performanceBudget` was an object, and the generator never opened it. A 61-component
+humanoid spec therefore built 14,208 triangles no matter what budget it declared, because
+every primitive's segment counts were module-level constants. Measured, not inferred: the
+emitted factory was constructed under node and its triangles counted.
+
+These tests pin the three properties that make the tier mechanism worth having:
+ 1. a spec that declares no budget generates exactly what it generated before tiers existed,
+ 2. a smaller budget really does emit coarser primitives,
+ 3. no tier may drop below the segment floors that skinning deformation depends on.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path[:0] = [str(ROOT / "_shared"), str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+
+from subdivision import ( # noqa: E402
+ CYLINDER_HEIGHT_SEGMENTS,
+ CYLINDER_RADIAL_SEGMENTS,
+ DEFAULT_TESSELLATION_TIER,
+ MIN_JOINT_HEIGHT_SEGMENTS,
+ MIN_RADIAL_SEGMENTS,
+ SPHERE_HEIGHT_SEGMENTS,
+ SPHERE_WIDTH_SEGMENTS,
+ TESSELLATION_TIERS,
+ segments_for_spec,
+ tier_for_target_triangles,
+ validate_tier,
+)
+
+
+class TierSelectionTest(unittest.TestCase):
+ def test_absent_or_unusable_budget_keeps_the_pre_tier_behaviour(self) -> None:
+ for value in (None, 0, -1, "3000", True, float("nan") * 0 - 1):
+ self.assertEqual(tier_for_target_triangles(value), DEFAULT_TESSELLATION_TIER, value)
+ self.assertEqual(segments_for_spec({}), TESSELLATION_TIERS[DEFAULT_TESSELLATION_TIER])
+ self.assertEqual(
+ segments_for_spec({"performanceBudget": {}}),
+ TESSELLATION_TIERS[DEFAULT_TESSELLATION_TIER],
+ )
+
+ def test_budget_maps_to_a_coarser_tier(self) -> None:
+ self.assertEqual(tier_for_target_triangles(3_000), "low")
+ self.assertEqual(tier_for_target_triangles(6_000), "low")
+ self.assertEqual(tier_for_target_triangles(20_000), "standard")
+ self.assertEqual(tier_for_target_triangles(250_000), "hero")
+
+ def test_hero_tier_is_the_module_constants(self) -> None:
+ """Backwards compatibility is a property, not a hope: `hero` must BE the old values."""
+ hero = TESSELLATION_TIERS["hero"]
+ self.assertEqual(hero["SPHERE_WIDTH_SEGMENTS"], SPHERE_WIDTH_SEGMENTS)
+ self.assertEqual(hero["SPHERE_HEIGHT_SEGMENTS"], SPHERE_HEIGHT_SEGMENTS)
+ self.assertEqual(hero["CYLINDER_RADIAL_SEGMENTS"], CYLINDER_RADIAL_SEGMENTS)
+ self.assertEqual(hero["CYLINDER_HEIGHT_SEGMENTS"], CYLINDER_HEIGHT_SEGMENTS)
+
+
+class TierFloorTest(unittest.TestCase):
+ def test_every_shipped_tier_clears_the_deformation_floors(self) -> None:
+ for name in TESSELLATION_TIERS:
+ validate_tier(name) # raises if a floor is violated
+
+ def test_the_joint_floor_matches_the_in_repo_precedent_not_the_textbook(self) -> None:
+ """External practice says 3 loops at a joint; this repo already decided 3 was too few.
+
+ `emit_rig.py:399` derives `max(4, ceil(cyl_length / target_ring_spacing))` — a hard
+ floor of 4 — in the same module whose NOTES.md documents the single-quad-band
+ joint-pinch failure. A measurement made here outranks a rule of thumb made elsewhere.
+ """
+ self.assertEqual(MIN_JOINT_HEIGHT_SEGMENTS, 4)
+ for name, table in TESSELLATION_TIERS.items():
+ for key in ("CYLINDER_HEIGHT_SEGMENTS", "ATTACHMENT_CYLINDER_HEIGHT_SEGMENTS"):
+ self.assertGreaterEqual(table[key], 4, f"{name}.{key}")
+
+ def test_cone_height_segments_is_pinned_out_of_the_budget_knobs(self) -> None:
+ """A tapering cone welds to 0/0 only at 1; higher counts are a real topology defect."""
+ for name, table in TESSELLATION_TIERS.items():
+ self.assertEqual(table["CONE_HEIGHT_SEGMENTS"], 1, name)
+ original = TESSELLATION_TIERS["low"]["CONE_HEIGHT_SEGMENTS"]
+ TESSELLATION_TIERS["low"]["CONE_HEIGHT_SEGMENTS"] = 4
+ try:
+ with self.assertRaises(ValueError) as caught:
+ validate_tier("low")
+ self.assertIn("welds cleanly", str(caught.exception))
+ finally:
+ TESSELLATION_TIERS["low"]["CONE_HEIGHT_SEGMENTS"] = original
+
+ def test_a_tier_below_the_joint_floor_is_refused(self) -> None:
+ """One quad across a joint leaves no vertex at the pivot, so the joint collapses."""
+ original = TESSELLATION_TIERS["low"]["CYLINDER_HEIGHT_SEGMENTS"]
+ TESSELLATION_TIERS["low"]["CYLINDER_HEIGHT_SEGMENTS"] = MIN_JOINT_HEIGHT_SEGMENTS - 1
+ try:
+ with self.assertRaises(ValueError) as caught:
+ validate_tier("low")
+ self.assertIn("deform", str(caught.exception))
+ finally:
+ TESSELLATION_TIERS["low"]["CYLINDER_HEIGHT_SEGMENTS"] = original
+
+ def test_a_tier_below_the_radial_floor_is_refused(self) -> None:
+ original = TESSELLATION_TIERS["low"]["CAPSULE_RADIAL_SEGMENTS"]
+ TESSELLATION_TIERS["low"]["CAPSULE_RADIAL_SEGMENTS"] = MIN_RADIAL_SEGMENTS - 1
+ try:
+ with self.assertRaises(ValueError) as caught:
+ validate_tier("low")
+ self.assertIn("round", str(caught.exception))
+ finally:
+ TESSELLATION_TIERS["low"]["CAPSULE_RADIAL_SEGMENTS"] = original
+
+ def test_unknown_tier_is_refused(self) -> None:
+ with self.assertRaises(ValueError):
+ validate_tier("potato")
+
+
+class EmittedGeometryTest(unittest.TestCase):
+ """The tier has to reach the generated source, not just the resolver."""
+
+ def _emit(self, primitive: str, tier: str) -> str:
+ from generate_threejs_factory import geometry_for
+
+ return geometry_for(primitive, {}, False, TESSELLATION_TIERS[tier])
+
+ def test_low_tier_emits_coarser_primitives_than_hero(self) -> None:
+ for primitive in ("sphere", "cylinder", "capsule", "box"):
+ hero = self._emit(primitive, "hero")
+ low = self._emit(primitive, "low")
+ self.assertNotEqual(hero, low, f"{primitive} ignored the tier")
+
+ def test_default_argument_reproduces_the_hero_string(self) -> None:
+ from generate_threejs_factory import geometry_for
+
+ self.assertEqual(geometry_for("sphere", {}), self._emit("sphere", "hero"))
+ self.assertEqual(
+ geometry_for("sphere", {}),
+ f"new THREE.SphereGeometry(0.5, {SPHERE_WIDTH_SEGMENTS}, {SPHERE_HEIGHT_SEGMENTS})",
+ )
+
+
+class SdfResolutionCapTest(unittest.TestCase):
+ """An implicit surface has no segment counts, so the tier has to reach its sampling grid.
+
+ Left uncapped it is the one unbudgeted source of triangles in an otherwise budgeted model.
+ Marching-cubes output scales with the surface it crosses — O(N^2), measured on a capsule
+ field at N = 64/96/128 → 3,432/7,840/13,960 crossing cells — so lowering the grid is a
+ real lever, not a rounding error.
+ """
+
+ def _capped(self, resolution: int, tier: str) -> int:
+ from generate_threejs_factory import capped_sdf
+
+ result = capped_sdf({"resolution": resolution}, TESSELLATION_TIERS[tier])
+ return result["resolution"]
+
+ def test_low_tier_lowers_a_grid_above_its_ceiling(self) -> None:
+ self.assertEqual(self._capped(32, "low"), TESSELLATION_TIERS["low"]["SDF_MAX_RESOLUTION"])
+
+ def test_a_grid_already_below_the_ceiling_is_left_alone(self) -> None:
+ """The cap must never make a deliberately coarse field denser."""
+ self.assertEqual(self._capped(8, "low"), 8)
+ self.assertEqual(self._capped(32, "hero"), 32)
+
+ def test_a_descriptor_without_a_resolution_is_returned_unchanged(self) -> None:
+ from generate_threejs_factory import capped_sdf
+
+ descriptor = {"primitives": [], "operations": []}
+ self.assertIs(capped_sdf(descriptor, TESSELLATION_TIERS["low"]), descriptor)
+
+ def test_every_tier_declares_a_ceiling(self) -> None:
+ for name, table in TESSELLATION_TIERS.items():
+ self.assertIn("SDF_MAX_RESOLUTION", table, name)
+
+
+class FlatShadingTest(unittest.TestCase):
+ """The faceted low-poly look has to be expressible, and has to stay opt-in.
+
+ three.js gives every face its own normals for flat shading, which needs unshared
+ vertices — the geometry becomes non-indexed and the vertex count triples. Enabling it
+ by default would silently spend the budget the tier mechanism exists to protect.
+ """
+
+ def _generated(self) -> str:
+ import json
+
+ from generate_threejs_factory import generate
+
+ fixture = ROOT / "tests" / "fixtures" / "subdivision_cage.json"
+ return generate(json.loads(fixture.read_text(encoding="utf-8")), "form-pass")
+
+ def test_flat_shading_is_emitted_and_reads_from_the_material_spec(self) -> None:
+ self.assertIn("flatShading: spec.flatShading === true", self._generated())
+
+ def test_flat_shading_defaults_to_off(self) -> None:
+ """`=== true` and nothing looser: a truthy stray value must not enable it."""
+ generated = self._generated()
+ self.assertNotIn("flatShading: spec.flatShading,", generated)
+ self.assertNotIn("flatShading: !!spec.flatShading", generated)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_turntable_gate.py b/forge/tests/test_turntable_gate.py
new file mode 100644
index 0000000..3a9999c
--- /dev/null
+++ b/forge/tests/test_turntable_gate.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python3
+"""Tests for the mandatory turntable coverage + interior-hole gate."""
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+from turntable_gate import analyze_turntable # noqa: E402
+from diagnose_render_multi_angle import silhouette_area_fraction # noqa: E402
+
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path, w, h, pixel_fn):
+ """Minimal, stdlib-only (zlib + struct) uncompressed-filter RGB PNG encoder,
+ just enough for read_png/load_image to decode back in tests."""
+
+ def chunk(tag, data):
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0) # filter type 0 (none) per scanline
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0) # bit depth 8, color type 2 (RGB)
+ path.write_bytes(
+ PNG_SIGNATURE
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b"")
+ )
+
+
+BACKGROUND = (255, 255, 255)
+FOREGROUND = (20, 20, 20)
+
+
+def _blob(x0, y0, x1, y1, hole_center=None, hole_radius=0):
+ """Pixel fn: a solid dark square blob on a white background, optionally
+ with a background-coloured disc punched through its middle (the
+ silhouette-encloses-background regression case an area check can't see).
+ """
+
+ def fn(x, y, w, h):
+ if hole_center is not None:
+ dx, dy = x - hole_center[0], y - hole_center[1]
+ if dx * dx + dy * dy <= hole_radius * hole_radius:
+ return BACKGROUND
+ if x0 <= x < x1 and y0 <= y < y1:
+ return FOREGROUND
+ return BACKGROUND
+
+ return fn
+
+
+def _low_contrast_gradient(x, y, w, h):
+ """Pixel fn: a saturated dark subject on a saturated dark gradient.
+
+ This reproduces the review harness's own render style, which is what
+ defeated `build_foreground_mask` in practice. The mechanism is specific: the
+ segmenter accepts a pixel as foreground when `distance > threshold` OR
+ `saturation > 0.16 and luma < 0.94`. A dark violet background satisfies the
+ second clause everywhere, so coverage crosses the 0.9 line, the "not clearly
+ isolated" warning fires, and the mask becomes the whole frame. A grey-ish
+ low-contrast image does NOT reproduce this — it fails the saturation clause
+ and segments normally at ~0.58 coverage. The colours below are load-bearing.
+ """
+ base = 30 + int(22 * (y / max(1, h)))
+ if 60 <= x < 140 and 60 <= y < 140:
+ return (base + 40, base + 20, base + 62)
+ return (base, base - 6, base + 22)
+
+
+class TurntableGateTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+
+ def _write(self, name, w, h, pixel_fn):
+ path = self.tmp / name
+ write_rgb_png(path, w, h, pixel_fn)
+ return path
+
+ def test_unsegmentable_capture_blocks_the_gate_instead_of_passing(self):
+ # Found by running this gate on a REAL review turntable: every angle
+ # reported area=0.9966 and the verdict was a confident PASS, because
+ # build_foreground_mask fell back to "use most pixels" and the mask
+ # covered the whole frame. The subject was never measured at all. A gate
+ # that cannot see its subject must block, not pass.
+ captures = [
+ (azimuth, self._write(f"flat_{azimuth}.png", 200, 200, _low_contrast_gradient))
+ for azimuth in (0, 90, 180, 270)
+ ]
+ result = analyze_turntable(captures)
+
+ self.assertEqual(sorted(result["unsegmentedAzimuths"]), [0.0, 90.0, 180.0, 270.0])
+ self.assertFalse(result["segmentationReliable"])
+ self.assertFalse(result["passed"])
+ # Coverage was complete and nothing collapsed -- without the segmentation
+ # check every other signal here says "fine", which is precisely the trap.
+ self.assertTrue(result["covered"])
+ self.assertFalse(result["degenerate"])
+
+ def test_allow_holes_does_not_excuse_an_unsegmentable_capture(self):
+ # allow_holes means "this subject may legitimately have a through-hole".
+ # It must never be readable as "evaluate this render blind".
+ captures = [
+ (azimuth, self._write(f"flat2_{azimuth}.png", 200, 200, _low_contrast_gradient))
+ for azimuth in (0, 90, 180, 270)
+ ]
+ self.assertFalse(analyze_turntable(captures, allow_holes=True)["passed"])
+
+ def test_solid_blob_at_all_required_azimuths_passes(self):
+ captures = []
+ for azimuth in (0, 90, 180, 270):
+ path = self._write(f"solid_{azimuth}.png", 200, 200, _blob(40, 40, 160, 160))
+ captures.append((azimuth, path))
+
+ result = analyze_turntable(captures)
+ self.assertTrue(result["passed"])
+ self.assertFalse(result["holed"])
+ self.assertEqual(result["missingAzimuths"], [])
+ self.assertTrue(result["covered"])
+ self.assertFalse(result["degenerate"])
+
+ def test_punched_disc_is_holed_and_fails_while_area_barely_moves(self):
+ # Regression case (lead): a background-coloured disc punched through
+ # the middle of the blob is an enclosed-background hole. Silhouette
+ # AREA barely changes (the disc removes a small fraction of the
+ # blob's pixels), so the existing area-collapse signal alone would
+ # miss it -- the whole point of this module.
+ solid_path = self._write("solid.png", 200, 200, _blob(40, 40, 160, 160))
+ punched_path = self._write(
+ "punched.png", 200, 200, _blob(40, 40, 160, 160, hole_center=(100, 100), hole_radius=20)
+ )
+
+ solid_fraction = silhouette_area_fraction(solid_path)
+ punched_fraction = silhouette_area_fraction(punched_path)
+ self.assertAlmostEqual(solid_fraction, punched_fraction, delta=0.05)
+
+ captures = [(0, punched_path), (90, solid_path), (180, solid_path), (270, solid_path)]
+ result = analyze_turntable(captures)
+ self.assertTrue(result["holed"])
+ self.assertFalse(result["passed"])
+ # And the underlying area signal really did barely move -- this is
+ # what makes the hole check a genuinely new signal, not a duplicate.
+ self.assertFalse(result["degenerate"])
+
+ def test_missing_azimuths_reported_and_fails(self):
+ path = self._write("front.png", 200, 200, _blob(40, 40, 160, 160))
+ result = analyze_turntable([(0, path)])
+ self.assertEqual(sorted(result["missingAzimuths"]), [90.0, 180.0, 270.0])
+ self.assertFalse(result["covered"])
+ self.assertFalse(result["passed"])
+
+ def test_allow_holes_flips_holed_case_back_to_passing(self):
+ solid_path = self._write("solid2.png", 200, 200, _blob(40, 40, 160, 160))
+ punched_path = self._write(
+ "punched2.png", 200, 200, _blob(40, 40, 160, 160, hole_center=(100, 100), hole_radius=20)
+ )
+ captures = [(0, punched_path), (90, solid_path), (180, solid_path), (270, solid_path)]
+
+ gated = analyze_turntable(captures, allow_holes=False)
+ allowed = analyze_turntable(captures, allow_holes=True)
+
+ self.assertFalse(gated["passed"])
+ self.assertTrue(allowed["passed"])
+ # The raw signal is still reported even when allowed -- allow_holes
+ # only changes whether it fails the gate, not whether it's detected.
+ self.assertTrue(allowed["holed"])
+
+ def test_tiny_hole_does_not_trip_the_gate(self):
+ # A 1px anti-aliasing-scale speckle must not read as a defect.
+ captures = []
+ for azimuth in (0, 90, 180, 270):
+ path = self._write(
+ f"speckle_{azimuth}.png",
+ 200,
+ 200,
+ _blob(40, 40, 160, 160, hole_center=(100, 100), hole_radius=1),
+ )
+ captures.append((azimuth, path))
+
+ result = analyze_turntable(captures)
+ self.assertFalse(result["holed"])
+ self.assertTrue(result["passed"])
+
+ def test_wraparound_azimuth_matches_required_zero(self):
+ captures = [
+ (359.5, self._write("wrap_0.png", 200, 200, _blob(40, 40, 160, 160))),
+ (90.3, self._write("wrap_90.png", 200, 200, _blob(40, 40, 160, 160))),
+ (180.0, self._write("wrap_180.png", 200, 200, _blob(40, 40, 160, 160))),
+ (269.8, self._write("wrap_270.png", 200, 200, _blob(40, 40, 160, 160))),
+ ]
+ result = analyze_turntable(captures)
+ self.assertEqual(result["missingAzimuths"], [])
+ self.assertTrue(result["covered"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_uv_unwrap.py b/forge/tests/test_uv_unwrap.py
new file mode 100644
index 0000000..60802bb
--- /dev/null
+++ b/forge/tests/test_uv_unwrap.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+"""Tests for UV unwrapping, built on shapes whose correct answer is known in advance.
+
+The centrepiece is `test_planar_grid_unwraps_without_distortion`: a flat grid has an exact isometric
+flattening, so LSCM must reproduce it to within solver tolerance. If the conformal system is wired
+wrong -- a sign flipped, real and imaginary parts crossed -- the result is still a plausible-looking
+scatter of UVs, and only a case with a known answer catches it.
+
+`test_closed_cube_reports_non_disk_charts_when_uncut` guards the failure mode that would otherwise
+ship silently: a chart that is not a topological disk has no valid flattening, and LSCM returns one
+anyway.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import math
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage3_build"))
+
+from uv_unwrap import ( # noqa: E402
+ chart_distortion,
+ chart_is_disk,
+ enforce_disk_charts,
+ lscm,
+ pack_charts,
+ segment_charts,
+ unwrap,
+ _triangles,
+)
+
+
+def planar_grid(n: int = 5, size: float = 1.0):
+ """An n x n quad grid on the z = 0 plane, triangulated."""
+ vertices = []
+ for row in range(n + 1):
+ for column in range(n + 1):
+ vertices.append([size * column / n, size * row / n, 0.0])
+ indices = []
+ for row in range(n):
+ for column in range(n):
+ a = row * (n + 1) + column
+ b = a + 1
+ c = a + (n + 1)
+ d = c + 1
+ indices.extend([a, b, d, a, d, c])
+ return vertices, indices
+
+
+def unit_cube():
+ """A closed cube: six flat faces, and as one surface not a disk."""
+ vertices = [
+ [0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
+ [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1],
+ ]
+ quads = [
+ (0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
+ (2, 3, 7, 6), (1, 2, 6, 5), (0, 4, 7, 3),
+ ]
+ indices = []
+ for a, b, c, d in quads:
+ indices.extend([a, b, c, a, c, d])
+ return vertices, indices
+
+
+def open_cylinder(segments: int = 12, rings: int = 3, radius: float = 1.0, height: float = 2.0):
+ """A tube with open ends: connected, but a cylinder rather than a disk."""
+ vertices = []
+ for ring in range(rings + 1):
+ y = height * ring / rings
+ for segment in range(segments):
+ angle = 2 * math.pi * segment / segments
+ vertices.append([radius * math.cos(angle), y, radius * math.sin(angle)])
+ indices = []
+ for ring in range(rings):
+ for segment in range(segments):
+ a = ring * segments + segment
+ b = ring * segments + (segment + 1) % segments
+ c = a + segments
+ d = b + segments
+ indices.extend([a, b, d, a, d, c])
+ return vertices, indices
+
+
+class ConformalCorrectness(unittest.TestCase):
+ def test_planar_grid_unwraps_without_distortion(self) -> None:
+ vertices, indices = planar_grid(5)
+ result = unwrap({"vertices": vertices, "indices": indices})
+
+ self.assertEqual(result["chartCount"], 1)
+ self.assertEqual(result["totalFlippedTriangles"], 0)
+ self.assertEqual(result["nonDiskCharts"], [])
+ # A plane has an exact isometric flattening, so every triangle must scale identically and the
+ # worst/median ratio must sit at 1.
+ self.assertAlmostEqual(result["worstAreaDistortion"], 1.0, delta=0.02)
+
+ def test_planar_grid_uv_preserves_relative_distances(self) -> None:
+ # Stronger than the distortion ratio: checks the LAYOUT, not just the areas. A map that folded
+ # the grid onto itself could still show uniform area scaling.
+ vertices, indices = planar_grid(4)
+ faces = _triangles(indices)
+ charts = segment_charts(vertices, faces)
+ uv = lscm(vertices, faces, charts[0])
+
+ def ratio(i: int, j: int) -> float:
+ du = uv[i][0] - uv[j][0]
+ dv = uv[i][1] - uv[j][1]
+ dx = vertices[i][0] - vertices[j][0]
+ dy = vertices[i][1] - vertices[j][1]
+ return math.hypot(du, dv) / max(math.hypot(dx, dy), 1e-12)
+
+ pairs = [(0, 4), (0, 20), (4, 24), (6, 18)]
+ ratios = [ratio(i, j) for i, j in pairs]
+ for value in ratios:
+ self.assertAlmostEqual(value, ratios[0], delta=0.05)
+
+ def test_a_curved_chart_costs_area_and_the_number_says_so(self) -> None:
+ # LSCM preserves angles, not areas. A cylinder chart must show measurably more area
+ # distortion than a flat one -- if it did not, the metric would be inert.
+ flat_v, flat_i = planar_grid(5)
+ flat = unwrap({"vertices": flat_v, "indices": flat_i})
+
+ cyl_v, cyl_i = open_cylinder()
+ faces = _triangles(cyl_i)
+ # One chart over the whole tube, bypassing segmentation, to isolate the solver's behaviour.
+ whole = list(range(len(faces)))
+ uv = lscm(cyl_v, faces, whole)
+ curved = chart_distortion(cyl_v, faces, whole, uv)
+
+ self.assertGreater(curved["areaDistortion"], flat["worstAreaDistortion"])
+
+
+class ChartTopology(unittest.TestCase):
+ def test_flat_grid_is_a_disk(self) -> None:
+ vertices, indices = planar_grid(3)
+ faces = _triangles(indices)
+ self.assertTrue(chart_is_disk(faces, list(range(len(faces)))))
+
+ def test_closed_cube_surface_is_not_a_disk(self) -> None:
+ vertices, indices = unit_cube()
+ faces = _triangles(indices)
+ self.assertFalse(chart_is_disk(faces, list(range(len(faces)))))
+
+ def test_open_cylinder_is_not_a_disk(self) -> None:
+ vertices, indices = open_cylinder()
+ faces = _triangles(indices)
+ self.assertFalse(chart_is_disk(faces, list(range(len(faces)))))
+
+ def test_uncut_tube_is_split_into_disks_not_merely_reported(self) -> None:
+ """LSCM returns UVs for a non-disk chart and they are garbage, so reporting is not enough.
+
+ Measured on a real skull, leaving seven non-disk charts in place drove worst-case area
+ distortion to 171300 with twelve inverted triangles; cutting them first brought both down.
+ A threshold of 180 degrees deliberately defeats segmentation so the whole tube arrives as one
+ non-disk chart and only `enforce_disk_charts` can save it.
+ """
+ vertices, indices = open_cylinder(segments=16, rings=2)
+ faces = _triangles(indices)
+ self.assertFalse(chart_is_disk(faces, list(range(len(faces)))))
+
+ result = unwrap({"vertices": vertices, "indices": indices}, angle_threshold_degrees=180.0)
+ self.assertGreater(result["topologySplits"], 0)
+ self.assertEqual(result["nonDiskCharts"], [])
+
+ def test_enforce_disk_charts_terminates_and_covers_every_face(self) -> None:
+ # A single triangle is always a disk, so the recursion has a floor; this pins that it is
+ # reached without dropping or duplicating a face on the way.
+ vertices, indices = open_cylinder(segments=12, rings=3)
+ faces = _triangles(indices)
+ charts, splits = enforce_disk_charts(faces, [list(range(len(faces)))])
+ self.assertGreater(splits, 0)
+ self.assertEqual(sorted(i for chart in charts for i in chart), list(range(len(faces))))
+ for chart in charts:
+ self.assertTrue(chart_is_disk(faces, chart))
+
+
+class Segmentation(unittest.TestCase):
+ def test_cube_splits_into_six_planar_charts(self) -> None:
+ vertices, indices = unit_cube()
+ faces = _triangles(indices)
+ charts = segment_charts(vertices, faces, angle_threshold_degrees=50.0)
+ self.assertEqual(len(charts), 6)
+ for chart in charts:
+ self.assertTrue(chart_is_disk(faces, chart))
+
+ def test_growth_is_measured_against_the_seed_not_the_neighbour(self) -> None:
+ # Against the neighbour, a chart creeps around a cylinder one tolerable step at a time until
+ # its ends face opposite ways. Against the seed it cannot: a 12-segment tube turns 30 degrees
+ # per step, so a 50-degree limit must stop well short of wrapping the whole ring.
+ vertices, indices = open_cylinder(segments=12, rings=1)
+ faces = _triangles(indices)
+ charts = segment_charts(vertices, faces, angle_threshold_degrees=50.0)
+ self.assertGreater(len(charts), 1)
+ self.assertLess(max(len(chart) for chart in charts), len(faces))
+
+ def test_every_face_lands_in_exactly_one_chart(self) -> None:
+ vertices, indices = open_cylinder()
+ faces = _triangles(indices)
+ charts = segment_charts(vertices, faces)
+ assigned = [index for chart in charts for index in chart]
+ self.assertEqual(sorted(assigned), list(range(len(faces))))
+
+
+class Packing(unittest.TestCase):
+ def test_packed_uvs_stay_inside_the_unit_square(self) -> None:
+ vertices, indices = unit_cube()
+ result = unwrap({"vertices": vertices, "indices": indices})
+ for u, v in result["uv"]:
+ self.assertGreaterEqual(u, -1e-6)
+ self.assertLessEqual(u, 1.0 + 1e-6)
+ self.assertGreaterEqual(v, -1e-6)
+
+ def test_packing_reports_efficiency_rather_than_claiming_optimality(self) -> None:
+ vertices, indices = unit_cube()
+ result = unwrap({"vertices": vertices, "indices": indices})
+ self.assertGreater(result["packingEfficiency"], 0.0)
+ self.assertLessEqual(result["packingEfficiency"], 1.0)
+ self.assertTrue(any("heuristic" in note for note in result["notes"]))
+
+ def test_empty_chart_list_does_not_crash_the_packer(self) -> None:
+ packed, efficiency = pack_charts([])
+ self.assertEqual(packed, [])
+ self.assertEqual(efficiency, 0.0)
+
+
+class SeamHonesty(unittest.TestCase):
+ def test_multi_chart_mesh_reports_its_seam_vertices(self) -> None:
+ # A cube corner belongs to three charts and therefore carries three UVs. Whichever is written
+ # last wins, so the bake needs to know which vertices must be duplicated first.
+ vertices, indices = unit_cube()
+ result = unwrap({"vertices": vertices, "indices": indices})
+ self.assertGreater(result["seamVertexCount"], 0)
+ self.assertTrue(any("duplicated" in note for note in result["notes"]))
+
+
+class DegenerateInput(unittest.TestCase):
+ def test_empty_vertices_raise(self) -> None:
+ with self.assertRaises(ValueError):
+ unwrap({"vertices": [], "indices": [0, 1, 2]})
+
+ def test_too_few_indices_raise(self) -> None:
+ with self.assertRaises(ValueError):
+ unwrap({"vertices": [[0, 0, 0]], "indices": []})
+
+ def test_grouped_and_flat_index_encodings_agree(self) -> None:
+ vertices, flat = planar_grid(3)
+ grouped = [flat[i:i + 3] for i in range(0, len(flat), 3)]
+ self.assertEqual(
+ unwrap({"vertices": vertices, "indices": flat})["uv"],
+ unwrap({"vertices": vertices, "indices": grouped})["uv"],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_validate_rig_payload.py b/forge/tests/test_validate_rig_payload.py
new file mode 100644
index 0000000..9341ddb
--- /dev/null
+++ b/forge/tests/test_validate_rig_payload.py
@@ -0,0 +1,62 @@
+import copy
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from forge.stage5_rig.validate_rig_payload import validate # noqa: E402
+
+
+def payload():
+ return {
+ "schemaVersion": 1,
+ "coordinateSystem": {"up": "Y", "handedness": "right", "unit": "normalized"},
+ "joints": [[0, 0, 0], [0, 1, 0], [0.5, 1.5, 0]],
+ "parents": [None, 0, 1],
+ "names": ["root", "spine", "arm_L"],
+ "matrix_local": [
+ [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0.5, 0, 1, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1],
+ ],
+ "skinIndex": [[0, 1, 2, 0], [1, 2, 0, 0]],
+ "skinWeight": [[0.5, 0.3, 0.2, 0], [0.2, 0.8, 0, 0]],
+ }
+
+
+class ValidateRigPayloadTest(unittest.TestCase):
+ def test_valid_payload_passes(self):
+ result = validate(payload())
+ self.assertTrue(result["passed"], result)
+ self.assertEqual(result["summary"]["maxInfluences"], 4)
+
+ def test_parent_order_is_hard_gate(self):
+ value = payload()
+ value["parents"][2] = 2
+ result = validate(value)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("parent < child" in error for error in result["errors"]))
+
+ def test_weight_normalization_and_nan_are_hard_gates(self):
+ value = payload()
+ value["skinWeight"][0] = [0.5, 0.5, 0.5, 0]
+ value["skinWeight"][1][0] = float("nan")
+ result = validate(value)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("must sum to 1" in error for error in result["errors"]))
+ self.assertTrue(any("finite non-negative" in error for error in result["errors"]))
+
+ def test_duplicate_names_and_bad_matrix_are_hard_gates(self):
+ value = copy.deepcopy(payload())
+ value["names"][2] = "spine"
+ value["matrix_local"][1][15] = 0
+ result = validate(value)
+ self.assertFalse(result["passed"])
+ self.assertTrue(any("duplicate joint name" in error for error in result["errors"]))
+ self.assertTrue(any("affine last row" in error for error in result["errors"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_visual_hull.py b/forge/tests/test_visual_hull.py
new file mode 100644
index 0000000..2f7b184
--- /dev/null
+++ b/forge/tests/test_visual_hull.py
@@ -0,0 +1,251 @@
+#!/usr/bin/env python3
+"""Contracts for opt-in orthographic visual-hull geometry carving."""
+
+from __future__ import annotations
+
+import copy
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+
+ROOT = Path(__file__).resolve().parent.parent
+FIXTURE = ROOT / "tests" / "fixtures" / "visual_hull_two_views.json"
+
+
+def import_forge_modules():
+ module_names = ("generate_threejs_factory", "validate_sculpt_spec", "visual_hull")
+ original_modules = {name: sys.modules.pop(name, None) for name in module_names}
+ original_path = sys.path[:]
+ sys.path[:0] = [str(ROOT / "stage2_spec"), str(ROOT / "stage3_build")]
+ try:
+ from generate_threejs_factory import generate
+ from validate_sculpt_spec import validate_spec
+ from visual_hull import MAX_VISUAL_HULL_RESOLUTION, MAX_VISUAL_HULL_TRIANGLES
+ finally:
+ sys.path[:] = original_path
+ for name, module in original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+ return generate, validate_spec, MAX_VISUAL_HULL_RESOLUTION, MAX_VISUAL_HULL_TRIANGLES
+
+
+generate, validate_spec, MAX_VISUAL_HULL_RESOLUTION, MAX_VISUAL_HULL_TRIANGLES = import_forge_modules()
+
+
+def load_fixture() -> dict:
+ return json.loads(FIXTURE.read_text(encoding="utf-8"))
+
+
+def compile_generated_module(generated: str, work_dir: Path) -> tuple[subprocess.CompletedProcess[str], Path]:
+ source = work_dir / "visual-hull.ts"
+ build_dir = work_dir / "build"
+ source.write_text(generated, encoding="utf-8")
+ result = subprocess.run(
+ [
+ "npx", "tsc", "--target", "ES2020", "--module", "NodeNext", "--moduleResolution", "NodeNext",
+ "--strict", "--skipLibCheck", "--noUnusedLocals", "--noUnusedParameters", "--outDir", str(build_dir), str(source),
+ ],
+ cwd=showcase_root(),
+ capture_output=True,
+ text=True,
+ )
+ return result, build_dir / "visual-hull.js"
+
+
+class VisualHullContractTest(unittest.TestCase):
+ def test_accepts_two_orthographic_silhouettes_with_bounded_budget(self) -> None:
+ spec = load_fixture()
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertEqual(errors, [])
+
+ def test_rejects_invalid_visual_hull_shape_bounds_confidence_and_budget(self) -> None:
+ cases = (
+ ("projection", ("projection",), "perspective", "projection must be 'orthographic'"),
+ ("bounds space", ("boundsSpace",), "world", "boundsSpace must be 'component-local'"),
+ ("resolution", ("resolution",), MAX_VISUAL_HULL_RESOLUTION + 1, "must not exceed"),
+ ("budget", ("triangleBudget",), 12, "requires at least"),
+ ("bounds", ("bounds", "min", 0), 1.0, "must be less than"),
+ ("confidence", ("views", 0, "confidence"), 1.1, "must be a number from 0 to 1"),
+ ("mask", ("views", 0, "mask", 0), "00102", "must contain only '0' and '1'"),
+ ("axis", ("views", 1, "axis"), "front", "must use distinct axes"),
+ )
+ for label, path, value, expected in cases:
+ with self.subTest(label=label):
+ spec = load_fixture()
+ target = spec["componentTree"][0]["geometryDescriptor"]["visualHull"]
+ for key in path[:-1]:
+ target = target[key]
+ target[path[-1]] = value
+
+ errors, _warnings = validate_spec(spec)
+
+ self.assertTrue(any("geometryDescriptor.visualHull" in error and expected in error for error in errors), errors)
+
+ def test_requires_two_views_and_preserves_default_source_without_helper(self) -> None:
+ visual_hull_spec = load_fixture()
+ one_view_spec = copy.deepcopy(visual_hull_spec)
+ one_view_spec["componentTree"][0]["geometryDescriptor"]["visualHull"]["views"] = one_view_spec["componentTree"][0]["geometryDescriptor"]["visualHull"]["views"][:1]
+ default_spec = copy.deepcopy(visual_hull_spec)
+ default_spec["componentTree"][0]["geometryDescriptor"] = {}
+
+ errors, _warnings = validate_spec(one_view_spec)
+ default_source = generate(default_spec, "blockout")
+ visual_hull_source = generate(visual_hull_spec, "blockout")
+
+ self.assertTrue(any("at least two views" in error for error in errors), errors)
+ self.assertNotIn("function buildVisualHullGeometry", default_source)
+ self.assertIn("function buildVisualHullGeometry", visual_hull_source)
+ self.assertIn("hiddenRegions", visual_hull_source)
+
+ def test_component_local_bounds_preserve_component_transform_application(self) -> None:
+ """PLAN_1.5 WS-E: shape dimensions are baked into a part's geometry, never into
+ the pivot Group's scale. The pivot node's own scale must stay identity (so a
+ non-uniform component cannot distort a child that is later parented under it);
+ the component's declared scale instead multiplies the geometry's vertex data
+ directly. This supersedes the pre-WS-E contract, which asserted the opposite
+ (`node.scale == component.transform.scale`, geometry left un-scaled) — that was
+ exactly the anti-pattern WS-E removes, since it is what forced every character
+ part to flatten onto a single hidden root instead of nesting under a real
+ parent (see docs/PLAN_1.5_ANIMATION_READY_RIGS.md, WS-E)."""
+ baseline_spec = load_fixture()
+ scaled_spec = load_fixture()
+ scaled_spec["componentTree"][0]["transform"] = {
+ "position": [3.0, 2.0, -1.0],
+ "rotation": [0.0, 0.0, 0.0],
+ "scale": [2.0, 1.0, 3.0],
+ }
+ baseline_source = generate(baseline_spec, "blockout")
+ scaled_source = generate(scaled_spec, "blockout")
+
+ def read_bounds(generated: str, work_dir: Path) -> dict:
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node", "--input-type=module", "--eval",
+ (
+ "import { createTwoViewVisualHullModel } from './build/visual-hull.js'; "
+ "const model = createTwoViewVisualHullModel(); "
+ "const node = model.userData.sculptRuntime.nodes['carved-body']; "
+ "const geometry = model.userData.sculptRuntime.meshes['carved-body'].geometry; "
+ "geometry.computeBoundingBox(); "
+ "console.log(JSON.stringify({ position: node.position.toArray(), scale: node.scale.toArray(), localMin: geometry.boundingBox.min.toArray(), localMax: geometry.boundingBox.max.toArray() }));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ return json.loads(runtime.stdout)
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ base_dir = Path(directory) / "baseline"
+ scaled_dir = Path(directory) / "scaled"
+ base_dir.mkdir()
+ scaled_dir.mkdir()
+ baseline = read_bounds(baseline_source, base_dir)
+ scaled = read_bounds(scaled_source, scaled_dir)
+
+ # Position/rotation still cascade through the pivot Group exactly as before.
+ self.assertEqual(scaled["position"], [3, 2, -1])
+ # The pivot node's scale is always identity now, in both the default-scale and
+ # the non-uniform-scale case — dimensions never live on this transform.
+ self.assertEqual(baseline["scale"], [1, 1, 1])
+ self.assertEqual(scaled["scale"], [1, 1, 1])
+ # The component's declared [2, 1, 3] scale is applied directly to the geometry's
+ # vertex data instead: the scaled local bounds equal the baseline (unit-scale)
+ # local bounds multiplied elementwise by the component scale.
+ factor = [2, 1, 3]
+ for axis in range(3):
+ self.assertAlmostEqual(scaled["localMin"][axis], baseline["localMin"][axis] * factor[axis], places=5)
+ self.assertAlmostEqual(scaled["localMax"][axis], baseline["localMax"][axis] * factor[axis], places=5)
+
+ def test_contradictory_silhouettes_raise_typed_occupancy_error(self) -> None:
+ spec = load_fixture()
+ views = spec["componentTree"][0]["geometryDescriptor"]["visualHull"]["views"]
+ views[0]["mask"] = ["1111111111111111"] * 8 + ["0000000000000000"] * 8
+ views[1]["mask"] = ["0000000000000000"] * 8 + ["1111111111111111"] * 8
+ errors, _warnings = validate_spec(spec)
+ self.assertEqual(errors, [])
+ generated = generate(spec, "blockout")
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node", "--input-type=module", "--eval",
+ (
+ "import { createTwoViewVisualHullModel } from './build/visual-hull.js'; "
+ "try { createTwoViewVisualHullModel(); console.log(JSON.stringify({ rejected: false })); } "
+ "catch (error) { console.log(JSON.stringify({ rejected: error instanceof Error && error.name === 'VisualHullOccupancyError', name: error instanceof Error ? error.name : '' })); }"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertTrue(result["rejected"])
+ self.assertEqual(result["name"], "VisualHullOccupancyError")
+
+ def test_generated_visual_hull_is_deterministic_welded_and_manifold(self) -> None:
+ spec = load_fixture()
+ generated = generate(spec, "blockout")
+ self.assertEqual(generated, generate(copy.deepcopy(spec), "blockout"))
+
+ with tempfile.TemporaryDirectory(dir=showcase_root()) as directory:
+ work_dir = Path(directory)
+ compile_result, _module_path = compile_generated_module(generated, work_dir)
+ self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
+ runtime = subprocess.run(
+ [
+ "node", "--input-type=module", "--eval",
+ (
+ "import { createTwoViewVisualHullModel } from './build/visual-hull.js'; "
+ "const model = createTwoViewVisualHullModel(); "
+ "const geometry = model.userData.sculptRuntime.meshes['carved-body'].geometry; "
+ "const position = geometry.getAttribute('position'); const uv = geometry.getAttribute('uv'); "
+ "const index = geometry.getIndex(); const edges = new Map(); "
+ "for (let offset = 0; offset < index.count; offset += 3) { "
+ "const triangle = [index.getX(offset), index.getX(offset + 1), index.getX(offset + 2)]; "
+ "for (let corner = 0; corner < 3; corner += 1) { const a = triangle[corner]; const b = triangle[(corner + 1) % 3]; const key = a < b ? `${a}:${b}` : `${b}:${a}`; edges.set(key, (edges.get(key) ?? 0) + 1); } } "
+ "const repeat = createTwoViewVisualHullModel().userData.sculptRuntime.meshes['carved-body'].geometry; "
+ "console.log(JSON.stringify({ positions: position.count, uvCount: uv.count, triangles: index.count / 3, manifold: Array.from(edges.values()).every((count) => count === 2), metadata: geometry.userData.visualHull, sameIndexCount: repeat.getIndex().count === index.count }));"
+ ),
+ ],
+ cwd=work_dir,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(runtime.returncode, 0, runtime.stderr)
+ result = json.loads(runtime.stdout)
+
+ self.assertGreater(result["positions"], 8)
+ self.assertEqual(result["uvCount"], result["positions"])
+ self.assertLessEqual(result["triangles"], 50000)
+ self.assertTrue(result["manifold"])
+ self.assertTrue(result["sameIndexCount"])
+ self.assertTrue(result["metadata"]["lowConfidence"]["hiddenRegions"])
+ self.assertEqual(result["metadata"]["observedAxes"], ["front", "side"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_visual_hull_carve.py b/forge/tests/test_visual_hull_carve.py
new file mode 100644
index 0000000..2894ea8
--- /dev/null
+++ b/forge/tests/test_visual_hull_carve.py
@@ -0,0 +1,175 @@
+#!/usr/bin/env python3
+"""Tests for the visual-hull carve, each pinning a property the carve could plausibly get wrong.
+
+The load-bearing one is `test_carved_surface_is_watertight`. Emitting all six faces of every occupied
+voxel is the obvious implementation and it is wrong: shared faces become duplicated interior walls and
+the result is not a surface at all. Because that mesh still *looks* right when rendered from outside,
+the only thing that catches it is an edge count, so that is what this asserts.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage3_build"))
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from visual_hull import carve_visual_hull # noqa: E402
+from geometry_integrity import mesh_edge_counts # noqa: E402
+
+
+def solid_mask(size: int) -> list[str]:
+ return ["1" * size for _ in range(size)]
+
+
+def disc_mask(size: int, radius_fraction: float = 0.45) -> list[str]:
+ """A filled circle, the silhouette a sphere casts from any direction."""
+ rows = []
+ centre = (size - 1) / 2
+ radius = size * radius_fraction
+ for y in range(size):
+ row = []
+ for x in range(size):
+ inside = (x - centre) ** 2 + (y - centre) ** 2 <= radius**2
+ row.append("1" if inside else "0")
+ rows.append("".join(row))
+ return rows
+
+
+def descriptor(views, resolution=8, size=16, budget=400_000):
+ return {
+ "projection": "orthographic",
+ "boundsSpace": "component-local",
+ "bounds": {"min": [-1.0, -1.0, -1.0], "max": [1.0, 1.0, 1.0]},
+ "resolution": resolution,
+ "triangleBudget": budget,
+ "views": [{"axis": axis, "confidence": 0.9, "mask": mask} for axis, mask in views],
+ }
+
+
+class CarveGeometry(unittest.TestCase):
+ def test_carved_surface_is_watertight(self) -> None:
+ # Interior walls, or unwelded corners, both show up here and nowhere else.
+ result = carve_visual_hull(
+ descriptor([("front", disc_mask(16)), ("side", disc_mask(16)), ("top", disc_mask(16))])
+ )
+ counts = mesh_edge_counts(result["vertices"], result["indices"])
+ self.assertEqual(counts["boundaryEdges"], 0)
+ self.assertEqual(counts["nonManifoldEdges"], 0)
+ self.assertGreater(result["triangleCount"], 0)
+
+ def test_three_discs_carve_a_rounded_solid_not_the_whole_box(self) -> None:
+ result = carve_visual_hull(
+ descriptor([("front", disc_mask(16)), ("side", disc_mask(16)), ("top", disc_mask(16))])
+ )
+ # Three orthogonal discs intersect to a rounded solid strictly inside the bounding cube.
+ self.assertGreater(result["occupiedFraction"], 0.15)
+ self.assertLess(result["occupiedFraction"], 0.75)
+
+ def test_a_view_that_sees_background_carves_the_voxel_away(self) -> None:
+ # The defining property: survival requires foreground in EVERY view, not any view.
+ empty_left = [("0" * 8 + "1" * 8) for _ in range(16)]
+ both_solid = carve_visual_hull(
+ descriptor([("front", solid_mask(16)), ("side", solid_mask(16))])
+ )
+ one_half = carve_visual_hull(
+ descriptor([("front", empty_left), ("side", solid_mask(16))])
+ )
+ self.assertLess(one_half["occupiedVoxelCount"], both_solid["occupiedVoxelCount"])
+ self.assertAlmostEqual(
+ one_half["occupiedVoxelCount"] / both_solid["occupiedVoxelCount"], 0.5, delta=0.1
+ )
+
+ def test_disjoint_silhouettes_carve_everything_away_and_say_so(self) -> None:
+ # One bad mask erases the model rather than degrading it. The count must make that visible
+ # instead of handing back an empty mesh that reads as "carve succeeded".
+ left = [("1" * 8 + "0" * 8) for _ in range(16)]
+ right = [("0" * 8 + "1" * 8) for _ in range(16)]
+ result = carve_visual_hull(descriptor([("front", left), ("top", right)]))
+ self.assertEqual(result["occupiedVoxelCount"], 0)
+ self.assertEqual(result["triangleCount"], 0)
+
+
+class CarveHonesty(unittest.TestCase):
+ def test_two_views_report_the_unconstrained_axis(self) -> None:
+ result = carve_visual_hull(
+ descriptor([("front", disc_mask(16)), ("side", disc_mask(16))])
+ )
+ # front frees z, side frees x -- so y is never the camera direction and stays unconstrained.
+ self.assertEqual(result["unconstrainedAxes"], ["y"])
+ self.assertTrue(any("extrudes along" in line for line in result["limitations"]))
+
+ def test_three_views_leave_nothing_unconstrained(self) -> None:
+ result = carve_visual_hull(
+ descriptor([("front", disc_mask(16)), ("side", disc_mask(16)), ("top", disc_mask(16))])
+ )
+ self.assertEqual(result["unconstrainedAxes"], [])
+ self.assertFalse(any("extrudes along" in line for line in result["limitations"]))
+
+ def test_concavity_limitation_is_always_stated(self) -> None:
+ # Stated even for a three-view carve, because view count never fixes it.
+ result = carve_visual_hull(
+ descriptor([("front", disc_mask(16)), ("side", disc_mask(16)), ("top", disc_mask(16))])
+ )
+ self.assertTrue(any("concavity" in line for line in result["limitations"]))
+
+ def test_budget_is_guaranteed_upstream_so_the_carve_needs_no_verdict(self) -> None:
+ """Pins WHY carve_visual_hull reports no budget-overrun boolean.
+
+ The validator requires triangleBudget >= resolution**3 * 12, the worst case for the grid, so
+ an under-budget descriptor never reaches the carve at all. If that rule is ever relaxed this
+ test fails, which is the signal that the carve then does need its own verdict.
+ """
+ with self.assertRaises(ValueError) as caught:
+ carve_visual_hull(
+ descriptor([("front", solid_mask(16)), ("side", solid_mask(16))], resolution=8, budget=10)
+ )
+ self.assertIn("triangleBudget", str(caught.exception))
+
+ generous = carve_visual_hull(
+ descriptor([("front", solid_mask(16)), ("side", solid_mask(16))], resolution=8)
+ )
+ self.assertLessEqual(generous["triangleCount"], generous["triangleBudget"])
+
+
+class CarveConventions(unittest.TestCase):
+ def test_front_view_rows_run_downward_in_y(self) -> None:
+ """Row 0 of a mask is the TOP of the image, which is MAX y, not min.
+
+ Getting this backwards flips every carve upside down while leaving voxel counts, watertightness
+ and every other assertion in this file completely unchanged -- so nothing else here would
+ notice. The mask's top half is foreground, so the survivors must all sit at y >= 0.
+
+ Half the mask rather than one row on purpose: with resolution 8 against a 16-row mask, the
+ topmost voxel's CENTRE lands in mask row 1, not row 0, so a single-row mask carves everything
+ away and would fail for a sampling reason that has nothing to do with direction.
+ """
+ top_half = ["1" * 16 for _ in range(8)] + ["0" * 16 for _ in range(8)]
+ result = carve_visual_hull(
+ descriptor([("front", top_half), ("side", solid_mask(16))], resolution=8)
+ )
+ self.assertGreater(result["occupiedVoxelCount"], 0)
+ ys = [v[1] for v in result["vertices"]]
+ self.assertGreaterEqual(min(ys), -1e-9)
+
+ # And the mirror image really does land on the other side, so this is measuring direction
+ # rather than an accident of where the geometry happened to be.
+ bottom_half = ["0" * 16 for _ in range(8)] + ["1" * 16 for _ in range(8)]
+ flipped = carve_visual_hull(
+ descriptor([("front", bottom_half), ("side", solid_mask(16))], resolution=8)
+ )
+ self.assertLessEqual(max(v[1] for v in flipped["vertices"]), 1e-9)
+
+ def test_invalid_descriptor_raises_rather_than_carving_nonsense(self) -> None:
+ bad = descriptor([("front", disc_mask(16))]) # one view; the schema requires two
+ with self.assertRaises(ValueError):
+ carve_visual_hull(bad)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_vlm_gate.py b/forge/tests/test_vlm_gate.py
index 59f9336..bd37653 100644
--- a/forge/tests/test_vlm_gate.py
+++ b/forge/tests/test_vlm_gate.py
@@ -4,13 +4,17 @@
from __future__ import annotations
import sys
+import io
+import json
import unittest
+import tempfile
+from contextlib import redirect_stderr
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "stage4_review"))
-from vlm_gate import aggregate_samples, calibrate, evidence_consistent, gate # noqa: E402
+from vlm_gate import aggregate_samples, calibrate, evidence_consistent, gate, main # noqa: E402
def const_sampler(scores: dict):
@@ -21,6 +25,18 @@ def high_all(claimed="knife"):
return {"objectness": 0.9, "semantic": 0.88, "structural": 0.86, "specular": 0.85, "claimedClass": claimed}
+def run_main_with_samples(samples):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ eye = root / "eye.json"
+ sample_file = root / "samples.json"
+ eye.write_text(json.dumps({"verdict": "pass", "action": "continue", "hardGateFailures": []}), encoding="utf-8")
+ sample_file.write_text(json.dumps(samples), encoding="utf-8")
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ return main(["--eye", str(eye), "--samples", str(sample_file)]), stderr.getvalue()
+
+
class VlmGateTest(unittest.TestCase):
def test_hard_gate_failure_does_not_consult_vlm(self):
eye = {"verdict": "reject", "action": "refine-code", "hardGateFailures": ["silhouette IoU 0.40 < 0.85"]}
@@ -96,6 +112,21 @@ class VlmGateTest(unittest.TestCase):
agg = aggregate_samples([{"objectness": 0.2}, {"objectness": 0.8}, {"objectness": 0.6}])
self.assertAlmostEqual(agg["criteria"]["objectness"], 0.6, places=5)
+ def test_cli_rejects_empty_samples(self):
+ return_code, stderr = run_main_with_samples([])
+ self.assertEqual(return_code, 2)
+ self.assertIn("--samples must contain a non-empty JSON list", stderr)
+
+ def test_cli_rejects_non_list_samples(self):
+ return_code, stderr = run_main_with_samples({})
+ self.assertEqual(return_code, 2)
+ self.assertIn("--samples must contain a non-empty JSON list", stderr)
+
+ def test_cli_rejects_non_object_sample_entries(self):
+ return_code, stderr = run_main_with_samples([1])
+ self.assertEqual(return_code, 2)
+ self.assertIn("--samples entries must be JSON objects", stderr)
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/forge/tests/test_workflow_state.py b/forge/tests/test_workflow_state.py
index 089a176..61fb3ec 100644
--- a/forge/tests/test_workflow_state.py
+++ b/forge/tests/test_workflow_state.py
@@ -35,6 +35,26 @@ class WorkflowStateTest(unittest.TestCase):
self.assertLess(ids.index("projection-route"), ids.index("spec-authoring"))
self.assertLess(ids.index("material-evidence"), ids.index("strict-validation"))
+ def test_material_reference_wiring_is_in_the_setup_checklist(self):
+ """The material track is executable, not prose.
+
+ Both steps were dropped once already: merge 7214452 resolved this file to a revision
+ whose `material-evidence` step only *described* running a script, and which had no
+ wiring step at all, so `material_region_analysis.py` and `apply_material_analysis.py`
+ became unreachable from the checklist that drives the pipeline. This test is what makes
+ that regression fail loudly instead of silently.
+ """
+ state = new_state("reference.png")
+ by_id = {entry["id"]: entry for entry in state["checklist"]}
+ self.assertIn("material-evidence", by_id)
+ self.assertIn("material-spec-wiring", by_id)
+ self.assertIn("material_region_analysis.py", by_id["material-evidence"]["command"])
+ self.assertIn("apply_material_analysis.py", by_id["material-spec-wiring"]["command"])
+ ids = [entry["id"] for entry in state["checklist"]]
+ self.assertLess(ids.index("spec-authoring"), ids.index("material-evidence"))
+ self.assertLess(ids.index("material-evidence"), ids.index("material-spec-wiring"))
+ self.assertLess(ids.index("material-spec-wiring"), ids.index("strict-validation"))
+
def test_cs2_state_includes_classification_and_manifest_before_pre_spec(self):
state = new_state("knife.png", profile="cs2")
ids = [entry["id"] for entry in state["checklist"]]
diff --git a/forge/tests/test_ws6_docs.py b/forge/tests/test_ws6_docs.py
new file mode 100644
index 0000000..6bff6d8
--- /dev/null
+++ b/forge/tests/test_ws6_docs.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+"""WS6 documentation and version metadata guard tests."""
+
+from __future__ import annotations
+
+import re
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+GRIMOIRE_BUILD = ROOT / "grimoire" / "build"
+SKILL = ROOT / "SKILL.md"
+README = ROOT / "README.md"
+CHANGELOG = ROOT / "CHANGELOG.md"
+
+# Both release paths anchor the version key at column zero: `scripts/release_metadata.py` with
+# VERSION_PATTERN, and `.github/workflows/beta-release.yml` with an equivalent sed. Accept the
+# stable and the beta spellings the beta workflow round-trips between.
+SKILL_VERSION_PATTERN = re.compile(r"^version: (\d+\.\d+\.\d+(?:-beta\.\d+)?)$", re.MULTILINE)
+README_BADGE_PATTERN = re.compile(r"version-(\d+\.\d+\.\d+(?:-beta\.\d+)?)-green\.svg")
+
+
+class Ws6DocsTest(unittest.TestCase):
+ def test_ws6_docs_exist(self) -> None:
+ for relative_path in (
+ "implicit_sdf_modeling.md",
+ "visual_hull_reconstruction.md",
+ "subdivision_surfaces.md",
+ ):
+ with self.subTest(relative_path=relative_path):
+ self.assertTrue((GRIMOIRE_BUILD / relative_path).exists())
+
+ def test_fitting_doc_mentions_divine_eye_loop(self) -> None:
+ text = (GRIMOIRE_BUILD / "analysis_by_synthesis_fitting.md").read_text(encoding="utf-8")
+ for marker in (
+ "fit_against_divine_eye()",
+ "correction_loop.decide()",
+ "bestRawFidelity",
+ ):
+ with self.subTest(marker=marker):
+ self.assertIn(marker, text)
+
+ def test_skill_version_is_reachable_by_the_release_tooling(self) -> None:
+ """Assert against the real SKILL.md, never a fixture.
+
+ Nesting the key under a `metadata:` parent is valid YAML and reads fine to a human, so it
+ survived review; both release paths then match nothing and abort -- the beta workflow with
+ "SKILL.md must contain one supported version field", `release_metadata.py` with
+ "must contain exactly one replaceable version". A fixture-only test cannot see that,
+ because the fixture is the shape the tooling wants rather than the shape on disk.
+ """
+ match = SKILL_VERSION_PATTERN.search(SKILL.read_text(encoding="utf-8"))
+ self.assertIsNotNone(
+ match,
+ "SKILL.md needs one unindented `version:` front-matter key for the release tooling",
+ )
+
+ def test_readme_declares_one_version_badge_matching_the_skill(self) -> None:
+ """A duplicated badge block let README carry two different versions at once.
+
+ `release_metadata.py` rewrites with count=1, so a second badge is never updated and goes
+ stale silently. Pin the count as well as the value.
+ """
+ skill_match = SKILL_VERSION_PATTERN.search(SKILL.read_text(encoding="utf-8"))
+ assert skill_match is not None # the test above reports this failure properly
+ badges = README_BADGE_PATTERN.findall(README.read_text(encoding="utf-8"))
+
+ self.assertEqual(len(badges), 1, f"README must declare exactly one version badge, got {badges}")
+ self.assertEqual(badges[0], skill_match.group(1))
+
+ def test_changelog_defines_each_link_reference_once(self) -> None:
+ """A merge kept both sides' link blocks, so six versions had two definitions each.
+
+ Markdown silently resolves the first and ignores the rest, so half the block was dead text
+ pointing at a different organisation than the live one -- invisible in the rendered page.
+ Deliberately not asserting heading order: `update_changelog` inserts above the first `## [`,
+ so a test pinning `Unreleased` to the top would fail on the first automated release.
+ """
+ labels = re.findall(r"^\[([^\]]+)\]:", CHANGELOG.read_text(encoding="utf-8"), re.MULTILINE)
+ duplicates = sorted({label for label in labels if labels.count(label) > 1})
+
+ self.assertEqual(duplicates, [], f"CHANGELOG.md defines these link references twice: {duplicates}")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/grimoire/build/analysis_by_synthesis_fitting.md b/grimoire/build/analysis_by_synthesis_fitting.md
new file mode 100644
index 0000000..983d5dc
--- /dev/null
+++ b/grimoire/build/analysis_by_synthesis_fitting.md
@@ -0,0 +1,114 @@
+# Analysis-By-Synthesis Fitting
+
+This is the WS4 fitting loop for v1.5. It ties the deterministic parameter search
+to Divine Eye so the loop behaves like a bounded artist correction pass, not a
+free-running guesser.
+
+`forge/stage4_review/fit_params.py` provides pure-stdlib, deterministic bounded
+coordinate descent for analysis-by-synthesis parameters. Use it to tune a small
+rendering or scene vector only when the caller can provide a deterministic objective.
+
+## API And Limits
+
+```python
+result = fit(initial, bounds, objective, FitConfig())
+```
+
+- `initial` has 1 through 15 finite, non-boolean numeric parameters.
+- `bounds` has one `[lower, upper]` finite pair for each parameter. The lower value
+ is strictly less than the upper value, and every initial value is in range.
+- `objective(parameters)` returns a finite score. Higher scores are better.
+- Candidate order is fixed: for every coordinate, evaluate the bounded lower move,
+ then the bounded upper move. `seed` is metadata only; no random source is used.
+- `max_iterations` and `max_evaluations` are hard limits. The fitter additionally
+ stops on a configured plateau or consecutive coordinate-direction thrashing; flip
+ tracking applies only to consecutive iterations whose net gain is below
+ `min_improvement`. Each unstable iteration with at least one reversal advances the
+ thrash streak once; tracking resets after a stable iteration or one without a
+ reversal. This keeps normal bracket refinement, one multi-coordinate reversal,
+ and non-consecutive flips out of the `oscillation` stop condition.
+- If the evaluation budget blocks the second direction for a coordinate, an already
+ evaluated better first-direction proposal is committed and recorded before the
+ `max-evaluations` result is returned.
+
+`FitResult` contains final `parameters`, objective `best_score`, `status`, evaluation
+and iteration totals, `seed`, and per-iteration `FitTelemetry` with objective score,
+improvement flag, cumulative evaluations, and step sizes. `to_json()` retains
+`bestScore` for compatibility and adds the explicit `bestObjectiveScore` field.
+
+`fit_against_divine_eye()` wraps `fit()` with a render callback, calls the Divine Eye
+evaluator for each candidate, stores the raw results, and writes candidate metadata
+back onto every evaluated record. Clean candidates keep their raw fidelity in the
+`[0, 1]` range. Candidates with hard gates are scored as `-1.0` for the objective,
+but their raw fidelity is still preserved separately as `bestRawFidelity` and in the
+copied `divineEyeResults` / `correctionHistory` payloads.
+
+## CLI Fixture Objective
+
+The CLI only runs a deterministic quadratic fixture objective. Its top-level object
+must contain exactly `initial`, `bounds`, `target`, and `config`; it reads:
+
+```json
+{
+ "initial": [0.0],
+ "bounds": [[-1.0, 1.0]],
+ "target": [0.5],
+ "config": {"maxIterations": 20, "maxEvaluations": 200, "seed": 7}
+}
+```
+
+`config` accepts only `maxIterations`, `maxEvaluations`, `minImprovement`,
+`plateauIterations`, `oscillationFlips`, and `seed`. Unknown keys are rejected with
+exit status 2. Production callers use `fit()` directly with their own objective.
+
+## Executable Divine Eye Fitting
+
+`fit_against_divine_eye(initial, bounds, render_for_parameters, reference_png, evaluator=None, config=FitConfig())`
+turns a deterministic parameter-to-render callback into a bounded fidelity objective.
+For every evaluation it calls `render_for_parameters(parameters)`, evaluates the
+render against `reference_png`, and maximizes a gate-aware objective score. Clean
+results use their raw Divine Eye fidelity in `[0, 1]`; results with non-empty
+`hardGateFailures` use `-1.0`, below every clean score. The raw fidelity is retained
+unchanged in evaluator results and correction history, so all-gated runs remain
+bounded and auditable without allowing a high raw gated score to displace a clean fit.
+
+The optional evaluator receives `(reference_path, render_path)` and defaults to a
+lazy import of `divine_eye.evaluate`, so importing the fitting module does not load
+image-analysis dependencies. Its `DivineEyeFitResult` returns the `fit_result`, a
+copied record of every evaluator result, and normalized `correction_history` with
+hard gates and full Divine Eye provenance. The integration does not mutate evaluator
+result mappings. Each copied result receives adapter-owned `fitCandidateParameters`,
+`fitReferencePng`, and `fitRenderPath` fields.
+
+`DivineEyeFitResult.fit_result.best_score` and `bestObjectiveScore` are objective
+scores, not necessarily raw fidelity: an all-gated run reports `-1.0`. Use optional
+`best_raw_fidelity` / JSON `bestRawFidelity` for the selected clean candidate. Its
+`correction_history` / JSON `correctionHistory` is derived from raw copied Divine Eye
+records, never objective scores, so it remains valid and auditable for all-gated runs.
+
+## Divine Eye And Correction Loop
+
+`divine_eye_fidelity(result)` reads the original Divine Eye `fidelity` as a scalar
+objective score only when it is finite and within `[0, 1]`. `divine_eye_correction_history(results)` retains each result's
+`hardGateFailures` and copies the same values into correction-loop `defectTags`.
+Each normalized record also has a deep-copied `divineEye` mapping with the original
+result context, including fidelity, gate failures, action, signals, and reference or
+render paths when present. A result is approved only when it has no hard gates and
+its present routing fields are `action="continue"` and `verdict="pass"`; fidelity-only
+mappings remain approved for compatibility. A fidelity decrease from the last
+approved best score records `reverted=True`; pending (`probe`/non-pass), reverted,
+or hard-gated attempts do not replace that baseline or win gate-aware fitting.
+Neither the source mapping nor its nested provenance is mutated.
+
+`correction_loop.decide()` is the stop policy. It checks, in order, hard gates,
+pending review routing, success, repeated defects, oscillation, plateau, and the
+hard ceiling. That order matters, because a hard gate always routes to `refine-code`
+and the ceiling always stops the loop even if the score is still climbing.
+
+When correction history contains nested `divineEye` provenance, its finite fidelity,
+hard gates, action, and verdict are authoritative. Mirrored top-level fidelity and
+routing fields must match or validation rejects the entry; fidelity-only history
+entries remain supported.
+
+`budget_exceeded(spent_tokens, budget)` accepts a finite non-negative numeric spend
+and a non-negative integer budget; malformed values raise `ValueError`.
diff --git a/grimoire/build/geometry_patterns.md b/grimoire/build/geometry_patterns.md
index edb0b7d..eeeaf2b 100644
--- a/grimoire/build/geometry_patterns.md
+++ b/grimoire/build/geometry_patterns.md
@@ -133,7 +133,7 @@ A procedural object is usually failing when:
**Curve the small details.** Serrations/scallops/teeth as straight boxes look wrong. Use `ellipsoid` (or slightly canted primitives, alternating ±angle) for rounded scallop teeth. Each detail with its own small cant reads as a hand-ground edge.
-**Grip / friction texture = geometric ridge segments.** For a knurled/wrapped/segmented grip, model raised barrel bands: a thin core cylinder + N short attachment-tube segments (radius just *proud* of the core, small groove gaps). Size them barely larger than the core — oversized tori read as a coil/spring, not a grip. Material texture alone (no geometry) reads as smooth/"thô".
+**Grip / friction texture = geometric ridge segments.** For a knurled/wrapped/segmented grip, model raised barrel bands: a thin core cylinder + N short attachment-tube segments (radius just *proud* of the core, small groove gaps). Size them barely larger than the core — oversized tori read as a coil/spring, not a grip. Material texture alone (no geometry) reads as smooth and coarse at once.
**`invisibleRoot`/container material is still subject to the material-pass PBR gate.** Give the container a *complete* material (roughness map, frequency bands, textureResolution) — copy a proven one — or it fails "needs usable referencePbr / roughness map" even though it never renders.
diff --git a/grimoire/build/implicit_sdf_modeling.md b/grimoire/build/implicit_sdf_modeling.md
new file mode 100644
index 0000000..0f9c9f8
--- /dev/null
+++ b/grimoire/build/implicit_sdf_modeling.md
@@ -0,0 +1,59 @@
+# Implicit SDF Modeling
+
+This is WS1. It gives the generator a code-side implicit surface path for shapes
+that need one welded organic body instead of a stack of separate primitives.
+
+Use it when the reference calls for smooth unions, blended limbs, soft transitions,
+or another form that breaks down if you keep stacking boxes and capsules.
+
+## What the spec carries
+
+The spec uses `component.topologyClass: "implicit"` together with
+`geometryDescriptor.sdf`.
+
+The descriptor is limited to these primitive types:
+
+```json
+{
+ "primitives": [
+ { "id": "torso", "type": "capsule", "radius": 0.28, "height": 1.1 },
+ { "id": "head", "type": "sphere", "radius": 0.34 }
+ ],
+ "operations": [
+ { "type": "smooth-union", "left": "torso", "right": "head", "radius": 0.12, "id": "body" }
+ ],
+ "resolution": 32,
+ "bounds": { "min": [-1.2, -1.6, -1.2], "max": [1.2, 1.6, 1.2] }
+}
+```
+
+Supported primitives are `sphere`, `capsule`, `box`, `cone`, and `ellipsoid`.
+Supported operations are `smooth-union`, `subtract`, and `intersect`.
+
+## Limits
+
+- `primitives` must be non-empty and stay at or below 64 entries.
+- `operations` is optional, but when present it stays at or below 128 entries.
+- `resolution` must stay between 4 and 64.
+- Optional bounds, when present, must have ordered `min` and `max` vectors.
+
+## Generator behavior
+
+The generator samples the SDF, polygonizes it, and recomputes normals on the
+resulting geometry. The output is still procedural code, not an imported mesh.
+
+The emitted geometry keeps the default pipeline unchanged when no SDF block is
+present. Subdivision is not available on the emitted `implicit sdf` path.
+
+## Validation rules
+
+- `geometryDescriptor.sdf` must be structurally valid before codegen.
+- `sdf` and `visualHull` cannot live on the same component.
+- `sdf` and `subdivide` cannot be combined for the implicit path.
+- Primitive and operation ids must stay unique.
+
+## Acceptance criteria
+
+- A torso plus limb fixture emits one welded geometry with continuous normals.
+- Default object-only specs stay byte-identical.
+- Forge unit tests pass and the showcase TypeScript smoke stays clean.
diff --git a/grimoire/build/python_threejs_render_bridge.md b/grimoire/build/python_threejs_render_bridge.md
new file mode 100644
index 0000000..f722726
--- /dev/null
+++ b/grimoire/build/python_threejs_render_bridge.md
@@ -0,0 +1,169 @@
+# Python ↔ Three.js render bridge skill
+
+Use this skill when Python is involved in rendering, inspecting, or batch-capturing a
+procedural Three.js character, including the explicit GLB-mediated reference route.
+
+## Contract
+
+Python is the deterministic controller and evidence producer. The browser-hosted Three.js
+runtime is the rendering authority. A Python image, Blender image, notebook preview, or GLB
+export is not a substitute for a screenshot of the target Three.js route.
+
+## Routing
+
+1. Existing Chrome DevTools MCP available: use it first for runtime capture.
+2. Existing project Playwright dependency or explicit user permission: use Playwright as a
+ cross-browser/headless fallback.
+3. BlenderProc or Blender Python: use only for optional reference passes, synthetic data,
+ preprocessing, or an explicitly requested external asset route.
+4. pythreejs: use for notebook-side parameter exploration; never use it as the final fidelity
+ gate unless the target itself is a pythreejs application.
+
+## GLB-mediated reference route
+
+When the user provides a GLB produced from an image, the GLB is an intermediate reference
+mesh, not the procedural output. The required order is:
+
+```text
+image (optional provenance)
+ -> user/adapter-produced GLB
+ -> probe_glb.py + hash/provenance
+ -> render the GLB through the target Three.js browser route
+ -> reference baseline captures
+ -> derive a procedural ObjectSculptSpec
+ -> generate TypeScript geometry/material/rig
+ -> render the procedural route with the same camera batch
+ -> compare procedural captures against GLB baseline captures
+```
+
+Initialize this route with:
+
+```bash
+python3 forge/stage1_intake/probe_glb.py /path/to/reference.glb
+python3 forge/stage4_review/render_bridge.py init \
+ --reference-glb /path/to/reference.glb \
+ --reference-browser-url /references/reference.glb \
+ --runtime-url http://127.0.0.1:5173/#/character-demo \
+ --out work/character/render-manifest.json
+
+python3 scripts/capture_threejs_playwright.py \
+ --manifest work/character/render-manifest.json --mode reference
+```
+
+The browser route must expose an explicit reference mode that loads the local GLB with
+`GLTFLoader`, applies the same renderer/camera/lighting contract, and captures the GLB baseline.
+The optional Playwright adapter uses `setReferenceMode({kind: "glb", url})` and records those
+images with `render_bridge.py record-reference` semantics. Chrome DevTools MCP integrations must
+provide the same mode switch and write to the same manifest fields. Only then may
+`render_bridge.py diagnose` compare the procedural hero against the baseline.
+
+This route measures agreement with the intermediate GLB. If the original image is not retained,
+it does not prove agreement with the image that produced the GLB; hidden geometry, materials,
+and generation artifacts must be recorded as confidence/approximation notes.
+
+## Capture invariant
+
+Every batch must preserve:
+
+```text
+reference hash + reference kind + runtime URL + viewport/DPR + camera transform + renderer settings
+ + ready evidence + screenshot hash + diagnostics + visual decision
+```
+
+Before accepting a render, reopen the saved screenshot with an image-capable tool. Reject
+background-only, clipped, stale, unreadable, or incorrectly sized files. Capture fixed,
+`±35°`, profile, rear, and head close-up views for a character.
+
+## GLB-mediated v2 passes
+
+Pass `--render-profile docs/specs/render-profile.v2.example.json` to `render_bridge.py init`
+to opt into the v2 fidelity track. The profile is validated once and hashed into the manifest;
+both the GLB reference mode and procedural mode must use it. Record each browser-produced pass
+with:
+
+```bash
+python3 forge/stage4_review/render_bridge.py record-pass \
+ --manifest work/character/render-manifest.json \
+ --capture-id hero --pass-id semantic-id --image work/character/hero/semantic-id.png
+```
+
+Add `--reference` for the GLB baseline pass. The required pass IDs are `beauty`,
+`alpha-silhouette`, `semantic-id`, `depth`, `normal`, and `roughness-material-id`.
+After all paired passes exist, run:
+
+```bash
+python3 forge/stage4_review/compare_region_passes.py \
+ --manifest work/character/render-manifest.json --capture-id hero \
+ --out work/character/hero-pass-comparison.json
+```
+
+The comparison blocks per-region claims when the semantic-ID pass or region colors are absent.
+It is a deterministic diagnostic, not an AI likeness score.
+
+## Failure routing
+
+- no browser/MCP: `request-input` and ask for installation/authentication;
+- runtime not ready or console error: `refine-code`/runtime repair;
+- background-only close-up: repair near/far, target, settle frames, and recapture;
+- degenerate orbit: `refine-code` geometry, not a material tweak;
+- diagnostics pass but semantic identity fails: `refine-code` and list the failed feature;
+- repeated plateau: `refine-spec` or `request-input` for more views;
+- never report confidence >9 without readable head/profile evidence.
+
+## Minimal manifest fields
+
+`schemaVersion`, `reference.kind`, `reference.path`, `reference.sha256`, `runtime.url`, `runtime.viewport`,
+`runtime.devicePixelRatio`, `runtime.renderer`, `captures[]`, each capture's camera transform,
+`readySignal`, screenshot path/hash, diagnostics paths, and final decision.
+
+## Executable alpha path
+
+The 1.5-alpha branch includes a dependency-free manifest controller and an optional Playwright
+adapter. From the repository root:
+
+```bash
+python3 forge/stage4_review/render_bridge.py init \
+ --reference /path/to/reference.png \
+ --runtime-url http://127.0.0.1:5173/#/character-demo \
+ --out work/character/render-manifest.json
+
+# Use Chrome DevTools MCP or the optional adapter to produce the actual browser PNGs.
+python3 scripts/capture_threejs_playwright.py \
+ --manifest work/character/render-manifest.json
+
+python3 forge/stage4_review/render_bridge.py validate \
+ --manifest work/character/render-manifest.json --require-complete
+
+python3 forge/stage4_review/render_bridge.py diagnose \
+ --manifest work/character/render-manifest.json \
+ --out work/character/diagnostics.json
+```
+
+The Playwright adapter is intentionally optional. Install it outside the stdlib core only when
+needed: `python3 -m pip install playwright` followed by `playwright install chromium`. The target
+route must expose this small browser-side contract:
+
+```js
+window.__IMG2THREEJS_READY__ = true;
+window.__IMG2THREEJS_CAPTURE__ = {
+ async setCamera({ azimuthDegrees, elevationDegrees, target, near, far }) {
+ // Apply the camera and controls to the real Three.js scene, then resolve.
+ },
+ async capturePass({ passId, mode }) {
+ // Select beauty/diagnostic render target, settle, and return { ok: true, selector: 'canvas' }.
+ },
+};
+```
+
+If the ready signal, capture contract, canvas, screenshot, or hash check fails, the adapter stops.
+It does not fall back to a Python/Blender image and does not claim that a render happened.
+
+## Prohibited shortcuts
+
+- Do not use Python to claim it rendered Three.js when it rendered Blender instead.
+- Do not copy GLB/VRM topology, vertices, or imported materials into a code-only factory.
+- Do not compare a procedural screenshot directly to an unrendered GLB; the GLB must first produce
+ a fresh baseline screenshot through the same Three.js runtime.
+- Do not compare orbit images to a reference angle that was never supplied.
+- Do not infer visual success from TypeScript compilation, `__READY__`, or an inline preview.
+- Do not add Playwright/Chromium dependencies to the zero-install core without explicit scope.
diff --git a/grimoire/build/subdivision_surfaces.md b/grimoire/build/subdivision_surfaces.md
new file mode 100644
index 0000000..12ebba1
--- /dev/null
+++ b/grimoire/build/subdivision_surfaces.md
@@ -0,0 +1,46 @@
+# Subdivision Surfaces
+
+This is WS3. It adds an opt-in Catmull-Clark refinement pass so a coarse cage can
+become a smooth dense surface without leaving the code pipeline.
+
+Use it when the control cage is right but the surface still needs a cleaner read or
+more even density.
+
+## Spec shape
+
+The spec uses `geometryDescriptor.subdivide.iterations`.
+
+```json
+{
+ "geometryDescriptor": {
+ "subdivide": { "iterations": 2 }
+ }
+}
+```
+
+`iterations` is optional. When it is missing, the generator does not emit the helper.
+
+## Limits
+
+- `iterations` must be an integer from 0 to 4.
+- The projected quad face count must stay at or below 100000.
+- Primitive paths that cannot be budgeted safely, such as open planes or implicit SDF output, are rejected.
+
+## Generator behavior
+
+The generator emits `subdivideCatmullClark`, applies the requested iteration count,
+and recomputes normals after each subdivision pass.
+
+The helper is deterministic. The same input spec produces the same output source.
+
+## Validation rules
+
+- `subdivide` cannot rescue a topology that is already invalid.
+- Non-manifold edges, open boundary edges, and disconnected face fans are rejected.
+- `implicit sdf` output does not use this path.
+
+## Acceptance criteria
+
+- A valid cage gains the expected quad growth per iteration.
+- UV2 data stays in step with the subdivided surface.
+- The showcase TypeScript smoke stays clean after generation.
diff --git a/grimoire/build/visual_hull_reconstruction.md b/grimoire/build/visual_hull_reconstruction.md
new file mode 100644
index 0000000..6547c4b
--- /dev/null
+++ b/grimoire/build/visual_hull_reconstruction.md
@@ -0,0 +1,58 @@
+# Visual Hull Reconstruction
+
+This is WS2. It reconstructs geometry from clean silhouette views, then treats the
+hidden areas as low confidence instead of inventing detail.
+
+Use it when you have at least two clean orthographic-ish masks and the silhouette is
+the main thing that is holding back the model.
+
+## What the spec carries
+
+The spec uses `geometryDescriptor.visualHull` with these fields:
+
+```json
+{
+ "projection": "orthographic",
+ "boundsSpace": "component-local",
+ "bounds": { "min": [-1, -1, -1], "max": [1, 1, 1] },
+ "resolution": 32,
+ "triangleBudget": 400000,
+ "views": [
+ { "axis": "front", "confidence": 0.9, "mask": ["11110000"] },
+ { "axis": "side", "confidence": 0.8, "mask": ["11100000"] }
+ ],
+ "hiddenRegions": ["back", "underside"]
+}
+```
+
+The `views` array needs distinct axes. Valid axes are `front`, `side`, and `top`.
+Each mask is a binary string grid.
+
+## Limits
+
+- At least two views are required.
+- `resolution` must stay between 4 and 32.
+- `triangleBudget` must be positive and stay at or below 400000.
+- The budget must also cover the worst-case triangle count implied by the chosen resolution.
+- Masks must stay within the supported size window and contain foreground pixels.
+
+## Generator behavior
+
+The generator carves the volume from silhouettes, welds the result, and stores the
+visual-hull metadata on the runtime geometry. The emitted source keeps the hidden
+regions visible in the metadata so the review loop can mark them low confidence.
+
+This path does not combine with `sdf` or `subdivide` on the same component.
+
+## Validation rules
+
+- `projection` must be `orthographic`.
+- `boundsSpace` must be `component-local`.
+- Repeated axes are rejected.
+- Contradictory masks fail at runtime with a typed occupancy error.
+
+## Acceptance criteria
+
+- Two clean silhouettes produce a welded mesh whose silhouette matches each view.
+- Hidden regions stay marked low confidence.
+- The turnaround path improves the reference baseline instead of flattening into noise.
diff --git a/grimoire/character/head_construction.md b/grimoire/character/head_construction.md
new file mode 100644
index 0000000..7dd8ac1
--- /dev/null
+++ b/grimoire/character/head_construction.md
@@ -0,0 +1,284 @@
+# Creature Head Construction
+
+Use this alongside `grimoire/character/reconstruction.md` (which fixes body proportions)
+and `grimoire/character/structure_decomposition.md` (which fixes what parts exist). This
+document is about the head specifically, because the head is where likeness lives and
+where proportion error is least forgiving.
+
+The worked case is the Vijay Ghume mini-dragon imp. Every number below was measured off
+the reference pixels, not estimated.
+
+## How these numbers were obtained
+
+Reference: `vijay-ghume-mini-dragon-2.jpg`, the pure front view, 1920×1920.
+
+Background was isolated by flood-filling inward from the image corners. The discriminator
+is specific and worth recording, because a naive threshold eats the horns: the studio navy
+has `b − r = +19…+21` at saturation ≈ 0.42, while the black horn keratin has `b − r =
++2…+9` at saturation 0.09…0.31. A test of `b − r ≥ 13 ∧ max < 78 ∧ sat > 0.32` separates
+them cleanly. Flood-filling rather than thresholding also keeps enclosed dark regions —
+pupils, mouth recess — on the foreground side.
+
+Irises were found by thresholding saturated yellow inside bounded windows so the gold
+jewellery could not contaminate them. Midline landmarks came from a vertical class scan at
+`x = 959`. Widths that cross a *shading* boundary rather than a *silhouette* boundary — the
+skull edge behind the ear, for instance — cannot be scanned and were read off a 25 px
+measuring grid overlaid on the image. Each row below says which method produced it.
+
+**Unit: `HH` = head height = crown to chin at the midline = 377 px.**
+
+## Measured landmarks — front view
+
+| Landmark | Pixel | Method |
+|---|---|---|
+| Horn tip, highest | y = 98 | scan |
+| Crown, top of pink cranium at midline | y = 416 | scan |
+| Frontal boss highlight band | y = 515…526 | scan |
+| Eye line, iris centres | y = 586 | scan |
+| Nostril band | y = 635…655 | grid |
+| Lip ridge at midline | y = 686…690 | scan |
+| Fang tips | y = 705 | grid |
+| Chin / jaw bottom at midline | y = 793 | scan |
+| Iris, left | x 776…876, y 541…629 | scan |
+| Iris, right | x 1038…1141, y 543…631 | scan |
+| Horn bases | centres at x = 959 ± 80, y ≈ 505; ⌀ ≈ 70 | scan |
+| Skull width, widest, ears excluded | 456 | grid |
+| Muzzle width, widest | 395 | grid |
+| Ear tip to ear tip | 830 | grid |
+| Hoof bottom | y = 1620 | grid |
+
+The obvious trap: a naive "lowest foreground pixel" scan returns y = 1816 for the feet.
+That is the cast shadow plus the tail's arrow tip, not the hoof. Cropping the leg region
+and reading it directly gives 1620. The difference moves the head-to-body ratio from 3.7
+to 3.2 head-units, so it matters.
+
+## Proportion table
+
+| Ratio | Value | Reading |
+|---|---|---|
+| **Skull width / HH** | **1.21** | the head is 21% wider than it is tall |
+| Muzzle width / HH | 1.05 | the muzzle is as wide as the head is tall |
+| Ear span / HH | 2.20 | the ears more than double the head's width |
+| Interocular, iris centre to centre / HH | 0.70 | |
+| Interocular / skull width | 0.58 | eyes sit in the outer half of the skull |
+| Iris width / HH | 0.265 | roughly 5× the human relative iris size |
+| Iris aspect, h/w | 0.88 | |
+| **Eye line depth from crown** | **0.45** | eyes sit *above* the head's midpoint |
+| Nostril band from crown | 0.63 | |
+| Lip ridge from crown | 0.72 | |
+| Fang tips from crown | 0.77 | |
+| Chin | 1.00 | by definition |
+| Horn length above crown / HH | 0.84 | |
+| Head + horn total height / HH | 1.84 | |
+| Horn base centre from midline | ±0.21 | |
+| Horn base diameter / skull width | 0.15 | |
+| Ear length / HH | 0.85 | |
+| Ear axis rake off vertical | 29° | |
+| Body height, crown to hoof / HH | 3.19 | **pose-dependent** — see below |
+
+The 3.19 head-units figure is not a design constant. All five reference views share one
+crouched jump pose with the legs folded, so crown-to-hoof is compressed. A proportion
+scaffold should be driven by *segment lengths* (femur, tibia) rather than by posed
+silhouette height.
+
+## The depth axis is not measurable from this reference set
+
+There is no orthographic profile view. View `-4` is a three-quarter, so every depth reading
+is a projection of unknown foreshortening. What can be established:
+
+- The muzzle's frontmost point sits **58 px ahead of the iris centre**, in a view where
+ eye-to-chin is 213 px. Eye-to-chin is 207 px at HH = 377 in the front view, so the two
+ views are within 3% of the same scale. That puts projected protrusion at **0.15 HH**,
+ and correcting for a ~25° turn still only reaches ~0.17 HH.
+- Below the mouth the profile *recedes*: at the chin the frontmost pixel is at x = 142…153
+ against the muzzle's x = 110. **The chin is set back behind the upper lip.**
+- Total head horizontal extent in that view is ≈ 0.62 HH, but the occiput is occluded by
+ the ear and neck, so 0.62 is a lower bound on depth, not a measurement.
+
+**Therefore: muzzle width-to-protrusion ≈ 1.05 / 0.17 ≈ 6 : 1.** This is a wide flat
+frog-or-bat muzzle, not a long dog snout — the single most consequential fact about this
+head, and the one most likely to be got wrong.
+
+Cranium depth is *inferred*, not measured: **0.75–0.85 HH**, confidence moderate. The
+reasoning is that 1.21 HH of width already supplies braincase volume laterally, so depth
+does not need to compensate, while enough depth must remain behind for the neck joint and
+jaw musculature. Treat it as a constrained assumption and validate by projecting the built
+model back onto view `-4` at a matched camera.
+
+## Block construction
+
+Coordinates in HH. Origin at the crown on the midline; **y grows downward**; z forward.
+
+| # | Block | Primitive | Extent | Placement | Join |
+|---|---|---|---|---|---|
+| 1 | Cranium | ellipsoid | W 1.21, H 0.60, D ~0.80 | centre y 0.30 | base form |
+| 2 | Upper muzzle | flattened capsule | W 1.05, H 0.30, D ~0.20 | centre y 0.60 | smooth union, **deliberately overlapping the cranium from y 0.45–0.60** |
+| 3 | Lower jaw / chin | ellipsoid | W ~0.80, H 0.25 | centre y 0.875, pushed back in −z | union, tucked under block 2 |
+| 4 | Frontal boss | diamond wedge | W ~0.20, H ~0.25 | midline, y ≈ 0.26 | smooth union |
+| 5 | Brow ridge | V-shaped tube pair | span ~1.10 | from the boss, sweeping down-and-outward | smooth union |
+| 6 | Eye sockets | ellipsoid | — | x ±0.35, y 0.45 | **subtract** |
+| 7 | Nose pad | small flattened capsule | — | midline, y 0.63 | union, sitting on block 2 |
+| 8 | Lip ridge | hard crease, not a block | full muzzle width | y 0.72, corners lifting | crease |
+| 9 | Fangs ×4 | cones | tips at y 0.77 | from the upper lip, pointing **down** | union |
+| 10 | Ears ×2 | curved wedge shells | L 0.85, span 2.20 | base on the rear half of the skull, rake 29° | union |
+| 11 | Horns ×2 | tapered curved capsules | L 0.84, base ⌀ 0.19 | base x ±0.21, y ≈ 0.24 | union |
+| 12 | Mouth bag | inverted shell | — | behind the lip crease | subtract then shell |
+
+The 0.45–0.60 overlap between muzzle and cranium is intentional, not an error: it is what
+produces the cheek swell and the deep-set eye. Blocks that merely abut produce a seam.
+
+## Design logic — what makes it read as "menacing but appealing"
+
+Getting this backwards is easy, and an earlier pass of this analysis did get it backwards.
+**Eye-line height is a threat cue here, not a cute cue.** Neoteny requires a *large*
+forehead, which means the eye line sits *low* — around 0.50 for a human adult and 0.60 or
+more for an infant. This head measures **0.45**, a smaller forehead than an adult human's.
+That is a predator signal.
+
+**Appeal comes from:**
+- Interocular 0.58 of skull width — eyes pushed into the outer half, which reads as
+ prey-animal or primitive creature rather than a forward-converging hunter
+- Muzzle 1.05 HH wide at 6:1 width-to-depth — a frog-wide mouth, which cancels the wolf
+- Ear span 2.20 HH at 29° rake — oversized sensory organs read as vulnerable
+- Iris 0.265 HH, roughly 5× human relative scale
+- A small cat-like nose pad, and smooth skin with no scales
+
+**Threat comes from:**
+- Eye line at 0.45 — compressed forehead
+- A V-shaped supraorbital ridge overhanging the sockets, tilting the eye axis down-inward
+- Horns at 0.84 HH with a base 0.15 of skull width — heavy, weapon-like, not decorative
+- Four maxillary canines pointing down over a closed lower lip
+
+The balance is structural: a predator's *features* mounted on a wide, flat, big-eared
+*armature*. Remove either side and the design collapses into something ordinary.
+
+## Sensitivity — what breaks likeness fastest
+
+Ranked by how little error it takes to destroy the read:
+
+1. **Muzzle width, 1.05 HH.** Narrow it 10–15% and the frog-wide mouth is gone; the
+ character becomes a hellcat or a generic bat.
+2. **Interocular, 0.58 of skull width.** Bring the eyes below 0.50 and the read flips from
+ creature to primate.
+3. **Muzzle protrusion, ~0.17 HH.** Push past 0.25 HH and it is a dog snout. This is the
+ error a modeller trained on human or canine anatomy will make by reflex.
+4. **Skull width, 1.21 HH.** Drop to 1.0 and the head "grows up" into a goblin or orc.
+5. **Eye line, 0.45.** Raise it to 0.35 and the forehead disappears; the character reads
+ as a troll.
+6. **Horn length 0.84 HH and base 0.19 HH.** Thin or shorten them 20% and the triangular
+ silhouette — horn apex spreading down to the ear tips — falls apart, leaving a child in
+ a costume.
+
+## Topology requirements
+
+For a head that must open its mouth, blink and furrow its brow:
+
+- **≥ 4 concentric loops around each eye**, packed tightly at the lid margin.
+- **≥ 3 concentric loops around the mouth**, flowing continuously from the outer lip into
+ the inner mouth bag so no lighting seam forms at the lip.
+- **≥ 3 horizontal compression loops across the muzzle bridge**, so the surface can
+ accordion when the character snarls instead of collapsing.
+- **Poles at every horn and ear base.** Use a downward-pointing four-point transition to
+ step a 12-point cylinder down to 8 points. Without this, loops from the appendages
+ propagate down the neck and into the body.
+
+## Ear structure
+
+Five cartilage landmarks carry the read: helix (the folded outer rim), antihelix (the
+inner raised ridge, forking into two branches), concha (the deep bowl), tragus and
+antitragus. At 0.85 HH long, this ear needs three geometry layers — front surface, back
+surface for thickness, and extruded ridges for the antihelix. The concha bowl should recess
+roughly **0.15–0.20 HH** into the temporal mass; shallower and the ear reads as a flat
+paddle.
+
+## Jaw hinge
+
+The lifted mouth corners at 0.72 HH, the set-back mandible and the downward maxillary
+canines together imply a **low-set temporomandibular joint** — at or slightly below the
+occlusal plane, the configuration that favours a fast, wide gape over crushing force.
+
+If the mouth needs to open, place the jaw rotation axis at approximately:
+
+- y = 0.72–0.75 HH
+- z = −0.10 to −0.20 HH behind the skull centre, leaving room for the temporalis lever
+- x = ±0.45–0.50 HH, out at the skull's lateral edge
+
+## Build order
+
+Steps marked **[likeness]** tolerate no more than ~5% error; the rest can be refined later.
+
+1. **[likeness] Primary blocks.** Cranium, upper muzzle, lower jaw. Check from *top and
+ bottom* views, not just front — the plan-view outline must be a flattened oval at
+ roughly 1.5:1 width-to-depth. This is where the dog-snout error gets caught.
+2. **[likeness] Eye line and sockets.** Fix y = 0.45, interocular 0.70 HH, then subtract
+ the sockets.
+3. **Brow and boss.** Add the midline diamond, sweep the V ridge down-and-outward. Check
+ that the eye axis now tilts down-inward.
+4. **[likeness] Silhouette appendages.** Horns at x ±0.21 running 0.84 HH; ears on the rear
+ half of the skull at 29° rake, 2.20 HH span. Judge these as a black silhouette only.
+5. **Creases and small forms.** Lip ridge at 0.72, nose pad at 0.63, four fangs with tips
+ at 0.77. The lip is a *crease*, never a pair of fleshy human lips.
+6. **Validate.** Project the model back onto view `-4` at a matched camera to test the
+ depth assumption, which is the only axis the reference cannot pin down.
+
+## Skills to develop, in order
+
+1. **Camera matching.** Needed because the reference set has no clean profile, so depth can
+ only be validated by projection. *Exercise:* put a box in the scene, load view `-4` as a
+ backplate, and adjust rotation and FOV (35–50 mm range) until the box edges agree with
+ the character's perspective. *Passing:* you can lock a camera that makes the reference
+ silhouette overlay the model consistently.
+2. **Non-human proportion control.** Human-anatomy habit forces a round skull and a
+ protruding snout. This head is 1.21 wide and ~0.8 deep. *Exercise:* sculpt a frog or a
+ ray head; scale on X with Y locked. *Passing:* your top-view outline measures the target
+ ratio without you correcting it afterwards.
+3. **Prognathic head framing.** A human Loomis has a vertical temple slice; this skull needs
+ a horizontal one. *Exercise:* draw the slice plane and the C-curve from ear through
+ cheekbone to chin. *Passing:* the zygomatic angle visibly bisects that C-curve.
+4. **Hybrid anatomy blending.** Joining a reptile's sloped frontal deck to a broad
+ mammalian cheek. *Exercise:* build the nasal deck as a flat plane driving into the wide
+ zygomatic mass. *Passing:* the transition reads as one skull, not two glued halves.
+5. **Hard creases on organic surfaces.** The lip ridge and lid margins are sharp on
+ otherwise soft skin with no scales. *Exercise:* cut a deep crease across a smooth sphere
+ without pinching artefacts at either end. *Passing:* the crease holds under smooth
+ shading and subdivision.
+6. **Deformation topology and appendage transitions.** *Exercise:* retopologise the face
+ mask to 4 eye loops, 3 mouth loops, 3 muzzle compression loops; terminate horn and ear
+ bases with four-point poles. *Passing:* a 45° jaw open produces no stretching at the
+ mouth corners, and no loop from a horn reaches the neck.
+
+## Acceptance rubric
+
+Ten points. **Pass is > 9.0.** The reference head scores 10.
+
+| # | Criterion | Weight | Full marks | Zero |
+|---|---|---|---|---|
+| 1 | Frame widths | 3.0 | skull W 1.19–1.23 HH and muzzle W 1.03–1.07 HH | muzzle W < 1.0 HH |
+| 2 | Eye placement | 2.5 | eye line y 0.44–0.46 HH and interocular 0.56–0.60 of skull width | eye line y > 0.50, or interocular < 0.50 |
+| 3 | Facial flatness | 1.5 | muzzle protrusion 0.15–0.18 HH, width-to-depth ≈ 6:1, chin behind the upper lip | protrusion > 0.25 HH |
+| 4 | Appendage silhouette | 1.5 | horn 0.81–0.87 HH, ear span 2.15–2.25 HH, rake ≈ 29° | −1.0 per failure |
+| 5 | Threat detail | 1.5 | four **upper** canines pointing down (0.5), V brow ridge (0.5), lip crease at y 0.72 (0.5) | fangs rising from the lower jaw scores 0 for that item |
+
+Weights sum to 10.0. Each criterion is checkable by measurement, not opinion — which is
+what makes a 9 mean something.
+
+## Eight common failures
+
+| Failure | Visible sign | Fix |
+|---|---|---|
+| Dog snout | muzzle juts forward in three-quarter view | flatten in z until width:depth ≈ 6:1 |
+| Convergent eyes | eyes drift toward the midline; creature reads as a primate | restore interocular to 0.70 HH |
+| Lost forehead | reads as an adult goblin or troll | keep y 0…0.45 clear above the eye line |
+| Orc fangs | canines rise from the mandible | remove them; hang four from the maxilla, tips at y 0.77 |
+| Human lips | upper and lower lips carry volume | flatten to a single crease at y 0.72 |
+| Underbite | chin level with or ahead of the upper lip | push the mandible back in −z and blend into the neck |
+| Wrong nose | a raised bridge or a bulbous tip | flatten to a pad with two keyhole nostrils |
+| Narrow horn base | horns cluster on the crown like cattle | separate the bases to x ±0.21 and widen to ⌀ 0.19 HH |
+
+## Gate notes
+
+Criteria 1–3 are numeric and belong in the spec validator: they can be checked against the
+emitted `RigSpec` and geometry bounds without rendering anything. Criterion 4 is a
+silhouette check and belongs with Divine Eye. Criterion 5 is a part-inventory check — the
+four maxillary canines must exist as L2 parts with the correct parent bone, per
+`structure_decomposition.md`.
diff --git a/grimoire/character/structure_decomposition.md b/grimoire/character/structure_decomposition.md
new file mode 100644
index 0000000..697fcb6
--- /dev/null
+++ b/grimoire/character/structure_decomposition.md
@@ -0,0 +1,238 @@
+# Character Structure Decomposition
+
+Use this reference when `objectClass.primaryDomain` is `character` or `hybrid`, alongside
+`grimoire/character/reconstruction.md`. That document fixes *proportions and landmarks*;
+this one fixes *what parts exist and how each one is built and rigged*.
+
+A character that has every part but no layer discipline produces the same failure every
+time: rigid jewellery clipping through skin, membranes tearing at seams, holes that were
+modelled as geometry instead of subtracted, and details invented from nothing. The layer
+system exists to make each of those a classification error you can catch, not a judgement
+call.
+
+## The Layer Ontology
+
+Nine layers. Every part of every character belongs to exactly one **primary geometry
+layer** and may additionally carry **modifier layers**.
+
+| Layer | Definition | Membership test | Build method | Rig treatment |
+|---|---|---|---|---|
+| **L-1 Proportion Scaffold** | Bounding volumes + head-unit system that fix overall silhouette | Not a part — a constraint every part is clamped into | Math bounds only | none |
+| **L0 Core Volume** | The continuous central mass: head, torso, limbs | Crosses joints; cannot be detached | Implicit SDF smooth-union → marching cubes | `SkinnedMesh`, spatial `W(p)` falloff |
+| **L1 Deformable Appendages** | Elongated parts extending off L0 that must bend along their length: tail, wings, long ears | Crosses joints; has its own bone chain reaching outside the core volume | Sweep / loft along a spline | `SkinnedMesh`, same skeleton, same `W(p)` |
+| **L-Void Negative Space** | Subtractive volumes: mouth cavity, ear concha, torn hems, pierced holes | Produces no visible surface; only removes | SDF difference / CSG subtract | none |
+| **L2 Internal Cavities** | Parts that sit inside an L-Void: eyes, teeth, tongue, gums | Only visible because something was subtracted | Primitives, inverted-normal shells | Tongue skinned; eyes/teeth single-bone (see L3) |
+| **L3 Single-Bone Isolates** | Anything whose whole extent lies inside one bone's dominant region: horns, claws, hooves, cuffs, rings, tail spade | **Does not cross a joint** | Primitives, lathe, extrude, boolean | `SkinnedMesh` with weight forced to `(1,0,0,0)` |
+| **L4 Cross-Joint Shells** | Offset layers over L0 that span a joint: loincloth, tunic, cape, armour plates spanning a limb | Crosses joints, sits outside the skin surface | Offset shell from L0 + trim | `SkinnedMesh`, spatial `W(p)` |
+| **L5 Surface Markings** | Colour that does not change silhouette: stripes, scars, tattoos, gradients | Zero geometric footprint | Shader mixing on spatial function (§ Markings) | inherits host mesh |
+| **L6 VFX / Ephemera** | Non-material elements: fire, smoke, glow | No solid geometry at all | Sprites, particles, scrolling-UV meshes | Emitter parented to a bone |
+| **L-Proxy Collision** | Invisible primitives for raycast/physics | Never rendered | Box / capsule / sphere | Parented to bones; already modelled by `root.userData.sculptRuntime.colliders` |
+
+## The Classification Test That Actually Matters
+
+The naive test is "is this part hard or soft?" That test is wrong and it produces the
+clipping bug.
+
+The real test is **does this part cross a joint?**
+
+Because weights are a pure spatial function `W(p_world)` (see
+`docs/PLAN_1.5_ANIMATION_READY_RIGS.md` §3), a mesh lying entirely inside one bone's
+dominant region *automatically* receives `≈(1,0,0,0)` and therefore *automatically* moves
+rigidly. Rigid and skinned converge. There is no second code path.
+
+Consequences:
+
+- A gold cuff placed mid-forearm is skinned, and moves rigidly anyway. Nothing special
+ needed.
+- A gold cuff placed **at the wrist** picks up a blend of forearm and hand — the metal
+ visibly squashes. Fix: tag it `L3` and **override** every one of its vertices to weight
+ `1.0` on the bone nearest its bounding-box centre, bypassing the falloff. It stays a
+ `SkinnedMesh` sharing one shader; it is simply permanently rigid.
+- Do **not** solve clipping by making rigid parts skinned in the general case. That
+ trades a clipping bug for a stretching-metal bug.
+
+Soft goods (L4) need the opposite reasoning. A loincloth sits 1–2 cm off the skin, so its
+vertices are not coincident with skin vertices — but that offset is deep inside the
+hip/thigh envelope, so `W(p_cloth) ≈ W(p_skin)` and the cloth follows the leg correctly
+without copying weights from anywhere. If the cloth gets its own secondary bones for
+sway, those bones join the **same** skeleton but must be given a very small envelope
+radius, so no skin vertex ever falls inside their influence.
+
+## Primary + Modifier Rule
+
+Some parts genuinely feel like they belong to two layers. Resolve it, don't debate it:
+
+> Each part is assigned exactly **one** primary geometry layer (L0, L1, L2, L3, L4, L6),
+> which determines how it is built and skinned. It may additionally carry any number of
+> **modifier** layers (L-1, L-Void, L5, L-Proxy).
+
+- Ear = primary **L1** + modifier **L-Void** (concha cavity)
+- Loincloth = primary **L4** + modifier **L-Void** (torn hem)
+- Tail spade and tail ring = primary **L3**, parented to the last bone of the tail's L1
+ chain — a rigid tip on a deformable chain is not ambiguous, it is two parts
+- Purple shoulder stripes = modifier **L5** on the L0 host
+
+## Ontology Order ≠ Execution Order
+
+The table above reads inside-out. The build DAG does not. In particular L-Void must enter
+the SDF **before** meshing, so it cannot run "after" L1.
+
+1. **Scaffold** — establish L-1 bounds; derive joint positions.
+2. **Field construction** *(parallel)* — build the SDF equations for L0, L1, L4. No
+ surfaces yet.
+3. **Subtraction** *(choke point)* — apply every L-Void operator to those fields.
+4. **Meshing** — marching cubes / dual contouring → `BufferGeometry`.
+5. **Discrete geometry** *(parallel)* — instantiate L2 and L3 primitives.
+6. **Skinning** — evaluate `W(p_world)` for every vertex; apply L3 weight overrides;
+ attach L-Proxy colliders.
+7. **Appearance** — apply L5 shader mixing and L6 emitters.
+
+## Markings Without Textures
+
+L5 must not use vertex colours on an implicit-surface mesh. Marching-cubes topology is
+irregular, so vertex-interpolated colour bands and produces jagged transitions instead of
+a gradient.
+
+Mix in the shader from a spatial function instead, via `onBeforeCompile`:
+
+```glsl
+// object-space gradient, e.g. magenta body → orange muzzle/chin
+float g = smoothstep(zStart, zEnd, vPosition.z) * smoothstep(yStart, yEnd, -vPosition.y);
+diffuseColor.rgb = mix(colorBase, colorAccent, g);
+```
+
+This is topology-independent, needs no texture file, and stays diffable.
+
+## Layers Deliberately Excluded
+
+Studio pipelines carry these; a code-only Three.js generator should not.
+
+| Excluded | Why |
+|---|---|
+| Strand-level hair / fur / feather grooming | Draw-call and simulation cost far beyond a code generator. Force it into solid masses under L1 or L3 |
+| Secondary/tertiary form passes (wrinkle maps, pore maps) | Requires multi-million-poly sculpting and baking. Approximate in L5 material terms |
+| LOD chains | Real in AAA, but the pipeline has no LOD concept and a showcase does not need one. Revisit only if a demo demonstrably needs it — do not make it a handoff gate |
+| Bone naming as a *layer* | It is a rule, not a layer. Enforce it in L-1 metadata |
+
+## Worked Coverage Test — stylized imp / mini-dragon
+
+Reference: `vijay-ghume-mini-dragon-{ref,1..5}.jpg` — 2D concept plus five 3D views
+(front, front-¾, rear-¾, side, rear). This character is the stress test for the system
+because it contains at least one part from every layer.
+
+| Part | Primary | Modifiers | Build | Bone | Material zone |
+|---|---|---|---|---|---|
+| Head, torso, arms, legs | L0 | L-1, L5 | SDF smooth-union | spine / limb chains | magenta skin |
+| Tail (root → pre-tip) | L1 | — | curve sweep | tail chain | magenta skin |
+| Wing membranes ×2 | L1 | L-Void (ragged trailing edge) | surface spanned between spar splines | wing chains | pink membrane |
+| Wing leading edge + 3 spars ×2 | L1 | — | tube sweeps | wing chains | black |
+| Ears ×2 | L1 | L-Void (concha) | flattened cone shell | ear bones | magenta / orange inner |
+| Mouth bag | L2 | depends on L-Void | inverted-normal shell | head / jaw | dark interior |
+| Eyes ×2 | L2 | L5 (iris/sclera) | spheres | eye or head | yellow-orange iris, violet corner |
+| Fangs — 4 upper canines pointing **down**, 2 per side | L2 | — | cones | maxilla / head | white |
+| Horns ×2 (long, swept back) | L3 | — | tapered tube | head | black |
+| Hand claws | L3 | — | curved cones | finger bones | black |
+| Wing wrist claws ×2 | L3 | — | curved cone | wing wrist | black |
+| Cloven hooves ×2 | L3 | — | split solid | foot bones | black |
+| Ear hoop | L3 | — | torus | ear bone | gold |
+| Neck strap + hanging ring pendant | L3 | — | torus + strap loop | chest / neck | brown leather, gold |
+| Forearm cuffs ×2 (gold ring / black band / gold ring) | L3 | — | stacked cylinders | lower arm | gold + black |
+| Ankle rings ×2 | L3 | — | cylinder | lower leg | gold |
+| Tail ring | L3 | — | cylinder | tail tip | gold |
+| Tail spade | L3 | — | extruded arrow | tail tip | pink |
+| Loincloth + brown belt | L4 | L-Void (torn hem, open back) | offset shell + trim | hips (+ optional sway bones) | navy cloth, brown leather |
+| Purple stripes (3 per upper arm, 2 per scapula) | — | L5 on L0 | shader mix | inherits | violet |
+| Fire | L6 | — | sprites / particles | head, hips, wrists, tail | emissive |
+| Hitboxes | L-Proxy | — | capsules | major bones | not rendered |
+
+### Two findings this test surfaced
+
+- **There is no mane.** The black mass appearing between the horns in the rear-¾ view is
+ the far wing folded forward — it has a hook (the wing wrist claw) and a sliver of pink
+ membrane beside it. The pure rear view shows the nape and spine are smooth pink. A
+ generator that emits a mane is hallucinating; reject it.
+- **There are no scales.** All five 3D views show completely smooth skin with soft muscle
+ forms only. The demo's `dragon-skin_*` / `dragon-body-skin_*` texture set contradicts the
+ reference and should not be carried forward.
+
+### Measured proportions
+
+Total height `H` = crown to hoof, **excluding horns and wings**. These are read off the
+front and rear views; the inferred rows are marked because the pose foreshortens them.
+
+| Measure | Ratio of H | Source |
+|---|---|---|
+| Head height | **0.33** | measured |
+| Skull width (no ears) | 0.25–0.28 | measured |
+| Total width including flared ears | 0.45–0.50 | measured |
+| Neck length | 0.05 | measured — chin nearly on chest |
+| Torso, shoulder → hip | 0.35 | measured |
+| Leg, hip → hoof | 0.27 | measured |
+| Shoulder span | 0.35 | measured |
+| Arm, shoulder → wrist | ~0.45 | inferred (foreshortened) |
+| Wingspan | 1.5–1.8 | inferred (wings folded) |
+| Tail length | 0.8–0.9 | inferred (curled) |
+
+Total ≈ **3 head-units** — the chibi/figurine end of the scale in
+`reconstruction.md`. Head height + neck + torso + legs sums to 1.00, which is the
+consistency check.
+
+**Use skull width, not total width, for the L-1 scaffold.** Ears are L1 and are explicitly
+allowed to extend beyond the core volume's bounds. Scaffolding to the ear span produces a
+head like a barrel.
+
+### Material recipe for smooth stylized skin
+
+`MeshPhysicalMaterial`: `roughness` 0.5–0.6, `metalness` 0.0, `clearcoat` 0.15 with
+`clearcoatRoughness` 0.6, `sheen` 1.0 with a pink-violet `sheenColor` for the rim
+falloff.
+
+Forbidden for this character: any noise-derived `normalMap` or `bumpMap`. The surface
+reads as smooth rubber; let the subdivided geometry carry the form.
+
+## Structural Completeness Checklist
+
+A character is structurally complete when all of the following hold. Every line is
+checkable by code or by direct inspection.
+
+1. Every component in the spec maps to exactly one primary geometry layer.
+2. The core volume's bounding box fits entirely inside the L-1 proportion scaffold.
+3. Every L-Void operator was applied to the SDF **before** meshing, not after.
+4. No degenerate faces (area ≈ 0) along any L-Void-trimmed edge.
+5. Bone names follow the project naming convention and are unique.
+6. Every bone's `scale` is `(1,1,1)` at bind pose, with identity rest rotation.
+7. No vertex has more than four non-zero influences.
+8. Every vertex's weights sum to 1.0 within `1e-5`, and no vertex has a zero sum.
+9. Every L3 part, and every rigid L2 part, carries a forced single weight of 1.0.
+10. At L0↔L1 seams, paired vertices are spatially coincident within `1e-4`.
+11. Pose sweep passes: at 90° joint flexion the bounding sphere neither collapses nor
+ diverges, and no vertex lands on the origin.
+12. Every joint centre lies inside the built volume (allow ≤5% of bbox outside for parts
+ under armour or clothing).
+13. No L4 shell clips through L0 anywhere in the pose sweep.
+14. L-Proxy colliders exist for every physics- or raycast-relevant bone, exposed through
+ `root.userData.sculptRuntime.colliders`.
+15. Every part in the spec traces to an `evidenceRef` in an admitted reference view — and
+ any part that cannot is deleted, not guessed.
+
+## Predicted Failure Points
+
+The three things a generator gets wrong most often on a character like this:
+
+- **Wing membrane built as a flat sheet intersecting the spar tubes** instead of a surface
+ spanned *between* the spars. Detect by checking normals at the membrane–spar boundary: a
+ sudden perpendicular flip is an intersection, not an organic join.
+- **Degenerate polygons along the torn loincloth hem**, from the boolean trim. Detect by
+ scanning triangle areas on the emitted geometry.
+- **Inner thighs webbing together.** The legs are short and thick, so left and right thigh
+ are spatially close at bind pose and the spatial falloff bleeds weight across. Detect in
+ the pose sweep: lift one leg and measure displacement on the other. If the planted leg
+ moves, the envelope overlap factor `F` is too high.
+
+## Gate Notes
+
+Layer assignment is spec data and must be validated in
+`forge/stage2_spec/validate_sculpt_spec.py` — a part with no primary layer, or with two,
+is a rejected spec. Items 6–13 of the checklist are exactly what the pose-sweep rig gate
+in `docs/PLAN_1.5_ANIMATION_READY_RIGS.md` §7 measures; item 15 is the existing
+detail-inventory evidence discipline applied to structure.
diff --git a/grimoire/character/stylized_hair_threejs.md b/grimoire/character/stylized_hair_threejs.md
new file mode 100644
index 0000000..2f2cbeb
--- /dev/null
+++ b/grimoire/character/stylized_hair_threejs.md
@@ -0,0 +1,225 @@
+# Stylized 3D Hair for Three.js
+
+Version: 1.0
+Scope: code-only procedural character hair, Three.js r169 / WebGL, fixed hero view plus meaningful orbit views.
+Target case: Zenonia Chronobreak warrior.
+
+## Provenance and distillation status
+
+NotebookLM deep research was completed for this topic under notebook `d397a9fe-a8a8-49d8-92ac-56eb92e623c3` and research task `560deabc-c7d1-4c5c-be68-c5548c9b3087`. NotebookLM reported 120 imported sources. The local facts supplied to that notebook were sanitized and contained only visual observations; internal workspace paths were not uploaded.
+
+The NotebookLM `ask` distill response was submitted but could not be read back after the environment's escalation usage limit was reached. Therefore this file is an explicitly labelled local distillation of the completed research task, the imported-source summary, the sanitized reference facts, and the official Three.js/paper sources listed below. It is not claimed to be a verbatim NotebookLM answer. Refresh this document with a successful NotebookLM ask before treating it as a final research publication.
+
+## 1. Requirement classification
+
+| Label | Zenonia hair requirement or decision | Evidence / confidence |
+|---|---|---|
+| REQUIREMENT | Keep the model code-only and procedural; do not download hair meshes or art packs. | img2threejs contract; high |
+| REQUIREMENT | Support the installed Three.js r169 / WebGL runtime. | project constraint; high |
+| REQUIREMENT | Review a fixed hero view and at least two non-degenerate orbit views. | img2threejs visual gate; high |
+| OBSERVATION | The hairstyle is a large blonde crown mass made of broad layered locks, not realistic individual fibers. | sanitized multi-view facts; high |
+| OBSERVATION | Front bangs frame the face; the eyes must remain readable in the hero view. | sanitized multi-view facts; high |
+| OBSERVATION | Three-quarter/profile views show real depth, rear locks and overlap. | sanitized multi-view facts; medium-high |
+| INFERENCE | A hybrid clustered-lock system is a better representation than a strand groom or one flat card. | synthesis of observations and implementation research; high |
+| IMPLEMENTATION | Use a scalp mass, custom tapered volumetric ribbon locks, and curved tube/loft locks for secondary depth. | geometry decision; high |
+| APPROXIMATION | Hidden backside topology, exact strand count and exact fiber scattering are not observable and must be parameterized as inferred. | multi-view coverage; medium |
+| ACCEPTANCE | Geometry and material are evaluated separately; a blonde shader cannot compensate for a wrong silhouette or detached lock. | review policy; high |
+
+## 2. Hairstyle taxonomy and route selection
+
+### Clustered anime/spiky locks
+
+Visual signature: a few large, deliberate masses with tapered tips, controlled asymmetry and readable negative space. The silhouette is designed in image space but each lock has enough depth to survive an orbit.
+
+Recommended representation: custom tapered ribbon/loft geometry around a 3D centerline, backed by a low-poly scalp mass.
+
+Failure mode: cones or repeated straight spikes create a porcupine silhouette; identical lengths and angles destroy the reference's designed rhythm.
+
+### Ribbon or strip locks
+
+Visual signature: broad graphic surfaces with a strong front-facing contour and a narrow edge profile.
+
+Recommended representation: custom `BufferGeometry` with two or more width samples per curve section, front/back faces, side thickness, UVs and stable normals. This is the primary route for the Zenonia crown and bangs.
+
+Failure mode: a single flat extruded panel reads as a petal or card. The ribbon needs a changing width, thickness, normal frame and root overlap.
+
+### Curve-tube locks
+
+Visual signature: round or semi-round secondary strands that wrap around the scalp and preserve profile depth.
+
+Recommended representation: `CatmullRomCurve3` plus `TubeGeometry`, or a custom elliptical tube when the section needs to be flattened or tapered. Three.js `TubeGeometry` takes one constant constructor radius, so a procedural taper requires per-ring scaling or custom geometry.
+
+Failure mode: constant-radius tubes look like noodles; an overly small radius produces wires; too many radial segments make stylized hair visually soft and expensive.
+
+### Hair cards
+
+Visual signature: many thin locks or wisps represented by alpha-cut planes.
+
+Recommended representation: small numbers of oriented cards with an alpha map and hard cutout (`alphaTest`) for micro-strands only.
+
+Failure mode: transparent cards sort incorrectly, self-overlap, or reveal their plane at orbit angles. Three.js documentation explicitly treats perfect transparency as difficult; alpha-tested cutouts are safer when the edge can be hard.
+
+### Shell/fur layers
+
+Visual signature: dense short fur or fuzzy volume produced by concentric shells and alpha detail.
+
+Recommended representation: layered shells with alpha-tested textures.
+
+Failure mode: overdraw, sorting, noisy silhouette and excessive detail. This is inappropriate for the broad, graphic Zenonia crown except perhaps for a tiny soft root fringe.
+
+### Groomed individual strands
+
+Visual signature: realistic fiber field, many fine curves, anisotropic strand highlights and natural clumping.
+
+Recommended representation: strand curves, cards, or a dedicated hair renderer.
+
+Failure mode: high authoring/runtime cost and poor return for stylized reference matching. Physical hair scattering improves material realism, not the large-scale crown silhouette.
+
+### Hybrid route selected for Zenonia
+
+Use one continuous scalp/crown mass, 10–16 primary custom ribbon-loft locks, 4–6 front bangs, 8–14 secondary curved locks, and optional 0–24 micro-cards only where a screenshot proves they are needed. The counts are starting ranges, not a universal rule; fit them to the silhouette and performance budget.
+
+## 3. Zenonia hair analysis
+
+### Observable
+
+- Blonde/golden palette with soft highlight bands and darker occlusion between locks.
+- Broad crown volume with locks rising upward and fanning outward from a central root region.
+- Front bangs are separated and frame the face.
+- Side and rear locks change the silhouette in three-quarter/profile views.
+- Tips are tapered, curved and varied in length and direction.
+- Roots visually merge into the scalp/crown mass; floating pieces are not acceptable.
+- Stylization depends on large readable masses more than individual fiber count.
+
+### Inferred construction
+
+- The crown should be layered front-to-back: rear mass first, middle silhouette locks second, bangs last.
+- Each primary lock should have 3–5 control points, a broad root, a narrowing middle, a near-zero tip width and small twist.
+- The scalp mass should be hidden but overlap each root enough to prevent visible seams.
+- A slight lock-to-lock color variation is useful, but the palette must remain a unified warm blonde family.
+- The rear topology and exact number of strands remain medium-confidence inference; validate them from orbit renders rather than treating them as reference truth.
+
+### Hair/face constraints
+
+- No primary bang may cross both eye centres in the hero view.
+- A bang may overlap a small part of the forehead or outer eye region only if the reference shows it.
+- The nose-to-hair clearance visible in profile must remain open.
+- Hair depth should be visible in the positive and negative orbit, but the head must not become hollow between locks.
+
+## 4. Three.js design recipe
+
+### Build order
+
+1. Create the head-local scalp/crown mass.
+2. Add rear locks that establish depth and back silhouette.
+3. Add primary crown locks with custom tapered ribbon-loft geometry.
+4. Add side locks and front bangs with explicit face-occlusion limits.
+5. Add secondary tube/elliptical locks only where they improve profile or root continuity.
+6. Tune hair materials and lighting after silhouette review.
+7. Add micro-cards or instanced wisps only after a screenshot shows a missing scale band.
+
+### Custom tapered ribbon-loft
+
+For each sampled centerline point, compute a tangent `T`, a stable side vector `B`, and a surface normal `N`. Emit front/back vertices using width `w(t)` and thickness `d(t)`, connect adjacent sections, assign `u` across the lock and `v` along its length, then compute normals. Use a stable frame or parallel-transport-like update when the tangent approaches the world-up vector; do not allow the frame to flip at a bend.
+
+Recommended profiles:
+
+```text
+width: 1.00 -> 0.80 -> 0.40 -> 0.03
+thickness: 1.00 -> 0.75 -> 0.35 -> 0.08
+```
+
+Those are normalized shape profiles, not world-unit constants. The first section should be embedded into the scalp; the last section should be capped or closed cleanly.
+
+### When to use each Three.js primitive
+
+- `CatmullRomCurve3`: control a lock centreline through artist-readable points.
+- `TubeGeometry`: secondary rounded locks; scale ring radii manually for taper, or author an elliptical custom section.
+- `ExtrudeGeometry`: small fixed graphic trims or a temporary blockout, not the final crown system.
+- `BufferGeometry`: primary crown/bang locks, because width, thickness, twist and normals must vary per section.
+- `InstancedMesh`: repeated micro-strands that share geometry and material; never use it to hide different primary silhouettes inside one generic instance.
+- Hair cards: only hard-cut micro detail, with controlled orientation and `alphaTest`; avoid large transparent overlapping planes.
+
+### Material route
+
+Start with a non-metal physical material: `metalness: 0`, mid roughness, restrained `sheen`, warm sheen colour and moderate specular intensity. Use darker materials or vertex/lock colour at roots and occluded overlaps. Material tuning cannot repair wrong lock topology.
+
+The physically based hair literature explains tangent-oriented highlights and multiple scattering lobes, but a full Marschner implementation is beyond the current r169/WebGL scope. A custom tangent-aware shader is a later material experiment, not a prerequisite for fixing Zenonia likeness. TSL/WebGPU should remain optional because the current deliverable is WebGL r169.
+
+## 5. Parameter contract
+
+The machine-readable contract lives in `grimoire/character/threejs_hair_parameter_contract.json`. It is intentionally head-local and deterministic so a script can generate both a spec artifact and TypeScript factory inputs.
+
+Coordinate convention:
+
+- `headHeight = 1` is the visible head height from crown scalp to chin.
+- `x` is character-left/right, `y` is up, `z` is forward.
+- `root` and `controlPoints` are in head-local units.
+- Camera fit parameters are separate from geometry parameters.
+- Values labelled as starting ranges must be fitted against screenshots, not copied as universal constants.
+
+Important fields:
+
+- `scalpMass`: ellipsoid/low-poly anchor that receives roots.
+- `locks[].family`: `primary`, `bang`, `secondary`, `rear` or `micro`.
+- `locks[].layer`: depth ordering for deterministic assembly.
+- `locks[].controlPoints`: 3–5 centreline points in head-local space.
+- `locks[].widthProfile` and `thicknessProfile`: normalized profiles from root to tip.
+- `locks[].rootEmbedDepth`: overlap into the scalp mass, not a visual gap.
+- `locks[].twistDegrees`: controlled section rotation, clamped to avoid flips.
+- `locks[].visibility`: hero-view eye/face occlusion constraints.
+- `materials`: base, root shadow and highlight variants.
+- `lod`: sample/radial budgets for hero and orbit views.
+- `reviewCameras`: fixed plus positive/negative orbit contracts.
+
+## 6. Acceptance and diagnosis
+
+### Fixed hero view
+
+Inspect the saved PNG, not an inline preview. Score separately:
+
+- crown top/side silhouette;
+- width and spacing of primary locks;
+- bang-to-eye clearance;
+- root continuity;
+- taper and tip direction;
+- warm blonde palette and root occlusion.
+
+### Two orbit views
+
+Use one positive and one negative orbit. Confirm the crown retains volume, rear locks remain attached, the profile has a believable depth order, and no flat card or hollow head is exposed.
+
+### Side-by-side and semantic review
+
+Create a side-by-side sheet with the matching reference view. Use semantic feature labels rather than a single global score: `crown-silhouette`, `bang-eye-clearance`, `side-depth`, `rear-attachment`, `root-continuity`, `tip-taper`, `hair-palette`.
+
+### Pixel/feature review
+
+Use hair-specific ROIs or a visible-footprint comparison. A global 64×64 score can miss a bang that covers an eye or a small detached root. Do not use isolation renders that show geometry hidden in the reference; measure the visible footprint instead.
+
+### Background warning
+
+Brown studio gradients can be classified as foreground by simple segmentation. In that condition, IoU/area/aspect results may look excellent while measuring the background rather than the hair. Use a neutral, separable capture background or an explicit foreground mask for diagnosis, and record the warning instead of claiming a visual pass.
+
+## 7. Ordered implementation backlog
+
+1. Add a dedicated hair parameter object to the Zenonia model factory; keep it separate from renderer objects.
+2. Implement `createTaperedHairRibbon()` with a stable frame, variable width, thickness, twist, UVs and normals.
+3. Replace crown/bang `ExtrudeGeometry` blades with parameterized volumetric ribbon locks.
+4. Keep `TubeGeometry` only for secondary/profile locks and apply true ring taper.
+5. Add scalp overlap and root shadow material; remove any lock that floats or terminates visibly at the scalp.
+6. Encode eye-clearance constraints and reject/adjust any front lock that crosses both eye centres in the fixed camera.
+7. Tune non-metal blonde hair material only after the geometry review.
+8. Capture fixed plus two orbit PNGs, read them back with the image-capable tool, create the comparison sheet, run semantic/pixel feature checks and `diagnose_render.py`, then record the honest next action.
+
+## Source register
+
+- Three.js `TubeGeometry`: https://threejs.org/docs/pages/TubeGeometry.html
+- Three.js `CatmullRomCurve3`: https://threejs.org/docs/pages/CatmullRomCurve3.html
+- Three.js custom `BufferGeometry`: https://threejs.org/manual/en/custom-buffergeometry.html
+- Three.js transparency and `alphaTest`: https://threejs.org/manual/en/transparency.html
+- Three.js `MeshPhysicalMaterial`: https://threejs.org/docs/pages/MeshPhysicalMaterial.html
+- Three.js `InstancedMesh`: https://threejs.org/docs/pages/InstancedMesh.html
+- Kajiya and Kay, *Rendering Fur with Three Dimensional Textures*: https://doi.org/10.1145/74333.74361
+- Marschner et al., *Light Scattering from Human Hair Fibers*: https://www.cs.cornell.edu/~srm/publications/SG03-hair-abstract.html
+- CHARM, *Control-point-based 3D Anime Hairstyle Auto-Generation*: https://arxiv.org/abs/2509.21111
diff --git a/grimoire/character/threejs_hair_parameter_contract.json b/grimoire/character/threejs_hair_parameter_contract.json
new file mode 100644
index 0000000..192f6f7
--- /dev/null
+++ b/grimoire/character/threejs_hair_parameter_contract.json
@@ -0,0 +1,102 @@
+{
+ "schemaVersion": "1.0",
+ "status": "research-distill-local-refresh-required",
+ "target": "zenonia-chronobreak-warrior",
+ "runtime": {
+ "threeVersion": "0.169.x",
+ "renderer": "WebGL",
+ "codeOnly": true
+ },
+ "coordinateSystem": {
+ "space": "head-local",
+ "headHeight": 1.0,
+ "x": "character-left-right",
+ "y": "up",
+ "z": "forward",
+ "units": "head-height"
+ },
+ "scalpMass": {
+ "primitive": "ellipsoid",
+ "scaleRange": {
+ "x": [0.72, 0.90],
+ "y": [0.78, 1.02],
+ "z": [0.62, 0.86]
+ },
+ "rootOverlapRange": [0.025, 0.08]
+ },
+ "lockDefaults": {
+ "primaryCountRange": [10, 16],
+ "bangCountRange": [4, 6],
+ "secondaryCountRange": [8, 14],
+ "rearCountRange": [4, 8],
+ "controlPointCountRange": [3, 5],
+ "rootWidthRange": [0.12, 0.28],
+ "tipWidthRange": [0.003, 0.03],
+ "rootThicknessRange": [0.035, 0.12],
+ "tipThicknessRange": [0.003, 0.018],
+ "rootEmbedDepthRange": [0.025, 0.08],
+ "twistDegreesRange": [-18, 18]
+ },
+ "locks": [
+ {
+ "id": "crown-primary-01",
+ "family": "primary",
+ "layer": "mid",
+ "geometry": "tapered-ribbon-loft",
+ "controlPoints": [[-0.18, 0.42, 0.02], [-0.30, 0.72, 0.00], [-0.38, 1.02, -0.02]],
+ "widthProfile": [1.0, 0.82, 0.42, 0.03],
+ "thicknessProfile": [1.0, 0.75, 0.35, 0.08],
+ "rootEmbedDepth": 0.045,
+ "twistDegrees": -6,
+ "materialId": "hair-base",
+ "visibility": {
+ "maxHeroEyeOcclusionFraction": 0.08,
+ "mustRemainAttachedInOrbit": true
+ }
+ }
+ ],
+ "materials": {
+ "hair-base": {
+ "color": "#D9A64A",
+ "metalness": 0.0,
+ "roughnessRange": [0.35, 0.55],
+ "sheenRange": [0.15, 0.35],
+ "specularIntensityRange": [0.45, 0.80]
+ },
+ "hair-root-shadow": {
+ "color": "#8C552B",
+ "metalness": 0.0,
+ "roughnessRange": [0.48, 0.68],
+ "sheenRange": [0.05, 0.18],
+ "specularIntensityRange": [0.25, 0.55]
+ },
+ "hair-highlight": {
+ "color": "#F3D58B",
+ "metalness": 0.0,
+ "roughnessRange": [0.28, 0.45],
+ "sheenRange": [0.20, 0.40],
+ "specularIntensityRange": [0.55, 0.90]
+ }
+ },
+ "lod": {
+ "hero": {"curveSamples": 12, "ribbonSections": 8, "tubeRadialSegments": 6},
+ "orbit": {"curveSamples": 8, "ribbonSections": 6, "tubeRadialSegments": 4},
+ "microDisabledUntilScreenshotEvidence": true
+ },
+ "reviewCameras": {
+ "fixed": {"name": "hero-fixed", "required": true},
+ "orbits": [
+ {"name": "orbit-positive", "azimuthDegrees": 35, "required": true},
+ {"name": "orbit-negative", "azimuthDegrees": -35, "required": true}
+ ],
+ "requiredHairFeatures": [
+ "crown-silhouette",
+ "bang-eye-clearance",
+ "side-depth",
+ "rear-attachment",
+ "root-continuity",
+ "tip-taper",
+ "hair-palette"
+ ]
+ }
+}
diff --git a/grimoire/feedback/shading_realism.md b/grimoire/feedback/shading_realism.md
index 21b6dff..57f7a00 100644
--- a/grimoire/feedback/shading_realism.md
+++ b/grimoire/feedback/shading_realism.md
@@ -89,7 +89,7 @@ If the mismatch is mostly color/texture/lighting, choose `refine-code` only when
**Sample the CORRECT region per material.** Verify the crop is actually on the part you think — a "handle" crop taken from the blade region gave a navy-blue "grey" handle. Crop, *look at the crop*, then extract.
-**Aged / worn / faded materials — preserve mottling, don't flatten.** A uniform dark band looks crude ("thô"). Instead: keep the crop's real luminance variation (scratches, worn patches) but remap it into a **dark aged band** (e.g. luminance→charcoal 15–45), add micro-grain, and a **roughness map that varies** (worn high-spots slightly glossier, grooves matte). Keep the cast cool-neutral for gunmetal — a warm remap drifts to tan. Darken more than you think: a mid-grey albedo reads light under a strong key light.
+**Aged / worn / faded materials — preserve mottling, don't flatten.** A uniform dark band looks crude. Instead: keep the crop's real luminance variation (scratches, worn patches) but remap it into a **dark aged band** (e.g. luminance→charcoal 15–45), add micro-grain, and a **roughness map that varies** (worn high-spots slightly glossier, grooves matte). Keep the cast cool-neutral for gunmetal — a warm remap drifts to tan. Darken more than you think: a mid-grey albedo reads light under a strong key light.
**Render-capture must wait for textures.** `TextureLoader` is async; a screenshot fired before maps load shows `color:white` + metalness = a false "chrome" render (and a Divine-Eye false-reject). Poll `material.map.image.complete` before capturing. The render host must serve the reference PBR maps (copy to `public/`) or they 404 → white.
diff --git a/grimoire/intake/local_spec_search.md b/grimoire/intake/local_spec_search.md
index 3725d5f..e161e49 100644
--- a/grimoire/intake/local_spec_search.md
+++ b/grimoire/intake/local_spec_search.md
@@ -21,9 +21,10 @@ For extra focused retrieval, the direct CLI remains available:
python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json
```
-For CS2, include English/Vietnamese variants, for example `--spec-query "safety ring vòng ngón"`
-or `search_specs.py "roughness độ nhám" --collection cs2`. Expand queries with object names,
-component names, material/finish terms, behavior terms, and bilingual aliases; retry focused
+For CS2, include the anatomical and the colloquial name, for example
+`--spec-query "safety ring finger ring"` or `search_specs.py "roughness matte" --collection cs2`.
+Expand queries with object names,
+component names, material/finish terms, behavior terms, and known aliases; retry focused
alternatives when the first result is incomplete. Build the spec from returned evidence and do
not invent domain specs when local evidence exists. Search caches are local/generated only;
preserve JSONL records and source provenance rather than replacing them with cache output.
diff --git a/grimoire/readiness/procedural_rigging_contract.md b/grimoire/readiness/procedural_rigging_contract.md
new file mode 100644
index 0000000..b6fe316
--- /dev/null
+++ b/grimoire/readiness/procedural_rigging_contract.md
@@ -0,0 +1,46 @@
+# Procedural rigging contract — 1.5-alpha
+
+The implementation-facing rig contract: what the payload owns, and what it deliberately does not.
+
+## Payload ownership
+
+The procedural TypeScript factory owns geometry and authored rig data. Python owns
+deterministic validation and evidence packaging. The browser owns bone updates, skinning,
+pose application, dynamic bounds, and final pixels.
+
+| Layer | Required output | Failure action |
+| --- | --- | --- |
+| Spec | named joints, parent map, rest pose, sockets, pose probes | `refine-spec` |
+| Forge | validated payload report and coverage warnings | block build |
+| Three.js bind | one hierarchy, one skeleton, matching skin attributes | static fallback + `refine-code` |
+| Deformation smoke | neutral plus stress poses, no NaN/Inf, bounded stretch/collapse | block likeness review |
+| Browser evidence | fixed, orbit, profile and close-up screenshots | `request-input` or `refine-code` |
+
+## Runtime invariants
+
+- Use one shared `THREE.Skeleton` for all skinned meshes that share the character rig.
+- Bind in rest pose before applying animation; do not treat a posed mesh as the bind pose.
+- Update `skeleton.update()`/world matrices before measuring bounds or capturing a pose.
+- Keep `skinIndex` and `skinWeight` attributes aligned with the geometry vertex count.
+- Recompute or conservatively expand bounds after bone motion; a static load-time box may
+ cull an animated limb or hair mass.
+- Use semantic aliases only through an explicit map (`mixamo:LeftArm` → local joint id);
+ never infer a joint from a string suffix alone.
+- Keep auxiliary joints (ribbon, hair, skirt) explicitly tagged; their lack of direct
+ surface influence is a warning, not an accidental missing bone.
+
+## Pose probes before likeness
+
+The first browser smoke set is intentionally mechanical:
+
+- neutral rest pose;
+- elbow flexion and shoulder abduction;
+- hip/knee bend;
+- wrist/ankle and hand/foot end-effector reach;
+- head turn and spine bend;
+- stylized hair/ribbon attachment check;
+- `+35°`, `-35°`, profile and rear camera views.
+
+These probes are deformation and attachment evidence, not reference likeness scores. A
+rig must pass the deterministic payload gate and produce readable screenshots before
+`diagnose_render.py`, comparison sheets, semantic scoring, or confidence claims.
diff --git a/grimoire/readiness/standard_character_pipeline.md b/grimoire/readiness/standard_character_pipeline.md
new file mode 100644
index 0000000..922c4c8
--- /dev/null
+++ b/grimoire/readiness/standard_character_pipeline.md
@@ -0,0 +1,142 @@
+# Standard character pipeline contract — 1.5 beta + 1.5 alpha
+
+Beta owns the quality-gated sculpt/build/review pipeline. Alpha owns the Python manifest,
+browser capture evidence and UniRig-shaped rig payload boundary. External neural/GLB/VRM
+systems are adapters, never silent replacements.
+
+## Route selection
+
+```text
+code-only:
+ reference → spec → procedural TypeScript factory → authored/validated rig → Three.js
+
+external-asset (opt-in):
+ reference → CharacterGen/Tripo/etc. → GLB/VRM → UniRig/adapter → Three.js
+
+glb-mediated-reference (opt-in, new):
+ image (optional) → user/adapter-produced GLB → GLB probe → Three.js GLB baseline
+ → procedural TypeScript factory → same Three.js camera batch → comparison
+```
+
+The external route is valid for proving character-generation capability, but its artifact must
+not be reported as a procedural factory. The GLB-mediated route uses the imported GLB as a
+structural reference and browser-rendered baseline only; it still generates a separate procedural
+TypeScript factory. Both routes share the same browser capture, diagnostic and reference-loop gates.
+
+## Required artifacts
+
+| Artifact | Owner | Required content |
+| --- | --- | --- |
+| `reference-set.json` | intake | admitted views, paths, hashes, dimensions, camera role, hidden-region confidence |
+| `glb-reference.json` | GLB intake | GLB hash, scene/mesh/material/skin inventory, bounds, warnings, provenance |
+| `assessment.json` | intake/spec | character classification, complexity, anatomy, landmarks, local evidence refs |
+| `character-sculpt-spec.json` | spec | hierarchy, topology class, materials, feature targets, camera and quality contract |
+| `rig-payload.json` | rig | Y-up/right-handed coordinates, joints, parents, names, local matrices, packed skin weights |
+| `render-manifest.json` | alpha bridge | runtime URL, viewport/DPR, camera batch, reference/output hashes, readiness evidence |
+| `comparison-sheet.png` | review | fixed reference beside current browser render |
+| `diagnose-render.json` | review | tier-1 and multi-angle deterministic diagnostics plus next action |
+
+For a GLB-mediated reference, `render-manifest.json` additionally stores a `reference.kind` of
+`glb` and a browser-rendered baseline capture for every camera used in the procedural batch.
+The raw GLB is never passed to pixel comparison as if it were an image.
+
+For the 1.5 alpha GLB-mediated v2 track, the manifest may declare
+`fidelityTrack: "glb-mediated-v2"` plus a validated `renderProfile` shared by both routes.
+Each camera record then owns six paired browser passes: `beauty`, `alpha-silhouette`,
+`semantic-id`, `depth`, `normal`, and `roughness-material-id`. Per-region scores are blocked
+until the semantic-ID pass is readable and has declared region colors. A merged single-node
+GLB is recorded as semantically insufficient; region-growing or curvature partitions are
+hypotheses, not labels.
+
+## Character scene contract
+
+- Root is a named `THREE.Group` with `root.userData.sculptRuntime`.
+- Every identity-defining part has a stable name, material ID and optional anchor/socket.
+- Body, head, hair, outfit, armor, weapon and accessories are separate semantic modules.
+- Face geometry is one continuous head/face volume wherever possible. Eyes, nose and mouth
+ should use controlled surface/color/material regions or landmark-derived attached forms;
+ avoid arbitrary floating primitives.
+- Stylized hair uses a mass plus directional clumps with root/tip, side/rear coverage and
+ overlap checks. A flat billboard is not an acceptable character hair solution.
+
+## Coordinate, unit and rig contract
+
+- Internal procedural payloads are Y-up, right-handed and finite.
+- Root joint is index `0` with `parent = null`; every later parent index is less than the
+ child index. BFS/DFS is an authoring choice, not the runtime invariant.
+- WebGL skinning uses four packed influence slots per vertex with finite, nonnegative weights
+ normalized to one. The validator reports joints with no active weights.
+- When exporting external VRM, convert to meter units, right-handed Y-up, model facing `-Z`,
+ humanoid mapping and T-pose. Record conversion rather than hiding it in loader code.
+- Structural rig validation is not deformation proof. Neutral, shoulder, elbow, wrist, knee,
+ foot and accessory stress poses still require runtime evidence.
+
+## Browser capture contract
+
+The target showcase route must expose:
+
+```js
+window.__IMG2THREEJS_READY__ = true;
+window.__IMG2THREEJS_CAPTURE__ = {
+ setCamera(cameraSpec) { /* apply camera, target, near/far, exposure */ },
+ setReferenceMode({ kind, url }) { /* load GLB reference and swap the visible subject */ },
+ capturePass({ passId, mode }) { /* select pass and resolve when pixels are ready */ }
+};
+```
+
+For a GLB-mediated run, the route must also provide an explicit reference mode, for example
+`#/character-demo?reference=glb`, that loads the local GLB with `GLTFLoader`. The capture manifest
+records whether each PNG is the `reference` baseline or the `procedural` render. Both must use the
+same camera, viewport, DPR, tone mapping, exposure and background.
+For v2, `capturePass` must return `{ok: true, selector?: "canvas"}` or a comparable
+target selector so the adapter saves the actual pass canvas rather than surrounding UI.
+
+The capture adapter waits for readiness, rejects fatal console errors and zero-sized canvases,
+sets the camera, waits for settled frames, saves PNGs inside the workspace, reopens them with an
+image-capable reader, and records hashes in the manifest. Python never renders a replacement scene.
+
+## Required character capture batch
+
+```text
+hero/reference-match
+orbit +35°
+orbit -35°
+profile ~78°
+rear 180°
+head hero
+head three-quarter
+```
+
+Only the fixed view is pixel/feature aligned to the supplied reference. Orbit views are judged
+for volume, attachment, rear coverage, hair continuity, deformation and non-degenerate form.
+
+## Acceptance order
+
+1. reference admission and image/GLB readback;
+2. for GLB-mediated runs, GLB probe plus fresh browser baseline captures;
+3. character spec and strict-quality validation;
+4. blockout silhouette and proportion lock;
+5. face landmarks and unified head volume;
+6. hair/outfit/material modules;
+7. rig payload validation and runtime pose stress;
+8. browser readiness and fresh screenshot batch;
+9. tier-1 diagnostics, side-by-side sheet and semantic/per-feature review;
+10. multi-angle/attachment/self-intersection gates;
+11. exactly one next action: `continue`, `refine-spec`, `refine-code`, `request-input` or `stop`.
+
+The v2 correction order is one group per loop: camera, silhouette, face, clothing, accessory,
+materials, then lighting. Changing multiple groups in one loop invalidates attribution of the
+comparison result.
+
+Confidence above 9/10 is a visual acceptance target, not something inferred from tests,
+generated code, GLB export or a runtime-ready flag.
+
+## Migration map
+
+| Area | Beta contribution | Alpha contribution | Merged standard |
+| --- | --- | --- | --- |
+| intake/spec/build/review | strict-quality, geometry/material and review gates | character/rig research references | beta gates remain authoritative; alpha research feeds spec fields |
+| rigging | shared skeleton and pose/deformation tests | UniRig payload schema and validator | validate payload, then run real Three.js stress poses |
+| rendering | browser/runtime smoke infrastructure | Python manifest, camera batch, hash and diagnosis bridge | browser is renderer; Python is evidence controller |
+| external generation | optional asset handoffs | CharacterGen/UniRig research boundary | explicit adapter only, with provenance and no code-only claim |
+| visual acceptance | comparison/review gates | screenshot readback and multi-angle manifest | all screenshot and diagnostic gates are mandatory |
diff --git a/grimoire/review/divine_eye_microscope.md b/grimoire/review/divine_eye_microscope.md
new file mode 100644
index 0000000..75731ef
--- /dev/null
+++ b/grimoire/review/divine_eye_microscope.md
@@ -0,0 +1,205 @@
+# Divine Eye Microscope — four-tier fidelity review
+
+Divine Eye today scores a whole silhouette against a whole silhouette. That answers "is this the
+right shape" and cannot answer "is tear-04 on the right wing the right width", because the two
+questions live at different scales. This document specifies the microscope: a review that descends
+macro → component → feature → micro, and where **one critical feature failing fails the iteration
+regardless of a high global score**.
+
+## Audit first — what is already here
+
+Do not re-implement these. Verified against the code, not assumed:
+
+| Capability | State | Where |
+|---|---|---|
+| Critical-feature AND gate | **already implemented** | `stage4_review/per_feature.py` — `is_gating()` returns true for `tier == "critical"` or `mustPass`, and `passed` is false if any gating feature is missing or below threshold |
+| Arbitrary named ROIs in the inventory | **already implemented** | `stage1_intake/build_detail_inventory.py` — `component-zones` mode plus `--components` takes named normalized regions. The *default* (`DEFAULT_COMPONENT_ZONES`) is only upper/middle/lower thirds, which is what makes it feel grid-only |
+| Chamfer distance | referenced | `stage4_review/divine_eye.py` |
+| ΔE colour difference | present | `stage4_review/diagnose_render.py` |
+| SSIM | present | `stage4_review/divine_eye.py` |
+
+Genuinely absent, and therefore the actual work: `setViewOffset` zoom patches, render targets, SDF,
+Hausdorff, ID/depth/normal/albedo passes, per-ROI ΔE2000, and **occlusion masking in stage 4**
+(occlusion appears in stage 2 spec and stage 1 intake, nowhere in review).
+
+## The resolution problem, stated exactly
+
+`divine_eye.py` sets `LUMA_SIZE = 64` and `EDGE_SIZE = 96`. Every SSIM, tonal, blowout and
+edge-overlap signal is computed on those grids. A tear a few pixels wide in a 1920px reference is
+sub-pixel at 64×64 — it is not scored badly, it is **absent**. No threshold tuning recovers it; the
+information is gone before any comparison happens.
+
+`per_feature.py` cannot compensate: `evaluate_features(feature_targets, feature_scores)` consumes a
+scores dict. It never opens an image. So the tier machinery is sound and starved — it gates
+faithfully on numbers nothing produces at feature scale.
+
+`make_comparison_sheet.py` composites whole reference beside whole render. At sheet scale a
+few-pixel tear is invisible to a human reviewer and to a VLM alike.
+
+## Tier structure
+
+1. **Macro** — whole model, every required view.
+2. **Component** — wing-left, wing-right, head, torso, tail.
+3. **Feature** — individual spar, ear, eye, fang, tear.
+4. **Micro** — contour, tear edge, bevel, roughness, colour gradient.
+
+## Microscope plan — the feature descriptor
+
+```json
+{
+ "featureId": "wing-right-tear-04",
+ "componentId": "wing-right",
+ "criticality": "critical",
+ "requiredViews": ["front-primary", "rear", "side"],
+ "referenceRoi": [0.61, 0.22, 0.73, 0.39],
+ "localAnchor": [0.68, 0.91],
+ "minimumProjectedPixels": 128,
+ "captureResolution": 512,
+ "metrics": ["directionalChamfer", "sdf", "curvature", "deltaE00"]
+}
+```
+
+Missing ROI, missing render, missing camera, or a missing required feature **fails closed**. Exit
+nonzero — never a printed complaint and a zero exit.
+
+## Active zoom in Three.js
+
+Do **not** move the camera closer and do **not** switch to orthographic. Both change the
+projection, so the patch no longer shows what the reference view shows. NotebookLM's orthographic
+suggestion is only correct when the reference itself is orthographic.
+
+- `PerspectiveCamera.setViewOffset()` — crop a sub-rectangle of the *original* projection.
+- `WebGLRenderTarget` — render the patch at 512² or 1024².
+- `camera.layers` or visibility masks — isolate the component. **See the occlusion warning below.**
+- Object-ID pass — one flat unique colour per mesh.
+- Depth and normal passes — separate geometry error from material error.
+- `readRenderTargetPixelsAsync()` for pixel readback.
+- DPR pinned to 1. Hardware antialias **off**; supersample 2×/4× and downsample deterministically.
+- Camera, viewport, FOV, target, near/far, tone mapping and exposure all frozen.
+
+### Occlusion warning — isolation renders are not what the reference sees
+
+**This one is empirically established, not theoretical.** It produced a confident false finding in
+the mini-dragon build and cost a full correction cycle before it was caught.
+
+Isolating a component by layers or `visible` hides everything else, so the render reveals parts of
+the component that are **hidden in the real frame**. Measured that way the dragon's wings read
+`darkShare` 0.4362 against a reference 0.2240 — "the spars are twice too thick". Spar radii were
+scaled to 0.72× on the strength of it. Measured correctly at the *original* radii the same wings
+read 0.1891 against 0.2240, a delta of 0.0349, comfortably inside tolerance. **The spars were never
+too thick.**
+
+The cause: the reference's wing material spans 0.924–2.135 face widths from the centre, the model's
+spans 0.519–1.739 — the same span to within 1%, but reaching 0.405 face widths further inboard,
+because in the isolation render nothing occluded the wing root. That root carries the thickest spars
+and the arm spar, so the model was charged for dark geometry the reference photograph cannot contain.
+
+The fix, and the rule:
+
+> A fidelity comparison must measure the component's **visible footprint**: render the full frame,
+> render it again with only that component hidden, and take the pixels that differ. Those are the
+> pixels where the component is the frontmost thing drawn — which is exactly what a photograph of
+> the same pose shows of it. Keep isolation renders for *structural* questions (is the spar present,
+> are left and right consistent), where seeing occluded geometry is a feature rather than a bias.
+
+Note also which instrument caught this. Thinning the spars improved the new feature metric and cost
+the older silhouette ratchet 0.0075 IoU on one view, twice its tolerance. **Two instruments
+disagreeing is information, and the newer one is not automatically right.** Never let a freshly
+written metric override a regression in one already trusted; investigate the disagreement instead.
+
+## Micro algorithms
+
+- **Image pyramid / MS-SSIM** — compare at multiple scales rather than one.
+- **Patch-wise comparison** — so a large correct skin area cannot mask a small wrong tear edge.
+- **3-SSIM** — weight edge and texture above smooth regions.
+- **SDF** — signed distance between two contours.
+- **Bidirectional / directional Chamfer** — position *and* orientation of a tear edge.
+- **Curvature extrema** — locate each notch's apex and lobes.
+- **Hausdorff / worst-edge distance** — catch the worst local error, which averages hide.
+- **Occlusion mask** — never score a hidden region. See the warning above.
+- **Multi-view correspondence** — the same tear must sit consistently across views.
+- **Adaptive subdivision** — subdivide ROIs that are edge-dense or uncertain.
+
+Saliency alone is insufficient: a small tear need not be salient. Combine three sources — the
+declared feature inventory (mandatory), automatic edge/curvature discovery, and saliency/uncertainty
+for finding regions worth zooming that nobody declared.
+
+## Tear descriptor
+
+Store each tear independently; never mirror descriptors between wings.
+
+Centre in normalized u/v · mouth width · tear depth · mouth angle · apex position · left and right
+edge angle · curvature at apex · distance to previous and next tear · profile (V, U, slit, scallop) ·
+edge thickness and bevel · roughness/fray amplitude · relation to nearest spar · side and asymmetry ·
+visibility and occlusion per view.
+
+That is what lets the review say "tear-04 is 12% too wide, 8% too shallow, 6px off its spar" instead
+of "wing score low".
+
+## Colour microscope
+
+Three separate passes:
+
+1. **Geometry pass** — unlit, no tone mapping. Silhouette, ID, depth, normal.
+2. **Albedo pass** — neutral light or map-stripped, to check base colour.
+3. **Beauty/PBR pass** — fixed lighting/HDRI/tone mapping, to check appearance.
+
+Colour metrics: convert sRGB to linear properly · de-light the reference before comparing albedo ·
+CIELAB/ΔE2000 per ROI · mask highlights, shadows and occluded regions · check hue, chroma and
+luminance separately · derive roughness/specular from highlight width and intensity under controlled
+relighting only.
+
+**Do not hard-gate roughness from an image whose lighting is unknown.** `hueZoneParity` and specular
+signals stay report-only until a calibration corpus exists.
+
+### Corollary — a dark ratio cannot separate material from shadow on a concave part
+
+Also empirically established. The mini-dragon's reference ear reads 14.3% "dark keratin" even along
+its own axis corridor, so it is not a crop artefact. But bucketing those pixels by `min(r,g,b)` shows
+only 14% near-black, peaking at 60–79 — a gradient. The wing's dark over the same classifier is 32.9%
+near-black. The ear's dark is **cavity shading**, and the model reading 0.0% is not a missing
+material. Gating on it would have driven a dark inner-ear material to be invented to match a shadow.
+
+> Before promoting any ROI to a colour-gating metric, bucket its reference dark pixels by
+> `min(r,g,b)`. A material clusters near-black; shading spreads mid-grey. Concave, unlit features are
+> report-only.
+
+## Aggregation
+
+Never average globally.
+
+```
+critical feature AND gate
+ ↓
+ worst patch
+ ↓
+ worst component
+ ↓
+ worst view
+ ↓
+ overall verdict
+```
+
+One missing critical tear fails the whole iteration.
+
+## Acceptance criteria
+
+- [ ] Divine Eye accepts a view × component × feature manifest.
+- [ ] Zoom patches rendered via `setViewOffset`, projection unchanged.
+- [ ] Every critical feature rendered at ≥128–256 px.
+- [ ] ID, depth, normal, albedo and beauty outputs produced.
+- [ ] SDF + directional Chamfer for contours.
+- [ ] Per-ROI ΔE2000 for colour.
+- [ ] Any missing required patch exits nonzero.
+- [ ] **Fidelity metrics measured on the visible footprint (full minus component-hidden), not on an isolation render.**
+- [ ] A fixture identical everywhere but missing one small tear **fails**.
+- [ ] A VLM may not override a geometry or micro-detail hard gate.
+- [ ] Overall verdict from worst patch/view, not an average.
+- [ ] Every artifact carries plan hash, model hash, camera, renderer config and iteration ID.
+
+## The hard limit
+
+**Zoom cannot create information the reference does not contain.** If a tear occupies 1–2 pixels in
+the source image, Divine Eye must return `insufficient-reference-resolution`. Super-resolution output
+is never ground truth — it is a plausible invention, and gating a model against an invention is worse
+than not gating it at all.
diff --git a/grimoire/scripts.md b/grimoire/scripts.md
index 54fc512..2113481 100644
--- a/grimoire/scripts.md
+++ b/grimoire/scripts.md
@@ -7,6 +7,15 @@ paths resolve as `forge/<name>.py`. Non-zero exit = a gate failed; read the prin
Division of labor: **scripts enforce structure and package evidence; they never score visuals.**
The acceptance score always comes from the agent's own vision inspecting the comparison sheet.
+## Input and evidence hardening
+
+- PNG and baseline 8-bit JPEG references are decoded in-process by the stdlib core. Unsupported
+ progressive/12-bit/CMYK JPEGs must take an explicit external-converter fallback; never guess at
+ pixels.
+- `diagnose_render.py` and `divine_eye.py` treat tiny/inverted foreground masks and empty unions as
+ unusable evidence. Re-capture the reference/render with the subject filling the frame.
+- `vlm_gate.py --samples` requires a non-empty JSON list whose entries are objects. `analyze_texture.py`
+ requires `--spec` and `--material-id` together, and `--in-place` requires both.
## state.py and next.py
- `state.py init --state .img2threejs/state.json --reference IMG [--profile generic|cs2|character]`
@@ -64,9 +73,95 @@ threshold (default 0.7), and every critical feature ≥ its own threshold.
## stage3_build/generate_threejs_factory.py
`stage3_build/generate_threejs_factory.py spec.json --out src/createObjectModel.ts [--pass-id PASS] [--force]`
-Emits a TypeScript Three.js `Group` factory for the **current unlocked pass only**. Passing a
+First enforces `strict-quality`; if that gate fails it prints a machine-readable `BLOCKED` report,
+optionally writes it with `--blocked-report`, and does not create or overwrite the factory. It emits
+a TypeScript Three.js `Group` factory for the **current unlocked pass only**. Passing a
future `--pass-id` fails until earlier passes are reviewed `continue`. Output exposes
`root.userData.sculptRuntime` (nodes/meshes/sockets/colliders/destructionGroups) — hand-refine it.
+`--allow-nonstrict` is reserved for legacy test fixtures and must not be used for production output.
+
+## Forge subdivision runtime validation
+Runtime subdivision tests compile generated TypeScript against `img2threejs-showcase`. Set
+`IMG2THREEJS_SHOWCASE_ROOT` to that checkout. Without it, runtime-only cases skip locally with an
+actionable message while static contracts continue; set `IMG2THREEJS_REQUIRE_SHOWCASE=1` in CI to
+fail when the checkout is unavailable. Forge showcase tests share this resolver, including visual-hull
+runtime and smoke coverage.
+
+```bash
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_subdivision.py
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 -m unittest discover -s forge/tests
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_showcase_tsc_smoke.py
+```
+
+## Triangle budget: tessellation tiers and decimation
+
+`performanceBudget.targetTriangles` picks a tessellation tier for every primitive that has
+segment counts, and caps implicit-surface sampling grids:
+
+| targetTriangles | tier | sphere | cylinder | SDF grid ceiling |
+|---|---|---|---|---|
+| ≤ 6,000 | `low` | 16×10 | 10×4 | 24 |
+| ≤ 60,000 | `standard` | 32×20 | 24×8 | 40 |
+| otherwise / absent | `hero` | 64×40 | 48×16 | 64 |
+
+`hero` IS the pre-tier constants, so a spec without a budget generates byte-identical output.
+Height segments never drop below 4 and cone height segments are pinned at 1 — the first
+because a single quad across a joint leaves no vertex at the pivot and the joint collapses
+(`emit_rig.py:399` derives the same floor), the second because a tapering cone only welds
+cleanly at 1. `validate_tier()` raises rather than letting a tier violate either.
+
+When a tier is not precise enough — an SDF's grid is quantised, so it can only get near a
+number — decimate that component:
+
+```json
+"geometryDescriptor": { "decimate": { "targetRatio": 0.4 } }
+```
+
+Emits a Garland-Heckbert quadric collapse into the generated factory, refusing collapses that
+would flip a face or erode a boundary edge. It runs **before** skin binding: the bind pass
+recomputes weights from `position`, so weights land on the surviving vertices and no
+skinIndex/skinWeight is interpolated across a vertex merge. It keeps `position` only and
+recomputes normals, so it is refused on an authored/unwrapped `uvStrategy`.
+
+Measured on the implicit fixture: 856 → 342 triangles at 0.4. On a rigged humanoid at 0.5:
+828 → 414 triangles, 49 bones and 5 SkinnedMesh intact, every vertex's four skin weights
+still summing to 1.0.
+
+For offline LOD tiers from an exported mesh, the same algorithm:
+
+```bash
+python3 forge/stage3_build/decimate.py meshes.json --ratio 0.5 --json
+```
+
+## Visual-hull descriptor
+
+`geometryDescriptor.visualHull` is an opt-in deterministic orthographic carving path. It requires
+`boundsSpace: "component-local"`; bounded `min`/`max` local extents are created before the existing
+component pivot applies its `transform`, plus a voxel `resolution` from 4 to 32, a triangle budget, and
+at least two distinct `front`, `side`, or `top` binary silhouettes. Each view carries a 0 to 1
+confidence value; generated geometry records every unobserved region as low-confidence metadata. A
+valid descriptor whose silhouettes intersect to no voxels throws `VisualHullOccupancyError` at runtime
+instead of silently returning an empty geometry.
+
+```json
+{
+ "visualHull": {
+ "projection": "orthographic",
+ "boundsSpace": "component-local",
+ "bounds": { "min": [-1, -1, -1], "max": [1, 1, 1] },
+ "resolution": 16,
+ "triangleBudget": 50000,
+ "views": [
+ { "axis": "front", "confidence": 0.94, "mask": ["0110", "1111", "1111", "0110"] },
+ { "axis": "side", "confidence": 0.91, "mask": ["0110", "1111", "1111", "0110"] }
+ ]
+ }
+}
+```
+
+```bash
+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_visual_hull.py
+```
Use `--force` for the next pass only after preserving valid hand refinements in the spec.
Do not regenerate after `refine-code`; edit the existing artifact. Regenerate with `--force` after
`refine-spec` or when advancing to a new pass.
@@ -84,6 +179,20 @@ Evidence flags: `--matched --mismatches --spec-fixes --code-fixes --evidence --r
--require-screenshot-files`. Layer keys: `silhouetteProportion, componentStructure, formDetail,
materialSurface, lightingCamera`. Records one self-correction entry into `reviewHistory`.
+## GLB-mediated v2 render profile
+
+`stage4_review/validate_render_profile.py docs/specs/render-profile.v2.example.json`
+validates the shared browser renderer/camera/environment contract. Use it when initializing
+the GLB-mediated route:
+
+`stage4_review/render_bridge.py init --reference-glb GLB --render-profile PROFILE --runtime-url URL --out render-manifest.json`
+
+Record each pass with `stage4_review/render_bridge.py record-pass --manifest MANIFEST
+--capture-id hero --pass-id semantic-id --image semantic-id.png [--reference]`. Required passes
+are `beauty`, `alpha-silhouette`, `semantic-id`, `depth`, `normal`, and
+`roughness-material-id`. Compare paired browser evidence with
+`stage4_review/compare_region_passes.py --manifest MANIFEST --capture-id hero --out comparison.json`.
+
## stage1_intake/extract_pbr_evidence.py
`stage1_intake/extract_pbr_evidence.py <crop> --out-dir DIR --material-id ID [--target-threshold 0.7] [--size N]
[--palette-size N] [--spec spec.json --in-place | --out-spec p.json] [--report r.json]
@@ -96,3 +205,138 @@ and refuses to patch the spec when confidence < `--target-threshold` (default 0.
## _shared/feature_acceptance_policy.py
Internal helper imported by the orchestrator/validator (`feature_gate_failures`,
`feature_review_policy`). Enforces the ≤5 critical / ≤3 important feature-tier policy. Not a CLI.
+
+## Character geometry pipeline
+
+All analytic — no trained model, no weights. Each replaces a capability the pipeline named but never
+implemented, or supplies one it never had.
+
+### stage3_build/visual_hull.py
+`stage3_build/visual_hull.py descriptor.json [--out mesh.json] [--json]`
+`carve_visual_hull()` intersects the silhouette cones on a voxel grid and emits only the faces between
+solid and empty, so the result is a closed surface rather than a box soup with interior walls. Read
+`occupiedVoxelCount` before trusting a mesh: survival requires foreground in EVERY view, so one bad
+mask erases the model rather than degrading it. `unconstrainedAxes` names the direction a two-view
+hull extrudes along, and a hull can never contain a concavity no supplied view sees as background.
+
+### stage3_build/uv_unwrap.py
+`stage3_build/uv_unwrap.py mesh.json [--angle DEG] [--out uv.json] [--json]`
+Chart segmentation by normal similarity (growth compared against the SEED, so a chart cannot creep
+around a cylinder one tolerable step at a time), LSCM solved by conjugate gradient, skyline packing.
+**Read `areaDistortionMedian` and `areaDistortionP95`, not the max** — sweeping the threshold on a real
+skull gave 2299 / 93609 / 6595 / 378 / 15.85, which is one sliver chart dominating a maximum, not a
+trend. Non-disk charts are cut, not merely reported: leaving seven in place drove distortion to 171300
+with twelve inverted triangles. Vertices in `seamVertices` carry more than one UV and must be
+duplicated before a bake.
+
+### stage5_rig/geodesic_skinning.py
+`stage5_rig/geodesic_skinning.py mesh.json --bones bones.json [--resolution N] [--json]`
+Distance measured THROUGH the solid, not in a straight line. On an arm-beside-torso fixture the field
+correctly reads 1.37 units to the spine and 4.45 to the arm; the residual cross-talk after that is set
+by `DEFAULT_FALLOFF_POWER` (power 2 leaves 8.6%, power 3 leaves 2.8%, power 4 leaves 0.9%) and not by
+the distance field. `euclidean_bind` is kept so the difference can be measured rather than asserted.
+
+### stage4_review/joint_loops.py
+`stage4_review/joint_loops.py meshes.json --bones bones.json [--min-loops N] [--json]`
+Counts distinct vertex BANDS along the bone axis near each joint. Bands, not vertices: ten thousand
+vertices in two rings still cannot bend, and a vertex count calls that mesh dense. The window is axial,
+not a sphere, because a limb's thickness has nothing to do with whether its joint can bend.
+
+### stage4_review/pairwise_penetration.py
+`stage4_review/pairwise_penetration.py meshes.json [--allow nameA,nameB]... [--json]`
+Ray parity across meshes. Samples vertices, edge midpoints and face centroids — vertices alone miss a
+bar driven through a block, where every corner of each is outside the other. Still sampling, not exact
+intersection; `samplingLimitation` says so. Use `--allow` for parts meant to touch.
+
+### stage3_build/morph_targets.py and stage3_build/decimate.py
+`morph_targets.py base.json --target pose.json [--out morphs.json]`
+`decimate.py mesh.json --ratio 0.5 [--out lod.json]`
+Morph targets are RELATIVE deltas; set `morphTargetsRelative = true` in Three.js or every target is
+read as an absolute position and the mesh collapses toward the origin. A target with a mismatched
+vertex count is refused rather than zip-truncated into a plausible-looking nonsense deformation.
+Decimation refuses any collapse that would flip a face or erode a boundary, and reports
+`collapsesRefusedForFlip` — stopping short of the target is not a failure, but hitting the number with
+a folded surface would be.
+
+## Off-axis and placement gates
+
+Three checks that exist because a review captured only from the reference camera, and scored only by
+edge counts, passed a model with a hole through its skull, a hat mounted at hip height, and a charm
+floating detached below the ground plane. Each answers a question no earlier gate asked. All three
+exit `0` clean / `1` gate failure / `2` error, so they compose in a script.
+
+### stage4_review/self_intersection.py
+`stage4_review/self_intersection.py meshes.json [--max-samples N] [--epsilon E] [--json]`
+Ray-parity test for a surface that has folded through its own volume. `geometry_integrity.py` counts
+only `boundaryEdges` and `nonManifoldEdges`, which are **topological** — pushing existing vertices
+through the far side of a mesh changes no connectivity, so a punched-through model reports 0 and 0 and
+passes. This is the geometric check that can see it. Reports `sampledVertexCount` /
+`totalVertexCount` / `samplingStride`: read them, because a clean verdict over a strided sample is a
+weaker claim than a clean verdict over the whole mesh. `undecided` samples (grazing rays) are counted
+separately and never folded into either answer.
+
+Input is the same mesh shape `geometry_integrity.py` accepts. Produce it from a live scene with
+`runtime/scripts/export_mesh_geometry.mjs` (below).
+
+`measure_geometry_integrity` calls this automatically for every mesh that supplies `vertices` and
+`indices`, reporting a `selfIntersection` block per mesh and raising a `self-intersection` failure.
+That call site is deliberate: as a standalone CLI the check only runs when somebody remembers to run
+it, and the defect it exists to catch survived eight review rounds precisely because nobody did.
+
+### stage4_review/turntable_gate.py
+`stage4_review/turntable_gate.py --capture 0=front.png --capture 90=right.png ... [--required N]... [--collapse-ratio R] [--allow-holes] [--json]`
+Two things `diagnose_render_multi_angle.py` does not do. First, **coverage is mandatory**: a missing
+required azimuth (default 0/90/180/270) fails the gate rather than going unnoticed, which is the
+entire point — defects that exist only off-axis survive any number of front-only review rounds.
+Second, **interior-hole detection**: flood-fill the background from the border, and any background
+region left unreached is enclosed by the object. A hole through a model barely changes silhouette
+AREA, so the collapse check cannot see it; this can. Use `--allow-holes` for a subject that genuinely
+has a through-hole at that angle — the hole is still reported, only the verdict changes.
+
+### stage4_review/attachment_anchor.py
+`stage4_review/attachment_anchor.py spec.json [--measured measured.json] [--json]`
+Relates a worn or held item to the thing it is worn on or held by. `ANCHOR_DECLARED`,
+`ANCHOR_RESOLVES`, `ANCHOR_NOT_ROOT` (the literal shared bug — parenting to root leaves the item's
+transform unrelated to its body part), `ANCHOR_NOT_CYCLIC`, and, when `--measured` world positions are
+supplied, `ANCHOR_PROXIMITY` against `attachment.maxOffset`. Attachments absent from `measured` are
+listed under `unmeasuredAttachments` instead of counting as passes — "0 violations" because the check
+never ran is the failure this repository keeps rediscovering. A spec with no attachment metadata
+passes cleanly, so existing specs are unaffected.
+
+### runtime/scripts/export_mesh_geometry.mjs
+`node runtime/scripts/export_mesh_geometry.mjs --url URL --out meshes.json [--include RE] [--exclude RE] [--max-triangles N] [--ready-flag F] [--viewer-handle H]`
+Dumps a running model's meshes as the JSON `self_intersection.py` reads. Vertices are emitted in
+**world** space on purpose: a parent's non-uniform scale can fold a mesh through itself even when its
+local geometry is fine, and local space would hide exactly that. Normals go through the
+inverse-transpose. Every mesh it declines to emit — instanced, over the triangle cap, filtered out —
+is listed with its reason, so a short mesh list cannot be mistaken for a clean one.
+
+## Reference comparison and baselines
+
+### stage4_review/mesh_reference_compare.py
+`stage4_review/mesh_reference_compare.py REFERENCE.glb CANDIDATE.glb [--bands N] [--json]`
+Says **where** a candidate is wrong, band by band, instead of returning one aggregate score. Both
+meshes are normalised from the **feet** (lowest point to 0, height to 1) because the ground is a
+landmark both subjects share, while the top of the bounding box is whatever pokes up highest — three
+earlier attempts banded down from the bbox top and measured their own misalignment. Each band reports
+the 5th–95th percentile width rather than the extremes, so a long thin staff stops dominating the
+number, and the lateral/depth **centroid** as well as the width, which is what catches a limb that is
+the right size on the wrong side. Reads uncompressed `.glb` with the standard library only.
+
+### scripts/character_audit.sh
+`scripts/character_audit.sh <page-url> <output-dir> [mesh-name-regex] [--allow a,b]...`
+Runs every geometry gate against a live model and writes a baseline to diff against later, so "before
+and after" is a number rather than an impression. Arguments after the regex are forwarded to the
+penetration gate, which is where `--allow` belongs: parts that *should* share space (an ear root in a
+skull, a hand gripping a staff) are contact, not defects, and a gate with no exemption list flags them
+until someone switches the gate off entirely.
+
+### integrations/mesh3d/generate_reference_mesh.py — optional, external
+`integrations/mesh3d/generate_reference_mesh.py <image>... --out-dir <dir> [--space S] [--hf-token T]`
+Generates a reference mesh from reference image(s) via a hosted Space, emitting GLB **and** OBJ from
+one generation and one transform. GLB is the transport format so the reference can be rendered with
+the same camera and shader as the candidate — comparing a PBR render against a photograph is what
+pins `ssim` at 0. OBJ is the scoring format, because `forge/` gates are pure-stdlib by house rule and
+OBJ is ASCII a short parser reads. Unlike everything else in this cheatsheet it needs network access
+and a third-party endpoint, so it is never on a required path: its output is an input to review, not
+evidence that a gate passed.
diff --git a/integrations/mesh3d/generate_reference_mesh.py b/integrations/mesh3d/generate_reference_mesh.py
new file mode 100644
index 0000000..86c1684
--- /dev/null
+++ b/integrations/mesh3d/generate_reference_mesh.py
@@ -0,0 +1,205 @@
+#!/usr/bin/env python
+"""
+Generate a reference mesh from reference image(s) via a hosted TRELLIS Space, as GLB **and** OBJ.
+
+Why a hosted Space and not a local model: TRELLIS states "the code is currently tested only on
+Linux" and "an NVIDIA GPU with at least 16GB of memory is necessary", and its submodules (spconv,
+nvdiffrast, diff-gaussian-rasterization, flash-attn) are CUDA-only. There is no MPS path. The Space
+runs on the provider's CUDA hardware, so an Apple Silicon machine gets TRELLIS output without
+TRELLIS ever running locally.
+
+Why BOTH formats, from one generation:
+ GLB — transport/render format. Three.js loads it natively (GLTFLoader), so the reference can be
+ rendered with the SAME camera and shader as the candidate model. That identical-domain
+ render is the entire point: comparing a PBR render against a photograph is what pins
+ `ssim` at 0 and `tonalParity` at 0.11.
+ OBJ — scoring format. `forge/` gates are pure-stdlib by house rule, and OBJ is `v/vn/f` ASCII
+ that a ~30-line stdlib parser reads. Decoding GLB accessors/bufferViews in pure Python is
+ 200-400 fiddly lines and impossible outright if the file is Draco-compressed.
+
+Both files are written from ONE generation and ONE transform, because the most dangerous failure
+here is silent: if the GLB and the OBJ disagree on axis convention, the Three.js render and the
+Python metric score two different objects and neither complains. glTF fixes Y-up/right-handed/metres
+by spec; OBJ fixes nothing. `--assert-axes` compares their bounding boxes and refuses to continue on
+a mismatch.
+
+Texture is deliberately minimal. The metrics this unlocks (Chamfer, F-score, normal consistency) are
+geometric, and the depth/normal render path discards materials anyway. A generated texture is a
+hallucinated bake of a single view with shading and AO burned in — strictly worse than the original
+reference images, which remain the colour authority.
+
+Usage:
+ python generate_reference_mesh.py IMAGE [IMAGE ...] --out-dir DIR [--space ID] [--seed N]
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import struct
+import sys
+from pathlib import Path
+
+DEFAULT_SPACE = "trellis-community/TRELLIS"
+
+
+def parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("images", nargs="*", type=Path, help="reference image(s); 2+ enables multi-view")
+ p.add_argument("--out-dir", type=Path, required=True)
+ p.add_argument("--from-glb", type=Path, default=None,
+ help="skip generation and convert an existing GLB. Generation costs finite "
+ "ZeroGPU quota, so a failure in the local conversion step must never force "
+ "a regeneration of a mesh that already exists")
+ p.add_argument("--space", default=DEFAULT_SPACE)
+ p.add_argument("--seed", type=int, default=0)
+ p.add_argument("--mesh-simplify", type=float, default=0.95,
+ help="TRELLIS simplify ratio, demo range 0.9-0.98. In the reference demo this is "
+ "the fraction of triangles REMOVED, so higher means a lighter mesh -- but "
+ "verify against the triangle count this script reports rather than trusting "
+ "the direction stated here")
+ p.add_argument("--texture-size", type=int, default=512,
+ help="kept small on purpose: geometry is what is being scored")
+ p.add_argument("--hf-token", default=None)
+ return p.parse_args()
+
+
+def generate(args: argparse.Namespace) -> Path:
+ from gradio_client import Client, handle_file
+
+ for image in args.images:
+ if not image.exists():
+ sys.exit(f"reference image not found: {image}")
+
+ # `token=`, not `hf_token=` — gradio_client 2.6.0 names it `token` and rejects the other spelling
+ # outright. And fall back to the stored login rather than leaving it None: a user who ran
+ # `hf auth login` specifically to get ZeroGPU quota should actually get it, not silently run
+ # anonymous.
+ from huggingface_hub import get_token
+
+ token = args.hf_token or get_token()
+ client = Client(args.space, token=token, verbose=False)
+ print(f"auth : {'token' if token else 'anonymous'}")
+ primary = handle_file(str(args.images[0]))
+ # TRELLIS takes the extra views as {image, caption} records, and only consults them when
+ # `multiimage_algo` is set. A single view genuinely cannot show hidden sides; two clay
+ # turnarounds at different azimuths constrain the back far better than one ever can.
+ extra = [{"image": handle_file(str(p)), "caption": None} for p in args.images[1:]]
+
+ print(f"space : {args.space}")
+ print(f"views : {len(args.images)} ({'multi-view' if extra else 'single-view'})")
+
+ # `/start_session` MUST be called first, and nothing in the API listing says so.
+ #
+ # The TRELLIS app creates a per-session scratch directory (TMP_DIR/<session_hash>) inside a
+ # `demo.load(...)` handler and every later step writes into it. `demo.load` fires when a browser
+ # opens the page; it does NOT fire for an API client. Skipping it produced a bare server-side
+ # `FileNotFoundError` with no indication of which file or why -- the failure names the symptom
+ # and hides the cause. The session hash is per-Client, so this has to run on the same instance.
+ client.predict(api_name="/start_session")
+ result = client.predict(
+ image=primary,
+ multiimages=extra,
+ seed=args.seed,
+ ss_guidance_strength=7.5,
+ ss_sampling_steps=12,
+ slat_guidance_strength=3.0,
+ slat_sampling_steps=12,
+ multiimage_algo="stochastic" if extra else "stochastic",
+ mesh_simplify=args.mesh_simplify,
+ texture_size=args.texture_size,
+ api_name="/generate_and_extract_glb",
+ )
+ # The endpoint returns (preview video, extracted asset, downloadable GLB).
+ glb_source = None
+ for item in result:
+ candidate = item.get("video") if isinstance(item, dict) else item
+ if isinstance(candidate, str) and candidate.lower().endswith(".glb"):
+ glb_source = candidate
+ if glb_source is None:
+ sys.exit(f"no .glb in response: {result!r}")
+
+ args.out_dir.mkdir(parents=True, exist_ok=True)
+ glb_path = args.out_dir / "reference.glb"
+ shutil.copy(glb_source, glb_path)
+ return glb_path
+
+
+def inspect_glb(glb_path: Path) -> dict:
+ """Read the glTF JSON chunk with stdlib only, to catch compression before anything depends on it.
+
+ Draco or meshopt compression is common in generated GLB and is the one condition that makes the
+ pure-Python scoring path impossible — it must be detected at intake, not discovered later.
+ """
+ data = glb_path.read_bytes()
+ magic, _version, _length = struct.unpack_from("<III", data, 0)
+ if magic != 0x46546C67:
+ sys.exit(f"{glb_path} is not a GLB (bad magic)")
+ chunk_length, chunk_type = struct.unpack_from("<II", data, 12)
+ if chunk_type != 0x4E4F534A:
+ sys.exit("first GLB chunk is not JSON")
+ gltf = json.loads(data[20:20 + chunk_length])
+ required = gltf.get("extensionsRequired", [])
+ return {
+ "extensionsRequired": required,
+ "compressed": any("draco" in e.lower() or "meshopt" in e.lower() for e in required),
+ "meshes": len(gltf.get("meshes", [])),
+ "materials": len(gltf.get("materials", [])),
+ }
+
+
+def write_obj(glb_path: Path, obj_path: Path) -> dict:
+ """GLB -> triangulated, smooth-normal OBJ, and report the geometry both consumers must agree on.
+
+ Smooth rather than flat normals: flat normals encode the TESSELLATION, not the form, so a normal
+ comparison against a flat-shaded reference would score how the generator chose to triangulate.
+ Flat shading also splits a vertex per face, tripling the count for nothing.
+ """
+ import trimesh
+
+ scene_or_mesh = trimesh.load(glb_path, force="scene")
+ mesh = scene_or_mesh.to_mesh() if hasattr(scene_or_mesh, "to_mesh") else scene_or_mesh
+ mesh.merge_vertices() # weld first, so smooth normals average across real neighbours
+ mesh.fix_normals()
+ obj_path.write_text(trimesh.exchange.obj.export_obj(mesh, include_normals=True, include_texture=False))
+ bounds = mesh.bounds
+ return {
+ "vertices": int(len(mesh.vertices)),
+ "triangles": int(len(mesh.faces)),
+ "bbox_min": [round(float(v), 4) for v in bounds[0]],
+ "bbox_max": [round(float(v), 4) for v in bounds[1]],
+ "size": [round(float(v), 4) for v in (bounds[1] - bounds[0])],
+ "watertight": bool(mesh.is_watertight),
+ }
+
+
+def main() -> None:
+ args = parse_args()
+ if args.from_glb is not None:
+ if not args.from_glb.exists():
+ sys.exit(f"--from-glb not found: {args.from_glb}")
+ glb_path = args.from_glb
+ print(f"reusing : {glb_path} (no generation)")
+ else:
+ if not args.images:
+ sys.exit("provide reference image(s), or --from-glb to convert an existing mesh")
+ glb_path = generate(args)
+ obj_path = glb_path.with_suffix(".obj")
+
+ glb_info = inspect_glb(glb_path)
+ obj_info = write_obj(glb_path, obj_path)
+
+ report = {"glb": str(glb_path), "obj": str(obj_path), **glb_info, **obj_info}
+ (args.out_dir / "reference-mesh.json").write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+
+ if glb_info["compressed"]:
+ print("\nWARNING: GLB declares compression in extensionsRequired. Three.js needs DRACOLoader "
+ "and the pure-Python path cannot read it. The OBJ above is still usable.", file=sys.stderr)
+ print("\nNOTE: this mesh is a generative PROXY, not ground truth. Score it against the original "
+ "reference image before using it as a scoring reference — a hallucinated back side is "
+ "exactly what a confident-but-wrong metric would optimise toward.", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/integrations/vision/.python-version b/integrations/vision/.python-version
new file mode 100644
index 0000000..2c07333
--- /dev/null
+++ b/integrations/vision/.python-version
@@ -0,0 +1 @@
+3.11
diff --git a/integrations/vision/README.md b/integrations/vision/README.md
new file mode 100644
index 0000000..1e3a0c8
--- /dev/null
+++ b/integrations/vision/README.md
@@ -0,0 +1,41 @@
+# Optional local vision adapters
+
+This environment adds SAM2 masks, Depth Anything V2 relative-depth priors, and MediaPipe
+face/pose landmarks without adding dependencies to the stdlib-only `forge` core.
+
+Install and prefetch:
+
+```bash
+uv sync --project integrations/vision --python 3.11
+python3 forge/stage1_intake/run_vision_adapter.py prefetch
+python3 forge/stage1_intake/run_vision_adapter.py health
+```
+
+Use:
+
+```bash
+python3 forge/stage1_intake/run_vision_adapter.py \
+ segment reference.png --point 512 320 --out evidence/subject-mask.png
+
+python3 forge/stage1_intake/run_vision_adapter.py \
+ depth reference.png --out evidence/relative-depth.png
+
+python3 forge/stage1_intake/run_vision_adapter.py \
+ landmarks face reference.png --out evidence/face-landmarks.json
+
+python3 forge/stage1_intake/run_vision_adapter.py \
+ landmarks pose reference.png --out evidence/pose-landmarks.json
+```
+
+Every command emits provenance and an evidence boundary. SAM2 masks still require agent
+confirmation that the intended component was selected. Depth is relative, not metric, and cannot
+justify hidden geometry. MediaPipe landmarks require anatomy review before they enter the sculpt
+spec.
+
+The environment and models are local-only:
+
+- environment: `integrations/vision/.venv/`
+- Hugging Face cache: `runtime/vision/huggingface/`
+- MediaPipe task models and manifest: `runtime/vision/models/`
+
+See `docs/integrations/reference_fidelity_tooling.md` for pipeline routing and MCP usage.
diff --git a/integrations/vision/pyproject.toml b/integrations/vision/pyproject.toml
new file mode 100644
index 0000000..47c6ac0
--- /dev/null
+++ b/integrations/vision/pyproject.toml
@@ -0,0 +1,16 @@
+[project]
+name = "img2threejs-vision"
+version = "0.1.0"
+description = "Optional local vision evidence adapters for the img2threejs procedural pipeline"
+requires-python = ">=3.11,<3.13"
+dependencies = [
+ "mediapipe>=0.10.21,<0.11",
+ "numpy>=1.26,<3",
+ "pillow>=11,<13",
+ "torch>=2.5,<3",
+ "torchvision>=0.20,<1",
+ "transformers>=4.56,<5",
+]
+
+[tool.uv]
+package = false
diff --git a/integrations/vision/reference_vision.py b/integrations/vision/reference_vision.py
new file mode 100644
index 0000000..99d8c5b
--- /dev/null
+++ b/integrations/vision/reference_vision.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python3
+"""Optional local vision evidence for img2threejs.
+
+This module is deliberately outside ``forge`` so the core pipeline remains Python
+stdlib-only. Every command emits provenance JSON. The outputs are evidence for the
+agent and deterministic gates; they never choose geometry or approve a build pass.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.metadata
+import json
+import os
+import sys
+import urllib.request
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_RUNTIME = ROOT / "runtime" / "vision"
+DEFAULT_MODELS = DEFAULT_RUNTIME / "models"
+DEFAULT_HF_CACHE = DEFAULT_RUNTIME / "huggingface"
+SAM_MODEL = "facebook/sam2.1-hiera-tiny"
+DEPTH_MODEL = "depth-anything/Depth-Anything-V2-Small-hf"
+FACE_MODEL_URL = (
+ "https://storage.googleapis.com/mediapipe-models/face_landmarker/"
+ "face_landmarker/float16/latest/face_landmarker.task"
+)
+POSE_MODEL_URL = (
+ "https://storage.googleapis.com/mediapipe-models/pose_landmarker/"
+ "pose_landmarker_lite/float16/latest/pose_landmarker_lite.task"
+)
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _write_json(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+
+
+def _versions() -> dict[str, str]:
+ names = ("mediapipe", "numpy", "opencv-contrib-python", "Pillow", "torch", "torchvision", "transformers")
+ versions: dict[str, str] = {}
+ for name in names:
+ try:
+ versions[name] = importlib.metadata.version(name)
+ except importlib.metadata.PackageNotFoundError:
+ versions[name] = "missing"
+ return versions
+
+
+def _device_name(torch_module: Any) -> str:
+ if getattr(torch_module.backends, "mps", None) and torch_module.backends.mps.is_available():
+ return "mps"
+ if torch_module.cuda.is_available():
+ return "cuda"
+ return "cpu"
+
+
+def command_health(args: argparse.Namespace) -> int:
+ import torch
+
+ payload = {
+ "status": "ok",
+ "python": sys.version.split()[0],
+ "platform": sys.platform,
+ "device": _device_name(torch),
+ "packages": _versions(),
+ "models": {
+ "sam2": SAM_MODEL,
+ "depth": DEPTH_MODEL,
+ "faceTask": str(Path(args.models_dir) / "face_landmarker.task"),
+ "poseTask": str(Path(args.models_dir) / "pose_landmarker_lite.task"),
+ },
+ "boundary": "evidence-only; never geometry truth or pass authority",
+ }
+ if args.json_out:
+ _write_json(Path(args.json_out), payload)
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ return 0
+
+
+def _download(url: str, destination: Path) -> dict[str, Any]:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if not destination.exists():
+ with urllib.request.urlopen(url, timeout=180) as response:
+ destination.write_bytes(response.read())
+ return {
+ "url": url,
+ "path": str(destination),
+ "bytes": destination.stat().st_size,
+ "sha256": _sha256(destination),
+ }
+
+
+def command_prefetch(args: argparse.Namespace) -> int:
+ from transformers import AutoImageProcessor, AutoModelForDepthEstimation, Sam2Model, Sam2Processor
+
+ models_dir = Path(args.models_dir)
+ hf_cache = Path(args.hf_cache)
+ models_dir.mkdir(parents=True, exist_ok=True)
+ hf_cache.mkdir(parents=True, exist_ok=True)
+
+ sam_processor = Sam2Processor.from_pretrained(SAM_MODEL, cache_dir=hf_cache, use_fast=False)
+ sam_model = Sam2Model.from_pretrained(SAM_MODEL, cache_dir=hf_cache)
+ depth_processor = AutoImageProcessor.from_pretrained(DEPTH_MODEL, cache_dir=hf_cache, use_fast=False)
+ depth_model = AutoModelForDepthEstimation.from_pretrained(DEPTH_MODEL, cache_dir=hf_cache)
+
+ payload = {
+ "status": "ok",
+ "packages": _versions(),
+ "huggingFaceCache": str(hf_cache),
+ "models": {
+ "sam2": {
+ "id": SAM_MODEL,
+ "revision": getattr(sam_model.config, "_commit_hash", None)
+ or getattr(sam_processor, "_commit_hash", None),
+ },
+ "depth": {
+ "id": DEPTH_MODEL,
+ "revision": getattr(depth_model.config, "_commit_hash", None)
+ or getattr(depth_processor, "_commit_hash", None),
+ },
+ "faceTask": _download(FACE_MODEL_URL, models_dir / "face_landmarker.task"),
+ "poseTask": _download(POSE_MODEL_URL, models_dir / "pose_landmarker_lite.task"),
+ },
+ "boundary": "downloaded models produce priors/evidence only",
+ }
+ manifest = models_dir / "model_manifest.json"
+ _write_json(manifest, payload)
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ return 0
+
+
+def _load_image(path: Path) -> Any:
+ from PIL import Image
+
+ return Image.open(path).convert("RGB")
+
+
+def command_segment(args: argparse.Namespace) -> int:
+ import numpy as np
+ import torch
+ from PIL import Image
+ from transformers import Sam2Model, Sam2Processor
+
+ image_path = Path(args.image).expanduser().resolve()
+ image = _load_image(image_path)
+ device = _device_name(torch)
+ processor = Sam2Processor.from_pretrained(
+ SAM_MODEL,
+ cache_dir=args.hf_cache,
+ local_files_only=True,
+ use_fast=False,
+ )
+ model = Sam2Model.from_pretrained(
+ SAM_MODEL,
+ cache_dir=args.hf_cache,
+ local_files_only=True,
+ ).to(device)
+ model.eval()
+
+ points = args.point or [[image.width / 2.0, image.height / 2.0]]
+ inputs = processor(
+ images=image,
+ input_points=[[points]],
+ input_labels=[[[1] * len(points)]],
+ return_tensors="pt",
+ )
+ original_sizes = inputs["original_sizes"].clone()
+ model_inputs = {
+ key: value.to(device) if hasattr(value, "to") else value
+ for key, value in inputs.items()
+ }
+ with torch.inference_mode():
+ outputs = model(**model_inputs)
+ masks = processor.post_process_masks(outputs.pred_masks.cpu(), original_sizes)[0]
+ scores = outputs.iou_scores.detach().cpu().reshape(-1)
+ best = int(torch.argmax(scores).item())
+ mask_tensor = masks.reshape(-1, masks.shape[-2], masks.shape[-1])[best]
+ mask = (mask_tensor.numpy() > 0).astype(np.uint8) * 255
+
+ output = Path(args.out).expanduser().resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray(mask).save(output)
+ payload = {
+ "kind": "segmentation-mask",
+ "model": SAM_MODEL,
+ "sourceImage": str(image_path),
+ "sourceSha256": _sha256(image_path),
+ "output": str(output),
+ "outputSha256": _sha256(output),
+ "prompt": {"positivePoints": [[round(float(px), 3), round(float(py), 3)] for px, py in points]},
+ "predictedIou": round(float(scores[best].item()), 6),
+ "foregroundPixels": int((mask > 0).sum()),
+ "imageSize": [image.width, image.height],
+ "device": device,
+ "boundary": "mask evidence only; agent must confirm the selected subject/component",
+ }
+ json_out = Path(args.json_out or f"{output}.json")
+ _write_json(json_out, payload)
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ return 0
+
+
+def command_depth(args: argparse.Namespace) -> int:
+ import numpy as np
+ import torch
+ from PIL import Image
+ from transformers import AutoImageProcessor, AutoModelForDepthEstimation
+
+ image_path = Path(args.image).expanduser().resolve()
+ image = _load_image(image_path)
+ device = _device_name(torch)
+ processor = AutoImageProcessor.from_pretrained(
+ DEPTH_MODEL,
+ cache_dir=args.hf_cache,
+ local_files_only=True,
+ use_fast=False,
+ )
+ model = AutoModelForDepthEstimation.from_pretrained(
+ DEPTH_MODEL,
+ cache_dir=args.hf_cache,
+ local_files_only=True,
+ ).to(device)
+ model.eval()
+ inputs = processor(images=image, return_tensors="pt")
+ model_inputs = {
+ key: value.to(device) if hasattr(value, "to") else value
+ for key, value in inputs.items()
+ }
+ with torch.inference_mode():
+ outputs = model(**model_inputs)
+ result = processor.post_process_depth_estimation(
+ outputs,
+ target_sizes=[(image.height, image.width)],
+ )[0]["predicted_depth"].detach().cpu().numpy()
+ minimum = float(result.min())
+ maximum = float(result.max())
+ normalized = (result - minimum) / max(maximum - minimum, 1e-9)
+ pixels = (normalized * 65535.0).round().astype(np.uint16)
+
+ output = Path(args.out).expanduser().resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray(pixels).save(output)
+ payload = {
+ "kind": "relative-depth-prior",
+ "model": DEPTH_MODEL,
+ "sourceImage": str(image_path),
+ "sourceSha256": _sha256(image_path),
+ "output": str(output),
+ "outputSha256": _sha256(output),
+ "rawRange": [minimum, maximum],
+ "imageSize": [image.width, image.height],
+ "device": device,
+ "boundary": "relative depth prior only; never metric scale or hidden geometry truth",
+ }
+ json_out = Path(args.json_out or f"{output}.json")
+ _write_json(json_out, payload)
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ return 0
+
+
+def _category_payload(category: Any) -> dict[str, Any]:
+ return {
+ "index": int(category.index),
+ "score": float(category.score),
+ "name": category.category_name or category.display_name or "",
+ }
+
+
+def command_landmarks(args: argparse.Namespace) -> int:
+ import mediapipe as mp
+ from mediapipe.tasks import python
+ from mediapipe.tasks.python import vision
+
+ image_path = Path(args.image).expanduser().resolve()
+ model_path = Path(args.model or Path(args.models_dir) / (
+ "face_landmarker.task" if args.kind == "face" else "pose_landmarker_lite.task"
+ ))
+ if not model_path.exists():
+ raise FileNotFoundError(f"missing MediaPipe model {model_path}; run the prefetch command first")
+ image = mp.Image.create_from_file(str(image_path))
+ base = python.BaseOptions(
+ model_asset_path=str(model_path),
+ delegate=python.BaseOptions.Delegate.CPU,
+ )
+
+ if args.kind == "face":
+ options = vision.FaceLandmarkerOptions(
+ base_options=base,
+ running_mode=vision.RunningMode.IMAGE,
+ output_face_blendshapes=True,
+ output_facial_transformation_matrixes=True,
+ num_faces=1,
+ )
+ with vision.FaceLandmarker.create_from_options(options) as task:
+ result = task.detect(image)
+ landmarks = [
+ [{"x": p.x, "y": p.y, "z": p.z, "visibility": getattr(p, "visibility", None)} for p in face]
+ for face in result.face_landmarks
+ ]
+ extras = {
+ "blendshapes": [[_category_payload(item) for item in face] for face in result.face_blendshapes],
+ "transformationMatrices": [matrix.tolist() for matrix in result.facial_transformation_matrixes],
+ }
+ else:
+ options = vision.PoseLandmarkerOptions(
+ base_options=base,
+ running_mode=vision.RunningMode.IMAGE,
+ output_segmentation_masks=False,
+ num_poses=1,
+ )
+ with vision.PoseLandmarker.create_from_options(options) as task:
+ result = task.detect(image)
+ landmarks = [
+ [{"x": p.x, "y": p.y, "z": p.z, "visibility": p.visibility} for p in pose]
+ for pose in result.pose_landmarks
+ ]
+ extras = {
+ "worldLandmarks": [
+ [{"x": p.x, "y": p.y, "z": p.z, "visibility": p.visibility} for p in pose]
+ for pose in result.pose_world_landmarks
+ ]
+ }
+
+ payload = {
+ "kind": f"{args.kind}-landmarks",
+ "model": {
+ "path": str(model_path),
+ "sha256": _sha256(model_path),
+ },
+ "sourceImage": str(image_path),
+ "sourceSha256": _sha256(image_path),
+ "landmarks": landmarks,
+ **extras,
+ "boundary": "observed landmark evidence; geometry and anatomy still require agent review",
+ }
+ output = Path(args.out).expanduser().resolve()
+ _write_json(output, payload)
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ return 0
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.set_defaults(func=None)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ health = subparsers.add_parser("health", help="Verify the isolated vision environment")
+ health.add_argument("--models-dir", default=str(DEFAULT_MODELS))
+ health.add_argument("--json-out")
+ health.set_defaults(func=command_health)
+
+ prefetch = subparsers.add_parser("prefetch", help="Download the pinned local vision models")
+ prefetch.add_argument("--models-dir", default=str(DEFAULT_MODELS))
+ prefetch.add_argument("--hf-cache", default=str(DEFAULT_HF_CACHE))
+ prefetch.set_defaults(func=command_prefetch)
+
+ segment = subparsers.add_parser("segment", help="Create a SAM2 point-prompted mask")
+ segment.add_argument("image")
+ # Repeatable. SAM2 resolves a single point to whatever region that point sits in, which on a
+ # character in a busy scene is one garment, not the character: a single click on the sash of a
+ # forest render returned the sash alone at predictedIou 0.604. Several positive points spread over
+ # head, torso and legs tell it they belong to ONE object.
+ segment.add_argument(
+ "--point", nargs=2, type=float, metavar=("X", "Y"), action="append", dest="point",
+ )
+ segment.add_argument("--out", required=True)
+ segment.add_argument("--json-out")
+ segment.add_argument("--hf-cache", default=str(DEFAULT_HF_CACHE))
+ segment.set_defaults(func=command_segment)
+
+ depth = subparsers.add_parser("depth", help="Create a relative Depth Anything V2 prior")
+ depth.add_argument("image")
+ depth.add_argument("--out", required=True)
+ depth.add_argument("--json-out")
+ depth.add_argument("--hf-cache", default=str(DEFAULT_HF_CACHE))
+ depth.set_defaults(func=command_depth)
+
+ landmarks = subparsers.add_parser("landmarks", help="Extract face or pose landmarks with MediaPipe")
+ landmarks.add_argument("kind", choices=("face", "pose"))
+ landmarks.add_argument("image")
+ landmarks.add_argument("--out", required=True)
+ landmarks.add_argument("--model")
+ landmarks.add_argument("--models-dir", default=str(DEFAULT_MODELS))
+ landmarks.set_defaults(func=command_landmarks)
+ return parser
+
+
+def main(argv: list[str]) -> int:
+ os.environ.setdefault("HF_HOME", str(DEFAULT_HF_CACHE))
+ os.environ.setdefault("MPLCONFIGDIR", str(DEFAULT_RUNTIME / "matplotlib"))
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ return int(args.func(args))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/integrations/vision/uv.lock b/integrations/vision/uv.lock
new file mode 100644
index 0000000..6ace17f
--- /dev/null
+++ b/integrations/vision/uv.lock
@@ -0,0 +1,1105 @@
+version = 1
+revision = 3
+requires-python = ">=3.11, <3.13"
+resolution-markers = [
+ "python_full_version >= '3.12'",
+ "python_full_version < '3.12'",
+]
+
+[[package]]
+name = "absl-py"
+version = "2.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d0/4f/d79676ab82f2e42fc3611618139f13a9c4c31d0cff4b486982047679a802/absl_py-2.5.0.tar.gz", hash = "sha256:0c996f25c0490700fadabe6351630f6111534fa0ae252cc6d2014ea3b141135f", size = 118119, upload-time = "2026-07-03T10:57:48.157Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/0a/a10b45aab35b175aded078a462dc8d0c698f5b13946e7cb0869097b78bb6/absl_py-2.5.0-py3-none-any.whl", hash = "sha256:0f17b89f2a4eaaedc4f28c622998aa690564b3012a396a4ffad0821007fe03ba", size = 137410, upload-time = "2026-07-03T10:57:46.735Z" },
+]
+
+[[package]]
+name = "certifi"
+version = "2026.7.22"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
+]
+
+[[package]]
+name = "cffi"
+version = "2.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pycparser", marker = "implementation_name != 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/57/5f/ff100cae70ebe9d8df1c01a00e510e45d9adb5c1fdda84791b199141de97/cffi-2.1.0.tar.gz", hash = "sha256:efc1cdd798b1aaf39b4610bba7aad28c9bea9b910f25c784ccf9ec1fa719d1f9", size = 531036, upload-time = "2026-07-06T21:34:30.382Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d3/67/85c89a59ba36a671e79638f44d466749f08179266a57e4f2ffdf92174072/cffi-2.1.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:02cb7ff33ded4f1532476731f89ede53e2e488a8e6205515a82144246ffa7dcc", size = 183845, upload-time = "2026-07-06T21:32:26.32Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/dd/e3b0baa2d3d6a857ac72b7efbf18e32e487c9cdafcc13049ad765495b15e/cffi-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f5bce581e6b8c235e566a14768a943b172ada3ed73537bb0c0be1edee312d4e7", size = 184186, upload-time = "2026-07-06T21:32:28.025Z" },
+ { url = "https://files.pythonhosted.org/packages/65/68/9f3ef890cf3c6ab97bd531c5677f67613d302165d16f8142b2811782a614/cffi-2.1.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:30b65779d598c370374fefabf138d456fd6f3216bfa7bedfab1ba82025b0cd93", size = 211892, upload-time = "2026-07-06T21:32:29.565Z" },
+ { url = "https://files.pythonhosted.org/packages/22/d7/1a74539db16d8bfd839ff1515948948efbb162e574650fd3d846896eea95/cffi-2.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88023dfe18799507b73f1dbb0d14326a17465de1bc9c9c7655c22845e9ddc3a2", size = 218793, upload-time = "2026-07-06T21:32:30.951Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/d1/9a5b7169499e8e8d8e636de70b97ac7c9447104d2ff1a2cd94790cea5162/cffi-2.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0a96b74cda968eebbad56d973efe5098974f0a9fb323865bf99ea1fd24e3e64c", size = 205737, upload-time = "2026-07-06T21:32:32.216Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/b0/e131a9c41f10607926278453d9596163594fe1c4ebc46efe3b5e5b34eb84/cffi-2.1.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a5781494d4d400a3f47f8f1da94b324f6e6b440a53387774002890a2a2f4b50f", size = 204909, upload-time = "2026-07-06T21:32:33.655Z" },
+ { url = "https://files.pythonhosted.org/packages/fb/d2/4398416cd699b35167947c6e22aca52c47e69ad5695073c9f1f2c52e04aa/cffi-2.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aa7a1b53a2a4452ada2d1b5dade9960b2522f1e61293a811a077439e39029565", size = 217883, upload-time = "2026-07-06T21:32:35.173Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/a5/d4fe77b589e5e82d43ebc809bf2e6474afe8e48e32ea050b9357645b6471/cffi-2.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:9d8272c0e483b024e1b9ad029821470ed8ec65631dbd90217469da0e7cd89f1c", size = 221251, upload-time = "2026-07-06T21:32:36.527Z" },
+ { url = "https://files.pythonhosted.org/packages/22/f0/a2fc43084c0433caf7f461bccc013e28f848d04ee1c5ed7fce71423cf4d9/cffi-2.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7762faa47e8ff7eb80bd261d9a7d8eea2d8baa69de5e95b70c1f338bbe712f02", size = 214250, upload-time = "2026-07-06T21:32:37.852Z" },
+ { url = "https://files.pythonhosted.org/packages/04/8c/b925975448cf20634a9fbd5efceb807219db452653648d2897c0989cab2d/cffi-2.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:89095c1968b4ba8285840e131bf2891b09ae137fe2146905acae0354fbce1b5e", size = 219441, upload-time = "2026-07-06T21:32:39.146Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/da/5c4918a2d61d86fa927d716cb3d8e4626ef8dc8f605a599d32f33897f59a/cffi-2.1.0-cp311-cp311-win32.whl", hash = "sha256:64c753a0f87a256020004f37a1c8c02c480e725f910f0b2a0f3f07debd1b2479", size = 174496, upload-time = "2026-07-06T21:32:40.467Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/c8/6c2de1d55cf35ef8b92885d5ef280790f0fb9634d87ea1cc315176aecd61/cffi-2.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:4f26194e3d95e06501b942642855aed4f953d55e95d7d01b7c4483db3ecff458", size = 185113, upload-time = "2026-07-06T21:32:41.761Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/4e/e8d7cb5783f1841a3c8fb3a7735838d7484d08ec08c9f984b14cac1ac0e9/cffi-2.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:35aaea0c7ee0e58a5cd8c2fd1a48fdf7ece0d2699b7ecdda08194e9ce5dd9b3d", size = 179927, upload-time = "2026-07-06T21:32:42.961Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/85/990925db5df586ec90beb97529c853497e7f85ba0234830447faf41c3057/cffi-2.1.0-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:df2b82571a1b30f58a87bf4e5a9e78d2b1eff6c6ce8fd3aa3757221f93f0863f", size = 184829, upload-time = "2026-07-06T21:32:44.324Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/92/e7bb136ad6b5352603732cf907ef862ca103f20f2031c1735a46300c20c9/cffi-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78474632761faa0fb96f30b1c928c84ebcf68713cbb80d15bab09dfe61640fde", size = 184728, upload-time = "2026-07-06T21:32:45.683Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/c0/d1ec30ffb370f748f2fb54425972bfef9871e0132e82fb589c46b6676049/cffi-2.1.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:5972433ad71a9e46516584ef60a0fda12d9dc459938d1539c3ddecf9bdc1368d", size = 214815, upload-time = "2026-07-06T21:32:48.557Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/dc/5620cf930688be01f2d673804291de757a934c90b946dbdc3d84130c2ea4/cffi-2.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b6422532152adf4e59b110cb2808cee7a033800952f5c036b4af047ee43199e7", size = 222429, upload-time = "2026-07-06T21:32:49.848Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/a4/77b53abbf7a1e0beb9637edbef2a94d15f9c822f591e85d439ffd91519a6/cffi-2.1.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:46b1c8db8f6122420f32d02fffb924c2fe9bc772d228c7c711748fff56aabb2b", size = 210315, upload-time = "2026-07-06T21:32:51.221Z" },
+ { url = "https://files.pythonhosted.org/packages/58/0c/f528df19cc94b675087324d4760d9e6d5bfae97d6217aa4fac43de4f5fcc/cffi-2.1.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9fafc5aa2e2a39aaf7f8cc0c1f044a9b07fca12e558dca53a3cc5c654ad67a7", size = 208859, upload-time = "2026-07-06T21:32:52.512Z" },
+ { url = "https://files.pythonhosted.org/packages/62/f2/c9522a81c32132799a1972c39f5c5f8b4c8b9f00488a23feaa6c06f07741/cffi-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1e9f50d192a3e525b15a75ab5114e442d83d657b7ec29182a991bc9a88fd3a66", size = 221844, upload-time = "2026-07-06T21:32:53.704Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/28/bd53988b9833e8f8ad539d26f4c07a6b3f6bcb1e9e02e7ca038250b3428d/cffi-2.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:98fff996e983a36d3aa2eca83af40c5821202e7e6f32d13ae94e3d2286f10cfe", size = 225287, upload-time = "2026-07-06T21:32:54.907Z" },
+ { url = "https://files.pythonhosted.org/packages/79/99/0d0fd37f055224085f42bbb2c022d002e17dde4a97972822327b07d84101/cffi-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:379de10ce1ba048b1448599d1b37b24caee16309d1ac98d3982fc997f768700b", size = 223681, upload-time = "2026-07-06T21:32:56.329Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/80/c138990aa2a70b1a269f6e06348729836d733d6f970867943f61d367f8cc/cffi-2.1.0-cp312-cp312-win32.whl", hash = "sha256:9b8f0f26ca4e7513c534d351eca551947d053fac438f2a04ac96d882909b0d3a", size = 175269, upload-time = "2026-07-06T21:32:57.777Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/eb/f636456ff21a83fc13c032b58cc5dde061691546ac79efa284b2989b7982/cffi-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:c97f080ea627e2863524c5af3836e2270b5f5dfff1f104392b959f8df0c5d384", size = 185881, upload-time = "2026-07-06T21:32:59.253Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/2c/400ea43e721727dca8a65c4521390e9196757caba4a45643acb2b63271b8/cffi-2.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:6d194185eabd279f1c05ebe3504265ddfc5ad2b58d0714f7db9f01da592e9eb6", size = 180088, upload-time = "2026-07-06T21:33:02.278Z" },
+]
+
+[[package]]
+name = "charset-normalizer"
+version = "3.4.9"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bd/2a/23f34ec9d04624958e137efdc394888716353190e75f25dd22c7a2c7a8aa/charset_normalizer-3.4.9.tar.gz", hash = "sha256:673611bbd43f0810bec0b0f028ddeaaa501190339cac411f347ac76917c3ae7b", size = 152439, upload-time = "2026-07-07T14:34:58.454Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0b/e3/85ec501f206fb049259288c1f3506e53876937fb00edb47009348e66756b/charset_normalizer-3.4.9-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0e94703ec9684807f20cfb5eed95c70f67f2a8f21ad620146d7b5a13677b93e5", size = 317075, upload-time = "2026-07-07T14:32:56.021Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/69/2a5385192e67175f7d8bd5ce4f57c24bc956439adeae5c13a99aa28a53d1/charset_normalizer-3.4.9-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a441ea71902098ffe78c5abe6c494f44160b4af614ed16c3d9a3b1d17fd8ee2", size = 213837, upload-time = "2026-07-07T14:32:57.78Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/46/03ddc7da576d814fe0a36dd1f0fd3258e95404b4b2e3c026b7923d7e133f/charset_normalizer-3.4.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:304b13570067b2547562e308af560b3963857b1fa90bd6afd978130130fe2d6a", size = 235503, upload-time = "2026-07-07T14:32:59.205Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/6e/de0229a7ef40f6f9d28a837eebf4ec47bdca5dab4e900c84f22919af636a/charset_normalizer-3.4.9-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4773092f8019072343a7447203308b176e10199920eb02d6195e81bbb3274c29", size = 229944, upload-time = "2026-07-07T14:33:00.803Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/34/49b9060e8418b14fb5cba9cf6bfb383111e2538a03a1fb18e66a95aeb3d5/charset_normalizer-3.4.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:04ce310cb89c15df659582aee80a0603788732a5e017d5bd5c81158106ce249c", size = 221276, upload-time = "2026-07-07T14:33:02.199Z" },
+ { url = "https://files.pythonhosted.org/packages/44/95/80282cce0fae9c3061203d723ee87da996aed79679e65d8935050ee7ca1f/charset_normalizer-3.4.9-cp311-cp311-manylinux_2_31_armv7l.whl", hash = "sha256:c0323c9daef75ef2e5083624b4585018a0c9d5e3b40f607eed81a311270b934b", size = 205260, upload-time = "2026-07-07T14:33:03.698Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/74/2f62c8821b969ea3bd67cc2e6976834f48ca5d12664d2559ebcd9bcfbed7/charset_normalizer-3.4.9-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:871ff67ea1aad4dfd91736464934d56b32dac49f9fbe16cddba36198a7b3a0db", size = 217786, upload-time = "2026-07-07T14:33:05.12Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/8d/feabb82cb49fcad14515b1d7d1ca4787b0da7fc723a212bf89bc9e0fac52/charset_normalizer-3.4.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:67830fc78e67501f47bb950471b2dcb9b35b140084429318e862895a8e89c993", size = 216798, upload-time = "2026-07-07T14:33:06.629Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/ff/c946d63bc3786d5b84d960b0f7ab7e25b828486a946b5aa997625bcaf6a6/charset_normalizer-3.4.9-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3d92613ec25e43b05f042302531ec0f00b8445190e43325880cbd6ab7c2581da", size = 206429, upload-time = "2026-07-07T14:33:08.006Z" },
+ { url = "https://files.pythonhosted.org/packages/af/ba/5e5007c370702f85d2ef75791fac7943ed41e080364a673b20142e430e3e/charset_normalizer-3.4.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:280081916dc341820640489a66e4696049401ef1cf6dd672f672e70ad915aca3", size = 223066, upload-time = "2026-07-07T14:33:09.783Z" },
+ { url = "https://files.pythonhosted.org/packages/83/d5/9096aa3cf532dfad237861544eb47a0f20d5adbf1039760fed8eaae935d9/charset_normalizer-3.4.9-cp311-cp311-win32.whl", hash = "sha256:ac351b3b8014eead140e77e9717e2992c6bbe30b63bc3422422eb84865412e3d", size = 150456, upload-time = "2026-07-07T14:33:11.217Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/a1/e29995109e455dc8eff8d0fac6ae509be39561318a7cfeac5d33ad029213/charset_normalizer-3.4.9-cp311-cp311-win_amd64.whl", hash = "sha256:6366a16e1a25018694d6a5d784d09b046edc9eac40ea2b54065c3052672516a1", size = 161410, upload-time = "2026-07-07T14:33:12.743Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/8d/1569f4d0032d6ba2a4fe4591c35bf87868c600c41a71eb5c2e1ffa8464c2/charset_normalizer-3.4.9-cp311-cp311-win_arm64.whl", hash = "sha256:1d22856ffbe153a602df38e4a5464f0b748a54002e0d69ac6d2ad0a197cc99ec", size = 152649, upload-time = "2026-07-07T14:33:14.173Z" },
+ { url = "https://files.pythonhosted.org/packages/70/4a/ecbd131485c07fcdfad54e28946d513e3da22ef3b4bd854dcafae54ec739/charset_normalizer-3.4.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:45b0cc4e3556cd875e09102988d1ab8356c998b596c9fced84547c8138b487a0", size = 319300, upload-time = "2026-07-07T14:33:15.666Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/96/5d9364e3342d69f3a045e1777bc47c85c383e6e9466d561b33fdb419d1f9/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b2aff1c7b3884512b9512c3eaadd9bab39fb45042ffaaa1dd08ff2b9f8109d9", size = 215802, upload-time = "2026-07-07T14:33:17.031Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/4c/5361f9aa7f2cb58d94f2ab831b3d493f69efb1d239654b4744e3c09527cb/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9104ed0bd76a429d46f9ec0dbc9b08ad1d2dcdf2b00a5a0daa1c145329b35b44", size = 237171, upload-time = "2026-07-07T14:33:18.576Z" },
+ { url = "https://files.pythonhosted.org/packages/50/78/ce342ca4ff30b2eb49fe6d9578df85974f90c67d294113e94efdd9664cbd/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7b86a2b16095d250c6f58b3d9b2eee6f4147754344f3dab0922f7c9bf7d226c9", size = 233075, upload-time = "2026-07-07T14:33:20.084Z" },
+ { url = "https://files.pythonhosted.org/packages/01/c4/4fa4c8b3097a11f3c5f09a35b72ed6855fb1d332469504962ab7bafcc702/charset_normalizer-3.4.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e226f6218febc71f6c1fc2fafb91c226f75bdc1d8fb12d66823716e891608fd", size = 224256, upload-time = "2026-07-07T14:33:21.747Z" },
+ { url = "https://files.pythonhosted.org/packages/87/3a/ad914516df7e358a81aae018caa5e0470ba827fa6d763b1d2e87d920a5f6/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:90c44bc373b7687f6948b693cceaea1348ae0975d7474746559494468e3c1d84", size = 208784, upload-time = "2026-07-07T14:33:23.313Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/74/3c12f9755717dfe5c5c87da63f35d765fa0c00382ec26bf23f7fae34f2ba/charset_normalizer-3.4.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cdef90ae47919cae358d8ab15797a800ed41da7aba5d72419fb510729e2ed4b", size = 219928, upload-time = "2026-07-07T14:33:24.814Z" },
+ { url = "https://files.pythonhosted.org/packages/33/9a/895095b83e7907abd6d3d99aad3a38ad0d9686cc186cb0c94c24320fe63e/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:60f44ade2cf573dad7a277e6f8ca9a51a21dda572b13bd7d8539bb3cd5dbedde", size = 218489, upload-time = "2026-07-07T14:33:26.42Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/34/ef5c05f412f42520d7709b7d3784d19640839eb7366ded1755511585429f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a1786910334ed46ab1dd73222f2cd1e05c2c3bb39f6dddb4f8b36fc382058a39", size = 210267, upload-time = "2026-07-07T14:33:27.952Z" },
+ { url = "https://files.pythonhosted.org/packages/83/dc/9b29fa4412b318bf3bfea985c35d67eb55e04b59a7c3f2237168b0e0be6f/charset_normalizer-3.4.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03d07803992c6c7bbc976327f34b18b6160327fc81cb82c9d504720ac0be3b62", size = 226030, upload-time = "2026-07-07T14:33:29.397Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/42/6dbc00b8cd16011691203e33570fa42ed5746599a2e878112d16eab403a3/charset_normalizer-3.4.9-cp312-cp312-win32.whl", hash = "sha256:78841cccf1af7b40f6f716338d50c0902dbe88d9f800b3c973b7a9a0a693a642", size = 151185, upload-time = "2026-07-07T14:33:30.781Z" },
+ { url = "https://files.pythonhosted.org/packages/80/cc/f920afd1a23c58ccd53c1d36085a71893a4737ff5e66e0371efab6809850/charset_normalizer-3.4.9-cp312-cp312-win_amd64.whl", hash = "sha256:4b3dac63058cc36820b0dd072f89898604e2d39686fe05321729d00d8ac185a0", size = 162557, upload-time = "2026-07-07T14:33:32.176Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/e6/0386d43a261ff4e4b30c5857af7df877254b46bec7b9d1b74b6bf969a90b/charset_normalizer-3.4.9-cp312-cp312-win_arm64.whl", hash = "sha256:78fa18e436a1a0e58dbd7e02fc4473f3f32cceb12df9dfca542d075961c307d2", size = 152665, upload-time = "2026-07-07T14:33:33.711Z" },
+ { url = "https://files.pythonhosted.org/packages/98/2b/f97f1c193fb855c345d678f5077d6926034db0722df74c8f057020e05a25/charset_normalizer-3.4.9-py3-none-any.whl", hash = "sha256:68e5f26a1ad57ded6d1cfb85331d1c1a195314756471d97758c48498bb4dcdf5", size = 64538, upload-time = "2026-07-07T14:34:56.993Z" },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
+]
+
+[[package]]
+name = "contourpy"
+version = "1.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" },
+ { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" },
+ { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" },
+ { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" },
+ { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" },
+ { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" },
+ { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" },
+ { url = "https://files.pythonhosted.org/packages/be/45/adfee365d9ea3d853550b2e735f9d66366701c65db7855cd07621732ccfc/contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb", size = 293419, upload-time = "2025-07-26T12:01:21.16Z" },
+ { url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" },
+ { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" },
+ { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" },
+ { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" },
+ { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" },
+ { url = "https://files.pythonhosted.org/packages/cf/8f/5847f44a7fddf859704217a99a23a4f6417b10e5ab1256a179264561540e/contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69", size = 185018, upload-time = "2025-07-26T12:01:35.64Z" },
+ { url = "https://files.pythonhosted.org/packages/19/e8/6026ed58a64563186a9ee3f29f41261fd1828f527dd93d33b60feca63352/contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b", size = 226567, upload-time = "2025-07-26T12:01:36.804Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" },
+ { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" },
+]
+
+[[package]]
+name = "cuda-bindings"
+version = "13.3.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cuda-pathfinder" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/6b/457ca12dad3ee9bfcc9a545cfd6b64b359ba49de40f776f6e028e678f262/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5879712accf6e14bb01aa5e67440eb84998b8d104b509cc7a6dc0b8f656a474", size = 6053539, upload-time = "2026-05-29T23:11:43.19Z" },
+ { url = "https://files.pythonhosted.org/packages/95/7a/c5e3c34a409b148f5c0f5a4ea374158f95d488862c1dffedf9aa5c639df9/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:04436a9364059c84b8f9636f359eccda1cf814341f5b670c71d80d2f79dbc708", size = 6674166, upload-time = "2026-05-29T23:11:45.478Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/67/5e7dba1ba576dd73da5dee894ca076ca5e959450dfff66d6d510a255d1f7/cuda_bindings-13.3.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7855c4868aabc0cfae28abbe83d56734bdfbd08f08fc234ac1912a12858bf49", size = 6025351, upload-time = "2026-05-29T23:11:49.685Z" },
+ { url = "https://files.pythonhosted.org/packages/39/2a/6d2e9047d1fb243dbaa364b01e0297534b9ed7fd27dba1c9f361519cf69b/cuda_bindings-13.3.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e32d08f71ebcdf00f0f41eab2eb37e8da94c8ed411cc9f7f7a019ce6b34abe3a", size = 6657965, upload-time = "2026-05-29T23:11:52.227Z" },
+]
+
+[[package]]
+name = "cuda-pathfinder"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fc/b4/d088047afe39827556df21118cac9ffd20cc3f968c99a7681494d1eb333c/cuda_pathfinder-1.6.0-py3-none-any.whl", hash = "sha256:1503af579d8379c24bdd65528379bc57039b0455be9f5f9686cf8e473a1fce51", size = 54591, upload-time = "2026-07-21T15:03:56.224Z" },
+]
+
+[[package]]
+name = "cuda-toolkit"
+version = "13.0.3.0"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" },
+]
+
+[package.optional-dependencies]
+cublas = [
+ { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cudart = [
+ { name = "nvidia-cuda-runtime", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cufft = [
+ { name = "nvidia-cufft", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cufile = [
+ { name = "nvidia-cufile", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cupti = [
+ { name = "nvidia-cuda-cupti", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+curand = [
+ { name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cusolver = [
+ { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-cusolver", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+cusparse = [
+ { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+ { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+nvjitlink = [
+ { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+nvrtc = [
+ { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+nvtx = [
+ { name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" },
+]
+
+[[package]]
+name = "cycler"
+version = "0.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },
+]
+
+[[package]]
+name = "filelock"
+version = "3.32.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/57/3ba6e6cb097f85b855b00163d169f35365f44277df044dcf96d55b8f62a3/filelock-3.32.2.tar.gz", hash = "sha256:c33351e1f49cae33414acbc6d56784e6ecee82514ec90795da1161fc4836b5b8", size = 217172, upload-time = "2026-07-29T22:46:04.895Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/e8/72f8cef9fdfeffe06213fe8508039396ee48daa0e3259457ed766173bfd6/filelock-3.32.2-py3-none-any.whl", hash = "sha256:87dd94cf281e586d135fa51132b8e3d9a598b316e90377a288663c9321036c82", size = 98830, upload-time = "2026-07-29T22:46:03.52Z" },
+]
+
+[[package]]
+name = "flatbuffers"
+version = "25.12.19"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" },
+]
+
+[[package]]
+name = "fonttools"
+version = "4.63.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/84/69/c97f2c18e0db87d2c7b15da1974dace76ae938f1cfa22e2727a648b7ed43/fonttools-4.63.0.tar.gz", hash = "sha256:caeb583deeb5168e694b65cda8b4ee62abedfa66cf88488734466f2366b9c4e0", size = 3597189, upload-time = "2026-05-14T12:04:30.958Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/75/2b/a7f1545bdf5da69c4bda0cea2a5781f0ad2a6623e0277267672db43c5fe6/fonttools-4.63.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2b8ae05d9eacf6081414d759c0a352769ac28ce31280d6bb8e77b03f9e3c449f", size = 2881793, upload-time = "2026-05-14T12:02:56.645Z" },
+ { url = "https://files.pythonhosted.org/packages/49/50/965308c703f085f225db2886813b27e015b8b3438c350b22dd65b52c2a2c/fonttools-4.63.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:79cdc9f567aec74a72918fd060283911406750cbc9fd28c1316023deb6ce31a9", size = 2428130, upload-time = "2026-05-14T12:02:58.891Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/38/6937fbd7f2dc3a6b48725851bc2c15ec949b9af14d9bbcb5fe83cdf9bdf9/fonttools-4.63.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c14b4fd138c4bafcca294765c547914e1aa431ae1ca94ab99d8db08c958bd3b", size = 5111952, upload-time = "2026-05-14T12:03:01.263Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/43/a81f20050a3115b57d62c8e781446949512eac36690dc384ccea65ff4cc1/fonttools-4.63.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d76ac49f929aecaf82d83250b8347e099d7aecba0f4726c1d9b6df3b8bb5fe18", size = 5082308, upload-time = "2026-05-14T12:03:03.211Z" },
+ { url = "https://files.pythonhosted.org/packages/67/00/cdd9d4944ca6ae280d01e69cc37bde3bf663630b837a6fc6d2cd65d80e0e/fonttools-4.63.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dcf076a4474fe0d7367e5bbf5b052c7284fa1feca729c04176ce513521afd8a0", size = 5087932, upload-time = "2026-05-14T12:03:05.147Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/f1/0aa0dbea778c75adbef223c42019fd47d22262b905974d62d829545d485f/fonttools-4.63.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:7dd683fef0663e9f0f45cf541d788d24caa3ec9db50796b588e1757d8b3bc007", size = 5213271, upload-time = "2026-05-14T12:03:07.238Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/99/253e4056e1f0e67b9390125a154b73b5eb73ad521bece95c004858fdeec2/fonttools-4.63.0-cp311-cp311-win32.whl", hash = "sha256:afefc1ed0a59785a7fb06ea7e1678e849c193e1e387db783579bc7b3056fcfcb", size = 2304473, upload-time = "2026-05-14T12:03:09.271Z" },
+ { url = "https://files.pythonhosted.org/packages/08/60/defa5e69641db890a63be281f41345f4c33b157824eaf0b9fad3e08b0dcb/fonttools-4.63.0-cp311-cp311-win_amd64.whl", hash = "sha256:063e08bd17bd5a90127a14123de0d6a952dbc847695fd98b63c043d58057f90c", size = 2356389, upload-time = "2026-05-14T12:03:11.53Z" },
+ { url = "https://files.pythonhosted.org/packages/08/ef/b3c6b9b5be2f82416d73fe2ed2e96e2793cd80e7510bd6a17ca79cdd88ec/fonttools-4.63.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:37dd23e621e3b0aef1baa70a303b80aaf38449632cfc8fd2a55fb285bbccfc02", size = 2881131, upload-time = "2026-05-14T12:03:13.386Z" },
+ { url = "https://files.pythonhosted.org/packages/44/a0/c815bea63117fa63e4e1c01f8a1110d2112fa003f838e6467094ec2432ce/fonttools-4.63.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a9faff9e0c1f76f9fd55899d2ce785832efebab37eb8ae13995853aef178bef0", size = 2426704, upload-time = "2026-05-14T12:03:15.801Z" },
+ { url = "https://files.pythonhosted.org/packages/44/04/0b91d8e916e92ad1fac9e4624760baf0fd5ff2ead614c2f68fb21373f03f/fonttools-4.63.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef3048ef05dbb552b89817713d9cac912e00d0fde4a3105c00d29e52e10c89af", size = 5044298, upload-time = "2026-05-14T12:03:18.085Z" },
+ { url = "https://files.pythonhosted.org/packages/77/c7/2342da9830e3e9d4870305ca5d2091d2a83284f2953079b7bdd3b5e029d8/fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:58dc6bb86a78d782f00f9190ca02c119cf5bbe2807536e361e18d42019f877d8", size = 4999800, upload-time = "2026-05-14T12:03:20.161Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/6d/67fe16c48d7ce050979b33f47e0d28a318f02da030602e944c34f7a16ef3/fonttools-4.63.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ee08ebfa58f6e1aeff5697ab9582105bb620008c1caafb681e4c557e7483027b", size = 4982666, upload-time = "2026-05-14T12:03:22.87Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/00/3bbab338c07c71fa56269953845e92c951a61457bbbb0f1022551ea266d9/fonttools-4.63.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:27fdc65af8da6f88b9c6121c47a464cbe359fcfff7ff6fc2d37a1f395d755b78", size = 5133598, upload-time = "2026-05-14T12:03:25.168Z" },
+ { url = "https://files.pythonhosted.org/packages/62/f2/aa27c7f98db5b064883dadcc5283947e81e034de42e22a33675878d98b54/fonttools-4.63.0-cp312-cp312-win32.whl", hash = "sha256:af2fd1664d00a397d75f806985ddb36282091c2131a73a6485c23b4a34722263", size = 2292575, upload-time = "2026-05-14T12:03:27.496Z" },
+ { url = "https://files.pythonhosted.org/packages/87/36/cccb9bc2a6ab63d1b2980374f0dca72ce95ae267c9b4cfe77455bb70d0d4/fonttools-4.63.0-cp312-cp312-win_amd64.whl", hash = "sha256:59ac449f8cca9b4ffa08d2e7bbadad87ce710d69d1eda5c3c1ce579baa987272", size = 2343211, upload-time = "2026-05-14T12:03:30.057Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" },
+]
+
+[[package]]
+name = "fsspec"
+version = "2026.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" },
+]
+
+[[package]]
+name = "hf-xet"
+version = "1.5.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/63/39/67be8d71f900d9a55761b6022821d6679fb56c64f1b6063d5af2c2606727/hf_xet-1.5.2.tar.gz", hash = "sha256:73044bd31bae33c984af832d19c752a0dffb67518fee9ddbd91d616e1101cf47", size = 903674, upload-time = "2026-07-16T17:29:56.833Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/ba/2b70603c7552db82baeb2623e2336898304a17328845151be4fe1f48d420/hf_xet-1.5.2-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:f922b8f5fb84f1dd3d7ab7a1316354a1bca9b1c73ecfc19c76e51a2a49d29799", size = 4033760, upload-time = "2026-07-16T17:29:43.884Z" },
+ { url = "https://files.pythonhosted.org/packages/60/ac/b097a86a1e4a6098f3a79382643ab09d5733d87ccc864877ad1e12b49b70/hf_xet-1.5.2-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:045f84440c55cdeb659cf1a1dd48c77bcd0d2e93632e2fea8f2c3bdee79f38ed", size = 3841438, upload-time = "2026-07-16T17:29:45.539Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/35/db860aa3a0780660324a506ad4b3d322ddc6ecbba4b9340aed0942cbf21c/hf_xet-1.5.2-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:db78c39c83d6279daddc98e2238f373ab8980685556d42472b4ec51abcf03e8c", size = 4428006, upload-time = "2026-07-16T17:29:46.996Z" },
+ { url = "https://files.pythonhosted.org/packages/af/6b/832dd980af4b0c3ae0660e309285f2ffcdff2faa38129390dbb47aa4a3f9/hf_xet-1.5.2-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7db73c810500c54c6760be8c39d4b2e476974de85424c50063efc22fdda13025", size = 4221099, upload-time = "2026-07-16T17:29:48.525Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/05/ae50f0d34e3254e6c3e208beb2519f6b8673016fc4b3643badaf6450d186/hf_xet-1.5.2-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6395cfe3c9cbead4f16b31808b0e67eac428b66c656f856e99636adaddea878f", size = 4420766, upload-time = "2026-07-16T17:29:50.092Z" },
+ { url = "https://files.pythonhosted.org/packages/07/a9/c050bc2743a2bcd68928bfee157b08681667a164a24ec95fbfcfcd717e08/hf_xet-1.5.2-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:cde8cd167126bb6109b2ceb19b844433a4988643e8f3e01dd9dd0e4a34535097", size = 4636716, upload-time = "2026-07-16T17:29:51.62Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/f8/68b01c5c2edb56ac9a67b3d076ffddcb90867abaee923923eb34e7a14e76/hf_xet-1.5.2-cp38-abi3-win_amd64.whl", hash = "sha256:ecf63d1cb69a9a7319910f8f83fcf9b46e7a32dfcf4b8f8eeddb55f647306e65", size = 3988373, upload-time = "2026-07-16T17:29:53.395Z" },
+ { url = "https://files.pythonhosted.org/packages/39/c6/988383e9dc17294d536fcbcd6fd16eed882e411ad16c954984a53e47b09c/hf_xet-1.5.2-cp38-abi3-win_arm64.whl", hash = "sha256:1da28519496eb7c8094c11e4d25509b4a468457a0302d58136099db2fd9a671d", size = 3816957, upload-time = "2026-07-16T17:29:54.991Z" },
+]
+
+[[package]]
+name = "huggingface-hub"
+version = "0.36.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "requests" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7c/b7/8cb61d2eece5fb05a83271da168186721c450eb74e3c31f7ef3169fa475b/huggingface_hub-0.36.2.tar.gz", hash = "sha256:1934304d2fb224f8afa3b87007d58501acfda9215b334eed53072dd5e815ff7a", size = 649782, upload-time = "2026-02-06T09:24:13.098Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a8/af/48ac8483240de756d2438c380746e7130d1c6f75802ef22f3c6d49982787/huggingface_hub-0.36.2-py3-none-any.whl", hash = "sha256:48f0c8eac16145dfce371e9d2d7772854a4f591bcb56c9cf548accf531d54270", size = 566395, upload-time = "2026-02-06T09:24:11.133Z" },
+]
+
+[[package]]
+name = "idna"
+version = "3.18"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" },
+]
+
+[[package]]
+name = "img2threejs-vision"
+version = "0.1.0"
+source = { virtual = "." }
+dependencies = [
+ { name = "mediapipe" },
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+ { name = "pillow" },
+ { name = "torch" },
+ { name = "torchvision" },
+ { name = "transformers" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "mediapipe", specifier = ">=0.10.21,<0.11" },
+ { name = "numpy", specifier = ">=1.26,<3" },
+ { name = "pillow", specifier = ">=11,<13" },
+ { name = "torch", specifier = ">=2.5,<3" },
+ { name = "torchvision", specifier = ">=0.20,<1" },
+ { name = "transformers", specifier = ">=4.56,<5" },
+]
+
+[[package]]
+name = "jinja2"
+version = "3.1.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markupsafe" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
+]
+
+[[package]]
+name = "kiwisolver"
+version = "1.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d0/67/9c61eccb13f0bdca9307614e782fec49ffdde0f7a2314935d489fa93cd9c/kiwisolver-1.5.0.tar.gz", hash = "sha256:d4193f3d9dc3f6f79aaed0e5637f45d98850ebf01f7ca20e69457f3e8946b66a", size = 103482, upload-time = "2026-03-09T13:15:53.382Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/dd/a495a9c104be1c476f0386e714252caf2b7eca883915422a64c50b88c6f5/kiwisolver-1.5.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9eed0f7edbb274413b6ee781cca50541c8c0facd3d6fd289779e494340a2b85c", size = 122798, upload-time = "2026-03-09T13:12:58.963Z" },
+ { url = "https://files.pythonhosted.org/packages/11/60/37b4047a2af0cf5ef6d8b4b26e91829ae6fc6a2d1f74524bcb0e7cd28a32/kiwisolver-1.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3c4923e404d6bcd91b6779c009542e5647fef32e4a5d75e115e3bbac6f2335eb", size = 66216, upload-time = "2026-03-09T13:13:00.155Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/aa/510dc933d87767584abfe03efa445889996c70c2990f6f87c3ebaa0a18c5/kiwisolver-1.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0df54df7e686afa55e6f21fb86195224a6d9beb71d637e8d7920c95cf0f89aac", size = 63911, upload-time = "2026-03-09T13:13:01.671Z" },
+ { url = "https://files.pythonhosted.org/packages/80/46/bddc13df6c2a40741e0cc7865bb1c9ed4796b6760bd04ce5fae3928ef917/kiwisolver-1.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2517e24d7315eb51c10664cdb865195df38ab74456c677df67bb47f12d088a27", size = 1438209, upload-time = "2026-03-09T13:13:03.385Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/d6/76621246f5165e5372f02f5e6f3f48ea336a8f9e96e43997d45b240ed8cd/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff710414307fefa903e0d9bdf300972f892c23477829f49504e59834f4195398", size = 1248888, upload-time = "2026-03-09T13:13:05.231Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/c1/31559ec6fb39a5b48035ce29bb63ade628f321785f38c384dee3e2c08bc1/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6176c1811d9d5a04fa391c490cc44f451e240697a16977f11c6f722efb9041db", size = 1266304, upload-time = "2026-03-09T13:13:06.743Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/ef/1cb8276f2d29cc6a41e0a042f27946ca347d3a4a75acf85d0a16aa6dcc82/kiwisolver-1.5.0-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50847dca5d197fcbd389c805aa1a1cf32f25d2e7273dc47ab181a517666b68cc", size = 1319650, upload-time = "2026-03-09T13:13:08.607Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/e4/5ba3cecd7ce6236ae4a80f67e5d5531287337d0e1f076ca87a5abe4cd5d0/kiwisolver-1.5.0-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:01808c6d15f4c3e8559595d6d1fe6411c68e4a3822b4b9972b44473b24f4e679", size = 970949, upload-time = "2026-03-09T13:13:10.299Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/69/dc61f7ae9a2f071f26004ced87f078235b5507ab6e5acd78f40365655034/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1f9f4121ec58628c96baa3de1a55a4e3a333c5102c8e94b64e23bf7b2083309", size = 2199125, upload-time = "2026-03-09T13:13:11.841Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/7b/abbe0f1b5afa85f8d084b73e90e5f801c0939eba16ac2e49af7c61a6c28d/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:b7d335370ae48a780c6e6a6bbfa97342f563744c39c35562f3f367665f5c1de2", size = 2293783, upload-time = "2026-03-09T13:13:14.399Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/80/5908ae149d96d81580d604c7f8aefd0e98f4fd728cf172f477e9f2a81744/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:800ee55980c18545af444d93fdd60c56b580db5cc54867d8cbf8a1dc0829938c", size = 1960726, upload-time = "2026-03-09T13:13:16.047Z" },
+ { url = "https://files.pythonhosted.org/packages/84/08/a78cb776f8c085b7143142ce479859cfec086bd09ee638a317040b6ef420/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:c438f6ca858697c9ab67eb28246c92508af972e114cac34e57a6d4ba17a3ac08", size = 2464738, upload-time = "2026-03-09T13:13:17.897Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/e1/65584da5356ed6cb12c63791a10b208860ac40a83de165cb6a6751a686e3/kiwisolver-1.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:8c63c91f95173f9c2a67c7c526b2cea976828a0e7fced9cdcead2802dc10f8a4", size = 2270718, upload-time = "2026-03-09T13:13:19.421Z" },
+ { url = "https://files.pythonhosted.org/packages/be/6c/28f17390b62b8f2f520e2915095b3c94d88681ecf0041e75389d9667f202/kiwisolver-1.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:beb7f344487cdcb9e1efe4b7a29681b74d34c08f0043a327a74da852a6749e7b", size = 73480, upload-time = "2026-03-09T13:13:20.818Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/0e/2ee5debc4f77a625778fec5501ff3e8036fe361b7ee28ae402a485bb9694/kiwisolver-1.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:ad4ae4ffd1ee9cd11357b4c66b612da9888f4f4daf2f36995eda64bd45370cac", size = 64930, upload-time = "2026-03-09T13:13:21.997Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/b2/818b74ebea34dabe6d0c51cb1c572e046730e64844da6ed646d5298c40ce/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4e9750bc21b886308024f8a54ccb9a2cc38ac9fa813bf4348434e3d54f337ff9", size = 123158, upload-time = "2026-03-09T13:13:23.127Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/d9/405320f8077e8e1c5c4bd6adc45e1e6edf6d727b6da7f2e2533cf58bff71/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:72ec46b7eba5b395e0a7b63025490d3214c11013f4aacb4f5e8d6c3041829588", size = 66388, upload-time = "2026-03-09T13:13:24.765Z" },
+ { url = "https://files.pythonhosted.org/packages/99/9f/795fedf35634f746151ca8839d05681ceb6287fbed6cc1c9bf235f7887c2/kiwisolver-1.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ed3a984b31da7481b103f68776f7128a89ef26ed40f4dc41a2223cda7fb24819", size = 64068, upload-time = "2026-03-09T13:13:25.878Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/13/680c54afe3e65767bed7ec1a15571e1a2f1257128733851ade24abcefbcc/kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bb5136fb5352d3f422df33f0c879a1b0c204004324150cc3b5e3c4f310c9049f", size = 1477934, upload-time = "2026-03-09T13:13:27.166Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/2f/cebfcdb60fd6a9b0f6b47a9337198bcbad6fbe15e68189b7011fd914911f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b2af221f268f5af85e776a73d62b0845fc8baf8ef0abfae79d29c77d0e776aaf", size = 1278537, upload-time = "2026-03-09T13:13:28.707Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/0d/9b782923aada3fafb1d6b84e13121954515c669b18af0c26e7d21f579855/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b0f172dc8ffaccb8522d7c5d899de00133f2f1ca7b0a49b7da98e901de87bf2d", size = 1296685, upload-time = "2026-03-09T13:13:30.528Z" },
+ { url = "https://files.pythonhosted.org/packages/27/70/83241b6634b04fe44e892688d5208332bde130f38e610c0418f9ede47ded/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6ab8ba9152203feec73758dad83af9a0bbe05001eb4639e547207c40cfb52083", size = 1346024, upload-time = "2026-03-09T13:13:32.818Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/db/30ed226fb271ae1a6431fc0fe0edffb2efe23cadb01e798caeb9f2ceae8f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:cdee07c4d7f6d72008d3f73b9bf027f4e11550224c7c50d8df1ae4a37c1402a6", size = 987241, upload-time = "2026-03-09T13:13:34.435Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/bd/c314595208e4c9587652d50959ead9e461995389664e490f4dce7ff0f782/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c60d3c9b06fb23bd9c6139281ccbdc384297579ae037f08ae90c69f6845c0b1", size = 2227742, upload-time = "2026-03-09T13:13:36.4Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/43/0499cec932d935229b5543d073c2b87c9c22846aab48881e9d8d6e742a2d/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e315e5ec90d88e140f57696ff85b484ff68bb311e36f2c414aa4286293e6dee0", size = 2323966, upload-time = "2026-03-09T13:13:38.204Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/6f/79b0d760907965acfd9d61826a3d41f8f093c538f55cd2633d3f0db269f6/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:1465387ac63576c3e125e5337a6892b9e99e0627d52317f3ca79e6930d889d15", size = 1977417, upload-time = "2026-03-09T13:13:39.966Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/31/01d0537c41cb75a551a438c3c7a80d0c60d60b81f694dac83dd436aec0d0/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:530a3fd64c87cffa844d4b6b9768774763d9caa299e9b75d8eca6a4423b31314", size = 2491238, upload-time = "2026-03-09T13:13:41.698Z" },
+ { url = "https://files.pythonhosted.org/packages/e4/34/8aefdd0be9cfd00a44509251ba864f5caf2991e36772e61c408007e7f417/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1d9daea4ea6b9be74fe2f01f7fbade8d6ffab263e781274cffca0dba9be9eec9", size = 2294947, upload-time = "2026-03-09T13:13:43.343Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/cf/0348374369ca588f8fe9c338fae49fa4e16eeb10ffb3d012f23a54578a9e/kiwisolver-1.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:f18c2d9782259a6dc132fdc7a63c168cbc74b35284b6d75c673958982a378384", size = 73569, upload-time = "2026-03-09T13:13:45.792Z" },
+ { url = "https://files.pythonhosted.org/packages/28/26/192b26196e2316e2bd29deef67e37cdf9870d9af8e085e521afff0fed526/kiwisolver-1.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:f7c7553b13f69c1b29a5bde08ddc6d9d0c8bfb84f9ed01c30db25944aeb852a7", size = 64997, upload-time = "2026-03-09T13:13:46.878Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/fa/2910df836372d8761bb6eff7d8bdcb1613b5c2e03f260efe7abe34d388a7/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:5ae8e62c147495b01a0f4765c878e9bfdf843412446a247e28df59936e99e797", size = 130262, upload-time = "2026-03-09T13:15:35.629Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/41/c5f71f9f00aabcc71fee8b7475e3f64747282580c2fe748961ba29b18385/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f6764a4ccab3078db14a632420930f6186058750df066b8ea2a7106df91d3203", size = 138036, upload-time = "2026-03-09T13:15:36.894Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/91/53255615acd2a1eaca307ede3c90eb550bae9c94581f8c00081b6b1c8f44/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:1f1489f769582498610e015a8ef2d36f28f505ab3096d0e16b4858a9ec214f57", size = 75987, upload-time = "2026-03-09T13:15:39.65Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/eb/5fcbbbf9a0e2c3a35effb88831a483345326bbc3a030a3b5b69aee647f84/kiwisolver-1.5.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ec4c85dc4b687c7f7f15f553ff26a98bfe8c58f5f7f0ac8905f0ba4c7be60232", size = 59532, upload-time = "2026-03-09T13:15:47.047Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/9b/e17104555bb4db148fd52327feea1e96be4b88e8e008b029002c281a21ab/kiwisolver-1.5.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:12e91c215a96e39f57989c8912ae761286ac5a9584d04030ceb3368a357f017a", size = 57420, upload-time = "2026-03-09T13:15:48.199Z" },
+ { url = "https://files.pythonhosted.org/packages/48/44/2b5b95b7aa39fb2d8d9d956e0f3d5d45aef2ae1d942d4c3ffac2f9cfed1a/kiwisolver-1.5.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:be4a51a55833dc29ab5d7503e7bcb3b3af3402d266018137127450005cdfe737", size = 79892, upload-time = "2026-03-09T13:15:49.694Z" },
+ { url = "https://files.pythonhosted.org/packages/52/7d/7157f9bba6b455cfb4632ed411e199fc8b8977642c2b12082e1bd9e6d173/kiwisolver-1.5.0-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:daae526907e262de627d8f70058a0f64acc9e2641c164c99c8f594b34a799a16", size = 77603, upload-time = "2026-03-09T13:15:50.945Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/dd/8050c947d435c8d4bc94e3252f4d8bb8a76cfb424f043a8680be637a57f1/kiwisolver-1.5.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:59cd8683f575d96df5bb48f6add94afc055012c29e28124fcae2b63661b9efb1", size = 73558, upload-time = "2026-03-09T13:15:52.112Z" },
+]
+
+[[package]]
+name = "markupsafe"
+version = "3.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/08/db/fefacb2136439fc8dd20e797950e749aa1f4997ed584c62cfb8ef7c2be0e/markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad", size = 11631, upload-time = "2025-09-27T18:36:18.185Z" },
+ { url = "https://files.pythonhosted.org/packages/e1/2e/5898933336b61975ce9dc04decbc0a7f2fee78c30353c5efba7f2d6ff27a/markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a", size = 12058, upload-time = "2025-09-27T18:36:19.444Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/09/adf2df3699d87d1d8184038df46a9c80d78c0148492323f4693df54e17bb/markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50", size = 24287, upload-time = "2025-09-27T18:36:20.768Z" },
+ { url = "https://files.pythonhosted.org/packages/30/ac/0273f6fcb5f42e314c6d8cd99effae6a5354604d461b8d392b5ec9530a54/markupsafe-3.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf", size = 22940, upload-time = "2025-09-27T18:36:22.249Z" },
+ { url = "https://files.pythonhosted.org/packages/19/ae/31c1be199ef767124c042c6c3e904da327a2f7f0cd63a0337e1eca2967a8/markupsafe-3.0.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f", size = 21887, upload-time = "2025-09-27T18:36:23.535Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/76/7edcab99d5349a4532a459e1fe64f0b0467a3365056ae550d3bcf3f79e1e/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a", size = 23692, upload-time = "2025-09-27T18:36:24.823Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/28/6e74cdd26d7514849143d69f0bf2399f929c37dc2b31e6829fd2045b2765/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115", size = 21471, upload-time = "2025-09-27T18:36:25.95Z" },
+ { url = "https://files.pythonhosted.org/packages/62/7e/a145f36a5c2945673e590850a6f8014318d5577ed7e5920a4b3448e0865d/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a", size = 22923, upload-time = "2025-09-27T18:36:27.109Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/62/d9c46a7f5c9adbeeeda52f5b8d802e1094e9717705a645efc71b0913a0a8/markupsafe-3.0.3-cp311-cp311-win32.whl", hash = "sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19", size = 14572, upload-time = "2025-09-27T18:36:28.045Z" },
+ { url = "https://files.pythonhosted.org/packages/83/8a/4414c03d3f891739326e1783338e48fb49781cc915b2e0ee052aa490d586/markupsafe-3.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01", size = 15077, upload-time = "2025-09-27T18:36:29.025Z" },
+ { url = "https://files.pythonhosted.org/packages/35/73/893072b42e6862f319b5207adc9ae06070f095b358655f077f69a35601f0/markupsafe-3.0.3-cp311-cp311-win_arm64.whl", hash = "sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c", size = 13876, upload-time = "2025-09-27T18:36:29.954Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" },
+ { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" },
+ { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" },
+]
+
+[[package]]
+name = "matplotlib"
+version = "3.11.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "contourpy" },
+ { name = "cycler" },
+ { name = "fonttools" },
+ { name = "kiwisolver" },
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+ { name = "packaging" },
+ { name = "pillow" },
+ { name = "pyparsing" },
+ { name = "python-dateutil" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/49/64/f9a391af28f518b11ad45a8a712353c94a0aefce09d3703200e5c54b610a/matplotlib-3.11.1.tar.gz", hash = "sha256:69647db5746941c793d6e445a4cd349323ffb87d9cc958c2ad84a659b4832d30", size = 32612045, upload-time = "2026-07-18T03:39:46.63Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6e/d0/791aa183dd88491555cf7d4be0b52b0bcf6c3c2a2c22c815a2e819bf53e2/matplotlib-3.11.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:b7cf158e7add54a8d51ac9b5a84abd6d4e13ed4951b4f25f1c5139f41c2addb2", size = 9440302, upload-time = "2026-07-18T03:38:03.844Z" },
+ { url = "https://files.pythonhosted.org/packages/35/74/82bbdf683a301f4478384c8aaba6903631a2ca18294b2d7655c9a542bffb/matplotlib-3.11.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d2ace7273b9a5061a3b420918a16fae1f2dc5dfee1abcc13aba71b5d94b1820c", size = 9268549, upload-time = "2026-07-18T03:38:06.144Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/f0/9b4298911303f74e6d83e64a81d996c0616405ec95046fac7f17e4258b9e/matplotlib-3.11.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aee55e9041211bf84302ab55ec3965df18dd90ae19f8b58332a7feaf208bfe83", size = 10024922, upload-time = "2026-07-18T03:38:08.236Z" },
+ { url = "https://files.pythonhosted.org/packages/84/6f/0bc3c3d05b021db44c14bc379a7c0df7d57302aa15380c16fd4e63fd6a9b/matplotlib-3.11.1-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f4bdeea33a8d15a071dbfe6d119451b1d719c733ac666d65357082901a9099", size = 10832170, upload-time = "2026-07-18T03:38:10.276Z" },
+ { url = "https://files.pythonhosted.org/packages/db/4d/e375f39acdb2af5a9342730618608e39790ec842e6f1b392863028781459/matplotlib-3.11.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b4c78ceb2f11bcac7389d305cda17aeb1f4586a857854ab5780bd3dd8dbfc407", size = 10916701, upload-time = "2026-07-18T03:38:12.512Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/be/fa26ed085b41298f64a8f9b7592c671bbf1acc8b0df124c1c5de96b859f8/matplotlib-3.11.1-cp311-cp311-win_amd64.whl", hash = "sha256:7f33a781e12b1e53b278deb2f5373c2e55ec4f10727be3440c0cfb5cda9f944f", size = 9315331, upload-time = "2026-07-18T03:38:14.949Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/f3/eb5bdf3b6e191b200db298b08bbc1638b7f3c82cdc8680f9d88bf72559ae/matplotlib-3.11.1-cp311-cp311-win_arm64.whl", hash = "sha256:67e4c3cd578c65ebd81bdc09a1b6592ceafee6dfafe116dc85dfcb647b5bbb18", size = 9003475, upload-time = "2026-07-18T03:38:17.205Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/6c/7ef7ebcb2bd9739b2b66b18b076e077f44bb46fdbe28ca0506edb3c62c79/matplotlib-3.11.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e15ef41507f3d525f46154ac9e3ae785dacde9f20e593a25de8986267892ef74", size = 9453849, upload-time = "2026-07-18T03:38:19.593Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/f8/6d0c312c8d9738e7d9677f09fe5c986b3239e651a7b73a2deb38b65e4a71/matplotlib-3.11.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:21a67b961a6d597bca54fae826cd20695ba4a6e4d05424a08da6e13e3176fd6b", size = 9283113, upload-time = "2026-07-18T03:38:21.95Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/cf/b4ad2cc81b6672ea29ea04e64e350a9f9b493b0908ccd884c67eeff8f7b2/matplotlib-3.11.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ba8f811b8ddfac493734d6af0b2dff96919d0c28ca0d641858dab4262777c6ea", size = 10035615, upload-time = "2026-07-18T03:38:24.315Z" },
+ { url = "https://files.pythonhosted.org/packages/88/90/4e10e033d9b66589d8ed98b84c95cdbb57033d57c1f41339d7393dbd2f2e/matplotlib-3.11.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c52f7ad20ef476806ed212380b1d54d20310c8b86bdc2c9a68b51f0024a44472", size = 10842559, upload-time = "2026-07-18T03:38:26.285Z" },
+ { url = "https://files.pythonhosted.org/packages/88/eb/799612d0f8cd3e816a10fec59329fca52cd2353264df80378dfc541ae855/matplotlib-3.11.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8b14eb22961fe865efb0e4ff167e333e428908b00115a8d800ccb65ee108e481", size = 10927532, upload-time = "2026-07-18T03:38:28.532Z" },
+ { url = "https://files.pythonhosted.org/packages/88/89/56649bbaa2fd12e20f3be03dbcc135b0c8676d88bac17977599e3eb442a0/matplotlib-3.11.1-cp312-cp312-win_amd64.whl", hash = "sha256:88a2a27dd9691ae448dfae4b26f59036be90c3c28757edd3553a29559d00859f", size = 9333886, upload-time = "2026-07-18T03:38:30.477Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/11/4d124efbbad677b7b7552f6f85a3bd432d4232f95400cea98fcd2ae36ef3/matplotlib-3.11.1-cp312-cp312-win_arm64.whl", hash = "sha256:480194afceca4df2f137c2721227d3cba67121fbf4397b69cee7f83714b0a58a", size = 9007545, upload-time = "2026-07-18T03:38:32.833Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/38/ceb1d637c4db6d06141f3739e93af3321e7caaabe69b57ae48ffe3ee95b1/matplotlib-3.11.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:427258425f9a3fc4ed79a91f9e9b9aaf5a82cb6571e85dc14063cc6fbb993741", size = 9438045, upload-time = "2026-07-18T03:39:39.491Z" },
+ { url = "https://files.pythonhosted.org/packages/89/25/72ad8b58602d3a6ef1dfc4b65ecd01634ab65a2bdf494c9fe0e966dbf081/matplotlib-3.11.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:1ac697e591c11b6ad04679a73c2d2f9980fe9d9f0311fb414a2e329706343dfb", size = 9266127, upload-time = "2026-07-18T03:39:41.597Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/6d/69552382fcc8e93d1f2763ef2665980a900a48b7f3a4c57ed290726d1cbc/matplotlib-3.11.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4b9ac2f1f607ecda2af90a5232beee2af7582fce1cc30c4b6a1b012dc21ee99", size = 10019439, upload-time = "2026-07-18T03:39:43.78Z" },
+]
+
+[[package]]
+name = "mediapipe"
+version = "0.10.35"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "absl-py" },
+ { name = "certifi" },
+ { name = "flatbuffers" },
+ { name = "matplotlib" },
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+ { name = "opencv-contrib-python" },
+ { name = "sounddevice" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/aa/c2/439e948d2a9a542498aee5d8fa3fb91ac6f4478be5d502f0c78ca3fb2333/mediapipe-0.10.35-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3b31376f34ca3665e34b834565996464cd66c9c91316e914fa7f149c891ce7ac", size = 17782605, upload-time = "2026-04-27T17:45:29.457Z" },
+ { url = "https://files.pythonhosted.org/packages/32/8f/1bc57dbc9b7b03c8f875aac23380ec57e9002cc02fe6720045fb263f3966/mediapipe-0.10.35-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:db9a579df48cffe9570cd3e93f6a5d2dd089a1103b846c60c5b5de8a21c38db0", size = 12400490, upload-time = "2026-04-27T17:45:31.848Z" },
+ { url = "https://files.pythonhosted.org/packages/5b/f6/763477e9aeed98accc984ed6ee3f11a21a0c5fd1d1c6586b8d07067748ff/mediapipe-0.10.35-py3-none-win_amd64.whl", hash = "sha256:b08f001cf3c3cd0d88d9ed68f3368dc8a4913f568281a93117f083115aa672ba", size = 10905503, upload-time = "2026-04-27T17:45:33.946Z" },
+ { url = "https://files.pythonhosted.org/packages/07/b3/5c7fa594c731e8dafab9f1a46ab6cef670fa62dbbfb6248cc70e42ec6fc5/mediapipe-0.10.35-py3-none-win_arm64.whl", hash = "sha256:46255326a6213118aaa518a7aa25e35f93337e82677960cc2a945f117bff8444", size = 9992331, upload-time = "2026-04-27T17:45:36.193Z" },
+]
+
+[[package]]
+name = "mpmath"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" },
+]
+
+[[package]]
+name = "networkx"
+version = "3.6.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" },
+]
+
+[[package]]
+name = "numpy"
+version = "2.4.6"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.12'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/49/ec46835a70be8fa6446c495126ac84fdb28cb2558e1620ffb87a10c8b64c/numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4", size = 16969194, upload-time = "2026-05-18T23:33:13.503Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/0d/f5957185c0ee2f3e12f78715aa9e3b353fd83633316c8532b38faa37e3f6/numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d", size = 14964111, upload-time = "2026-05-18T23:33:17.795Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/40/40a40ee0ddf7ceb782c49af278894b686e586d65d8c1889c8b5da01a3d7d/numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8", size = 5469159, upload-time = "2026-05-18T23:33:20.654Z" },
+ { url = "https://files.pythonhosted.org/packages/63/13/f9a8046535cb21deae82f8d03de9617e08882d274fad2539630761888228/numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538", size = 6798936, upload-time = "2026-05-18T23:33:22.987Z" },
+ { url = "https://files.pythonhosted.org/packages/33/a8/6fa8c1a345a8c85dbb21932c447bee07c30a2c2a3f31e369c0a84b300147/numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47", size = 15966692, upload-time = "2026-05-18T23:33:26.62Z" },
+ { url = "https://files.pythonhosted.org/packages/02/03/74fe2a4cb3817d94d86402f2506554130a2f01414e299b5a843e5a8a957f/numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93", size = 16918164, upload-time = "2026-05-18T23:33:29.955Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/80/3615be3313f7e7696609bc194b9f0101da809df79e859bdb84e0cd043f46/numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8", size = 17322877, upload-time = "2026-05-18T23:33:34.724Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/ac/a691e0fe2675e370d0e08ff905adc49a1c8830e8cae03efe4477e92cd55d/numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6", size = 18651487, upload-time = "2026-05-18T23:33:38.217Z" },
+ { url = "https://files.pythonhosted.org/packages/15/a7/9bc1cd626d7bf6869bfedf27b91b6ab5dd607758bf8e959d6fa80c6a59cb/numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8", size = 6233945, upload-time = "2026-05-18T23:33:41.331Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/31/7fc6239c12bce7e931463251cca4426c465e1876ba3cc785402ef4dd8f4e/numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147", size = 12608406, upload-time = "2026-05-18T23:33:44.131Z" },
+ { url = "https://files.pythonhosted.org/packages/27/83/140f85a466595a16382996a1bf06b2b54bcd597488921b0c9daaeeda72af/numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577", size = 10479528, upload-time = "2026-05-18T23:33:50.725Z" },
+ { url = "https://files.pythonhosted.org/packages/95/2a/3d7b5ac8aac24feaf9ad7ed58f45b0bbc06d37e4338ae84c9f2298b570f9/numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1", size = 16689119, upload-time = "2026-05-18T23:33:54.065Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/12/92c4c131527599e8288d6918e888d88726f84d805d784b771f32408aeaef/numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb", size = 14699246, upload-time = "2026-05-18T23:33:57.621Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/fe/c0a6b7b2ca128a8fb228575147073b660656734b8ebe4d76c8fd748dcc79/numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41", size = 5204410, upload-time = "2026-05-18T23:34:00.302Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/d4/9770d14ba719432bb90a421bfd443872ed0f70f7264b64bec12ea363d5fd/numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698", size = 6551240, upload-time = "2026-05-18T23:34:02.852Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/c6/50a46a6205feba2343f1d6d17438107c5dc491ed1c736e6ea68689fd906b/numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f", size = 15671012, upload-time = "2026-05-18T23:34:05.485Z" },
+ { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538, upload-time = "2026-05-18T23:34:09.265Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/c5/693cbe59e57db94d2231fa519ca3978dc9e19da5a8f088588f5c6e947ff2/numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a", size = 17020706, upload-time = "2026-05-18T23:34:13.053Z" },
+ { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541, upload-time = "2026-05-18T23:34:17.024Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/81/e1b27545deedce7f4a0b348618c6b62d74e36a4dc9ccd42f3eb2f85eee32/numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45", size = 5962825, upload-time = "2026-05-18T23:34:20.3Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/ca/feab00bd44aa5fe1ad2c18f08b4d3bb92e26484b0b1d1443897809ed528c/numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751", size = 12321687, upload-time = "2026-05-18T23:34:23.095Z" },
+ { url = "https://files.pythonhosted.org/packages/63/cf/5a6d34850a39d1093558564f77ee8e8e0bee5061151b8f05a55711001ec7/numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8", size = 10221482, upload-time = "2026-05-18T23:34:25.876Z" },
+ { url = "https://files.pythonhosted.org/packages/de/12/b422cc84439adc0d00de605bf4a308890ae5c26f2c71fbd73e5d08fbb0dd/numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662", size = 16847511, upload-time = "2026-05-18T23:36:50.673Z" },
+ { url = "https://files.pythonhosted.org/packages/44/53/f481bef68011740f8849418d82db07230e825013f31f4eef5ba5b805316a/numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7", size = 14889064, upload-time = "2026-05-18T23:36:53.879Z" },
+ { url = "https://files.pythonhosted.org/packages/7f/57/42ed575c10ced8af951d426bc4e1f8aff16fd851db33f067036215a7f860/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f", size = 5394157, upload-time = "2026-05-18T23:36:57.194Z" },
+ { url = "https://files.pythonhosted.org/packages/6a/ef/f66cc724fcc36c1e364c67f51ae9146090b8b584f27d58b97fdae3edd737/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c", size = 6708728, upload-time = "2026-05-18T23:36:59.575Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/9c/c531f2293b91265d8b48e9b329f54fdd7ffae73cb4134ea10cca4237e9cc/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0", size = 15798374, upload-time = "2026-05-18T23:37:02.674Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/b0/413077f6b1153ed3cba361401c6783bbad6114804a000cc22eb71c13e190/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02", size = 16747286, upload-time = "2026-05-18T23:37:06.327Z" },
+ { url = "https://files.pythonhosted.org/packages/15/ce/e5ec180bc41812edcd8daeb8639d205622c0e8c02259d8ab25a0201b3c2a/numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73", size = 12504263, upload-time = "2026-05-18T23:37:09.715Z" },
+]
+
+[[package]]
+name = "numpy"
+version = "2.5.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/7b/14687aa674250e5e546f616f486b0d56d3631cd5b2415739141ce40bdcea/numpy-2.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2c889b56fe48b1018f764b0eec8df59ab654e9148aa91faa12596043500de277", size = 16801574, upload-time = "2026-07-04T17:06:12.423Z" },
+ { url = "https://files.pythonhosted.org/packages/e1/19/cc5bb2a3f2913d27d6dbb2c78d25921fabaedc6741d4a5a615a11f3c5bf3/numpy-2.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab451b59c5643c570974c43aef780703ef1d3b4965d2be07afd530615a9358d1", size = 11772250, upload-time = "2026-07-04T17:06:15.726Z" },
+ { url = "https://files.pythonhosted.org/packages/42/77/fdf34a71dd30f54979b18603bee915e0aaf825b07afe79acd60b04b691e2/numpy-2.5.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:78798bd5b9ad744056af8efa90e3b9ddaa53272a0848a483084a1cc0a13b2dc0", size = 5331516, upload-time = "2026-07-04T17:06:17.913Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/e2/eb7efa015b4cce41e2517bf182a7fce0d7d5b9d9ed76a29bfa0f4fe4505c/numpy-2.5.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:2ae0ca40bcb22d6ba59c1dfd5446f49940b0f2d821fde133f10dda11f816b84e", size = 6664863, upload-time = "2026-07-04T17:06:20.02Z" },
+ { url = "https://files.pythonhosted.org/packages/a9/4b/a2b32dd94ee9ffbeecb28152240042a3949db33b1c834d44090b80e1b3b8/numpy-2.5.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61ac47e772e6b8ea489e1d2f441a34c5c3ac17327e7ce294cbdf535795ad4e75", size = 15167977, upload-time = "2026-07-04T17:06:21.621Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/a9/6e73d68500f80773f65f0654ea932019d6694329a0eb0ed0533de38df376/numpy-2.5.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:59fda5e192b570217ec2580c96f00e9a7e12ef6866a900eb089b62c1a32545ca", size = 16672469, upload-time = "2026-07-04T17:06:24.064Z" },
+ { url = "https://files.pythonhosted.org/packages/24/7d/ad3e59015135f5261c95fd4cafeff159c955febd83a99a1d9250c4233815/numpy-2.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f7119ebff1a9829e9f431a4f9d28e703023bb6b9fe7c8f724467dbfc27c94ab3", size = 16527531, upload-time = "2026-07-04T17:06:26.69Z" },
+ { url = "https://files.pythonhosted.org/packages/83/d0/a39b2fbcde9cb17a1dac678f254b33a6336298af9df338824c685425d5e8/numpy-2.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e824c2acf8862052246be5a44c15da1777940c60d010dd2aab897824d9c430f9", size = 18431940, upload-time = "2026-07-04T17:06:29.521Z" },
+ { url = "https://files.pythonhosted.org/packages/04/12/cff070947791c1ed425ff76413189adbdc2fbe215eba7ce7fa454a03c7f8/numpy-2.5.1-cp312-cp312-win32.whl", hash = "sha256:08d60c810432eb83360958dea0999ac4cfb94531ea8efcbf0b7f277c2068aeb2", size = 6066764, upload-time = "2026-07-04T17:06:32.571Z" },
+ { url = "https://files.pythonhosted.org/packages/65/66/53f31807a48a750f9d748da273bc3fcedd12b27ff1f3e373bfec55ef2dc0/numpy-2.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:f7d60026c0bdb1380e83bfa7a0419c4577ee4b9a08880afcb6dadeb74c649fa2", size = 12430966, upload-time = "2026-07-04T17:06:34.926Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/2a/d1a88066b1c14186f5d3c0d18c94f17b064511982bab0578d49ee9d43c29/numpy-2.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:17a25e09640602e10bc8de0e6fa2b3fd68eedd84ba6d7842dc8f32f9ab87bd0b", size = 10350488, upload-time = "2026-07-04T17:06:37.785Z" },
+]
+
+[[package]]
+name = "nvidia-cublas"
+version = "13.1.1.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cuda-nvrtc" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-cupti"
+version = "13.0.85"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" },
+ { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-nvrtc"
+version = "13.0.88"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" },
+ { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-runtime"
+version = "13.0.96"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" },
+]
+
+[[package]]
+name = "nvidia-cudnn-cu13"
+version = "9.20.0.48"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" },
+]
+
+[[package]]
+name = "nvidia-cufft"
+version = "12.0.0.61"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" },
+]
+
+[[package]]
+name = "nvidia-cufile"
+version = "1.15.1.6"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" },
+]
+
+[[package]]
+name = "nvidia-curand"
+version = "10.4.0.35"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" },
+]
+
+[[package]]
+name = "nvidia-cusolver"
+version = "12.0.4.66"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas" },
+ { name = "nvidia-cusparse" },
+ { name = "nvidia-nvjitlink" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" },
+]
+
+[[package]]
+name = "nvidia-cusparse"
+version = "12.6.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" },
+]
+
+[[package]]
+name = "nvidia-cusparselt-cu13"
+version = "0.8.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" },
+ { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" },
+]
+
+[[package]]
+name = "nvidia-nccl-cu13"
+version = "2.29.7"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" },
+ { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" },
+]
+
+[[package]]
+name = "nvidia-nvjitlink"
+version = "13.3.33"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f0/ee/580ca6f29dcab0221db8706badca1bbbb084f1975c4d4e83329c3a7e31f0/nvidia_nvjitlink-13.3.33-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:26a6de7fb4c8fdaa7703d3dad720d6d427ddfea5c48a528fd97c11733ad830e5", size = 40742423, upload-time = "2026-05-26T16:54:51.613Z" },
+ { url = "https://files.pythonhosted.org/packages/69/30/45414e35ff2eee7db3da037e5707037ccf9d2b5218ffbdb055ea4d5aa98a/nvidia_nvjitlink-13.3.33-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ce48b37dfeb3cb1eae4cf85adacb47d7a6539ea2272870c9a3628ce275c2037e", size = 39168635, upload-time = "2026-05-26T16:54:13.906Z" },
+]
+
+[[package]]
+name = "nvidia-nvshmem-cu13"
+version = "3.4.5"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" },
+]
+
+[[package]]
+name = "nvidia-nvtx"
+version = "13.0.85"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" },
+]
+
+[[package]]
+name = "opencv-contrib-python"
+version = "5.0.0.93"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/89/e8/7882cbecf8c81129b0b808690cac9ba3015b0ced02ab329bf4a781c7f8ca/opencv_contrib_python-5.0.0.93.tar.gz", hash = "sha256:da0ba61096b08c63cb4440d8fd6f323835cbb78b714c5ba22a39e1db68c83166", size = 154110105, upload-time = "2026-07-02T06:57:59.097Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f7/5c/ca1c31afec1a1dc3ff6e1cc94091ac288d0fa8663567398809372fec73b9/opencv_contrib_python-5.0.0.93-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:3ebb8e0506573f36f54038116321a086c97aeda8ef154198931f3ea18b435cc7", size = 55653098, upload-time = "2026-07-02T05:50:29.816Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/5f/1ec2b7bc3a2ef169f9acd643c7279bc3208a83240f03ba7fe4e12683272c/opencv_contrib_python-5.0.0.93-cp37-abi3-macosx_14_0_x86_64.whl", hash = "sha256:45a1ce7c68828907348e649edd471a7dc5244d3d0ac21989e67c63d2f4fa629a", size = 42828002, upload-time = "2026-07-02T05:51:35.32Z" },
+ { url = "https://files.pythonhosted.org/packages/73/76/011d759d3c8f2a43e8a435d1e39be4a24ed9fb8c14d6c610d72b9ac2124e/opencv_contrib_python-5.0.0.93-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cac609c9a4fce67feb287837c671a2c4da9467df8e47fa0cce7bdc453d12a529", size = 57890569, upload-time = "2026-07-02T06:49:13.356Z" },
+ { url = "https://files.pythonhosted.org/packages/60/82/e82b0e3b02617af8bcaff0ff29c75992e916dc7b34daaaef3e0f805967de/opencv_contrib_python-5.0.0.93-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29b916da864002a921c79b6df4cfb2dcf79870f166ddf3ce1179b558bc7313d7", size = 79172364, upload-time = "2026-07-02T06:49:44.204Z" },
+ { url = "https://files.pythonhosted.org/packages/71/dc/85ed9767f52425dc811a3a8288d2c643cc0c1341a3b4bdd3166410c77669/opencv_contrib_python-5.0.0.93-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b84f0b0fcdbd2421b5819e517542463e71eed7f41e0a0c4ec280ed88b7269a66", size = 57856049, upload-time = "2026-07-02T06:50:07.911Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/39/f87d154d2dca8e9815ca9e4f925aee41e5931162da730d17f3200e7786f3/opencv_contrib_python-5.0.0.93-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:8427dcb0561dc3ba32f3771c627f52b87c29932c265bea28ffcb54804c3c3fec", size = 82057630, upload-time = "2026-07-02T06:50:54.022Z" },
+ { url = "https://files.pythonhosted.org/packages/25/6d/31fee2843aef301252f6fa54bafe6bc2500fab80b152c5850ed3cbc2b7ef/opencv_contrib_python-5.0.0.93-cp37-abi3-win32.whl", hash = "sha256:dd8a80a04a8610c033757135b7846ad2027ba2d3bf9faf2f83f3dc6ed9e3814a", size = 44362046, upload-time = "2026-07-02T05:50:05.275Z" },
+ { url = "https://files.pythonhosted.org/packages/09/29/6985260569ee3c7f6fcae252bc06e2a843e5b90eed665a2936bdd26fa283/opencv_contrib_python-5.0.0.93-cp37-abi3-win_amd64.whl", hash = "sha256:461622db95c964652d4d8fda171034961c3de270f78a6095aaad31050771774a", size = 53822579, upload-time = "2026-07-02T05:50:02.092Z" },
+]
+
+[[package]]
+name = "packaging"
+version = "26.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
+]
+
+[[package]]
+name = "pillow"
+version = "12.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },
+ { url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },
+ { url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },
+ { url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },
+ { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
+ { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
+ { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
+ { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
+ { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
+ { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
+ { url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },
+ { url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },
+ { url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },
+ { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
+]
+
+[[package]]
+name = "pycparser"
+version = "3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },
+]
+
+[[package]]
+name = "pyparsing"
+version = "3.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" },
+]
+
+[[package]]
+name = "python-dateutil"
+version = "2.9.0.post0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" },
+ { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" },
+ { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" },
+ { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" },
+ { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" },
+ { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" },
+ { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" },
+ { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" },
+ { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" },
+ { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" },
+ { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" },
+ { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" },
+]
+
+[[package]]
+name = "regex"
+version = "2026.7.19"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/20/98/04b13f1ddfb63158025291c02e03eb42fbb7acb51d091d541050eb4e35e8/regex-2026.7.19.tar.gz", hash = "sha256:7e77b324909c1617cbb4c668677e2c6ae13f44d7c1de0d4f15f2e3c10f3315b5", size = 416440, upload-time = "2026-07-19T00:19:48.923Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/e5/cef4de2bac939280b68d32adc659478845238a8274f2f79c465063f590ad/regex-2026.7.19-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ac777001cdfc28b72477d93c8564bb7583081ea8fb45cdca3d568e0a4f87183c", size = 494012, upload-time = "2026-07-19T00:16:39.927Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/87/e86f51eb117457bb7803132ffe5cb6e2841e2b5bea4cc85d397f3c6e257d/regex-2026.7.19-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:59787bd5f8c70aa339084e961d2996b53fbdeab4d5393bba5c1fe1fc32e02bae", size = 295281, upload-time = "2026-07-19T00:16:41.433Z" },
+ { url = "https://files.pythonhosted.org/packages/41/2e/2360c41d8080a3d9ec7e5c90fad6eab3b50192869d10e9a5609e48c8177b/regex-2026.7.19-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:90c633e7e8d6bf4e992b8b36ce69e018f834b641dd6de8cea6d78c06ffa119c5", size = 290615, upload-time = "2026-07-19T00:16:43.058Z" },
+ { url = "https://files.pythonhosted.org/packages/cf/69/b65ba4344efbc771b28fe5dde84cbbb6c8f9551165952fe78def5b9dde6a/regex-2026.7.19-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:87ccab0db8d5f4fbb0272642113c1adb2ffc698c16d3a0944580222331fa7a20", size = 791804, upload-time = "2026-07-19T00:16:44.662Z" },
+ { url = "https://files.pythonhosted.org/packages/81/b6/a40dfa0dc6224b36f620c00296eacc830489cbf8c2837b6750dfe6170375/regex-2026.7.19-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e50d748a32da622f256e8d505867f5d3c43a837c6a9f0efb149655fadd1042a", size = 861723, upload-time = "2026-07-19T00:16:46.412Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/02/735991dee71abd83196a7962f7ed8bf5aa05720ff06e2d3ff896a85e2bbb/regex-2026.7.19-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bf1516fe58fc104f39b2d1dbe2d5e27d0cd45c4be2e42ba6ee0cc763701ec3c7", size = 905932, upload-time = "2026-07-19T00:16:47.956Z" },
+ { url = "https://files.pythonhosted.org/packages/45/6c/e7098d8b846ccdbf431d8c081b61e496526a27a28094ed09e0dce21b3f54/regex-2026.7.19-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:09f3e5287f94f17b709dc9a9e70865855feee835c861613be144218ce4ca82cc", size = 801407, upload-time = "2026-07-19T00:16:49.43Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/18/34b69274e2649bcc7d9b089c2b2983fb2632d8ecf667e359593be9072e79/regex-2026.7.19-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6383cd2ed53a646c659ba1fe65727db76437fdaa069e697a0b44a51d5843d864", size = 774448, upload-time = "2026-07-19T00:16:51.352Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/e6/0a72247d025585fd3800b98e040b84d562a88af6303347100484849f4f01/regex-2026.7.19-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:09d3007fc76249a83cdd33de160d50e6cb77f54e09d8fa9e7148e10607ce24af", size = 783297, upload-time = "2026-07-19T00:16:53.071Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/aa/c4f65ae7dd02a36b323a70c4cff326e1f3442361aaebc9311100a130d54f/regex-2026.7.19-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:6f8c6e7a1cfa3dc9d0ee2de0e65e834537fa29992cc3976ffec914afc35c5dd5", size = 854736, upload-time = "2026-07-19T00:16:54.607Z" },
+ { url = "https://files.pythonhosted.org/packages/62/c3/668082bcc817b9e694189b84997aeba7385b7779faa6711788679c482e35/regex-2026.7.19-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:b2ea4a3e8357be8849e833beeae757ac3c7a6b3fc055c03c808a53c91ad30d82", size = 763298, upload-time = "2026-07-19T00:16:56.289Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/fb/2d07ad555e7af88aa5f867fdafa47a8d945ee237c20af3ebceb46a820835/regex-2026.7.19-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:80115dd39481fd3a4b4080220799dbcacb921a844de4b827264ececacbe17c78", size = 844430, upload-time = "2026-07-19T00:16:57.933Z" },
+ { url = "https://files.pythonhosted.org/packages/51/15/c82a471fe3dce56f03745635b43aa456c40dc0db089e07ef148b331507d1/regex-2026.7.19-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d6ce43a0269d68cee79a7d1ade7def53c20f8f2a047b92d7b5d5bcc73ae88327", size = 789683, upload-time = "2026-07-19T00:16:59.583Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/f4/7532a2c59d56f5398902c20de60f0c9a5d1cd364e42a051b48e1b210be7b/regex-2026.7.19-cp311-cp311-win32.whl", hash = "sha256:9be2a6647740dd3cca6acb24e87f03d7632cd280dbce9bbe40c26353a215a45d", size = 266778, upload-time = "2026-07-19T00:17:01.032Z" },
+ { url = "https://files.pythonhosted.org/packages/83/2b/cf1bc631db154eb95520d9d5dbc2371ff77a0f014bbf7d748fed8496aa63/regex-2026.7.19-cp311-cp311-win_amd64.whl", hash = "sha256:8d3469c91dd92ee41b7c95280edbd975ef1ba9195086686623a1c6e8935ce965", size = 277983, upload-time = "2026-07-19T00:17:02.571Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/bd/56ceaf170e875d5a6761bf2bfd0d040f1cacc896850d5e40cb29b11bbd06/regex-2026.7.19-cp311-cp311-win_arm64.whl", hash = "sha256:36aacfb15faaff3ced55afbf35ec72f50d4aee22082c4f7fe0573a33e2fca92e", size = 276961, upload-time = "2026-07-19T00:17:04.135Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/b9/d11d7e501ac8fd7d617684423ebb9561e0b998481c1e4cbc0cb212c5d74a/regex-2026.7.19-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2cc3460cedf7579948486eab03bc9ad7089df4d7281c0f47f4afe03e8d13f02d", size = 496778, upload-time = "2026-07-19T00:17:05.677Z" },
+ { url = "https://files.pythonhosted.org/packages/3f/a9/a5ab6f312f24318019170dc485d5421fe4f89e43a98640da50d95a8a7041/regex-2026.7.19-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0e9554c8785eac5cffe6300f69a91f58ba72bc88a5f8d661235ad7c6aa5b8ccd", size = 297122, upload-time = "2026-07-19T00:17:07.59Z" },
+ { url = "https://files.pythonhosted.org/packages/b3/63/4cab4d7f2d384a144d420b763d97674cb70619c878ea6fcd7640d0e62143/regex-2026.7.19-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d7da47a0f248977f08e2cb659ff3c17ddc13a4d39b3a7baa0a81bf5b415430f6", size = 292009, upload-time = "2026-07-19T00:17:09.648Z" },
+ { url = "https://files.pythonhosted.org/packages/22/85/102a81b218298957d4ea7d2f084fae537a71add9d6ff93c8e67284c5f45e/regex-2026.7.19-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93db40c8de0815baab96a06e08a984bac71f989d13bab789e382158c5d426797", size = 796708, upload-time = "2026-07-19T00:17:11.542Z" },
+ { url = "https://files.pythonhosted.org/packages/78/b5/dc136af5629938a037cd2b304c12240e132ec92f38be8ff9cc89af2a1f2d/regex-2026.7.19-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:66bd62c59a5427746e8c44becae1d9b99d22fb13f30f492083dfb9ad7c45cc18", size = 865651, upload-time = "2026-07-19T00:17:13.312Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/75/67402ae3cd9c8c988a4c805d15ee3eef015e7ca4cb112cf3e640fc1f4153/regex-2026.7.19-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1649eb39fcc9ea80c4d2f110fde2b8ab2aef3877b98f02ab9b14e961f418c511", size = 911756, upload-time = "2026-07-19T00:17:15.015Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/8e/096d00c7c480ef2ff4265349b14e2261d4ab787ba1f74e2e80d1c58079c3/regex-2026.7.19-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9dce8ec9695f531a1b8a6f314fd4b393adcccf2ea861db480cdf97a301d01a68", size = 801798, upload-time = "2026-07-19T00:17:17.208Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/41/e7ecac6edb5722417f85cc67eaf386322fbe8acf6918ec2fdc37c20dd9d0/regex-2026.7.19-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3080a7fd38ef049bd489e01c970c97dd84ff446a885b0f1f6b26d9b1ad13ce11", size = 776933, upload-time = "2026-07-19T00:17:19.347Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/69/03c9b3f058d66403e0ca2c938696e81d51cd4c6d47ec5265f02f96948d9a/regex-2026.7.19-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1d793a7988e04fcb1e2e135567443d82173225d657419ec09414a9b5a145b986", size = 784338, upload-time = "2026-07-19T00:17:21.057Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/f7/b38ab3d43f284afbb618fcd15d0e77eb786ae461ce1f6bc7494619ddc0f2/regex-2026.7.19-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e8b0abe7d870f53ca5143895fef7d1041a0c831a140d3dc2c760dd7ba25d4a8b", size = 860452, upload-time = "2026-07-19T00:17:23.119Z" },
+ { url = "https://files.pythonhosted.org/packages/15/5c/ff60ef0571121714f3cf9920bc183071e384a10b556d042e0fdb06cc07a5/regex-2026.7.19-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:4e5413bd5f13d3a4e3539ca98f70f75e7fca92518dd7f117f030ebedd10b60cb", size = 765958, upload-time = "2026-07-19T00:17:24.81Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/0f/bd34021162c0ab47f9a315bd56cd5642e920c8e5668a75ef6c6a6fca590d/regex-2026.7.19-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:73b133a9e6fb512858e7f065e96f1180aa46646bc74a83aea62f1d314f3dd035", size = 851765, upload-time = "2026-07-19T00:17:26.993Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/20/a2ca43edade0595cccfdc98636739f536d9e26898e7dbddc2b9e98898953/regex-2026.7.19-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dbe6493fbd27321b1d1f2dd4f5c7e5bd4d8b1d7cab7f32fd67db3d0b2ed8248a", size = 789714, upload-time = "2026-07-19T00:17:28.699Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/47/e02db4015d424fc83c00ea0ac8c5e5ec14397943de9abf909d5ce3a25931/regex-2026.7.19-cp312-cp312-win32.whl", hash = "sha256:ddd67571c10869f65a5d7dde536d1e066e306cc90de57d7de4d5f34802428bb5", size = 267157, upload-time = "2026-07-19T00:17:31.051Z" },
+ { url = "https://files.pythonhosted.org/packages/08/8e/c780c131f79b42ed22d1bd7da4096c2c35f813e835acd02ef0f018bd892c/regex-2026.7.19-cp312-cp312-win_amd64.whl", hash = "sha256:e30d40268a28d54ce0437031750497004c22602b8e3ab891f759b795a003b312", size = 277777, upload-time = "2026-07-19T00:17:32.848Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/4c/e4d7e086449bdf379d89774bf1f89dc4a41943f3c5a6125a03905b34b5fb/regex-2026.7.19-cp312-cp312-win_arm64.whl", hash = "sha256:de9208bb427130c82a5dbfd104f92c8876fc9559278c880b3002755bbbe9c83d", size = 277136, upload-time = "2026-07-19T00:17:34.803Z" },
+]
+
+[[package]]
+name = "requests"
+version = "2.34.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "charset-normalizer" },
+ { name = "idna" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" },
+]
+
+[[package]]
+name = "safetensors"
+version = "0.8.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" },
+ { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" },
+ { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" },
+ { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" },
+ { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" },
+ { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" },
+ { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" },
+ { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" },
+ { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" },
+ { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" },
+]
+
+[[package]]
+name = "setuptools"
+version = "83.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/34/26/f5d29e25ffdb535afef2d35cdb55b325298f96debd670da4c325e08d70f4/setuptools-83.0.0.tar.gz", hash = "sha256:025bccbbf0fa05b6192bc64ae1e7b16e001fd6d6d4d5de03c97b1c1ade523bef", size = 1154254, upload-time = "2026-07-04T15:31:22.699Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5d/40/e1e72872c6354b306daef1703549e8e83b4d43cfea356311bf722a043752/setuptools-83.0.0-py3-none-any.whl", hash = "sha256:29b23c360f22f414dc7336bb39178cc7bcbf6021ed2733cde173f09dba19abb3", size = 1008090, upload-time = "2026-07-04T15:31:20.885Z" },
+]
+
+[[package]]
+name = "six"
+version = "1.17.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
+]
+
+[[package]]
+name = "sounddevice"
+version = "0.5.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/2a/f9/2592608737553638fca98e21e54bfec40bf577bb98a61b2770c912aab25e/sounddevice-0.5.5.tar.gz", hash = "sha256:22487b65198cb5bf2208755105b524f78ad173e5ab6b445bdab1c989f6698df3", size = 143191, upload-time = "2026-01-23T18:36:43.529Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/0a/478e441fd049002cf308520c0d62dd8333e7c6cc8d997f0dda07b9fbcc46/sounddevice-0.5.5-py3-none-any.whl", hash = "sha256:30ff99f6c107f49d25ad16a45cacd8d91c25a1bcdd3e81a206b921a3a6405b1f", size = 32807, upload-time = "2026-01-23T18:36:35.649Z" },
+ { url = "https://files.pythonhosted.org/packages/56/f9/c037c35f6d0b6bc3bc7bfb314f1d6f1f9a341328ef47cd63fc4f850a7b27/sounddevice-0.5.5-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:05eb9fd6c54c38d67741441c19164c0dae8ce80453af2d8c4ad2e7823d15b722", size = 108557, upload-time = "2026-01-23T18:36:37.41Z" },
+ { url = "https://files.pythonhosted.org/packages/88/a1/d19dd9889cd4bce2e233c4fac007cd8daaf5b9fe6e6a5d432cf17be0b807/sounddevice-0.5.5-py3-none-win32.whl", hash = "sha256:1234cc9b4c9df97b6cbe748146ae0ec64dd7d6e44739e8e42eaa5b595313a103", size = 317765, upload-time = "2026-01-23T18:36:39.047Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/0e/002ed7c4c1c2ab69031f78989d3b789fee3a7fba9e586eb2b81688bf4961/sounddevice-0.5.5-py3-none-win_amd64.whl", hash = "sha256:cfc6b2c49fb7f555591c78cb8ecf48d6a637fd5b6e1db5fec6ed9365d64b3519", size = 365324, upload-time = "2026-01-23T18:36:40.496Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/39/a61d4b83a7746b70d23d9173be688c0c6bfc7173772344b7442c2c155497/sounddevice-0.5.5-py3-none-win_arm64.whl", hash = "sha256:3861901ddd8230d2e0e8ae62ac320cdd4c688d81df89da036dcb812f757bb3e6", size = 317115, upload-time = "2026-01-23T18:36:42.235Z" },
+]
+
+[[package]]
+name = "sympy"
+version = "1.14.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mpmath" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" },
+]
+
+[[package]]
+name = "tokenizers"
+version = "0.22.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "huggingface-hub" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" },
+ { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" },
+ { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" },
+ { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" },
+ { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" },
+ { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" },
+ { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" },
+ { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" },
+]
+
+[[package]]
+name = "torch"
+version = "2.13.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cuda-bindings", marker = "sys_platform == 'linux'" },
+ { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" },
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "jinja2" },
+ { name = "networkx" },
+ { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux'" },
+ { name = "setuptools" },
+ { name = "sympy" },
+ { name = "triton", marker = "sys_platform == 'linux'" },
+ { name = "typing-extensions" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" },
+ { url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/3a/ed0f4d4d1dcde03bced7aac9a28e800abcdc0cbd06b6775044c9fbd877b7/torch-2.13.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:2fe228aba290d14b9f31b049be550dbd469c3fd3013d7a19705b30454da97027", size = 111213045, upload-time = "2026-07-08T16:05:22.997Z" },
+ { url = "https://files.pythonhosted.org/packages/df/a9/f6a2a4d763ff1df02e9a64c477029db614295bc9367f4131223791ccc243/torch-2.13.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:572df8be8ffb4599c88cbd6a0726f1f854f4da65d2e3c09f0e2c2283333cd6d4", size = 427210998, upload-time = "2026-07-08T16:04:37.708Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/82/fea946351658e6534db52d2cc12bc53087cbf87f9440c5f180f367c1950b/torch-2.13.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:796633c4cdf0fe2cdced72d8f88f22e73dbcfce83132763162f6d4bff13b820b", size = 526605292, upload-time = "2026-07-08T16:04:22.81Z" },
+ { url = "https://files.pythonhosted.org/packages/21/d6/e8f3c6f7e01f626f77259de9860d2a78bc84c40539e28e79b7e98b0bb659/torch-2.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:024c6cc0c1b085f2f91f20a3dc27b0471d021c31ce84b81be3afdc39f791fd9d", size = 122057313, upload-time = "2026-07-08T16:03:53.43Z" },
+]
+
+[[package]]
+name = "torchvision"
+version = "0.28.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+ { name = "pillow" },
+ { name = "torch" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7a/b2/1e010052079e4c577007b789db336ea7075f1a426e84d17121fbc3745516/torchvision-0.28.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:83fe6c020866a85acd7d97deccc45ff11d66daf42916d04396a4309c66c0ccb8", size = 1856017, upload-time = "2026-07-08T16:07:55.533Z" },
+ { url = "https://files.pythonhosted.org/packages/27/be/1b9c5de9c655ca2df4a74100fa671a7b848532ff787e077ccde14a7dea2a/torchvision-0.28.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:5a38bc6da3d72621be003400b66f66a2b4c6d644fde05f680c2cb7ca8cf8dd6c", size = 7841822, upload-time = "2026-07-08T16:07:49.207Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/9b/f1e68e861d4462e3e195a642c2b448e7b7d3fad5f209487162b9a2133d9b/torchvision-0.28.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:7e80f543b22503d9415e126db5f0ff3917036925e38560ee6b9ae38c571a4002", size = 7670718, upload-time = "2026-07-08T16:07:46.525Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/de/1494610ff54cbb154beb55033cc2cd50f3de04dac132fa2dd00e4f2b2556/torchvision-0.28.0-cp311-cp311-win_amd64.whl", hash = "sha256:9a45ea67235d965ef52187130d20002a4de20c54ea3d927a24286961d268dc37", size = 3814319, upload-time = "2026-07-08T16:07:37.153Z" },
+ { url = "https://files.pythonhosted.org/packages/15/49/c1cab1ecbb3ff1a380a3f99283db1dee61b8afe354f6352c643b65937130/torchvision-0.28.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:e9f54c30cd52e3ef7fd034cc69b7bb7e0964e1c8f8743e018ab92e95b40f9eee", size = 1856020, upload-time = "2026-07-08T16:07:52.182Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/4c/95233776e2def960e5abb7a07931230a545f43717a56a1e1140162033598/torchvision-0.28.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:5cf78ebc401ce64ae19b8c55de866bb836797d559a4de9c25ccbe74cfa642d3a", size = 7842127, upload-time = "2026-07-08T16:07:53.446Z" },
+ { url = "https://files.pythonhosted.org/packages/93/e4/e9b2495d0d57b9f60d63c57d0a910410a81b4b073bf70917bef815291119/torchvision-0.28.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:028a3d481b37d785605620d7cdad897064c5a55bae2aa1f2658766333e291940", size = 7675040, upload-time = "2026-07-08T16:07:58.017Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/9c/55ed9cb6dfe3ee9c837df5cd0e758372e5829aa38b8dd71343aa632cc4e2/torchvision-0.28.0-cp312-cp312-win_amd64.whl", hash = "sha256:87dc16b2df427c1318ad335f1e2be2b3b15b2cf20f7934c83b0505a48425ee5d", size = 4085785, upload-time = "2026-07-08T16:07:50.928Z" },
+]
+
+[[package]]
+name = "tqdm"
+version = "4.70.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/21/3b/6c24bec5be5e743ffd99576daa5cc077722fc7d5bbc00bd133fa0c698dc6/tqdm-4.70.0.tar.gz", hash = "sha256:55b0b0dbd97462d06ebee91e4dac24ed4d4702be82b24f07e6c1d27e08cea220", size = 795438, upload-time = "2026-07-27T11:33:15.271Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f9/1c/01bfd571a64e7f270e6bab5e33777debe0edc56759233ce84f27dec92d14/tqdm-4.70.0-py3-none-any.whl", hash = "sha256:7f585706bfddbdebf89daac705b2dfcc16890130727d3197ca62c732b4310953", size = 80184, upload-time = "2026-07-27T11:33:13.167Z" },
+]
+
+[[package]]
+name = "transformers"
+version = "4.57.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "huggingface-hub" },
+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
+ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "regex" },
+ { name = "requests" },
+ { name = "safetensors" },
+ { name = "tokenizers" },
+ { name = "tqdm" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c4/35/67252acc1b929dc88b6602e8c4a982e64f31e733b804c14bc24b47da35e6/transformers-4.57.6.tar.gz", hash = "sha256:55e44126ece9dc0a291521b7e5492b572e6ef2766338a610b9ab5afbb70689d3", size = 10134912, upload-time = "2026-01-16T10:38:39.284Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/03/b8/e484ef633af3887baeeb4b6ad12743363af7cce68ae51e938e00aaa0529d/transformers-4.57.6-py3-none-any.whl", hash = "sha256:4c9e9de11333ddfe5114bc872c9f370509198acf0b87a832a0ab9458e2bd0550", size = 11993498, upload-time = "2026-01-16T10:38:31.289Z" },
+]
+
+[[package]]
+name = "triton"
+version = "3.7.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" },
+ { url = "https://files.pythonhosted.org/packages/94/fa/f856e24deb462d5f18bd4b5a746957862ab9b6ee5834bda60605ec348366/triton-3.7.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9497f2e696ee368862a181a90b2dcc03ca978cc4f602abd67c7d81022a6988e1", size = 184692359, upload-time = "2026-06-17T20:03:48.288Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/6f/fb96d15db6f36d6eae4cafb998c2e0353bf59d7c4ea1662d7497f269134a/triton-3.7.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7e40869937a68206ec70d7f25bb7ec6433cb083f9135e1f36dbd318dc449a728", size = 197719725, upload-time = "2026-06-17T19:53:20.419Z" },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
+]
+
+[[package]]
+name = "urllib3"
+version = "2.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
+]
diff --git a/scripts/capture_threejs_playwright.py b/scripts/capture_threejs_playwright.py
new file mode 100644
index 0000000..cc7dadc
--- /dev/null
+++ b/scripts/capture_threejs_playwright.py
@@ -0,0 +1,249 @@
+#!/usr/bin/env python3
+"""Optional Playwright adapter for the Python↔Three.js render bridge.
+
+The target page must expose:
+
+ window.__IMG2THREEJS_READY__ = true
+ window.__IMG2THREEJS_CAPTURE__.setCamera(cameraSpec)
+
+The adapter captures the actual browser canvas/viewport. It never renders a
+replacement scene in Python and fails closed when the runtime contract is absent.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+from forge.stage4_review.render_bridge import ( # noqa: E402
+ find_capture,
+ manifest_path,
+ read_manifest,
+ record_capture,
+ record_capture_pass,
+ record_reference_capture,
+ PASS_IDS,
+ write_manifest,
+)
+
+
+def capture(manifest_path_value: Path, capture_ids: list[str], headed: bool, timeout_ms: int, mode: str) -> dict:
+ try:
+ from playwright.sync_api import Error as PlaywrightError # type: ignore[import-not-found]
+ from playwright.sync_api import sync_playwright # type: ignore[import-not-found]
+ except ImportError as exc:
+ raise RuntimeError(
+ "Playwright is not installed. Install it in an isolated environment "
+ "(`python3 -m pip install playwright` and `playwright install chromium`) "
+ "or use the existing Chrome DevTools MCP adapter."
+ ) from exc
+
+ manifest = read_manifest(manifest_path_value)
+ runtime = manifest.get("runtime", {})
+ viewport = runtime.get("viewport", [620, 1000])
+ dpr = float(runtime.get("devicePixelRatio", 1))
+ url = str(runtime.get("url", ""))
+ if not url:
+ raise ValueError("manifest runtime.url is missing")
+ reference = manifest.get("reference", {})
+ fidelity_v2 = manifest.get("fidelityTrack") == "glb-mediated-v2"
+ if mode == "reference":
+ if reference.get("kind") != "glb":
+ raise ValueError("--mode reference requires a GLB reference manifest")
+ if not reference.get("browserUrl"):
+ raise ValueError("GLB reference manifest needs reference.browserUrl for the browser adapter")
+ selected = capture_ids or [str(item["id"]) for item in manifest.get("captures", [])]
+ console_errors: list[str] = []
+ page_errors: list[str] = []
+ browser_info: dict = {}
+
+ try:
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless=not headed)
+ browser_info = {"adapter": "playwright", "browser": "chromium", "headless": not headed}
+ context = browser.new_context(
+ viewport={"width": int(viewport[0]), "height": int(viewport[1])},
+ device_scale_factor=dpr,
+ )
+ page = context.new_page()
+ page.on("pageerror", lambda error: page_errors.append(str(error)))
+ page.on("console", lambda message: console_errors.append(message.text) if message.type == "error" else None)
+ page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
+ page.wait_for_function("() => Boolean(window.__IMG2THREEJS_READY__)", timeout=timeout_ms)
+
+ if fidelity_v2:
+ pass_contract = page.evaluate(
+ "() => ({capturePass: typeof window.__IMG2THREEJS_CAPTURE__?.capturePass === 'function'})"
+ )
+ if not pass_contract.get("capturePass"):
+ raise RuntimeError(
+ "GLB-mediated-v2 route must expose "
+ "window.__IMG2THREEJS_CAPTURE__.capturePass({passId, mode})"
+ )
+
+ mode_result = page.evaluate(
+ """
+ async ({mode, reference}) => {
+ const api = window.__IMG2THREEJS_CAPTURE__;
+ if (mode !== 'reference') return {ok: true};
+ if (!api || typeof api.setReferenceMode !== 'function') {
+ return {ok: false, reason: 'window.__IMG2THREEJS_CAPTURE__.setReferenceMode is missing'};
+ }
+ await api.setReferenceMode({kind: 'glb', url: reference.browserUrl});
+ return {ok: true};
+ }
+ """,
+ {"mode": mode, "reference": reference},
+ )
+ if not mode_result.get("ok"):
+ raise RuntimeError(str(mode_result.get("reason", "reference mode contract failed")))
+
+ for capture_id in selected:
+ capture_spec = find_capture(manifest, capture_id)
+ result = page.evaluate(
+ """
+ async (camera) => {
+ const api = window.__IMG2THREEJS_CAPTURE__;
+ if (!api || typeof api.setCamera !== 'function') {
+ return {ok: false, reason: 'window.__IMG2THREEJS_CAPTURE__.setCamera is missing'};
+ }
+ await api.setCamera(camera);
+ return {ok: true};
+ }
+ """,
+ capture_spec,
+ )
+ if not result.get("ok"):
+ raise RuntimeError(str(result.get("reason", "camera contract failed")))
+ page.evaluate(
+ """
+ async (frames) => {
+ for (let i = 0; i < frames; i += 1) {
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ }
+ }
+ """,
+ 2,
+ )
+ canvas = page.evaluate(
+ """
+ () => {
+ const canvas = document.querySelector('canvas');
+ return canvas ? {width: canvas.width, height: canvas.height} : null;
+ }
+ """
+ )
+ if not canvas or canvas["width"] <= 0 or canvas["height"] <= 0:
+ raise RuntimeError("Three.js canvas has zero dimensions")
+ if mode == "reference":
+ reference_spec = capture_spec.get("reference")
+ if not isinstance(reference_spec, dict) or not reference_spec.get("path"):
+ raise RuntimeError(f"capture {capture_id} has no GLB reference path")
+ screenshot = manifest_path(manifest_path_value, str(reference_spec["path"]))
+ else:
+ screenshot = manifest_path(manifest_path_value, str(capture_spec["path"]))
+ screenshot.parent.mkdir(parents=True, exist_ok=True)
+ if fidelity_v2:
+ # The capture contract may return a selector when the route has a
+ # dedicated pass canvas; default to the target Three.js canvas.
+ pass_result = page.evaluate(
+ """
+ async ({passId, mode}) => {
+ const api = window.__IMG2THREEJS_CAPTURE__;
+ const result = await api.capturePass({passId, mode});
+ return result || {ok: true};
+ }
+ """,
+ {"passId": "beauty", "mode": mode},
+ )
+ if pass_result.get("ok") is False:
+ raise RuntimeError(str(pass_result.get("reason", "beauty pass failed")))
+ selector = str(pass_result.get("selector", "canvas"))
+ page.locator(selector).screenshot(path=str(screenshot))
+ else:
+ page.screenshot(path=str(screenshot), full_page=False)
+ ready_value = page.evaluate("() => window.__IMG2THREEJS_READY__")
+ if mode == "reference":
+ record_reference_capture(
+ manifest_path_value,
+ manifest,
+ capture_id,
+ screenshot,
+ ready_signal=ready_value,
+ console_errors=console_errors + page_errors,
+ )
+ else:
+ record_capture(
+ manifest_path_value,
+ manifest,
+ capture_id,
+ screenshot,
+ ready_signal=ready_value,
+ console_errors=console_errors + page_errors,
+ browser_snapshot={"canvas": canvas},
+ )
+
+ if fidelity_v2:
+ for pass_id in PASS_IDS:
+ if pass_id == "beauty":
+ pass_path = screenshot
+ else:
+ target = capture_spec.get("reference") if mode == "reference" else capture_spec
+ pass_path = manifest_path(manifest_path_value, str(target["passes"][pass_id]["path"]))
+ pass_path.parent.mkdir(parents=True, exist_ok=True)
+ pass_result = page.evaluate(
+ """
+ async ({passId, mode}) => {
+ const api = window.__IMG2THREEJS_CAPTURE__;
+ const result = await api.capturePass({passId, mode});
+ return result || {ok: true};
+ }
+ """,
+ {"passId": pass_id, "mode": mode},
+ )
+ if pass_result.get("ok") is False:
+ raise RuntimeError(str(pass_result.get("reason", "diagnostic pass failed")))
+ selector = str(pass_result.get("selector", "canvas"))
+ page.locator(selector).screenshot(path=str(pass_path))
+ record_capture_pass(
+ manifest_path_value,
+ manifest,
+ capture_id,
+ pass_id,
+ pass_path,
+ reference=mode == "reference",
+ )
+
+ browser.close()
+ except PlaywrightError as exc:
+ raise RuntimeError(f"Playwright capture failed: {exc}") from exc
+
+ manifest.setdefault("evidence", {})["browser"] = browser_info
+ manifest["evidence"]["consoleErrors"] = console_errors + page_errors
+ write_manifest(manifest_path_value, manifest)
+ return {"captured": selected, "mode": mode, "browser": browser_info, "consoleErrors": console_errors + page_errors}
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, required=True)
+ parser.add_argument("--capture-id", action="append", default=[], help="capture only this id; repeatable")
+ parser.add_argument("--headed", action="store_true")
+ parser.add_argument("--timeout-ms", type=int, default=30000)
+ parser.add_argument("--mode", choices=("procedural", "reference"), default="procedural")
+ args = parser.parse_args(argv)
+ try:
+ result = capture(args.manifest.expanduser().resolve(), args.capture_id, args.headed, args.timeout_ms, args.mode)
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if not result["consoleErrors"] else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/character_audit.sh b/scripts/character_audit.sh
new file mode 100755
index 0000000..dfbb14a
--- /dev/null
+++ b/scripts/character_audit.sh
@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# Run every geometry gate against a live model and write a baseline you can diff against later.
+#
+# The point of a baseline is that "before and after" becomes a number instead of an impression. Run
+# this once before touching a model, run it again after, and diff the JSON: 49 -> 0 vertices inside
+# the skull is an argument; "it looks better" is not.
+#
+# Usage:
+# scripts/character_audit.sh <page-url> <output-dir> [mesh-name-regex] [--allow a,b]...
+#
+# Anything after the regex is forwarded to the penetration gate, which is where `--allow` belongs:
+# parts that SHOULD share space (an ear root embedded in a skull, a rim wrapping the shell it binds,
+# a hand gripping a staff) are contact, not defects, and a gate without an exemption list flags them
+# forever until someone switches it off.
+#
+# Example:
+# scripts/character_audit.sh \
+# 'http://localhost:5175/img2threejs-showcase/zbrush-mouse-warrior.html?view=front&clean=1' \
+# baseline/ '' --allow ear-l-paper-thin-shell,craniofacial-unified-shell
+set -uo pipefail
+
+URL="${1:-}"
+OUT="${2:-baseline}"
+FILTER="${3:-}"
+shift 3 2>/dev/null || shift $#
+PENETRATION_ARGS=("$@")
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+
+if [ -z "$URL" ]; then
+ echo "usage: $0 <page-url> <output-dir> [mesh-name-regex]" >&2
+ exit 2
+fi
+
+mkdir -p "$OUT"
+MESHES="$OUT/meshes.json"
+
+echo "== exporting meshes =="
+if [ -n "$FILTER" ]; then
+ node "$ROOT/runtime/scripts/export_mesh_geometry.mjs" --url "$URL" --out "$MESHES" --include "$FILTER" || exit 2
+else
+ node "$ROOT/runtime/scripts/export_mesh_geometry.mjs" --url "$URL" --out "$MESHES" || exit 2
+fi
+
+# Every gate's exit code is captured rather than allowed to abort the run. A failing gate is the
+# expected outcome on a model with defects, and stopping at the first one would hide the rest --
+# which is the opposite of what an audit is for.
+declare -A STATUS
+
+run_gate() {
+ local name="$1"; shift
+ echo
+ echo "== $name =="
+ "$@" --json > "$OUT/$name.json" 2> "$OUT/$name.err"
+ STATUS[$name]=$?
+ # Human-readable copy alongside the JSON, since the JSON is for diffing and this is for reading.
+ "$@" > "$OUT/$name.txt" 2>/dev/null
+ head -20 "$OUT/$name.txt" 2>/dev/null || cat "$OUT/$name.err"
+}
+
+run_gate self-intersection python3 "$ROOT/forge/stage4_review/self_intersection.py" "$MESHES"
+run_gate penetration python3 "$ROOT/forge/stage4_review/pairwise_penetration.py" "$MESHES" "${PENETRATION_ARGS[@]+"${PENETRATION_ARGS[@]}"}"
+run_gate uv python3 "$ROOT/forge/stage3_build/uv_unwrap.py" "$MESHES"
+
+echo
+echo "== summary =="
+FAILED=0
+for name in "${!STATUS[@]}"; do
+ code="${STATUS[$name]}"
+ case "$code" in
+ 0) verdict="clean" ;;
+ 1) verdict="GATE FAILURE"; FAILED=1 ;;
+ *) verdict="ERROR (could not run)"; FAILED=1 ;;
+ esac
+ printf ' %-20s %s\n' "$name" "$verdict"
+done
+echo
+echo "baseline written to $OUT/ -- diff these JSON files after your next change"
+echo "read sampledVertexCount and skippedMeshes before trusting any clean verdict:"
+echo "a zero because the defect is gone and a zero because the check never ran look identical."
+exit $FAILED
diff --git a/scripts/release_metadata.py b/scripts/release_metadata.py
new file mode 100644
index 0000000..55e0bb8
--- /dev/null
+++ b/scripts/release_metadata.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import argparse
+import json
+import re
+from dataclasses import dataclass
+from datetime import date
+from enum import Enum
+from pathlib import Path
+from typing import Final
+
+
+VERSION_PATTERN: Final = re.compile(r"^version: (\d+)\.(\d+)\.(\d+)$", re.MULTILINE)
+BADGE_PATTERN: Final = re.compile(r"version-\d+\.\d+\.\d+-green\.svg")
+HEADING_PATTERN: Final = re.compile(r"^## \[", re.MULTILINE)
+REFERENCE_PATTERN: Final = re.compile(r"^\[", re.MULTILINE)
+BREAKING_PATTERN: Final = re.compile(r"^[a-z]+(?:\([^\n]+\))?!:", re.MULTILINE)
+
+
+class ReleaseLevel(Enum):
+ PATCH = "patch"
+ MINOR = "minor"
+ MAJOR = "major"
+
+
+@dataclass(frozen=True, slots=True)
+class Version:
+ major: int
+ minor: int
+ patch: int
+
+ def __str__(self) -> str:
+ return f"{self.major}.{self.minor}.{self.patch}"
+
+ def bump(self, level: ReleaseLevel) -> "Version":
+ match level:
+ case ReleaseLevel.PATCH:
+ return Version(self.major, self.minor, self.patch + 1)
+ case ReleaseLevel.MINOR:
+ return Version(self.major, self.minor + 1, 0)
+ case ReleaseLevel.MAJOR:
+ return Version(self.major + 1, 0, 0)
+ case unreachable:
+ raise AssertionError(f"unhandled release level: {unreachable}")
+
+
+@dataclass(frozen=True, slots=True)
+class ReleasePlan:
+ current: Version
+ next: Version
+ level: ReleaseLevel
+ commits: tuple[str, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class ReleaseRequest:
+ root: Path
+ commits: tuple[str, ...]
+ release_date: str
+ repository_url: str
+ dry_run: bool
+
+
+def release_level(commits: tuple[str, ...]) -> ReleaseLevel | None:
+ if any("BREAKING CHANGE:" in commit or BREAKING_PATTERN.search(commit) for commit in commits):
+ return ReleaseLevel.MAJOR
+ if any(commit.lstrip().startswith("feat") for commit in commits):
+ return ReleaseLevel.MINOR
+ if any(commit.lstrip().startswith("fix") for commit in commits):
+ return ReleaseLevel.PATCH
+ return None
+
+
+def parse_version(skill_text: str) -> Version:
+ match = VERSION_PATTERN.search(skill_text)
+ if match is None:
+ raise ValueError("SKILL.md must contain one semantic version front-matter field")
+ return Version(*(int(value) for value in match.groups()))
+
+
+def parse_commits(commits_text: str) -> tuple[str, ...]:
+ return tuple(commit.strip() for commit in commits_text.split("\x1e") if commit.strip())
+
+
+def change_sections(commits: tuple[str, ...]) -> str:
+ features = [commit.splitlines()[0].removeprefix("feat: ") for commit in commits if commit.lstrip().startswith("feat")]
+ fixes = [commit.splitlines()[0].removeprefix("fix: ") for commit in commits if commit.lstrip().startswith("fix")]
+ breaking = [commit.splitlines()[0] for commit in commits if "BREAKING CHANGE:" in commit or BREAKING_PATTERN.search(commit)]
+ sections: list[str] = []
+ if breaking:
+ sections.extend(["### Breaking Changes", *(f"- {item}" for item in breaking), ""])
+ if features:
+ sections.extend(["### Added", *(f"- {item}" for item in features), ""])
+ if fixes:
+ sections.extend(["### Fixed", *(f"- {item}" for item in fixes), ""])
+ return "\n".join(sections).rstrip()
+
+
+def replace_once(pattern: re.Pattern[str], text: str, replacement: str, description: str) -> str:
+ updated, replacements = pattern.subn(replacement, text, count=1)
+ if replacements != 1:
+ raise ValueError(f"{description} must contain exactly one replaceable version")
+ return updated
+
+
+def update_changelog(changelog: str, plan: ReleasePlan, release_date: str, repository_url: str) -> str:
+ heading = f"## [{plan.next}] — {release_date}\n\n{change_sections(plan.commits)}\n\n"
+ heading_match = HEADING_PATTERN.search(changelog)
+ if heading_match is None:
+ raise ValueError("CHANGELOG.md must contain a version heading")
+ with_heading = changelog[:heading_match.start()] + heading + changelog[heading_match.start():]
+ reference_match = REFERENCE_PATTERN.search(with_heading)
+ if reference_match is None:
+ raise ValueError("CHANGELOG.md must contain version reference links")
+ reference = f"[{plan.next}]: {repository_url}/compare/v{plan.current}...v{plan.next}\n"
+ return with_heading[:reference_match.start()] + reference + with_heading[reference_match.start():]
+
+
+def apply_release(request: ReleaseRequest) -> ReleasePlan | None:
+ level = release_level(request.commits)
+ if level is None:
+ return None
+ skill_path = request.root / "SKILL.md"
+ readme_path = request.root / "README.md"
+ changelog_path = request.root / "CHANGELOG.md"
+ skill_text = skill_path.read_text(encoding="utf-8")
+ current = parse_version(skill_text)
+ plan = ReleasePlan(current=current, next=current.bump(level), level=level, commits=request.commits)
+ updated_skill = replace_once(VERSION_PATTERN, skill_text, f"version: {plan.next}", "SKILL.md")
+ readme_text = readme_path.read_text(encoding="utf-8")
+ updated_readme = replace_once(BADGE_PATTERN, readme_text, f"version-{plan.next}-green.svg", "README.md")
+ changelog_text = changelog_path.read_text(encoding="utf-8")
+ updated_changelog = update_changelog(changelog_text, plan, request.release_date, request.repository_url)
+ if request.dry_run:
+ return plan
+ skill_path.write_text(updated_skill, encoding="utf-8")
+ readme_path.write_text(updated_readme, encoding="utf-8")
+ changelog_path.write_text(updated_changelog, encoding="utf-8")
+ return plan
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, default=Path.cwd())
+ parser.add_argument("--commits-file", type=Path, required=True)
+ parser.add_argument("--date", default=date.today().isoformat())
+ parser.add_argument("--repository-url", required=True)
+ parser.add_argument("--dry-run", action="store_true")
+ arguments = parser.parse_args()
+ commits = parse_commits(arguments.commits_file.read_text(encoding="utf-8"))
+ request = ReleaseRequest(arguments.root, commits, arguments.date, arguments.repository_url, arguments.dry_run)
+ plan = apply_release(request)
+ if plan is None:
+ print(json.dumps({"release": False}))
+ return 0
+ print(json.dumps({"release": True, "version": str(plan.next), "level": plan.level.value}))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())