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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea clothes: cloth maps, panels in their own colour, and trims (buttons, straps, a belt) on sewn garments
shinyobjectz82a461297d2e
diff --git a/docs/character.feature b/docs/character.featureindex 4e0698c7..7821ee43 100644--- a/docs/character.feature+++ b/docs/character.feature@@ -986,6 +986,25 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generatedThen words make a helmet, a hat or armour that SOMA wears and moves withAnd each piece is its own part on the bone it covers, so pieces mix with sewn garments as layers+ Scenario: CH49a. A sewn garment's cloth, panels and trims+ # A sewn garment was one flat colour, so wool read as vinyl at a close-up, and a uniform had no buttons,+ # straps, belt or collar facing. THE GAMBIT's 1917 greatcoat (M1915 Einheitsmantel) was the first case.+ # 11-17, built in tools/garments (README):+ # - fabric.py: wool, serge, cotton or felt as tileable albedo, normal and roughness maps in the cut's UVs. The+ # UVs are laid flat in metres, so one tile is 1 m of cloth. Each material keeps its colour in its factor.+ # - bake_batch.py PANELS (sew.sh --panels): the pieces a key names (collar, cuff) in a colour of their own,+ # set per face before the seams are welded.+ # - trims.py: buttons, conformed patches (shoulder straps with piping, pocket flaps, a buckle) and a band (a+ # belt), each cast onto the draped cloth from outside. Each is skinned from the nearest cloth vertex and+ # carries the source it is attested by.+ # - glbio.py: rewrites the glb so a cover or trim set made again replaces the last.+ # Open:+ # - `raea clothes make --cloth/--panels/--design` (the CLI and the manual);+ # - embossed detail (a button's crown, a buckle's motto) as a normal map;+ # - a trim on cloth that folds over itself (a turn-down collar's top layer is found, the layer under it not).+ Then a sewn garment can be covered in a named cloth whose weave and fuzz show at a close-up+ And a uniform's buttons, straps, belt and collar facing sit on its cloth and move with it+Scenario: CH50. The people of a place, drawn from its roles# 11-17, sdk/character/src/people (raea/people), for a city's worth of characters (THE GAMBIT's Berlin): a# project lists roles (a profession, a rank in a service, a household part: the share of women, the ages, thediff --git a/tools/garments/README.md b/tools/garments/README.mdindex 1ec6a2d8..2193a1c6 100644--- a/tools/garments/README.md+++ b/tools/garments/README.md@@ -26,6 +26,21 @@ changes settings by path (`design.py`, which checks each against its options orraea's models folder (`garments/`) the first time and calls it (engine/cli/src/sewn.ts); `hide_under.py` leaves outthe body's skin under worn garments for `raea clothes wear`.+ tools/garments/sew.sh OUT_DIR greatcoat "" --design old/design.yaml --set collar.component.depth=8 \+ --colour "#66695a" --panels '{"collar": "#4a5543"}' --cloth wool++- `--design FILE` starts from a saved design (a garment made again with a setting changed) instead of words.+- `--panels` gives the pieces whose names hold a key a colour and material of their own (a uniform's collar in its+ badge cloth); `bake_batch.py` reads it as `PANELS`, set per face before the seams are welded.+- `--cloth wool|serge|cotton|felt` covers the garment in `fabric.py`'s cloth: a tileable weave, fibre fuzz and a+ melange as albedo, normal and roughness maps in the cut's UVs (laid flat in metres, so 1 m of cloth is one tile).+ The colour stays in each material's factor, so a `<MeshStandardMaterial color>` still recolours it. A garment+ already made: `python tools/garments/fabric.py GARMENT.glb wool`.+- `trims.py GARMENT.glb TRIMS.json` adds buttons, straps, flaps and a belt, each cast onto the draped cloth from+ outside and skinned as the cloth under it is (the format is at the top of the script; `--landmarks` prints the+ body's joints to place by). Made again, a set replaces the last; run it after a cover when a trim is in the+ garment's cloth. `glbio.py` reads and rewrites the glb for both.+## Runtools/garments/engine.sh OUT_DIR 24 11 # 24 random designs, seed 11@@ -42,6 +57,7 @@ stretch, cloth inside the skin, and whether it stayed on).- `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`)+- `fabric.py`, `trims.py`, `glbio.py`: cloth maps, trims, and the glb they rewrite (above)- `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 bodydiff --git a/tools/garments/bake_batch.py b/tools/garments/bake_batch.pyindex 8911194d..e03ec22a 100644--- a/tools/garments/bake_batch.py+++ b/tools/garments/bake_batch.py@@ -29,6 +29,10 @@ cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")); sc.collection.obcam.data.type = "ORTHO"; cam.data.ortho_scale = 2.0VIEWS = {"front": (0, -4, 0.95), "threequarter": (2.8, -2.8, 0.95), "side": (4, 0, 0.95), "back": (0, 4, 0.95)}PICS = os.environ.get("PICTURES") == "1"+# PANELS='{"collar": "#4d5a45"}': the pieces whose names hold a key, in that colour as a material of their own (a+# uniform's collar in its badge cloth, cuffs in a facing colour); the rest in COLOUR. Set before the seams are welded,+# while each face still knows its piece (the draped npz's start, the panels json's names)+PANELS = json.loads(os.environ.get("PANELS") or "{}")if PICS: sc.render.image_settings.file_format = "JPEG"; sc.render.image_settings.quality = 88for d in dirs:@@ -43,6 +47,17 @@ for d in dirs: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]+ if PANELS:+ names = [p["name"] for p in json.load(open(os.path.join(d, name + ".panels.json")))["pieces"]]+ piece = np.searchsorted(np.asarray(Z["start"]), np.arange(len(X)), "right") - 1+ keys, hit = list(PANELS), {}+ for fc in bm.faces:+ pn = names[piece[fc.verts[0].index]]+ k = next((i for i, key in enumerate(keys) if key in pn), None)+ if k is not None:+ fc.material_index = k + 1; hit[keys[k]] = hit.get(keys[k], 0) + 1+ for key in keys:+ print(f"bake: {name}: {key} pieces {'in their own colour (%d faces)' % hit[key] if key in hit else 'NOT FOUND among ' + ', '.join(names)}", flush=True)bm.verts.ensure_lookup_table(); targets = {}for i, j in Z["seams"]:i, j = int(i), int(j)@@ -70,6 +85,14 @@ for d in dirs:bsdf.inputs["Base Color"].default_value = (*[x ** 2.2 for x in rgb], 1); bsdf.inputs["Roughness"].default_value = 0.9mat.diffuse_color = (*[x ** 2.2 for x in rgb], 1)me.materials.append(mat)+ extra = []+ for key, c in PANELS.items():+ pm = bpy.data.materials.new(f"{name}-{key}"); pm.use_nodes = True+ prgb = [int(c[i:i + 2], 16) / 255 for i in (1, 3, 5)]+ pb = next(x for x in pm.node_tree.nodes if x.type == "BSDF_PRINCIPLED")+ pb.inputs["Base Color"].default_value = (*[x ** 2.2 for x in prgb], 1); pb.inputs["Roughness"].default_value = 0.9+ pm.diffuse_color = (*[x ** 2.2 for x in prgb], 1)+ me.materials.append(pm); extra.append(pm)if not PICS: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,@@ -82,4 +105,5 @@ for d in dirs: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)+ for pm in extra: bpy.data.materials.remove(pm)print(f"bake: {name}: {len(X)} -> {welded} vertices, {colour}, {time.time() - t0:.1f} s", flush=True)diff --git a/tools/garments/fabric.py b/tools/garments/fabric.pynew file mode 100644index 00000000..ed3fb091--- /dev/null+++ b/tools/garments/fabric.py@@ -0,0 +1,146 @@+# A garment's cloth as textures in its cut's UVs (bake_batch.py lays the pattern's panels flat in metres, the grain+# along v): a tileable weave height (a twill's diagonal ribs, or a plain weave's grid), the fibre fuzz over it, the+# colour as a melange of lighter and darker fibres, and from the height a normal map and a roughness map. Made in+# numpy with periodic noise (filtered in Fourier space), so a 1 m tile repeats with no seam. A metre of cloth is+# SIZE pixels (2048: 2 px a millimetre, a coarse twill's rib at 5 px; at a film's distances a pixel on screen covers+# a millimetre or two of cloth). Kinds:+# wool fulled broadcloth (uniform cloth, greatcoats, women's coats): the twill barely shows under the felted fuzz+# serge a hard-wearing worsted twill (trousers, skirts, tunics): the diagonal shows+# cotton a plain weave (aprons, shirts, headscarves): a fine grid, smoother, less fuzz+# felt no weave at all (hats): fuzz alone+import numpy as np++KINDS = {+ # rib pitch mm, rib height, plain weave?, fuzz, fuzz streak along the warp, melange, roughness lo, hi+ "wool": dict(pitch=2.4, rib=0.18, plain=False, fuzz=0.55, streak=2.5, melange=0.07, r0=0.86, r1=0.99),+ "serge": dict(pitch=2.8, rib=0.65, plain=False, fuzz=0.22, streak=4.0, melange=0.05, r0=0.74, r1=0.92),+ "cotton": dict(pitch=1.2, rib=0.45, plain=True, fuzz=0.12, streak=1.5, melange=0.03, r0=0.80, r1=0.95),+ "felt": dict(pitch=2.0, rib=0.0, plain=False, fuzz=0.85, streak=1.0, melange=0.05, r0=0.90, r1=1.00),+}+++def noise(size, rng, scale_px, beta=2.0, stretch=1.0):+ """Periodic noise: white noise shaped by 1/f^beta above a feature size of `scale_px`, stretched along v+ (rows) by `stretch` (fibres lie along the warp). Zero mean, unit spread."""+ f = np.fft.fftfreq(size)+ fu, fv = np.meshgrid(f, f * stretch)+ r = np.sqrt(fu ** 2 + fv ** 2)+ r[0, 0] = 1+ amp = np.where(r < 1 / scale_px, 1.0, (r * scale_px) ** (-beta / 2))+ amp[0, 0] = 0+ w = rng.standard_normal((size, size)) + 1j * rng.standard_normal((size, size))+ n = np.real(np.fft.ifft2(w * amp))+ return (n - n.mean()) / (n.std() + 1e-9)+++def weave(kind, rgb, size=2048, seed=1):+ """(albedo uint8 HxWx3 sRGB, normal uint8 HxWx3, roughness-metal uint8 HxWx3 as glTF packs it) for 1 m of cloth+ of `kind` in sRGB colour `rgb` (0..1)."""+ k = KINDS[kind]+ rng = np.random.default_rng(seed)+ u, v = np.meshgrid(np.arange(size) / size, np.arange(size) / size)+ ribs = round(1000 / k["pitch"]) # ribs a metre: a whole number, so the tile is seamless+ if k["plain"]:+ h = 0.5 * (np.sin(2 * np.pi * ribs * u) * np.sin(2 * np.pi * ribs * v))+ else: # a 2/2 twill: ribs at 45 degrees, rounded+ h = 0.5 + 0.5 * np.sin(2 * np.pi * ribs * (u + v))+ h = h ** 1.5+ px_mm = size / 1000+ fuzz = noise(size, rng, 0.6 * px_mm, 2.2, k["streak"]) # fibres a little under a millimetre+ clump = noise(size, rng, 6 * px_mm, 2.6, 1.5) # the felting's clumps, a few millimetres+ height = k["rib"] * h + k["fuzz"] * (0.35 * fuzz + 0.2 * clump)+ # the colour: a melange (lighter and darker fibres), darker in the weave's hollows, a faint cloud across the tile+ cloud = noise(size, rng, 120 * px_mm, 3.0, 1.0)+ fib = noise(size, rng, 0.8 * px_mm, 1.6, k["streak"] * 1.5)+ lin = np.asarray(rgb, np.float64) ** 2.2+ shade = 1 + k["melange"] * (1.6 * fib + 0.6 * cloud) - 0.12 * k["rib"] * (1 - h)+ albedo = np.clip(lin[None, None, :] * shade[..., None], 0, 1) ** (1 / 2.2)+ # normal from the height (mm of relief: a rib stands about a tenth of a millimetre)+ relief = height * 0.12+ dx = (np.roll(relief, -1, 1) - np.roll(relief, 1, 1)) / 2 * px_mm+ dy = (np.roll(relief, -1, 0) - np.roll(relief, 1, 0)) / 2 * px_mm+ n = np.dstack([-dx, dy, np.ones_like(dx)])+ n /= np.linalg.norm(n, axis=2, keepdims=True)+ normal = (n * 0.5 + 0.5)+ # rougher on the fuzz and in the hollows, a touch smoother on worn rib tops+ t = np.clip(0.5 + 0.35 * fuzz * k["fuzz"] - 0.25 * (h - 0.5) * k["rib"], 0, 1)+ rough = k["r0"] + (k["r1"] - k["r0"]) * t+ mr = np.dstack([np.zeros_like(rough), rough, np.zeros_like(rough)]) # glTF: G roughness, B metal+ to8 = lambda a: (np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)+ return to8(albedo), to8(normal), to8(mr)+++GREY = 0.8 # a cover's albedo map's mean (linear): a material's baseColorFactor carries the colour over it+++def lin(colour):+ return [(int(colour[i:i + 2], 16) / 255) ** 2.2 for i in (1, 3, 5)]+++def cover(glb, kind, size=2048, seed=None, colour=None):+ """Re-cover a sewn garment's glb (bake_batch.py: its UVs are the cut laid flat in metres) in cloth of `kind`: the+ weave's albedo (a grey melange, the colour kept in baseColorFactor so a <MeshStandardMaterial color> still+ recolours it), normal and roughness maps, 1 m of cloth a tile, repeated. Its own colour unless `colour` (#rrggbb).+ Trims in the garment's cloth (trims.py) keep their colours over the new maps."""+ import io, os, sys, zlib+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ from glbio import Glb+ from PIL import Image+ g = Glb(glb)+ j = g.j+ mats = j.setdefault("materials", [])+ if not mats:+ mats.append({})+ m0 = mats[0]+ if colour:+ own = lin(colour)+ elif m0.get("extras", {}).get("colour"):+ own = lin(m0["extras"]["colour"])+ else:+ f = (m0.get("pbrMetallicRoughness", {}).get("baseColorFactor") or [0.2, 0.2, 0.2, 1])[:3]+ own = [c * GREY for c in f] if "baseColorTexture" in m0.get("pbrMetallicRoughness", {}) else f+ seed = zlib.crc32(os.path.basename(glb).encode()) % 100000 if seed is None else seed+ a, n, r = weave(kind, [GREY ** (1 / 2.2)] * 3, size, seed)+ j.pop("images", None); j.pop("textures", None)+ j["samplers"] = [{"magFilter": 9729, "minFilter": 9987, "wrapS": 10497, "wrapT": 10497}]++ def add(img):+ buf = io.BytesIO()+ Image.fromarray(img).save(buf, "JPEG", quality=92, subsampling=0)+ j.setdefault("textures", []).append({"sampler": 0, "source": g.image(buf.getvalue(), "image/jpeg")})+ return len(j["textures"]) - 1++ ta, tn, tr = add(a), add(n), add(r)+ hexed = lambda c: "#" + "".join(f"{round(255 * x ** (1 / 2.2)):02x}" for x in c)+ def own_of(m): # a panel's own colour (bake_batch.py PANELS): kept, as the garment's is+ ex, pbr = m.get("extras", {}), m.get("pbrMetallicRoughness", {})+ if ex.get("colour"):+ return lin(ex["colour"])+ f = (pbr.get("baseColorFactor") or [0.2, 0.2, 0.2, 1])[:3]+ return [c * GREY for c in f] if "baseColorTexture" in pbr else f+ for i, m in enumerate(mats):+ ex = m.setdefault("extras", {})+ trim = ex.get("trim")+ if trim and not ex.get("cloth"):+ continue+ c = lin(ex["colour"]) if trim else own if i == 0 else own_of(m)+ pbr = m.setdefault("pbrMetallicRoughness", {})+ pbr["baseColorFactor"] = [min(1.0, x / GREY) for x in c] + [1.0]+ pbr["baseColorTexture"] = {"index": ta}+ pbr["metallicRoughnessTexture"] = {"index": tr}+ pbr["metallicFactor"], pbr["roughnessFactor"] = 0.0, 1.0+ m["normalTexture"] = {"index": tn, "scale": 1.0}+ ex["cloth"] = kind+ if not trim:+ ex["colour"] = hexed(c)+ return g.save(glb)++if __name__ == "__main__":+ # python fabric.py GARMENT.glb KIND [--size PX] [--colour #rrggbb] (KIND: wool, serge, cotton or felt)+ import argparse+ ap = argparse.ArgumentParser()+ ap.add_argument("glb"); ap.add_argument("kind", choices=sorted(KINDS))+ ap.add_argument("--size", type=int, default=2048); ap.add_argument("--colour"); ap.add_argument("--seed", type=int)+ x = ap.parse_args()+ size = cover(x.glb, x.kind, x.size, x.seed, x.colour)+ print(f"cloth: {x.glb} covered in {x.kind} ({x.size} px a metre), {size / 1e6:.1f} MB")diff --git a/tools/garments/glbio.py b/tools/garments/glbio.pynew file mode 100644index 00000000..c042bdab--- /dev/null+++ b/tools/garments/glbio.py@@ -0,0 +1,119 @@+# A garment's glb read and rewritten in place (fabric.py's cloth, trims.py's buttons and straps): accessors as numpy+# arrays, new ones and pictures added, and on save the buffer laid out again from what is still referenced, so a+# cover or a set of trims made again replaces the last one instead of piling up behind it.+import json+import struct++import numpy as np++CT = {5120: np.int8, 5121: np.uint8, 5122: np.int16, 5123: np.uint16, 5125: np.uint32, 5126: np.float32}+NC = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}+TYPE = {1: "SCALAR", 2: "VEC2", 3: "VEC3", 4: "VEC4", 16: "MAT4"}+CODE = {np.dtype(v): k for k, v in CT.items()}+++class Glb:+ def __init__(self, path):+ b = open(path, "rb").read()+ assert b[:4] == b"glTF", f"{path}: not a glb"+ n = struct.unpack("<I", b[12:16])[0]+ self.j = json.loads(b[20:20 + n])+ rest = b[20 + n:]+ blob = rest[8:8 + struct.unpack("<I", rest[:4])[0]] if len(rest) >= 8 else b""+ self.views = [blob[v.get("byteOffset", 0):v.get("byteOffset", 0) + v["byteLength"]] for v in self.j.get("bufferViews", [])]+ assert not any("sparse" in a for a in self.j.get("accessors", [])), "sparse accessors aren't read"++ def read(self, i):+ a = self.j["accessors"][i]+ v = self.j["bufferViews"][a["bufferView"]]+ dt, nc = np.dtype(CT[a["componentType"]]), NC[a["type"]]+ raw, off, stride = self.views[a["bufferView"]], a.get("byteOffset", 0), v.get("byteStride", 0) or dt.itemsize * nc+ x = np.ndarray((a["count"], nc), dt, raw, off, (stride, dt.itemsize)).copy()+ if a.get("normalized") and dt.kind in "ui":+ x = x.astype(np.float32) / np.iinfo(dt).max+ return x++ def view(self, data, target=None):+ self.j.setdefault("bufferViews", []).append({"buffer": 0, "byteLength": len(data), **({"target": target} if target else {})})+ self.views.append(bytes(data))+ return len(self.views) - 1++ def accessor(self, arr, target=None, bounds=False):+ arr = np.ascontiguousarray(arr)+ a = arr.reshape(len(arr), -1)+ acc = {"bufferView": self.view(a.tobytes(), target), "componentType": CODE[a.dtype], "count": len(a), "type": TYPE[a.shape[1]]}+ if bounds:+ acc["min"], acc["max"] = a.min(0).tolist(), a.max(0).tolist()+ self.j.setdefault("accessors", []).append(acc)+ return len(self.j["accessors"]) - 1++ def image(self, data, mime):+ self.j.setdefault("images", []).append({"bufferView": self.view(data), "mimeType": mime})+ return len(self.j["images"]) - 1++ def save(self, path):+ j = self.j+ used = sorted({a["bufferView"] for a in j.get("accessors", []) if "bufferView" in a} | {im["bufferView"] for im in j.get("images", []) if "bufferView" in im})+ remap, blob, views = {}, bytearray(), []+ for i in used:+ while len(blob) % 4:+ blob.append(0)+ v = dict(j["bufferViews"][i], byteOffset=len(blob), byteLength=len(self.views[i]), buffer=0)+ remap[i] = len(views)+ views.append(v)+ blob.extend(self.views[i])+ while len(blob) % 4:+ blob.append(0)+ for a in j.get("accessors", []):+ if "bufferView" in a:+ a["bufferView"] = remap[a["bufferView"]]+ for im in j.get("images", []):+ if "bufferView" in im:+ im["bufferView"] = remap[im["bufferView"]]+ j["bufferViews"], j["buffers"] = views, [{"byteLength": len(blob)}]+ self.views = [bytes(blob[v["byteOffset"]:v["byteOffset"] + v["byteLength"]]) for v in views]+ # accessors nothing uses any more (a trim's, dropped) go too, the rest renumbered where meshes and skins name them+ js = json.dumps(j, separators=(",", ":")).encode()+ js += b" " * (-len(js) % 4)+ out = struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(blob))+ out += struct.pack("<II", len(js), 0x4E4F534A) + js + struct.pack("<II", len(blob), 0x004E4942) + bytes(blob)+ open(path, "wb").write(out)+ return len(blob)++ def drop_accessors(self, keep):+ """Keep only the accessors `keep` says (a set of indices), renumbering every reference to them."""+ j = self.j+ old = j.get("accessors", [])+ remap = {i: n for n, i in enumerate(sorted(keep))}+ j["accessors"] = [old[i] for i in sorted(keep)]+ for m in j.get("meshes", []):+ for p in m["primitives"]:+ p["attributes"] = {k: remap[v] for k, v in p["attributes"].items()}+ if "indices" in p:+ p["indices"] = remap[p["indices"]]+ for t in p.get("targets", []):+ for k in t:+ t[k] = remap[t[k]]+ for s in j.get("skins", []):+ if "inverseBindMatrices" in s:+ s["inverseBindMatrices"] = remap[s["inverseBindMatrices"]]+ for an in j.get("animations", []):+ for s in an.get("samplers", []):+ s["input"], s["output"] = remap[s["input"]], remap[s["output"]]++ def used_accessors(self):+ j, used = self.j, set()+ for m in j.get("meshes", []):+ for p in m["primitives"]:+ used |= set(p["attributes"].values())+ if "indices" in p:+ used.add(p["indices"])+ for t in p.get("targets", []):+ used |= set(t.values())+ for s in j.get("skins", []):+ if "inverseBindMatrices" in s:+ used.add(s["inverseBindMatrices"])+ for an in j.get("animations", []):+ for s in an.get("samplers", []):+ used |= {s["input"], s["output"]}+ return useddiff --git a/tools/garments/sew.sh b/tools/garments/sew.shindex a9471002..3a7a3c27 100755--- a/tools/garments/sew.sh+++ b/tools/garments/sew.sh@@ -1,7 +1,10 @@#!/bin/bash# One sewn garment for SOMA (docs/character.feature CH45c): a design from words (the garment model) or from the plain# base, settings changed by path, cut to SOMA, draped on the GPU and baked to a skinned glb. `raea clothes make` runs it.-# tools/garments/sew.sh OUT_DIR NAME "WORDS" [--plain] [--set PATH=VALUE]... [--colour #rrggbb]+# tools/garments/sew.sh OUT_DIR NAME "WORDS" [--plain] [--set PATH=VALUE]... [--colour #rrggbb] [--cloth wool|serge|cotton|felt] [--design FILE] [--panels '{"collar": "#rrggbb"}']+# (--cloth: the cloth's weave, fuzz and sheen as maps in the cut's UVs, fabric.py; without it a plain colour. --design: a+# saved design.yaml to start from, instead of the words or the plain base. --panels: pieces whose names hold a key in+# their own colour, bake_batch.py's PANELS)# Needs GARMENTCODE, GARMENT_PY (README.md), GARMENT_MODEL (the words model, unless --plain) and GARMENT_SDF (the body# as a distance grid, sdf_igl.py); SOMA_BODY is the body it is baked on, GARMENT_MEASURES its measurements in# GarmentCode's terms (soma_measure.py; soma.yaml, the template's, unless given: a body of another build, body.py@@ -15,18 +18,27 @@ SDF=${GARMENT_SDF:-$HOME/.cache/raea-garments/soma_sdf.npz}BODY=${SOMA_BODY:-$HOME/.local/share/raea-models/soma/body/body.glb}MEAS=${GARMENT_MEASURES:-$T/soma.yaml}OUT=${1:?out dir}; n=${2:?name}; words=${3:-}; shift 3 || true-PLAIN=0; SETS=(); COLOUR=+PLAIN=0; SETS=(); COLOUR=; CLOTH=; DESIGN=; PANELS=while [ $# -gt 0 ]; docase "$1" in--plain) PLAIN=1; shift ;;--set) SETS+=("$2"); shift 2 ;;--colour) COLOUR=$2; shift 2 ;;+ --cloth) CLOTH=$2; shift 2 ;;+ --design) DESIGN=$2; shift 2 ;;+ --panels) PANELS=$2; shift 2 ;;*) echo "sew: unknown word $1" >&2; exit 2 ;;esacdoned=$OUT/$n+if [ -n "$DESIGN" ]; then+ [ -f "$DESIGN" ] || { echo "sew: FAILED no design at $DESIGN" >&2; exit 1; }+ held=$(mktemp); cp "$DESIGN" "$held"; trap 'rm -f "$held"' EXIT+firm -rf "${d:?}"; mkdir -p "$d"; printf '%s\n' "$words" > "$d/words.txt"-if [ "$PLAIN" = 1 ]; then+if [ -n "$DESIGN" ]; then+ cp "$held" "$d/design.yaml"+elif [ "$PLAIN" = 1 ]; thencp "$GC/assets/design_params/t-shirt.yaml" "$d/design.yaml"else"$PY" -I "$T/garment_model.py" make "${GARMENT_MODEL:?the words model (garment_model.py train), or --plain}" "$words" "$d" > "$d/make.log"@@ -35,13 +47,14 @@ if [ ${#SETS[@]} -gt 0 ]; then "$PY" -I "$T/design.py" "$d/design.yaml" "$d/desipattern() { (cd "$T" && DESIGN="$d/design.yaml" GID=$n "$PY" -I sample_designs.py "$GC" "$MEAS" "$OUT" 1 1) 2>&1 | grep -E "^sample: " | cut -c1-200 || true; }said=$(pattern)# refused as decoded from words alone (a combination GarmentCode's checks don't allow): the training design nearest the words-if [ ! -f "$d/$n.panels.json" ] && [ "$PLAIN" = 0 ] && [ ${#SETS[@]} -eq 0 ] && [ -f "$d/nearest.yaml" ]; then+if [ ! -f "$d/$n.panels.json" ] && [ "$PLAIN" = 0 ] && [ -z "$DESIGN" ] && [ ${#SETS[@]} -eq 0 ] && [ -f "$d/nearest.yaml" ]; thencp "$d/nearest.yaml" "$d/design.yaml"; echo nearest > "$d/fallback.txt"; said=$(pattern)echo "sew: the design decoded from the words was refused; the nearest design known is used instead"fi[ -f "$d/$n.panels.json" ] || { echo "sew: FAILED the pattern can't be cut: ${said#sample: }" >&2; exit 1; }log=$( (cd "$T" && "$PY" -I drape_mlx.py "$SDF" "$d/$n.panels.json" "$d" 150 -0.064 "$MEAS") 2>&1 ) || { echo "sew: FAILED the drape: $(grep -vE '^\s*$' <<<"$log" | tail -1)" >&2; exit 1; }"$PY" -I -c 'import json,sys; r=json.load(open(sys.argv[1])); g=r["seam_gap_mm"]; print("sew: draped in %.0f s: %s" % (r["seconds"], "it stayed on and every seam closed" if r["ok"] else "FAULT " + ("it slid off" if not r["stayed"] else "a seam is open or cloth is in the skin") + " (seam gap %.0f mm at most)" % g.get("max", 0)))' "$d/$n.drape.json"-COLOUR=$COLOUR "${RAEA_BIN:-raea}" blender run "$T/bake_batch.py" "$BODY" "$d" 2>&1 | grep -E '^bake|Error|Traceback' | sed 's/^bake: /sew: baked /'+COLOUR=$COLOUR PANELS=$PANELS "${RAEA_BIN:-raea}" blender run "$T/bake_batch.py" "$BODY" "$d" 2>&1 | grep -E '^bake|Error|Traceback' | sed 's/^bake: /sew: baked /'[ -f "$d/$n.glb" ] || { echo "sew: FAILED no glb was baked" >&2; exit 1; }+if [ -n "$CLOTH" ]; then "$PY" -I "$T/fabric.py" "$d/$n.glb" "$CLOTH" | sed 's/^cloth: .*covered/sew: covered/'; fiecho "sew: made: $(cat "$d/caption.txt" 2>/dev/null || echo "$n")"diff --git a/tools/garments/trims.py b/tools/garments/trims.pynew file mode 100644index 00000000..34fef61e--- /dev/null+++ b/tools/garments/trims.py@@ -0,0 +1,319 @@+# A sewn garment's trims (buttons, shoulder straps, pocket flaps, a belt) as parts of its glb: each one found on the+# draped cloth by casting toward it from outside, built there as its own small mesh (a domed button, a slab that+# follows the cloth, a band round the body), and skinned as the cloth under it is (each vertex the nearest cloth+# vertex's joints and weights), so it moves with the garment wherever <Character> takes it. A trim set made again+# replaces the last. Run after fabric.py's cover when a trim is in the garment's own cloth (it takes the cloth's maps).+# python tools/garments/trims.py GARMENT.glb TRIMS.json (add --landmarks: the body's joints, to place by)+# TRIMS.json: {"trims": [ ... ]}, every length in metres, in the garment's frame (glTF: y up, the body facing +z; all+# of raea's sewn garments are cut to SOMA's one body, so a place on one is the same place on another). Each trim:+# {"kind": "button", "at": [x, y], "from": "front", "d": 0.022, "material": {...}} from front|back|left|right+# (or "at": [x, y, z] with "from": [dx, dy, dz], the direction it is cast along); "copies": [[dx, dy], ...]+# places more of the same, offset; "mirror": true adds the -x twin of each+# {"kind": "patch", "centre": [x, y, z], "from": [dx, dy, dz], "along": [ux, uy, uz], "size": [length, width],+# "thick": 0.003, "end": "square"|"round"|"point" (the far end along `along`), "piping": {"w": 0.002, ...material},+# "mirror": true, "material": {...}} a shoulder strap, a pocket flap, a collar patch+# "over": metres a button or patch stands further out (on a strap or a belt, not the cloth under it).+# {"kind": "band", "y": 1.0, "h": 0.05, "thick": 0.004, "axis": [x, z], "within": 0.32, "material": {...}}+# round the body at a height, on the outermost cloth nearer the axis than `within` (not the sleeves)+# material: {"colour": "#rrggbb", "metal": 0..1, "rough": 0..1, "cloth": true (the garment's cloth maps under the+# colour)}. Any trim may carry "source": where it is attested (printed, kept in the glb's extras).+import json+import os+import sys++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from glbio import Glb # noqa: E402++LIFT = 0.0008 # off the cloth, so a trim never sinks into it where the cloth's triangles bow out between samples+DIRS = {"front": (0, 0, -1), "back": (0, 0, 1), "left": (-1, 0, 0), "right": (1, 0, 0), "top": (0, -1, 0)}+++def unit(v):+ v = np.asarray(v, np.float64)+ return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-12)+++class Cloth:+ def __init__(self, P, T, N):+ self.P, self.T, self.N = P, T, N+ self.A, self.B, self.C = P[T[:, 0]], P[T[:, 1]], P[T[:, 2]]+ self.e1, self.e2 = self.B - self.A, self.C - self.A++ def hits(self, o, d):+ """Every crossing of the ray o + t d (t > 0): [(t, point, normal)], nearest first (Moller-Trumbore)."""+ p = np.cross(d, self.e2)+ det = (self.e1 * p).sum(1)+ ok = np.abs(det) > 1e-12+ inv = np.where(ok, 1 / np.where(ok, det, 1), 0)+ s = o - self.A+ u = (s * p).sum(1) * inv+ q = np.cross(s, self.e1)+ v = (q * d).sum(1) * inv+ t = (q * self.e2).sum(1) * inv+ k = np.nonzero(ok & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 1e-6))[0]+ out = []+ for i in k[np.argsort(t[k])]:+ w = np.array([1 - u[i] - v[i], u[i], v[i]])+ n = unit((self.N[self.T[i]] * w[:, None]).sum(0))+ if (n * d).sum() > 0: # the side facing where the ray came from+ n = -n+ out.append((t[i], o + t[i] * d, n))+ return out++ def onto(self, at, d):+ """The cloth's first surface met from `at` along `d` (`at` outside it): (point, normal) or None."""+ h = self.hits(np.asarray(at, np.float64), unit(d))+ return (h[0][1], h[0][2]) if h else None+++def dome(p, n, r, h, seg=24):+ """A button: a domed disc of radius r standing h off the cloth at p, facing n."""+ t = unit(np.cross(n, [0, 1, 0] if abs(n[1]) < 0.9 else [1, 0, 0]))+ b = np.cross(n, t)+ rings = [(0.0, h), (0.45, 0.96 * h), (0.78, 0.86 * h), (0.93, 0.74 * h), (1.0, 0.5 * h), (1.0, -0.4 * h)]+ a = np.linspace(0, 2 * np.pi, seg, endpoint=False)+ V, UV = [], []+ for rr, hh in rings:+ for x in a:+ V.append(p + n * (hh + LIFT) + r * rr * (np.cos(x) * t + np.sin(x) * b))+ UV.append([0.5 + 0.5 * rr * np.cos(x), 0.5 + 0.5 * rr * np.sin(x)])+ F = []+ for i in range(len(rings) - 1):+ for k in range(seg):+ a0, a1 = i * seg + k, i * seg + (k + 1) % seg+ F += [[a0, a0 + seg, a1], [a1, a0 + seg, a1 + seg]]+ return np.array(V), np.array(F), np.array(UV)+++def slab(grid_p, grid_n, inside, thick):+ """A slab conformed to the cloth: grid points (nu x nv x 3) and normals where it lies, `inside` (nu x nv) the+ cells' corners kept (a rounded or pointed end leaves some out), standing `thick` off it. Returns V, F, UV+ (UV in metres along the slab, so the garment's cloth maps lie on it at their own scale)."""+ nu, nv = inside.shape+ top = grid_p + grid_n * (LIFT + thick)+ bot = grid_p + grid_n * LIFT * 0.5+ V, UV, idx = [], [], -np.ones((2, nu, nv), int)+ du = np.linalg.norm(np.diff(grid_p, axis=0), axis=2).mean() if nu > 1 else 0+ dv = np.linalg.norm(np.diff(grid_p, axis=1), axis=2).mean() if nv > 1 else 0+ for layer, G in ((0, top), (1, bot)):+ for i in range(nu):+ for k in range(nv):+ if inside[i, k]:+ idx[layer, i, k] = len(V)+ V.append(G[i, k])+ UV.append([k * dv, i * du])+ F = []+ for i in range(nu - 1):+ for k in range(nv - 1):+ q = [idx[0, i, k], idx[0, i + 1, k], idx[0, i + 1, k + 1], idx[0, i, k + 1]]+ if min(q) >= 0:+ F += [[q[0], q[2], q[1]], [q[0], q[3], q[2]]]+ # the edge: wherever a kept corner has an unkept (or no) neighbour, a wall from the top down to the cloth+ def kept(i, k):+ return 0 <= i < nu and 0 <= k < nv and inside[i, k]+ for i in range(nu):+ for k in range(nv):+ for (di, dk) in ((1, 0), (0, 1)):+ i2, k2 = i + di, k + dk+ if not (kept(i, k) and kept(i2, k2)):+ continue+ # the two cells either side of this edge: a wall when only one of them is whole+ if di:+ sides = [all(kept(i + a, k + b) for a in (0, 1) for b in (s, s + 1)) for s in (-1, 0)]+ else:+ sides = [all(kept(i + a, k + b) for a in (s, s + 1) for b in (0, 1)) for s in (-1, 0)]+ if sides[0] == sides[1]:+ continue+ a0, a1, b0, b1 = idx[0, i, k], idx[0, i2, k2], idx[1, i, k], idx[1, i2, k2]+ F += [[a0, b0, a1], [a1, b0, b1]] if sides[1] ^ bool(di) else [[a0, a1, b0], [a1, b1, b0]]+ return np.array(V), np.array(F), np.array(UV)+++def patch_grid(cl, centre, d, along, size, end, res=0.006):+ """Cast a grid over a length x width rectangle at `centre` (length along `along`) down `d` onto the cloth."""+ d = unit(d)+ U = unit(np.asarray(along) - (np.asarray(along) @ d) * d)+ W = np.cross(d, U)+ L, w = size+ nu, nv = max(2, int(np.ceil(L / res)) + 1), max(2, int(np.ceil(w / res)) + 1)+ P = np.zeros((nu, nv, 3)); N = np.zeros((nu, nv, 3)); ok = np.zeros((nu, nv), bool)+ for i in range(nu):+ for k in range(nv):+ u, v = -L / 2 + L * i / (nu - 1), -w / 2 + w * k / (nv - 1)+ # the far end: round (a semicircle of the width) or point (a chevron), cut from the rectangle+ far = u - (L / 2 - w / 2)+ if end == "round" and far > 0 and far ** 2 + v ** 2 > (w / 2) ** 2 + 1e-9:+ continue+ if end == "point" and far > 0 and abs(v) > (w / 2) * (1 - far / (w / 2)) + 1e-9:+ continue+ o = np.asarray(centre) + u * U + v * W - d * 0.4+ h = cl.onto(o, d)+ if h is None:+ continue+ P[i, k], N[i, k], ok[i, k] = h[0], h[1], True+ return P, N, ok+++def band(cl, y, h, thick, axis, within, seg=96):+ """A band round the body: at each angle, the outermost cloth nearer the axis than `within`."""+ rows = 4+ P = np.zeros((rows, seg + 1, 3)); N = np.zeros_like(P); ok = np.zeros((rows, seg + 1), bool)+ for r in range(rows):+ yy = y - h / 2 + h * r / (rows - 1)+ for k in range(seg + 1):+ a = 2 * np.pi * k / seg+ o = np.array([axis[0] + 0.8 * np.cos(a), yy, axis[1] + 0.8 * np.sin(a)])+ hs = cl.hits(o, unit([axis[0] - o[0], 0, axis[1] - o[2]]))+ hs = [x for x in hs if np.hypot(x[1][0] - axis[0], x[1][2] - axis[1]) < within]+ if hs:+ P[r, k], N[r, k], ok[r, k] = hs[0][1], unit(hs[0][2] * [1, 0.3, 1]), True+ # a gap (a ray that met nothing) filled from its neighbours round the ring+ for r in range(rows):+ good = np.nonzero(ok[r])[0]+ if len(good) == 0:+ raise SystemExit(f"trims: no cloth round y={y:.3f} within {within} m of the axis")+ for k in np.nonzero(~ok[r])[0]:+ j = good[np.argmin(np.minimum(np.abs(good - k), seg - np.abs(good - k)))]+ P[r, k], N[r, k] = P[r, j], N[r, j]+ ok[r] = True+ # smooth round the ring (the cloth's folds shouldn't kink a belt pulled tight over them)+ for _ in range(3):+ P[:, 1:-1] = (P[:, :-2] + 2 * P[:, 1:-1] + P[:, 2:]) / 4+ P[:, -1] = P[:, 0]+ return P, N, ok+++def material(spec, base, name):+ c = spec.get("colour", "#808080")+ lin = [(int(c[i:i + 2], 16) / 255) ** 2.2 for i in (1, 3, 5)]+ pbr = base.get("pbrMetallicRoughness", {})+ m = {"name": name, "extras": {"trim": True, "colour": c}}+ if spec.get("cloth") and "baseColorTexture" in pbr:+ m["pbrMetallicRoughness"] = {"baseColorFactor": [min(1, x / 0.8) for x in lin] + [1], "baseColorTexture": pbr["baseColorTexture"],+ "metallicRoughnessTexture": pbr["metallicRoughnessTexture"], "metallicFactor": 0.0, "roughnessFactor": 1.0}+ m["normalTexture"] = base["normalTexture"]+ m["extras"]["cloth"] = base.get("extras", {}).get("cloth", True)+ else:+ m["pbrMetallicRoughness"] = {"baseColorFactor": lin + [1], "metallicFactor": float(spec.get("metal", 0)), "roughnessFactor": float(spec.get("rough", 0.6))}+ return m+++def main():+ if len(sys.argv) < 2:+ raise SystemExit(__doc__ or "trims.py GARMENT.glb TRIMS.json")+ path = sys.argv[1]+ g = Glb(path)+ j = g.j+ if "--landmarks" in sys.argv:+ # the joints' bind-pose places: each joint's world matrix is the inverse of its inverse bind matrix+ sk = j["skins"][0]+ ibm = g.read(sk["inverseBindMatrices"]).reshape(-1, 4, 4).transpose(0, 2, 1)+ for n, m in zip(sk["joints"], ibm):+ w = np.linalg.inv(m)+ name = j["nodes"][n].get("name", n)+ if any(s in name for s in ("Neck", "Spine", "Chest", "Hips", "Shoulder", "Clavicle", "Arm", "Head", "Leg")) and "Twist" not in name:+ print(f"{name:24s} {w[0, 3]:+.3f} {w[1, 3]:+.3f} {w[2, 3]:+.3f}")+ return+ spec = json.load(open(sys.argv[2]))+ mesh = j["meshes"][0]+ # the last trims out: their primitives, materials and accessors+ keep = [p for p in mesh["primitives"] if not p.get("extras", {}).get("trim")]+ mesh["primitives"] = keep+ mats = j.get("materials", [])+ live = [i for i, m in enumerate(mats) if not m.get("extras", {}).get("trim")]+ remap = {o: n for n, o in enumerate(live)}+ j["materials"] = [mats[i] for i in live]+ for p in keep:+ if "material" in p:+ p["material"] = remap[p["material"]]+ g.drop_accessors(g.used_accessors())+ # the cloth is every primitive the garment had (a collar in its own colour is a primitive of its own)+ base = keep[0]+ Ps, Ns, Ts, Js, Ws, at = [], [], [], [], [], 0+ for p in keep:+ Ps.append(g.read(p["attributes"]["POSITION"]).astype(np.float64)); Ns.append(g.read(p["attributes"]["NORMAL"]).astype(np.float64))+ Ts.append(g.read(p["indices"]).reshape(-1, 3).astype(np.int64) + at); at += len(Ps[-1])+ Js.append(g.read(p["attributes"]["JOINTS_0"]).astype(np.uint16)); Ws.append(g.read(p["attributes"]["WEIGHTS_0"]).astype(np.float32))+ P, Nr, T, Jn, Wt = (np.concatenate(x) for x in (Ps, Ns, Ts, Js, Ws))+ cl = Cloth(P, T, Nr)+ from scipy.spatial import cKDTree+ tree = cKDTree(P)+ cloth_mat = j["materials"][base.get("material", 0)] if j.get("materials") else {}+ made = []++ def emit(V, F, UV, mspec, label, src):+ if len(F) == 0:+ print(f"trims: {label}: nothing of it lies on the cloth (missed)")+ return+ V, F = np.asarray(V, np.float64), np.asarray(F, np.int64)+ # normals: area-weighted from the faces+ Nv = np.zeros_like(V)+ fn = np.cross(V[F[:, 1]] - V[F[:, 0]], V[F[:, 2]] - V[F[:, 0]])+ for c in range(3):+ np.add.at(Nv, F[:, c], fn)+ Nv = unit(Nv).astype(np.float32)+ _, nn = tree.query(V)+ j.setdefault("materials", []).append(material(mspec, cloth_mat, label))+ prim = {"attributes": {"POSITION": g.accessor(V.astype(np.float32), 34962, bounds=True), "NORMAL": g.accessor(Nv, 34962),+ "TEXCOORD_0": g.accessor(np.asarray(UV, np.float32), 34962), "JOINTS_0": g.accessor(Jn[nn], 34962),+ "WEIGHTS_0": g.accessor(Wt[nn], 34962)},+ "indices": g.accessor(F.astype(np.uint32).reshape(-1), 34963), "material": len(j["materials"]) - 1,+ "extras": {"trim": label, **({"source": src} if src else {})}}+ mesh["primitives"].append(prim)+ made.append(label)++ for n, t in enumerate(spec["trims"]):+ kind, src = t["kind"], t.get("source", "")+ label = t.get("name", f"{kind}-{n}")+ mirrors = [1, -1] if t.get("mirror") else [1]+ if kind == "button":+ d = DIRS[t["from"]] if isinstance(t["from"], str) else t["from"]+ d = unit(d)+ spots = [t["at"]] + [[t["at"][0] + o[0], t["at"][1] + o[1]] + list(t["at"][2:]) for o in t.get("copies", [])]+ Vs, Fs, UVs = [], [], []+ for sx in mirrors:+ for at in spots:+ at = np.array([sx * at[0], at[1], at[2] if len(at) > 2 else 0.0])+ dd = d * [sx, 1, 1]+ if len(t["at"]) == 2: # from outside along d: start well clear+ at = at - dd * 0.6+ if t["from"] in ("front", "back"):+ at[2] = -dd[2] * 0.6+ h = cl.onto(at, dd)+ if h is None:+ print(f"trims: {label}: no cloth at {np.round(at, 3).tolist()}")+ continue+ V, F, UV = dome(h[0] + h[1] * t.get("over", 0), h[1], t.get("d", 0.022) / 2, t.get("h", t.get("d", 0.022) * 0.18))+ Fs.append(F + sum(len(x) for x in Vs)); Vs.append(V); UVs.append(UV)+ if Vs:+ emit(np.concatenate(Vs), np.concatenate(Fs), np.concatenate(UVs), t.get("material", {}), label, src)+ elif kind == "patch":+ for sx in mirrors:+ c = np.array(t["centre"]) * [sx, 1, 1]+ d = np.array(DIRS[t["from"]] if isinstance(t["from"], str) else t["from"], np.float64) * [sx, 1, 1]+ u = np.array(t["along"], np.float64) * [sx, 1, 1]+ L, w = t["size"]+ if "piping" in t:+ pw = t["piping"].get("w", 0.002)+ Pg, Ng, ok = patch_grid(cl, c, d, u, [L + 2 * pw, w + 2 * pw], t.get("end", "square"))+ V, F, UV = slab(Pg, Ng, ok, t.get("thick", 0.003) * 0.85)+ emit(V, F, UV, t["piping"], f"{label}-piping{'-r' if sx < 0 else ''}", src)+ Pg, Ng, ok = patch_grid(cl, c, d, u, [L, w], t.get("end", "square"))+ V, F, UV = slab(Pg + Ng * t.get("over", 0), Ng, ok, t.get("thick", 0.003))+ emit(V, F, UV, t.get("material", {}), f"{label}{'-r' if sx < 0 else ''}", src)+ elif kind == "band":+ Pg, Ng, ok = band(cl, t["y"], t.get("h", 0.05), t.get("thick", 0.004), t.get("axis", [0, -0.02]), t.get("within", 0.32))+ V, F, UV = slab(Pg.transpose(1, 0, 2), Ng.transpose(1, 0, 2), ok.T, t.get("thick", 0.004))+ emit(V, F, UV, t.get("material", {}), label, src)+ else:+ raise SystemExit(f"trims: {label}: kind {kind} is button, patch or band")+ if src:+ print(f"trims: {label} ({src})")+ size = g.save(path)+ print(f"trims: {len(made)} parts on {os.path.basename(path)} ({size / 1e6:.1f} MB)")+++if __name__ == "__main__":+ main()