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.

CH48a: the garment data engine (tools/garments): random GarmentCode designs cut to SOMA, draped by our own cloth on the GPU with pins at the waist, neck and armpit, skinned, pictured and labelled; CH48 proposed

shinyobjectz8cfb2241c203
diff --git a/docs/character.feature b/docs/character.feature
index cc716c11..92d4f1fa 100644
--- a/docs/character.feature
+++ b/docs/character.feature
@@ -575,3 +575,47 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
shape at build, and kept as a skinned mesh with its flat cut as its UVs
And words become settings (a language model picks components and values), never pictures of the body
And layers drape in order, each over the one beneath, and creatures get their own pattern blocks
+
+ Scenario: CH48. A garment model that dresses SOMA in anything (proposed)
+ # The user's answer to CH47, 11-15: "clothing or what you wear could realistically be anything. I wonder
+ # what we could do if we trained a small model like kimodo did or idol did, build off some existing
+ # weights we ship and create something that builds more intelligently". Patterns make only what is cut
+ # and sewn; armour, shoes, hats, a backpack or a costume are not patterns. Kimodo is good because it
+ # learned in one fixed frame (SOMA's skeleton), so what it makes plays on our body unchanged: the garment
+ # model would make garments in SOMA's rest pose and frame, so fit, skinning and layers come free. The data
+ # comes from CH47a's tools run as an engine (GarmentCode's design sampler across SOMA's shapes, draped by
+ # our cloth on the GPU, rendered from the mannequin's cameras, each example labelled exactly: its design,
+ # its pattern, its 3D on the body, its pictures), plus hard-surface things drawn and made 3D by Idol and
+ # cut from the body. GarmentCodeData itself is not used (draped on SMPL bodies, its licence unconfirmed).
+ # The base weights would be Idol's (Apache-2.0, shipped): one picture of the mannequin dressed in anything
+ # in, the garment alone out, in 3D on SOMA. Idol ships no training code, so its fine-tune is ours to write.
+ Then a garment is made by a model from words or a picture, on SOMA's body, as a layer
+ And the training data is ours, made by our own tools on SOMA, with where each example came from
+ And its cost is said before any training is paid for
+
+ @done
+ Scenario: CH48a. The garment data engine: random designs cut to SOMA, draped on the GPU, pictured, labelled
+ # 11-15, CH48's data half (tools/garments/engine.sh OUT N SEED). GarmentCode's sampler draws a design and
+ # its own checks refuse about 60 per cent; each kept one is cut to SOMA and draped by CH47a's cloth on the
+ # GPU (MLX): the body as a 7 mm signed distance grid signed by winding number (the nearest face's normal
+ # put patches of "inside" in the air above the shoulders), every link solved at once, compiled. The
+ # T-shirt that took 125 s on the CPU takes 7 s with the same seams (0.83 mm median) and stretch. Three
+ # things threw garments off, each found from snapshots of the drape: the cloth was too soft under gravity
+ # (+18 per cent stretch at the 95th percentile with 10 solver passes a substep: armholes opened over the
+ # shoulders; 60 passes give +5); SOMA's bust had been read at the chest's most forward level (81 cm), not
+ # the fullest girth under the arms (89.9), so fitted tops were cut too small; and GarmentCode's own drapes
+ # pin labelled edges to planes (a waistband's top at the waist, a neckline inside the neck's sides, a
+ # strapless top's edge at the armpit), without which gathered waistbands (up to 1.9 times the waist) and
+ # strapless tops fall. Ours are one-sided planes kept on, as elastic, boning or the neck holds them, a
+ # low-rise band pinned between waist and hips by its rise. Then 24 designs from 61 draws all hang right,
+ # 4 to 33 s each (about 7,000 a day on this Mac, $0). Rendered properly, the cloth first looked pebbled:
+ # the bake left it flat-shaded, so its glb had three vertices for every triangle (198,881 for 66,305) and
+ # shaded as facets everywhere it was drawn; smooth, it is one surface. The fabric is also stiffer than
+ # CH47a's (bending 0.3, squash 0.6 against 0.05 and 0.25), which buckled at the mesh's own scale; folds
+ # stay and stretch is +6 per cent at the 95th percentile. An example is its design's settings (the labels), a
+ # caption, the pattern, the flat pieces with seams and edge labels, the draped mesh, a skinned glb, four
+ # pictures on the mannequin and the drape's numbers. Faults: GarmentCode's space is mostly dresses and
+ # skirts (no open-front shirts, jackets, pockets, shoes or hats); one body shape so far; no collision
+ # 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
diff --git a/tools/garments/README.md b/tools/garments/README.md
new file mode 100644
index 00000000..b5be04d3
--- /dev/null
+++ b/tools/garments/README.md
@@ -0,0 +1,36 @@
+# tools/garments: garments from sewing patterns, and the data engine
+
+Garments for SOMA's body made the way clothes are made: flat pieces cut to a pattern, sewn, and draped by gravity
+on the body (docs/character.feature CH47a, CH48a). The patterns come from GarmentCode (ETH Zurich, `pygarment`,
+MIT): garments as programs of components (bodices, sleeves, collars, cuffs, waistbands, trousers, skirts) joined by
+seams and sized from body measurements. The cloth is our own position-based solver on the GPU (MLX).
+
+Not used, on purpose: GarmentCode's simulator (a fork of an old NVIDIA Warp under a non-commercial licence),
+its sample SMPL bodies (research-only) and GarmentCodeData (draped on SMPL, licence unconfirmed).
+
+## Setup, once
+
+ git clone https://github.com/maria-korosteleva/GarmentCode && git -C GarmentCode checkout d449629
+ python3.11 -m venv venv && venv/bin/pip install "numpy<2" scipy pyyaml svgwrite svgpathtools cairosvg \
+ matplotlib cgal trimesh psutil networkx shapely rtree libigl pillow mlx
+ export GARMENTCODE=$PWD/GarmentCode GARMENT_PY=$PWD/venv/bin/python
+
+## Run
+
+ tools/garments/engine.sh OUT_DIR 24 11 # 24 random designs, seed 11
+
+Each `OUT_DIR/<id>/` holds `design.yaml` (the design's settings: the labels), `caption.txt`, GarmentCode's
+pattern, `<id>.panels.json` (flat pieces, their place round the body, seams as vertex pairs, edge labels),
+`<id>.draped.npz`, a skinned `<id>.glb`, four pictures on the mannequin and `<id>.drape.json` (seam gaps,
+stretch, cloth inside the skin, and whether it stayed on).
+
+## The scripts
+
+- `soma_measure.py`: SOMA in GarmentCode's 26 measurements (`soma.yaml`; chest is the fullest girth under the arms)
+- `sample_designs.py`: random designs from GarmentCode's sampler, its own checks, cut to `soma.yaml`
+- `sdf_igl.py`: the body as a 7 mm signed distance grid, signed by winding number
+- `drape_mlx.py`: the cloth (edges at their flat length, seams to a point, pins, pushed out of the skin)
+- `bake_batch.py`: seams welded, the flat cut as UVs, weights from the skin, glb, pictures (`raea blender run`)
+- `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
diff --git a/tools/garments/bake_batch.py b/tools/garments/bake_batch.py
new file mode 100644
index 00000000..48fc8fd6
--- /dev/null
+++ b/tools/garments/bake_batch.py
@@ -0,0 +1,77 @@
+# The garment data engine's last step: each GPU-draped garment (drape_mlx.py) becomes a worn garment and its pictures.
+# The body loads once; per garment: seams welded, the cut as UVs, weights from the skin, skinned to SOMA's armature,
+# exported as <name>.glb, and rendered on the mannequin from four sides (<name>_<view>.png).
+# raea blender run bake_batch.py BODY.glb DIR... (each DIR holds one <name>.draped.npz)
+import bpy, bmesh, sys, os, glob, json, zlib, time
+import numpy as np
+from mathutils import Vector
+
+a = sys.argv[sys.argv.index("--") + 1:]
+body_glb, dirs = a[0], a[1:]
+PALETTE = ["#d9d4c7", "#2f3b52", "#8a3b2f", "#3f5a3c", "#c9a227", "#6b4f7a", "#1f1f1f", "#b8c4cc", "#a85d3d", "#e8e2d6"]
+bpy.ops.wm.read_factory_settings(use_empty=True)
+bpy.ops.import_scene.gltf(filepath=body_glb)
+for o in [o for o in bpy.data.objects if o.type == "MESH" and not any(m.type == "ARMATURE" for m in o.modifiers)]:
+ bpy.data.objects.remove(o)
+skin = max((o for o in bpy.data.objects if o.type == "MESH"), key=lambda o: len(o.data.vertices))
+arm = next(o for o in bpy.data.objects if o.type == "ARMATURE")
+sm = bpy.data.materials.new("skin"); sm.use_nodes = True
+sb = next(x for x in sm.node_tree.nodes if x.type == "BSDF_PRINCIPLED"); sb.inputs["Base Color"].default_value = (0.55, 0.55, 0.57, 1)
+sm.diffuse_color = (0.55, 0.55, 0.57, 1) # Workbench draws the viewport colour, not the node's
+skin.data.materials.clear(); skin.data.materials.append(sm)
+sc = bpy.context.scene
+sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.92, 0.92, 0.9)
+sc.render.engine = "BLENDER_WORKBENCH"; sc.display.shading.light = "STUDIO"; sc.display.shading.color_type = "MATERIAL"
+sc.display.shading.show_cavity = True; sc.render.resolution_x = 512; sc.render.resolution_y = 768
+cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")); sc.collection.objects.link(cam); sc.camera = cam
+cam.data.type = "ORTHO"; cam.data.ortho_scale = 2.0
+VIEWS = {"front": (0, -4, 0.95), "threequarter": (2.8, -2.8, 0.95), "side": (4, 0, 0.95), "back": (0, 4, 0.95)}
+
+for d in dirs:
+ t0 = time.time()
+ src = glob.glob(os.path.join(d, "*.draped.npz"))
+ if not src: print(f"bake: {d}: nothing draped", flush=True); continue
+ Z = np.load(src[0]); name = os.path.basename(src[0])[:-len(".draped.npz")]
+ X = Z["X"].astype(float); X = np.c_[X[:, 0], -X[:, 2], X[:, 1]] # glTF (x, y, z) is Blender (x, -z, y)
+ me = bpy.data.meshes.new(name); me.from_pydata(X.tolist(), [], Z["F"].tolist()); me.update()
+ g = bpy.data.objects.new(name, me); sc.collection.objects.link(g)
+ bm = bmesh.new(); bm.from_mesh(me); uv = bm.loops.layers.uv.new("cut"); FLAT = Z["FLAT"]
+ for fc in bm.faces:
+ for l in fc.loops: l[uv].uv = FLAT[l.vert.index]
+ bm.verts.ensure_lookup_table(); targets = {}
+ for i, j in Z["seams"]:
+ i, j = int(i), int(j)
+ while i in targets: i = targets[i]
+ while j in targets: j = targets[j]
+ if j != i: targets[j] = i
+ bmesh.ops.weld_verts(bm, targetmap={bm.verts[j]: bm.verts[i] for j, i in targets.items()})
+ bmesh.ops.recalc_face_normals(bm, faces=bm.faces); bm.to_mesh(me); bm.free()
+ # smooth: a flat-shaded mesh exports every triangle with its own three vertices (198,881 for 66,305), shading
+ # as facets ("pebbles") wherever it is drawn
+ me.polygons.foreach_set("use_smooth", [True] * len(me.polygons)); me.update()
+ for vg in skin.vertex_groups: g.vertex_groups.new(name=vg.name)
+ for o in bpy.data.objects: o.select_set(o is g)
+ bpy.context.view_layer.objects.active = g
+ dt = g.modifiers.new("weights", "DATA_TRANSFER"); dt.object = skin
+ dt.use_vert_data = True; dt.data_types_verts = {"VGROUP_WEIGHTS"}; dt.vert_mapping = "POLYINTERP_NEAREST"
+ dt.layers_vgroup_select_src = "ALL"; dt.layers_vgroup_select_dst = "NAME"
+ bpy.ops.object.modifier_apply(modifier=dt.name)
+ g.parent = arm; g.modifiers.new("skin", "ARMATURE").object = arm
+ colour = PALETTE[zlib.crc32(name.encode()) % len(PALETTE)]
+ rgb = [int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5)]
+ mat = bpy.data.materials.new(name); mat.use_nodes = True
+ bsdf = next(x for x in mat.node_tree.nodes if x.type == "BSDF_PRINCIPLED")
+ bsdf.inputs["Base Color"].default_value = (*[x ** 2.2 for x in rgb], 1); bsdf.inputs["Roughness"].default_value = 0.9
+ mat.diffuse_color = (*[x ** 2.2 for x in rgb], 1)
+ me.materials.append(mat)
+ for o in bpy.data.objects: o.select_set(o is g or o is arm)
+ bpy.ops.export_scene.gltf(filepath=os.path.join(d, name + ".glb"), export_format="GLB", use_selection=True,
+ export_animations=False, export_yup=True, export_skins=True)
+ for view, loc in VIEWS.items():
+ cam.location = loc; cam.rotation_euler = (Vector((0, 0, 0.95)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+ sc.render.filepath = os.path.join(d, f"{name}_{view}.png"); bpy.ops.render.render(write_still=True)
+ welded = len(me.vertices)
+ json.dump({"name": name, "colour": colour, "views": list(VIEWS), "vertices": welded},
+ open(os.path.join(d, name + ".bake.json"), "w"))
+ bpy.data.objects.remove(g); bpy.data.meshes.remove(me); bpy.data.materials.remove(mat)
+ print(f"bake: {name}: {len(X)} -> {welded} vertices, {colour}, {time.time() - t0:.1f} s", flush=True)
diff --git a/tools/garments/design.py b/tools/garments/design.py
new file mode 100644
index 00000000..df067435
--- /dev/null
+++ b/tools/garments/design.py
@@ -0,0 +1,17 @@
+# A GarmentCode design from a base design and settings by path: the words-to-garment step's output format.
+# python design.py BASE.yaml OUT.yaml meta.upper=Shirt sleeve.length=1.0 collar.component.style=Hood2Panels ...
+import sys, yaml
+
+base, out, *sets = sys.argv[1:]
+d = yaml.safe_load(open(base))
+for s in sets:
+ path, val = s.split("=", 1)
+ node = d["design"]
+ for k in path.split("."):
+ node = node[k]
+ v = yaml.safe_load(val)
+ if "range" in node and node.get("type", "").startswith("select") and v is not None and v not in node["range"]:
+ sys.exit(f"design: {path}={v} is not one of {node['range']}")
+ node["v"] = v
+yaml.safe_dump(d, open(out, "w"), sort_keys=False)
+print("design:", out, " ".join(sets))
diff --git a/tools/garments/drape_mlx.py b/tools/garments/drape_mlx.py
new file mode 100644
index 00000000..99cc60fb
--- /dev/null
+++ b/tools/garments/drape_mlx.py
@@ -0,0 +1,172 @@
+# drape_pbd.py's cloth on the GPU (MLX), for the garment data engine: no Blender in the loop. The body is a signed
+# distance grid (sdf_build.py) instead of a BVH; everything is in glTF's frame (metres, y up, +z ahead).
+# python drape_mlx.py SDF.npz PANELS.json OUT_DIR [FRAMES] [SHIFT_Z_M]
+# env as drape_pbd.py: LIFT 0.07, STRETCH 0.9, SQUASH 0.25, BEND 0.05, SUB 10, ITERS 10, FRICTION 0.4, THICK 0.004,
+# OMEGA 1.7, REACH 0.05 (only cloth less than this deep in the body is pushed out: a deeper point is on the far side)
+# OUT_DIR/<name>.draped.npz holds X (draped, m), F, FLAT (the cut, m), seams, start; <name>.drape.json the report.
+import sys, os, json, time
+import numpy as np
+import mlx.core as mx
+
+sdf_path, panels_path, out_dir = sys.argv[1:4]
+FRAMES = int(sys.argv[4]) if len(sys.argv) > 4 else 150
+SHIFT_Z = float(sys.argv[5]) if len(sys.argv) > 5 else -0.064
+BODY_YAML = sys.argv[6] if len(sys.argv) > 6 else None # the measurements the pattern was cut to: turns the pins on
+E = lambda k, d: float(os.environ.get(k, d))
+LIFT, STRETCH, SQUASH, BEND = E("LIFT", 0.07), E("STRETCH", 0.9), E("SQUASH", 0.6), E("BEND", 0.3) # 0.25 and 0.05 buckled at the mesh scale
+# ITERS 60: at 10 the cloth stretched +18% (p95) under gravity, armholes opened and tops slid off the shoulders; 60 gives +5%
+SUB, ITERS, FRICTION, THICK = int(E("SUB", 10)), int(E("ITERS", 60)), E("FRICTION", 0.4), E("THICK", 0.004)
+OMEGA, REACH = E("OMEGA", 1.7), E("REACH", 0.05)
+os.makedirs(out_dir, exist_ok=True)
+P = json.load(open(panels_path)); NAME = P["name"]
+
+# the body
+S = np.load(sdf_path)
+dims = np.array(S["sdf"].shape); origin = mx.array(S["origin"]); cell = float(S["cell"])
+SDF = mx.array(S["sdf"].ravel()); GRAD = mx.array(S["grad"].reshape(-1, 3))
+hi = mx.array((dims - 1.001).astype(np.float32)); ny, nz = int(dims[1]), int(dims[2])
+
+def body(p):
+ """distance to the skin (negative inside) and the way out, trilinear in the grid"""
+ u = mx.clip((p - origin) / cell, 0, hi)
+ i0 = mx.floor(u); f = u - i0; i0 = i0.astype(mx.int32)
+ s = mx.zeros(p.shape[0]); g = mx.zeros(p.shape)
+ for dx in (0, 1):
+ wx = f[:, 0] if dx else 1 - f[:, 0]
+ for dy in (0, 1):
+ wy = wx * (f[:, 1] if dy else 1 - f[:, 1])
+ for dz in (0, 1):
+ w = wy * (f[:, 2] if dz else 1 - f[:, 2])
+ idx = ((i0[:, 0] + dx) * ny + (i0[:, 1] + dy)) * nz + (i0[:, 2] + dz)
+ s = s + w * mx.take(SDF, idx)
+ g = g + w[:, None] * mx.take(GRAD, idx, axis=0)
+ return s, g / (mx.sqrt(mx.sum(g * g, axis=1, keepdims=True)) + 1e-9)
+
+# the pieces, placed round the body, and the flat cut
+LIFT_LOW = E("LIFT_LOW", 0.01) # skirts, trousers and waistbands start nearer their place than tops
+X, F, FLAT, start = [], [], [], []
+for piece in P["pieces"]:
+ start.append(len(X))
+ lift = LIFT_LOW if piece["name"].startswith(("skirt", "wb", "pant", "level")) else LIFT
+ X += [(p[0] / 100, p[1] / 100 + lift, p[2] / 100 + SHIFT_Z) for p in piece["placed"]]
+ FLAT += [(q[0] / 100, q[1] / 100) for q in piece["flat"]]
+ F += [[start[-1] + i for i in f] for f in piece["faces"]]
+X = np.array(X, np.float32); FLAT = np.array(FLAT, np.float32); F = np.array(F, np.int32); n = len(X)
+seams = np.array([(start[pa] + ia, start[pb] + ib) for pa, ia, pb, ib in P["seams"]], np.int32).reshape(-1, 2)
+seams = seams[seams[:, 0] != seams[:, 1]]
+opp = {}
+for f in F:
+ for k in range(3):
+ i, j, o = int(f[k]), int(f[(k + 1) % 3]), int(f[(k + 2) % 3])
+ opp.setdefault((min(i, j), max(i, j)), []).append(o)
+edges = np.array(list(opp.keys()), np.int32)
+bends = np.array([v for v in opp.values() if len(v) == 2], np.int32).reshape(-1, 2)
+rest_e = np.linalg.norm(FLAT[edges[:, 0]] - FLAT[edges[:, 1]], axis=1)
+rest_b = np.linalg.norm(FLAT[bends[:, 0]] - FLAT[bends[:, 1]], axis=1)
+cnt = np.bincount(np.concatenate([edges.ravel(), bends.ravel(), seams.ravel()]), minlength=n).astype(np.float32)[:, None]
+# pins: one-sided planes on GarmentCode's labelled edges, what elastic, boning or the neck does in a real garment.
+# A waistband (lower_interface) stays at or above the waist, a strapless top's edge at or above the armpit, a neckline
+# no further out than the side of the neck. Always on: the garment is skinned from this drape and must stay put.
+pin_i, pin_p, pin_n = [], [], []
+if BODY_YAML:
+ import yaml
+ b = yaml.safe_load(open(BODY_YAML))["body"]
+ waist_y = (b["height"] - b["head_l"] - b["waist_line"]) / 100
+ waist_y -= (1 - min(1.0, P.get("rise", 1.0))) * b["hips_line"] / 100 # low-rise bottoms sit between waist and hips
+ armpit_y = (b["height"] - b["head_l"] - b["armscye_depth"]) / 100
+ neck_x = (b["neck_w"] - 2) / 200
+ planes = {"lower_interface": ((0, waist_y, 0), (0, 1, 0)), "strapless_top": ((0, armpit_y, 0), (0, 1, 0)),
+ "right_collar": ((-neck_x, 0, 0), (1, 0, 0)), "left_collar": ((neck_x, 0, 0), (-1, 0, 0))}
+ for s, piece in zip(start, P["pieces"]):
+ for label, idx in piece.get("labels", {}).items():
+ if label not in planes: continue
+ for i in idx:
+ pin_i.append(s + i); pin_p.append(planes[label][0]); pin_n.append(planes[label][1])
+PINS = len(pin_i) > 0
+if PINS:
+ pin_i = mx.array(np.array(pin_i, np.int32)); pin_p = mx.array(np.array(pin_p, np.float32)); pin_n = mx.array(np.array(pin_n, np.float32))
+print(f"drape: {NAME}: {n} vertices, {len(edges)} edges, {len(bends)} bends, {len(seams)} seam pairs, "
+ f"{len(pin_p) if PINS else 0} pinned", flush=True)
+
+# every link in one list: edges, bends, seams (rest 0); per link a pull and a push stiffness
+pairs = mx.array(np.concatenate([edges, bends, seams]))
+rest = mx.array(np.concatenate([rest_e, rest_b, np.zeros(len(seams))]).astype(np.float32))
+ne, nb, ns = len(edges), len(bends), len(seams)
+is_seam = mx.array(np.r_[np.zeros(ne + nb), np.ones(ns)].astype(np.float32))
+k_pull0 = mx.array(np.r_[np.full(ne, STRETCH), np.full(nb, BEND), np.zeros(ns)].astype(np.float32))
+k_push0 = mx.array(np.r_[np.full(ne, SQUASH), np.full(nb, BEND * 0.5), np.zeros(ns)].astype(np.float32))
+a, b = pairs[:, 0], pairs[:, 1]
+scale = mx.array(OMEGA / cnt)
+
+def substep(X, V, k_seam, grav, damp):
+ V = V * damp + mx.array([0, -9.81, 0]) * grav * (1 / 60 / SUB)
+ sp = mx.sqrt(mx.sum(V * V, axis=1, keepdims=True)); V = mx.where(sp > 3, V * 3 / (sp + 1e-9), V)
+ p = X + V * (1 / 60 / SUB)
+ kp = k_pull0 + is_seam * k_seam; kq = k_push0 + is_seam * k_seam
+ for _ in range(ITERS):
+ d = p[b] - p[a]; L = mx.sqrt(mx.sum(d * d, axis=1)) + 1e-9
+ c = L - rest
+ corr = (0.5 * mx.where(c > 0, kp, kq) * c / L)[:, None] * d
+ acc = mx.zeros_like(p).at[a].add(corr).at[b].add(-corr)
+ p = p + acc * scale
+ if PINS:
+ q = p[pin_i]; c = mx.sum((q - pin_p) * pin_n, axis=1)
+ p = p.at[pin_i].add(-mx.minimum(c, 0)[:, None] * pin_n)
+ s, nrm = body(p)
+ hit = (s < THICK) & (s > -REACH)
+ p = p + mx.where(hit[:, None], nrm * (THICK - s)[:, None], 0)
+ Vn = (p - X) * (60 * SUB)
+ Vn = mx.where(hit[:, None], Vn * (1 - FRICTION), Vn)
+ return p, Vn
+
+step = mx.compile(substep)
+SEWN = int(FRAMES * 0.45)
+Xm, Vm = mx.array(X), mx.zeros((n, 3))
+ea, eb, re = mx.array(edges[:, 0]), mx.array(edges[:, 1]), mx.array(rest_e.astype(np.float32))
+sa, sb = mx.array(seams[:, 0]), mx.array(seams[:, 1])
+def stats():
+ gap = np.array(mx.sqrt(mx.sum((Xm[sa] - Xm[sb]) ** 2, axis=1))) * 1000
+ strain = np.array(mx.sqrt(mx.sum((Xm[ea] - Xm[eb]) ** 2, axis=1)) / re - 1)
+ return gap, strain
+t0 = time.time(); snaps = {}
+for f in range(1, FRAMES + 1):
+ if os.environ.get("SNAP") and f in (1, SEWN // 2, SEWN, SEWN + 15, SEWN + 40, FRAMES): snaps[f"f{f:03d}"] = np.array(Xm)
+ grav = 0.0 if f < SEWN else min(1.0, (f - SEWN) / 20)
+ k_seam = min(0.6, 0.05 + 0.55 * f / max(1, SEWN // 2))
+ damp = 0.9 if f < SEWN else 0.985
+ ks, gr, dm = mx.array(k_seam, mx.float32), mx.array(grav, mx.float32), mx.array(damp, mx.float32)
+ for _ in range(SUB):
+ Xm, Vm = step(Xm, Vm, ks, gr, dm)
+ mx.eval(Xm, Vm)
+ if f in (1, SEWN // 2, SEWN, FRAMES) or f % 30 == 0:
+ gap, strain = stats()
+ print(f"drape: frame {f}: seam gap mm median {np.median(gap):.1f} p95 {np.percentile(gap, 95):.1f}; edge strain p5 "
+ f"{np.percentile(strain, 5):+.3f} p95 {np.percentile(strain, 95):+.3f}; {time.time() - t0:.1f} s", flush=True)
+
+SMOOTH = int(E("SMOOTH", 0)) # Taubin passes after the drape: takes out buckling at the mesh's own scale, keeps folds
+if SMOOTH:
+ nb = np.concatenate([edges, seams]); deg = np.bincount(nb.ravel(), minlength=n).astype(np.float32)[:, None]
+ na, nbb = mx.array(nb[:, 0]), mx.array(nb[:, 1]); degm = mx.array(np.maximum(deg, 1))
+ def lap(p):
+ acc = mx.zeros_like(p).at[na].add(p[nbb]).at[nbb].add(p[na])
+ return acc / degm - p
+ for _ in range(SMOOTH):
+ Xm = Xm + 0.5 * lap(Xm); Xm = Xm - 0.53 * lap(Xm)
+ s, nrm = body(Xm); Xm = Xm + mx.where(((s < THICK) & (s > -REACH))[:, None], nrm * (THICK - s)[:, None], 0)
+ mx.eval(Xm)
+gap, strain = stats()
+s, _ = body(Xm); inside = int(np.sum(np.array(s) < -0.001))
+Xd = np.array(Xm)
+# stayed: a top still hangs from the shoulders (SOMA's are at 1.45 m), anything else from the waist (1.05 m)
+has_top = any("torso" in p["name"] for p in P["pieces"])
+top_y = float(Xd[:, 1].max()); stayed = top_y > (1.38 if has_top else 0.95)
+ok = bool(np.isfinite(Xd).all() and np.percentile(gap, 95) < 15 and inside < 0.01 * n and stayed)
+np.savez_compressed(os.path.join(out_dir, NAME + ".draped.npz"), X=Xd, F=F, FLAT=FLAT, seams=seams, start=np.array(start))
+if snaps: np.savez_compressed(os.path.join(out_dir, NAME + ".snaps.npz"), start=np.array(start), **snaps)
+report = {"name": NAME, "frames": FRAMES, "vertices": n, "seconds": round(time.time() - t0, 1), "ok": ok,
+ "stayed": bool(stayed), "top_y": round(top_y, 3),
+ "seam_gap_mm": {"median": float(np.median(gap)), "p95": float(np.percentile(gap, 95)), "max": float(gap.max())},
+ "edge_strain": {"p5": float(np.percentile(strain, 5)), "p95": float(np.percentile(strain, 95))},
+ "cloth_vertices_inside_skin": inside}
+json.dump(report, open(os.path.join(out_dir, NAME + ".drape.json"), "w"), indent=1)
+print("drape:", json.dumps(report), flush=True)
diff --git a/tools/garments/engine.sh b/tools/garments/engine.sh
new file mode 100755
index 00000000..15cd35de
--- /dev/null
+++ b/tools/garments/engine.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# 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]
+# 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
+T=$(cd "$(dirname "$0")" && pwd)
+GC=${GARMENTCODE:?a GarmentCode clone, see tools/garments/README.md}
+PY=${GARMENT_PY:?the venv python, see tools/garments/README.md}
+DATA=${GARMENT_DATA:-$HOME/.cache/raea-garments}
+BODY=${SOMA_BODY:-$HOME/.local/share/raea-models/soma/body/body.glb}
+RAEA=${RAEA:-raea}
+OUT=${1:?out dir}; N=${2:?count}; SEED=${3:-1}
+[ -f "$DATA/soma_sdf.npz" ] || "$PY" -I "$T/sdf_igl.py" "$BODY" "$DATA/soma_sdf.npz"
+(cd "$T" && "$PY" -I sample_designs.py "$GC" "$T/soma.yaml" "$OUT" "$N" "$SEED") | grep --line-buffered -v rejected
+for d in "$OUT"/g*/; do
+ n=$(basename "$d")
+ [ -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"
+done
+"$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/grid.py b/tools/garments/grid.py
new file mode 100644
index 00000000..c9b4c472
--- /dev/null
+++ b/tools/garments/grid.py
@@ -0,0 +1,20 @@
+# a compact grid: per garment its front and three-quarter views, cropped to the body, captioned
+# python grid.py OUT.jpg COLS DIR...
+import sys, glob, os, json, textwrap
+from PIL import Image, ImageDraw
+out, cols, dirs = sys.argv[1], int(sys.argv[2]), sys.argv[3:]
+cells = []
+for d in dirs:
+ v = [glob.glob(os.path.join(d, f"*_{k}.png")) for k in ("front", "threequarter")]
+ if not all(v): continue
+ ims = [Image.open(p[0]).convert("RGB").crop((96, 40, 416, 728)).resize((200, 430)) for p in v]
+ cell = Image.new("RGB", (400, 470), "white"); [cell.paste(im, (i * 200, 40)) for i, im in enumerate(ims)]
+ cap = open(os.path.join(d, "caption.txt")).read().strip()
+ r = json.load(open(glob.glob(os.path.join(d, "*.drape.json"))[0]))
+ t = f"{os.path.basename(d.rstrip('/'))}: {cap}" + ("" if r["ok"] else " [FAIL]")
+ ImageDraw.Draw(cell).multiline_text((4, 2), "\n".join(textwrap.wrap(t, 64)[:3]), fill="black" if r["ok"] else "red")
+ cells.append(cell)
+rows = (len(cells) + cols - 1) // cols
+sheet = Image.new("RGB", (cols * 400, rows * 470), "white")
+for i, c in enumerate(cells): sheet.paste(c, ((i % cols) * 400, (i // cols) * 470))
+sheet.save(out, quality=86); print(out, sheet.size)
diff --git a/tools/garments/make_garment.py b/tools/garments/make_garment.py
new file mode 100644
index 00000000..f75b3766
--- /dev/null
+++ b/tools/garments/make_garment.py
@@ -0,0 +1,41 @@
+# A GarmentCode garment for a measured body, written as flat pieces for a drape of our own.
+# python make_garment.py GARMENTCODE_SRC BODY.yaml DESIGN.yaml NAME OUT_DIR [RES_CM]
+# OUT_DIR/NAME_specification.json is GarmentCode's pattern; OUT_DIR/NAME.panels.json is, per piece, its flat
+# vertices (cm, the cut), its triangles and its place around the body (3D, cm, Y up, facing +Z), and the seams as
+# pairs of piece vertices to be sewn together.
+import sys, json
+from pathlib import Path
+import numpy as np, yaml
+
+src, body_yaml, design_yaml, name, out = sys.argv[1:6]
+res = float(sys.argv[6]) if len(sys.argv) > 6 else 1.5
+sys.path.insert(0, src)
+from assets.garment_programs.meta_garment import MetaGarment
+from assets.bodies.body_params import BodyParameters
+from pygarment.meshgen.boxmeshgen import BoxMesh
+
+body = BodyParameters(body_yaml)
+design = yaml.safe_load(open(design_yaml))["design"]
+garment = MetaGarment(name, body, design)
+pattern = garment.assembly()
+if garment.is_self_intersecting(): print(f"{name}: self-intersecting panels")
+folder = Path(pattern.serialize(Path(out), tag="", to_subfolder=False, with_3d=False, with_text=False,
+ view_ids=False, with_printable=False))
+spec = next(folder.glob(f"{name}*specification.json"))
+box = BoxMesh(spec, res)
+box.load()
+
+pieces, index = [], {}
+for pname, panel in box.panels.items():
+ v2 = np.asarray(panel.panel_vertices, dtype=float)
+ v3 = np.asarray(panel.rot_trans_panel(v2), dtype=float)
+ index[pname] = len(pieces)
+ pieces.append({"name": pname, "flat": v2.round(4).tolist(), "placed": v3.round(4).tolist(),
+ "faces": np.asarray(panel.panel_faces, dtype=int).tolist()})
+seams = []
+for locs in box.verts_glob_loc:
+ locs = sorted(set(locs))
+ for a, b in zip(locs, locs[1:]):
+ seams.append([index[a[0]], int(a[1]), index[b[0]], int(b[1])])
+json.dump({"name": name, "units": "cm", "pieces": pieces, "seams": seams}, open(folder / f"{name}.panels.json", "w"))
+print(f"{name}: {len(pieces)} pieces, {sum(len(p['flat']) for p in pieces)} vertices, {len(seams)} seam pairs -> {folder}")
diff --git a/tools/garments/render_pretty.py b/tools/garments/render_pretty.py
new file mode 100644
index 00000000..55f33236
--- /dev/null
+++ b/tools/garments/render_pretty.py
@@ -0,0 +1,64 @@
+# A worn garment rendered to look at: smooth shading, a fabric material, soft studio light, Cycles on the GPU.
+# raea blender run render_pretty.py BODY.glb OUT_DIR DIR... (each DIR holds <name>.glb and <name>.bake.json)
+import bpy, sys, os, glob, json, math
+from mathutils import Vector
+
+a = sys.argv[sys.argv.index("--") + 1:]
+body_glb, out_dir, dirs = a[0], a[1], a[2:]
+os.makedirs(out_dir, exist_ok=True)
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+for eng in ("BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"): # Cycles compiles Metal kernels silently for minutes on first use
+ try: sc.render.engine = eng; break
+ except TypeError: pass
+ee = sc.eevee
+for k, v in (("taa_render_samples", 64), ("use_shadows", True), ("use_raytracing", True), ("use_gtao", True), ("shadow_ray_count", 2)):
+ if hasattr(ee, k): setattr(ee, k, v)
+print("render: engine", sc.render.engine, flush=True)
+sc.render.resolution_x, sc.render.resolution_y = 900, 1350
+sc.view_settings.view_transform = "AgX"; sc.view_settings.look = "AgX - Medium High Contrast"; sc.view_settings.exposure = -0.6
+
+bpy.ops.import_scene.gltf(filepath=body_glb)
+for o in [o for o in bpy.data.objects if o.type == "MESH" and not any(m.type == "ARMATURE" for m in o.modifiers)]:
+ bpy.data.objects.remove(o)
+skin = max((o for o in bpy.data.objects if o.type == "MESH"), key=lambda o: len(o.data.vertices))
+sm = bpy.data.materials.new("mannequin"); sm.use_nodes = True
+b = next(x for x in sm.node_tree.nodes if x.type == "BSDF_PRINCIPLED")
+b.inputs["Base Color"].default_value = (0.5, 0.49, 0.47, 1); b.inputs["Roughness"].default_value = 0.45
+skin.data.materials.clear(); skin.data.materials.append(sm)
+for p in skin.data.polygons: p.use_smooth = True
+
+w = bpy.data.worlds.new("w"); sc.world = w; w.use_nodes = True
+w.node_tree.nodes["Background"].inputs[0].default_value = (0.9, 0.9, 0.88, 1); w.node_tree.nodes["Background"].inputs[1].default_value = 0.35
+bpy.ops.mesh.primitive_plane_add(size=30); floor = bpy.context.object
+fm = bpy.data.materials.new("floor"); fm.use_nodes = True
+fb = next(x for x in fm.node_tree.nodes if x.type == "BSDF_PRINCIPLED"); fb.inputs["Base Color"].default_value = (0.82, 0.81, 0.79, 1); fb.inputs["Roughness"].default_value = 0.9
+floor.data.materials.append(fm)
+def light(name, loc, power, size):
+ l = bpy.data.lights.new(name, "AREA"); l.energy = power; l.size = size
+ o = bpy.data.objects.new(name, l); sc.collection.objects.link(o); o.location = loc
+ o.rotation_euler = (Vector((0, 0, 1.0)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+light("key", (-2.2, -2.6, 3.0), 900, 2.5); light("fill", (2.8, -1.8, 1.6), 260, 3.0); light("rim", (0.8, 3.0, 2.6), 500, 1.5)
+cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")); sc.collection.objects.link(cam); sc.camera = cam
+cam.data.lens = 70; cam.location = (1.55, -4.6, 1.05)
+cam.rotation_euler = (Vector((0, 0, 0.92)) - cam.location).to_track_quat("-Z", "Y").to_euler()
+
+for d in dirs:
+ g = glob.glob(os.path.join(d, "*.glb")); bj = glob.glob(os.path.join(d, "*.bake.json"))
+ if not g or not bj: continue
+ name = os.path.basename(g[0])[:-4]; colour = json.load(open(bj[0]))["colour"]
+ before = set(bpy.data.objects); bpy.ops.import_scene.gltf(filepath=g[0]); new = set(bpy.data.objects) - before
+ cloth = [o for o in new if o.type == "MESH"]
+ rgb = [(int(colour[i:i + 2], 16) / 255) ** 2.2 for i in (1, 3, 5)]
+ m = bpy.data.materials.new(name); m.use_nodes = True
+ p = next(x for x in m.node_tree.nodes if x.type == "BSDF_PRINCIPLED")
+ p.inputs["Base Color"].default_value = (*rgb, 1); p.inputs["Roughness"].default_value = 0.82
+ for k, v in (("Sheen Weight", 0.6), ("Sheen Roughness", 0.4)):
+ if k in p.inputs: p.inputs[k].default_value = v
+ for o in cloth:
+ o.data.materials.clear(); o.data.materials.append(m)
+ for f in o.data.polygons: f.use_smooth = True
+ s = o.modifiers.new("thick", "SOLIDIFY"); s.thickness = 0.0025; s.offset = 1
+ sc.render.filepath = os.path.join(out_dir, name + ".png"); bpy.ops.render.render(write_still=True)
+ print(f"render: {name}", flush=True)
+ for o in new: bpy.data.objects.remove(o)
diff --git a/tools/garments/sample_designs.py b/tools/garments/sample_designs.py
new file mode 100644
index 00000000..7c643b32
--- /dev/null
+++ b/tools/garments/sample_designs.py
@@ -0,0 +1,84 @@
+# The garment data engine's first step: random GarmentCode designs, cut to SOMA's measurements, each a folder with
+# its design (the labels), a caption in words, the pattern and the flat pieces for the drape.
+# python sample_designs.py GARMENTCODE_SRC SOMA.yaml OUT_DIR N [SEED]
+# OUT_DIR/<id>/{design.yaml, caption.txt, <id>_specification.json, <id>.panels.json}
+import sys, json, random, string, traceback
+from pathlib import Path
+import numpy as np, yaml
+
+src, body_yaml, out, N = sys.argv[1], sys.argv[2], Path(sys.argv[3]), int(sys.argv[4])
+seed = int(sys.argv[5]) if len(sys.argv) > 5 else 1
+sys.path.insert(0, src)
+import pygarment as pyg
+from pattern_sampler import assert_param_combinations
+from assets.garment_programs.meta_garment import MetaGarment
+from assets.bodies.body_params import BodyParameters
+from pygarment.meshgen.boxmeshgen import BoxMesh
+
+random.seed(seed); np.random.seed(seed)
+body = BodyParameters(body_yaml)
+sampler = pyg.DesignSampler(str(Path(src) / "assets/design_params/default.yaml"))
+v = lambda d, *p: (lambda n: n["v"])(__import__("functools").reduce(lambda a, k: a[k], p, d))
+
+def caption(d):
+ """the design in plain words, from its settings (a first caption; a picture's caption can join it later)"""
+ words = []
+ up, low, wb = v(d, "meta", "upper"), v(d, "meta", "bottom"), v(d, "meta", "wb")
+ if up:
+ sleeveless = v(d, "sleeve", "sleeveless")
+ sl = "sleeveless" if sleeveless else ("long-sleeved" if v(d, "sleeve", "length") > 0.7 else "short-sleeved")
+ coll = v(d, "collar", "component", "style")
+ neck = {"Hood2Panels": "with a hood", "Turtle": "with a turtle neck", "SimpleLapel": "with lapels"}.get(coll, "")
+ if v(d, "collar", "fc_depth") > 1.0: neck = (neck + " and" if neck else "with") + " a deep neckline"
+ fit = "fitted" if up == "FittedShirt" else ("loose" if v(d, "shirt", "width") > 1.1 else "")
+ if up == "FittedShirt" and v(d, "shirt", "strapless"): sl, neck, sleeveless = "strapless", "", True
+ length = "long" if v(d, "shirt", "length") > 1.4 else ("cropped" if v(d, "shirt", "length") < 1.0 else "")
+ cuff = "with cuffs" if v(d, "sleeve", "cuff", "type") and not sleeveless else ""
+ asym = "asymmetric" if v(d, "left", "enable_asym") else ""
+ words.append(" ".join(x for x in [length, fit, asym, sl, "top", neck, cuff] if x))
+ if low:
+ kind = {"Pants": "trousers", "PencilSkirt": "pencil skirt", "SkirtCircle": "circle skirt", "AsymmSkirtCircle": "asymmetric circle skirt",
+ "GodetSkirt": "godet skirt", "Skirt2": "skirt", "SkirtManyPanels": "panelled skirt", "SkirtLevels": "tiered skirt"}[low]
+ words.append(kind)
+ if wb: words.append("a gathered waistband" if v(d, "waistband", "waist") > 1.15 else "a waistband")
+ return ", ".join(words)
+
+made, tries = 0, 0
+while made < N and tries < N * 20:
+ tries += 1
+ d = sampler.randomize()
+ gid = "g" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
+ try:
+ assert_param_combinations(d)
+ garment = MetaGarment(gid, body, d)
+ garment.assert_total_length()
+ if garment.is_self_intersecting(): raise ValueError("self-intersecting panels")
+ folder = out / gid; folder.mkdir(parents=True, exist_ok=True)
+ pattern = garment.assembly()
+ pattern.serialize(folder, tag="", to_subfolder=False, with_3d=False, with_text=False, view_ids=False, with_printable=False)
+ box = BoxMesh(next(folder.glob(f"{gid}*specification.json")), 1.0); box.load()
+ pieces, index = [], {}
+ for pname, panel in box.panels.items():
+ v2 = np.asarray(panel.panel_vertices, float); v3 = np.asarray(panel.rot_trans_panel(v2), float)
+ index[pname] = len(pieces)
+ labels = {} # GarmentCode's edge labels (lower_interface, right_collar, left_collar, strapless_top) as piece vertices
+ for edge in panel.edges:
+ if getattr(edge, "label", ""):
+ labels.setdefault(edge.label, []).extend(int(i) for i in edge.vertex_range)
+ pieces.append({"name": pname, "flat": v2.round(4).tolist(), "placed": v3.round(4).tolist(),
+ "faces": np.asarray(panel.panel_faces, int).tolist(), "labels": labels})
+ seams = []
+ for locs in box.verts_glob_loc:
+ locs = sorted(set(locs))
+ seams += [[index[a[0]], int(a[1]), index[b[0]], int(b[1])] for a, b in zip(locs, locs[1:])]
+ # the bottoms' rise (1 at the waist, 0 at the hips): where the waistband's pin goes
+ rise = next((float(s.get_rise()) for s in garment.subs if hasattr(s, "get_rise")), 1.0)
+ json.dump({"name": gid, "units": "cm", "rise": rise, "pieces": pieces, "seams": seams}, open(folder / f"{gid}.panels.json", "w"))
+ yaml.safe_dump({"design": d}, open(folder / "design.yaml", "w"), sort_keys=False)
+ (folder / "caption.txt").write_text(caption(d) + "\n")
+ made += 1
+ print(f"sample: {gid} {sum(len(p['flat']) for p in pieces)} vertices, {len(pieces)} pieces: {caption(d)}", flush=True)
+ except BaseException as e: # GarmentCode's IncorrectElementConfiguration is a BaseException
+ if isinstance(e, KeyboardInterrupt): raise
+ print(f"sample: rejected ({type(e).__name__}: {str(e)[:80]})", flush=True)
+print(f"sample: {made} designs from {tries} tries -> {out}")
diff --git a/tools/garments/sdf_igl.py b/tools/garments/sdf_igl.py
new file mode 100644
index 00000000..fafccc88
--- /dev/null
+++ b/tools/garments/sdf_igl.py
@@ -0,0 +1,22 @@
+# SOMA's body as a signed distance grid for the GPU drape, signed by fast winding number (libigl) rather than by the
+# nearest face's normal (sdf_build.py), which put "inside" patches in the air above the shoulders.
+# python sdf_igl.py BODY.glb OUT.npz [CELL_M]
+# Metres, glTF's frame (y up, +z ahead), negative inside; OUT holds origin, cell, sdf (nx, ny, nz), grad (nx, ny, nz, 3).
+import sys, time
+import numpy as np, trimesh, igl
+
+glb, out = sys.argv[1:3]
+cell = float(sys.argv[3]) if len(sys.argv) > 3 else 0.007
+scene = trimesh.load(glb, process=False)
+skin = max(scene.dump() if isinstance(scene, trimesh.Scene) else [scene], key=lambda m: len(m.vertices))
+V = np.asarray(skin.vertices, float); F = np.asarray(skin.faces, np.int64)
+print(f"sdf: skin {len(V)} vertices, y {V[:, 1].min():.3f}..{V[:, 1].max():.3f}, z {V[:, 2].min():.3f}..{V[:, 2].max():.3f}", flush=True)
+lo = np.array([-0.75, -0.05, -0.32]); hi = np.array([0.75, 1.88, 0.34])
+n = np.ceil((hi - lo) / cell).astype(int) + 1
+g = np.stack(np.meshgrid(*[lo[i] + cell * np.arange(n[i]) for i in range(3)], indexing="ij"), -1).reshape(-1, 3)
+t0 = time.time()
+S, _, _, _ = igl.signed_distance(g, V, F, sign_type=igl.SIGNED_DISTANCE_TYPE_FAST_WINDING_NUMBER)
+sdf = S.reshape(n).astype(np.float32)
+grad = np.stack(np.gradient(sdf, cell), axis=-1).astype(np.float32)
+np.savez_compressed(out, origin=lo.astype(np.float32), cell=np.float32(cell), sdf=sdf, grad=grad)
+print(f"sdf: {tuple(int(x) for x in n)} points at {cell * 1000:.0f} mm, inside {int((sdf < 0).sum())}, {time.time() - t0:.0f} s -> {out}")
diff --git a/tools/garments/sheet.py b/tools/garments/sheet.py
new file mode 100644
index 00000000..da8d8328
--- /dev/null
+++ b/tools/garments/sheet.py
@@ -0,0 +1,19 @@
+# a row of pictures per garment, labelled: python sheet.py OUT.jpg DIR...
+import sys, glob, os
+from PIL import Image, ImageDraw
+out, dirs = sys.argv[1], sys.argv[2:]
+rows = []
+for d in dirs:
+ views = [p for v in ("front", "threequarter", "side", "back") for p in glob.glob(os.path.join(d, f"*_{v}.png"))]
+ if not views: continue
+ ims = [Image.open(p).convert("RGB") for p in views]
+ w, h = ims[0].size; row = Image.new("RGB", (w * len(ims), h + 36), "white")
+ for i, im in enumerate(ims): row.paste(im, (i * w, 36))
+ cap = open(os.path.join(d, "caption.txt")).read().strip() if os.path.exists(os.path.join(d, "caption.txt")) else ""
+ rep = glob.glob(os.path.join(d, "*.drape.json")); r = __import__("json").load(open(rep[0])) if rep else {}
+ flag = "" if r.get("ok", True) else " [FAILED: " + ("slid" if not r.get("stayed", True) else "seams/inside") + "]"
+ ImageDraw.Draw(row).text((8, 10), f"{os.path.basename(d.rstrip('/'))}: {cap}{flag}", fill="red" if flag else "black")
+ rows.append(row)
+W = max(r.width for r in rows); sheet = Image.new("RGB", (W, sum(r.height for r in rows)), "white"); y = 0
+for r in rows: sheet.paste(r, (0, y)); y += r.height
+sheet.thumbnail((2048, 100000)); sheet.save(out, quality=88); print(out, sheet.size)
diff --git a/tools/garments/snaps_view.py b/tools/garments/snaps_view.py
new file mode 100644
index 00000000..4467fb2e
--- /dev/null
+++ b/tools/garments/snaps_view.py
@@ -0,0 +1,20 @@
+# the drape's snapshots (drape_mlx.py with SNAP=1) over the body's outline, front and side, one column a snapshot
+# python snaps_view.py SDF.npz SNAPS.npz OUT.png
+import sys
+import numpy as np
+import matplotlib; matplotlib.use("Agg")
+import matplotlib.pyplot as plt
+S = np.load(sys.argv[1]); Z = np.load(sys.argv[2]); out = sys.argv[3]
+sdf, o, c = S["sdf"], S["origin"], float(S["cell"])
+front = (sdf < 0).any(axis=2).T # (y, x)
+side = (sdf < 0).any(axis=0) # (y, z)
+keys = sorted(k for k in Z.files if k.startswith("f")); start = list(Z["start"])
+fig, ax = plt.subplots(2, len(keys), figsize=(3 * len(keys), 8))
+for col, k in enumerate(keys):
+ X = Z[k]; piece = np.searchsorted(start, np.arange(len(X)), side="right") - 1
+ for row, (mask, h, ext) in enumerate([(front, 0, (o[0], o[0] + c * sdf.shape[0])), (side, 2, (o[2], o[2] + c * sdf.shape[2]))]):
+ a = ax[row, col]
+ a.imshow(mask, origin="lower", extent=(*ext, o[1], o[1] + c * sdf.shape[1]), cmap="Greys", alpha=0.35)
+ a.scatter(X[:, h], X[:, 1], s=0.2, c=piece, cmap="tab10", vmin=0, vmax=9)
+ a.set_xlim(*(ext if row else (-0.6, 0.6))); a.set_ylim(0.6, 1.75); a.set_aspect("equal"); a.set_xticks([]); a.set_title(k if row == 0 else "")
+plt.tight_layout(); plt.savefig(out, dpi=90); print(out)
diff --git a/tools/garments/soma.yaml b/tools/garments/soma.yaml
new file mode 100644
index 00000000..e8027199
--- /dev/null
+++ b/tools/garments/soma.yaml
@@ -0,0 +1,27 @@
+body:
+ arm_length: 54.5693
+ arm_pose_angle: 51.2417
+ armscye_depth: 13.1527
+ back_width: 39.0946
+ bum_points: 18.6377
+ bust: 89.9
+ bust_line: 26.2633
+ bust_points: 17.3213
+ crotch_hip_diff: 4.9663
+ head_l: 30.0272
+ height: 175.796
+ hip_back_width: 47.307
+ hip_inclination: 8.382
+ hips: 92.7319
+ hips_line: 27.9755
+ leg_circ: 52.3856
+ neck_w: 18.5
+ shoulder_incl: 22.1574
+ shoulder_w: 35.5
+ underbust: 74.3795
+ vert_bust_line: 23.2466
+ waist: 73.2455
+ waist_back_width: 33.8168
+ waist_line: 35.1364
+ waist_over_bust_line: 41.4579
+ wrist: 16.907
diff --git a/tools/garments/soma_measure.py b/tools/garments/soma_measure.py
new file mode 100644
index 00000000..f85fdf00
--- /dev/null
+++ b/tools/garments/soma_measure.py
@@ -0,0 +1,128 @@
+# SOMA's body measured in GarmentCode's terms (docs/Body Measurements GarmentCode.pdf), in cm.
+# python soma_measure.py BODY.glb SKELETON.json NEUTRAL.yaml OUT.yaml
+# Girths are convex-hull perimeters of the torso's horizontal slice (a tape measure lies over hollows).
+# The geodesic lengths (waist_line, bust lines) are read along the body's back or front midline profile.
+# What isn't measured here is the neutral body's value scaled by height, and printed as such.
+import json, sys, math
+import numpy as np, trimesh, yaml
+from scipy.spatial import ConvexHull
+
+glb, skel_path, neutral_path, out = sys.argv[1:5]
+scene = trimesh.load(glb, process=False)
+meshes = list(scene.geometry.values()) if isinstance(scene, trimesh.Scene) else [scene]
+body = max(meshes, key=lambda m: len(m.vertices))
+V = np.asarray(body.vertices)
+J = {j["name"]: np.array(j["head"]) for j in json.load(open(skel_path))["joints"]}
+neutral = yaml.safe_load(open(neutral_path))["body"]
+
+def polys(y):
+ sec = body.section(plane_origin=[0, y, 0], plane_normal=[0, 1, 0])
+ if sec is None: return []
+ out = []
+ for ent in sec.discrete: # closed loops in 3D
+ out.append(np.asarray(ent)[:, [0, 2]])
+ return out
+
+def hull_perim(p):
+ h = ConvexHull(p); q = p[h.vertices]
+ return float(np.sum(np.linalg.norm(q - np.roll(q, 1, axis=0), axis=1)))
+
+def torso(y):
+ """the loop at height y around x=0 (the torso), or None"""
+ best = None
+ for p in polys(y):
+ if len(p) < 8: continue
+ if p[:, 0].min() < 0 < p[:, 0].max():
+ if best is None or len(p) > len(best): best = p
+ return best
+
+H = V[:, 1].max() - V[:, 1].min(); floor = V[:, 1].min()
+m = {}
+m["height"] = H * 100
+nape = J["Neck1"][1]
+m["head_l"] = (V[:, 1].max() - nape) * 100
+
+# waist: the narrowest torso girth between the hips joint and the chest joint
+ys = np.linspace(J["Hips"][1] + 0.03, J["Chest"][1], 40)
+g = [(hull_perim(t), y) for y in ys if (t := torso(y)) is not None]
+waist, waist_y = min(g); m["waist"] = waist * 100
+# bust: the torso girth at the chest's most forward level, below the armpits
+ys = np.linspace(J["Chest"][1] - 0.08, J["Chest"][1] + 0.12, 40)
+front = []
+for y in ys:
+ t = torso(y)
+ if t is None: continue
+ if t[:, 0].max() - t[:, 0].min() > 0.45: continue # the arms joined in: above the armpit
+ front.append((t[:, 1].max(), y, hull_perim(t), t))
+fz, bust_y, bust, bt = max(front, key=lambda r: r[0])
+# the girth is the chest at its fullest, under the arms, as a tailor takes it: on a man that is above the most forward
+# level (SOMA: 89.9 cm against 81 there), and a fitted top cut to the smaller one is squeezed down off the chest.
+# bust_y stays at the forward level, where the darts aim.
+full = max(front, key=lambda r: r[2]); m["bust"] = full[2] * 100; bt = full[3] # back_width is read there too
+ub = torso(bust_y - 0.07); m["underbust"] = hull_perim(ub) * 100
+# hips: the widest girth between the crotch and the hips joint, where the slice is still one loop
+crotch_y = V[(np.abs(V[:, 0]) < 0.01) & (V[:, 1] > 0.5), 1].min()
+for y in []:
+ t = torso(y)
+ if t is None or not (t[:, 0].min() < -0.03 and t[:, 0].max() > 0.03 and len(polys(y)) >= 1 and abs(t[:, 0].mean()) < 0.02):
+ crotch_y = y; break
+ loops = [p for p in polys(y) if len(p) > 8 and p[:, 0].max() - p[:, 0].min() > 0.08]
+ if len(loops) >= 2: crotch_y = y; break
+ys = np.linspace(crotch_y + 0.01, J["Hips"][1], 30)
+g = [(hull_perim(t), y, t) for y in ys if (t := torso(y)) is not None]
+hips, hip_y, ht = max(g, key=lambda r: r[0]); m["hips"] = hips * 100
+m["hips_line"] = (waist_y - hip_y) * 100
+m["crotch_hip_diff"] = (hip_y - crotch_y) * 100
+wt = torso(waist_y)
+m["hip_inclination"] = math.degrees(math.atan2(ht[:, 0].max() - wt[:, 0].max(), waist_y - hip_y))
+# back widths: the hull's back half between the balance lines (the slice's x extremes)
+def back_width(t):
+ h = ConvexHull(t); q = t[h.vertices]
+ zc = (q[np.argmin(q[:, 0]), 1] + q[np.argmax(q[:, 0]), 1]) / 2
+ seg = 0.0
+ for a, b in zip(q, np.roll(q, -1, axis=0)):
+ if a[1] < zc and b[1] < zc: seg += np.linalg.norm(a - b)
+ elif a[1] < zc or b[1] < zc: seg += 0.5 * np.linalg.norm(a - b)
+ return seg * 100
+m["waist_back_width"], m["back_width"], m["hip_back_width"] = back_width(wt), back_width(bt), back_width(ht)
+# thigh: the largest single-leg loop just under the crotch
+legs = []
+for y in np.linspace(crotch_y - 0.01, crotch_y - 0.08, 8):
+ for p in polys(y):
+ if len(p) > 8 and p[:, 0].mean() > 0.02: legs.append(hull_perim(p))
+m["leg_circ"] = max(legs) * 100
+# arm: shoulder joint to wrist, and its angle down from the horizontal
+sh, el, wr = J["LeftArm"], J["LeftForeArm"], J["LeftHand"]
+m["arm_length"] = float(np.linalg.norm(wr - sh)) * 100
+d = el - sh; m["arm_pose_angle"] = math.degrees(math.atan2(-d[1], abs(d[0])))
+# wrist: the loop of a plane across the forearm at the wrist
+n = (wr - el) / np.linalg.norm(wr - el)
+sec = body.section(plane_origin=wr - n * 0.01, plane_normal=n)
+loops = [np.asarray(e) for e in sec.discrete]
+lp = min(loops, key=lambda l: np.linalg.norm(l.mean(axis=0) - wr))
+basis = np.linalg.svd(lp - lp.mean(axis=0))[2][:2]
+m["wrist"] = hull_perim((lp - lp.mean(axis=0)) @ basis.T) * 100
+# shoulders and neck
+m["shoulder_w"] = 2 * abs(sh[0]) * 100
+nt = torso(J["Neck2"][1])
+m["neck_w"] = (nt[:, 0].max() - nt[:, 0].min()) * 100
+top = lambda x: V[(np.abs(V[:, 0] - x) < 0.01) & (np.abs(V[:, 2] - sh[2]) < 0.05), 1].max()
+x0, x1 = m["neck_w"] / 200, abs(sh[0])
+
+m["vert_bust_line"] = (nape - bust_y) * 100
+# geodesics along the midline profiles
+def profile(x, y0, y1, side):
+ pts = []
+ for y in np.linspace(y0, y1, 60):
+ sel = V[(np.abs(V[:, 0] - x) < 0.012) & (np.abs(V[:, 1] - y) < 0.006)]
+ if len(sel): pts.append([y, sel[:, 2].max() if side > 0 else sel[:, 2].min()])
+ p = np.array(pts); return float(np.sum(np.linalg.norm(np.diff(p, axis=0), axis=1))) * 100
+m["waist_line"] = (nape - waist_y) * 100 * 1.06 # vertical, plus the back's curve
+
+scale = m["height"] / neutral["height"]
+for k, v in neutral.items():
+ if k not in m:
+ m[k] = v * scale; print(f"scaled from the neutral body: {k}")
+for k in sorted(m): print(f"{k:22s} SOMA {m[k]:7.2f} neutral {neutral[k]:7.2f}")
+yaml.safe_dump({"body": {k: round(float(v), 4) for k, v in sorted(m.items())}}, open(out, "w"))
+print("wrote", out)