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
CH45c: raea clothes make sews; the picture-measured garments are gone. make NAME ["WORDS"] [--plain] [--set PATH=VALUE,...] [--colour] makes a sewn garment in the project (a GarmentCode pattern from the words model or the plain base, settings changed by path and checked, cut to SOMA, draped by our cloth, baked: tools/garments/sew.sh, engine/cli/src/sewn.ts, which sets up raea's models folder the first time); settings lists the settings; wear takes sewn garments beside ones laid on the skin and leaves out the skin under them (hide_under.py). Taken out: make by four drawn pictures, remeasure, the mannequin's views (wardrobe.ts's drawing, garment.py's measure, mannequin.py). A tee and trousers by settings in 18 and 28 s, $0, walk as clothes on the generated person. With the earlier garment session's nearest-design fallback (garment_model.py, words.sh, sheet.py).
shinyobjectzab0fc62c4c6e
diff --git a/docs/character.feature b/docs/character.featureindex f1b252bd..f932c8ff 100644--- a/docs/character.feature+++ b/docs/character.feature@@ -710,6 +710,30 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated# garment a call; an outfit is several calls, innermost first.Then a garment is made by one command from words or by procedure, and an outfit is worn by one more+ @done+ Scenario: CH45c. `raea clothes make` sews; the picture-measured garments are gone+ # 11-15 night. `raea clothes make NAME ["WORDS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB]` makes a+ # sewn garment (CH47a's patterns, CH48c's model) in the project: assets/clothes/NAME.json (kind "sewn") and+ # assets/clothes/NAME/ (the glb, the design, the flat pattern, four pictures). The design is the garment+ # model's from the words, or GarmentCode's plain base with --plain or no words; each --set changes one of its+ # 122 settings by path, checked against its options or range (a wrong one says what is allowed);+ # `raea clothes settings` lists them. The first use sets up raea's models folder (garments/): GarmentCode+ # cloned at a fixed commit and checked by it, a Python 3.11 environment made by uv from a pinned list, SOMA's+ # body as a distance grid. `wear` takes sewn garments beside ones laid on the skin: each sewn glb is copied+ # and the skin under it left out (tools/garments/hide_under.py). Measured before building: the model alone+ # is not enough ("a short-sleeved t-shirt" came out an open flared tunic with ruffled cuffs, "straight+ # trousers" knee-length culottes, colours by chance), so the settings are the control and the words a first+ # guess. A tee and trousers by settings, 18 and 28 seconds, $0, worn with the generated head and walked+ # (sheet3d compositions/soma_sewn.tsx): they read as clothes, with a cut, a hem and folds. Taken out: `make`+ # by four drawn pictures measured onto the skin, `remeasure`, the mannequin's views (wardrobe.ts's drawing,+ # tools/clothes/garment.py's measure, mannequin.py); a garment measured that way is refused by `wear` with+ # what to do instead. `cover` stays for what is skin-tight. Wrong still: an outer garment is draped on the+ # bare body (the trousers' waistband shows through the tee's hem); trousers at length 0.9 drag on the+ # floor; a sewn garment is skinned in motion, not simulated (CH44); the words model is not fetched by a+ # release yet (only this machine's models folder has one).+ Then a garment is sewn by one command from words or from settings, for nothing, and worn by one more+ And no garment is measured from pictures any more+Scenario: CH45. From words to a wardrobeThen `raea` takes a description of an outfit, draws its layers and views, builds the garments, and writesthem beside the body, saying what each picture cost; the pictures are kept with the garment as its sourcediff --git a/docs/manual/reference/cli/clothes.md b/docs/manual/reference/cli/clothes.mdindex f476c384..eb45e115 100644--- a/docs/manual/reference/cli/clothes.md+++ b/docs/manual/reference/cli/clothes.md@@ -12,7 +12,7 @@ Clothes for SOMA's body from words: make has an image model (flux_2_pro, one pic## Usage```sh-raea clothes [make NAME "WHAT IT IS, AS WORN" [--over UNDER[,UNDER...]] [--max-cents N] | remeasure NAME | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)+raea clothes [make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.@@ -22,24 +22,28 @@ Headless: it needs nothing running and opens no window. Takes any number of argu| Flag | Takes | What it does || --- | --- | --- || `--body` | `DIR` | With `wear`: dress this SOMA body folder (body.glb, skeleton.json) instead of SOMA's own, such as a headless body that a generated head joins at the collar. |-| `--colour` | `#RRGGBB` | With `cover`: the garment's one colour. |+| `--colour` | `#RRGGBB` | The garment's one colour. With `make` it is optional: one is picked from the name unless said. || `--head` | `HEAD_DIR` | With `wear`: the head folder (head.json, head.glb) that joins a headless body at the collar. The body's skin takes the head's neck colour and is graded to the head's own skin just under the collar, so no step of colour shows at the join. |-| `--max-cents` | `N` | With `make`: the most one of the four pictures may cost, in cents (10 unless said). |-| `--over` | `UNDER` | With `make`: draw the garment over garments already made, innermost first, comma-separated, as the next layer. With `cover`: lay it over one garment, a layer's thickness off it. |+| `--over` | `UNDER` | With `cover`: lay it over one garment made by `cover`, a layer's thickness off it. || `--parts` | `PART` | With `cover`: the body's parts the garment covers, comma-separated; a limb takes a share, how far along it from its top (`foreArm:0.5` is the half nearest the elbow). |+| `--plain` | – | With `make`: start from the plain base (a short-sleeved top) instead of a pattern guessed from words. The default when no words are given. |+| `--set` | `PATH=VALUE,...` | With `make`: change settings of the garment's pattern by path, comma-separated (`sleeve.length=0.9,meta.bottom=Pants`). A choice must be one of its options and a number within its range; `raea clothes settings` lists them. || `--stand` | `MM` | With `cover`: how far the cloth stands off the skin, in millimetres (6 unless said). |<!-- generated:end -->-## An outfit, layer by layer+## An outfit```sh-raea clothes cover tee --parts chest,torso,waist,upperArm:0.45 --colour "#e8e4da"-raea clothes cover shorts --parts hips,thigh:0.55 --colour "#2b3a55" --stand 7-raea clothes make overshirt "a red and black buffalo-check flannel overshirt, worn open" --over tee,shorts-raea clothes wear assets/characters/flannel tee shorts overshirt+raea clothes make tee --plain --set shirt.length=1.5 --colour "#e8e2d6"+raea clothes make trousers --set meta.upper=none,meta.bottom=Pants,meta.wb=StraightWB,pants.length=0.8 --colour "#2f3b52"+raea clothes wear assets/characters/dressed trousers tee```-The first two are made by procedure and cost nothing. The third has an image model draw the mannequin's four views over the first two, one picture a view (about 20 cents), and measures them onto SOMA's vertices; look at its pictures in `assets/clothes/overshirt/views` before you wear it. `wear` writes a body folder and prints the lines that put it in a composition: `registerBody` with the folder, and each garment's `.glb` as one of `<Character>`'s `parts`.+`make` sews a garment: a sewing pattern (flat pieces joined by seams) cut to SOMA's measurements, draped on the body by gravity and baked to a skinned glb. It costs nothing and takes about 20 seconds. The pattern comes from the plain base (a short-sleeved top) with `--plain` or when no words are given, and each `--set PATH=VALUE` changes one of its settings; `raea clothes settings` lists them all with what each may be. Given words (`raea clothes make hoodie "a hooded sweatshirt"`), the pattern is the garment model's first guess from them; the command says what it made, and `--set` corrects it.-A garment is a file on SOMA's template vertices, so the same file dresses every SOMA body. It lies on the skin at a measured stand-off: cloth that hangs free of the body (a skirt, a coat's tails, a shirt hanging over the hips) is not made by this command yet.+The first use sets up what sewing runs on in raea's models folder (`garments/`): GarmentCode's pattern components (MIT) at a fixed commit, a Python 3.11 environment made by `uv`, and SOMA's body as a distance grid for the drape.++A sewn garment is `assets/clothes/NAME.json` with its files in `assets/clothes/NAME/`: the glb, the design, the flat pattern and four pictures of it on the mannequin. Look at the pictures before you wear it.++`cover` lays a garment on the skin by procedure, for what is skin-tight; it can't hang free. `wear` writes a body folder with each garment's glb and the body without the skin that is wholly under cloth; with `--head`, the body's skin is graded to the head at the collar.diff --git a/engine/cli/conformance/clothes.test.ts b/engine/cli/conformance/clothes.test.tsindex 97b56d71..f58e779e 100644--- a/engine/cli/conformance/clothes.test.ts+++ b/engine/cli/conformance/clothes.test.ts@@ -1,11 +1,11 @@-// `raea clothes`: what the command sends the host for a garment made from words or garments put on a body (docs/-// character.feature CH45), and what it refuses before anything is drawn or paid for. The host (src/wardrobe.ts, which-// runs Blender and the image model) is faked: this is the command's side.+// `raea clothes`: what the command sends the host for a garment sewn from words or settings, one made by procedure,+// or garments put on a body (docs/character.feature CH45c), and what it refuses before anything is made. The host+// (src/wardrobe.ts and sewn.ts, which run the sewing tools and Blender) is faked: this is the command's side.import { describe, expect, test } from "bun:test";import { clothesVerb } from "../src/clothes.ts";/** clothesVerb with a host that keeps each op it was asked and answers as the host does */-function run(args: string[], garments: { name: string; layer: number; vertices: number; over?: string }[] = []) {+function run(args: string[], garments: { name: string; layer: number; vertices?: number; over?: string; sewn?: string }[] = []) {const ops: Record<string, unknown>[] = [];const ask = (op: string, b: Record<string, unknown>) => {expect(op).toBe("clothes");@@ -17,15 +17,18 @@ function run(args: string[], garments: { name: string; layer: number; vertices:describe("raea clothes", () => {test("alone, it lists the project's garments, and says how to make one when there are none", () => {- expect(run([]).out).toContain('raea clothes make NAME "what it is, as worn"');- const { out } = run(["list"], [{ name: "tee-jeans", layer: 0, vertices: 11873 }, { name: "bomber", layer: 1, vertices: 6120, over: "tee-jeans" }]);- expect(out).toBe("tee-jeans layer 0, 11873 of SOMA's vertices\nbomber layer 1, 6120 of SOMA's vertices, over tee-jeans\n");+ expect(run([]).out).toContain('raea clothes make NAME "what it is"');+ const { out } = run(["list"], [{ name: "shorts", layer: 0, vertices: 769 }, { name: "bomber", layer: 1, vertices: 6120, over: "shorts" }, { name: "trousers", layer: 0, sewn: "trousers, a waistband" }]);+ expect(out).toBe("shorts layer 0, 769 of SOMA's vertices\nbomber layer 1, 6120 of SOMA's vertices, over shorts\ntrousers sewn: trousers, a waistband\n");});- test("make sends the name, the words, the layer under it and the most a picture may cost", () => {- const { ops } = run(["make", "bomber", "an olive bomber jacket, zipped", "--over", "tee-jeans", "--max-cents", "8"]);- expect(ops).toEqual([{ op: "make", name: "bomber", words: "an olive bomber jacket, zipped", over: "tee-jeans", cents: 8 }]);- expect(run(["make", "tee", "a white tee"]).ops[0]).toMatchObject({ over: undefined, cents: 10 });+ test("make sends the name, the words or the plain base, the settings changed and the colour", () => {+ const { ops } = run(["make", "hoodie", "a hooded sweatshirt", "--set", "sleeve.length=0.9, shirt.length=1.6", "--colour", "3f5a3c"]);+ expect(ops).toEqual([{ op: "make", name: "hoodie", words: "a hooded sweatshirt", set: ["sleeve.length=0.9", "shirt.length=1.6"], plain: false, colour: "#3f5a3c" }]);+ expect(run(["make", "tee", "--plain"]).ops[0]).toEqual({ op: "make", name: "tee", words: undefined, set: [], plain: true, colour: undefined });+ expect(run(["make", "trousers", "--set", "meta.upper=none,meta.bottom=Pants"]).ops[0]).toMatchObject({ words: undefined, plain: true, set: ["meta.upper=none", "meta.bottom=Pants"] });+ expect(run(["make", "tee", "--plain", "a white tee"]).ops[0]).toMatchObject({ words: undefined, plain: true });+ expect(run(["settings"]).ops).toEqual([{ op: "settings" }]);});test("cover sends the parts, the colour and the stand-off in metres, for a garment with no picture", () => {@@ -42,12 +45,12 @@ describe("raea clothes", () => {test("what doesn't fit is said before anything is drawn", () => {const refused = (args: string[], says: string) => expect(() => run(args)).toThrow(says);- refused(["make", "tee"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');- refused(["make", "tee", "a white tee", "and more"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');+ refused(["make", "tee"], "say what tee is, or make it from the plain base");+ refused(["make", "tee", "a white tee", "and more"], 'raea clothes make NAME ["WHAT IT IS"]');refused(["make", "../tee", "a white tee"], "a garment's name is letters, digits, - and _");- refused(["make", "tee", "a white tee", "--over", "a b"], "--over a b: name garments already made");- expect(run(["make", "jacket", "a denim jacket", "--over", "tee,shorts"]).ops[0]).toMatchObject({ over: "tee,shorts" });- refused(["make", "tee", "a white tee", "--max-cents", "0"], "--max-cents takes the most one picture may cost");+ refused(["make", "tee", "a white tee", "--set", "sleeve length 3"], "--set sleeve length 3: a setting is PATH=VALUE");+ refused(["make", "tee", "a white tee", "--colour", "white"], "--colour white: a colour is #RRGGBB");+ refused(["settings", "tee"], "raea clothes settings takes nothing after it");refused(["cover", "tee", "--parts", "chest"], "raea clothes cover NAME --parts");refused(["cover", "tee", "--parts", "belly", "--colour", "#ffffff"], "--parts: no part belly");refused(["cover", "tee", "--parts", "shin:1.5", "--colour", "#ffffff"], "a share is how far along the limb");diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 4ffb3348..93a20962 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -134,8 +134,8 @@ pub fn run(args: &[String]) -> R<String> {// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usagelet usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");- // clothes for SOMA's body from words (docs/character.feature CH45): engine/cli/src/clothes.ts and wardrobe.ts- let usage = format!("{usage}\n raea clothes [make NAME \"WHAT IT IS, AS WORN\" [--over UNDER[,UNDER...]] [--max-cents N] | remeasure NAME | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");+ // clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts+ let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);diff --git a/engine/cli/src/clothes.ts b/engine/cli/src/clothes.tsindex 24227a30..dd66b8e0 100644--- a/engine/cli/src/clothes.ts+++ b/engine/cli/src/clothes.ts@@ -1,18 +1,19 @@-// `raea clothes`: clothes for SOMA's body from words (raea docs/character.feature CH40 to CH45). make has an image-// model dress the mannequin's four views, one view a call, and measures the pictures onto SOMA's template vertices-// (a garment rides any SOMA body); wear puts garments on a body, innermost first. The work is the host's (op-// "clothes": engine/cli/src/wardrobe.ts on the native raea); this file reads the words and says what was done.+// `raea clothes`: clothes for SOMA's body (raea docs/character.feature CH45c). make sews a garment: a pattern from+// words (the garment model's first guess) or from the plain base, any setting changed by path, cut to SOMA, draped+// and baked; cover makes one by procedure on the skin; wear puts garments on a body. The work is the host's (op+// "clothes": engine/cli/src/wardrobe.ts and sewn.ts on the native raea); this file reads the words and says what+// was done.type Ask = (op: string, args: Record<string, unknown>) => any;/** the body's parts a garment made by procedure covers (tools/clothes/garment.py's PARTS) */export const PARTS = ["chest", "foot", "foreArm", "hand", "head", "hips", "neck", "shin", "thigh", "toes", "torso", "upperArm", "waist"];-export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their pictures in assets/clothes/NAME/)-raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER[,UNDER...]] [--max-cents N] (drawn over the garments named; N: the most one picture may cost, 10 unless said)-raea clothes remeasure NAME (measured again from its kept pictures, after raea's measuring changed: nothing drawn or paid for)-raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] (by procedure, no picture: ${PARTS.join(", ")}; a limb's share is how far along it from its top, foreArm:0.5)-raea clothes wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said; HEAD_DIR: the head that joins a headless body, whose skin the body's is graded to at the collar)+export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their files in assets/clothes/NAME/)+raea clothes make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] (a sewn garment: its pattern from the words, or from the plain base with --plain or no words; each PATH=VALUE changes one setting)+raea clothes settings (a sewn garment's settings: each path, its value in the plain base, what it may be)+raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] (by procedure on the skin: ${PARTS.join(", ")}; a limb's share is how far along it from its top, foreArm:0.5)+raea clothes wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said; HEAD_DIR: the head that joins a headless body, whose skin is graded to it at the collar)`;const flagOf = (args: string[], name: string) => {@@ -29,25 +30,23 @@ export function clothesVerb(ask: Ask, args: string[]): string {switch (sub) {case undefined:case "list": {- const gs: { name: string; layer: number; vertices: number; over?: string }[] = q("list").garments;- if (!gs.length) return 'No garments yet. raea clothes make NAME "what it is, as worn" makes one.\n';- return gs.map((g) => `${g.name} layer ${g.layer}, ${g.vertices} of SOMA's vertices${g.over ? `, over ${g.over}` : ""}`).join("\n") + "\n";+ const gs: { name: string; layer: number; vertices?: number; over?: string; sewn?: string }[] = q("list").garments;+ if (!gs.length) return 'No garments yet. raea clothes make NAME "what it is" sews one.\n';+ return gs.map((g) => (g.sewn !== undefined ? `${g.name} sewn: ${g.sewn}` : `${g.name} layer ${g.layer}, ${g.vertices} of SOMA's vertices${g.over ? `, over ${g.over}` : ""}`)).join("\n") + "\n";}case "make": {- const [name, words, ...more] = plain(rest);- if (!name || !words || more.length) throw new Error(`raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER] [--max-cents N]\n${CLOTHES_USAGE}`);+ const plainBase = rest.includes("--plain"), [name, words, ...more] = plain(rest.filter((x) => x !== "--plain"));+ if (!name || more.length) throw new Error(`raea clothes make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB]\n${CLOTHES_USAGE}`);if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);- const over = flagOf(rest, "--over"), cents = Number(flagOf(rest, "--max-cents") ?? 10);- if (over !== undefined && !over.split(",").every((o) => NAME.test(o))) throw new Error(`--over ${over}: name garments already made, innermost first, with commas between (raea clothes lists them)`);- if (!(cents > 0)) throw new Error("--max-cents takes the most one picture may cost, in cents");- return q("make", { name, words, over, cents }).said;- }- case "remeasure": {- const [name, ...more] = plain(rest);- if (!name || more.length) throw new Error(`raea clothes remeasure NAME (measured again from its kept pictures; nothing is drawn or paid for)\n${CLOTHES_USAGE}`);- if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);- return q("remeasure", { name }).said;+ const set = flagOf(rest, "--set")?.split(",").map((x) => x.trim()).filter(Boolean) ?? [], colour = flagOf(rest, "--colour");+ for (const x of set) if (!/^[a-z][a-z0-9_.-]*=[^=]+$/i.test(x)) throw new Error(`--set ${x}: a setting is PATH=VALUE, sleeve.length=0.3 (raea clothes settings lists them)`);+ if (colour !== undefined && !/^#?[0-9a-f]{6}$/i.test(colour)) throw new Error(`--colour ${colour}: a colour is #RRGGBB`);+ if (!words && !plainBase && !set.length) throw new Error(`say what ${name} is, or make it from the plain base: --plain, --set PATH=VALUE,...\n${CLOTHES_USAGE}`);+ return q("make", { name, words: plainBase ? undefined : words, set, plain: plainBase || !words, colour: colour === undefined ? undefined : colour.startsWith("#") ? colour : `#${colour}` }).said;}+ case "settings":+ if (rest.length) throw new Error(`raea clothes settings takes nothing after it\n${CLOTHES_USAGE}`);+ return q("settings").said;case "cover": {const [name, ...more] = plain(rest);const parts = flagOf(rest, "--parts"), colour = flagOf(rest, "--colour"), over = flagOf(rest, "--over"), mm = Number(flagOf(rest, "--stand") ?? 6);diff --git a/engine/cli/src/sewn.ts b/engine/cli/src/sewn.tsnew file mode 100644index 00000000..5074c04f--- /dev/null+++ b/engine/cli/src/sewn.ts@@ -0,0 +1,117 @@+// Sewn garments for `raea clothes` (docs/character.feature CH45c): a garment is a sewing pattern (GarmentCode's+// components, MIT) cut to SOMA's measurements, draped on the body by raea's own cloth on the GPU and baked to a+// skinned glb, by tools/garments/sew.sh. Its design comes from words (the garment model, when raea's models folder+// has one) or from the plain base, with any setting changed by path. A project's sewn garment is+// assets/clothes/NAME.json (kind "sewn") with its files in assets/clothes/NAME/.+//+// What it runs on, in raea's models folder under garments/ (or named by GARMENTCODE, GARMENT_PY, GARMENT_MODEL):+// GarmentCode at a fixed commit (cloned the first time and checked by that commit), a Python 3.11 environment made+// by uv from a pinned list, the body as a distance grid (made once from SOMA's body), and the words model.+import { spawnSync } from "node:child_process";+import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join, relative } from "node:path";++type Env = Record<string, string | undefined>;++const GARMENTCODE = "d449629979028123a5c4dc9e732a2ec19b7fce31";+/** the environment's packages, as the first one was made (uv pip freeze), less what they bring with them */+const PACKAGES = ["numpy==1.26.4", "scipy==1.17.1", "pyyaml==6.0.3", "svgwrite==1.4.3", "svgpathtools==1.8.0", "cairosvg==2.9.1", "matplotlib==3.11.2", "cgal==6.0.1.post202410241521", "trimesh==5.2.1", "psutil==7.2.2", "networkx==3.6.1", "shapely==2.2.0", "rtree==1.4.1", "libigl==2.6.3", "pillow==13.0.0", "mlx==0.32.4", "onnxruntime==1.32.0", "tokenizers==0.23.3"];++export type Sewn = { name: string; kind: "sewn"; layer: number; words: string; made: string; colour: string; set: string[]; plain: boolean; glb: string; vertices: number; ok: boolean };++const run = (cmd: string, args: string[], env?: Env) => spawnSync(cmd, args, { encoding: "utf8", maxBuffer: 64 << 20, env: env as NodeJS.ProcessEnv });+const tail = (r: { stdout?: string; stderr?: string }) => `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-6).join("\n");++/** tools/garments: in RAEA_HOME, beside a release's bin/raea (share/raea/tools), or in the tree a built raea is in */+function tools(raea: string, env: Env): string {+ const bin = dirname(realpathSync(raea));+ const found = [env.RAEA_HOME && join(env.RAEA_HOME, "tools/garments"), join(bin, "../share/raea/tools/garments"), join(bin, "../../tools/garments")].find((p) => p && existsSync(join(p, "sew.sh")));+ if (!found) throw new Error(`no tools/garments/sew.sh beside ${bin} (a release keeps it in share/raea/tools/garments)`);+ return found;+}++/** What sewing runs on, set up the first time; `made` says what was fetched or built */+function setup(raea: string, env: Env, models: string, body: string): { env: Env; model: string | undefined; made: string[] } {+ const dir = join(models, "garments"), made: string[] = [], t = tools(raea, env);+ const gc = env.GARMENTCODE ?? join(dir, "GarmentCode"), py = env.GARMENT_PY ?? join(dir, "venv/bin/python");+ if (!existsSync(join(gc, "assets/design_params/t-shirt.yaml"))) {+ mkdirSync(dir, { recursive: true });+ rmSync(gc, { recursive: true, force: true });+ const c = run("git", ["clone", "--quiet", "https://github.com/maria-korosteleva/GarmentCode", gc]);+ if (c.status !== 0) throw new Error(`couldn't fetch GarmentCode (the sewing patterns): ${tail(c)}`);+ const o = run("git", ["-C", gc, "checkout", "--quiet", GARMENTCODE]), at = run("git", ["-C", gc, "rev-parse", "HEAD"]).stdout?.trim();+ if (o.status !== 0 || at !== GARMENTCODE) {+ rmSync(gc, { recursive: true, force: true });+ throw new Error(`GarmentCode has no commit ${GARMENTCODE}; nothing was kept`);+ }+ made.push(`fetched GarmentCode (MIT) at ${GARMENTCODE.slice(0, 7)}: ${gc}`);+ }+ if (!existsSync(py)) {+ const venv = dirname(dirname(py));+ const v = run("uv", ["venv", "--quiet", "--python", "3.11", venv]);+ if (v.error) throw new Error("sewing needs uv to make its Python environment (https://docs.astral.sh/uv: brew install uv), or GARMENT_PY naming one that has tools/garments/README.md's packages");+ if (v.status !== 0) throw new Error(`couldn't make the sewing environment: ${tail(v)}`);+ const p = run("uv", ["pip", "install", "--quiet", "--python", py, ...PACKAGES]);+ if (p.status !== 0) {+ rmSync(venv, { recursive: true, force: true });+ throw new Error(`couldn't install the sewing environment's packages: ${tail(p)}`);+ }+ made.push(`made the sewing environment (Python 3.11, ${PACKAGES.length} packages): ${venv}`);+ }+ const sdf = join(dir, "soma_sdf.npz");+ if (!existsSync(sdf)) {+ mkdirSync(dir, { recursive: true });+ const r = run(py, ["-I", join(t, "sdf_igl.py"), join(body, "body.glb"), sdf]);+ if (r.status !== 0 || !existsSync(sdf)) throw new Error(`couldn't measure SOMA's body for the drape: ${tail(r)}`);+ made.push(`measured SOMA's body as a distance grid for the drape: ${sdf}`);+ }+ const model = env.GARMENT_MODEL ?? join(dir, "garment-words.npz");+ return { env: { ...env, GARMENTCODE: gc, GARMENT_PY: py, GARMENT_SDF: sdf, SOMA_BODY: join(body, "body.glb"), RAEA_BIN: raea, PATH: `${dirname(realpathSync(raea))}:${env.PATH ?? ""}` }, model: existsSync(model) ? model : undefined, made };+}++/** every setting of a design: its path, its value in the plain base, what it may be */+export function settings(raea: string, env: Env, models: string, body: string): { said: string } {+ const s = setup(raea, env, models, body), r = run(s.env.GARMENT_PY!, ["-I", join(tools(raea, env), "design.py"), join(s.env.GARMENTCODE!, "assets/design_params/t-shirt.yaml")]);+ if (r.status !== 0) throw new Error(tail(r));+ return { said: [...s.made, "A sewn garment's settings, as the plain base has them (raea clothes make NAME --plain --set PATH=VALUE,...):", r.stdout.trim()].join("\n") + "\n" };+}++/** One sewn garment made in the project: assets/clothes/NAME.json and assets/clothes/NAME/ */+export function sew(raea: string, cwd: string, env: Env, models: string, body: string, a: { name: string; words?: string; set?: string[]; plain?: boolean; colour?: string; layer?: number }): { said: string } {+ const s = setup(raea, env, models, body), clothes = join(cwd, "assets/clothes"), own = join(clothes, a.name), file = join(clothes, `${a.name}.json`);+ const plain = a.plain || !a.words;+ if (!plain && !s.model) throw new Error(`no words model here yet (${join(models, "garments/garment-words.npz")}): make it from the plain base, raea clothes make ${a.name} --plain --set PATH=VALUE,... (raea clothes settings lists the settings)`);+ mkdirSync(clothes, { recursive: true });+ const args = [clothes, a.name, a.words ?? "", ...(plain ? ["--plain"] : []), ...(a.set ?? []).flatMap((x) => ["--set", x]), ...(a.colour ? ["--colour", a.colour] : [])];+ const r = run("bash", [join(tools(raea, env), "sew.sh"), ...args], { ...s.env, ...(s.model ? { GARMENT_MODEL: s.model } : {}) });+ const lines = `${r.stdout ?? ""}`.split("\n").filter((l) => l.startsWith("sew: ")).map((l) => l.slice(5));+ if (r.status !== 0 || !existsSync(join(own, `${a.name}.glb`))) {+ const why = `${r.stderr ?? ""}`.split("\n").filter((l) => l.startsWith("sew: FAILED") || l.startsWith("design: ")).map((l) => l.replace(/^(sew: FAILED |design: )/, "")).join("; ");+ if (!existsSync(file)) rmSync(own, { recursive: true, force: true }); // (nothing half-made left beside the project's garments)+ throw new Error(`${a.name} wasn't sewn: ${why || tail(r)}`);+ }+ const bake = JSON.parse(readFileSync(join(own, `${a.name}.bake.json`), "utf8")) as { colour: string; vertices: number };+ const drape = JSON.parse(readFileSync(join(own, `${a.name}.drape.json`), "utf8")) as { ok: boolean };+ const made = existsSync(join(own, "caption.txt")) ? readFileSync(join(own, "caption.txt"), "utf8").trim() : a.name;+ // (the drape's working files are not the garment: its pattern, its design and its pictures are kept)+ for (const f of [`${a.name}.draped.npz`, `${a.name}.panels.json`, "make.log", "nearest.yaml"]) rmSync(join(own, f), { force: true });+ const g: Sewn = { name: a.name, kind: "sewn", layer: a.layer ?? 0, words: a.words ?? "", made, colour: bake.colour, set: a.set ?? [], plain, glb: `${a.name}/${a.name}.glb`, vertices: bake.vertices, ok: drape.ok };+ writeFileSync(file, `${JSON.stringify(g, null, 1)}\n`);+ return {+ said: [...s.made, ...lines, `${relative(cwd, file)}, its pictures in ${relative(cwd, own)} (${a.name}_front.png ...): look at them, and change it with --set (raea clothes settings).`, `raea clothes wear assets/characters/NAME ${a.name} puts it on SOMA's body.`].join("\n") + "\n",+ };+}++/** Sewn garments put on a body folder already written at `out`: each one's glb beside the body, and the body's skin+ * wholly under them left out (tools/garments/hide_under.py); the lines said */+export function wearSewn(raea: string, cwd: string, env: Env, out: string, files: string[]): string[] {+ const glbs = files.map((f) => {+ const g = JSON.parse(readFileSync(f, "utf8")) as Sewn, to = join(out, `${g.name}.glb`);+ copyFileSync(join(dirname(f), g.glb), to);+ return to;+ });+ const body = join(out, "body.glb"), r = run(raea, ["blender", "run", join(tools(raea, env), "hide_under.py"), body, body, ...glbs]);+ const said = `${r.stdout ?? ""}${r.stderr ?? ""}`.split("\n").filter((l) => l.startsWith("hide_under: ")).map((l) => `the body under ${files.length > 1 ? "the sewn garments" : "the sewn garment"}: ${l.slice(12)}`);+ if (r.status !== 0 || !said.length) throw new Error(`couldn't leave out the skin under the sewn garments: ${tail(r)}`);+ return [...glbs.map((g) => `wore ${relative(cwd, g)}`), ...said];+}diff --git a/engine/cli/src/wardrobe.ts b/engine/cli/src/wardrobe.tsindex e35cbed4..568089d8 100644--- a/engine/cli/src/wardrobe.ts+++ b/engine/cli/src/wardrobe.ts@@ -1,14 +1,16 @@// The host's side of `raea clothes` (clothes.ts) on the native raea. SOMA-X's two body files are fetched once at a// fixed commit (NVlabs/SOMA-X, Apache-2.0, checked by their SHA-256 and kept with the licence in raea's models-// folder, soma/), SOMA's body and the mannequin's views are made from them once by Blender (tools/clothes/body.py,-// mannequin.py), each view is dressed by `raea gen image`, and garments are measured and worn by-// tools/clothes/garment.py. A project's garments are assets/clothes/NAME.json, with their pictures in-// assets/clothes/NAME/.+// folder, soma/) and SOMA's body is made from them once by Blender (tools/clothes/body.py). A garment is sewn+// (sewn.ts: a pattern cut to SOMA, draped and baked) or made by procedure on the skin (tools/clothes/garment.py+// cover); both are worn by `wear`. A project's garments are assets/clothes/NAME.json, their files in+// assets/clothes/NAME/. (Garments measured from four drawn pictures were taken out on 11-15: paint on a+// skin-tight shell showed no cut, hem or fold, and four pictures never agreed.)import { spawnSync } from "node:child_process";import { createHash } from "node:crypto";-import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from "node:fs";import { basename, dirname, isAbsolute, join, relative } from "node:path";import { gradeToHead } from "./grade";+import { settings, sew, wearSewn } from "./sewn";type Env = Record<string, string | undefined>;type Said = { said: string };@@ -18,17 +20,6 @@ const SOMA_X: Record<string, string> = {"SOMA_template_rig.usda": "a952cb7bdf4ccd801e355d53122d395b985b69d0d9181439edad5081bb171856","SOMA_neutral.npz": "5829af4a5333abdba5ad449360b868faacee99d395971e62f35c0e7169432b63",};-const VIEWS = ["front", "back", "left", "right"];-// what every picture must keep, so it lies over the mannequin pixel for pixel and the measure can read it-const KEEP =- "Keep EXACTLY the pose, the proportions, the place of every limb and finger, the size in the frame and the camera view. Where no clothing covers it the mannequin stays featureless dark grey. Flat, even, unlit colour: no cast shadows, no highlights, plain light grey #C8C8C8 background, no text.";-const seen = (v: string) =>- v === "front"- ? "seen from the FRONT"- : v === "back"- ? "seen from BEHIND: we see its back, the back of its head and its heels, and only the back of each garment (no front opening, zip or buttons)"- : `seen exactly from its ${v} side, in profile`;-/** raea's models folder (raea_io_home::models): ~/.local/share/raea-models, %LOCALAPPDATA%\raea\models on Windows */const modelsDir = (env: Env) => (process.platform === "win32" && env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "raea", "models") : join(env.HOME ?? "", ".local/share/raea-models"));@@ -70,109 +61,22 @@ function somaX(dir: string): { rig: string; shapes: string } {return { rig: join(dir, "SOMA_template_rig.usda"), shapes: join(dir, "SOMA_neutral.npz") };}-/** SOMA's body (soma/body: body.glb, skeleton.json) and the mannequin's four views (soma/mannequin), made once */-function soma(raea: string, env: Env): { rig: string; body: string; mannequin: string; made: string[] } {+/** SOMA's body (soma/body: body.glb, skeleton.json), made once */+function soma(raea: string, env: Env): { rig: string; body: string; made: string[] } {const dir = join(modelsDir(env), "soma"), x = somaX(dir), made: string[] = [];- const body = join(dir, "body"), mannequin = join(dir, "mannequin");+ const body = join(dir, "body");if (!["body.glb", "skeleton.json", "joint.glb"].every((f) => existsSync(join(body, f)))) made.push(...blender(raea, env, "body.py", [x.rig, x.shapes, body]));- if (!VIEWS.every((v) => existsSync(join(mannequin, `mannequin_${v}.png`)))) made.push(...blender(raea, env, "mannequin.py", [join(body, "body.glb"), mannequin]));- return { rig: x.rig, body, mannequin, made };+ return { rig: x.rig, body, made };}-type Garment = { name: string; layer: number; vertices: number[]; stand: number[]; over?: string; topology?: string; source?: { views?: string } };+type Garment = { name: string; layer: number; vertices: number[]; stand: number[]; over?: string; topology?: string; kind?: string; made?: string };const readGarment = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Garment;-/** a garment and what it is over, innermost first */-function chainOf(clothes: string, name: string, depth = 0): string[] {- const file = join(clothes, `${name}.json`);- if (!existsSync(file)) throw new Error(`no garment ${name} (assets/clothes/${name}.json): raea clothes lists the ones made`);- // (over several at once: "tee+shorts")- const g = readGarment(file), under = g.over && depth < 8 ? g.over.split("+").flatMap((o) => chainOf(clothes, o, depth + 1)) : [];- return [...new Set(under.filter((n) => n !== name)), name];-}--/** What a new garment is drawn over: the pictures to draw on and measure against, and the layer beneath as one- * garment file. One garment drawn from pictures is its own pictures; a garment made by procedure (no pictures), or- * several at once, is drawn: the mannequin wearing them, innermost first, by Blender. */-function beneath(raea: string, env: Env, s: { rig: string; body: string }, clothes: string, own: string, over: string[]): { views: string; file: string; said: string[] } {- const one = over.length === 1 ? readGarment(join(clothes, `${over[0]}.json`)) : undefined;- if (one?.source?.views && existsSync(join(clothes, over[0], "views", "front.jpg"))) return { views: join(clothes, over[0], "views"), file: join(clothes, `${over[0]}.json`), said: [] };- const names = [...new Set(over.flatMap((n) => chainOf(clothes, n)))], files = names.map((n) => join(clothes, `${n}.json`));- const worn = join(own, "under"), views = join(own, "under", "views");- blender(raea, env, "garment.py", ["wear", join(s.body, "body.glb"), s.rig, worn, ...files]);- blender(raea, env, "mannequin.py", [join(worn, "body.glb"), views, "1024", ...names.map((n) => join(worn, `${n}.glb`))]);- // the layers beneath as one: every vertex any of them covers, at the farthest any stands off- const gs = files.map(readGarment), stand = new Map<number, number>();- for (const g of gs) g.vertices.forEach((v, k) => stand.set(v, Math.max(stand.get(v) ?? 0, g.stand[k])));- const ids = [...stand.keys()].sort((x, y) => x - y), file = join(worn, "beneath.json");- writeFileSync(file, JSON.stringify({ name: over.join("+"), layer: Math.max(...gs.map((g) => g.layer)), vertices: ids, stand: ids.map((v) => stand.get(v)) }));- return { views, file, said: [`drew the mannequin wearing ${names.join(", ")} to draw over (${views})`] };-}-function list(cwd: string) {const dir = join(cwd, "assets/clothes");const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")).sort() : [];- const garments = files.map((f) => readGarment(join(dir, f))).filter((g) => g.topology?.startsWith("SOMA"));- return { garments: garments.map((g) => ({ name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };-}--/** what one picture cost: the gen log's last "cents" (its total; the ones before are its steps') */-const centsOf = (log: string) => Number([...readFileSync(log, "utf8").matchAll(/"cents":\s*(\d+(?:\.\d+)?)/g)].pop()?.[1] ?? 0);--/** The four views dressed by the image model at once, each its own call (a sheet of views, or a second picture to- * follow, loses the registration), kept as OWN/views/VIEW.jpg; what they cost, in cents */-function draw(raea: string, cwd: string, own: string, sources: (v: string) => string, layered: boolean, words: string, cents: number): number {- const views = join(own, "views");- mkdirSync(views, { recursive: true });- const jobs = VIEWS.flatMap((v) => {- const src = sources(v);- if (!existsSync(src)) throw new Error(`${src}: the ${v} view to draw on is missing`);- const prompt = layered- ? `This dressed mannequin is ${seen(v)}. Add exactly one thing and keep everything else pixel for pixel: ${words}, worn over what it already wears. ${KEEP}`- : `This grey mannequin is ${seen(v)}. Turn it into the same mannequin, still ${seen(v)}, wearing ${words}; only the surface changes where clothing covers it. ${KEEP}`;- rmSync(join(own, `gen_${v}`), { recursive: true, force: true });- return [prompt, src, join(own, `gen_${v}`), String(cents)];- });- const run = 'r=$1; shift; while [ $# -gt 0 ]; do ( "$r" gen image "$1" --model flux_2_pro --image "$2" --aspect 1:1 -o "$3" --max-cents "$4" > "$3.log" 2>&1 ) & shift 4; done; wait';- spawnSync("bash", ["-c", run, "clothes", raea, ...jobs], { encoding: "utf8" });- let spent = 0;- for (const v of VIEWS) {- const dir = join(own, `gen_${v}`), pic = existsSync(dir) ? readdirSync(dir).find((f) => /^out\.(jpe?g|png|webp)$/.test(f)) : undefined;- if (!pic) throw new Error(`no picture for the ${v} view: ${relative(cwd, `${dir}.log`)} says why`);- copyFileSync(join(dir, pic), join(views, `${v}.jpg`));- spent += centsOf(`${dir}.log`);- }- return spent;-}--/** make draws and measures; again (remeasure) measures the pictures already kept, drawing nothing */-function make(raea: string, cwd: string, env: Env, a: { name: string; words?: string; over?: string; cents?: number; again?: boolean }): Said {- const clothes = join(cwd, "assets/clothes"), own = join(clothes, a.name), views = join(own, "views"), file = join(clothes, `${a.name}.json`);- let over = a.over ? a.over.split(",") : [];- if (a.again) {- if (!existsSync(file)) throw new Error(`no garment ${a.name} (assets/clothes/${a.name}.json): raea clothes lists the ones made`);- const g = readGarment(file);- if (!g.source?.views || !VIEWS.every((v) => existsSync(join(views, `${v}.jpg`)))) throw new Error(`${a.name} has no pictures to measure (${relative(cwd, views)}): one made by procedure is made again with raea clothes cover`);- over = g.over ? g.over.split("+") : [];- }- for (const o of over) if (!existsSync(join(clothes, `${o}.json`))) throw new Error(`no garment ${o} (assets/clothes/${o}.json): raea clothes lists the ones made`);- if (over.includes(a.name)) throw new Error("a garment can't be drawn over itself");- const s = soma(raea, env);- mkdirSync(own, { recursive: true });- const under = over.length ? beneath(raea, env, s, clothes, own, over) : undefined;- const cents = a.again ? 0 : draw(raea, cwd, own, (v) => (under ? join(under.views, `${v}.jpg`) : join(s.mannequin, `mannequin_${v}.png`)), !!under, a.words ?? "", a.cents ?? 10);- const said = blender(raea, env, "garment.py", ["measure", join(s.body, "body.glb"), s.rig, views, file, ...(under ? [under.file, under.views] : [])]);- if (!existsSync(file)) throw new Error(`the pictures didn't measure into a garment (${relative(cwd, views)})`);- const worn = [...new Set(over.flatMap((o) => chainOf(clothes, o))), a.name].join(" ");- return {- said: [- ...s.made,- ...(under?.said ?? []),- a.again ? `${a.name}: measured again from its four pictures (${relative(cwd, views)}), nothing drawn` : `${a.name}: four pictures, ${cents} cents (${relative(cwd, views)})`,- ...said,- `${relative(cwd, file)}. raea clothes wear assets/characters/NAME ${worn} puts it on SOMA's body; look at its pictures before you do.`,- ].join("\n") + "\n",- };+ const garments = files.map((f) => readGarment(join(dir, f))).filter((g) => g.kind === "sewn" || g.topology?.startsWith("SOMA"));+ return { garments: garments.map((g) => (g.kind === "sewn" ? { name: g.name, layer: g.layer, sewn: g.made ?? "" } : { name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };}function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string }): Said {@@ -190,13 +94,15 @@ function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: sconst at = (p: string) => (isAbsolute(p) ? p : join(cwd, p));const files = a.garments.map((g) => (g.endsWith(".json") ? at(g) : join(cwd, "assets/clothes", `${g}.json`)));for (const f of files) if (!existsSync(f)) throw new Error(`no garment ${relative(cwd, f)}: raea clothes lists the ones made`);- // innermost first: a garment drawn over another goes after it- const layers = files.map((f) => readGarment(f).layer);+ // sewn garments are their own meshes; the ones made on the skin are laid on it innermost first+ const sewn = files.filter((f) => readGarment(f).kind === "sewn"), onSkin = files.filter((f) => !sewn.includes(f));+ const layers = onSkin.map((f) => readGarment(f).layer);if (layers.some((l, k) => k > 0 && l < layers[k - 1])) throw new Error(`put the garments innermost first (their layers are ${layers.join(", ")})`);const s = soma(raea, env), body = a.body ? at(a.body) : s.body, out = at(a.out);if (!existsSync(join(body, "body.glb"))) throw new Error(`${a.body}: not a body folder (no body.glb)`);mkdirSync(out, { recursive: true });- const said = blender(raea, env, "garment.py", ["wear", join(body, "body.glb"), s.rig, out, ...files]);+ const said = blender(raea, env, "garment.py", ["wear", join(body, "body.glb"), s.rig, out, ...onSkin]);+ if (sewn.length) said.push(...wearSewn(raea, cwd, env, out, sewn));// the dressed body is a body folder of its own: its skeleton, its joints' stand-in and a headless body's collarfor (const f of ["skeleton.json", "joint.glb", "collar.json"]) if (existsSync(join(body, f))) copyFileSync(join(body, f), join(out, f));// a head that joins the body at the collar: the body's skin graded to the head's (grade.ts)@@ -212,15 +118,19 @@ function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: sreturn { said: [...s.made, ...said].join("\n") + use + "\n" };}-/** host op "clothes": list, make, remeasure, cover or wear */+/** host op "clothes": list, settings, make, cover or wear */export function clothesHost(raea: string, cwd: string, env: Env, a: Record<string, unknown>): unknown {switch (a.op) {case "list":return list(cwd);- case "make":- return make(raea, cwd, env, a as Parameters<typeof make>[3]);- case "remeasure":- return make(raea, cwd, env, { name: String(a.name), again: true });+ case "settings": {+ const s = soma(raea, env), r = settings(raea, env, modelsDir(env), s.body);+ return { said: [...s.made, r.said].join("\n") };+ }+ case "make": {+ const s = soma(raea, env), r = sew(raea, cwd, env, modelsDir(env), s.body, a as Parameters<typeof sew>[5]);+ return { said: [...s.made, r.said].join("\n") };+ }case "cover":return cover(raea, cwd, env, a as Parameters<typeof cover>[3]);case "wear":diff --git a/tools/clothes/garment.py b/tools/clothes/garment.pyindex 01f7fa24..1f3bf5d8 100644--- a/tools/clothes/garment.py+++ b/tools/clothes/garment.py@@ -1,17 +1,11 @@-# Clothes for SOMA's body from pictures of the dressed mannequin (raea docs/character.feature CH40 to CH45), the-# measuring and wearing behind `raea clothes make` and `raea clothes wear`. A garment is data on SOMA's own-# vertices, by their numbers in SOMA's template (so it rides any SOMA body): which are covered, how far the cloth-# stands off each, and its colour there.+# Clothes laid on SOMA's own skin by procedure (raea docs/character.feature CH45b, CH45c), the making and wearing+# behind `raea clothes cover` and `raea clothes wear`. A garment is data on SOMA's own vertices, by their numbers in+# SOMA's template (so it rides any SOMA body): which are covered, how far the cloth stands off each, and its+# colour there. (Sewn garments are tools/garments; garments measured from drawn pictures were taken out on 11-15.)#-# measure: raea blender run tools/clothes/garment.py measure BODY.glb RIG.usda VIEWS_DIR OUT.json [UNDER.json UNDER_VIEWS_DIR]-# VIEWS_DIR/{front,back,left,right}.jpg: the mannequin's views (tools/clothes/mannequin.py), each dressed by an-# image model on its own, so each lies over its mannequin pixel for pixel. Each vertex of the skin is looked up-# in the views that face it and see it; where the picture shows cloth it is covered and takes the colour. With-# UNDER (the layer beneath and the pictures it was measured from), the garment is only where the picture changed-# from the layer beneath, and it stands off at least that layer's distance plus its own thickness.# cover: raea blender run tools/clothes/garment.py cover BODY.glb RIG.usda OUT.json PART[:SHARE],... #RRGGBB STAND_M [UNDER.json]-# a garment by procedure in the same format, with no picture: the skin of the parts named (each limb as far-# along as its share), in one colour, so far off the skin (and a layer's thickness off UNDER).+# a garment by procedure: the skin of the parts named (each limb as far along as its share), in one colour, so+# far off the skin (and a layer's thickness off UNDER).# wear: raea blender run tools/clothes/garment.py wear BODY.glb RIG.usda OUT_DIR GARMENT.json... (innermost first)# writes OUT_DIR/<name>.glb for each garment (the covered skin pushed out, with the body's own weights) and# OUT_DIR/body.glb, the body with the skin that is wholly under cloth left out.@@ -22,7 +16,7 @@ from mathutils.bvhtree import BVHTreeargs = sys.argv[sys.argv.index("--") + 1:]mode, body_glb, rig_usd = args[:3]-OFF, THICK, MID = 0.004, 0.003, 0.9 # least stand-off, a layer's own thickness, the views' centre height (metres)+OFF, THICK = 0.004, 0.003 # least stand-off, a layer's own thickness (metres)def canon():@@ -66,197 +60,6 @@ bmw = bmesh.new(); bmw.from_mesh(me); bmw.transform(W); bvh = BVHTree.FromBMesh(ring = [[e.other_vert(v).index for e in v.link_edges] for v in bmw.verts]bmw.free()-VIEWS = { # the way to the camera, a point's place in the picture (u right, v down, 0 to 1), the picture's right in the world- "front": ((0, -1, 0), lambda p: (0.5 + p[0] / 2, 0.5 - (p[2] - MID) / 2), (1, 0, 0)),- "back": ((0, 1, 0), lambda p: (0.5 - p[0] / 2, 0.5 - (p[2] - MID) / 2), (-1, 0, 0)),- "left": ((1, 0, 0), lambda p: (0.5 + p[1] / 2, 0.5 - (p[2] - MID) / 2), (0, 1, 0)),- "right": ((-1, 0, 0), lambda p: (0.5 - p[1] / 2, 0.5 - (p[2] - MID) / 2), (0, -1, 0)),-}---def pixels(d, name):- img = bpy.data.images.load(os.path.join(d, f"{name}.jpg"))- w, h = img.size- return np.array(img.pixels[:], dtype=np.float32).reshape(h, w, 4)[::-1, :, :3]---def at(px, u, v):- h, w = px.shape[:2]- return px[min(h - 1, max(0, int(v * h))), min(w - 1, max(0, int(u * w)))]---def measure(views_dir, out, under=None, under_views=None):- weight = np.zeros(n); cloth = np.zeros(n); colour = np.zeros((n, 3)); PIX = {}- for name, (toward, place, _) in VIEWS.items():- px = PIX[name] = pixels(views_dir, name)- below = pixels(under_views, name) if under_views else None- t = Vector(toward)- for i in range(n):- facing = float(no[i] @ np.array(toward))- if facing < 0.35:- continue- p = Vector(co[i])- if bvh.ray_cast(p + t * 0.002 + Vector(no[i]) * 0.001, t)[0] is not None:- continue # the body itself is between this point and the camera- u, v = place(p)- c = at(px, u, v); k = facing * facing- weight[i] += k- sat = float(c.max() - c.min()) / max(float(c.max()), 1e-3)- bare = 0.17 < float(c.mean()) < 0.45 and sat < 0.12 # the mannequin's dark grey (black cloth is darker still)- new = below is None or float(np.abs(c - at(below, u, v)).max()) > 0.08 # the picture changed here- # (tried 11-15 and taken back: over a layer, counting any changed pixel as cloth whatever its shade. The- # mannequin's own shade differs a little between two pictures, and the jacket then covered the hands)- if not bare and new:- cloth[i] += k; colour[i] += k * c- seen = weight > 0- covered = seen & (cloth > 0.5 * weight)- colour[covered] /= cloth[covered][:, None]- for _ in range(14): # a vertex no view saw takes its neighbours' answer- for i in np.nonzero(~seen)[0]:- near = [j for j in ring[i] if seen[j]]- if near:- covered[i] = sum(covered[j] for j in near) * 2 > len(near)- cs = [colour[j] for j in near if covered[j]]- if covered[i] and cs:- colour[i] = np.mean(cs, axis=0)- seen[i] = True- for _ in range(3): # a bare vertex ringed by cloth is cloth- for i in [i for i in range(n) if not covered[i] and ring[i] and sum(covered[j] for j in ring[i]) * 3 >= len(ring[i]) * 2]:- cs = [colour[j] for j in ring[i] if covered[j]]- covered[i] = True; colour[i] = np.mean(cs, axis=0)- left = set(np.nonzero(covered)[0].tolist())- while left: # and a small island of cloth is not- stack, isle = [left.pop()], []- while stack:- i = stack.pop(); isle.append(i)- for j in ring[i]:- if j in left:- left.remove(j); stack.append(j)- if len(isle) < 150:- covered[isle] = False- # a small bare patch walled in by cloth is cloth: the tops of the shoulders, which no level view faces- bare = set(np.nonzero(~covered)[0].tolist())- while bare:- stack, patch = [bare.pop()], []- while stack:- i = stack.pop(); patch.append(i)- for j in ring[i]:- if j in bare:- bare.remove(j); stack.append(j)- if len(patch) < 400:- edge = [j for i in patch for j in ring[i] if covered[j]]- if edge:- c = np.mean(colour[edge], axis=0)- covered[patch] = True; colour[patch] = c- # and a bare vertex that faces up (which no level view sees squarely) among mostly covered skin is covered: the- # tops of the shoulders under a jacket, whose gap runs into the collar and so is walled in by nothing- for _ in range(4):- add = []- for i in np.nonzero(~covered & (no[:, 2] > 0.5))[0]:- near, edge = {int(i)}, [int(i)]- for _d in range(3):- edge = [j for k in edge for j in ring[k] if j not in near]- near.update(edge)- near.discard(int(i))- if near and sum(covered[j] for j in near) * 2 >= len(near):- add.append(i)- for i in add:- cs = [colour[j] for j in ring[i] if covered[j]]- covered[i] = True- if cs:- colour[i] = np.mean(cs, axis=0)- if not add:- break- # and one that faces upward with cloth both in front of it and behind it, within 7 cm: the top of a shoulder- # between a shirt's front and its back, which the bare neck beside it outvoted above, and the slope by the collar,- # where the front view sees the layer beneath through an open collar (11-15, the overshirt's pale yokes); the neck- # faces sideways and has no cloth in front of it- for _ in range(3):- held = np.nonzero(covered)[0]- if not len(held):- break- kd = kdtree.KDTree(len(held))- for k, i in enumerate(held):- kd.insert(Vector(co[i]), k)- kd.balance()- add = []- for i in np.nonzero(~covered & (no[:, 2] > 0.3))[0]:- ys = [co[held[k]][1] - co[i][1] for _, k, _ in kd.find_range(Vector(co[i]), 0.07)]- if any(y < -0.01 for y in ys) and any(y > 0.01 for y in ys):- add.append(i)- for i in add:- cs = [colour[j] for j in ring[i] if covered[j]]- covered[i] = True- if cs:- colour[i] = np.mean(cs, axis=0)- if not add:- break- # the stand-off: read where a view sees a covered vertex on the body's outline, outward along its normal in the- # picture until the backdrop, then spread over the garment- floor = np.full(n, OFF)- if under:- u_stand = np.zeros(len(C)); u_stand[under["vertices"]] = under["stand"]- floor = np.maximum(OFF, u_stand[cid] + THICK)- stand = np.full(n, np.nan)- for name, (toward, place, right) in VIEWS.items():- px = PIX[name]; h, w = px.shape[:2]- back = np.median(np.concatenate([px[:24, :24].reshape(-1, 3), px[:24, -24:].reshape(-1, 3)]), axis=0)- ur, vd = np.array(right, float), np.array((0, 0, -1), float)- for i in np.nonzero(covered)[0]:- if abs(float(no[i] @ np.array(toward))) > 0.3:- continue- d = np.array([no[i] @ ur, no[i] @ vd]); L = np.hypot(*d)- if L < 0.8:- continue- d /= L- u0, v0 = place(Vector(co[i]))- for k in range(1, 70):- x, y = int(u0 * w + d[0] * k), int(v0 * h + d[1] * k)- if not (0 <= x < w and 0 <= y < h):- break- if float(np.abs(px[y, x] - back).max()) < 0.07:- r = k * 2.0 / w- stand[i] = r if np.isnan(stand[i]) else min(stand[i], r)- break- known = ~np.isnan(stand)- val = np.where(known, np.clip(stand, floor, 0.08), floor)- for _ in range(60):- nxt = val.copy()- for i in np.nonzero(covered & ~known)[0]:- nb = [j for j in ring[i] if covered[j]]- if nb:- nxt[i] = sum(val[j] for j in nb) / len(nb)- val = nxt- for _ in range(4):- nxt = val.copy()- for i in np.nonzero(covered)[0]:- nb = [j for j in ring[i] if covered[j]]- if nb:- nxt[i] = 0.5 * val[i] + 0.5 * sum(val[j] for j in nb) / len(nb)- val = np.maximum(nxt, floor)- # and no further off than its part allows: a loose sleeve is drawn hanging below the arm in the mannequin's pose,- # and that depth, read at the outline and laid all round the arm, made a balloon of it (11-15)- gname = {g.index: g.name for g in skin.vertex_groups}- cap = np.array([STAND_CAP.get(part_of(gname[max(v.groups, key=lambda g: g.weight).group])[0], 0.08) if v.groups else 0.08 for v in me.vertices])- val = np.maximum(np.minimum(val, cap), floor)- # by the template's numbers: a template vertex is covered if any of the body's copies of it is- ids = sorted(set(int(c) for c in cid[covered]))- where = {c: k for k, c in enumerate(ids)}- s_sum = np.zeros(len(ids)); c_sum = np.zeros((len(ids), 3)); cnt = np.zeros(len(ids))- for i in np.nonzero(covered)[0]:- k = where[int(cid[i])]; s_sum[k] += val[i]; c_sum[k] += colour[i]; cnt[k] += 1- g = {"name": os.path.splitext(os.path.basename(out))[0], "topology": "SOMA template, c_skin_mid, 18056 vertices", "units": "metres", "layer": (under["layer"] + 1) if under else 0,- **({"over": under["name"]} if under else {}),- # (the views by their path from the garment's file, so a project's garments move with it)- "source": {"views": os.path.relpath(os.path.abspath(views_dir), os.path.dirname(os.path.abspath(out))), "how": "raea clothes make (tools/clothes/garment.py measure)"},- "vertices": ids, "stand": [round(float(x), 5) for x in s_sum / cnt], "colour_srgb": [[round(float(x), 4) for x in c] for c in c_sum / cnt[:, None]],- # how far the cloth may stray from its skinned place: nothing where it is snug, more the further it stands off- "stray": [round(float(max(0.0, x - 0.012) * 0.6), 5) for x in s_sum / cnt]}- json.dump(g, open(out, "w"), separators=(",", ":"))- q = np.percentile(val[covered], [10, 50, 90]) * 1000- print(f"clothes: {g['name']}: layer {g['layer']}, {len(ids)} of {len(C)} template vertices covered; stand-off mm at 10, 50, 90 per cent: {q[0]:.1f}, {q[1]:.1f}, {q[2]:.1f}; outline readings {int(known.sum())}")--def export(obj, path, also=()):for o in bpy.data.objects:o.select_set(o is obj or o in also or o.type == "ARMATURE")@@ -267,73 +70,6 @@ def export(obj, path, also=()):bpy.ops.export_scene.gltf(**kw)-def seen_by():- """per view: which of the body's vertices it sees (facing it, nothing of the body between)"""- out = {}- for name, (toward, _, _) in VIEWS.items():- t = Vector(toward); f = no @ np.array(toward)- out[name] = np.array([f[i] > 0.2 and bvh.ray_cast(Vector(co[i]) + t * 0.002 + Vector(no[i]) * 0.001, t)[0] is None for i in range(n)])- return out---def bake(mesh, covered, views_dir, vcol, size=2048):- """The garment's colour as a picture in the body's first UV set (spread to fill the picture): each texel of a- covered triangle is a point of the body, looked up in the view that faces it most among those that see it. Where- that view only grazes it, or shows backdrop or the bare mannequin there (a shoulder's top, a cuff past the drawn- sleeve), the texel takes the garment's measured colour at its corners (vcol, per body vertex) instead."""- uvl = mesh.uv_layers[0].data- mesh.calc_loop_triangles()- tris = [t for t in mesh.loop_triangles if all(covered[v] for v in t.vertices)]- uv = np.array([[uvl[l].uv[:] for l in t.loops] for t in tris], float)- lo, hi = uv.reshape(-1, 2).min(0), uv.reshape(-1, 2).max(0)- uv = (uv - lo) / np.maximum(hi - lo, 1e-9)- vid = np.array([t.vertices[:] for t in tris])- PIX = {name: pixels(views_dir, name) for name in VIEWS}- BACK = {name: np.median(np.concatenate([p[:24, :24].reshape(-1, 3), p[:24, -24:].reshape(-1, 3)]), axis=0) for name, p in PIX.items()}- vis = seen_by()- img = np.zeros((size, size, 3), np.float32); got = np.zeros((size, size), bool)- names = list(VIEWS)- toward = np.array([VIEWS[k][0] for k in names], float)- for k in range(len(tris)):- a, b, c = uv[k] * (size - 1)- x0, x1 = int(np.floor(min(a[0], b[0], c[0]))), int(np.ceil(max(a[0], b[0], c[0])))- y0, y1 = int(np.floor(min(a[1], b[1], c[1]))), int(np.ceil(max(a[1], b[1], c[1])))- gx, gy = np.meshgrid(np.arange(x0, x1 + 1), np.arange(y0, y1 + 1))- den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1])- if abs(den) < 1e-9:- continue- w0 = ((b[1] - c[1]) * (gx - c[0]) + (c[0] - b[0]) * (gy - c[1])) / den- w1 = ((c[1] - a[1]) * (gx - c[0]) + (a[0] - c[0]) * (gy - c[1])) / den- w2 = 1 - w0 - w1- inside = (w0 >= -0.02) & (w1 >= -0.02) & (w2 >= -0.02)- if not inside.any():- continue- v = vid[k]; fn = no[v].mean(0); fn /= max(np.linalg.norm(fn), 1e-9)- # the view: the one this triangle faces most, of those that see all its corners (else any it faces)- score = toward @ fn- ok = np.array([vis[nm][v].all() for nm in names])- pick = int(np.argmax(np.where(ok, score, score - 2)))- place = VIEWS[names[pick]][1]; px = PIX[names[pick]]; h, w = px.shape[:2]- P = w0[inside][:, None] * co[v[0]] + w1[inside][:, None] * co[v[1]] + w2[inside][:, None] * co[v[2]]- u, vv = place(P.T)- col = px[np.clip((vv * h).astype(int), 0, h - 1), np.clip((u * w).astype(int), 0, w - 1)]- mean, sat = col.mean(1), (col.max(1) - col.min(1)) / np.maximum(col.max(1), 1e-3)- off = (np.abs(col - BACK[names[pick]]).max(1) < 0.07) | ((mean > 0.17) & (mean < 0.45) & (sat < 0.12)) | (score[pick] < 0.35)- if off.any():- mine = w0[inside][:, None] * vcol[v[0]] + w1[inside][:, None] * vcol[v[1]] + w2[inside][:, None] * vcol[v[2]]- col = np.where(off[:, None], mine, col)- img[gy[inside], gx[inside]] = col; got[gy[inside], gx[inside]] = True- # (tried and taken out, 11-15: moving each other view's colours onto the front's by the front's main colours;- # pale denim on the back was taken for the shirt's white and turned white. The views' colours still differ.)- for _ in range(6): # spread past each island's edge, so a filtered lookup doesn't pull in black- nb = np.zeros_like(img); cnt = np.zeros(got.shape, np.float32)- for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):- nb += np.roll(np.roll(img * got[..., None], dy, 0), dx, 1); cnt += np.roll(np.roll(got, dy, 0), dx, 1)- fill = ~got & (cnt > 0)- img[fill] = nb[fill] / cnt[fill][:, None]; got |= fill- return img, lo, hi--def wear(out_dir, garments):os.makedirs(out_dir, exist_ok=True)under = np.zeros(n, bool)@@ -371,9 +107,8 @@ def wear(out_dir, garments):# its colour: a picture in the body's UVs, baked from the views it was measured from (the garment's own UVs# are the body's, spread to fill that picture); a garment made by procedure has no views and is its one colourif "views" in g["source"]:- tex, lo, hi = bake(skin.data, covered, os.path.join(os.path.dirname(os.path.abspath(path)), g["source"]["views"]), col[cid])- else:- tex, lo, hi = np.tile(np.mean(g["colour_srgb"], axis=0).astype(np.float32), (4, 4, 1)), np.zeros(2), np.ones(2)+ sys.exit(f"clothes: {g['name']} was measured from drawn pictures, which raea no longer wears: sew it (raea clothes make) or lay it on the skin (raea clothes cover)")+ tex, lo, hi = np.tile(np.mean(g["colour_srgb"], axis=0).astype(np.float32), (4, 4, 1)), np.zeros(2), np.ones(2)uvl = piece.data.uv_layers[0].datafor l in uvl:l.uv = ((l.uv[0] - lo[0]) / max(hi[0] - lo[0], 1e-9), (l.uv[1] - lo[1]) / max(hi[1] - lo[1], 1e-9))@@ -470,10 +205,7 @@ def cover(out, spec, colour, stand_m, under=None):print(f"clothes: {g['name']}: layer {g['layer']}, {len(ids)} of {len(C)} template vertices covered ({spec}), {colour}, {stand.min() * 1000:.1f} to {stand.max() * 1000:.1f} mm off what is under it")-if mode == "measure":- views_dir, out = args[3], args[4]- measure(views_dir, out, json.load(open(args[5])) if len(args) > 5 else None, args[6] if len(args) > 6 else None)-elif mode == "cover":+if mode == "cover":cover(args[3], args[4], args[5], float(args[6]), json.load(open(args[7])) if len(args) > 7 else None)else:wear(args[3], args[4:])diff --git a/tools/clothes/mannequin.py b/tools/clothes/mannequin.pydeleted file mode 100644index 8cd0f0c8..00000000--- a/tools/clothes/mannequin.py+++ /dev/null@@ -1,50 +0,0 @@-# The mannequin clothes are drawn on (raea docs/character.feature CH40): SOMA's body at rest, flat dark grey on-# mid grey, without perspective, from the front, the back, its left and its right, the four views in one picture so-# an image model dresses all of them as one garment. The cameras are written beside it, so what is drawn can be laid-# back on the body. `raea clothes` makes the machine's views once, in raea's models folder (soma/mannequin).-# raea blender run tools/clothes/mannequin.py BODY.glb OUT_DIR [SIZE] [PIECE.glb...]-# With PIECEs (a dressed body's garments, `raea clothes wear`), the mannequin is drawn wearing them in their own-# colours, and the views are OUT_DIR/{front,back,left,right}.jpg: what a garment made by procedure looks like, for-# one drawn over it.-import sys, os, json, math-import bpy-from mathutils import Vector, Matrix--a = sys.argv[sys.argv.index("--") + 1:]-src, out, size, pieces = a[0], a[1], int(a[2]) if len(a) > 2 else 1024, a[3:]-os.makedirs(out, exist_ok=True)-bpy.ops.wm.read_factory_settings(use_empty=True)-bpy.ops.import_scene.gltf(filepath=src)-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)-for o in bpy.data.objects: # the body's own parts in the mannequin's grey (workbench draws a material's viewport colour)- if o.type == "MESH":- for m in o.data.materials:- m.diffuse_color = (0.22, 0.22, 0.22, 1)-for p in pieces:- bpy.ops.import_scene.gltf(filepath=p)-sc = bpy.context.scene-sc.render.engine = "BLENDER_WORKBENCH"-sh = sc.display.shading-sh.light = "STUDIO"; sh.color_type = "TEXTURE" if pieces else "SINGLE"; sh.single_color = (0.22, 0.22, 0.22); sh.show_cavity = True; sh.cavity_type = "BOTH"; sh.show_shadows = False-sc.world = bpy.data.worlds.new("w"); sc.world.color = (0.578, 0.578, 0.578)-sc.render.film_transparent = False-sc.view_settings.view_transform = "Standard"-sc.render.resolution_x = sc.render.resolution_y = size-cam_d = bpy.data.cameras.new("c"); cam_d.type = "ORTHO"; cam_d.ortho_scale = 2.0-cam = bpy.data.objects.new("c", cam_d); sc.collection.objects.link(cam); sc.camera = cam-MID = 0.9 # metres up: the frame is 2 m tall, the floor 10 cm above its bottom-views = {"front": (0, -4), "back": (0, 4), "left": (4, 0), "right": (-4, 0)} # the body faces -Y in Blender; +X is its left-cams = {}-for name, (x, y) in views.items():- cam.location = (x, y, MID)- cam.rotation_euler = (Vector((0, 0, MID)) - cam.location).to_track_quat("-Z", "Y").to_euler()- if pieces:- sc.render.image_settings.file_format = "JPEG"; sc.render.image_settings.quality = 95- sc.render.filepath = os.path.join(out, f"{name}.jpg" if pieces else f"mannequin_{name}.png")- bpy.ops.render.render(write_still=True)- # raea's frame: y up, +z ahead, x its left- cams[name] = {"from": [x, MID, -y], "at": [0, MID, 0], "height_m": 2.0}-if not pieces:- json.dump({"units": "metres, Y up, +Z ahead", "orthographic": True, "size": size, "views": cams}, open(os.path.join(out, "mannequin.cam.json"), "w"), indent=1)-print("clothes: the mannequin's four views", out)diff --git a/tools/garments/README.md b/tools/garments/README.mdindex 026a42fa..1ec6a2d8 100644--- a/tools/garments/README.md+++ b/tools/garments/README.md@@ -15,6 +15,17 @@ its sample SMPL bodies (research-only) and GarmentCodeData (draped on SMPL, licematplotlib cgal trimesh psutil networkx shapely rtree libigl pillow mlxexport GARMENTCODE=$PWD/GarmentCode GARMENT_PY=$PWD/venv/bin/python+## One garment: what `raea clothes make` runs++ tools/garments/sew.sh OUT_DIR NAME "a hooded sweatshirt" [--set sleeve.length=0.9] [--colour #3f5a3c]+ tools/garments/sew.sh OUT_DIR NAME "" --plain --set meta.upper=none --set meta.bottom=Pants --set pants.length=0.8++`sew.sh` takes a design from words (the model, `GARMENT_MODEL`) or from GarmentCode's plain base (`--plain`),+changes settings by path (`design.py`, which checks each against its options or range), cuts it to SOMA, drapes it+(`GARMENT_SDF`: the body's distance grid) and bakes `OUT_DIR/NAME/NAME.glb`. `raea clothes make` sets these up in+raea's models folder (`garments/`) the first time and calls it (engine/cli/src/sewn.ts); `hide_under.py` leaves out+the body's skin under worn garments for `raea clothes wear`.+## Runtools/garments/engine.sh OUT_DIR 24 11 # 24 random designs, seed 11diff --git a/tools/garments/bake_batch.py b/tools/garments/bake_batch.pyindex dfcfe78b..8911194d 100644--- a/tools/garments/bake_batch.py+++ b/tools/garments/bake_batch.py@@ -63,7 +63,7 @@ for d in dirs: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)]+ colour = os.environ.get("COLOUR") or PALETTE[zlib.crc32(name.encode()) % len(PALETTE)] # COLOUR=#rrggbb: the colour asked forrgb = [int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5)]mat = bpy.data.materials.new(name); mat.use_nodes = Truebsdf = next(x for x in mat.node_tree.nodes if x.type == "BSDF_PRINCIPLED")diff --git a/tools/garments/design.py b/tools/garments/design.pyindex df067435..d6d3c2f3 100644--- a/tools/garments/design.py+++ b/tools/garments/design.py@@ -1,17 +1,43 @@-# A GarmentCode design from a base design and settings by path: the words-to-garment step's output format.+# A GarmentCode design from a base design and settings by path: what `raea clothes make --set` writes.# python design.py BASE.yaml OUT.yaml meta.upper=Shirt sleeve.length=1.0 collar.component.style=Hood2Panels ...+# python design.py BASE.yaml prints every setting: its path, its value, and what it may be+# A choice must be one of its options and a number within its range; a wrong path or value says what is allowed.import sys, yaml-base, out, *sets = sys.argv[1:]+base, *rest = sys.argv[1:]d = yaml.safe_load(open(base))+++def leaves(node, at=""):+ for k, v in node.items():+ if isinstance(v, dict) and "v" in v: yield at + k, v+ elif isinstance(v, dict): yield from leaves(v, at + k + ".")+++def allowed(n):+ t, r = n.get("type", ""), n.get("range")+ if t == "bool": return "true or false"+ if t.startswith("select"): return "one of " + ", ".join("none" if x is None else str(x) for x in r)+ return f"{r[0]} to {r[1]}" if r else "any"+++if not rest:+ for path, n in leaves(d["design"]):+ if not path.startswith("left."): print(f"{path} = {'none' if n['v'] is None else n['v']} ({allowed(n)})")+ sys.exit(0)+out, *sets = rest+known = dict(leaves(d["design"]))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']}")+ path, _, val = s.partition("=")+ if path not in known:+ near = [p for p in known if p.split(".")[0] == path.split(".")[0] and not p.startswith("left.")]+ sys.exit(f"design: no setting {path}" + (f"; under {path.split('.')[0]}: {', '.join(near)}" if near else "; `raea clothes settings` lists them"))+ node, v = known[path], yaml.safe_load(val)+ if isinstance(v, str) and v.lower() == "none": v = None+ t, r = node.get("type", ""), node.get("range")+ ok = (isinstance(v, bool) if t == "bool" else v in r if t.startswith("select") else+ isinstance(v, (int, float)) and not isinstance(v, bool) and (not r or r[0] <= v <= r[1]))+ if not ok: sys.exit(f"design: {path}={val}: it is {allowed(node)}")node["v"] = vyaml.safe_dump(d, open(out, "w"), sort_keys=False)print("design:", out, " ".join(sets))diff --git a/tools/garments/garment_model.py b/tools/garments/garment_model.pyindex 82bf4307..85b161ba 100644--- a/tools/garments/garment_model.py+++ b/tools/garments/garment_model.py@@ -111,7 +111,11 @@ def train(data, model_path):if s % 1000 == 0 or s == STEPS - 1: print(f"train: step {s} loss {float(l):.3f}", flush=True)net.eval()w = {k: np.array(v) for k, v in __import__("mlx.utils", fromlist=["tree_flatten"]).tree_flatten(net.parameters())}- np.savez(model_path, mu_i=mu_i, mu_t=mu_t, schema=schema.dump(), **{f"w:{k}": v for k, v in w.items()})+ # each training design with its pictures' mean embedding: the nearest one stands in when GarmentCode refuses+ # what the network decodes+ tn = np.array([str(n) for n in Z["names"][keep]]); kept = sorted(set(tn))+ near_E = unit(np.stack([X[tn == n].mean(0) for n in kept])); near_Y = np.stack([schema.encode(designs[n]) for n in kept])+ np.savez(model_path, mu_i=mu_i, mu_t=mu_t, schema=schema.dump(), near_E=near_E, near_Y=near_Y, **{f"w:{k}": v for k, v in w.items()})print(f"train: {len(names)} designs ({int(keep.sum())} pictures kept for training), {schema.width} slots -> {model_path}")@@ -159,9 +163,13 @@ def evaluate(data, model_path):def make(model_path, words, out):+ """OUT/design.yaml from the network, and OUT/nearest.yaml, the training design nearest the words (the fallback)"""M, net, schema = restore(model_path)- d = schema.decode(predict(net, schema, unit(text_embed([words]) - M["mu_t"]))[0])+ t = unit(text_embed([words]) - M["mu_t"])+ d = schema.decode(predict(net, schema, t)[0])os.makedirs(out, exist_ok=True); yaml.safe_dump({"design": d}, open(f"{out}/design.yaml", "w"), sort_keys=False)+ if "near_E" in M.files:+ yaml.safe_dump({"design": schema.decode(M["near_Y"][int((t @ M["near_E"].T).argmax())])}, open(f"{out}/nearest.yaml", "w"), sort_keys=False)print(f"make: {words!r} -> {out}/design.yaml (upper {_get(d, ('meta', 'upper'))['v']}, bottom {_get(d, ('meta', 'bottom'))['v']})")diff --git a/tools/garments/hide_under.py b/tools/garments/hide_under.pynew file mode 100644index 00000000..0c0ce1be--- /dev/null+++ b/tools/garments/hide_under.py@@ -0,0 +1,41 @@+# The body with the skin wholly under cloth left out, so it can't poke through as it moves.+# raea blender run hide_under.py BODY.glb OUT.glb GARMENT.glb...+# A body vertex is under cloth when a ray out along its normal meets a garment within REACH (6 cm); a face goes when+# its vertices and all their neighbours are under cloth (the edge of the cut stays, so no gap shows at a hem).+import bpy, bmesh, sys, os+from mathutils import Vector+from mathutils.bvhtree import BVHTree++a = sys.argv[sys.argv.index("--") + 1:]+body_glb, out, garments = a[0], a[1], a[2:]+REACH = float(os.environ.get("REACH", "0.06"))+bpy.ops.wm.read_factory_settings(use_empty=True)+bpy.ops.import_scene.gltf(filepath=body_glb)+skin = max((o for o in bpy.data.objects if o.type == "MESH"), key=lambda o: len(o.data.vertices))+keep = set(bpy.data.objects)+dg = bpy.context.evaluated_depsgraph_get()+cb = bmesh.new()+for gpath in garments:+ before = set(bpy.data.objects); bpy.ops.import_scene.gltf(filepath=gpath)+ for o in set(bpy.data.objects) - before:+ if o.type == "MESH":+ t = bmesh.new(); t.from_object(o, bpy.context.evaluated_depsgraph_get()); t.transform(o.matrix_world)+ m = bpy.data.meshes.new("t"); t.to_mesh(m); t.free(); cb.from_mesh(m)+bvh = BVHTree.FromBMesh(cb)+W = skin.matrix_world; N = W.to_3x3()+bm = bmesh.new(); bm.from_mesh(skin.data); bm.verts.ensure_lookup_table()+under = [False] * len(bm.verts)+for v in bm.verts:+ p = W @ v.co; nrm = (N @ v.normal).normalized()+ hit = bvh.ray_cast(p + nrm * 0.0005, nrm, REACH)+ under[v.index] = hit[0] is not None+deep = [under[v.index] and all(under[e.other_vert(v).index] for e in v.link_edges) for v in bm.verts]+gone = [f for f in bm.faces if all(deep[v.index] for v in f.verts)]+total = len(bm.faces)+bmesh.ops.delete(bm, geom=gone, context="FACES")+bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.link_faces], context="VERTS")+bm.to_mesh(skin.data); bm.free()+for o in bpy.data.objects:+ o.select_set(o in keep and o.type in ("MESH", "ARMATURE"))+bpy.ops.export_scene.gltf(filepath=out, export_format="GLB", use_selection=True, export_animations=False, export_yup=True, export_skins=True)+print(f"hide_under: {len(gone)} of {total} faces under cloth left out: {out}")diff --git a/tools/garments/sew.sh b/tools/garments/sew.shnew file mode 100755index 00000000..b01d0080--- /dev/null+++ b/tools/garments/sew.sh@@ -0,0 +1,44 @@+#!/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]+# 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. Writes OUT_DIR/NAME/: design.yaml, NAME.glb,+# NAME.drape.json, NAME.bake.json, caption.txt. Prints lines starting "sew: ". $0, about 30 s.+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}+SDF=${GARMENT_SDF:-$HOME/.cache/raea-garments/soma_sdf.npz}+BODY=${SOMA_BODY:-$HOME/.local/share/raea-models/soma/body/body.glb}+OUT=${1:?out dir}; n=${2:?name}; words=${3:-}; shift 3 || true+PLAIN=0; SETS=(); COLOUR=+while [ $# -gt 0 ]; do+ case "$1" in+ --plain) PLAIN=1; shift ;;+ --set) SETS+=("$2"); shift 2 ;;+ --colour) COLOUR=$2; shift 2 ;;+ *) echo "sew: unknown word $1" >&2; exit 2 ;;+ esac+done+d=$OUT/$n+rm -rf "${d:?}"; mkdir -p "$d"; printf '%s\n' "$words" > "$d/words.txt"+if [ "$PLAIN" = 1 ]; then+ cp "$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"+fi+if [ ${#SETS[@]} -gt 0 ]; then "$PY" -I "$T/design.py" "$d/design.yaml" "$d/design.yaml" "${SETS[@]}" > /dev/null; fi+pattern() { (cd "$T" && DESIGN="$d/design.yaml" GID=$n "$PY" -I sample_designs.py "$GC" "$T/soma.yaml" "$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+ cp "$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 "$T/soma.yaml") 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 /'+[ -f "$d/$n.glb" ] || { echo "sew: FAILED no glb was baked" >&2; exit 1; }+echo "sew: made: $(cat "$d/caption.txt" 2>/dev/null || echo "$n")"diff --git a/tools/garments/sheet.py b/tools/garments/sheet.pyindex 0a01627e..c546856f 100644--- a/tools/garments/sheet.py+++ b/tools/garments/sheet.py@@ -12,6 +12,7 @@ for d in dirs:cap = open(os.path.join(d, "caption.txt")).read().strip() if os.path.exists(os.path.join(d, "caption.txt")) else ""if os.path.exists(os.path.join(d, "words.txt")): # asked in words (words.sh): the words, then what was madecap = f'asked "{open(os.path.join(d, "words.txt")).read().strip()}", made: {cap}'+ if os.path.exists(os.path.join(d, "fallback.txt")): cap += " (refused as decoded: the nearest training design)"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")diff --git a/tools/garments/words.sh b/tools/garments/words.shindex 6fb1bd48..0bdc3f3a 100755--- a/tools/garments/words.sh+++ b/tools/garments/words.sh@@ -18,6 +18,12 @@ for words in "$@"; domkdir -p "$d"; printf '%s\n' "$words" > "$d/words.txt""$PY" -I "$T/garment_model.py" make "$MODEL" "$words" "$d" | grep -E "^make:"(cd "$T" && DESIGN="$d/design.yaml" GID=$n "$PY" -I sample_designs.py "$GC" "$T/soma.yaml" "$OUT" 1 1) | grep -E "^sample: (w|rejected)" | cut -c1-160+ # refused (a combination GarmentCode's checks don't allow): the training design nearest the words instead+ if [ ! -f "$d/$n.panels.json" ] && [ -f "$d/nearest.yaml" ]; then+ echo "words: $n ($words): GarmentCode refused the design; the nearest training design instead"+ cp "$d/nearest.yaml" "$d/design.yaml"; echo nearest > "$d/fallback.txt"+ (cd "$T" && DESIGN="$d/design.yaml" GID=$n "$PY" -I sample_designs.py "$GC" "$T/soma.yaml" "$OUT" 1 1) | grep -E "^sample: (w|rejected)" | cut -c1-160+ fi[ -f "$d/$n.panels.json" ] || { echo "words: $n ($words): GarmentCode refused the design"; continue; }log=$( (cd "$T" && "$PY" -I drape_mlx.py "$DATA/soma_sdf.npz" "$d/$n.panels.json" "$d" 150 -0.064 "$T/soma.yaml") 2>&1 ) && grep -E '^drape: \{' <<<"$log" | cut -c1-160 \|| echo "drape: $n failed: $(grep -vE '^\s*$' <<<"$log" | tail -1 | sed 's/Traceback/trace/')"diff --git a/tools/release.sh b/tools/release.shindex c59516f4..ed54d0e4 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -159,7 +159,7 @@ done# (@raea/ui, the page's DOM every render goes through, isn't an @raea/<name> path, so it's named here)git archive "$ref" sdk/tsconfig.base.json sdk/ui/src sdk/ui/package.json sdk/ui/bevy sdk/raea/src sdk/raea/library sdk/raea/package.json sdk/react/js/src sdk/react/js/lite sdk/react/js/shims sdk/react/js/package.json sdk/react/js/tsconfig.json sdk/shell/src \"${pkgs[@]}" \- tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove tools/clothes tools/ensure.sh sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \+ tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove tools/clothes tools/garments tools/ensure.sh sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \| tar -x -C "$stage/share/raea"# a folder copied as it is here (links kept, as rsync -a; tar, since Git's bash on Windows has no rsync)copy() { mkdir -p "$2" && tar -C "$(dirname "$1")" --exclude .cache -cf - "$(basename "$1")" | tar -C "$2" -xf -; }