Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

CH49: worn hard pieces from words, and CH48b: the garment training data at scale. tools/garments/wear.sh draws a piece on SOMA's mannequin with an image model, makes it 3D with Idol on this machine, lays it on SOMA (the turn searched, then turn, size and place refined against the skin), cuts the bare body away (by distance, or by a magenta key for pieces that leave skin bare), lifts what is kept 4 mm off the skin, and gives each face the bone it lies nearest, so each piece rides its bone rigidly as one part. Pilot: plate armour, fitted at SOMA's height within 0.05 per cent, walks with the body front and back. engine.sh LEAN=1 keeps what training needs, about 0.4 MB a design. The plan: periods, genres and armour in the training set (CH48b), rigid worn pieces (CH49)

shinyobjectz9055f7273f32
diff --git a/docs/character.feature b/docs/character.feature
index e5e0b08a..0a75ab2a 100644
--- a/docs/character.feature
+++ b/docs/character.feature
@@ -688,3 +688,28 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
# between the layers of one design; the captions are written from the settings, not seen.
Then one command makes N random garments, each worn on SOMA and labelled with its design
And a garment that slides off is caught by the drape's own check, not by eye
+
+ Scenario: CH48b. The training data at scale, with periods, genres and things that are not sewn (proposed)
+ # The user's choice, 11-15: scale the data and train now, before writing the missing pattern pieces. And,
+ # in his words: "use examples of time periods, futurism, armor/suits/helmets/hats/etc". The engine's lean
+ # mode (LEAN=1) keeps what training needs, about 0.4 MB a design: the design, its caption, the drape's
+ # numbers and the draped mesh; pictures and glbs are made again from those for the examples that need
+ # them. A caption from the settings alone ("fitted sleeveless top, trousers") can't name a period or a
+ # genre, so captions also come from a picture of the garment on the mannequin, written by an image-reading
+ # model asked what the garment is and what it evokes (Edwardian, 1970s, workwear, futurist, uniform), with
+ # its price per caption said first. What can't be sewn comes from CH49.
+ Then the training set holds sewn garments captioned by their settings and by what they look like
+ And worn hard pieces from CH49, each with its words, its picture and its 3D on SOMA
+
+ Scenario: CH49. Worn hard pieces: helmets, hats, armour, visors (proposed)
+ # Patterns make only what is cut and sewn. A helmet, a hat, a breastplate or a visor is made the way the
+ # user first proposed for clothes and the creature flow makes animals: a picture of SOMA's mannequin
+ # (one view, its camera written down) is dressed by an image model, keeping the pose and the view; Idol
+ # (Apache-2.0, run on this Mac) makes the dressed figure 3D; it is laid on SOMA by its camera and size; the
+ # body is cut away (everything within a few millimetres of the skin, by the body's distance grid); what is
+ # left is split by the bone it lies nearest, and each piece rides that bone rigidly, as the head's cap and
+ # glasses ride Head (CH21). It differs from the rejected picture-measured clothes: those painted cloth onto
+ # the skin from four separate pictures that never agreed; here one picture is made 3D whole, and only rigid
+ # things are kept, so nothing has to fold.
+ Then words make a helmet, a hat or armour that SOMA wears and moves with
+ And each piece is its own part on the bone it covers, so pieces mix with sewn garments as layers
diff --git a/tools/garments/README.md b/tools/garments/README.md
index b5be04d3..7b1e8299 100644
--- a/tools/garments/README.md
+++ b/tools/garments/README.md
@@ -34,3 +34,22 @@ stretch, cloth inside the skin, and whether it stayed on).
- `make_garment.py`, `design.py`: one garment from settings by path (`sleeve.length=0.95`)
- `render_pretty.py`: a garment to look at (EEVEE, fabric with sheen, soft studio light; `raea blender run`)
- `sheet.py`, `grid.py`, `snaps_view.py`: contact sheets, and the drape's snapshots (`SNAP=1`) over the body
+
+## Worn hard pieces (CH49)
+
+What can't be sewn (helmets, hats, armour, visors, hard-shell suits) is drawn on SOMA's mannequin by an image model,
+made 3D by Idol on this machine, laid on SOMA and split by bone:
+
+ tools/garments/wear.sh NAME "a tall black Victorian silk top hat" keyed # leaves skin bare: magenta mannequin
+ tools/garments/wear.sh NAME "a full suit of plate armour" full # covers the body: kept whole, lifted
+
+- `wear_mannequin.py`: SOMA at rest from three-quarters ahead, its camera written down (`KEY=1`: magenta)
+- `wear_fit.py`: Idol's mesh turned, sized and placed onto SOMA (turn searched, then refined against the skin), bare body
+ cut (by distance, or by the magenta key), what is kept lifted off the skin, each face given its nearest bone
+- `wear_bake.py`: each piece weighted wholly to its bone on SOMA's armature, Idol's colours made linear, one glb + a picture
+
+About 5 cents (the picture) and 5 minutes (Idol) a piece. Faults so far: the surface is as lumpy as Idol's 4 mm mesh;
+a full suit's hands and feet copy SOMA's bare shape when the drawn gauntlets don't match its hand pose.
+
+For training data at scale, `LEAN=1 tools/garments/engine.sh OUT N SEED` keeps each design's settings, caption, drape
+numbers and draped mesh only (about 0.4 MB a design).
diff --git a/tools/garments/engine.sh b/tools/garments/engine.sh
index 15cd35de..807c9a10 100755
--- a/tools/garments/engine.sh
+++ b/tools/garments/engine.sh
@@ -2,6 +2,8 @@
# The garment data engine (docs/character.feature CH48a): N random GarmentCode designs cut to SOMA's measurements,
# draped on the GPU, skinned, pictured on the mannequin, one contact sheet.
# tools/garments/engine.sh OUT_DIR N [SEED]
+# LEAN=1 tools/garments/engine.sh ... training data at scale: no glb, no pictures, no sheet, and each design's
+# panels.json dropped once draped (GarmentCode makes it again from design.yaml); about 0.4 MB a design
# Needs (see README.md): GARMENTCODE (a clone at d449629), GARMENT_PY (its venv's python, with mlx and libigl),
# and the body's signed distance grid at $GARMENT_DATA/soma_sdf.npz (sdf_igl.py builds it once).
set -euo pipefail
@@ -19,6 +21,8 @@ for d in "$OUT"/g*/; do
[ -f "$d/$n.drape.json" ] && continue
(cd "$T" && "$PY" -I drape_mlx.py "$DATA/soma_sdf.npz" "$d/$n.panels.json" "$d" 150 -0.064 "$T/soma.yaml") \
| grep --line-buffered -E '^drape: \{|Error|Traceback' || echo "drape: $n failed"
+ [ "${LEAN:-0}" = 1 ] && [ -f "$d/$n.drape.json" ] && rm -f "${d:?}${n:?}.panels.json"
done
+[ "${LEAN:-0}" = 1 ] && exit 0
"$RAEA" blender run "$T/bake_batch.py" "$BODY" "$OUT"/g*/ 2>&1 | grep --line-buffered -E '^bake|Error|Traceback'
"$PY" -I "$T/sheet.py" "$OUT/sheet.jpg" "$OUT"/g*/
diff --git a/tools/garments/wear.sh b/tools/garments/wear.sh
new file mode 100755
index 00000000..d176afff
--- /dev/null
+++ b/tools/garments/wear.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# Worn hard pieces from words (docs/character.feature CH49): SOMA's mannequin dressed by an image model, made 3D by Idol on
+# this machine, laid on SOMA, the body cut away, each piece riding the bone it covers.
+# tools/garments/wear.sh NAME "what is worn" full|keyed
+# full: the piece covers the whole body (a suit of armour, a space suit): the dressed surface is kept whole and lifted
+# 4 mm off the skin wherever it meets it. keyed: it leaves skin bare (a hat, a helmet, a breastplate): the mannequin is
+# drawn magenta and what comes back magenta is cut.
+# Needs: GARMENT_PY (the garments venv's python, see README.md), Idol's server on IDOL_URL (default 127.0.0.1:11399),
+# SHEET3D (its .venv with tools/idol_serve.py and splat_mesh.py) and SPLAT_NPZ (the creature flow's splat_npz.py).
+# Writes $WEAR/NAME/: art/out.jpg, idol/raw.glb, pieces.npz, NAME.glb and NAME.png. About 5 cents and 5 minutes.
+set -euo pipefail
+T=$(cd "$(dirname "$0")" && pwd)
+NAME=${1:?name}; WORDS=${2:?what is worn}; MODE=${3:-keyed}
+PY=${GARMENT_PY:?the garments venv python}
+WEAR=${WEAR:-$HOME/.cache/raea-garments/wear}
+BODY=${SOMA_DIR:-$HOME/Documents/raea/raea/projects/sheet3d/assets/characters/soma}
+S=${SHEET3D:-$HOME/Studio/internal/projects/sheet3d}
+NPZ=${SPLAT_NPZ:-$HOME/Documents/raea/raea/projects/p-new-mwhhwp6q4/tools/splat_npz.py}
+URL=${IDOL_URL:-http://127.0.0.1:11399}
+D=$WEAR/$NAME; M=$WEAR/_mannequin-$MODE
+mkdir -p "$D/art" "$D/idol"
+[ "$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 "$URL/" || true)" != 000 ] || { echo "FAILED Idol's server is not up on $URL" >&2; exit 1; }
+[ -f "$M/mannequin.png" ] || raea blender run "$T/wear_mannequin.py" "$BODY/body.glb" "$M" 30 6 1024 "$([ "$MODE" = keyed ] && echo 1 || echo 0)" | grep -E "wrote|Error"
+if [ "$MODE" = keyed ]; then
+ KEEP="Keep every bare part of the mannequin exactly as it is, the same flat magenta colour and shape: only the worn piece is added, nothing else is dressed."
+ FIT=(0.004 0.004 1)
+else
+ KEEP="The piece covers the whole body."
+ FIT=(-1 0.004 0)
+fi
+PROMPT="A studio product photograph of a physical object, not a drawing. Dress the mannequin in the image in $WORDS. Keep EXACTLY the mannequin's pose, its proportions, the place of each arm, hand, leg and foot, the head's direction and the camera view; the piece sits close on the body as it is worn. $KEEP Nothing held, no weapon, no base. Shown alone, the whole figure in frame with a margin. UNLIT: a flat albedo pass, every part in its own true colour, no cast shadows, no shading gradients, no highlights, no rim light. Plain solid light grey background (#C8C8C8), no floor, no ground shadow, no text, no watermark. Sharp detail."
+[ -f "$D/art/out.jpg" ] || raea gen image "$PROMPT" --model flux_2_pro --image "$M/mannequin.png" --aspect 1:1 -o "$D/art" --max-cents 12 | tail -1
+[ -f "$D/idol/raw.glb" ] || {
+ "$S/.venv/bin/python" "$S/tools/idol_serve.py" "$D/art/out.jpg" "$D/idol/splat.glb" --url "$URL" --steps 100 --gaussians 1048576 --geometry splat | tail -1
+ "$S/.venv/bin/python" "$NPZ" "$D/idol" | tail -1
+ "$S/.venv/bin/python" "$S/tools/splat_mesh.py" "$D/idol/splat.npz" "$D/idol/raw.glb" --voxel 0.004 | tail -1
+ rm -f "${D:?}/idol/splat.npz"
+}
+"$PY" -I "$T/wear_fit.py" "$D/idol/raw.glb" "$BODY/body.glb" "$BODY/skeleton.json" "$D/pieces.npz" "${FIT[@]}" | grep -E "^fit:|Error|Traceback"
+raea blender run "$T/wear_bake.py" "$BODY/body.glb" "$D/pieces.npz" "$D/$NAME.glb" "${METAL:-0.0}" | grep -E "^wear:|Error|Traceback"
diff --git a/tools/garments/wear_bake.py b/tools/garments/wear_bake.py
new file mode 100644
index 00000000..196943da
--- /dev/null
+++ b/tools/garments/wear_bake.py
@@ -0,0 +1,65 @@
+# Worn hard pieces (wear_fit.py's npz) as a part for SOMA (docs/character.feature CH49): each vertex weighted wholly to
+# the bone its face was given, on SOMA's own armature, coloured by Idol's vertex colours, exported as one glb with a
+# picture from three-quarters ahead beside it.
+# raea blender run tools/garments/wear_bake.py SOMA_BODY.glb PIECES.npz OUT.glb [METAL=0.0]
+import math, os, sys
+import bpy, numpy as np
+from mathutils import Vector
+
+a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[-3:]
+body, npz, out = a[0], a[1], a[2]
+metal = float(a[3]) if len(a) > 3 else 0.0
+z = np.load(npz)
+V, F, C, fb, names = z["V"], z["F"], z["C"], z["fbone"], [str(n) for n in z["names"]]
+bpy.ops.wm.read_factory_settings(use_empty=True)
+bpy.ops.import_scene.gltf(filepath=body)
+arm = next(o for o in bpy.data.objects if o.type == "ARMATURE")
+skin = [o for o in bpy.data.objects if o.type == "MESH"]
+# the pieces: split per face's bone (a vertex shared by two bones' faces is doubled, so each piece is rigid on its own)
+verts, faces, cols, vbone = [], [], [], []
+for b in np.unique(fb):
+ fs = F[fb == b]; used = np.unique(fs); remap = {int(u): i + len(verts) for i, u in enumerate(used)}
+ verts += [(float(V[u, 0]), float(-V[u, 2]), float(V[u, 1])) for u in used] # glTF (y up) to Blender (z up)
+ cols += [tuple(C[u]) for u in used]; vbone += [int(b)] * len(used)
+ faces += [tuple(remap[int(i)] for i in f) for f in fs]
+me = bpy.data.meshes.new("worn"); me.from_pydata(verts, [], faces); me.update()
+for p in me.polygons: p.use_smooth = True
+ca = me.color_attributes.new("Col", "FLOAT_COLOR", "POINT")
+# (Idol's colours are display values: made linear here, as a FLOAT_COLOR attribute holds linear light)
+lin = lambda x: x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4
+for i, c in enumerate(cols): ca.data[i].color = (lin(c[0]), lin(c[1]), lin(c[2]), 1.0)
+ob = bpy.data.objects.new("worn", me); bpy.context.scene.collection.objects.link(ob)
+groups = {}
+for i, b in enumerate(vbone):
+ n = names[b]
+ g = groups.get(n) or ob.vertex_groups.new(name=n); groups[n] = g
+ g.add([i], 1.0, "REPLACE")
+ob.parent = arm
+mod = ob.modifiers.new("arm", "ARMATURE"); mod.object = arm
+mat = bpy.data.materials.new("worn"); mat.use_nodes = True
+bsdf = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
+attr = mat.node_tree.nodes.new("ShaderNodeVertexColor"); attr.layer_name = "Col"
+mat.node_tree.links.new(attr.outputs["Color"], bsdf.inputs["Base Color"])
+bsdf.inputs["Metallic"].default_value = metal; bsdf.inputs["Roughness"].default_value = 0.35 if metal > 0 else 0.6
+me.materials.append(mat)
+# a picture: the pieces over the grey body, from three-quarters ahead
+sc = bpy.context.scene
+sc.render.engine = "BLENDER_WORKBENCH"
+sh = sc.display.shading; sh.light = "STUDIO"; sh.color_type = "VERTEX"; sh.show_cavity = True
+for o in skin:
+ o.color = (0.35, 0.35, 0.35, 1)
+sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.578, 0.578, 0.578)
+sc.view_settings.view_transform = "Standard"; sc.render.resolution_x = sc.render.resolution_y = 1024
+cam_d = bpy.data.cameras.new("c"); cam_d.type = "ORTHO"; cam_d.ortho_scale = 2.05
+cam = bpy.data.objects.new("c", cam_d); sc.collection.objects.link(cam); sc.camera = cam
+A, E = math.radians(30), math.radians(6)
+d = Vector((math.sin(A) * math.cos(E), -math.cos(A) * math.cos(E), math.sin(E)))
+cam.location = Vector((0, 0, 0.9)) + d * 10; cam.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler()
+sc.render.filepath = os.path.splitext(out)[0] + ".png"
+bpy.ops.render.render(write_still=True)
+# the glb: the armature and the pieces only
+for o in skin: bpy.data.objects.remove(o)
+for o in [o for o in bpy.data.objects if o.type == "MESH" and o.name.startswith("Icosphere")]: bpy.data.objects.remove(o)
+bpy.ops.object.select_all(action="DESELECT"); arm.select_set(True); ob.select_set(True)
+bpy.ops.export_scene.gltf(filepath=out, use_selection=True, export_skins=True, export_apply=False)
+print(f"wear: {out}: {len(verts)} vertices, {len(faces)} faces on {len(groups)} bones ({', '.join(sorted(groups))})")
diff --git a/tools/garments/wear_fit.py b/tools/garments/wear_fit.py
new file mode 100644
index 00000000..eb8dfa0c
--- /dev/null
+++ b/tools/garments/wear_fit.py
@@ -0,0 +1,134 @@
+# A worn hard piece laid on SOMA (docs/character.feature CH49): Idol's mesh of the dressed mannequin is turned, sized
+# and placed onto the body (the turn searched, then refined against the body's surface), the body is cut away (every
+# face within CUT metres of the skin or inside it), small crumbs are dropped, and each face is given to the bone it lies
+# nearest, so each piece can ride that bone rigidly.
+# python -I tools/garments/wear_fit.py IDOL.glb SOMA_BODY.glb SOMA_SKELETON.json OUT.npz [CUT=0.006] [LIFT=0] [KEY=0]
+# KEY=1: the mannequin was drawn magenta (wear_mannequin.py KEY=1), so faces that come back magenta are bare body and go.
+# CUT: faces nearer the skin than this are the body and go (a negative CUT keeps the whole dressed surface: a full suit).
+# LIFT: what is kept and lies nearer the skin than this is set out to it along the skin's normal, so a close-fitting
+# piece covers the body instead of meeting it.
+# OUT.npz: V (metres, glTF frame), F, C (vertex colours 0..1), bone (each vertex's joint index in the skeleton), and the
+# fit's numbers; a report line is printed as JSON.
+import json, sys
+import numpy as np
+import trimesh, igl
+from scipy.spatial import cKDTree
+
+idol_path, body_path, skel_path, out = sys.argv[1:5]
+CUT = float(sys.argv[5]) if len(sys.argv) > 5 else 0.006
+LIFT = float(sys.argv[6]) if len(sys.argv) > 6 else 0.0
+KEY = len(sys.argv) > 7 and sys.argv[7] == "1"
+
+def load(path, pick=None):
+ sc = trimesh.load(path, force="scene")
+ geoms = [(n, g) for n, g in sc.geometry.items() if isinstance(g, trimesh.Trimesh) and (pick is None or pick(n, g))]
+ parts = []
+ for n, g in geoms:
+ m = g.copy()
+ nodes = sc.graph.geometry_nodes.get(n, [])
+ if nodes: m.apply_transform(sc.graph.get(nodes[0])[0])
+ parts.append(m)
+ return trimesh.util.concatenate(parts)
+
+body = load(body_path, lambda n, g: len(g.vertices) > 5000) # the skin (the eyes are small pieces)
+dressed = load(idol_path)
+skel = json.load(open(skel_path))
+H = skel["height"]
+
+def umeyama(src, dst):
+ ms, md = src.mean(0), dst.mean(0); S, D = src - ms, dst - md
+ U, sv, Vt = np.linalg.svd(D.T @ S / len(src)); d = np.sign(np.linalg.det(U @ Vt)); E = np.diag([1, 1, d])
+ R = U @ E @ Vt; k = np.trace(np.diag(sv) @ E) / (S ** 2).sum() * len(src)
+ return k, R, md - k * R @ ms
+
+rng = np.random.default_rng(7)
+B = body.sample(6000, seed=7) if hasattr(body, "sample") else body.vertices[rng.choice(len(body.vertices), 6000)]
+B = np.asarray(B)
+P0 = np.asarray(dressed.vertices)
+sub = P0[rng.choice(len(P0), min(len(P0), 40000), replace=False)]
+
+def yaw(a):
+ c, s = np.cos(a), np.sin(a)
+ return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
+
+# the start: Idol's mesh stood up to the body's height, its middle on the body's, turned every 10 degrees; the turn whose
+# body points lie nearest the dressed surface is kept
+k0 = H / (P0[:, 1].max() - P0[:, 1].min())
+best = None
+for deg in range(0, 360, 10):
+ R = yaw(np.radians(deg)) * k0
+ Q = sub @ R.T
+ Q += np.array([B[:, 0].mean() - Q[:, 0].mean(), B[:, 1].min() - Q[:, 1].min(), B[:, 2].mean() - Q[:, 2].mean()])
+ d, _ = cKDTree(Q).query(B)
+ score = np.median(d)
+ if best is None or score < best[0]: best = (score, deg)
+_, deg = best
+T_k, T_R = k0, yaw(np.radians(deg))
+T_t = np.zeros(3)
+Q = sub @ (T_k * T_R).T
+T_t = np.array([B[:, 0].mean() - Q[:, 0].mean(), B[:, 1].min() - Q[:, 1].min(), B[:, 2].mean() - Q[:, 2].mean()])
+
+# refined: each body point paired with the nearest dressed point, the nearest 60 per cent kept, the similarity that
+# takes those dressed points onto their body points solved, repeated
+for it in range(40):
+ Q = (T_k * (sub @ T_R.T)) + T_t
+ d, idx = cKDTree(Q).query(B)
+ keep = d <= np.quantile(d, 0.6)
+ k, R, t = umeyama(sub[idx[keep]], B[keep])
+ T_k, T_R, T_t = k, R, t
+Q = (T_k * (P0 @ T_R.T)) + T_t
+d_fit, _ = cKDTree(Q).query(B)
+
+# the body cut away: the signed distance of each dressed vertex to the skin (inside negative)
+sd, _, Cp, _ = igl.signed_distance(Q, np.asarray(body.vertices, dtype=np.float64), np.asarray(body.faces, dtype=np.int64), sign_type=igl.SIGNED_DISTANCE_TYPE_FAST_WINDING_NUMBER)
+lifted = 0
+if LIFT > 0:
+ near = sd < LIFT
+ off = Q[near] - Cp[near]; ln = np.linalg.norm(off, axis=1, keepdims=True)
+ # outward: from the skin's nearest point toward the vertex when outside, away from it when inside
+ nrm = np.where(ln > 1e-9, off / np.maximum(ln, 1e-9), 0) * np.sign(sd[near])[:, None]
+ Q = Q.copy(); Q[near] = Cp[near] + nrm * LIFT; lifted = int(near.sum())
+F = np.asarray(dressed.faces)
+keepf = (sd[F] > CUT).all(1)
+try:
+ cols = np.asarray(dressed.visual.vertex_colors)[:, :3] / 255.0
+except Exception:
+ cols = np.full((len(Q), 3), 0.6)
+keyed = 0
+if KEY:
+ # magenta: red and blue high, green well under both (a garment's purple or pink keeps more green, or less red)
+ mag = (np.minimum(cols[:, 0], cols[:, 2]) > 0.25) & (cols[:, 1] < 0.55 * np.minimum(cols[:, 0], cols[:, 2])) & (np.abs(cols[:, 0] - cols[:, 2]) < 0.35)
+ bare = mag[F].sum(1) >= 2
+ keyed = int((keepf & bare).sum()); keepf &= ~bare
+# crumbs dropped: pieces under 0.5 per cent of what is kept
+faces_kept = F[keepf]
+lab = trimesh.graph.connected_component_labels(trimesh.graph.face_adjacency(faces_kept), node_count=len(faces_kept))
+sizes = np.bincount(lab)
+faces_kept = faces_kept[sizes[lab] >= 0.005 * len(faces_kept)]
+used = np.unique(faces_kept)
+remap = -np.ones(len(Q), int); remap[used] = np.arange(len(used))
+V, Fo, C = Q[used], remap[faces_kept], cols[used]
+
+# each vertex to the bone it lies nearest (the body's bones, not its helpers or bone ends; fingers count as the hand)
+J = skel["joints"]
+names = [j["name"] for j in J]
+def owner(n):
+ if "Twist" in n or n.endswith("End") or n in ("LeftEye", "RightEye", "Jaw"): return None
+ for side in ("Left", "Right"):
+ if n.startswith(side + "Hand") and n != side + "Hand": return side + "Hand"
+ return n
+segs = [(i, np.array(J[i]["head"]), np.array(J[i]["tail"])) for i, n in enumerate(names) if owner(n) == n]
+def seg_d(P, a, b):
+ ab = b - a; t = np.clip(((P - a) @ ab) / max(ab @ ab, 1e-12), 0, 1)
+ return np.linalg.norm(P - (a + t[:, None] * ab), axis=1)
+D = np.stack([seg_d(V, a, b) for _, a, b in segs], 1)
+bone = np.array([segs[i][0] for i in D.argmin(1)])
+# a face goes to the bone most of its corners have, so pieces are whole faces
+fb = bone[Fo]
+fbone = np.where(fb[:, 1] == fb[:, 2], fb[:, 1], fb[:, 0])
+counts = {names[b]: int((fbone == b).sum()) for b in np.unique(fbone)}
+report = {"turned": deg, "scale": round(float(T_k / k0), 4), "body_to_dressed_mm": {"median": round(float(np.median(d_fit) * 1000), 1), "p90": round(float(np.quantile(d_fit, 0.9) * 1000), 1)},
+ "kept_faces": int(len(Fo)), "of": int(len(F)), "cut_m": CUT, "pieces_by_bone": dict(sorted(counts.items(), key=lambda kv: -kv[1])),
+ "inside_skin_after_cut": int((sd[used] < 0).sum()) if LIFT <= 0 else 0, "lifted_vertices": lifted, "keyed_faces": keyed}
+np.savez_compressed(out, V=V.astype(np.float32), F=Fo.astype(np.int32), C=C.astype(np.float32), bone=bone.astype(np.int32), fbone=fbone.astype(np.int32), names=np.array(names))
+print("fit:", json.dumps(report), flush=True)
diff --git a/tools/garments/wear_mannequin.py b/tools/garments/wear_mannequin.py
new file mode 100644
index 00000000..361dbd62
--- /dev/null
+++ b/tools/garments/wear_mannequin.py
@@ -0,0 +1,47 @@
+# The mannequin a worn hard piece is drawn on (docs/character.feature CH49): SOMA's body at rest, flat grey, one view
+# without perspective from three-quarters ahead, the camera written beside it, so the dressed figure Idol makes from
+# the picture can be laid back on the body.
+# raea blender run tools/garments/wear_mannequin.py BODY.glb OUT_DIR [AZ=30] [EL=6] [SIZE=1024] [KEY=0]
+# KEY=1 draws the body flat magenta, for pieces that leave skin bare (a hat, a helmet, a breastplate alone): the image
+# model is told to keep bare parts magenta, and wear_fit.py cuts what comes back that colour.
+import json, math, os, sys
+import bpy
+from mathutils import Vector
+
+a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[-2:]
+src, out = a[0], a[1]
+az, el, size = (float(a[2]) if len(a) > 2 else 30.0), (float(a[3]) if len(a) > 3 else 6.0), (int(a[4]) if len(a) > 4 else 1024)
+key = len(a) > 5 and a[5] == "1"
+os.makedirs(out, exist_ok=True)
+bpy.ops.wm.read_factory_settings(use_empty=True)
+bpy.ops.import_scene.gltf(filepath=src)
+# (the importer adds a 2 m sphere for its bone shapes: dropped, or the frame is set by it)
+for o in [o for o in bpy.data.objects if o.type == "MESH" and o.name.startswith("Icosphere")]:
+ bpy.data.objects.remove(o)
+meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+sc = bpy.context.scene
+sc.render.engine = "BLENDER_WORKBENCH"
+sh = sc.display.shading
+sh.light = "STUDIO"; sh.color_type = "SINGLE"; sh.single_color = (0.42, 0.42, 0.42); sh.show_cavity = True; sh.cavity_type = "BOTH"; sh.show_shadows = False
+if key: sh.single_color = (0.85, 0.0, 0.85); sh.show_cavity = False
+sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.578, 0.578, 0.578)
+sc.view_settings.view_transform = "Standard"
+sc.render.resolution_x = sc.render.resolution_y = size
+dg = bpy.context.evaluated_depsgraph_get()
+pts = [o.matrix_world @ v.co for o in meshes for v in o.evaluated_get(dg).data.vertices]
+lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
+hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
+centre = (lo + hi) / 2
+cam_d = bpy.data.cameras.new("c"); cam_d.type = "ORTHO"; cam_d.ortho_scale = (hi.z - lo.z) * 1.12
+cam = bpy.data.objects.new("c", cam_d); sc.collection.objects.link(cam); sc.camera = cam
+# Blender's frame: z up, the body faces -y. The camera sits ahead of the body, turned `az` degrees to its left, `el` up.
+A, E = math.radians(az), math.radians(el)
+d = Vector((math.sin(A) * math.cos(E), -math.cos(A) * math.cos(E), math.sin(E)))
+cam.location = centre + d * 10
+cam.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler()
+sc.render.filepath = os.path.join(out, "mannequin.png")
+bpy.ops.render.render(write_still=True)
+# the camera in glTF's frame (y up, +z ahead of the body), as the creature flow writes its own
+json.dump({"az": az, "el": el, "centre": [centre.x, centre.z, -centre.y], "ortho_scale": cam_d.ortho_scale, "size": size,
+ "height": hi.z - lo.z, "frame": "glTF: y up, +z the body's ahead, x its left"}, open(os.path.join(out, "mannequin.cam.json"), "w"))
+print("wrote", sc.render.filepath)