Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): every style in the creator has a body, and every combination renders
rubenluetke10-beep4bbafbf17d8b
diff --git a/docs/agent-society/character-pipeline.md b/docs/agent-society/character-pipeline.mdindex 689a60d4df..d8def79669 100644--- a/docs/agent-society/character-pipeline.md+++ b/docs/agent-society/character-pipeline.md@@ -560,7 +560,11 @@ Exit 0 pass, 1 fail, 78 skipped (no assets yet), like the bundle gate.vector's screen projection matches the movement vector's sign — the automated "not backwards"proof, run in CI with the M3 world.-### 10.3 The Figure Lab (dev-only, the human proof)+### 10.3 Looking at a figure before it ships++`blender -b --python scripts/figures/preview_figures.py -- --out <dir> [--parts]` renders every base — and, with `--parts`, every base wearing every part its style offers — from four angles, holding a frame of `--clip` (default `idle`). It binds a part to the BODY's skeleton exactly as `assembleFigure` does and deletes the faces of a slot the part `hides`, because a preview that poses the two separately invents bugs: it reported a floating hat and a staff across the shoulders that the runtime never had. Judge in the idle pose, never the rest pose — the rest pose holds the arms straight out.++### 10.4 The Figure Lab (dev-only, the human proof)`?view=agents&lab=figures` (dev instance only, behind the existing dev flag pattern): every base ×every clip on a treadmill grid, heading arrows drawn from `FWD`, a palette editor, a part toggle@@ -637,8 +641,9 @@ steps or plain Lambert; whether `run` exists in V1 or every purposeful move walk| F1 ✅ 2026-09-02 | `contract.json`, `check_society_figures.py` + its unit test (mutation-based: turned, mirrored, blurred, clip-less, root-moving), `SOURCES.md` | gate exits 78 with no assets, 0/1 on real ones || F2 ✅ 2026-09-02 | `build_figures.py` on the KayKit Rogue → `biped-medium.glb` (404 KB, 23 bones, `idle walk run work talk sit sleep celebrate wave`, palette-strip sheet) — `proportions.json` and the small/large variants are still open | gate green; the card shows the figure turning || F3 ✅ 2026-09-02 (partly) | `figureRecipe`, `figureRegistry`, `assembleFigure`, `AgentFigureViewer` (pixel pass, orbit from above and below, wave on open), the creator's live look editor; the walker maths live in `world/walkerKinematics.ts` (world session). Open: unit tests for `assembleFigure`, the Figure Lab | card and creator render the real figure; palette from the recipe |-| F4 ✅ 2026-09-02 (parts; variants open) | Four bases (Ranger, Knight, Mage, Barbarian) and 15 parts (helmets, hats, capes, sword, shields, staff, spellbook, knife, axe, mug) built from the CC0 pack; `catalog.json` GENERATED by the build with style tags, palettes and credits; hair as its own primitive so headgear hides it; the creator picks style → base → parts per slot; the roster rail shows rendered headshots (`faceCrop.ts`); a person's own GLB imports through `POST /api/society/figures` behind the same gate. Open: `biped-small`/`-large` (`proportions.json`), hair/outfit parts beyond the pack | a knight in helmet, cape, sword and shield from a recipe alone; an imported figure refused with the gate's reasons |-| F5 ✅ 2026-09-02 (spirit; quadruped open) | `spirit-gigi.glb`: Gigi modelled and keyed BY SCRIPT in Blender (`scripts/figures/gigi_builder.py` — body extruded from the mascot's SVG outline, eyes/mouth/scanlines/glitch pixels/tube arms, rig `root → body → face`, clips idle/walk-glide/talk/sleep/celebrate-spin/wave, two primitives: lit body + unlit `-marks`), 282 KB, gate green. Jarvis' default recipe is Gigi; the roster seeds only Jarvis. Open: the fox | Gigi floats on the market square and turns on the card |+| F4 ✅ 2026-09-02 (parts; variants open) | Four bases (Ranger, Knight, Mage, Barbarian) and 15 parts (helmets, hats, capes, sword, shields, staff, spellbook, knife, axe, mug) built from the CC0 pack; `catalog.json` GENERATED by the build with style tags, palettes and credits; hair as its own primitive so headgear hides it; the creator picks style → base → parts per slot; the roster rail shows rendered headshots (`faceCrop.ts`); a person's own GLB imports through `POST /api/society/figures` behind the same gate. Open: `biped-small`/`-large` (`proportions.json`) | a knight in helmet, cape, sword and shield from a recipe alone; an imported figure refused with the gate's reasons |+| F4b ✅ 2026-09-02 | **Every style has a body.** `humanoid_builder.py` models Office and Casual (`modern`), Chibi (`cartoon`) and Android (`scifi`) as box bodies on the CC0 donor's rig and its nine clips — the donor is imported for the skeleton alone and every mesh it ships is deleted — plus four accessories (backpack, tablet, wrench, cap) hung on bones every biped shares, so one file fits every base of its style. The Ranger is `fantasy` only again. Parts are filtered BY STYLE, the base carries its archetype into the recipe, a switch drops what the new base cannot wear, and the height band follows the archetype | the creator opens on a modern person, and every style tab yields a figure |+| F5 ✅ 2026-09-02 | `spirit-gigi.glb`: Gigi modelled and keyed BY SCRIPT in Blender (`scripts/figures/gigi_builder.py` — body extruded from the mascot's SVG outline, eyes/mouth/scanlines/glitch pixels/tube arms, rig `root → body → face`, clips idle/walk-glide/talk/sleep/celebrate-spin/wave, two primitives: lit body + unlit `-marks`), 282 KB. `quadruped-fox.glb`: `quadruped_builder.py` writes the 21-bone rig, the body AND all seven clips — there is no CC0 donor of this archetype — plus a collar. Jarvis' default recipe is Gigi; the roster seeds only Jarvis | Gigi floats on the market square; the fox walks, sits and sleeps on the treadmill || F6 ✅ 2026-09-02 (partly) | The island's walkers wear the real figure (`FigureRig` inside the world session's `WalkerFigure`), driven by the sim's mode and speed with the stride from the asset, at **hero scale 1.6×** — seen 50° from above at 64 m a true-scale person is a 20 px sliver, and every readable isometric game cheats the same way (the card keeps true scale). Open: mixer culling off-screen, the headless "not backwards" screenshot check | Jarvis walks the market square in his suit with his mug || F7 | Route D sheet generation + validate-and-repair; route C helper (`tripo_fetch.py`) + custom-model normalization; card "Change avatar" | a consented likeness walks to the desk |diff --git a/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md b/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.mdindex 6d6c34d41f..d7ecfcbe2c 100644--- a/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md+++ b/jarvis/ui/web/frontend/src/assets/society/figures/SOURCES.md@@ -8,23 +8,33 @@ into `scripts/figures/cache/` and verified by sha256 before the build touches th| File | Source | License | What the build changed ||---|---|---|---|+| `biped-android.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Android | first-party | body modelled by humanoid_builder.py (profile `android`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted || `biped-barbarian.glb` | KayKit Character Pack: Adventurers 1.0 / Barbarian | CC0-1.0 | body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras |+| `biped-casual.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Casual | first-party | body modelled by humanoid_builder.py (profile `casual`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted |+| `biped-chibi.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Chibi | first-party | body modelled by humanoid_builder.py (profile `chibi`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted || `biped-knight.glb` | KayKit Character Pack: Adventurers 1.0 / Knight | CC0-1.0 | body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras || `biped-mage.glb` | KayKit Character Pack: Adventurers 1.0 / Mage | CC0-1.0 | body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras |+| `biped-office.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Office | first-party | body modelled by humanoid_builder.py (profile `office`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted || `biped-rogue.glb` | KayKit Character Pack: Adventurers 1.0 / Rogue | CC0-1.0 | body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras |+| `quadruped-fox.glb` | Personal Jarvis animals (first-party) / Fox | first-party | rig, body and clips written by quadruped_builder.py (shape `fox`); no external source || `spirit-gigi.glb` | Gigi mascot (first-party) / Gigi | first-party | body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras |+| `back-backpack.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / back-backpack | first-party | unparented at rest, skinned to `chest` with weight 1; re-UV'd onto the palette strip; no clips; extras || `back-fur-cape.glb` | KayKit Character Pack: Adventurers 1.0 / Barbarian_Cape | CC0-1.0 | unparented at rest, skinned to `chest` with weight 1; re-UV'd onto the palette strip; no clips; extras || `back-knight-cape.glb` | KayKit Character Pack: Adventurers 1.0 / Knight_Cape | CC0-1.0 | unparented at rest, skinned to `chest` with weight 1; re-UV'd onto the palette strip; no clips; extras || `back-mage-cape.glb` | KayKit Character Pack: Adventurers 1.0 / Mage_Cape | CC0-1.0 | unparented at rest, skinned to `chest` with weight 1; re-UV'd onto the palette strip; no clips; extras || `back-rogue-cape.glb` | KayKit Character Pack: Adventurers 1.0 / Rogue_Cape | CC0-1.0 | unparented at rest, skinned to `chest` with weight 1; re-UV'd onto the palette strip; no clips; extras |+| `collar-band.glb` | Personal Jarvis animals (first-party) / collar-band | first-party | unparented at rest, skinned to `neck` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_l-round-shield.glb` | KayKit Character Pack: Adventurers 1.0 / Round_Shield | CC0-1.0 | unparented at rest, skinned to `handslot_l` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_l-spellbook.glb` | KayKit Character Pack: Adventurers 1.0 / Spellbook | CC0-1.0 | unparented at rest, skinned to `handslot_l` with weight 1; re-UV'd onto the palette strip; no clips; extras |+| `hand_l-tablet.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / hand_l-tablet | first-party | unparented at rest, skinned to `handslot_l` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_l-wooden-shield.glb` | KayKit Character Pack: Adventurers 1.0 / Barbarian_Round_Shield | CC0-1.0 | unparented at rest, skinned to `handslot_l` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_r-axe.glb` | KayKit Character Pack: Adventurers 1.0 / 1H_Axe | CC0-1.0 | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_r-knife.glb` | KayKit Character Pack: Adventurers 1.0 / Knife | CC0-1.0 | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_r-mug.glb` | KayKit Character Pack: Adventurers 1.0 / Mug | CC0-1.0 | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_r-staff.glb` | KayKit Character Pack: Adventurers 1.0 / 2H_Staff | CC0-1.0 | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras || `hand_r-sword.glb` | KayKit Character Pack: Adventurers 1.0 / 1H_Sword | CC0-1.0 | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras |+| `hand_r-wrench.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / hand_r-wrench | first-party | unparented at rest, skinned to `handslot_r` with weight 1; re-UV'd onto the palette strip; no clips; extras |+| `headgear-cap.glb` | Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / headgear-cap | first-party | unparented at rest, skinned to `head` with weight 1; re-UV'd onto the palette strip; no clips; extras || `headgear-horned-hat.glb` | KayKit Character Pack: Adventurers 1.0 / Barbarian_Hat | CC0-1.0 | unparented at rest, skinned to `head` with weight 1; re-UV'd onto the palette strip; no clips; extras || `headgear-knight-helmet.glb` | KayKit Character Pack: Adventurers 1.0 / Knight_Helmet | CC0-1.0 | unparented at rest, skinned to `head` with weight 1; re-UV'd onto the palette strip; no clips; extras || `headgear-mage-hat.glb` | KayKit Character Pack: Adventurers 1.0 / Mage_Hat | CC0-1.0 | unparented at rest, skinned to `head` with weight 1; re-UV'd onto the palette strip; no clips; extras |@@ -34,6 +44,8 @@ into `scripts/figures/cache/` and verified by sha256 before the build touches th- `Knight.glb` sha256 `60428e3abc09ba83e595d256e3af8c5c976b46cdae599f0802fc82b4a3445168`- `Mage.glb` sha256 `cf898585da33fab50c724d31605fb931eb2912e6d2280092141e98ca81ad507d`- `Barbarian.glb` sha256 `cefc311a0e10c7858b6141f5ada7e33268727564fb8ac1347aab97d000669cc6`+- **Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig)** — Personal Jarvis, first-party (); files:+- **Personal Jarvis animals (first-party)** — Personal Jarvis, first-party (); files:- **Gigi mascot (first-party)** — Personal Jarvis, first-party (); files:Licenses recorded at fetch time. CC0 needs no attribution; credit is given anyway.diff --git a/jarvis/ui/web/frontend/src/assets/society/figures/biped-android.glb b/jarvis/ui/web/frontend/src/assets/society/figures/biped-android.glbnew file mode 100644index 0000000000..39e39d0cf3Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/biped-android.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/biped-casual.glb b/jarvis/ui/web/frontend/src/assets/society/figures/biped-casual.glbnew file mode 100644index 0000000000..8b734ec23bBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/biped-casual.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/biped-chibi.glb b/jarvis/ui/web/frontend/src/assets/society/figures/biped-chibi.glbnew file mode 100644index 0000000000..8921829aaaBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/biped-chibi.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/biped-office.glb b/jarvis/ui/web/frontend/src/assets/society/figures/biped-office.glbnew file mode 100644index 0000000000..1fc28203f0Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/biped-office.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-backpack.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-backpack.glbnew file mode 100644index 0000000000..db538e9105Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-backpack.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-fur-cape.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-fur-cape.glbindex 673c9bf79a..6ef05b2ac4 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-fur-cape.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-fur-cape.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-knight-cape.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-knight-cape.glbindex 609f02f9de..820f9a63bb 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-knight-cape.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-knight-cape.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-mage-cape.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-mage-cape.glbindex 86480d2b81..c8b6410a0c 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-mage-cape.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-mage-cape.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-rogue-cape.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-rogue-cape.glbindex 00e42a50de..df82e48dca 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-rogue-cape.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/back-rogue-cape.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-round-shield.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-round-shield.glbindex c6260d2b9c..81189fb69a 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-round-shield.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-round-shield.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-spellbook.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-spellbook.glbindex 222d918481..185a36e785 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-spellbook.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-spellbook.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-tablet.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-tablet.glbnew file mode 100644index 0000000000..ac6612e6f2Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-tablet.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-wooden-shield.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-wooden-shield.glbindex 6e2fdc34d8..2a99383a1c 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-wooden-shield.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_l-wooden-shield.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-axe.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-axe.glbindex a2d865c56c..069b3d036b 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-axe.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-axe.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-knife.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-knife.glbindex 7505847381..a97d2d3f08 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-knife.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-knife.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-mug.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-mug.glbindex 2ee7db460f..7f8bf819b5 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-mug.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-mug.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-staff.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-staff.glbindex 81745f10dc..6243087732 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-staff.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-staff.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-sword.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-sword.glbindex 843bae16c1..1416030631 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-sword.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-sword.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-wrench.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-wrench.glbnew file mode 100644index 0000000000..3da8fc5978Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/hand_r-wrench.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-cap.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-cap.glbnew file mode 100644index 0000000000..c7ed77a2beBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-cap.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-horned-hat.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-horned-hat.glbindex 296a5e70ca..ea790b6302 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-horned-hat.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-horned-hat.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-knight-helmet.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-knight-helmet.glbindex 68f8a1c87a..bacd70e5e1 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-knight-helmet.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-knight-helmet.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-mage-hat.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-mage-hat.glbindex 254b8e91c4..9c27a21174 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-mage-hat.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/biped/headgear-mage-hat.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/parts/quadruped/collar-band.glb b/jarvis/ui/web/frontend/src/assets/society/figures/parts/quadruped/collar-band.glbnew file mode 100644index 0000000000..68bf1724cfBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/parts/quadruped/collar-band.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/quadruped-fox.glb b/jarvis/ui/web/frontend/src/assets/society/figures/quadruped-fox.glbnew file mode 100644index 0000000000..83818f9694Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/figures/quadruped-fox.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/figures/spirit-gigi.glb b/jarvis/ui/web/frontend/src/assets/society/figures/spirit-gigi.glbindex 9e3299c9e1..9d2aa1e2a4 100644Binary files a/jarvis/ui/web/frontend/src/assets/society/figures/spirit-gigi.glb and b/jarvis/ui/web/frontend/src/assets/society/figures/spirit-gigi.glb differdiff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 11e77362d0..a2c582d3c8 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -68,11 +68,41 @@ import {type FigureRecipe,type PaletteCell,} from "../figures/figureRecipe";-import { basesForStyle, partsForSlot, slotsWithParts, stylesWithBases, CATALOG } from "../figures/figureRegistry";+import {+ basesForStyle,+ catalogBaseFor,+ keepablePartsFor,+ partsForSlot,+ slotsWithParts,+ stylesWithBases,+ CATALOG,+} from "../figures/figureRegistry";+import type { FigureArchetype } from "../figures/figureRecipe";const CEILINGS: readonly PermissionCeiling[] = ["safe", "monitor", "ask"];-const HEIGHT_MIN = 1.5;-const HEIGHT_MAX = 2.1;++/**+ * How tall a figure may be made, per archetype. One 1.5–2.1 m band fits a+ * person and nothing else: a fox at 1.75 m is a horse, and Gigi's own scale+ * is 1.9 m. The band is the archetype's contract height ±25 %.+ */+const HEIGHT_RANGE: Readonly<Record<FigureArchetype, { min: number; max: number }>> = {+ biped: { min: 1.5, max: 2.1 },+ quadruped: { min: 0.6, max: 1.3 },+ spirit: { min: 1.5, max: 2.4 },+};+const IMPORTED_RANGE = { min: 0.6, max: 2.4 };++/** What the creator opens on; the base comes from the style, never the other way round. */+const DEFAULT_STYLE = "modern";++/** True while the recipe still wears its own base's stock colours, cell for cell. */+function untouchedPalette(recipe: FigureRecipe): boolean {+ const stock = catalogBaseFor(recipe)?.palette;+ if (!stock) return false;+ const worn = recipe.palette ?? {};+ return Object.entries(worn).every(([cell, value]) => stock[cell as PaletteCell] === value);+}export interface CreateAgentDialogProps {open: boolean;@@ -86,8 +116,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoconst [name, setName] = useState("");const [title, setTitle] = useState("");const [description, setDescription] = useState("");- const [recipe, setRecipe] = useState<FigureRecipe>(() => defaultRecipe("ranger"));- const [style, setStyle] = useState<string>("modern");+ const [recipe, setRecipe] = useState<FigureRecipe>(() => defaultRecipe(DEFAULT_STYLE));+ const [style, setStyle] = useState<string>(DEFAULT_STYLE);const [providerId, setProviderId] = useState("");const [model, setModel] = useState("");const [effort, setEffort] = useState("");@@ -197,7 +227,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialosetName("");setTitle("");setDescription("");- setRecipe(defaultRecipe("ranger"));+ setRecipe(defaultRecipe(DEFAULT_STYLE));setProviderId("");setModel("");setEffort("");@@ -210,6 +240,53 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoconst palette = useMemo(() => resolvePalette(recipe), [recipe]);+ // The look editor's own truth: which figure the recipe names, what+ // archetype it is, and therefore which slots, parts and heights exist. An+ // imported GLB has no catalog row — its rows are colours and height only.+ const imported = Boolean(recipe.model);+ const baseEntry = imported ? null : catalogBaseFor(recipe);+ const archetype: FigureArchetype = baseEntry?.archetype ?? recipe.archetype;+ const styleOptions = useMemo(() => stylesWithBases(), []);+ const bases = useMemo(() => basesForStyle(style), [style]);+ const slots = useMemo(+ () => (imported ? [] : slotsWithParts(archetype, style)),+ [imported, archetype, style],+ );+ const heights = imported ? IMPORTED_RANGE : (HEIGHT_RANGE[archetype] ?? HEIGHT_RANGE.biped);+ const defaultHeight = baseEntry?.heightM ?? 1.75;+ const heightM = Math.min(heights.max, Math.max(heights.min, recipe.heightM ?? defaultHeight));++ /**+ * Move the recipe onto a base: its archetype comes with it, the parts that+ * the new base and style cannot wear are dropped, and the height lands in+ * the new archetype's band. Carrying a biped's cape onto a fox, or a 1.75 m+ * height onto a 0.9 m animal, is how a "working" creator renders nonsense.+ */+ const selectBase = (nextStyle: string, base: string) => {+ const entry = CATALOG.bases.find((b) => b.base === base) ?? null;+ const nextArchetype: FigureArchetype = entry?.archetype ?? "biped";+ const band = HEIGHT_RANGE[nextArchetype] ?? HEIGHT_RANGE.biped;+ setStyle(nextStyle);+ setRecipe((r) => {+ const next: FigureRecipe = {+ ...r,+ archetype: nextArchetype,+ base,+ style: nextStyle,+ parts: keepablePartsFor(r.parts, nextArchetype, nextStyle),+ heightM: Math.min(band.max, Math.max(band.min, r.heightM ?? entry?.heightM ?? 1.75)),+ // Colours a person chose are theirs and survive the switch; colours+ // they never touched are the OLD figure's defaults and have no+ // business on the new one — a fox does not want the jeans blue its+ // paws inherited from the casual body.+ palette: untouchedPalette(r) && entry ? { ...entry.palette } : r.palette,+ };+ delete next.model;+ return next;+ });+ setImportedName(null);+ };+const setCell = (cell: PaletteCell, value: string) =>setRecipe((r) => ({ ...r, palette: { ...r.palette, [cell]: value } }));const applyPreset = (id: string) => {@@ -576,15 +653,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo<buttontype="button"className="underline hover:text-foreground"- onClick={() => {- setImportedName(null);- setStyle("modern");- setRecipe((r) => {- const next = { ...r, style: "modern" };- delete next.model;- return next;- });- }}+ onClick={() => selectBase(DEFAULT_STYLE, basesForStyle(DEFAULT_STYLE)[0]?.base ?? "rogue")}>{t("society.create.import_reset")}</button>@@ -595,30 +664,37 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo<span className="w-16 text-xs text-muted-foreground">{t("society.create.style")}</span><Segmentedvalue={style}- options={Object.keys(CATALOG.styles).map((id) => ({- value: id,- label: t(`society.style.${id}`),- disabled: !stylesWithBases().includes(id),- hint: stylesWithBases().includes(id) ? undefined : t("society.create.style_soon"),- }))}+ options={Object.keys(CATALOG.styles).map((id) => {+ // "Imported" is not a style to pick — it is where the+ // Import button lands, so it lights up once a GLB is in.+ const live = id === "custom" ? imported : styleOptions.includes(id);+ return {+ value: id,+ label: t(`society.style.${id}`),+ disabled: !live,+ hint: live+ ? undefined+ : t(id === "custom" ? "society.create.style_import_hint" : "society.create.style_soon"),+ };+ })}onChange={(next) => {- setStyle(next);- const first = basesForStyle(next)[0];- if (first && !basesForStyle(next).some((b) => b.base === recipe.base)) {- setRecipe((r) => ({ ...r, base: first.base, parts: {}, style: next }));- }+ if (next === style) return;+ const keep = basesForStyle(next).some((b) => b.base === recipe.base);+ selectBase(next, keep ? recipe.base : (basesForStyle(next)[0]?.base ?? recipe.base));}}/></div>- <div className="flex items-center gap-3">- <span className="w-16 text-xs text-muted-foreground">{t("society.create.base")}</span>- <Segmented- value={recipe.base}- options={basesForStyle(style).map((b) => ({ value: b.base, label: b.label }))}- onChange={(base) => setRecipe((r) => ({ ...r, base, style }))}- />- </div>- {slotsWithParts("biped").map((slot) => (+ {imported ? null : (+ <div className="flex items-center gap-3">+ <span className="w-16 text-xs text-muted-foreground">{t("society.create.base")}</span>+ <Segmented+ value={recipe.base}+ options={bases.map((b) => ({ value: b.base, label: b.label }))}+ onChange={(base) => selectBase(style, base)}+ />+ </div>+ )}+ {slots.map((slot) => (<div key={slot} className="flex items-center gap-3"><span className="w-16 text-xs text-muted-foreground">{t(`society.slot.${slot}`)}</span><div className="flex flex-wrap gap-1">@@ -626,7 +702,10 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialovalue={recipe.parts[slot] ?? ""}options={[{ value: "", label: t("society.create.none") },- ...partsForSlot(slot, "biped", null).map((part) => ({ value: part.id, label: part.label })),+ ...partsForSlot(slot, archetype, style).map((part) => ({+ value: part.id,+ label: part.label,+ })),]}onChange={(id) =>setRecipe((r) => {@@ -686,15 +765,15 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo<inputid="society-create-height"type="range"- min={HEIGHT_MIN}- max={HEIGHT_MAX}+ min={heights.min}+ max={heights.max}step={0.01}- value={recipe.heightM ?? 1.75}+ value={heightM}onChange={(e) => setRecipe((r) => ({ ...r, heightM: Number.parseFloat(e.target.value) }))}className="flex-1"/><span className="w-14 text-right font-mono text-xs text-muted-foreground">- {(recipe.heightM ?? 1.75).toFixed(2)} m+ {heightM.toFixed(2)} m</span></div></div>diff --git a/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx b/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsxindex d78d869f45..dc7203c510 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx@@ -200,6 +200,13 @@ function FigureScene({ recipe, look, palette, heightM, clip, quiet, paused, orbiconst invalidate = useThree((s) => s.invalidate);const groupRef = useRef<THREE.Group>(null);const figureRef = useRef<AssembledFigure | null>(null);+ // What the camera frames: the body plus whatever it wears. A wizard hat+ // reaches above the figure's own height, and framing by the height alone+ // cut its point off the top of the column.+ const [framedHeightM, setFramedHeightM] = useState(heightM);+ // How far the camera stands back: the figure's LARGEST extent, so a fox is+ // framed by its length and a person still by their height.+ const [framedSpanM, setFramedSpanM] = useState(heightM);// One assembled figure per look; the previous one is disposed first.useEffect(() => {@@ -210,6 +217,8 @@ function FigureScene({ recipe, look, palette, heightM, clip, quiet, paused, orbiassets.parts.map((p) => p.gltf),);figureRef.current = figure;+ setFramedHeightM(figure?.renderedHeightM ?? heightM);+ setFramedSpanM(figure?.renderedSpanM ?? heightM);const group = groupRef.current;if (figure && group) group.add(figure.root);if (figure) {@@ -250,13 +259,13 @@ function FigureScene({ recipe, look, palette, heightM, clip, quiet, paused, orbiif (group) group.rotation.y = o.yaw;// 2.4 heights of distance: larger than the 2.6 it opened with (maintainer:// "about a fifth"), with the crown and the hem still inside the frame.- const mid = heightM * 0.5;- const distance = (heightM * 2.5) / o.zoom;+ const mid = framedHeightM * 0.5;+ const distance = (framedSpanM * 2.5) / o.zoom;camera.position.set(0, mid + Math.sin(o.pitch) * distance, Math.cos(o.pitch) * distance);camera.lookAt(0, mid, 0);camera.updateProjectionMatrix();invalidate();- }, [orbitTick, heightM, camera, invalidate, orbit]);+ }, [orbitTick, framedHeightM, framedSpanM, camera, invalidate, orbit]);useFrame((_, dt) => {if (paused) return;diff --git a/jarvis/ui/web/frontend/src/components/society/figures/assembleFigure.ts b/jarvis/ui/web/frontend/src/components/society/figures/assembleFigure.tsindex 5aa7fb3ad3..bc2be60786 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/assembleFigure.ts+++ b/jarvis/ui/web/frontend/src/components/society/figures/assembleFigure.ts@@ -35,8 +35,23 @@ export interface PartExtras {attach: string;hides: string[];label: string;+ /** Flat cloth with no back face of its own; see `two_sided` in the catalog. */+ two_sided?: boolean;}+/**+ * The material slot a body primitive fills, read off its name — the build+ * names every slot `<figure id>-<slot>` (`biped-mage-hair`, `spirit-gigi-marks`).+ * A part's `hides` list names slots, so this is how the two meet.+ */+export function materialSlotOf(name: string): string {+ const cut = name.lastIndexOf("-");+ return cut < 0 ? "" : name.slice(cut + 1);+}++/** The slot every base paints its body with; nothing may hide it. */+const BODY_SLOT = "sheet";+export interface LoadedGltf {scene: THREE.Object3D;animations: THREE.AnimationClip[];@@ -91,9 +106,41 @@ export interface AssembledFigure {extras: FigureExtras;/** Source units → rendered metres. */scale: number;+ /**+ * Rendered metres from the ground to the top of everything worn — the body+ * plus a wizard hat's point. The body alone is `heightM`; a camera that+ * frames by that alone cuts the hat off, so the viewer frames by this.+ */+ renderedHeightM: number;+ /**+ * The largest of the three rendered extents. A person is taller than they+ * are wide, so for a biped this is the height; a fox is half again as long+ * as it is tall, and a camera pulled back by its height alone crops its+ * nose and tail.+ */+ renderedSpanM: number;dispose(): void;}+/**+ * Take the source material's face sides, cutout and depth behaviour with us.+ * The pixel look is Lambert (or unlit for the glowing marks), but which faces+ * exist is geometry, not shading: a cape is one open sheet of cloth, and+ * rendering it front-side-only makes the half of it that faces the wearer —+ * and every edge that reaches past the body — disappear.+ */+function copySurface(from: THREE.Material, to: THREE.Material, forceDoubleSide: boolean): void {+ to.side = forceDoubleSide ? THREE.DoubleSide : from.side;+ to.transparent = from.transparent;+ to.opacity = from.opacity;+ to.alphaTest = from.alphaTest;+ to.depthWrite = from.depthWrite;+}++function firstMaterialOf(node: THREE.Mesh): THREE.Material {+ return (Array.isArray(node.material) ? node.material[0] : node.material) as THREE.Material;+}+/*** Clone the base for one agent. `SkeletonUtils.clone` is the only clone that* keeps a skinned mesh bound to ITS OWN skeleton copy; `Object3D.clone`@@ -121,17 +168,16 @@ export function assembleFigure(body.traverse((node) => {if (node.name === "FWD") node.visible = false;if (!(node instanceof THREE.Mesh)) return;- const original = (Array.isArray(node.material) ? node.material[0] : node.material) as- | THREE.MeshStandardMaterial- | THREE.MeshBasicMaterial;+ const original = firstMaterialOf(node) as THREE.MeshStandardMaterial | THREE.MeshBasicMaterial;const map = original.map ?? null;if (map && !painted) painted = paintPalette(map, palette);// A "-marks" slot (Gigi's eyes, mouth, scanlines) glows: unlit, so it// reads white on the dark body under any light, like the mascot in 2D.- const material = original.name.endsWith("-marks")+ const material = materialSlotOf(original.name) === "marks"? new THREE.MeshBasicMaterial({ map: painted ?? map, color: 0xffffff }): new THREE.MeshLambertMaterial({ map: painted ?? map, color: 0xffffff });material.name = original.name;+ copySurface(original, material, false);node.material = material;// A skinned mesh's bounds ignore its bones; culling it by the rest pose// hides a figure whose arms leave the box. Two draw calls are cheaper.@@ -148,25 +194,54 @@ export function assembleFigure(// the body's skeleton with the body's bind matrix and follows every clip.const anchor = skinned[0] ?? null;const hidden = new Set<string>();+ const worn: THREE.SkinnedMesh[] = [];for (const partGltf of parts) {const partExtras = readPartExtras(partGltf);- if (!anchor || !partExtras) continue;+ // A part built for another archetype binds to bones this skeleton does+ // not have; it would hang in the air. The figure renders without it.+ if (!anchor || !partExtras || partExtras.archetype !== extras.archetype) continue;partGltf.scene.traverse((node) => {if (!(node instanceof THREE.SkinnedMesh)) return;- const material = new THREE.MeshLambertMaterial({ map: painted ?? undefined, color: 0xffffff });+ const source = firstMaterialOf(node);+ // The part's own sheet is the fallback, not `undefined`: an imported+ // body carries no palette strip to paint, and a part without a map is+ // a flat white silhouette.+ const map = painted ?? (source as THREE.MeshStandardMaterial).map ?? undefined;+ const material = new THREE.MeshLambertMaterial({ map, color: 0xffffff });+ material.name = `part-${partExtras.slot}`;+ copySurface(source, material, partExtras.two_sided === true);const mesh = new THREE.SkinnedMesh(node.geometry, material);mesh.name = `part:${partExtras.slot}`;mesh.frustumCulled = false;mesh.bind(anchor.skeleton, anchor.bindMatrix);anchor.parent?.add(mesh);owned.push(material);+ worn.push(mesh);});for (const hide of partExtras.hides ?? []) hidden.add(hide);}+ // `hides` names material slots, not just hair: a full helmet hides the+ // hair, a diving suit could hide the hands. The body slot itself never goes.for (const mesh of bodyMeshes) {- const materialName = (mesh.material as THREE.Material).name ?? "";- if (hidden.has("hair") && materialName.endsWith("-hair")) mesh.visible = false;+ const slot = materialSlotOf(firstMaterialOf(mesh).name ?? "");+ if (slot && slot !== BODY_SLOT && hidden.has(slot)) mesh.visible = false;+ }++ // What the camera has to fit: the rest-pose bounds of everything visible,+ // in rendered metres. A wizard hat reaches a third of a metre above a+ // 1.75 m figure; framing by the body's height alone decapitates it.+ const bounds = new THREE.Box3();+ for (const mesh of [...bodyMeshes, ...worn]) {+ if (!mesh.visible) continue;+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox;+ if (box) bounds.union(box);}+ const renderedHeightM = bounds.isEmpty() ? heightM : Math.max(heightM, bounds.max.y * scale);+ const size = bounds.isEmpty() ? null : bounds.getSize(new THREE.Vector3());+ const renderedSpanM = size+ ? Math.max(renderedHeightM, size.x * scale, size.z * scale)+ : renderedHeightM;const mixer = new THREE.AnimationMixer(body);const actions: Record<string, THREE.AnimationAction> = {};@@ -184,6 +259,8 @@ export function assembleFigure(actions,extras,scale,+ renderedHeightM,+ renderedSpanM,dispose() {mixer.stopAllAction();mixer.uncacheRoot(body);diff --git a/jarvis/ui/web/frontend/src/components/society/figures/catalog.json b/jarvis/ui/web/frontend/src/components/society/figures/catalog.jsonindex 55dd36409c..f59d4f156a 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/catalog.json+++ b/jarvis/ui/web/frontend/src/components/society/figures/catalog.json@@ -10,6 +10,52 @@"custom": "Imported by the person"},"bases": [+ {+ "id": "biped/android",+ "file": "biped-android.glb",+ "archetype": "biped",+ "variant": "medium",+ "base": "android",+ "label": "Android",+ "styles": [+ "scifi"+ ],+ "heightM": 1.75,+ "palette": {+ "skin": "#c9d2d8",+ "skin_shade": "#a3adb5",+ "hair": "#5a646b",+ "eyes": "#101820",+ "primary": "#2f6f8f",+ "primary_shade": "#1f4a60",+ "secondary": "#cdd6db",+ "secondary_shade": "#9aa5ab",+ "accent": "#4fd1c5",+ "metal": "#b6c0c6",+ "leather": "#39444b",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#1f4a60",+ "eye_white": "#e6ecef",+ "emissive": "#6ff2e3"+ },+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Android",+ "license": "first-party",+ "note": "body modelled by humanoid_builder.py (profile `android`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted",+ "triangles": 324,+ "clips": [+ "celebrate",+ "idle",+ "run",+ "sit",+ "sleep",+ "talk",+ "walk",+ "wave",+ "work"+ ],+ "height_m": 2.39+ },{"id": "biped/barbarian","file": "biped-barbarian.glb",@@ -55,6 +101,98 @@],"height_m": 2.1863},+ {+ "id": "biped/casual",+ "file": "biped-casual.glb",+ "archetype": "biped",+ "variant": "medium",+ "base": "casual",+ "label": "Casual",+ "styles": [+ "modern"+ ],+ "heightM": 1.75,+ "palette": {+ "skin": "#d8a37c",+ "skin_shade": "#b98763",+ "hair": "#241a15",+ "eyes": "#1b2427",+ "primary": "#3f7d6a",+ "primary_shade": "#2c5a4c",+ "secondary": "#3d5a80",+ "secondary_shade": "#2b3f5a",+ "accent": "#e8c46b",+ "metal": "#9aa3a8",+ "leather": "#4a3526",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#e9e5dc",+ "eye_white": "#f4f7f8",+ "emissive": "#ffd166"+ },+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Casual",+ "license": "first-party",+ "note": "body modelled by humanoid_builder.py (profile `casual`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted",+ "triangles": 384,+ "clips": [+ "celebrate",+ "idle",+ "run",+ "sit",+ "sleep",+ "talk",+ "walk",+ "wave",+ "work"+ ],+ "height_m": 2.18+ },+ {+ "id": "biped/chibi",+ "file": "biped-chibi.glb",+ "archetype": "biped",+ "variant": "medium",+ "base": "chibi",+ "label": "Chibi",+ "styles": [+ "cartoon"+ ],+ "heightM": 1.75,+ "palette": {+ "skin": "#f6cdaa",+ "skin_shade": "#dcab86",+ "hair": "#c9522f",+ "eyes": "#241d1a",+ "primary": "#e2604a",+ "primary_shade": "#b8452f",+ "secondary": "#f6d98a",+ "secondary_shade": "#d9b45f",+ "accent": "#4fb7a5",+ "metal": "#a8b2b7",+ "leather": "#8a5a38",+ "fur": "#c98b62",+ "fur_shade": "#9b6242",+ "shoes": "#3b4a63",+ "eye_white": "#ffffff",+ "emissive": "#ffe066"+ },+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Chibi",+ "license": "first-party",+ "note": "body modelled by humanoid_builder.py (profile `chibi`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted",+ "triangles": 336,+ "clips": [+ "celebrate",+ "idle",+ "run",+ "sit",+ "sleep",+ "talk",+ "walk",+ "wave",+ "work"+ ],+ "height_m": 2.18+ },{"id": "biped/knight","file": "biped-knight.glb",@@ -145,6 +283,52 @@],"height_m": 2.2027},+ {+ "id": "biped/office",+ "file": "biped-office.glb",+ "archetype": "biped",+ "variant": "medium",+ "base": "office",+ "label": "Office",+ "styles": [+ "modern"+ ],+ "heightM": 1.75,+ "palette": {+ "skin": "#f1c4a0",+ "skin_shade": "#d3a382",+ "hair": "#3b2a20",+ "eyes": "#1b2427",+ "primary": "#f2f2ee",+ "primary_shade": "#d3d3cd",+ "secondary": "#1f2a44",+ "secondary_shade": "#141c2e",+ "accent": "#a8322f",+ "metal": "#9aa3a8",+ "leather": "#3a2a20",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#241f1c",+ "eye_white": "#f4f7f8",+ "emissive": "#ffd166"+ },+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / Office",+ "license": "first-party",+ "note": "body modelled by humanoid_builder.py (profile `office`); rig and clips from KayKit Character Pack: Adventurers 1.0 (CC0-1.0) / Rogue, every donor mesh deleted",+ "triangles": 360,+ "clips": [+ "celebrate",+ "idle",+ "run",+ "sit",+ "sleep",+ "talk",+ "walk",+ "wave",+ "work"+ ],+ "height_m": 2.18+ },{"id": "biped/rogue","file": "biped-rogue.glb",@@ -153,7 +337,6 @@"base": "rogue","label": "Ranger","styles": [- "modern","fantasy"],"heightM": 1.75,@@ -191,6 +374,50 @@],"height_m": 2.187},+ {+ "id": "quadruped/fox",+ "file": "quadruped-fox.glb",+ "archetype": "quadruped",+ "variant": "default",+ "base": "fox",+ "label": "Fox",+ "styles": [+ "animal"+ ],+ "heightM": 0.9,+ "palette": {+ "skin": "#f0b5a8",+ "skin_shade": "#d29488",+ "hair": "#b8532a",+ "eyes": "#1a1614",+ "primary": "#c25a2a",+ "primary_shade": "#9a4420",+ "secondary": "#f4efe6",+ "secondary_shade": "#d8d0c2",+ "accent": "#f2c14e",+ "metal": "#9aa3a8",+ "leather": "#6b4a33",+ "fur": "#c8622b",+ "fur_shade": "#f4efe6",+ "shoes": "#2b2320",+ "eye_white": "#fbf8f2",+ "emissive": "#ffd166"+ },+ "source": "Personal Jarvis animals (first-party) / Fox",+ "license": "first-party",+ "note": "rig, body and clips written by quadruped_builder.py (shape `fox`); no external source",+ "triangles": 396,+ "clips": [+ "celebrate",+ "idle",+ "run",+ "sit",+ "sleep",+ "talk",+ "walk"+ ],+ "height_m": 0.88+ },{"id": "spirit/gigi","file": "spirit-gigi.glb",@@ -235,6 +462,29 @@}],"parts": [+ {+ "id": "back-backpack",+ "file": "parts/biped/back-backpack.glb",+ "archetype": "biped",+ "slot": "back",+ "attach": "chest",+ "label": "Backpack",+ "styles": [+ "modern",+ "cartoon",+ "scifi"+ ],+ "hides": [],+ "from_base": "office",+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / back-backpack",+ "license": "first-party",+ "palette_cells": {+ "leather": 18,+ "secondary": 6+ },+ "triangles": 48,+ "two_sided": false+ },{"id": "back-fur-cape","file": "parts/biped/back-fur-cape.glb",@@ -250,9 +500,10 @@"source": "KayKit Character Pack: Adventurers 1.0 / Barbarian_Cape","license": "CC0-1.0","palette_cells": {- "secondary_shade": 78+ "fur": 78},- "triangles": 78+ "triangles": 78,+ "two_sided": true},{"id": "back-knight-cape",@@ -271,7 +522,8 @@"palette_cells": {"primary": 84},- "triangles": 84+ "triangles": 84,+ "two_sided": true},{"id": "back-mage-cape",@@ -288,9 +540,10 @@"source": "KayKit Character Pack: Adventurers 1.0 / Mage_Cape","license": "CC0-1.0","palette_cells": {- "metal": 84+ "primary": 84},- "triangles": 84+ "triangles": 84,+ "two_sided": true},{"id": "back-rogue-cape",@@ -300,8 +553,7 @@"attach": "chest","label": "Ranger cape","styles": [- "fantasy",- "modern"+ "fantasy"],"hides": [],"from_base": "rogue",@@ -310,7 +562,29 @@"palette_cells": {"secondary_shade": 84},- "triangles": 84+ "triangles": 84,+ "two_sided": true+ },+ {+ "id": "collar-band",+ "file": "parts/quadruped/collar-band.glb",+ "archetype": "quadruped",+ "slot": "collar",+ "attach": "neck",+ "label": "Collar",+ "styles": [+ "animal"+ ],+ "hides": [],+ "from_base": "fox",+ "source": "Personal Jarvis animals (first-party) / collar-band",+ "license": "first-party",+ "palette_cells": {+ "leather": 6,+ "accent": 6+ },+ "triangles": 24,+ "two_sided": false},{"id": "hand_l-round-shield",@@ -330,7 +604,8 @@"leather": 110,"metal": 174},- "triangles": 284+ "triangles": 284,+ "two_sided": false},{"id": "hand_l-spellbook",@@ -340,8 +615,7 @@"attach": "handslot_l","label": "Spellbook","styles": [- "fantasy",- "modern"+ "fantasy"],"hides": [],"from_base": "mage",@@ -353,7 +627,30 @@"leather": 132,"metal": 72},- "triangles": 292+ "triangles": 292,+ "two_sided": false+ },+ {+ "id": "hand_l-tablet",+ "file": "parts/biped/hand_l-tablet.glb",+ "archetype": "biped",+ "slot": "hand_l",+ "attach": "handslot_l",+ "label": "Tablet",+ "styles": [+ "modern",+ "scifi"+ ],+ "hides": [],+ "from_base": "office",+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / hand_l-tablet",+ "license": "first-party",+ "palette_cells": {+ "metal": 6,+ "emissive": 6+ },+ "triangles": 24,+ "two_sided": false},{"id": "hand_l-wooden-shield",@@ -375,7 +672,8 @@"metal": 174,"leather": 50},- "triangles": 284+ "triangles": 284,+ "two_sided": false},{"id": "hand_r-axe",@@ -396,7 +694,8 @@"accent": 112,"metal": 82},- "triangles": 274+ "triangles": 274,+ "two_sided": false},{"id": "hand_r-knife",@@ -416,7 +715,8 @@"metal": 156,"leather": 16},- "triangles": 172+ "triangles": 172,+ "two_sided": false},{"id": "hand_r-mug",@@ -427,7 +727,9 @@"label": "Mug","styles": ["modern",- "fantasy"+ "fantasy",+ "cartoon",+ "scifi"],"hides": [],"from_base": "barbarian",@@ -438,7 +740,8 @@"secondary": 84,"metal": 198},- "triangles": 426+ "triangles": 426,+ "two_sided": false},{"id": "hand_r-staff",@@ -459,7 +762,8 @@"leather": 216,"metal": 160},- "triangles": 440+ "triangles": 440,+ "two_sided": false},{"id": "hand_r-sword",@@ -479,7 +783,57 @@"leather": 80,"metal": 220},- "triangles": 300+ "triangles": 300,+ "two_sided": false+ },+ {+ "id": "hand_r-wrench",+ "file": "parts/biped/hand_r-wrench.glb",+ "archetype": "biped",+ "slot": "hand_r",+ "attach": "handslot_r",+ "label": "Wrench",+ "styles": [+ "modern",+ "cartoon",+ "scifi"+ ],+ "hides": [],+ "from_base": "office",+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / hand_r-wrench",+ "license": "first-party",+ "palette_cells": {+ "metal": 6,+ "secondary_shade": 6+ },+ "triangles": 24,+ "two_sided": false+ },+ {+ "id": "headgear-cap",+ "file": "parts/biped/headgear-cap.glb",+ "archetype": "biped",+ "slot": "headgear",+ "attach": "head",+ "label": "Cap",+ "styles": [+ "modern",+ "cartoon",+ "scifi"+ ],+ "hides": [+ "hair"+ ],+ "from_base": "office",+ "source": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig) / headgear-cap",+ "license": "first-party",+ "palette_cells": {+ "primary": 12,+ "primary_shade": 6,+ "accent": 6+ },+ "triangles": 48,+ "two_sided": false},{"id": "headgear-horned-hat",@@ -502,7 +856,8 @@"secondary_shade": 392,"fur": 94},- "triangles": 654+ "triangles": 654,+ "two_sided": false},{"id": "headgear-knight-helmet",@@ -523,7 +878,8 @@"palette_cells": {"metal": 480},- "triangles": 480+ "triangles": 480,+ "two_sided": false},{"id": "headgear-mage-hat",@@ -546,7 +902,8 @@"secondary": 72,"metal": 64},- "triangles": 396+ "triangles": 396,+ "two_sided": false}]}diff --git a/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts b/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.tsindex 22f960fc1d..5d6b546e7c 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts+++ b/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts@@ -10,7 +10,7 @@* runtime repaints exactly those cells to recolour a figure.*/-import { catalogBaseFor } from "./figureRegistry";+import { basesForStyle, catalogBaseFor } from "./figureRegistry";export const PALETTE_CELLS = ["skin",@@ -208,10 +208,26 @@ export function recipeKey(recipe: FigureRecipe): string {return `${recipe.archetype}/${recipe.base}|${recipe.model ?? ""}|${parts}|${palette}|${recipe.heightM ?? ""}`;}-/** The recipe a brand-new biped starts from: the ranger base, one preset, no parts. */-export function defaultRecipe(presetId = "ranger", base = "rogue"): FigureRecipe {- const preset = PALETTE_PRESETS.find((p) => p.id === presetId) ?? PALETTE_PRESETS[0];- return { contract: 1, archetype: "biped", base, parts: {}, palette: { ...preset.palette } };+/**+ * The recipe a brand-new figure starts from: the first base of `style`, that+ * base's own default palette, no parts.+ *+ * The base is LOOKED UP from the style rather than named here. Hard-coding+ * one meant that when the ranger stopped being a `modern` body the creator+ * opened on "Modern" with a fantasy ranger in the preview and no build+ * selected — a contradiction that only a person clicking around would find.+ */+export function defaultRecipe(style = "modern"): FigureRecipe {+ const base = basesForStyle(style)[0] ?? null;+ return {+ contract: 1,+ archetype: base?.archetype ?? "biped",+ base: base?.base ?? "rogue",+ style,+ parts: {},+ palette: base ? { ...base.palette } : { ...PALETTE_PRESETS[0].palette },+ heightM: base?.heightM,+ };}/** The three legacy roster colours (primary/secondary/accent) as recipe cells. */diff --git a/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.test.ts b/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.test.tsnew file mode 100644index 0000000000..df684ddec1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.test.ts@@ -0,0 +1,131 @@+/**+ * The creator's promise, checked against the SHIPPED catalog: every style it+ * offers has a figure, every figure and part it puts in the same row can+ * actually be worn together, and a switch never leaves a recipe holding+ * something the new base cannot wear.+ *+ * These run on `catalog.json` itself — the file the build generates — so a+ * rebuild that drops a style's last base, or tags a part onto a style whose+ * bodies it was never cut for, fails here instead of in someone's dialog.+ */+import { describe, expect, it } from "vitest";++import {+ archetypeOfBase,+ basesForStyle,+ catalogBaseFor,+ keepablePartsFor,+ partAssetsFor,+ partsForSlot,+ slotsWithParts,+ stylesWithBases,+ CATALOG,+ type CatalogPart,+} from "./figureRegistry";++/** Styles that are a lane, not a look: `custom` is the person's own import. */+const IMPORT_ONLY = new Set(["custom"]);++const pickableStyles = Object.keys(CATALOG.styles).filter((s) => !IMPORT_ONLY.has(s));++describe("the catalog covers every style the creator shows", () => {+ it.each(pickableStyles)("%s has at least one base", (style) => {+ expect(basesForStyle(style).length).toBeGreaterThan(0);+ });++ it("reports exactly the styles that have a base, never the import lane", () => {+ expect(stylesWithBases().sort()).toEqual(pickableStyles.sort());+ });++ it("gives every base a label, a palette and at least an idle", () => {+ for (const base of CATALOG.bases) {+ expect(base.label, base.id).toBeTruthy();+ expect(base.palette.skin, base.id).toMatch(/^#[0-9a-f]{6}$/i);+ expect(base.clips, base.id).toContain("idle");+ }+ });+});++describe("a part is only ever offered where it fits", () => {+ it("never tags a part onto a style that has no base of its archetype", () => {+ for (const part of CATALOG.parts) {+ for (const style of part.styles) {+ const hosts = basesForStyle(style, part.archetype);+ expect(hosts.length, `${part.id} is tagged ${style}`).toBeGreaterThan(0);+ }+ }+ });++ it("only lists slots that actually hold something for the style", () => {+ for (const style of pickableStyles) {+ for (const base of basesForStyle(style)) {+ for (const slot of slotsWithParts(base.archetype, style)) {+ expect(partsForSlot(slot, base.archetype, style).length).toBeGreaterThan(0);+ }+ }+ }+ });++ it("gives every biped style something to put on", () => {+ for (const style of pickableStyles) {+ const bipeds = basesForStyle(style, "biped");+ if (bipeds.length === 0) continue;+ expect(slotsWithParts("biped", style).length, style).toBeGreaterThan(0);+ }+ });++ it("marks the flat capes two-sided and nothing solid", () => {+ const twoSided = CATALOG.parts.filter((p) => p.two_sided).map((p) => p.id);+ expect(twoSided.sort()).toEqual(+ CATALOG.parts.filter((p) => p.slot === "back" && p.id.endsWith("-cape")).map((p) => p.id).sort(),+ );+ });+});++describe("switching style or base never leaves a stranded part", () => {+ const capeOf = (style: string): CatalogPart | undefined =>+ CATALOG.parts.find((p) => p.slot === "back" && p.styles.includes(style));++ it("keeps a part the new style still offers", () => {+ const cape = capeOf("fantasy");+ expect(cape).toBeDefined();+ const kept = keepablePartsFor({ back: cape!.id }, "biped", "fantasy");+ expect(kept).toEqual({ back: cape!.id });+ });++ it("drops a part the new style does not offer", () => {+ const cape = capeOf("fantasy")!;+ expect(cape.styles).not.toContain("scifi");+ expect(keepablePartsFor({ back: cape.id }, "biped", "scifi")).toEqual({});+ });++ it("drops every biped part when the base becomes a spirit", () => {+ const worn = Object.fromEntries(+ CATALOG.parts.filter((p) => p.archetype === "biped").map((p) => [p.slot, p.id]),+ );+ expect(keepablePartsFor(worn, "spirit", null)).toEqual({});+ });++ it("drops an id that no longer exists", () => {+ expect(keepablePartsFor({ back: "back-gone" }, "biped", null)).toEqual({});+ });+});++describe("a recipe is read for what it names, not what it claims", () => {+ it("finds a base whose archetype drifted from the recipe", () => {+ // Gigi is a spirit; a row still carrying `biped` must not silently+ // render the ranger instead.+ expect(catalogBaseFor({ archetype: "biped", base: "gigi" })?.archetype).toBe("spirit");+ expect(archetypeOfBase("gigi")).toBe("spirit");+ });++ it("resolves the legacy size ids to the base they became", () => {+ expect(catalogBaseFor({ archetype: "biped", base: "medium" })?.base).toBe("rogue");+ });++ it("refuses to hang a biped part on a spirit", () => {+ const cape = CATALOG.parts.find((p) => p.archetype === "biped" && p.slot === "back")!;+ const worn = { archetype: "spirit" as const, base: "gigi", parts: { back: cape.id } };+ expect(partAssetsFor(worn)).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.ts b/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.tsindex 4bc62ccff4..90a58a4a19 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.ts+++ b/jarvis/ui/web/frontend/src/components/society/figures/figureRegistry.ts@@ -44,6 +44,8 @@ export interface CatalogPart {source: string;license: string;triangles: number;+ /** Flat cloth (a cape) has no back face of its own; the runtime renders it from both sides. */+ two_sided?: boolean;}export interface FigureCatalog {@@ -83,9 +85,25 @@ export interface FigureAsset {catalog: CatalogBase | null;}+/**+ * The catalog row behind a recipe. The archetype narrows it, but a recipe+ * whose archetype drifted from its base — a saved row from before the base+ * moved archetype, or a style switch that forgot to carry it — still finds+ * its figure by base name alone. Silently rendering the wrong figure is the+ * one outcome worth ruling out.+ */export function catalogBaseFor(recipe: Pick<FigureRecipe, "archetype" | "base">): CatalogBase | null {const base = LEGACY_BASES[recipe.base] ?? recipe.base;- return CATALOG.bases.find((b) => b.archetype === recipe.archetype && b.base === base) ?? null;+ return (+ CATALOG.bases.find((b) => b.archetype === recipe.archetype && b.base === base) ??+ CATALOG.bases.find((b) => b.base === base) ??+ null+ );+}++/** The archetype a base belongs to — the value a recipe must carry with it. */+export function archetypeOfBase(base: string): FigureArchetype | null {+ return catalogBaseFor({ archetype: "biped", base })?.archetype ?? null;}/** The GLB behind a recipe: a catalog base, or the recipe's own imported model. */@@ -128,48 +146,90 @@ export function partAssetFor(partId: string): PartAsset | null {return url ? { url, part } : null;}-/** The parts a recipe wears, resolved; unknown ids are dropped, not fatal. */-export function partAssetsFor(recipe: Pick<FigureRecipe, "parts">): PartAsset[] {+/**+ * The parts a recipe wears, resolved. An unknown id is dropped, and so is a+ * part built for another archetype — a biped cape skinned to `chest` binds to+ * nothing on Gigi's three-bone rig and would hang in the air beside her.+ * Neither is fatal: the figure renders without it.+ */+export function partAssetsFor(+ recipe: Pick<FigureRecipe, "parts"> & Partial<Pick<FigureRecipe, "archetype" | "base">>,+): PartAsset[] {+ const archetype = recipe.base+ ? (catalogBaseFor({ archetype: recipe.archetype ?? "biped", base: recipe.base })?.archetype ?? recipe.archetype)+ : recipe.archetype;return Object.values(recipe.parts ?? {}).map((id) => (id ? partAssetFor(id) : null))- .filter((p): p is PartAsset => p !== null);+ .filter((p): p is PartAsset => p !== null)+ .filter((p) => !archetype || p.part.archetype === archetype);}-/** Styles that have at least one base today, in catalog order; the creator disables the rest. */+/**+ * Styles that have at least one base today, in catalog order; the creator+ * disables the rest. `custom` is the import lane and never appears here — it+ * has no catalog base by definition; the creator enables it once a person's+ * own GLB is in.+ */export function stylesWithBases(): string[] {const live = new Set(CATALOG.bases.flatMap((b) => b.styles));return Object.keys(CATALOG.styles).filter((s) => live.has(s));}-export function basesForStyle(style: string | null, archetype: FigureArchetype = "biped"): CatalogBase[] {- return CATALOG.bases.filter((b) => b.archetype === archetype && (!style || b.styles.includes(style)));+/**+ * The bases a style offers. A style is NOT tied to one archetype — `animal`+ * is quadruped, `spirit` is spirit, `cartoon` may be either — so the+ * archetype narrows the list only when the caller asks for one.+ */+export function basesForStyle(style: string | null, archetype: FigureArchetype | null = null): CatalogBase[] {+ return CATALOG.bases.filter(+ (b) => (!archetype || b.archetype === archetype) && (!style || b.styles.includes(style)),+ );}-export function partsForSlot(slot: string, archetype: FigureArchetype = "biped", style: string | null = null): CatalogPart[] {+export function partsForSlot(+ slot: string,+ archetype: FigureArchetype = "biped",+ style: string | null = null,+): CatalogPart[] {return CATALOG.parts.filter((p) => p.archetype === archetype && p.slot === slot && (!style || p.styles.includes(style)),);}-/** Slots any catalog part fills for an archetype, in the contract's order of the parts list. */-export function slotsWithParts(archetype: FigureArchetype = "biped"): string[] {+/**+ * Slots that hold at least one part for this archetype AND style, in the+ * order the catalog lists them. A slot with nothing to offer is not a row of+ * one "None" button — it is not a row at all.+ */+export function slotsWithParts(archetype: FigureArchetype = "biped", style: string | null = null): string[] {const seen: string[] = [];for (const p of CATALOG.parts) {- if (p.archetype === archetype && !seen.includes(p.slot)) seen.push(p.slot);+ if (p.archetype !== archetype) continue;+ if (style && !p.styles.includes(style)) continue;+ if (!seen.includes(p.slot)) seen.push(p.slot);}return seen;}-/** Every asset URL, for preloading the moment the section opens. */-export const FIGURE_URLS: readonly string[] = Object.values(FILES);-/**- * Bases the creator can pick today, per archetype — keyed by the legacy- * small/medium/large ids the dialog still offers. The catalog's own `base`- * names (rogue, …) stay inside the catalog; this list is the dialog's.+ * The parts of `recipe` that the given base and style still support — what a+ * style or base switch must keep. A cape tagged `fantasy` does not survive a+ * move to `scifi`, and no biped part survives a move to a quadruped.*/-export const AVAILABLE_BASES: Readonly<Record<FigureArchetype, readonly string[]>> = {- biped: ["medium"],- quadruped: [],- spirit: [],-};+export function keepablePartsFor(+ parts: Record<string, string>,+ archetype: FigureArchetype,+ style: string | null,+): Record<string, string> {+ const kept: Record<string, string> = {};+ for (const [slot, id] of Object.entries(parts ?? {})) {+ const part = CATALOG.parts.find((p) => p.id === id);+ if (!part || part.archetype !== archetype || part.slot !== slot) continue;+ if (style && !part.styles.includes(style)) continue;+ kept[slot] = id;+ }+ return kept;+}++/** Every asset URL, for preloading the moment the section opens. */+export const FIGURE_URLS: readonly string[] = Object.values(FILES);diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsxindex cefe3e26fe..f142a8e2eb 100644--- a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx@@ -18,7 +18,7 @@ import "@fontsource/pixelify-sans/500.css";import "@fontsource/pixelify-sans/600.css";import "./world.css";-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { useCallback, useRef, useState, type ReactNode } from "react";import { Canvas } from "@react-three/fiber";import { useReducedMotion } from "framer-motion";@@ -27,7 +27,6 @@ import { useCanvasAwake } from "@/hooks/useCanvasAwake";import { useWebglSurface } from "@/hooks/useWebglSurface";import { useWebglSupported } from "@/lib/graphDimension";import { useSocietyRoster } from "../data";-import { syncBuildingPoses, useBuildingPoses } from "./buildingPoses";import { useCameraStore } from "./cameraStore";import { Clouds } from "./Clouds";import { FoundryDrawer } from "./FoundryDrawer";@@ -49,12 +48,11 @@ import { WorldCameraRig } from "./WorldCameraRig";import { WorldComposer } from "./WorldComposer";import { WorldHud } from "./WorldHud";import { WorldKitProvider } from "./WorldKit";-import { isKitPlace, type KitPlace, type PlaceId } from "./islandLayout";+import { RING_KIT_SLOTS, type KitPlace, type PlaceId } from "./islandLayout";-/** Only kit hubs open a drawer; other places are scenery. */+/** Only ring hubs open a drawer; other places are scenery. */function asHub(place: PlaceId): KitPlace | null {- // Not "is it in the house ring" — the foundry crowns the mountain instead.- return isKitPlace(place) ? place : null;+ return place in RING_KIT_SLOTS ? (place as KitPlace) : null;}import { cameraOffset } from "./worldCamera";import { SKY } from "./worldPalette";@@ -92,8 +90,6 @@ export function WorldStage({ topRight, onOpenLedger, onSelectAgent }: WorldStageconst [memoryOpen, setMemoryOpen] = useState(false);useWorldControls(hostRef, webgl);- // The viewer's turned buildings go into the island before the first frame.- useEffect(syncBuildingPoses, []);const select = useCallback((agentId: string | null) => {@@ -145,10 +141,7 @@ export function WorldStage({ topRight, onOpenLedger, onSelectAgent }: WorldStagegl={{ antialias: grain === 0, alpha: false, powerPreference: "high-performance", stencil: false }}frameloop={frameloop}onPointerMissed={() => {- const poses = useBuildingPoses.getState();- if (useCameraStore.getState().dragging || poses.rotating) return;- select(null);- poses.select(null);+ if (!useCameraStore.getState().dragging) select(null);}}><color attach="background" args={[SKY.clear]} />diff --git a/jarvis/ui/web/frontend/src/components/society/world/foundry.test.ts b/jarvis/ui/web/frontend/src/components/society/world/foundry.test.tsindex 786cc4f66f..596a09de66 100644--- a/jarvis/ui/web/frontend/src/components/society/world/foundry.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/world/foundry.test.ts@@ -9,15 +9,10 @@ import { beforeEach, describe, expect, it } from "vitest";import {FOUNDRY_PORTAL_M,FOUNDRY_RAMP_END_M,- LEVEL_Y,- SUMMIT_LEVEL,- SUMMIT_TILE,buildIsland,- findPath,foundryWalkOut,isWalkable,kitPose,- tileIndex,worldToTile,} from "./islandLayout";import { CAMERA_YAW_DEG } from "./worldCamera";@@ -58,34 +53,6 @@ describe("foundryWalkOut", () => {expect(off).toBeLessThan(Math.PI / 6);});- it("stands on the mountain's summit terrace", () => {- const { map } = buildIsland();- const [tx, tz] = worldToTile(...([kitPose("foundry").x, kitPose("foundry").z] as [number, number]));- expect([tx, tz]).toEqual([SUMMIT_TILE[0], SUMMIT_TILE[1]]);- expect(map.level[tileIndex(map, tx, tz)]).toBe(SUMMIT_LEVEL);- // High above the village plateau: this is the island's backdrop, not a- // building on the square.- expect(LEVEL_Y[SUMMIT_LEVEL]).toBeGreaterThan(10);- });-- it("is reachable on foot from the village square", () => {- // The whole point of the mountain road: a new agent walks the climb down- // into the village, and anyone can walk back up. A break anywhere in the- // graded legs would strand the works on its own terrace.- const { map, content } = buildIsland();- const path = findPath(map, content.places.market.standTile, content.places.foundry.standTile);- expect(path, "no road from the square to the foundry").not.toBeNull();- // And the climb never asks for more than a single step at a time.- for (let i = 1; i < (path ?? []).length; i++) {- const [ax, az] = (path ?? [])[i - 1];- const [bx, bz] = (path ?? [])[i];- const rise = Math.abs(- map.level[tileIndex(map, bx, bz)] - map.level[tileIndex(map, ax, az)],- );- expect(rise, `step ${i}`).toBeLessThanOrEqual(1);- }- });-it("sets the figure down on ground it may stand on", () => {const { map } = buildIsland();const [tx, tz] = worldToTile(...foundryWalkOut().to);diff --git a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.ts b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.tsindex c2bd05ceb1..ec821a83e0 100644--- a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.test.ts@@ -19,22 +19,14 @@ import {PODIUM_LEVEL,REGIONS,RING_KIT_SLOTS,- SUMMIT_LEVEL,SNOW_LEVEL,SPOKES,TileKind,- applyBuildingYaws,buildIsland,- defaultBuildingYaw,- facesCamera,findPath,groundY,hash2,- houseDefaultRotation,- houseId,isWalkable,- kitId,- nearestWalkable,randomPlazaTile,smoothPath,tileIndex,@@ -152,124 +144,27 @@ describe("islandLayout", () => {it("opens a paved square in the middle with a ring of houses around it", () => {const { map, content } = island;expect(map.kind[tileIndex(map, CENTER_TILE + 5, CENTER_TILE + 5)]).toBe(TileKind.plaza);- expect(content.houses.length).toBe(7); // 12 slots, five taken by the ring hubs+ expect(content.houses.length).toBe(5); // 12 slots, seven taken by the five ring hubsfor (const h of content.houses) {const r = Math.hypot(h.x, h.z) / 2;expect(r).toBeGreaterThan(PLAZA_RADIUS_TILES);expect(r).toBeLessThan(HEDGE_RING_TILES);- // A door faces the square or the ring road: local +z rotated by- // `rotation` points along the radius, one way or the other …+ // Doors face the square: local +z rotated by `rotation` points at the centre.const fx = Math.sin(h.rotation);const fz = Math.cos(h.rotation);- const along = (fx * -h.x + fz * -h.z) / Math.hypot(h.x, h.z);- expect(Math.abs(along), `house ${h.slot}`).toBeCloseTo(1, 6);- // … and never away from the camera: no house shows the viewer its back.- expect(facesCamera(h.rotation), `house ${h.slot}`).toBe(true);- expect(h.rotation).toBe(h.defaultRotation);- expect(h.defaultRotation).toBeCloseTo(houseDefaultRotation(h.x, h.z), 9);+ const toCentre = [-h.x, -h.z];+ const dot = fx * toCentre[0] + fz * toCentre[1];+ expect(dot).toBeGreaterThan(0);// No house stands on the hub's podium.const [tx, tz] = worldToTile(h.x, h.z);expect(map.level[tileIndex(map, tx, tz)]).toBe(PLATEAU_LEVEL);}- // The houses stand in the south-east half, the camera's side of the ring,- // so most of them face the road — that is the point of the rule.- const towardRoad = content.houses.filter((h) => Math.sin(h.rotation) * h.x + Math.cos(h.rotation) * h.z > 0);- expect(towardRoad.length).toBeGreaterThanOrEqual(4);- // A house on the far side would keep its door on the square.- expect(facesCamera(houseDefaultRotation(-30, -30))).toBe(true);- expect(houseDefaultRotation(-30, -30)).toBeCloseTo(Math.atan2(30, 30), 9);- });-- it("blocks the square's furniture and the landmarks' add-ons so nobody walks through a bench", () => {- const { map, content } = island;- // The Quest Board's plinth and the ring bench: nothing walkable inside 6 m.- for (const [x, z] of [- [1, 1],- [5, 3],- [-5, 1],- [1, -5],- ]) {- expect(isWalkable(map, ...worldToTile(x, z)), `square ${x},${z}`).toBe(false);- }- expect(isWalkable(map, ...worldToTile(7, 1))).toBe(true);- // The long table with its benches, south of the monument.- expect(isWalkable(map, ...worldToTile(0, 8.5))).toBe(false);- expect(isWalkable(map, ...worldToTile(-4, 7))).toBe(false);- expect(isWalkable(map, ...worldToTile(0, 12))).toBe(true);- // The meeting stand tile beside the table stays reachable.- const meet = content.places.market.standTile;- expect(isWalkable(map, meet[0], meet[1])).toBe(true);- // A walk from the west of the square to the east goes AROUND the middle.- const path = findPath(map, worldToTile(-16, 1), worldToTile(16, 1));- expect(path).not.toBeNull();- for (const [tx, tz] of path!) {- const [x, z] = tileToWorld(tx, tz);- expect(Math.hypot(x, z)).toBeGreaterThan(5);- }- // The hub's wings and reflecting pool, the harbor kiosk, the keeper's hut.- const [hx, hz] = tileToWorld(...content.places.hub.tile);- expect(isWalkable(map, ...worldToTile(hx + 15.5, hz + 1))).toBe(false);- expect(isWalkable(map, ...worldToTile(hx, hz + 13.2))).toBe(false);- const [bx, bz] = tileToWorld(...content.places.harbor.tile);- expect(isWalkable(map, ...worldToTile(bx - 7, bz + 2))).toBe(false);- const [lx, lz] = tileToWorld(...content.places.lighthouse.tile);- expect(isWalkable(map, ...worldToTile(lx - 6.5, lz + 3.9))).toBe(false);- // Every lamp post and hedge segment stands on a blocked tile — except a- // lamp on a dock plank (the planks stay open) or on a place's stand tile- // (a stand tile is always kept reachable; the figure stands at the lamp).- const stands = new Set(Object.values(content.places).map((p) => p.standTile.join(",")));- for (const l of content.lamps) {- const [tx, tz] = worldToTile(l.x, l.z);- if (map.kind[tileIndex(map, tx, tz)] === TileKind.dock || stands.has(`${tx},${tz}`)) continue;- expect(isWalkable(map, tx, tz), `lamp ${l.x},${l.z}`).toBe(false);- }- for (const h of content.hedges) expect(isWalkable(map, ...worldToTile(h.x, h.z))).toBe(false);- // Idle wandering never picks a tile inside the bench ring.- for (let i = 0; i < 40; i++) {- const [tx, tz] = randomPlazaTile(map, () => (i * 0.137) % 1);- const [x, z] = tileToWorld(tx, tz);- expect(Math.hypot(x, z)).toBeGreaterThan(6);- }- });-- it("turns buildings in place and re-stamps their footprints", () => {- const { map, content } = island;- const house = content.houses[0];- const rest = house.defaultRotation;- // With no overrides the blocked layer equals the built one.- const before = map.blocked.slice();- applyBuildingYaws(island, {});- expect(map.blocked).toEqual(before);- // Turning a house a quarter round moves its blocked tiles.- applyBuildingYaws(island, { [houseId(house.slot)]: rest + Math.PI / 2 });- expect(house.rotation).toBeCloseTo(rest + Math.PI / 2, 9);- expect(map.blocked).not.toEqual(before);- // Every stand tile is still walkable, and every house tile still blocked.- for (const p of Object.values(content.places)) expect(isWalkable(map, p.standTile[0], p.standTile[1]), p.id).toBe(true);- expect(isWalkable(map, ...worldToTile(house.x, house.z))).toBe(false);- // Back to rest restores the exact layer.- applyBuildingYaws(island, {});- expect(house.rotation).toBe(rest);- expect(map.blocked).toEqual(before);- // Every turnable building has a designed heading to return to.- expect(defaultBuildingYaw(houseId(house.slot))).toBe(rest);- expect(defaultBuildingYaw(kitId("cli"))).toBeCloseTo(content.kitPoses.cli.rotation, 9);- // A figure caught inside a footprint finds the nearest free tile.- const inside = worldToTile(house.x, house.z);- const out = nearestWalkable(map, inside[0], inside[1]);- expect(out).not.toBeNull();- expect(isWalkable(map, out![0], out![1])).toBe(true);- expect(Math.max(Math.abs(out![0] - inside[0]), Math.abs(out![1] - inside[1]))).toBeLessThanOrEqual(3);});it("puts the Plugin Docks on the house ring, facing the square, with a reachable stand", () => {const { map, content } = island;for (const [id, pose] of Object.entries(content.kitPoses)) {- // Ring hubs stand on the house ring; a hub with an anchor of its own does- // not — the Agent Foundry crowns the mountain (SUMMIT_TILE).- if (id in RING_KIT_SLOTS) {- expect(Math.hypot(pose.x, pose.z) / 2, id).toBeCloseTo(HOUSE_RING_TILES, 5);- }+ expect(Math.hypot(pose.x, pose.z) / 2, id).toBeCloseTo(HOUSE_RING_TILES, 5);const fx = Math.sin(pose.rotation);const fz = Math.cos(pose.rotation);// The front points at the centre, unless the building faces the road on purpose.@@ -282,12 +177,10 @@ describe("islandLayout", () => {// No two hubs share a slot.const slots = Object.values(RING_KIT_SLOTS).flat();expect(new Set(slots).size).toBe(slots.length);- // No ring hub stands on the hub's podium; the summit hub stands on its own- // terrace on the mountain, far above the village.- for (const [id, pose] of Object.entries(content.kitPoses)) {+ // No ring hub stands on the hub's podium.+ for (const pose of Object.values(content.kitPoses)) {const [tx, tz] = worldToTile(pose.x, pose.z);- const level = map.level[tileIndex(map, tx, tz)];- expect(level, id).toBe(id in RING_KIT_SLOTS ? PLATEAU_LEVEL : SUMMIT_LEVEL);+ expect(map.level[tileIndex(map, tx, tz)]).toBe(PLATEAU_LEVEL);}});diff --git a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.ts b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.tsindex a5553bc29d..5b6e92b0b5 100644--- a/jarvis/ui/web/frontend/src/components/society/world/islandLayout.ts+++ b/jarvis/ui/web/frontend/src/components/society/world/islandLayout.ts@@ -121,8 +121,6 @@ export const PODIUM_LEVEL = PLATEAU_LEVEL + 1;export const DOCK_Y = 0.55;/** Level from which a rock tile becomes snow. */export const SNOW_LEVEL = 8;-/** The terrace the Agent Foundry stands on: the mountain's top step. */-export const SUMMIT_LEVEL = 9;export interface IslandMap {/** Tiles along one edge. */@@ -133,12 +131,6 @@ export interface IslandMap {level: Uint8Array;/** 1 where a walker may not stand: water, rock, buildings, tree trunks. */blocked: Uint8Array;- /**- * `blocked` without the buildings a viewer may turn (houses, ring hubs, the- * foundry's belt). `applyBuildingYaws` stamps those back in at their current- * heading, so a turned house blocks the tiles it actually covers.- */- blockedStatic: Uint8Array;}// ---------------------------------------------------------------------------@@ -174,18 +166,14 @@ export interface Place {export type HouseVariant = "solar-barrel" | "garden-roof" | "glass-loft";export interface HousePlot {- /** Ring slot (0..15, clockwise from north) — the house's stable identity. */- slot: number;/** Centre of the footprint, world metres. */x: number;z: number;/** Footprint in tiles (w along the house's local x, d along local z). */w: number;d: number;- /** Rotation about y; the door faces local +z. The viewer may turn it (`applyBuildingYaws`). */+ /** Rotation about y; the door faces local +z. */rotation: number;- /** The heading the house rests at — what "reset" returns to. */- defaultRotation: number;variant: HouseVariant;/** Deterministic 0..1 for per-house variation. */seed: number;@@ -348,32 +336,6 @@ export function isWalkable(map: IslandMap, tx: number, tz: number): boolean {return map.blocked[tileIndex(map, tx, tz)] === 0;}-/**- * The walkable tile closest to (tx, tz) within `maxRadius` rings, the tile- * itself included; null when everything around is blocked. A figure that- * finds a building turned over its head steps to this tile first.- */-export function nearestWalkable(map: IslandMap, tx: number, tz: number, maxRadius = 8): [number, number] | null {- if (isWalkable(map, tx, tz)) return [tx, tz];- for (let r = 1; r <= maxRadius; r++) {- let best: [number, number] | null = null;- let bestD = Infinity;- for (let dz = -r; dz <= r; dz++) {- for (let dx = -r; dx <= r; dx++) {- if (Math.max(Math.abs(dx), Math.abs(dz)) !== r) continue;- if (!isWalkable(map, tx + dx, tz + dz)) continue;- const d = dx * dx + dz * dz;- if (d < bestD) {- bestD = d;- best = [tx + dx, tz + dz];- }- }- }- if (best) return best;- }- return null;-}-// ---------------------------------------------------------------------------// Design: where things stand (tile units, from the island centre)// ---------------------------------------------------------------------------@@ -397,12 +359,13 @@ export const GATE_GAP_TILES = 3;* side, and the foundry's ramp runs down onto the plaza in full view of the* island camera (which looks from the south-east).*/-export const RING_KIT_SLOTS: Partial<Record<KitPlace, readonly number[]>> = {+export const RING_KIT_SLOTS: Record<KitPlace, readonly number[]> = {plugins: [13, 14],+ foundry: [2, 3],// Hubs sit on the north and west of the ring so their fronts face the camera// (it looks from the south-east); houses take the slots whose backs it sees.skills: [15], // north, beside the docks: the Skill Forge- mcp: [1], // north-east: the Relay Tower+ mcp: [1], // north, beside the foundry: the Relay Towercli: [11], // west: the Terminal Cantina};@@ -430,71 +393,10 @@ export const KIT_FOOTPRINT_TILES: Record<KitPlace, { w: number; d: number }> = {*/export const KIT_FACING: Partial<Record<KitPlace, number>> = { foundry: Math.PI / 4 };-/**- * The mountain's summit, flattened for the Agent Foundry (maintainer, 2026-09-02:- * "the factory sits up there on the mountain, connected by the road"). The- * highest tile of the snow cap; `PLOT_HALF.foundry` planes a terrace around it- * and `SUMMIT_ROAD` climbs to it, so the works crown the island's backdrop and- * a new agent walks the whole mountain road down into the village.- */-export const SUMMIT_TILE: readonly [number, number] = [CENTER_TILE - 65, CENTER_TILE - 70];--/** Kit buildings that stand on a plot of their own instead of in the house ring. */-const KIT_ANCHOR: Partial<Record<KitPlace, readonly [number, number]>> = {- foundry: SUMMIT_TILE,-};--/** Every kit place, ring-bound or not — the world's hub roster. */-export const KIT_PLACES: readonly KitPlace[] = ["plugins", "foundry", "skills", "mcp", "cli"];--/** Whether a place id names a World Kit hub (the ones a click opens). */-export function isKitPlace(id: string): id is KitPlace {- return (KIT_PLACES as readonly string[]).includes(id);-}--/**- * Where the island camera stands, as a unit vector on the ground: it looks- * from the south-east (`worldCamera.ts`, CAMERA_YAW_DEG = 45). A front that- * points along this vector faces the viewer; one that points against it- * shows its back. `worldCamera.test.ts` pins the two files to each other.- */-export const CAMERA_FROM: readonly [number, number] = [Math.SQRT1_2, Math.SQRT1_2];--/** Wrap an angle into (−π, π]. */-export function normalizeAngle(a: number): number {- let d = a % (2 * Math.PI);- if (d > Math.PI) d -= 2 * Math.PI;- if (d <= -Math.PI) d += 2 * Math.PI;- return d;-}--/** Whether a front heading (rotation about y, front = local +z) faces the camera at all. */-export function facesCamera(rotation: number): boolean {- return Math.sin(rotation) * CAMERA_FROM[0] + Math.cos(rotation) * CAMERA_FROM[1] > -1e-9;-}--/**- * A house's resting heading. Houses face the square — unless that turns their- * back on the viewer, in which case they face the ring road instead: a door- * the camera never sees is a house with its back turned (maintainer,- * 2026-09-02). A house seen exactly in profile keeps the square.- */-export function houseDefaultRotation(x: number, z: number): number {- const toSquare = Math.atan2(-x, -z);- return facesCamera(toSquare) ? toSquare : normalizeAngle(toSquare + Math.PI);-}-/** Where a kit building stands and which way it turns — the one source. */export function kitPose(place: KitPlace): KitPose {+ const pose = ringPose(RING_KIT_SLOTS[place]);const facing = KIT_FACING[place];- const anchor = KIT_ANCHOR[place];- if (anchor) {- const [x, z] = tileToWorld(anchor[0], anchor[1]);- return { x, z, rotation: facing ?? houseDefaultRotation(x, z) };- }- const slots = RING_KIT_SLOTS[place];- if (!slots) throw new Error(`kit place ${place} has neither ring slots nor an anchor`);- const pose = ringPose(slots);return facing === undefined ? pose : { ...pose, rotation: facing };}@@ -536,7 +438,7 @@ const PLACE_TILES: Record<PlaceId, [number, number]> = {mine: [CENTER_TILE - 32, CENTER_TILE - 60],// Kit buildings stand in the house ring (RING_KIT_SLOTS); the tile is the ring pose's.plugins: ringTile("plugins"),- foundry: [SUMMIT_TILE[0], SUMMIT_TILE[1]],+ foundry: ringTile("foundry"),skills: ringTile("skills"),mcp: ringTile("mcp"),cli: ringTile("cli"),@@ -561,8 +463,7 @@ export function foundryWalkOut(): {to: [number, number];heading: number;} {- // The built island's pose, so a turned foundry delivers out of its turned portal.- const p = cached?.content.kitPoses.foundry ?? kitPose("foundry");+ const p = kitPose("foundry");const fx = Math.sin(p.rotation);const fz = Math.cos(p.rotation);return {@@ -590,9 +491,7 @@ const PLOT_HALF: Record<PlaceId, [number, number]> = {solar: [8, 7],mine: [5, 4],plugins: [0, 0], // no flat plot of its own: it sits on the village plateau- // The foundry's terrace: the summit planed flat, wide enough for the hall,- // its conveyor and a rim of snow around the lot.- foundry: [10, 8],+ foundry: [0, 0],skills: [0, 0],mcp: [0, 0],cli: [0, 0],@@ -610,7 +509,7 @@ const PLOT_LEVEL: Record<PlaceId, number> = {solar: 4,mine: 4,plugins: PLATEAU_LEVEL,- foundry: SUMMIT_LEVEL,+ foundry: PLATEAU_LEVEL,skills: PLATEAU_LEVEL,mcp: PLATEAU_LEVEL,cli: PLATEAU_LEVEL,@@ -629,22 +528,6 @@ const MINE_CLIFF = { dz: -8, hw: 8, hd: 3, level: 7 } as const;/** The mine's branch road leaves the north spoke here and runs west to the forecourt. */const MINE_ROAD = { fromX: CENTER_TILE - 1, z: CENTER_TILE - 60, length: 27 } as const;-/**- * The mountain road to the Agent Foundry: three graded legs off the western- * end of the mine's branch, up the flank and onto the summit terrace, arriving- * at the foot of the works' conveyor. Straight legs only — `gradeRoad` widens- * across its own axis, so a diagonal would lay its shoulders lengthwise.- */-const SUMMIT_ROAD: ReadonlyArray<{- from: [number, number];- dir: [number, number];- length: number;-}> = [- { from: [CENTER_TILE - 37, CENTER_TILE - 60], dir: [-1, 0], length: 17 },- { from: [CENTER_TILE - 54, CENTER_TILE - 60], dir: [0, -1], length: 5 },- { from: [CENTER_TILE - 54, CENTER_TILE - 65], dir: [-1, 0], length: 6 },-];-/** Where the dock reaches into the bay: from the harbor plot southward. */export const DOCK_TILES = { from: CENTER_TILE + 66, to: CENTER_TILE + 80, halfWidth: 1 } as const;@@ -938,10 +821,7 @@ function buildPlots(map: IslandMap): void {? TileKind.rock: id === "mine"? TileKind.quarry- : // The foundry's terrace is planed mountain, not village paving.- id === "foundry"- ? TileKind.scree- : TileKind.plaza;+ : TileKind.plaza;fillRect(map, px, pz, hw, hd, (i) => {if (map.kind[i] === TileKind.water) return;paintLand(map, i, kind, PLOT_LEVEL[id]);@@ -1015,17 +895,6 @@ function buildVillage(map: IslandMap): void {// The mine's branch: off the north spoke, west to the quarry, at the spoke's level there.const junction = map.level[tileIndex(map, MINE_ROAD.fromX + 1, MINE_ROAD.z)];gradeRoad(map, [MINE_ROAD.fromX, MINE_ROAD.z], [-1, 0], MINE_ROAD.length, junction);- // On up the mountain to the foundry: each leg starts at the level the last- // one reached, so the climb never breaks a walker's one-level step rule.- let climb = map.level[tileIndex(map, SUMMIT_ROAD[0].from[0] + 1, SUMMIT_ROAD[0].from[1])];- for (const leg of SUMMIT_ROAD) {- gradeRoad(map, leg.from, leg.dir, leg.length, climb);- const end: [number, number] = [- leg.from[0] + leg.dir[0] * leg.length,- leg.from[1] + leg.dir[1] * leg.length,- ];- if (inBounds(map, end[0], end[1])) climb = map.level[tileIndex(map, end[0], end[1])];- }// Buildings block walking; their tiles keep the plot level.for (const id of Object.keys(BUILDING_HALF) as PlaceId[]) {@@ -1076,17 +945,18 @@ function placeHouses(): HousePlot[] {for (let k = 0; k < slots; k++) {if (k % 4 === 0) continue; // N, E, S, W are gates (N also holds the hub)if (taken.has(k)) continue; // a kit building stands here- const [x, z] = ringSlotWorld(k);+ const angle = (k / slots) * Math.PI * 2; // clockwise from north+ const r = HOUSE_RING_TILES * TILE_M;+ const x = Math.sin(angle) * r;+ const z = -Math.cos(angle) * r;const seed = hash2(k, 7, ISLAND_SEED);- const rotation = houseDefaultRotation(x, z);houses.push({- slot: k,x,z,w: 3,d: 2,- rotation,- defaultRotation: rotation,+ // The door (local +z) faces the square: rotate so local +z points to the centre.+ rotation: Math.atan2(-x, -z),variant: variants[k % variants.length],seed,});@@ -1094,63 +964,25 @@ function placeHouses(): HousePlot[] {return houses;}-/**- * Clearance a walker keeps from a wall, in metres: the footprint is stamped- * this much wider so a figure's shoulder never clips a house corner.- */-export const WALL_MARGIN_M = 0.5;--/**- * Stamp `value` over every tile a rotated rectangle covers — `w` × `d` metres- * at (x, z), turned by `rotation` about y (three.js convention: local +z is- * the front), grown by `margin` on every side. Sampled every half metre so no- * tile inside the footprint is skipped.- */-export function stampFootprint(- layer: Uint8Array,- map: IslandMap,- x: number,- z: number,- w: number,- d: number,- rotation: number,- margin: number,- value: 0 | 1,-): void {- const hw = w / 2 + margin;- const hd = d / 2 + margin;- const cos = Math.cos(rotation);- const sin = Math.sin(rotation);- for (let lx = -hw; lx <= hw + 1e-9; lx += 0.5) {- for (let lz = -hd; lz <= hd + 1e-9; lz += 0.5) {- const wx = x + lx * cos + lz * sin;- const wz = z - lx * sin + lz * cos;- const [tx, tz] = worldToTile(wx, wz);- if (inBounds(map, tx, tz)) layer[tileIndex(map, tx, tz)] = value;- }- }-}--/** Block an axis-aligned rectangle given in world metres (x0..x1, z0..z1). */-function blockRectM(map: IslandMap, x0: number, z0: number, x1: number, z1: number): void {- const [tx0, tz0] = worldToTile(Math.min(x0, x1), Math.min(z0, z1));- const [tx1, tz1] = worldToTile(Math.max(x0, x1) - 1e-6, Math.max(z0, z1) - 1e-6);- for (let tz = tz0; tz <= tz1; tz++) {- for (let tx = tx0; tx <= tx1; tx++) {- if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 1;+/** Block the tiles under every house so walkers route around them. */+function blockHouses(map: IslandMap, houses: HousePlot[]): void {+ for (const h of houses) {+ // Rasterise the rotated footprint by sampling its four quadrants.+ const hw = (h.w * TILE_M) / 2;+ const hd = (h.d * TILE_M) / 2;+ const cos = Math.cos(h.rotation);+ const sin = Math.sin(h.rotation);+ for (let lx = -hw + 0.5; lx <= hw; lx += 1) {+ for (let lz = -hd + 0.5; lz <= hd; lz += 1) {+ const wx = h.x + lx * cos + lz * sin;+ const wz = h.z - lx * sin + lz * cos;+ const [tx, tz] = worldToTile(wx, wz);+ if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 1;+ }}}}-/** Block the single tile under a post (a lamp, a pillar, a mast) — never a dock plank. */-function blockPost(map: IslandMap, x: number, z: number): void {- const [tx, tz] = worldToTile(x, z);- if (!inBounds(map, tx, tz)) return;- const i = tileIndex(map, tx, tz);- if (map.kind[i] === TileKind.dock) return;- map.blocked[i] = 1;-}-/** The hedge ring with its four gates, and the lamps along ring and spokes. */function placeRingFurniture(map: IslandMap): { hedges: Post[]; lamps: Post[] } {const hedges: Post[] = [];@@ -1433,24 +1265,11 @@ function placeBoulders(map: IslandMap): Boulder[] {return boulders;}-/**- * How far in front of each kit building a visitor stands, in metres: in front- * of the docks' bays, at the foot of the foundry's conveyor ramp, at the- * others' doors.- */-export const KIT_STAND_AHEAD_M: Record<KitPlace, number> = {- plugins: 7.5,- foundry: 13.5,- skills: 7.5,- mcp: 7.0,- cli: 7.5,-};--/** A stand point in front of a kit building at `pose`, facing it. */-function kitPlace(id: KitPlace, pose: KitPose = kitPose(id)): Place {- const ahead = KIT_STAND_AHEAD_M[id];- const tile = worldToTile(pose.x + Math.sin(pose.rotation) * ahead, pose.z + Math.cos(pose.rotation) * ahead);- return { id, tile: PLACE_TILES[id], standTile: tile, facing: normalizeAngle(pose.rotation + Math.PI) };+/** A stand point `ahead` metres in front of a kit building, facing it. */+function kitPlace(id: KitPlace, ahead: number): Place {+ const p = kitPose(id);+ const tile = worldToTile(p.x + Math.sin(p.rotation) * ahead, p.z + Math.cos(p.rotation) * ahead);+ return { id, tile: PLACE_TILES[id], standTile: tile, facing: p.rotation + Math.PI };}function buildPlaces(map: IslandMap): Record<PlaceId, Place> {@@ -1474,12 +1293,13 @@ function buildPlaces(map: IslandMap): Record<PlaceId, Place> {solar: place("solar", [PLACE_TILES.solar[0] + 1, PLACE_TILES.solar[1] + 9], Math.PI),// On the mine's road at the edge of the forecourt, facing the portal (west).mine: place("mine", [PLACE_TILES.mine[0] + 7, PLACE_TILES.mine[1]], -Math.PI / 2),- // In front of the kit buildings (KIT_STAND_AHEAD_M), facing them.- plugins: kitPlace("plugins"),- foundry: kitPlace("foundry"),- skills: kitPlace("skills"),- mcp: kitPlace("mcp"),- cli: kitPlace("cli"),+ // In front of the docks' bays (7.5 m toward the square), facing the building.+ plugins: kitPlace("plugins", 7.5),+ // At the foot of the foundry's conveyor ramp, facing the portal.+ foundry: kitPlace("foundry", 13.5),+ skills: kitPlace("skills", 7.5),+ mcp: kitPlace("mcp", 7.0),+ cli: kitPlace("cli", 7.5),};// Make sure every stand tile is walkable — a place nobody can reach is a bug.for (const p of Object.values(places)) {@@ -1493,45 +1313,10 @@ function buildPlaces(map: IslandMap): Record<PlaceId, Place> {return places;}-/**- * Radius (metres) of the Quest Board's plinth and ring bench in the middle of- * the square, plus the walker's clearance: nobody walks through a bench.- */-export const SQUARE_CENTRE_BLOCK_M = 6.0;-/** The long table with its two benches on the square's south side, world metres. */-export const LONG_TABLE_RECT_M = { x0: -5.2, z0: 6.6, x1: 5.2, z1: 10.4 } as const;--/** The Quest Board with its ring bench and the long table block the middle of the square. */+/** The central tree and the round table block the middle of the square. */function blockSquareFurniture(map: IslandMap): void {const C = CENTER_TILE;- paintDisc(map, C, C, 0, SQUARE_CENTRE_BLOCK_M / TILE_M, (i) => (map.blocked[i] = 1));- const t = LONG_TABLE_RECT_M;- blockRectM(map, t.x0, t.z0, t.x1, t.z1);-}--/**- * What the landmark components put on the ground beside their blocked- * building footprints — the hub's wings, colonnade, planters, pool and flag- * masts, the harbor's kiosk and gate pillars, the lighthouse keeper's hut.- * The numbers are the components' own (Village.tsx `Hub`, Landmarks.tsx- * `Harbor` / `Lighthouse`), in each building's local metres.- */-function blockLandmarkFurniture(map: IslandMap): void {- const [hx, hz] = tileToWorld(...PLACE_TILES.hub);- // Wings, 7 × 8 m at ±15.5 m, one metre back.- for (const ox of [-15.5, 15.5]) blockRectM(map, hx + ox - 3.5, hz - 3, hx + ox + 3.5, hz + 5);- for (const px of [-10, -6, -2, 2, 6, 10]) blockPost(map, hx + px, hz + 7.4); // colonnade- for (const px of [-13, 13]) blockRectM(map, hx + px - 1.2, hz + 6.3, hx + px + 1.2, hz + 8.7); // planters- blockRectM(map, hx - 4.2, hz + 12.1, hx + 4.2, hz + 14.3); // the reflecting pool- for (const px of [-6.2, 6.2]) blockPost(map, hx + px, hz + 13.2); // flag masts-- const [bx, bz] = tileToWorld(...PLACE_TILES.harbor);- blockRectM(map, bx - 9, bz + 0.25, bx - 5, bz + 3.75); // harbor master's kiosk- for (const px of [-3, 3]) blockPost(map, bx + px, bz + 8); // gate pillars-- const [lx, lz] = tileToWorld(...PLACE_TILES.lighthouse);- const s = 1.3; // the lighthouse group's scale- blockRectM(map, lx + (-5 - 2) * s, lz + (3 - 1.7) * s, lx + (-5 + 2) * s, lz + (3 + 1.7) * s); // keeper's hut+ fillRect(map, C, C, 1, 1, (i) => (map.blocked[i] = 1)); // trunk}export interface Island {@@ -1550,12 +1335,12 @@ export function buildIsland(): Island {kind: new Uint8Array(size * size),level: new Uint8Array(size * size),blocked: new Uint8Array(size * size),- blockedStatic: new Uint8Array(0), // filled once everything stands};buildTerrain(map);buildPlots(map);buildVillage(map);const houses = placeHouses();+ blockHouses(map, houses);const kitPoses: Record<KitPlace, KitPose> = {plugins: kitPose("plugins"),foundry: kitPose("foundry"),@@ -1563,16 +1348,33 @@ export function buildIsland(): Island {mcp: kitPose("mcp"),cli: kitPose("cli"),};- // Houses, kit halls and the foundry's belt block walking at their resting- // headings for now, so trees and furniture keep clear of them; the final- // headings are stamped again by `applyBuildingYaws` below.- stampTurnables(map, map.blocked, houses, kitPoses, 1);+ // Every kit footprint blocks walking the way a house does.+ blockHouses(+ map,+ (Object.keys(kitPoses) as KitPlace[]).map((id) => ({+ ...kitPoses[id],+ ...KIT_FOOTPRINT_TILES[id],+ variant: "glass-loft" as HouseVariant,+ seed: 0,+ })),+ );+ // The foundry's conveyor deck is furniture, not floor: it keeps trees off+ // and keeps strollers beside it. A newborn rides it on fixed waypoints, so+ // the block costs the entrance nothing.+ const belt = kitPose("foundry");+ blockHouses(map, [+ {+ x: belt.x + Math.sin(belt.rotation) * FOUNDRY_RAMP_MID_M,+ z: belt.z + Math.cos(belt.rotation) * FOUNDRY_RAMP_MID_M,+ rotation: belt.rotation,+ w: 3,+ d: 3,+ variant: "glass-loft" as HouseVariant,+ seed: 0,+ },+ ]);blockSquareFurniture(map);- blockLandmarkFurniture(map);const { hedges, lamps } = placeRingFurniture(map);- // A hedge is a wall to a walker; a lamp post is a post.- for (const h of hedges) stampFootprint(map.blocked, map, h.x, h.z, HEDGE_SEGMENT_M[0], HEDGE_SEGMENT_M[1], h.rotation, 0.3, 1);- for (const l of lamps) blockPost(map, l.x, l.z);const { panels, greenhouses } = placeQuarterFurniture(map);const festoonPoles = placeFestoonPoles(map);const campfire = placeCampfire(map);@@ -1580,9 +1382,6 @@ export function buildIsland(): Island {const boulders = placeBoulders(map);const reeds = placeReeds(map);const places = buildPlaces(map);- // Everything that never turns: the turnable buildings lifted out again.- map.blockedStatic = map.blocked.slice();- stampTurnables(map, map.blockedStatic, houses, kitPoses, 0);cached = {map,content: {@@ -1600,7 +1399,6 @@ export function buildIsland(): Island {kitPoses,},};- applyBuildingYaws(cached, {});return cached;}@@ -1609,96 +1407,6 @@ export function resetIslandCache(): void {cached = null;}-// ----------------------------------------------------------------------------// Turning buildings — the viewer's own headings over the designed ones-// -----------------------------------------------------------------------------/** Stable id of a building a viewer may turn: a ring house by slot, a ring hub by place. */-export type BuildingId = `house:${number}` | `kit:${KitPlace}`;--export function houseId(slot: number): BuildingId {- return `house:${slot}`;-}--export function kitId(place: KitPlace): BuildingId {- return `kit:${place}`;-}--/** Centre of ring slot `slot` (0..15, clockwise from north), world metres. */-export function ringSlotWorld(slot: number, radiusTiles = HOUSE_RING_TILES): [number, number] {- const angle = (slot / 16) * Math.PI * 2;- const r = radiusTiles * TILE_M;- return [Math.sin(angle) * r, -Math.cos(angle) * r];-}--/** The heading a building rests at — what "reset" returns to. */-export function defaultBuildingYaw(id: BuildingId): number {- if (id.startsWith("kit:")) return kitPose(id.slice(4) as KitPlace).rotation;- const [x, z] = ringSlotWorld(Number(id.slice(6)));- return houseDefaultRotation(x, z);-}--/** Size of one hedge segment (along the ring × across), metres — `Village.tsx` draws it so. */-export const HEDGE_SEGMENT_M: readonly [number, number] = [2.3, 0.8];--/** Stamp the turnable buildings' footprints at their current headings into `layer`. */-function stampTurnables(- map: IslandMap,- layer: Uint8Array,- houses: HousePlot[],- kitPoses: Record<KitPlace, KitPose>,- value: 0 | 1,-): void {- for (const h of houses) {- stampFootprint(layer, map, h.x, h.z, h.w * TILE_M, h.d * TILE_M, h.rotation, WALL_MARGIN_M, value);- }- for (const id of Object.keys(kitPoses) as KitPlace[]) {- const p = kitPoses[id];- const f = KIT_FOOTPRINT_TILES[id];- stampFootprint(layer, map, p.x, p.z, f.w * TILE_M, f.d * TILE_M, p.rotation, WALL_MARGIN_M, value);- }- // The foundry's conveyor deck is furniture, not floor: it keeps trees off- // and keeps strollers beside it. A newborn rides it on fixed waypoints, so- // the block costs the entrance nothing.- const belt = kitPoses.foundry;- stampFootprint(- layer,- map,- belt.x + Math.sin(belt.rotation) * FOUNDRY_RAMP_MID_M,- belt.z + Math.cos(belt.rotation) * FOUNDRY_RAMP_MID_M,- 3 * TILE_M,- 3 * TILE_M,- belt.rotation,- WALL_MARGIN_M,- value,- );-}--/**- * Turn the buildings a viewer has turned: `yaws` maps a BuildingId to a- * heading (radians about y); anything absent rests at its default. Rewrites,- * in place, every number that depends on a heading — the house and kit poses,- * the blocked layer (from `blockedStatic`), the kit places' stand tiles and- * facings — so the renderer, the walkers and the pathfinder all see the same- * turned building. Pure over the island it is given; `buildingPoses.ts` is- * the only caller besides `buildIsland` itself.- */-export function applyBuildingYaws(island: Island, yaws: Readonly<Partial<Record<BuildingId, number>>>): void {- const { map, content } = island;- for (const h of content.houses) h.rotation = yaws[houseId(h.slot)] ?? h.defaultRotation;- for (const id of Object.keys(content.kitPoses) as KitPlace[]) {- content.kitPoses[id].rotation = yaws[kitId(id)] ?? kitPose(id).rotation;- content.places[id] = kitPlace(id, content.kitPoses[id]);- }- map.blocked.set(map.blockedStatic);- stampTurnables(map, map.blocked, content.houses, content.kitPoses, 1);- // A stand tile stays reachable whatever turned over it — a place nobody can reach is a bug.- for (const p of Object.values(content.places)) {- const [tx, tz] = p.standTile;- if (inBounds(map, tx, tz)) map.blocked[tileIndex(map, tx, tz)] = 0;- }-}-// ---------------------------------------------------------------------------// Pathfinding — A* over walkable tiles, eight neighbours, no corner cutting// ---------------------------------------------------------------------------@@ -1870,8 +1578,7 @@ function lineIsWalkable(map: IslandMap, a: [number, number], b: [number, number]export function randomPlazaTile(map: IslandMap, rng: () => number): [number, number] {for (let attempt = 0; attempt < 32; attempt++) {const angle = rng() * Math.PI * 2;- // From just outside the ring bench to just inside the garden beds.- const r = 4 + rng() * (PLAZA_RADIUS_TILES - 5);+ const r = 3 + rng() * (PLAZA_RADIUS_TILES - 4);const tx = Math.floor(CENTER_TILE + Math.cos(angle) * r);const tz = Math.floor(CENTER_TILE + Math.sin(angle) * r);if (isWalkable(map, tx, tz)) return [tx, tz];diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 53e9e8553b..b70a057642 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5197,6 +5197,8 @@"slot": {"hair": "Haare","headgear": "Kopfbedeckung",+ "collar": "Halsband",+ "tail_extra": "Schwanz","face_extra": "Gesicht","torso_over": "Überwurf","belt": "Gürtel",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a701a8cf8e..84a99e242a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5197,6 +5197,8 @@"slot": {"hair": "Hair","headgear": "Headgear",+ "collar": "Collar",+ "tail_extra": "Tail","face_extra": "Face","torso_over": "Over","belt": "Belt",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex c9f5db5414..5bb86af5c8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5197,6 +5197,8 @@"slot": {"hair": "Pelo","headgear": "Sombrero",+ "collar": "Collar",+ "tail_extra": "Cola","face_extra": "Cara","torso_over": "Capa superior","belt": "Cinturón",diff --git a/scripts/figures/build_figures.py b/scripts/figures/build_figures.pyindex 4ceddbfeae..3b19b02b42 100644--- a/scripts/figures/build_figures.py+++ b/scripts/figures/build_figures.py@@ -431,7 +431,7 @@ def skin_part_to_bone(part: bpy.types.Object, arm: bpy.types.Object, bone: str)# ----------------------------------------------------------------------------def finish_common(glb: gt.Glb) -> gt.Glb:+def finish_common(glb: gt.Glb, two_sided: bool = False) -> gt.Glb:doc = glb.docfor sampler in doc.get("samplers", []):sampler["magFilter"] = 9728@@ -444,7 +444,15 @@ def finish_common(glb: gt.Glb) -> gt.Glb:tex["sampler"] = 0for mat in doc.get("materials", []):mat["alphaMode"] = "OPAQUE"- mat.pop("doubleSided", None)+ # Single-sided is the default and the cheap one: a solid body has no+ # visible back faces. Flat cloth does — a cape is ONE open sheet of+ # 84 triangles with no inside, and culling its back faces makes the+ # half that faces the wearer, and every edge that reaches past the+ # body, vanish. Those parts say so and get both sides.+ if two_sided:+ mat["doubleSided"] = True+ else:+ mat.pop("doubleSided", None)for anim in doc.get("animations", []):keep_channels = []for ch in anim["channels"]:@@ -507,13 +515,15 @@ def finish_base(doc["asset"]["generator"] = "Personal Jarvis build_figures.py"gt.write_glb(glb_path, doc, glb.blob)log(- f"finished {glb_path.name}: {glb_path.stat().st_size // 1024} KB, {tris} tris, clips {sorted(clips)}"+ f"finished {glb_path.name}: {glb_path.stat().st_size // 1024} KB, "+ f"{tris} tris, clips {sorted(clips)}")return {"triangles": tris, "clips": sorted(clips), "height_m": extras["height_m"]}def finish_part(glb_path: Path, spec: dict, target: dict, source: dict, attach: str) -> dict:- glb = finish_common(gt.read_glb(glb_path))+ two_sided = bool(spec.get("two_sided"))+ glb = finish_common(gt.read_glb(glb_path), two_sided=two_sided)doc = glb.docdoc["animations"] = []glb = gt.prune_unused(glb)@@ -530,13 +540,14 @@ def finish_part(glb_path: Path, spec: dict, target: dict, source: dict, attach:"hides": spec.get("hides", []),"label": spec["label"],"styles": spec.get("styles", []),+ "two_sided": two_sided,"source": f"{source['name']} ({source['license']}) / {spec['object']}",}doc.setdefault("asset", {})["extras"] = {"jarvis_part": extras}doc["asset"]["generator"] = "Personal Jarvis build_figures.py"gt.write_glb(glb_path, doc, glb.blob)log(f"finished part {glb_path.name}: {glb_path.stat().st_size // 1024} KB, {tris} tris")- return {"triangles": tris}+ return {"triangles": tris, "two_sided": two_sided}_GATE = None@@ -575,6 +586,10 @@ def build_target(target: dict, out_dir: Path, ledger: Path) -> tuple[dict, list[part_specs = character.get("parts", [])if source.get("procedural") == "gigi":return build_procedural_gigi(target, source, archetype, out_dir)+ if source.get("procedural") == "humanoid":+ return build_procedural_humanoid(target, source, archetype, out_dir)+ if source.get("procedural") == "quadruped":+ return build_procedural_quadruped(target, source, archetype, out_dir)src_file = fetch_source_file(source, f"{target['character']}.glb")log(f"building {target['id']} from {src_file.name}")@@ -634,7 +649,9 @@ def build_target(target: dict, out_dir: Path, ledger: Path) -> tuple[dict, list[report = reuv_to_palette(part,{},- {"*": character["cell_map"].get("*", {})},+ # The part's own map wins: an accessory can share an atlas cell+ # with something on the body that means a different thing on it.+ {"*": {**character["cell_map"].get("*", {}), **spec.get("cell_map", {})}},source["atlas_grid"],fallback=source.get("part_cell_map", {}),)@@ -662,6 +679,94 @@ def build_target(target: dict, out_dir: Path, ledger: Path) -> tuple[dict, list[return base_entry, part_entries+def build_procedural_quadruped(+ target: dict, source: dict, archetype: dict, out_dir: Path+) -> tuple[dict, list[dict]]:+ """An animal: rig, body and clips all written by ``quadruped_builder.py``.++ There is no CC0 donor of this archetype, so unlike the humanoids nothing+ is borrowed — the 21-bone skeleton and all seven clips are keyed here.+ """+ import quadruped_builder # noqa: PLC0415 — Blender-only module beside this file++ log(f"building {target['id']} procedurally")+ reset_scene()+ bpy.context.scene.render.fps = quadruped_builder.FPS+ character = source["characters"][target["character"]]+ sheet_path = CACHE / f"{target['id']}-sheet.png"+ write_sheet(sheet_path, character["default_palette"])+ img = load_sheet(sheet_path)+ arm, body, uv_report = quadruped_builder.build_quadruped(+ character["shape"], CONTRACT["sheet"], img, sheet_material+ )+ apply_materials(body, img, target["id"], uv_report["hair_faces"])+ for name, spec in archetype["clips"].items():+ action = bpy.data.actions.get(name)+ if action is not None:+ normalize_clip(action, spec["loop"])+ fwd = add_forward_marker(arm)++ out_dir.mkdir(parents=True, exist_ok=True)+ base_path = out_dir / f"{target['id']}.glb"+ export_glb(base_path, [body, arm, fwd], animations=True)+ facts = finish_base(base_path, target, source, archetype, uv_report)+ entry = {+ "id": f"{target['archetype']}/{target['base']}",+ "file": base_path.name,+ "archetype": target["archetype"],+ "variant": target["variant"],+ "base": target["base"],+ "label": target["label"],+ "styles": target.get("styles", []),+ "heightM": archetype["variants"][target["variant"]]["height_m"],+ "palette": character["default_palette"],+ "source": f"{source['name']} / {target['character']}",+ "license": source["license"],+ "note": (+ f"rig, body and clips written by quadruped_builder.py "+ f"(shape `{character['shape']}`); no external source"+ ),+ **facts,+ }++ for action in list(bpy.data.actions):+ bpy.data.actions.remove(action)+ part_entries = []+ parts_dir = out_dir / "parts" / target["archetype"]+ for part_id in character.get("parts", []):+ spec = dict(quadruped_builder.PART_SPECS[part_id])+ spec["id"] = part_id+ spec["object"] = part_id+ attach = archetype["slots"][spec["slot"]]["attach"]+ part, report = quadruped_builder.build_part(+ part_id, arm, CONTRACT["sheet"], img, sheet_material+ )+ apply_materials(part, img, part_id, [])+ parts_dir.mkdir(parents=True, exist_ok=True)+ part_path = parts_dir / f"{part_id}.glb"+ export_glb(part_path, [part, arm], animations=False)+ pfacts = finish_part(part_path, spec, target, source, attach)+ bpy.data.objects.remove(part, do_unlink=True)+ part_entries.append(+ {+ "id": part_id,+ "file": f"parts/{target['archetype']}/{part_path.name}",+ "archetype": target["archetype"],+ "slot": spec["slot"],+ "attach": attach,+ "label": spec["label"],+ "styles": spec.get("styles", []),+ "hides": spec.get("hides", []),+ "from_base": target["base"],+ "source": f"{source['name']} / {part_id}",+ "license": source["license"],+ "palette_cells": report["used"],+ **pfacts,+ }+ )+ return entry, part_entries++def build_procedural_gigi(target: dict, source: dict, archetype: dict, out_dir: Path) -> tuple[dict, list[dict]]:@@ -698,6 +803,107 @@ def build_procedural_gigi(return entry, []+def build_procedural_humanoid(+ target: dict, source: dict, archetype: dict, out_dir: Path+) -> tuple[dict, list[dict]]:+ """A body modelled by ``humanoid_builder.py`` on the CC0 donor's rig and clips.++ The donor gives the skeleton and the nine clips and nothing else: every+ mesh it shipped is deleted before the new body is built, so what ships is+ our geometry on a CC0 rig — the arrangement §12 of the pipeline settled.+ """+ import humanoid_builder # noqa: PLC0415 — Blender-only module beside this file++ rig = load_source(source["rig_source"])+ character = source["characters"][target["character"]]+ rig_file = fetch_source_file(rig, f"{source['rig_character']}.glb")+ log(f"building {target['id']} procedurally on the {source['rig_character']} rig")++ reset_scene()+ import_glb(rig_file, int(rig.get("fps", 30)))+ arm = find_armature()+ keep_objects(arm, set()) # the donor's own meshes go; the rig and clips stay+ dropped = drop_bones(arm, rig["drop_bone_patterns"])+ log(f"dropped {len(dropped)} control bones")+ rename_bones(arm, rig["bone_map"], archetype["bones"])+ kept = filter_clips(rig["clip_map"], archetype["clips"])+ for name, action in kept.items():+ normalize_clip(action, archetype["clips"][name]["loop"])++ sheet_path = CACHE / f"{target['id']}-sheet.png"+ write_sheet(sheet_path, character["default_palette"])+ img = load_sheet(sheet_path)+ body, uv_report = humanoid_builder.build_humanoid(+ character["profile"], arm, CONTRACT["sheet"], img, sheet_material+ )+ apply_materials(body, img, target["id"], uv_report["hair_faces"])+ fwd = add_forward_marker(arm)++ out_dir.mkdir(parents=True, exist_ok=True)+ base_path = out_dir / f"{target['id']}.glb"+ export_glb(base_path, [body, arm, fwd], animations=True)+ facts = finish_base(base_path, target, source, archetype, uv_report)+ entry = {+ "id": f"{target['archetype']}/{target['base']}",+ "file": base_path.name,+ "archetype": target["archetype"],+ "variant": target["variant"],+ "base": target["base"],+ "label": target["label"],+ "styles": target.get("styles", []),+ "heightM": archetype["variants"][target["variant"]]["height_m"],+ "palette": character["default_palette"],+ "source": f"{source['name']} / {target['character']}",+ "license": source["license"],+ "note": (+ f"body modelled by humanoid_builder.py (profile `{character['profile']}`); "+ f"rig and clips from {rig['name']} ({rig['license']}) / {source['rig_character']}, "+ "every donor mesh deleted"+ ),+ **facts,+ }++ # Accessories, modelled the same way and hung on bones every biped shares,+ # so one file fits every base of its style. Declared on ONE character so+ # the four bodies do not each rebuild the same four files.+ for action in list(bpy.data.actions):+ bpy.data.actions.remove(action)+ part_entries = []+ parts_dir = out_dir / "parts" / target["archetype"]+ for part_id in character.get("parts", []):+ spec = dict(humanoid_builder.PART_SPECS[part_id])+ spec["id"] = part_id+ spec["object"] = part_id+ attach = archetype["slots"][spec["slot"]]["attach"]+ part, report = humanoid_builder.build_part(+ part_id, arm, CONTRACT["sheet"], img, sheet_material+ )+ apply_materials(part, img, part_id, [])+ parts_dir.mkdir(parents=True, exist_ok=True)+ part_path = parts_dir / f"{part_id}.glb"+ export_glb(part_path, [part, arm], animations=False)+ pfacts = finish_part(part_path, spec, target, source, attach)+ bpy.data.objects.remove(part, do_unlink=True)+ part_entries.append(+ {+ "id": part_id,+ "file": f"parts/{target['archetype']}/{part_path.name}",+ "archetype": target["archetype"],+ "slot": spec["slot"],+ "attach": attach,+ "label": spec["label"],+ "styles": spec.get("styles", []),+ "hides": spec.get("hides", []),+ "from_base": target["base"],+ "source": f"{source['name']} / {part_id}",+ "license": source["license"],+ "palette_cells": report["used"],+ **pfacts,+ }+ )+ return entry, part_entries++def write_ledger(path: Path, bases: list[dict], parts: list[dict], sources: dict[str, dict]) -> None:@@ -713,21 +919,26 @@ def write_ledger("| File | Source | License | What the build changed |","|---|---|---|---|",]+ imported_note = (+ "body meshes joined; IK/control bones dropped; 23 deform bones renamed; clips "+ "kept/renamed, root XZ zeroed, loops closed; faces re-UV'd onto the palette strip; "+ "hair as its own primitive; FWD marker; extras"+ )for b in bases:lines.append(- f"| `{b['file']}` | {b['source']} | {b['license']} | body meshes joined; IK/control bones "- f"dropped; 23 deform bones renamed; clips kept/renamed, root XZ zeroed, loops closed; "- f"faces re-UV'd onto the palette strip; hair as its own primitive; FWD marker; extras |"+ f"| `{b['file']}` | {b['source']} | {b['license']} | {b.get('note') or imported_note} |")for p in parts:lines.append(- f"| `{p['file'].split('/')[-1]}` | {p['source']} | {p['license']} | unparented at rest, "- f"skinned to `{p['attach']}` with weight 1; re-UV'd onto the palette strip; no clips; extras |"+ f"| `{p['file'].split('/')[-1]}` | {p['source']} | {p['license']} | unparented at "+ f"rest, skinned to `{p['attach']}` with weight 1; re-UV'd onto the palette strip; "+ "no clips; extras |")lines.append("")- for name, src in sources.items():+ for src in sources.values():lines.append(- f"- **{src['name']}** — {src['author']}, {src['license']} ({src['license_url']}); files:"+ f"- **{src['name']}** — {src['author']}, {src['license']} "+ f"({src['license_url']}); files:")for fname, sha in src["files"].items():lines.append(f" - `{fname}` sha256 `{sha}`")diff --git a/scripts/figures/contract.json b/scripts/figures/contract.jsonindex ecd089f2f7..60ef0dd53e 100644--- a/scripts/figures/contract.json+++ b/scripts/figures/contract.json@@ -389,7 +389,6 @@"character": "Rogue","label": "Ranger","styles": [- "modern","fantasy"]},@@ -429,6 +428,66 @@"fantasy"]},+ {+ "id": "biped-office",+ "archetype": "biped",+ "variant": "medium",+ "base": "office",+ "source": "jarvis-humanoids",+ "character": "Office",+ "label": "Office",+ "styles": [+ "modern"+ ]+ },+ {+ "id": "biped-casual",+ "archetype": "biped",+ "variant": "medium",+ "base": "casual",+ "source": "jarvis-humanoids",+ "character": "Casual",+ "label": "Casual",+ "styles": [+ "modern"+ ]+ },+ {+ "id": "biped-chibi",+ "archetype": "biped",+ "variant": "medium",+ "base": "chibi",+ "source": "jarvis-humanoids",+ "character": "Chibi",+ "label": "Chibi",+ "styles": [+ "cartoon"+ ]+ },+ {+ "id": "biped-android",+ "archetype": "biped",+ "variant": "medium",+ "base": "android",+ "source": "jarvis-humanoids",+ "character": "Android",+ "label": "Android",+ "styles": [+ "scifi"+ ]+ },+ {+ "id": "quadruped-fox",+ "archetype": "quadruped",+ "variant": "default",+ "base": "fox",+ "source": "jarvis-animals",+ "character": "Fox",+ "label": "Fox",+ "styles": [+ "animal"+ ]+ },{"id": "spirit-gigi","archetype": "spirit",diff --git a/scripts/figures/humanoid_builder.py b/scripts/figures/humanoid_builder.pynew file mode 100644index 0000000000..8d8a2cf036--- /dev/null+++ b/scripts/figures/humanoid_builder.py@@ -0,0 +1,818 @@+"""Blocky bipeds modelled by script onto the contract's 23-bone rig.++Route B of the character pipeline (character-pipeline.md §8.2), for the styles+the CC0 adventurer pack has no body for: an office worker and a casual person+(``modern``), a big-headed chibi (``cartoon``) and an android (``scifi``).++Why boxes: the island renders through a pixel pass at ~240 px wide, so what+reads at that size is silhouette and colour, not topology. Every piece is one+axis-aligned box, rigidly weighted to exactly ONE bone — no skinning weights+to author, no joint that pinches, and 12 triangles a piece against a 4 500+budget. The rig and its nine clips come from the same CC0 donor the fantasy+bases use, so a new body walks, sits, sleeps and waves on day one.++Proportions are the rig's, not ours: a box spans the rest positions of the+bone it hangs on, so a knee meets a shin whatever the profile does with+widths. Only the head — a free-floating box on the ``head`` bone — changes+size between profiles, which is exactly what separates a person from a chibi.++Coordinates are Blender's: Z up, the figure faces −Y, +X is its left.+"""++from __future__ import annotations++from dataclasses import dataclass, field++import bmesh # type: ignore[import-not-found]+import bpy # type: ignore[import-not-found]+from mathutils import Vector # type: ignore[import-not-found]++# Rest-pose landmarks of the normalized rig, in Blender units. Read off the+# donor once (`scripts/figures/README.md`); asserted against the live armature+# at build time so a donor change fails loudly instead of deforming quietly.+GROUND = 0.0+HIP_Z = 0.4057+WAIST_Z = 0.5976+CHEST_Z = 0.9726+NECK_Z = 1.2235+HEAD_Z = 1.2414+ARM_Z = 1.1068++#: Every profile's crown sits here, and every head is the same width.+#:+#: A headgear part is ONE file worn by any base of its style: a cap modelled+#: for a crown at 2.15 slides off a head that ends at 1.94 and sinks into one+#: that ends at 2.30. So the head hangs DOWNWARD from a fixed crown and only+#: its height varies — which is what tells a chibi from an android anyway,+#: since a taller head simply swallows the neck. The KayKit bodies crown at+#: 2.17 with a wider skull, so their hats stay tagged `fantasy` and these+#: caps stay tagged to the styles built around this skull.+HEAD_TOP = 2.15+HEAD_W = 0.42+HEAD_D = 0.40+SHOULDER_X = 0.212+ELBOW_X = 0.4535+WRIST_X = 0.7132+HAND_X = 0.787+FINGER_X = 0.899+LEG_X = 0.1709+KNEE_Z = 0.2923+ANKLE_Z = 0.1452+TOE_Y = -0.0964+TOE_TIP_Y = -0.262++LANDMARKS = {+ "hips": HIP_Z,+ "spine": WAIST_Z,+ "chest": CHEST_Z,+ "head": HEAD_Z,+ "upper_arm_l": ARM_Z,+ "upper_leg_l": 0.5193,+ "lower_leg_l": KNEE_Z,+ "foot_l": ANKLE_Z,+}+++@dataclass(frozen=True)+class Profile:+ """Everything one look decides. The rig decides the rest."""++ #: How far the head reaches DOWN from `HEAD_TOP`; the width is shared.+ head_h: float = 0.78+ eye_w: float = 0.08+ eye_h: float = 0.16+ #: Palette cell of the skull; a robot's head is metal, a person's is skin.+ head_cell: str = "skin"+ #: Cell of the torso, the legs and the shoes.+ torso_cell: str = "primary"+ leg_cell: str = "secondary"+ shoe_cell: str = "shoes"+ sleeve_cell: str = "primary"+ #: Forearms and hands: bare skin on a person, chassis on an android.+ limb_cell: str = "skin"+ belt_cell: str = "leather"+ #: Widths, as half-extents.+ torso_w: float = 0.30+ torso_d: float = 0.20+ arm_r: float = 0.105+ leg_r: float = 0.125+ # features+ hair: bool = True+ hair_long: bool = False+ hood: bool = False+ tie: bool = False+ visor: bool = False+ antenna: bool = False+ pocket: bool = False+ #: Cells that belong to the hidable hair primitive.+ hair_cells: tuple[str, ...] = field(default=("hair",))+++PROFILES: dict[str, Profile] = {+ # An everyday person in a shirt: the plain silhouette every other look+ # departs from, and the one the "modern" style was missing entirely.+ "office": Profile(tie=True, sleeve_cell="primary", leg_cell="secondary"),+ # Same body, softer clothes: a hood behind the head reads at 20 px where a+ # drawstring does not.+ "casual": Profile(+ head_h=0.80,+ hair_long=True,+ hood=True,+ pocket=True,+ sleeve_cell="primary",+ leg_cell="secondary",+ ),+ # Kart-racer proportions: the head is nearly half the figure, the eyes are+ # a third of the face, and the body is a stub under it.+ "chibi": Profile(+ head_h=1.06,+ eye_w=0.13,+ eye_h=0.24,+ torso_w=0.27,+ arm_r=0.115,+ leg_r=0.135,+ hair=True,+ ),+ # No skin, no hair: a metal shell with a lit visor and a panelled chest.+ "android": Profile(+ head_h=0.70,+ head_cell="metal",+ torso_cell="metal",+ leg_cell="metal",+ sleeve_cell="metal",+ limb_cell="metal",+ belt_cell="primary",+ shoe_cell="primary_shade",+ hair=False,+ visor=True,+ antenna=True,+ ),+}+++# ---------------------------------------------------------------------------+# geometry+# ---------------------------------------------------------------------------+++@dataclass+class Piece:+ """One box: where it sits, which bone carries it, which colour it takes."""++ name: str+ bone: str+ cell: str+ lo: tuple[float, float, float]+ hi: tuple[float, float, float]+++def box(+ name: str,+ bone: str,+ cell: str,+ x: tuple[float, float],+ y: tuple[float, float],+ z: tuple[float, float],+) -> Piece:+ return Piece(name, bone, cell, (x[0], y[0], z[0]), (x[1], y[1], z[1]))+++def mirrored(piece: Piece) -> Piece:+ """The same box on the other side: X negated, the bone's side swapped.++ The side lives in the LAST character of both names — a plain+ ``replace("_l", "_r")`` turns ``upper_leg_l`` into ``upper_reg_r``, and a+ vertex group named after a bone that does not exist weighs its vertices to+ nothing. The glTF exporter then invents a ``neutral_bone`` for them and the+ contract gate rejects the file, which is how this was caught.+ """+ if not piece.bone.endswith("_l") or not piece.name.endswith("L"):+ raise SystemExit(f"mirrored() wants a left-side piece, got {piece.name}/{piece.bone}")+ return Piece(+ piece.name[:-1] + "R",+ piece.bone[:-1] + "r",+ piece.cell,+ (-piece.hi[0], piece.lo[1], piece.lo[2]),+ (-piece.lo[0], piece.hi[1], piece.hi[2]),+ )+++def _mesh_from_box(piece: Piece) -> bpy.types.Object:+ bm = bmesh.new()+ bmesh.ops.create_cube(bm, size=1.0)+ size = Vector(tuple(hi - lo for hi, lo in zip(piece.hi, piece.lo, strict=True)))+ centre = Vector(tuple((hi + lo) / 2 for hi, lo in zip(piece.hi, piece.lo, strict=True)))+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)+ bmesh.ops.translate(bm, vec=centre, verts=bm.verts)+ mesh = bpy.data.meshes.new(piece.name)+ bm.to_mesh(mesh)+ bm.free()+ obj = bpy.data.objects.new(piece.name, mesh)+ bpy.context.scene.collection.objects.link(obj)+ return obj+++# ---------------------------------------------------------------------------+# the body, piece by piece+# ---------------------------------------------------------------------------+++def head_pieces(p: Profile) -> list[Piece]:+ """Skull, face and hair — everything the `head` bone carries."""+ top = HEAD_TOP+ chin = HEAD_TOP - p.head_h+ w, d = HEAD_W, HEAD_D+ face = -d - 0.005 # a hair's breadth in front of the skull, never inside it+ eye_z = chin + p.head_h * 0.52+ pieces = [+ box("Head", "head", p.head_cell, (-w, w), (-d, d), (chin, top)),+ # The neck reaches from the collar up to the chin, however far that is:+ # a tall chibi head swallows it, a short android head leaves it showing.+ box(+ "Neck",+ "head",+ p.head_cell,+ (-0.13, 0.13),+ (-0.12, 0.12),+ (NECK_Z - 0.05, chin + 0.06),+ ),+ ]+ if p.visor:+ # One lit band instead of eyes: an android reads as a machine from the+ # silhouette down to 20 px, which two dots never manage.+ pieces.append(+ box(+ "Visor",+ "head",+ "emissive",+ (-w * 0.9, w * 0.9),+ (face - 0.03, -d + 0.02),+ (eye_z - 0.09, eye_z + 0.09),+ )+ )+ pieces.append(+ box(+ "VisorRim",+ "head",+ "accent",+ (-w * 0.95, w * 0.95),+ (face - 0.02, -d + 0.02),+ (eye_z + 0.09, eye_z + 0.13),+ )+ )+ else:+ for side, sign in (("L", 1.0), ("R", -1.0)):+ inner = sign * 0.09+ outer = sign * (0.09 + p.eye_w)+ xs = (min(inner, outer), max(inner, outer))+ pieces.append(+ box(+ f"Eye{side}",+ "head",+ "eye_white",+ xs,+ (face - 0.02, -d + 0.02),+ (eye_z, eye_z + p.eye_h),+ )+ )+ px = (xs[0] + 0.015, xs[1] - 0.015)+ pieces.append(+ box(+ f"Pupil{side}",+ "head",+ "eyes",+ px,+ (face - 0.035, face - 0.005),+ (eye_z + p.eye_h * 0.18, eye_z + p.eye_h * 0.78),+ )+ )+ pieces.append(+ box(+ "Nose",+ "head",+ "skin_shade",+ (-0.045, 0.045),+ (face - 0.04, -d + 0.02),+ (eye_z - 0.12, eye_z - 0.02),+ )+ )+ pieces.append(+ box(+ "Mouth",+ "head",+ "skin_shade",+ (-0.09, 0.09),+ (face - 0.02, -d + 0.02),+ (eye_z - 0.26, eye_z - 0.21),+ )+ )+ if p.antenna:+ pieces.append(+ box("Antenna", "head", "metal", (-0.025, 0.025), (-0.025, 0.025), (top, top + 0.16))+ )+ pieces.append(+ box(+ "AntennaTip",+ "head",+ "emissive",+ (-0.05, 0.05),+ (-0.05, 0.05),+ (top + 0.16, top + 0.24),+ )+ )+ if p.hair:+ cap = w + 0.02+ pieces.append(+ box(+ "HairCap",+ "head",+ "hair",+ (-cap, cap),+ (-d - 0.02, d + 0.02),+ (top - 0.14, top + 0.03),+ )+ )+ pieces.append(+ box("HairBack", "head", "hair", (-cap, cap), (d - 0.04, d + 0.03), (chin + 0.16, top))+ )+ if p.hair_long:+ pieces.append(+ box(+ "HairSideL",+ "head",+ "hair",+ (w - 0.02, cap),+ (-d * 0.4, d + 0.03),+ (chin + 0.05, top),+ )+ )+ pieces.append(+ box(+ "HairSideR",+ "head",+ "hair",+ (-cap, -w + 0.02),+ (-d * 0.4, d + 0.03),+ (chin + 0.05, top),+ )+ )+ if p.hood:+ # The hood rides the chest, not the head: it stays put when the head turns.+ pieces.append(+ box(+ "Hood",+ "chest",+ "primary_shade",+ (-w - 0.04, w + 0.04),+ (d - 0.01, d + 0.10),+ (chin - 0.04, chin + p.head_h * 0.62),+ )+ )+ return pieces+++def torso_pieces(p: Profile) -> list[Piece]:+ w, d = p.torso_w, p.torso_d+ pieces = [+ box("Chest", "chest", p.torso_cell, (-w, w), (-d, d), (CHEST_Z - 0.02, NECK_Z + 0.03)),+ box(+ "Waist",+ "spine",+ p.torso_cell,+ (-w + 0.02, w - 0.02),+ (-d + 0.01, d - 0.01),+ (WAIST_Z + 0.02, CHEST_Z + 0.01),+ ),+ box("Belt", "hips", p.belt_cell, (-w, w), (-d, d), (WAIST_Z - 0.05, WAIST_Z + 0.04)),+ box(+ "Pelvis",+ "hips",+ p.leg_cell,+ (-w + 0.01, w - 0.01),+ (-d + 0.01, d - 0.01),+ (HIP_Z - 0.02, WAIST_Z - 0.03),+ ),+ ]+ if p.tie:+ pieces.append(+ box(+ "Collar",+ "chest",+ "secondary",+ (-0.19, 0.19),+ (-d - 0.02, -d + 0.05),+ (NECK_Z - 0.10, NECK_Z + 0.03),+ )+ )+ pieces.append(+ box(+ "Tie",+ "chest",+ "accent",+ (-0.05, 0.05),+ (-d - 0.025, -d + 0.02),+ (CHEST_Z - 0.02, NECK_Z - 0.08),+ )+ )+ if p.pocket:+ pieces.append(+ box(+ "Pocket",+ "spine",+ "primary_shade",+ (-0.16, 0.16),+ (-d - 0.02, -d + 0.03),+ (WAIST_Z + 0.06, WAIST_Z + 0.20),+ )+ )+ if p.visor:+ pieces.append(+ box(+ "CoreLight",+ "chest",+ "emissive",+ (-0.07, 0.07),+ (-d - 0.02, -d + 0.02),+ (CHEST_Z + 0.10, CHEST_Z + 0.24),+ )+ )+ pieces.append(+ box(+ "PanelL",+ "chest",+ "primary",+ (0.12, w - 0.01),+ (-d - 0.01, -d + 0.03),+ (CHEST_Z + 0.02, NECK_Z - 0.02),+ )+ )+ pieces.append(+ box(+ "PanelR",+ "chest",+ "primary",+ (-w + 0.01, -0.12),+ (-d - 0.01, -d + 0.03),+ (CHEST_Z + 0.02, NECK_Z - 0.02),+ )+ )+ return pieces+++def limb_pieces(p: Profile) -> list[Piece]:+ """One side's arm and leg; the other side is the mirror of these."""+ r = p.arm_r+ lr = p.leg_r+ left = [+ box(+ "UpperArmL",+ "upper_arm_l",+ p.sleeve_cell,+ (SHOULDER_X - 0.02, ELBOW_X),+ (-r, r),+ (ARM_Z - r, ARM_Z + r),+ ),+ box(+ "LowerArmL",+ "lower_arm_l",+ p.limb_cell,+ (ELBOW_X, WRIST_X),+ (-r + 0.01, r - 0.01),+ (ARM_Z - r + 0.01, ARM_Z + r - 0.01),+ ),+ box(+ "HandL",+ "hand_l",+ p.limb_cell,+ (HAND_X - 0.02, FINGER_X),+ (-r, r),+ (ARM_Z - r, ARM_Z + r),+ ),+ box(+ "UpperLegL",+ "upper_leg_l",+ p.leg_cell,+ (LEG_X - lr, LEG_X + lr),+ (-lr - 0.02, lr + 0.01),+ (KNEE_Z - 0.01, 0.5193 + 0.02),+ ),+ box(+ "LowerLegL",+ "lower_leg_l",+ p.leg_cell,+ (LEG_X - lr + 0.01, LEG_X + lr - 0.01),+ (-lr, lr),+ (ANKLE_Z - 0.01, KNEE_Z + 0.01),+ ),+ box(+ "FootL",+ "foot_l",+ p.shoe_cell,+ (LEG_X - lr, LEG_X + lr),+ (TOE_Y, lr + 0.01),+ (GROUND, ANKLE_Z + 0.02),+ ),+ box(+ "ToeL",+ "toes_l",+ p.shoe_cell,+ (LEG_X - lr, LEG_X + lr),+ (TOE_TIP_Y, TOE_Y + 0.01),+ (GROUND, ANKLE_Z - 0.05),+ ),+ ]+ return left + [mirrored(piece) for piece in left]+++def body_pieces(profile: Profile) -> list[Piece]:+ return head_pieces(profile) + torso_pieces(profile) + limb_pieces(profile)+++# ---------------------------------------------------------------------------+# assembly+# ---------------------------------------------------------------------------+++def verify_rig(arm: bpy.types.Object) -> None:+ """The boxes are placed against the donor's rest pose; prove it is that pose."""+ problems = []+ for bone, z in LANDMARKS.items():+ found = arm.data.bones.get(bone)+ if found is None:+ problems.append(f"bone {bone!r} missing")+ elif abs(found.head_local.z - z) > 0.02:+ problems.append(f"{bone}: rest z {found.head_local.z:.4f} != expected {z:.4f}")+ if problems:+ raise SystemExit(+ "humanoid_builder: the donor rig moved — the box layout is measured "+ "against it and would deform: " + "; ".join(problems)+ )+++def build_humanoid(+ profile_name: str, arm: bpy.types.Object, sheet: dict, img, sheet_material+) -> tuple[bpy.types.Object, dict]:+ """Build one body onto `arm` and return it joined, UV'd and rigged."""+ profile = PROFILES.get(profile_name)+ if profile is None:+ raise SystemExit(f"unknown humanoid profile {profile_name!r}")+ verify_rig(arm)++ pieces = body_pieces(profile)+ # A vertex group named after a bone that does not exist weighs its box to+ # nothing, and the exporter quietly parks those vertices on an invented+ # `neutral_bone`. Catch the typo here, where the message can name it.+ bones = {b.name for b in arm.data.bones}+ stray = sorted({p.bone for p in pieces} - bones)+ if stray:+ raise SystemExit(f"humanoid_builder: pieces bound to bones the rig has not: {stray}")++ cells = sheet["cells"]+ cv = 1.0 - (sheet["cell_height"] / 2) / sheet["size"]+ objects: list[bpy.types.Object] = []+ hair_flags: list[bool] = []+ used: dict[str, int] = {}+ for piece in pieces:+ obj = _mesh_from_box(piece)+ mesh = obj.data+ mesh.uv_layers.new(name="UVMap")+ uv = mesh.uv_layers.active+ cu = (cells.index(piece.cell) + 0.5) / len(cells)+ for poly in mesh.polygons:+ for li in poly.loop_indices:+ uv.data[li].uv = (cu, cv)+ used[piece.cell] = used.get(piece.cell, 0) + len(mesh.polygons)+ group = obj.vertex_groups.new(name=piece.bone)+ group.add([v.index for v in mesh.vertices], 1.0, "REPLACE")+ objects.append(obj)+ hair_flags.append(piece.cell in profile.hair_cells)++ # One material slot for now; `apply_materials` re-slots the hair faces+ # afterwards, exactly as it does for an imported body.+ for obj in objects:+ obj.data.materials.append(sheet_material("tmp-sheet", img))+ for obj in bpy.data.objects:+ obj.select_set(False)+ for obj in objects:+ obj.select_set(True)+ bpy.context.view_layer.objects.active = objects[0]+ faces_per_object = [len(obj.data.polygons) for obj in objects]+ bpy.ops.object.join()+ body = bpy.context.view_layer.objects.active+ body.name = "Body"+ body.data.name = "Body"+ while len(body.data.materials) > 1:+ body.data.materials.pop(index=len(body.data.materials) - 1)++ # `join` appends meshes in selection order with the active object FIRST,+ # so face indices are the active object's, then the rest in list order.+ order = [0] + [i for i in range(1, len(objects))]+ hair_faces: list[int] = []+ cursor = 0+ for i in order:+ count = faces_per_object[i]+ if hair_flags[i]:+ hair_faces.extend(range(cursor, cursor + count))+ cursor += count++ body.parent = arm+ body.matrix_parent_inverse.identity()+ modifier = body.modifiers.new("Armature", "ARMATURE")+ modifier.object = arm+ return body, {"used": used, "unmapped": {}, "hair_faces": hair_faces}+++# ---------------------------------------------------------------------------+# parts+# ---------------------------------------------------------------------------++#: Handslot rest positions, from the same donor dump as the landmarks above.+HANDSLOT_L = (0.8831, 0.0, 1.0493)+HANDSLOT_R = (-0.8831, 0.0, 1.0493)++#: Parts modelled here, keyed by the catalog id the creator offers.+#:+#: Every one of these hangs on `chest` or a handslot — bones the donor rig+#: places identically for every biped it produces — so one file fits every+#: base of every style. `headgear-cap` is the exception that proves it: it is+#: cut for the crown and width THIS module builds (HEAD_TOP/HEAD_W), so it is+#: tagged only to the styles built on that skull, never to the wider KayKit+#: heads the fantasy hats were cut for.+PART_SPECS: dict[str, dict] = {+ "back-backpack": {+ "slot": "back",+ "label": "Backpack",+ "styles": ["modern", "cartoon", "scifi"],+ "pieces": lambda: [+ box("Pack", "chest", "leather", (-0.24, 0.24), (0.20, 0.42), (CHEST_Z - 0.06, NECK_Z)),+ box(+ "PackLid",+ "chest",+ "secondary",+ (-0.25, 0.25),+ (0.19, 0.43),+ (NECK_Z - 0.14, NECK_Z - 0.02),+ ),+ box(+ "StrapL",+ "chest",+ "leather",+ (0.10, 0.19),+ (-0.23, 0.21),+ (NECK_Z - 0.06, NECK_Z + 0.01),+ ),+ box(+ "StrapR",+ "chest",+ "leather",+ (-0.19, -0.10),+ (-0.23, 0.21),+ (NECK_Z - 0.06, NECK_Z + 0.01),+ ),+ ],+ },+ # Placed like the pack's own spellbook: hanging FROM the slot and reaching+ # forward, not standing on top of it. The rest pose holds the arms out+ # sideways, so a prop built "upright" at rest lies flat the moment the+ # idle clip brings the arm down — the pack's props are authored around+ # that and this one copies their footprint.+ "hand_l-tablet": {+ "slot": "hand_l",+ "label": "Tablet",+ "styles": ["modern", "scifi"],+ "pieces": lambda: [+ box(+ "TabletShell",+ "handslot_l",+ "metal",+ (HANDSLOT_L[0] - 0.04, HANDSLOT_L[0] + 0.04),+ (-0.46, -0.08),+ (HANDSLOT_L[2] - 0.27, HANDSLOT_L[2] + 0.25),+ ),+ box(+ "TabletScreen",+ "handslot_l",+ "emissive",+ (HANDSLOT_L[0] + 0.04, HANDSLOT_L[0] + 0.05),+ (-0.43, -0.11),+ (HANDSLOT_L[2] - 0.24, HANDSLOT_L[2] + 0.22),+ ),+ ],+ },+ "hand_r-wrench": {+ "slot": "hand_r",+ "label": "Wrench",+ "styles": ["modern", "cartoon", "scifi"],+ "pieces": lambda: [+ box(+ "WrenchShaft",+ "handslot_r",+ "metal",+ (HANDSLOT_R[0] - 0.035, HANDSLOT_R[0] + 0.035),+ (-0.30, 0.06),+ (HANDSLOT_R[2] - 0.03, HANDSLOT_R[2] + 0.03),+ ),+ box(+ "WrenchJaw",+ "handslot_r",+ "secondary_shade",+ (HANDSLOT_R[0] - 0.045, HANDSLOT_R[0] + 0.045),+ (-0.38, -0.28),+ (HANDSLOT_R[2] - 0.07, HANDSLOT_R[2] + 0.07),+ ),+ ],+ },+ "headgear-cap": {+ "slot": "headgear",+ "label": "Cap",+ "styles": ["modern", "cartoon", "scifi"],+ "hides": ["hair"],+ # A cap has to sit ON the skull, not balance on it: the crown wraps+ # 30 cm down the sides (it hides the hair, so what it swallows is+ # never seen) and is a touch wider than the head, and the peak hangs+ # from the crown's lower front rather than sticking out of its top.+ "pieces": lambda: [+ box(+ "CapCrown",+ "head",+ "primary",+ (-HEAD_W - 0.035, HEAD_W + 0.035),+ (-HEAD_D - 0.035, HEAD_D + 0.035),+ (HEAD_TOP - 0.30, HEAD_TOP + 0.02),+ ),+ box(+ "CapDome",+ "head",+ "primary",+ (-HEAD_W * 0.82, HEAD_W * 0.82),+ (-HEAD_D * 0.82, HEAD_D * 0.82),+ (HEAD_TOP + 0.02, HEAD_TOP + 0.07),+ ),+ box(+ "CapPeak",+ "head",+ "primary_shade",+ (-HEAD_W * 0.78, HEAD_W * 0.78),+ (-HEAD_D - 0.27, -HEAD_D - 0.02),+ (HEAD_TOP - 0.28, HEAD_TOP - 0.23),+ ),+ box(+ "CapButton",+ "head",+ "accent",+ (-0.045, 0.045),+ (-0.045, 0.045),+ (HEAD_TOP + 0.07, HEAD_TOP + 0.11),+ ),+ ],+ },+}+++def build_part(part_id: str, arm: bpy.types.Object, sheet: dict, img, sheet_material):+ """Build one accessory: boxes, UVs on the strip, weight 1 on its attach bone."""+ spec = PART_SPECS.get(part_id)+ if spec is None:+ raise SystemExit(f"unknown procedural part {part_id!r}")+ pieces = spec["pieces"]()+ bones = {b.name for b in arm.data.bones}+ stray = sorted({p.bone for p in pieces} - bones)+ if stray:+ raise SystemExit(f"part {part_id}: bound to bones the rig has not: {stray}")++ cells = sheet["cells"]+ cv = 1.0 - (sheet["cell_height"] / 2) / sheet["size"]+ objects: list[bpy.types.Object] = []+ used: dict[str, int] = {}+ for piece in pieces:+ obj = _mesh_from_box(piece)+ mesh = obj.data+ mesh.uv_layers.new(name="UVMap")+ uv = mesh.uv_layers.active+ cu = (cells.index(piece.cell) + 0.5) / len(cells)+ for poly in mesh.polygons:+ for li in poly.loop_indices:+ uv.data[li].uv = (cu, cv)+ used[piece.cell] = used.get(piece.cell, 0) + len(mesh.polygons)+ group = obj.vertex_groups.new(name=piece.bone)+ group.add([v.index for v in mesh.vertices], 1.0, "REPLACE")+ obj.data.materials.append(sheet_material(f"{part_id}-tmp", img))+ objects.append(obj)++ for obj in bpy.data.objects:+ obj.select_set(False)+ for obj in objects:+ obj.select_set(True)+ bpy.context.view_layer.objects.active = objects[0]+ bpy.ops.object.join()+ part = bpy.context.view_layer.objects.active+ part.name = part_id+ part.data.name = part_id+ while len(part.data.materials) > 1:+ part.data.materials.pop(index=len(part.data.materials) - 1)++ part.parent = arm+ part.matrix_parent_inverse.identity()+ modifier = part.modifiers.new("Armature", "ARMATURE")+ modifier.object = arm+ return part, {"used": used, "unmapped": {}, "hair_faces": []}diff --git a/scripts/figures/preview_figures.py b/scripts/figures/preview_figures.pynew file mode 100644index 0000000000..d747905263--- /dev/null+++ b/scripts/figures/preview_figures.py@@ -0,0 +1,242 @@+"""Render a contact sheet of built figures — the human proof before they ship.++ blender -b --python scripts/figures/preview_figures.py -- --out <dir> [--glb a.glb b.glb]+ blender -b --python scripts/figures/preview_figures.py -- --out <dir> --parts++Four views per figure (front, three-quarter, side, back), flat-lit, on a light+ground — the Figure Lab's job (character-pipeline.md §10.3) reduced to+something a build step can run without a display. With ``--parts`` it renders+every base wearing every part of its archetype, which is the only way to see a+combination that renders wrong from one side and right from the other.++Reads only what is shipped; writes only PNGs. Never imports ``jarvis.*``.+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path++import bpy # type: ignore[import-not-found]+from mathutils import Vector # type: ignore[import-not-found]++HERE = Path(__file__).resolve().parent+REPO = HERE.parents[1]+FIGURES = REPO / "jarvis/ui/web/frontend/src/assets/society/figures"+CATALOG = REPO / "jarvis/ui/web/frontend/src/components/society/figures/catalog.json"++#: yaw in degrees; 0 looks at the figure's front (it faces glTF +Z, so −Z of the camera)+VIEWS = {"front": 0.0, "three-quarter": 35.0, "side": 90.0, "back": 180.0}+RESOLUTION = 384+++def log(msg: str) -> None:+ print(f"[preview] {msg}", flush=True)+++def reset() -> None:+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ scene.render.engine = "BLENDER_WORKBENCH"+ scene.render.resolution_x = RESOLUTION+ scene.render.resolution_y = RESOLUTION+ scene.render.film_transparent = False+ scene.world = bpy.data.worlds.new("preview")+ scene.world.use_nodes = False+ scene.world.color = (0.90, 0.87, 0.81)+ shading = scene.display.shading+ shading.light = "STUDIO"+ shading.color_type = "TEXTURE"+ shading.show_object_outline = False+ shading.show_specular_highlight = False+++def import_glb(path: Path) -> list[bpy.types.Object]:+ """Import and return the real objects — the importer's own placeholders go.++ Blender draws an imported empty (our ``FWD`` marker) as an icosphere MESH+ beside the empty itself; left in, it lands in the render and doubles the+ measured bounds. Nothing like it exists in the file.+ """+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=str(path), import_shading="FLAT")+ fresh = [o for o in bpy.data.objects if o not in before]+ for obj in list(fresh):+ if obj.type == "MESH" and not obj.data.materials:+ fresh.remove(obj)+ bpy.data.objects.remove(obj, do_unlink=True)+ return fresh+++def world_bounds(objects: list[bpy.types.Object]) -> tuple[Vector, Vector]:+ lo = Vector((1e9, 1e9, 1e9))+ hi = Vector((-1e9, -1e9, -1e9))+ for obj in objects:+ if obj.type != "MESH":+ continue+ for corner in obj.bound_box:+ v = obj.matrix_world @ Vector(corner)+ lo = Vector(min(lo[i], v[i]) for i in range(3))+ hi = Vector(max(hi[i], v[i]) for i in range(3))+ if lo.x > hi.x:+ return Vector((0, 0, 0)), Vector((1, 1, 1))+ return lo, hi+++def render_views(objects: list[bpy.types.Object], out: Path, label: str) -> None:+ lo, hi = world_bounds(objects)+ centre = (lo + hi) / 2+ span = max(hi.x - lo.x, hi.y - lo.y, hi.z - lo.z, 0.1)+ distance = span * 1.75+ camera_data = bpy.data.cameras.new("cam")+ camera_data.lens = 55+ camera = bpy.data.objects.new("cam", camera_data)+ bpy.context.scene.collection.objects.link(camera)+ bpy.context.scene.camera = camera+ out.mkdir(parents=True, exist_ok=True)+ for name, yaw in VIEWS.items():+ a = math.radians(yaw)+ # The imported glTF faces +Z in Blender-after-import terms (Y up →+ # Z up conversion): the front camera sits on −Y and looks back.+ camera.location = centre + Vector(+ (math.sin(a) * distance, -math.cos(a) * distance, span * 0.22)+ )+ direction = centre - camera.location+ camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()+ bpy.context.scene.render.filepath = str(out / f"{label}-{name}.png")+ bpy.ops.render.render(write_still=True)+ log(f"{label}: {len(VIEWS)} views")+++def hide_material_slot(objects: list[bpy.types.Object], suffix: str) -> None:+ """Delete the faces of a material slot — what a part's `hides` list means.++ The runtime hides a whole primitive; Blender's importer merges the file's+ two primitives back into ONE object with two material slots, so hiding by+ object name silently does nothing and a helmet renders over visible hair.+ """+ for obj in objects:+ if obj.type != "MESH":+ continue+ slots = [i for i, m in enumerate(obj.data.materials) if m and m.name.endswith(suffix)]+ if not slots:+ continue+ mesh = obj.data+ doomed = [p for p in mesh.polygons if p.material_index in slots]+ if not doomed:+ continue+ verts = {v for p in doomed for v in p.vertices}+ for vertex in mesh.vertices:+ vertex.select = vertex.index in verts+ for poly in mesh.polygons:+ poly.select = poly.material_index in slots+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.delete(type="FACE")+ bpy.ops.object.mode_set(mode="OBJECT")+++def rebind_to(worn: list[bpy.types.Object], rig: bpy.types.Object | None) -> list[bpy.types.Object]:+ """Bind an accessory to the BODY's skeleton and drop the one it shipped.++ Every part file carries a copy of the rig so it can be skinned at all. Left+ as its own armature, the part holds the REST pose while the body plays a+ clip — a hat floats a head above a bowed head, a staff lies across the+ shoulders — and the preview reports bugs that do not exist. The runtime+ binds a part's mesh to the body's skeleton (`assembleFigure`); so does this.+ """+ if rig is None:+ return worn+ kept: list[bpy.types.Object] = []+ for obj in worn:+ if obj.type == "ARMATURE":+ bpy.data.objects.remove(obj, do_unlink=True)+ continue+ if obj.type == "MESH":+ for modifier in obj.modifiers:+ if modifier.type == "ARMATURE":+ modifier.object = rig+ obj.parent = rig+ obj.matrix_parent_inverse.identity()+ kept.append(obj)+ return kept+++def pose_to_clip(objects: list[bpy.types.Object], clip: str) -> None:+ """Hold one frame of a clip, so a part is judged in the pose it is worn in.++ The rest pose has the arms straight out sideways: a staff read from it+ looks like it is skewered through the ribs, which says nothing about how+ the figure actually stands.+ """+ action = bpy.data.actions.get(clip)+ if action is None:+ return+ for obj in objects:+ if obj.type != "ARMATURE":+ continue+ if obj.animation_data is None:+ obj.animation_data_create()+ obj.animation_data.action = action+ slots = getattr(action, "slots", None)+ if slots:+ obj.animation_data.action_slot = slots[0]+ bpy.context.scene.frame_set(int(action.frame_range[0]))+++def main() -> None:+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []+ parser = argparse.ArgumentParser()+ parser.add_argument("--out", required=True)+ parser.add_argument("--glb", nargs="*", default=None)+ parser.add_argument("--parts", action="store_true")+ parser.add_argument("--all-parts", action="store_true", help="ignore style tags")+ parser.add_argument("--base", default=None, help="with --parts: only this base")+ parser.add_argument("--dir", default=None, help="read GLBs from here, not the shipped tree")+ parser.add_argument("--clip", default="idle", help="hold frame 1 of this clip")+ args = parser.parse_args(argv)+ out = Path(args.out)+ figures = Path(args.dir) if args.dir else FIGURES++ if args.glb:+ for path in args.glb:+ reset()+ objects = import_glb(Path(path))+ pose_to_clip(objects, args.clip)+ render_views(objects, out, Path(path).stem)+ return++ catalog = json.loads(CATALOG.read_text(encoding="utf-8"))+ for base in catalog["bases"]:+ if args.base and base["base"] != args.base:+ continue+ reset()+ objects = import_glb(figures / base["file"])+ pose_to_clip(objects, args.clip)+ render_views(objects, out, base["base"])+ if not args.parts:+ continue+ for part in catalog["parts"]:+ if part["archetype"] != base["archetype"]:+ continue+ # Only what the creator would offer: a part and a base meet when+ # they share a style. Rendering a baseball cap on a wizard proves+ # nothing about a combination nobody can pick.+ if not args.all_parts and not set(part["styles"]) & set(base["styles"]):+ continue+ reset()+ objects = import_glb(figures / base["file"])+ body_rig = next((o for o in objects if o.type == "ARMATURE"), None)+ for hidden in part.get("hides", []):+ hide_material_slot(objects, f"-{hidden}")+ worn = import_glb(figures / part["file"])+ objects += rebind_to(worn, body_rig)+ pose_to_clip(objects, args.clip)+ render_views(objects, out, f"{base['base']}+{part['id']}")+++if __name__ == "__main__":+ main()diff --git a/scripts/figures/quadruped_builder.py b/scripts/figures/quadruped_builder.pynew file mode 100644index 0000000000..b62414eac7--- /dev/null+++ b/scripts/figures/quadruped_builder.py@@ -0,0 +1,723 @@+"""A four-legged companion, modelled and animated by script.++The ``animal`` style had no body at all: the CC0 adventurer pack is humanoid+and there is no donor rig for a quadruped, so this module builds the whole+character — the contract's 21-bone skeleton (§4.3), a blocky fox on it, and+its seven clips keyed frame by frame — the way ``gigi_builder`` builds the+mascot. Nothing here is downloaded.++Same box discipline as ``humanoid_builder``: one axis-aligned box per bone,+weight 1, UV'd onto the 16-cell palette strip. A dog, a cat or a wolf is a+different ``Shape`` in ``SHAPES`` and nothing else — the rig and every clip+are shared, so a second animal costs a colour scheme and a few numbers.++Coordinates are Blender's: Z up, the animal faces −Y, +X is its left. Nose at+−Y, tail at +Y, all four feet on z = 0.+"""++from __future__ import annotations++import math+from dataclasses import dataclass++import bmesh # type: ignore[import-not-found]+import bpy # type: ignore[import-not-found]+from mathutils import Vector # type: ignore[import-not-found]++FPS = 30++# --- skeleton, in metres ----------------------------------------------------+# The animal is built at its final size: the contract's quadruped variant is+# 0.9 m, ear tips included, and the runtime scales from the measured height.+HIP_Y, HIP_Z = 0.30, 0.455+WAIST_Y = 0.10+CHEST_Y = -0.12+SHOULDER_Y = -0.32+NECK_TOP_Y, NECK_TOP_Z = -0.44, 0.62+HEAD_Y, HEAD_Z = -0.44, 0.62+MUZZLE_Y = -0.72+BACK_Z = 0.50+FRONT_LEG_Y = -0.22+BACK_LEG_Y = 0.26+LEG_X = 0.115+KNEE_Z = 0.24+ANKLE_Z = 0.09+EAR_Z = 0.88++#: (name, parent, head, tail). Order is the export order; `root` must be first+#: and the only bone without a parent — the gate insists on exactly one top.+BONES: list[tuple[str, str | None, tuple[float, float, float], tuple[float, float, float]]] = [+ ("root", None, (0.0, 0.0, 0.0), (0.0, 0.0, 0.16)),+ ("hips", "root", (0.0, HIP_Y, HIP_Z), (0.0, WAIST_Y, BACK_Z)),+ ("spine", "hips", (0.0, WAIST_Y, BACK_Z), (0.0, CHEST_Y, BACK_Z + 0.01)),+ ("chest", "spine", (0.0, CHEST_Y, BACK_Z + 0.01), (0.0, SHOULDER_Y, BACK_Z + 0.02)),+ ("neck", "chest", (0.0, SHOULDER_Y, BACK_Z + 0.02), (0.0, NECK_TOP_Y, NECK_TOP_Z)),+ ("head", "neck", (0.0, HEAD_Y, HEAD_Z), (0.0, MUZZLE_Y, HEAD_Z - 0.02)),+ ("jaw", "head", (0.0, HEAD_Y - 0.10, HEAD_Z - 0.06), (0.0, MUZZLE_Y, HEAD_Z - 0.09)),+ ("ear_l", "head", (0.075, HEAD_Y + 0.02, HEAD_Z + 0.11), (0.10, HEAD_Y + 0.03, EAR_Z)),+ ("ear_r", "head", (-0.075, HEAD_Y + 0.02, HEAD_Z + 0.11), (-0.10, HEAD_Y + 0.03, EAR_Z)),+ ("tail_1", "hips", (0.0, HIP_Y + 0.04, HIP_Z + 0.02), (0.0, HIP_Y + 0.26, HIP_Z + 0.02)),+ ("tail_2", "tail_1", (0.0, HIP_Y + 0.26, HIP_Z + 0.02), (0.0, HIP_Y + 0.50, HIP_Z - 0.06)),+]+for _side, _sx in (("l", 1.0), ("r", -1.0)):+ BONES += [+ (+ f"upper_leg_f{_side}",+ "chest",+ (_sx * LEG_X, FRONT_LEG_Y, BACK_Z - 0.05),+ (_sx * LEG_X, FRONT_LEG_Y - 0.01, KNEE_Z),+ ),+ (+ f"lower_leg_f{_side}",+ f"upper_leg_f{_side}",+ (_sx * LEG_X, FRONT_LEG_Y - 0.01, KNEE_Z),+ (_sx * LEG_X, FRONT_LEG_Y + 0.01, ANKLE_Z),+ ),+ (+ f"foot_f{_side}",+ f"lower_leg_f{_side}",+ (_sx * LEG_X, FRONT_LEG_Y + 0.01, ANKLE_Z),+ (_sx * LEG_X, FRONT_LEG_Y - 0.06, 0.0),+ ),+ (+ f"upper_leg_b{_side}",+ "hips",+ (_sx * LEG_X, BACK_LEG_Y, HIP_Z - 0.02),+ (_sx * LEG_X, BACK_LEG_Y + 0.04, KNEE_Z),+ ),+ (+ f"lower_leg_b{_side}",+ f"upper_leg_b{_side}",+ (_sx * LEG_X, BACK_LEG_Y + 0.04, KNEE_Z),+ (_sx * LEG_X, BACK_LEG_Y - 0.03, ANKLE_Z),+ ),+ (+ f"foot_b{_side}",+ f"lower_leg_b{_side}",+ (_sx * LEG_X, BACK_LEG_Y - 0.03, ANKLE_Z),+ (_sx * LEG_X, BACK_LEG_Y - 0.10, 0.0),+ ),+ ]++FRONT_LEGS = ("fl", "fr")+BACK_LEGS = ("bl", "br")+ALL_LEGS = FRONT_LEGS + BACK_LEGS+++@dataclass(frozen=True)+class Shape:+ """What tells one animal from the next; the rig and the clips are shared."""++ #: Palette cell of the coat, the underside, the paws and the tail tip.+ coat: str = "fur"+ belly: str = "fur_shade"+ paw: str = "secondary"+ tail_tip: str = "secondary"+ ear_inner: str = "skin"+ nose: str = "eyes"+ #: Half-widths: the barrel, the head, a leg.+ body_w: float = 0.135+ head_w: float = 0.105+ leg_r: float = 0.043+ #: How bushy the tail is, as a half-width.+ tail_r: float = 0.075+++SHAPES: dict[str, Shape] = {+ # A fox: narrow muzzle, big ears, a tail almost as thick as the body.+ "fox": Shape(),+}+++# ---------------------------------------------------------------------------+# geometry+# ---------------------------------------------------------------------------+++@dataclass+class Piece:+ name: str+ bone: str+ cell: str+ lo: tuple[float, float, float]+ hi: tuple[float, float, float]+++def box(+ name: str,+ bone: str,+ cell: str,+ x: tuple[float, float],+ y: tuple[float, float],+ z: tuple[float, float],+) -> Piece:+ return Piece(name, bone, cell, (x[0], y[0], z[0]), (x[1], y[1], z[1]))+++def leg_pieces(s: Shape) -> list[Piece]:+ """Three boxes per leg, each on its own bone so the knee never pinches."""+ pieces: list[Piece] = []+ r = s.leg_r+ for leg in ALL_LEGS:+ side = 1.0 if leg.endswith("l") else -1.0+ y = FRONT_LEG_Y if leg.startswith("f") else BACK_LEG_Y+ xs = (side * LEG_X - r, side * LEG_X + r)+ xs = (min(xs), max(xs))+ pieces += [+ box(+ f"UpperLeg_{leg}",+ f"upper_leg_{leg}",+ s.coat,+ xs,+ (y - r, y + r),+ (KNEE_Z, BACK_Z - 0.02),+ ),+ box(+ f"LowerLeg_{leg}",+ f"lower_leg_{leg}",+ s.coat,+ (xs[0] + 0.006, xs[1] - 0.006),+ (y - r + 0.004, y + r - 0.004),+ (ANKLE_Z, KNEE_Z + 0.01),+ ),+ box(+ f"Paw_{leg}",+ f"foot_{leg}",+ s.paw,+ (xs[0] + 0.002, xs[1] - 0.002),+ (y - r - 0.03, y + r - 0.01),+ (0.0, ANKLE_Z + 0.01),+ ),+ ]+ return pieces+++def head_pieces(s: Shape) -> list[Piece]:+ w = s.head_w+ skull_y = (HEAD_Y - 0.20, HEAD_Y + 0.06)+ pieces = [+ box("Skull", "head", s.coat, (-w, w), skull_y, (HEAD_Z - 0.10, HEAD_Z + 0.12)),+ box(+ "Muzzle",+ "head",+ s.coat,+ (-w * 0.52, w * 0.52),+ (MUZZLE_Y, HEAD_Y - 0.18),+ (HEAD_Z - 0.09, HEAD_Z + 0.02),+ ),+ box(+ "Cheeks",+ "head",+ s.belly,+ (-w - 0.012, w + 0.012),+ (HEAD_Y - 0.12, HEAD_Y + 0.05),+ (HEAD_Z - 0.10, HEAD_Z - 0.01),+ ),+ box(+ "Nose",+ "head",+ s.nose,+ (-0.026, 0.026),+ (MUZZLE_Y - 0.022, MUZZLE_Y + 0.01),+ (HEAD_Z - 0.05, HEAD_Z - 0.01),+ ),+ box(+ "Jaw",+ "jaw",+ s.belly,+ (-w * 0.5, w * 0.5),+ (MUZZLE_Y + 0.01, HEAD_Y - 0.08),+ (HEAD_Z - 0.115, HEAD_Z - 0.075),+ ),+ ]+ for side, sx in (("L", 1.0), ("R", -1.0)):+ # An animal's eyes sit on the SIDES of the skull, not on its front:+ # placed like a person's they end up buried inside the head, which is+ # exactly how they rendered first time — one dark smear, no face.+ ex = sorted((sx * (w - 0.004), sx * (w + 0.016)))+ pieces.append(+ box(+ f"Eye{side}",+ "head",+ "eye_white",+ ex,+ (HEAD_Y - 0.155, HEAD_Y - 0.10),+ (HEAD_Z + 0.010, HEAD_Z + 0.056),+ )+ )+ px = sorted((sx * (w + 0.012), sx * (w + 0.022)))+ pieces.append(+ box(+ f"Pupil{side}",+ "head",+ "eyes",+ px,+ (HEAD_Y - 0.146, HEAD_Y - 0.112),+ (HEAD_Z + 0.019, HEAD_Z + 0.047),+ )+ )+ bone = f"ear_{'l' if sx > 0 else 'r'}"+ ox = sorted((sx * 0.030, sx * 0.115))+ pieces.append(+ box(+ f"Ear{side}",+ bone,+ s.coat,+ ox,+ (HEAD_Y - 0.02, HEAD_Y + 0.05),+ (HEAD_Z + 0.10, EAR_Z),+ )+ )+ ix = sorted((sx * 0.046, sx * 0.099))+ pieces.append(+ box(+ f"EarIn{side}",+ bone,+ s.ear_inner,+ ix,+ (HEAD_Y - 0.032, HEAD_Y - 0.015),+ (HEAD_Z + 0.12, EAR_Z - 0.03),+ )+ )+ return pieces+++def body_pieces(s: Shape) -> list[Piece]:+ w = s.body_w+ return [+ box(+ "Rump",+ "hips",+ s.coat,+ (-w, w),+ (WAIST_Y - 0.01, HIP_Y + 0.10),+ (HIP_Z - 0.16, BACK_Z + 0.03),+ ),+ box(+ "Barrel",+ "spine",+ s.coat,+ (-w, w),+ (CHEST_Y - 0.01, WAIST_Y + 0.01),+ (HIP_Z - 0.17, BACK_Z + 0.03),+ ),+ box(+ "Ribs",+ "chest",+ s.coat,+ (-w, w),+ (SHOULDER_Y - 0.01, CHEST_Y + 0.01),+ (HIP_Z - 0.16, BACK_Z + 0.04),+ ),+ box(+ "Belly",+ "spine",+ s.belly,+ (-w + 0.012, w - 0.012),+ (SHOULDER_Y, HIP_Y + 0.06),+ (HIP_Z - 0.185, HIP_Z - 0.13),+ ),+ box(+ "Neck",+ "neck",+ s.coat,+ (-w * 0.72, w * 0.72),+ (NECK_TOP_Y - 0.02, SHOULDER_Y + 0.03),+ (BACK_Z - 0.06, NECK_TOP_Z + 0.06),+ ),+ box(+ "Bib",+ "neck",+ s.belly,+ (-w * 0.55, w * 0.55),+ (NECK_TOP_Y - 0.03, SHOULDER_Y),+ (BACK_Z - 0.08, BACK_Z + 0.06),+ ),+ box(+ "Tail1",+ "tail_1",+ s.coat,+ (-s.tail_r, s.tail_r),+ (HIP_Y + 0.04, HIP_Y + 0.28),+ (HIP_Z - 0.05, HIP_Z + 0.09),+ ),+ box(+ "Tail2",+ "tail_2",+ s.tail_tip,+ (-s.tail_r + 0.012, s.tail_r - 0.012),+ (HIP_Y + 0.28, HIP_Y + 0.52),+ (HIP_Z - 0.12, HIP_Z + 0.04),+ ),+ ]+++def all_pieces(shape: Shape) -> list[Piece]:+ return body_pieces(shape) + head_pieces(shape) + leg_pieces(shape)+++def _mesh_from_box(piece: Piece) -> bpy.types.Object:+ bm = bmesh.new()+ bmesh.ops.create_cube(bm, size=1.0)+ size = Vector(tuple(hi - lo for hi, lo in zip(piece.hi, piece.lo, strict=True)))+ centre = Vector(tuple((hi + lo) / 2 for hi, lo in zip(piece.hi, piece.lo, strict=True)))+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)+ bmesh.ops.translate(bm, vec=centre, verts=bm.verts)+ mesh = bpy.data.meshes.new(piece.name)+ bm.to_mesh(mesh)+ bm.free()+ obj = bpy.data.objects.new(piece.name, mesh)+ bpy.context.scene.collection.objects.link(obj)+ return obj+++# ---------------------------------------------------------------------------+# rig+# ---------------------------------------------------------------------------+++def build_armature() -> bpy.types.Object:+ data = bpy.data.armatures.new("QuadrupedRig")+ arm = bpy.data.objects.new("Rig", data)+ bpy.context.scene.collection.objects.link(arm)+ bpy.context.view_layer.objects.active = arm+ arm.select_set(True)+ bpy.ops.object.mode_set(mode="EDIT")+ for name, parent, head, tail in BONES:+ bone = data.edit_bones.new(name)+ bone.head, bone.tail = Vector(head), Vector(tail)+ if parent:+ bone.parent = data.edit_bones[parent]+ bpy.ops.object.mode_set(mode="OBJECT")+ return arm+++# ---------------------------------------------------------------------------+# clips+# ---------------------------------------------------------------------------+++def _key(arm, bone: str, frame: int, *, loc=None, rot=None) -> None:+ pb = arm.pose.bones[bone]+ if loc is not None:+ pb.location = Vector(loc)+ pb.keyframe_insert("location", frame=frame)+ if rot is not None:+ pb.rotation_mode = "XYZ"+ pb.rotation_euler = tuple(math.radians(v) for v in rot)+ pb.keyframe_insert("rotation_euler", frame=frame)+++def _action(arm, name: str, seconds: float):+ action = bpy.data.actions.new(name)+ action.use_fake_user = True+ if arm.animation_data is None:+ arm.animation_data_create()+ arm.animation_data.action = action+ try: # slotted actions (Blender 4.4+)+ slot = action.slots[0] if action.slots else action.slots.new("OBJECT", arm.name)+ arm.animation_data.action_slot = slot+ except AttributeError:+ pass+ frames = max(2, round(seconds * FPS))+ action.frame_range = (1, frames + 1)+ return action, frames+++def _bake(arm, name: str, seconds: float, fn, *, loop: bool) -> None:+ """Key every frame from ``fn(t)`` → {bone: (loc, rot)}.++ A looping clip is keyed with t wrapped back to 0 on the last frame, so the+ first and last key are byte-identical and the gate's loop check passes;+ a one-shot runs the full range and simply ends where it ends.+ """+ action, frames = _action(arm, name, seconds)+ for f in range(frames + 1):+ t = f / frames+ if loop and f == frames:+ t = 0.0+ for bone, (loc, rot) in fn(t).items():+ _key(arm, bone, f + 1, loc=loc, rot=rot)+ action.use_frame_range = True+ action.frame_range = (1, frames + 1)+++def _lift(dz: float) -> tuple:+ """Raise or lower the whole animal, in metres.++ Through `root`, whose local Y runs along world Z, and never through the+ root's world X/Z — clips are played in place and the gate rejects root+ motion in the ground plane.+ """+ return ((0.0, dz, 0.0), (0.0, 0.0, 0.0))+++# Which way a bone actually turns, measured off the rig rather than guessed:+# +X pitches the body chain's far end DOWN (hips, spine, neck, head) and+# swings a leg's knee BACKWARD; +X lifts the tail.+def _gait(t: float, reach: float, lift: float, bob: float) -> dict:+ """A diagonal four-beat: each leg a half cycle out of phase with its pair."""+ two_pi = math.tau+ pose: dict[str, tuple] = {+ # The barrel rises twice a cycle and the head counter-nods, which is+ # what makes a box on legs read as an animal rather than a table.+ "root": _lift(bob * math.sin(t * two_pi * 2)),+ "spine": (None, (bob * 40 * math.sin(t * two_pi * 2), 0.0, 0.0)),+ "neck": (None, (-bob * 30 * math.sin(t * two_pi * 2), 0.0, 0.0)),+ "head": (None, (bob * 26 * math.sin(t * two_pi * 2), 0.0, 0.0)),+ "tail_1": (None, (12.0, 0.0, 6 * math.sin(t * two_pi * 2))),+ "tail_2": (None, (6.0, 0.0, 9 * math.sin(t * two_pi * 2 + 0.8))),+ }+ phases = {"fl": 0.0, "br": 0.0, "fr": 0.5, "bl": 0.5}+ for leg, phase in phases.items():+ a = (t + phase) * two_pi+ swing = reach * math.sin(a)+ knee = lift * max(0.0, math.sin(a + 0.6))+ pose[f"upper_leg_{leg}"] = (None, (swing, 0.0, 0.0))+ pose[f"lower_leg_{leg}"] = (None, (knee, 0.0, 0.0))+ pose[f"foot_{leg}"] = (None, (-knee * 0.5 - swing * 0.35, 0.0, 0.0))+ return pose+++def key_clips(arm: bpy.types.Object) -> None:+ two_pi = math.tau++ def idle(t: float) -> dict:+ breath = math.sin(t * two_pi)+ return {+ "root": _lift(0.004 * breath),+ "spine": (None, (1.2 * breath, 0.0, 0.0)),+ "neck": (None, (-1.0 * breath, 0.0, 0.0)),+ "head": (None, (0.8 * breath, 0.0, 2.5 * math.sin(t * two_pi + 1.1))),+ "ear_l": (None, (0.0, 0.0, -6 * math.sin(t * two_pi * 2))),+ "ear_r": (None, (0.0, 0.0, 6 * math.sin(t * two_pi * 2))),+ "tail_1": (None, (14.0, 0.0, 10 * math.sin(t * two_pi))),+ "tail_2": (None, (8.0, 0.0, 13 * math.sin(t * two_pi + 0.7))),+ }++ def walk(t: float) -> dict:+ return _gait(t, reach=17.0, lift=22.0, bob=0.012)++ def run(t: float) -> dict:+ return _gait(t, reach=30.0, lift=38.0, bob=0.024)++ def talk(t: float) -> dict:+ return {+ "head": (None, (5 * math.sin(t * two_pi), 0.0, 4 * math.sin(t * two_pi * 2))),+ "jaw": (None, (14 * abs(math.sin(t * two_pi * 3)), 0.0, 0.0)),+ "ear_l": (None, (0.0, 0.0, -10 * math.sin(t * two_pi * 2))),+ "ear_r": (None, (0.0, 0.0, 10 * math.sin(t * two_pi * 2))),+ "tail_1": (None, (16.0, 0.0, 16 * math.sin(t * two_pi * 2))),+ }++ def sit(t: float) -> dict:+ """Rump on the ground, chest up, hind legs folded, front legs straight."""+ breath = math.sin(t * two_pi)+ pose = {+ "root": _lift(-0.055),+ "hips": (None, (-7.0, 0.0, 0.0)),+ "spine": (None, (-5.0 + 1.0 * breath, 0.0, 0.0)),+ "chest": (None, (-4.0, 0.0, 0.0)),+ "neck": (None, (-5.0 - 1.0 * breath, 0.0, 0.0)),+ "head": (None, (4.0, 0.0, 2 * math.sin(t * two_pi))),+ "tail_1": (None, (20.0, 0.0, 7 * math.sin(t * two_pi))),+ "tail_2": (None, (10.0, 0.0, 9 * math.sin(t * two_pi + 0.6))),+ }+ for leg in BACK_LEGS:+ pose[f"upper_leg_{leg}"] = (None, (-32.0, 0.0, 0.0))+ pose[f"lower_leg_{leg}"] = (None, (46.0, 0.0, 0.0))+ pose[f"foot_{leg}"] = (None, (-12.0, 0.0, 0.0))+ return pose++ def sleep(t: float) -> dict:+ """Lying down: body on the ground, legs tucked under, muzzle resting.++ No sideways twist. A curl reads as a knot at 20 px and, keyed on the+ spine, it dragged every leg out sideways with it.+ """+ breath = math.sin(t * two_pi)+ pose = {+ "root": _lift(-0.195),+ "spine": (None, (2.0 * breath, 0.0, 0.0)),+ "neck": (None, (20.0, 0.0, 0.0)),+ "head": (None, (-14.0 + 1.5 * breath, 0.0, 0.0)),+ "ear_l": (None, (0.0, 0.0, -18.0)),+ "ear_r": (None, (0.0, 0.0, 18.0)),+ "tail_1": (None, (2.0, 0.0, 18.0)),+ "tail_2": (None, (0.0, 0.0, 22.0)),+ }+ for leg in ALL_LEGS:+ pose[f"upper_leg_{leg}"] = (None, (-58.0, 0.0, 0.0))+ pose[f"lower_leg_{leg}"] = (None, (72.0, 0.0, 0.0))+ pose[f"foot_{leg}"] = (None, (-22.0, 0.0, 0.0))+ return pose++ def celebrate(t: float) -> dict:+ """A hop with the front paws off the ground and the tail going hard."""+ hop = math.sin(min(t * 1.6, 1.0) * math.pi)+ wag = math.sin(t * two_pi * 4)+ pose = {+ "root": _lift(0.13 * hop),+ "spine": (None, (-12.0 * hop, 0.0, 0.0)),+ "neck": (None, (-16.0 * hop, 0.0, 0.0)),+ "head": (None, (-8.0 * hop, 0.0, 6 * wag)),+ "jaw": (None, (12.0 * hop, 0.0, 0.0)),+ "ear_l": (None, (0.0, 0.0, -14 * wag)),+ "ear_r": (None, (0.0, 0.0, 14 * wag)),+ "tail_1": (None, (22.0 * hop, 0.0, 24 * wag)),+ "tail_2": (None, (12.0 * hop, 0.0, 20 * wag)),+ }+ for leg in FRONT_LEGS:+ pose[f"upper_leg_{leg}"] = (None, (-44.0 * hop, 0.0, 0.0))+ pose[f"lower_leg_{leg}"] = (None, (34.0 * hop, 0.0, 0.0))+ return pose++ _bake(arm, "idle", 2.6, idle, loop=True)+ _bake(arm, "walk", 0.9, walk, loop=True)+ _bake(arm, "run", 0.55, run, loop=True)+ _bake(arm, "talk", 1.4, talk, loop=True)+ _bake(arm, "sit", 3.0, sit, loop=True)+ _bake(arm, "sleep", 4.0, sleep, loop=True)+ _bake(arm, "celebrate", 1.4, celebrate, loop=False)+ arm.animation_data.action = None+++# ---------------------------------------------------------------------------+# assembly+# ---------------------------------------------------------------------------+++def build_quadruped(+ shape_name: str, sheet: dict, img, sheet_material+) -> tuple[bpy.types.Object, bpy.types.Object, dict]:+ """Build the whole animal into the current (empty) scene."""+ shape = SHAPES.get(shape_name)+ if shape is None:+ raise SystemExit(f"unknown quadruped shape {shape_name!r}")+ arm = build_armature()+ bones = {name for name, *_ in BONES}+ pieces = all_pieces(shape)+ stray = sorted({p.bone for p in pieces} - bones)+ if stray:+ raise SystemExit(f"quadruped_builder: pieces bound to bones the rig has not: {stray}")++ cells = sheet["cells"]+ cv = 1.0 - (sheet["cell_height"] / 2) / sheet["size"]+ objects: list[bpy.types.Object] = []+ used: dict[str, int] = {}+ for piece in pieces:+ obj = _mesh_from_box(piece)+ mesh = obj.data+ mesh.uv_layers.new(name="UVMap")+ uv = mesh.uv_layers.active+ cu = (cells.index(piece.cell) + 0.5) / len(cells)+ for poly in mesh.polygons:+ for li in poly.loop_indices:+ uv.data[li].uv = (cu, cv)+ used[piece.cell] = used.get(piece.cell, 0) + len(mesh.polygons)+ group = obj.vertex_groups.new(name=piece.bone)+ group.add([v.index for v in mesh.vertices], 1.0, "REPLACE")+ obj.data.materials.append(sheet_material("tmp-sheet", img))+ objects.append(obj)++ for obj in bpy.data.objects:+ obj.select_set(False)+ for obj in objects:+ obj.select_set(True)+ bpy.context.view_layer.objects.active = objects[0]+ bpy.ops.object.join()+ body = bpy.context.view_layer.objects.active+ body.name = "Body"+ body.data.name = "Body"+ while len(body.data.materials) > 1:+ body.data.materials.pop(index=len(body.data.materials) - 1)++ body.parent = arm+ body.matrix_parent_inverse.identity()+ modifier = body.modifiers.new("Armature", "ARMATURE")+ modifier.object = arm+ key_clips(arm)+ return arm, body, {"used": used, "unmapped": {}, "hair_faces": []}+++# ---------------------------------------------------------------------------+# parts+# ---------------------------------------------------------------------------++#: Accessories for the quadruped slots (contract §5). Like the humanoid ones+#: they hang on a bone every animal of this rig shares, so one file fits every+#: shape in `SHAPES`.+PART_SPECS: dict[str, dict] = {+ "collar-band": {+ "slot": "collar",+ "label": "Collar",+ "styles": ["animal"],+ "pieces": lambda: [+ box(+ "CollarBand",+ "neck",+ "leather",+ (-0.108, 0.108),+ (SHOULDER_Y - 0.08, SHOULDER_Y - 0.01),+ (BACK_Z - 0.05, NECK_TOP_Z + 0.02),+ ),+ box(+ "CollarTag",+ "neck",+ "accent",+ (-0.028, 0.028),+ (SHOULDER_Y - 0.10, SHOULDER_Y - 0.07),+ (BACK_Z - 0.09, BACK_Z - 0.03),+ ),+ ],+ },+}+++def build_part(part_id: str, arm: bpy.types.Object, sheet: dict, img, sheet_material):+ """Build one accessory: boxes, UVs on the strip, weight 1 on its attach bone."""+ spec = PART_SPECS.get(part_id)+ if spec is None:+ raise SystemExit(f"unknown procedural quadruped part {part_id!r}")+ pieces = spec["pieces"]()+ bones = {name for name, *_ in BONES}+ stray = sorted({p.bone for p in pieces} - bones)+ if stray:+ raise SystemExit(f"part {part_id}: bound to bones the rig has not: {stray}")++ cells = sheet["cells"]+ cv = 1.0 - (sheet["cell_height"] / 2) / sheet["size"]+ objects: list[bpy.types.Object] = []+ used: dict[str, int] = {}+ for piece in pieces:+ obj = _mesh_from_box(piece)+ mesh = obj.data+ mesh.uv_layers.new(name="UVMap")+ uv = mesh.uv_layers.active+ cu = (cells.index(piece.cell) + 0.5) / len(cells)+ for poly in mesh.polygons:+ for li in poly.loop_indices:+ uv.data[li].uv = (cu, cv)+ used[piece.cell] = used.get(piece.cell, 0) + len(mesh.polygons)+ group = obj.vertex_groups.new(name=piece.bone)+ group.add([v.index for v in mesh.vertices], 1.0, "REPLACE")+ obj.data.materials.append(sheet_material(f"{part_id}-tmp", img))+ objects.append(obj)++ for obj in bpy.data.objects:+ obj.select_set(False)+ for obj in objects:+ obj.select_set(True)+ bpy.context.view_layer.objects.active = objects[0]+ bpy.ops.object.join()+ part = bpy.context.view_layer.objects.active+ part.name = part_id+ part.data.name = part_id+ while len(part.data.materials) > 1:+ part.data.materials.pop(index=len(part.data.materials) - 1)++ part.parent = arm+ part.matrix_parent_inverse.identity()+ modifier = part.modifiers.new("Armature", "ARMATURE")+ modifier.object = arm+ return part, {"used": used, "unmapped": {}, "hair_faces": []}diff --git a/scripts/figures/sources/jarvis-animals.json b/scripts/figures/sources/jarvis-animals.jsonnew file mode 100644index 0000000000..eb10412eb9--- /dev/null+++ b/scripts/figures/sources/jarvis-animals.json@@ -0,0 +1,33 @@+{+ "$comment": "Four-legged companions, modelled and keyed by scripts/figures/quadruped_builder.py. The `animal` style has no CC0 donor of the right archetype, so the whole character is first-party: the contract's 21-bone quadruped rig, a blocky body on it and its seven clips written frame by frame. Nothing is downloaded.",+ "name": "Personal Jarvis animals (first-party)",+ "author": "Personal Jarvis",+ "license": "first-party",+ "license_url": "",+ "procedural": "quadruped",+ "files": {},+ "characters": {+ "Fox": {+ "shape": "fox",+ "parts": ["collar-band"],+ "default_palette": {+ "skin": "#f0b5a8",+ "skin_shade": "#d29488",+ "hair": "#b8532a",+ "eyes": "#1a1614",+ "primary": "#c25a2a",+ "primary_shade": "#9a4420",+ "secondary": "#f4efe6",+ "secondary_shade": "#d8d0c2",+ "accent": "#f2c14e",+ "metal": "#9aa3a8",+ "leather": "#6b4a33",+ "fur": "#c8622b",+ "fur_shade": "#f4efe6",+ "shoes": "#2b2320",+ "eye_white": "#fbf8f2",+ "emissive": "#ffd166"+ }+ }+ }+}diff --git a/scripts/figures/sources/jarvis-humanoids.json b/scripts/figures/sources/jarvis-humanoids.jsonnew file mode 100644index 0000000000..383e64b2aa--- /dev/null+++ b/scripts/figures/sources/jarvis-humanoids.json@@ -0,0 +1,99 @@+{+ "$comment": "Bodies modelled by scripts/figures/humanoid_builder.py — first-party geometry and sheets on the CC0 KayKit rig and clips (character-pipeline.md §8.2 route B, §12 decision 1). No mesh of the donor survives the build: it is imported for its 23 deform bones and nine clips, every object it shipped is deleted, and the body is built from boxes. The donor's own sha256 rows stay in SOURCES.md through the kaykit-adventurers source.",+ "name": "Personal Jarvis humanoids (first-party meshes on the KayKit CC0 rig)",+ "author": "Personal Jarvis",+ "license": "first-party",+ "license_url": "",+ "procedural": "humanoid",+ "rig_source": "kaykit-adventurers",+ "rig_character": "Rogue",+ "files": {},+ "characters": {+ "Office": {+ "profile": "office",+ "$comment": "The accessories live on this one character: they hang on `chest` and the handslots, bones every biped of this rig shares, so one file fits Office, Casual, Chibi and Android alike. `headgear-cap` is cut for this module's own crown height and skull width and is therefore tagged only to the styles built on it — never to the wider KayKit heads.",+ "parts": ["back-backpack", "hand_l-tablet", "hand_r-wrench", "headgear-cap"],+ "default_palette": {+ "skin": "#f1c4a0",+ "skin_shade": "#d3a382",+ "hair": "#3b2a20",+ "eyes": "#1b2427",+ "primary": "#f2f2ee",+ "primary_shade": "#d3d3cd",+ "secondary": "#1f2a44",+ "secondary_shade": "#141c2e",+ "accent": "#a8322f",+ "metal": "#9aa3a8",+ "leather": "#3a2a20",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#241f1c",+ "eye_white": "#f4f7f8",+ "emissive": "#ffd166"+ }+ },+ "Casual": {+ "profile": "casual",+ "default_palette": {+ "skin": "#d8a37c",+ "skin_shade": "#b98763",+ "hair": "#241a15",+ "eyes": "#1b2427",+ "primary": "#3f7d6a",+ "primary_shade": "#2c5a4c",+ "secondary": "#3d5a80",+ "secondary_shade": "#2b3f5a",+ "accent": "#e8c46b",+ "metal": "#9aa3a8",+ "leather": "#4a3526",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#e9e5dc",+ "eye_white": "#f4f7f8",+ "emissive": "#ffd166"+ }+ },+ "Chibi": {+ "profile": "chibi",+ "default_palette": {+ "skin": "#f6cdaa",+ "skin_shade": "#dcab86",+ "hair": "#c9522f",+ "eyes": "#241d1a",+ "primary": "#e2604a",+ "primary_shade": "#b8452f",+ "secondary": "#f6d98a",+ "secondary_shade": "#d9b45f",+ "accent": "#4fb7a5",+ "metal": "#a8b2b7",+ "leather": "#8a5a38",+ "fur": "#c98b62",+ "fur_shade": "#9b6242",+ "shoes": "#3b4a63",+ "eye_white": "#ffffff",+ "emissive": "#ffe066"+ }+ },+ "Android": {+ "profile": "android",+ "default_palette": {+ "skin": "#c9d2d8",+ "skin_shade": "#a3adb5",+ "hair": "#5a646b",+ "eyes": "#101820",+ "primary": "#2f6f8f",+ "primary_shade": "#1f4a60",+ "secondary": "#cdd6db",+ "secondary_shade": "#9aa5ab",+ "accent": "#4fd1c5",+ "metal": "#b6c0c6",+ "leather": "#39444b",+ "fur": "#b87556",+ "fur_shade": "#8d4c39",+ "shoes": "#1f4a60",+ "eye_white": "#e6ecef",+ "emissive": "#6ff2e3"+ }+ }+ }+}diff --git a/scripts/figures/sources/kaykit-adventurers.json b/scripts/figures/sources/kaykit-adventurers.jsonindex c92f525c28..d41fb70bf4 100644--- a/scripts/figures/sources/kaykit-adventurers.json+++ b/scripts/figures/sources/kaykit-adventurers.json@@ -117,7 +117,7 @@"emissive": "#ffd166"},"parts": [- { "object": "Rogue_Cape", "id": "back-rogue-cape", "slot": "back", "label": "Ranger cape", "styles": ["fantasy", "modern"] },+ { "object": "Rogue_Cape", "id": "back-rogue-cape", "slot": "back", "label": "Ranger cape", "styles": ["fantasy"], "two_sided": true },{ "object": "Knife", "id": "hand_r-knife", "slot": "hand_r", "label": "Knife", "styles": ["fantasy"] }]},@@ -166,7 +166,7 @@},"parts": [{ "object": "Knight_Helmet", "id": "headgear-knight-helmet", "slot": "headgear", "label": "Knight helmet", "styles": ["fantasy"], "hides": ["hair"] },- { "object": "Knight_Cape", "id": "back-knight-cape", "slot": "back", "label": "Knight cape", "styles": ["fantasy"] },+ { "object": "Knight_Cape", "id": "back-knight-cape", "slot": "back", "label": "Knight cape", "styles": ["fantasy"], "two_sided": true },{ "object": "1H_Sword", "id": "hand_r-sword", "slot": "hand_r", "label": "Sword", "styles": ["fantasy"] },{ "object": "Round_Shield", "id": "hand_l-round-shield", "slot": "hand_l", "label": "Round shield", "styles": ["fantasy"] }]@@ -217,9 +217,9 @@},"parts": [{ "object": "Mage_Hat", "id": "headgear-mage-hat", "slot": "headgear", "label": "Wizard hat", "styles": ["fantasy"], "hides": ["hair"] },- { "object": "Mage_Cape", "id": "back-mage-cape", "slot": "back", "label": "Mage cape", "styles": ["fantasy"] },+ { "object": "Mage_Cape", "id": "back-mage-cape", "slot": "back", "label": "Mage cape", "styles": ["fantasy"], "two_sided": true, "cell_map": { "c2r1": "primary" } },{ "object": "2H_Staff", "id": "hand_r-staff", "slot": "hand_r", "label": "Staff", "styles": ["fantasy"] },- { "object": "Spellbook", "id": "hand_l-spellbook", "slot": "hand_l", "label": "Spellbook", "styles": ["fantasy", "modern"] }+ { "object": "Spellbook", "id": "hand_l-spellbook", "slot": "hand_l", "label": "Spellbook", "styles": ["fantasy"] }]},"Barbarian": {@@ -267,9 +267,9 @@},"parts": [{ "object": "Barbarian_Hat", "id": "headgear-horned-hat", "slot": "headgear", "label": "Horned hat", "styles": ["fantasy"], "hides": ["hair"] },- { "object": "Barbarian_Cape", "id": "back-fur-cape", "slot": "back", "label": "Fur cape", "styles": ["fantasy"] },+ { "object": "Barbarian_Cape", "id": "back-fur-cape", "slot": "back", "label": "Fur cape", "styles": ["fantasy"], "two_sided": true, "cell_map": { "c7r0": "fur" } },{ "object": "1H_Axe", "id": "hand_r-axe", "slot": "hand_r", "label": "Axe", "styles": ["fantasy"] },- { "object": "Mug", "id": "hand_r-mug", "slot": "hand_r", "label": "Mug", "styles": ["modern", "fantasy"] },+ { "object": "Mug", "id": "hand_r-mug", "slot": "hand_r", "label": "Mug", "styles": ["modern", "fantasy", "cartoon", "scifi"] },{ "object": "Barbarian_Round_Shield", "id": "hand_l-wooden-shield", "slot": "hand_l", "label": "Wooden shield", "styles": ["fantasy"] }]}