Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add optional cloth layers with tunable garment physics

shinshin8624f8172650f8
diff --git a/.changeset/cloth-prototype.md b/.changeset/cloth-prototype.md
new file mode 100644
index 0000000..3cbda21
--- /dev/null
+++ b/.changeset/cloth-prototype.md
@@ -0,0 +1,7 @@
+---
+"mesh-avatar": minor
+"mesh-avatar-element": minor
+"mesh-avatar-react": minor
+---
+
+Add optional cloth layers with body-following garment physics and per-garment tuning through `setClothTuning`. Preserve the clothed base for older players and export `ClothTuning` through the runtime, element and React packages.
diff --git a/docs/agent-guide.md b/docs/agent-guide.md
index 8d4cd4a..273200e 100644
--- a/docs/agent-guide.md
+++ b/docs/agent-guide.md
@@ -200,6 +200,42 @@ uv run tools/build-sprites.py projects/<name>
It cuts accepted variants into `built/sprites/`. Render the poses again (Step 5); the
`angry`, `sad` and `surprise` frames show the expression eyes and mouths.
+## Optional — Garments
+
+For a skirt or hanging fabric, prepare a local `source_under.png` with exactly the
+same size, pose and pixel alignment as `source.png`. Remove the skirt and its tails,
+leaving modest inner shorts and complete legs. Ask before sending any image to an
+external generation service. Small redraw differences can create edge artifacts;
+compare the two images before building. If this input is absent, the builder uses
+inpainting, which may look blurry when the cloth swings away from the body.
+
+Add optional `rig.cloth` entries (see [Rig fields](rig-fields.md)). Trace each `outline`
+around the whole garment, place its `waist` along the attachment and its `hem` across
+the lower edge. Use the calibrated coordinates, zoomed grids and overlays from the
+earlier steps. Keep the grid wide enough for projecting ruffles; narrow or degenerate
+grids can distort extrapolated points. Put rear tails in separate entries with
+`behind: true`; use `parent: "skirt"` when their attachment should follow an earlier
+skirt entry. Depth controls drawing order; parent controls motion, independently.
+For planted feet, optionally set `body.hip: { "shift": 20, "band": [900, 1400] }`,
+adjusting these example coordinates to the illustration. `mesh.clothCell` defaults to 8.
+
+Validate the draft before rebuilding:
+
+```sh
+npm run validate-rig -- projects/<name>/rig.draft.json
+uv run --with numpy --with pillow --with opencv-python-headless tools/build-layers.py projects/<name> --rig rig.draft.json
+npm run render-poses -- projects/<name>
+```
+
+Inspect `review/rest.png` at the waist, ruffles and tail edges. Inspect the ten
+`cloth-sway-0.png` through `cloth-sway-9.png` frames for lag, reversal and settling,
+not just the contact sheet. Set `wind: 0` when checking convergence to rest; default
+wind intentionally keeps a small motion. Compare a lower `swing` or higher `damping`
+to the defaults. In Studio, select Cloth, adjust its numeric fields, save and reopen
+to confirm persistence. Waist/hem handles affect motion immediately; changing an
+outline marks layers stale and requires a rebuild. Keep `base.png` intact for older
+players; verify `base_cloth.png` and all `cloth_<name>` layers are present when packing.
+
## Step 7 — Hand over
Tell the person:
diff --git a/docs/format.md b/docs/format.md
index 6b3d9a4..ec9824c 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -13,6 +13,8 @@ rig.json complete version 1 rig, including sampled eye cur
built/
layers.json image size, layer rectangles and sampled eye curves
base.png image with movable parts removed and inpainted
+ base_cloth.png required only for nonempty rig.cloth; base without garments
+ cloth_<name>.png garment cutout for each rig.cloth entry
hairmask.png full-size hair mask, read from the red channel
<name>.png one image for every entry in layers.json.layers
sprites/ optional drawn eye and mouth variants
@@ -30,6 +32,15 @@ generated eye layers and procedural mouth without drawn variants.
Readers ignore unknown files and unknown JSON keys. A project may also contain drafts,
source variants, masks and review images; these are not required for playback.
+For nonempty `rig.cloth`, `base_cloth.png` is a full-size image and every garment has a
+`cloth_<name>` rectangle in `layers.json.layers` with a matching cropped PNG. Players
+draw rear garments, `base_cloth`, eye/mouth layers, front garments, accessories, then
+the optional hand. `base.png` retains the garments so older players still show the
+clothed illustration. `pack-avatar` includes both bases and the garment cutouts.
+The optional editing input `source_under.png` has the same dimensions and alignment
+as `source.png`, with only garments removed; it is not needed for playback and is
+not included by `pack-avatar`. Without it the layer builder inpaints the covered area.
+
## Manifest: `avatar.json`
```json
diff --git a/docs/rig-fields.md b/docs/rig-fields.md
index 7621fec..569f926 100644
--- a/docs/rig-fields.md
+++ b/docs/rig-fields.md
@@ -150,3 +150,36 @@ the engine mapping. Do not copy the example illustration's coordinates into a ne
Draft validation accepts omitted `x0/x1/top/bot` only as a complete group; supplying some of
the four fields is an error. Complete rigs always require all four. Changing eye geometry
requires rebuilding; old sampled curves cannot reconstruct new image pixels.
+
+## Optional garments
+
+`cloth` is an optional array. Omit it or use `[]` to retain the existing rendering.
+Coordinates are source-image pixels, with x increasing right and y increasing down.
+
+| Field | Meaning / default |
+| --- | --- |
+| `cloth[*].name` | Unique letters/digits/underscore/hyphen name; generates `cloth_<name>.png`. |
+| `cloth[*].outline` | Cutout polygon, at least three points, enclosing all ruffles and tails belonging to this garment. Changing it requires rebuilding layers. |
+| `cloth[*].waist` | Upper attachment polyline, at least two points, from image-left to right. Follows the body or parent garment. |
+| `cloth[*].hem` | Lower polyline, at least two points, from image-left to right. Cover the full width of the cloth, including projecting ruffles. |
+| `cloth[*].columns`, `rows` | Integer grid node counts, both at least `2`; defaults `8`, `5`. |
+| `cloth[*].swing` | Positive hem spring frequency in Hz; default `1`. Lower values give a slower response. |
+| `cloth[*].stiffness` | Positive spring multiplier; default `1`. Also affects frequency. |
+| `cloth[*].damping` | Positive damping multiplier; default `1`. Larger values suppress oscillations. |
+| `cloth[*].follow` | Fraction of the previous row's lag inherited by the next, `0..1`; default `0.85`. |
+| `cloth[*].cohesion` | Integer smoothing passes between columns, `0..8`; default `3`. |
+| `cloth[*].wind` | Nonnegative breeze strength as a fraction of `max`; default `0.05`, `0` disables wind. |
+| `cloth[*].max` | Positive maximum simulated grid displacement from the body-carried shape, px; default `20`. Extrapolated mesh points outside the grid can move farther. |
+| `cloth[*].behind` | Optional boolean, default `false`; draw before the bare base when true. Changing depth requires rebuilding overlapping cutouts. |
+| `cloth[*].parent` | Optional name of an **earlier** cloth entry. Its displaced grid drives this garment's waist, useful for rear tails attached to a skirt. |
+| `body.hip.shift` | Optional full-body sideways travel at `bodyAngleX=10`, px. Supply with `band` to fade sideways motion toward planted feet. |
+| `body.hip.band` | Increasing source-y range over which sideways body travel fades to zero. Existing rigs without `hip` keep their original deformation. |
+| `mesh.clothCell` | Positive integer garment render-mesh spacing, px; default `8`. Independent of cloth grid node counts. |
+
+`setClothTuning(name, tuning)` accepts a `Partial<ClothTuning>` containing the seven
+physics fields above. A `null` name applies to all garments; a string applies only to
+that name. Updates take effect on the next simulation step without resetting velocity,
+changing the rig or rebuilding layers. Invalid values or an unknown name throw a
+`RangeError`. Studio edits update the rig and are included when saving it.
+The element exposes this method through `element.avatar` / `await element.ready`;
+React exposes the same element through its ref and the runtime through `onLoad`.
diff --git a/e2e/cloth.spec.ts b/e2e/cloth.spec.ts
new file mode 100644
index 0000000..4f0012a
--- /dev/null
+++ b/e2e/cloth.spec.ts
@@ -0,0 +1,46 @@
+import { test, expect } from '@playwright/test';
+import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { basename, join, resolve } from 'node:path';
+import { PNG } from 'pngjs';
+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+test('cloth defaults edit the preview, persist on reopen, and outline edits require rebuilding', async ({ page }) => {
+ test.setTimeout(90000);
+ test.skip(!samplePresent, sampleSkipReason);
+ await mkdir('projects', { recursive: true });
+ const directory = await mkdtemp(join(resolve('projects'), 'cloth-check-'));
+ try {
+ await cp(resolve('samples/miko-qipao'), directory, { recursive: true });
+ const rigPath = join(directory, 'rig.json'), rig = JSON.parse(await readFile(rigPath, 'utf8'));
+ rig.cloth = [{ name: 'skirt', outline: [[0, 900], [100, 900], [100, 1000], [0, 1000]], waist: [[0, 900], [100, 900]], hem: [[0, 1000], [100, 1000]] }];
+ await writeFile(rigPath, JSON.stringify(rig));
+ await cp(join(directory, 'built/base.png'), join(directory, 'built/base_cloth.png'));
+ const metaPath = join(directory, 'built/layers.json'), meta = JSON.parse(await readFile(metaPath, 'utf8'));
+ meta.layers.cloth_skirt = [0, 900, 100, 100]; await writeFile(metaPath, JSON.stringify(meta));
+ const image = new PNG({ width: 100, height: 100 }); image.data.fill(160);
+ await writeFile(join(directory, 'built/cloth_skirt.png'), PNG.sync.write(image));
+ const open = async () => {
+ await page.goto('/'); await dismissGuide(page); await page.locator('.open-menu > summary').click();
+ await page.getByTestId(`project-${basename(directory)}`).click();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByTestId('part-cloth').click();
+ await page.locator('.inspector details').evaluateAll(nodes => nodes.forEach(node => { (node as HTMLDetailsElement).open = true; }));
+ };
+ await open();
+ const swing = page.getByRole('spinbutton', { name: 'cloth.0.swing', exact: true });
+ await expect(swing).toHaveValue('1');
+ const preview = page.getByTestId('preview'), revision = Number(await preview.getAttribute('data-revision'));
+ await swing.fill('0.5');
+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await expect(page.getByTestId('stale-banner')).toHaveCount(0);
+ await page.getByRole('spinbutton', { name: 'cloth.0.cohesion', exact: true }).fill('4.7');
+ await expect(page.getByRole('spinbutton', { name: 'cloth.0.cohesion', exact: true })).toHaveValue('5');
+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();
+ await expect.poll(async () => JSON.parse(await readFile(rigPath, 'utf8')).cloth[0].swing).toBe(0.5);
+ await open(); await expect(swing).toHaveValue('0.5');
+ await page.locator('.inspector details').evaluateAll(nodes => nodes.forEach(node => { (node as HTMLDetailsElement).open = true; }));
+ await page.getByRole('spinbutton', { name: 'cloth.0.outline.0.0', exact: true }).fill('1');
+ await expect(page.getByTestId('stale-banner')).toBeVisible();
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index f119be8..aca84ff 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -3,7 +3,7 @@ import { DEFAULT_SRC, frameSeconds, parseEmotion, parseExpression, parseFit, Rea
export { DEFAULT_SRC, EMOTIONS } from './attributes.js';
export type { Emotion, Fit } from './attributes.js';
-export type { AvatarSource, MeshAvatar, LiveExpression } from 'mesh-avatar';
+export type { AvatarSource, MeshAvatar, LiveExpression, ClothTuning } from 'mesh-avatar';
const STYLE = `
:host { display: block; position: relative; aspect-ratio: 1 / 1; }
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 9537da9..a9ed143 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -5,7 +5,7 @@ import { type MeshAvatarElement, type AvatarSource, type Emotion, type Fit, type
import 'mesh-avatar-element';
export { DEFAULT_SRC, EMOTIONS } from 'mesh-avatar-element';
-export type { MeshAvatarElement, AvatarSource, Emotion, Fit, LiveExpression, MeshAvatar as MeshAvatarInstance } from 'mesh-avatar-element';
+export type { MeshAvatarElement, AvatarSource, Emotion, Fit, LiveExpression, ClothTuning, MeshAvatar as MeshAvatarInstance } from 'mesh-avatar-element';
export interface MeshAvatarProps extends Omit<HTMLAttributes<MeshAvatarElement>, 'onLoad' | 'onError' | 'children' | 'dangerouslySetInnerHTML'> {
src?: string;
diff --git a/packages/runtime/src/engine/cloth-tuning.js b/packages/runtime/src/engine/cloth-tuning.js
new file mode 100644
index 0000000..bebfc4b
--- /dev/null
+++ b/packages/runtime/src/engine/cloth-tuning.js
@@ -0,0 +1,16 @@
+/** @type {Readonly<import('../rig/types').ClothTuning>} */
+export const CLOTH_DEFAULTS = Object.freeze({
+ swing: 1, stiffness: 1, damping: 1, follow: 0.85, cohesion: 3, wind: 0.05, max: 20,
+});
+
+/** Validate a partial override before applying it to any garment. */
+export function checkClothTuning(tuning) {
+ if (!tuning || typeof tuning !== 'object' || Array.isArray(tuning)) throw new TypeError('Expected cloth tuning');
+ for (const [key, value] of Object.entries(tuning)) {
+ if (!Object.hasOwn(CLOTH_DEFAULTS, key)) throw new RangeError(`Unknown cloth tuning: ${key}`);
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new RangeError(`${key}: expected a finite number`);
+ if (['swing', 'stiffness', 'damping', 'max'].includes(key) && value <= 0) throw new RangeError(`${key}: must be positive`);
+ if (['follow', 'wind'].includes(key) && (value < 0 || (key === 'follow' && value > 1))) throw new RangeError(`${key}: out of range`);
+ if (key === 'cohesion' && (!Number.isInteger(value) || value < 0 || value > 8)) throw new RangeError('cohesion: expected an integer from 0 to 8');
+ }
+}
diff --git a/packages/runtime/src/engine/cloth.js b/packages/runtime/src/engine/cloth.js
new file mode 100644
index 0000000..4cd37a6
--- /dev/null
+++ b/packages/runtime/src/engine/cloth.js
@@ -0,0 +1,182 @@
+// Garments (rig.cloth): a grid of nodes between the waist line and the hem. Each column is a
+// spring chain from the waist down, and the columns are bound together so the garment swings
+// as one sheet instead of splitting into strips. The garment layer is skinned to the grid.
+// The waist row follows the body; the rest keeps hanging down when the body rolls.
+
+import { CLOTH_DEFAULTS, checkClothTuning } from './cloth-tuning.js';
+
+/** Evenly spaced points (by arc length) along a polyline. */
+function resample(line, n) {
+ const lengths = [0];
+ for (let i = 1; i < line.length; i++)
+ lengths.push(lengths[i - 1] + Math.hypot(line[i][0] - line[i - 1][0], line[i][1] - line[i - 1][1]));
+ const total = lengths.at(-1);
+ return Array.from({ length: n }, (_, k) => {
+ const d = total * k / (n - 1);
+ let i = 1;
+ while (i < line.length - 1 && lengths[i] < d) i++;
+ const u = (d - lengths[i - 1]) / Math.max(1e-9, lengths[i] - lengths[i - 1]);
+ return [0, 1].map(a => line[i - 1][a] + (line[i][a] - line[i - 1][a]) * u);
+ });
+}
+
+/** @param {ReturnType<import('./rig.js').createRig>} engine
+ * @param {import('../rig/types').Rig} rig */
+export function createCloth(engine, rig) {
+ const { baseWeights, deformBase } = engine;
+ const TUNE = { waistHz: 2.6, zeta: 0.32 };
+
+ const garments = (rig.cloth ?? []).map(c => {
+ const cols = c.columns ?? 8, rows = c.rows ?? 5;
+ const top = resample(c.waist, cols), bot = resample(c.hem, cols);
+ const rest = new Float64Array(rows * cols * 2);
+ for (let r = 0; r < rows; r++) for (let k = 0; k < cols; k++) {
+ const v = r / (rows - 1), i = (r * cols + k) * 2;
+ rest[i] = top[k][0] + (bot[k][0] - top[k][0]) * v;
+ rest[i + 1] = top[k][1] + (bot[k][1] - top[k][1]) * v;
+ }
+ return {
+ c, tuning: Object.fromEntries(Object.entries(CLOTH_DEFAULTS).map(([key, value]) => [key, c[key] ?? value])),
+ cols, rows, rest, top, weights: top.map(([x, y]) => baseWeights(x, y, 0)),
+ target: new Float64Array(rest.length), pos: null, vel: new Float64Array(rest.length),
+ out: Float64Array.from(rest), parent: null, parentLoc: null, meshes: [],
+ };
+ });
+ const byName = Object.fromEntries(garments.map(g => [g.c.name, g]));
+
+ // Grid coordinates of a point: the cell and its bilinear (s, t). Points outside the grid get
+ // the nearest cell, extrapolated, so ruffles past the waist or hem line still follow it.
+ function locate(g, x, y) {
+ let best = null;
+ for (let r = 0; r < g.rows - 1; r++) for (let k = 0; k < g.cols - 1; k++) {
+ const q = [(r * g.cols + k) * 2, (r * g.cols + k + 1) * 2, ((r + 1) * g.cols + k + 1) * 2, ((r + 1) * g.cols + k) * 2];
+ const [ax, ay, bx, by, cx, cy, dx, dy] = q.flatMap(i => [g.rest[i], g.rest[i + 1]]);
+ let s = 0.5, t = 0.5;
+ for (let it = 0; it < 10; it++) {
+ const fx = ax * (1 - s) * (1 - t) + bx * s * (1 - t) + cx * s * t + dx * (1 - s) * t - x;
+ const fy = ay * (1 - s) * (1 - t) + by * s * (1 - t) + cy * s * t + dy * (1 - s) * t - y;
+ const sx = (bx - ax) * (1 - t) + (cx - dx) * t, sy = (by - ay) * (1 - t) + (cy - dy) * t;
+ const tx = (dx - ax) * (1 - s) + (cx - bx) * s, ty = (dy - ay) * (1 - s) + (cy - by) * s;
+ const det = sx * ty - sy * tx;
+ if (Math.abs(det) < 1e-9) break;
+ s -= (fx * ty - fy * tx) / det;
+ t -= (sx * fy - sy * fx) / det;
+ }
+ const miss = Math.max(0, -s, s - 1) + Math.max(0, -t, t - 1);
+ if (!best || miss < best.miss) best = { q, s, t, miss };
+ }
+ best.s = Math.min(4, Math.max(-3, best.s));
+ best.t = Math.min(4, Math.max(-3, best.t));
+ return best;
+ }
+ function place(p, loc, out) {
+ const { q, s, t } = loc, w = [(1 - s) * (1 - t), s * (1 - t), s * t, (1 - s) * t];
+ out[0] = 0; out[1] = 0;
+ for (let j = 0; j < 4; j++) { out[0] += p[q[j]] * w[j]; out[1] += p[q[j] + 1] * w[j]; }
+ return out;
+ }
+ for (const g of garments) if (g.c.parent) {
+ g.parent = byName[g.c.parent];
+ g.parentLoc = g.top.map(([x, y]) => locate(g.parent, x, y));
+ }
+
+ const softLimit = (o, i, m) => {
+ const l = Math.hypot(o[i], o[i + 1]);
+ if (l < 1e-6) return;
+ const k = m * Math.tanh(l / m) / l;
+ o[i] *= k; o[i + 1] *= k;
+ };
+
+ class Cloth {
+ constructor() {
+ this.gain = 1;
+ this.time = 0;
+ }
+
+ setTuning(name, tuning) {
+ checkClothTuning(tuning);
+ if (name !== null && !Object.hasOwn(byName, name)) throw new RangeError(`Unknown cloth: ${name}`);
+ for (const g of garments) if (name === null || g.c.name === name) Object.assign(g.tuning, tuning);
+ }
+
+ /** Skin a layer mesh (rest/pos arrays in source px) to the named garment. */
+ attach(name, mesh) {
+ const g = byName[name];
+ const locs = [];
+ for (let i = 0; i < mesh.rest.length; i += 2) locs.push(locate(g, mesh.rest[i], mesh.rest[i + 1]));
+ g.meshes.push({ mesh, locs });
+ }
+
+ step(P, dt, phys) {
+ const sub = Math.max(1, Math.ceil(dt / (1 / 240)));
+ const h = Math.min(dt, 0.05) / sub;
+ const gain = this.gain, a = [0, 0];
+ for (const g of garments) {
+ const { cols, rows, rest, target, vel, out } = g;
+ const { stiffness: stiff, damping: damp, max, swing, follow, cohesion, wind: breeze } = g.tuning;
+ // the waist row follows the body (or the parent garment); every row below is carried by
+ // its column's waist point without rotating, so the garment keeps hanging down
+ for (let k = 0; k < cols; k++) {
+ if (g.parent) place(g.parent.out, g.parentLoc[k], a);
+ else deformBase(g.top[k][0], g.top[k][1], g.weights[k], P, phys, a);
+ const dx = a[0] - rest[k * 2], dy = a[1] - rest[k * 2 + 1];
+ for (let r = 0; r < rows; r++) {
+ const i = (r * cols + k) * 2;
+ target[i] = rest[i] + dx; target[i + 1] = rest[i + 1] + dy;
+ }
+ }
+ if (!g.pos) g.pos = Float64Array.from(target);
+ const pos = g.pos;
+ for (let k = 0; k < cols * 2; k++) { pos[k] = target[k]; vel[k] = 0; }
+ for (let n = 0; n < sub; n++) {
+ const t = this.time + n * h;
+ for (let r = 1; r < rows; r++) {
+ const v = rows > 2 ? (r - 1) / (rows - 2) : 1;
+ const w = 2 * Math.PI * (TUNE.waistHz + (swing - TUNE.waistHz) * v);
+ const kk = w * w * stiff / Math.max(0.35, gain);
+ const c = 2 * TUNE.zeta * damp * Math.sqrt(kk);
+ const down = r / (rows - 1);
+ for (let k = 0; k < cols; k++) {
+ const i = (r * cols + k) * 2, up = i - cols * 2;
+ const wind = (Math.sin(t * 1.1 + k * 0.5) * 0.6 + Math.sin(t * 2.3 + k * 0.9) * 0.4) * max * breeze * down;
+ const tx = target[i] + (pos[up] - target[up]) * follow + wind;
+ const ty = target[i + 1] + (pos[up + 1] - target[up + 1]) * follow;
+ vel[i] += (kk * (tx - pos[i]) - c * vel[i]) * h;
+ vel[i + 1] += (kk * (ty - pos[i + 1]) - c * vel[i + 1]) * h;
+ pos[i] += vel[i] * h; pos[i + 1] += vel[i + 1] * h;
+ }
+ }
+ }
+ // offsets from the carried rest shape, smoothed across the columns and limited
+ const o = new Float64Array(pos.length);
+ for (let i = 0; i < pos.length; i++) o[i] = pos[i] - target[i];
+ for (let pass = 0; pass < cohesion; pass++) for (let r = 1; r < rows; r++) {
+ const row = o.slice(r * cols * 2, (r + 1) * cols * 2);
+ for (let k = 0; k < cols; k++) {
+ const l = Math.max(0, k - 1), rr = Math.min(cols - 1, k + 1), i = (r * cols + k) * 2;
+ for (const ax of [0, 1]) o[i + ax] = row[k * 2 + ax] * 0.5 + (row[l * 2 + ax] + row[rr * 2 + ax]) * 0.25;
+ }
+ }
+ for (let r = 1; r < rows; r++) for (let k = 0; k < cols; k++)
+ softLimit(o, (r * cols + k) * 2, max * r / (rows - 1) / Math.max(1, Math.abs(gain)));
+ for (let i = 0; i < pos.length; i++) out[i] = target[i] + o[i] * gain;
+ }
+ this.time += dt;
+ }
+
+ deform() {
+ const p = [0, 0];
+ for (const g of garments) for (const { mesh, locs } of g.meshes) {
+ for (let v = 0; v < locs.length; v++) {
+ place(g.out, locs[v], p);
+ mesh.pos[v * 2] = p[0]; mesh.pos[v * 2 + 1] = p[1];
+ }
+ }
+ }
+
+ /** Grid nodes per garment, for debug overlays. */
+ get grids() { return garments.map(g => ({ name: g.c.name, cols: g.cols, rows: g.rows, nodes: g.out })); }
+ }
+
+ return { Cloth, garments };
+}
diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.js
index a2700eb..5e0f767 100644
--- a/packages/runtime/src/engine/createMeshAvatar.js
+++ b/packages/runtime/src/engine/createMeshAvatar.js
@@ -4,6 +4,7 @@
import { createRig } from './rig.js';
import { createRenderer } from './renderer.js';
import { createPhysics } from './physics.js';
+import { createCloth } from './cloth.js';
import { createSpriteModule, eyeMood } from './sprites.js';
import { Motion } from './motion.js';
import { ExpressionOverlay } from './expression-overlay.js';
@@ -71,6 +72,8 @@ export async function createMeshAvatarImpl(canvas, options) {
handWeights, handFrame, deformHand, TASSELS } = engine;
const { Renderer, buildGrid } = createRenderer(engine, rig);
const { Physics } = createPhysics(engine, rig);
+ const { Cloth } = createCloth(engine, rig);
+ const CLOTH = rig.cloth ?? [];
const { createSprites } = createSpriteModule(engine, rig);
const base = (options.assetsBase ?? '').replace(/\/?$/, '/');
const asset = (name, build) => {
@@ -82,8 +85,11 @@ export async function createMeshAvatarImpl(canvas, options) {
};
const meta = await loadJson(asset('layers.json'));
- const names = ['base', ...(rig.hand ? ['hand'] : []), ...TASSELS.map(t => t.name), ...[0, 1].flatMap(i => EYE_PARTS.map(p => `eye${i}_${p}`)), 'hairmask'];
+ // with garments the base drawing is the one without them (base.png keeps them for older runtimes)
+ const baseName = CLOTH.length ? 'base_cloth' : 'base';
+ const names = [baseName, ...(rig.hand ? ['hand'] : []), ...TASSELS.map(t => t.name), ...CLOTH.map(c => `cloth_${c.name}`), ...[0, 1].flatMap(i => EYE_PARTS.map(p => `eye${i}_${p}`)), 'hairmask'];
const imgs = Object.fromEntries(await Promise.all(names.map(async n => [n, await loadImage(asset(`${n}.png`, meta.build))])));
+ if (CLOTH.length) imgs.base = imgs.base_cloth;
const hairMask = channelOf(imgs.hairmask, 0);
const hairAt = (x, y) => hairMask[Math.min(IMG.h - 1, Math.max(0, Math.round(y))) * IMG.w + Math.min(IMG.w - 1, Math.max(0, Math.round(x)))] / 255;
@@ -94,6 +100,16 @@ export async function createMeshAvatarImpl(canvas, options) {
const rects = { base: [0, 0, IMG.w, IMG.h], ...meta.layers };
// base layer, denser where hair strands bend and the face parts shift
+ // garments behind the body (drawn first) and in front of it, each skinned to its cloth grid
+ const cloth = new Cloth();
+ const addCloth = c => {
+ const n = `cloth_${c.name}`;
+ const mesh = buildGrid(rects[n], rig.mesh.clothCell ?? 8, alphaOf(imgs[n]), imgs[n].width);
+ cloth.attach(c.name, mesh);
+ R.addLayer(n, imgs[n], mesh);
+ };
+ CLOTH.filter(c => c.behind).forEach(addCloth);
+
const baseMesh = buildGrid(rects.base, rig.mesh.baseCell, alphaOf(imgs.base), imgs.base.width, rig.mesh.fine);
const baseW = [];
for (let i = 0; i < baseMesh.rest.length / 2; i++) {
@@ -128,6 +144,8 @@ export async function createMeshAvatarImpl(canvas, options) {
console.warn('eye / mouth sprites not loaded:', err);
}
+ CLOTH.filter(c => !c.behind).forEach(addCloth);
+
const tassels = TASSELS.map(t => {
const mesh = buildGrid(rects[t.name], rig.mesh.tasselCell, alphaOf(imgs[t.name]), imgs[t.name].width);
return R.addLayer(t.name, imgs[t.name], mesh);
@@ -191,6 +209,7 @@ export async function createMeshAvatarImpl(canvas, options) {
hp[i * 2] = tmp[0]; hp[i * 2 + 1] = tmp[1];
}
physics.chains.forEach((ch, k) => deformTassel(ch, tassels[k].mesh));
+ if (CLOTH.length) { cloth.step(P, dt, phys); cloth.deform(); }
const ball = 7; // px of iris travel
R.draw({
@@ -248,7 +267,8 @@ export async function createMeshAvatarImpl(canvas, options) {
getLightingStats() { return { ...R.lightingStats }; },
setAutoMotion(on) { motion.autoMotion = !!on; },
/** Hair / tassel sway multiplier (1 = default). */
- setSwayGain(g) { physics.gain = g; },
+ setSwayGain(g) { physics.gain = g; cloth.gain = g; },
+ setClothTuning(name, tuning) { cloth.setTuning(name, tuning); },
/** Called with the motion id when a motion starts and with null when it ends. */
onMotion(fn) { listeners.add(fn); return () => listeners.delete(fn); },
/** Advance the simulation by `sec` and draw (for tests / hidden tabs). */
diff --git a/packages/runtime/src/engine/index.ts b/packages/runtime/src/engine/index.ts
index 44d7868..34d6956 100644
--- a/packages/runtime/src/engine/index.ts
+++ b/packages/runtime/src/engine/index.ts
@@ -1,5 +1,5 @@
import type { LightingSettings } from '../lighting/settings';
-import type { Rig } from '../rig/types';
+import type { Rig, ClothTuning } from '../rig/types';
import { parseRig } from '../rig/validate';
import { createMeshAvatarImpl } from './createMeshAvatar.js';
import { OVERLAY_EXPRESSIONS } from './expression-overlay.js';
@@ -37,6 +37,8 @@ export interface MeshAvatar {
setAutoIdle(on: boolean): void;
setAutoMotion(on: boolean): void;
setSwayGain(gain: number): void;
+ /** Override garment physics without rebuilding layers; null applies to every garment. */
+ setClothTuning(name: string | null, tuning: Partial<ClothTuning>): void;
onMotion(listener: (id: string | null) => void): () => void;
advance(seconds: number, fps?: number): void;
advanceParameters(seconds: number): void;
diff --git a/packages/runtime/src/engine/rig.js b/packages/runtime/src/engine/rig.js
index 0b0b584..cbab833 100644
--- a/packages/runtime/src/engine/rig.js
+++ b/packages/runtime/src/engine/rig.js
@@ -192,7 +192,10 @@ export function createRig(rig) {
// inhale: everything above the cut-off rises, shoulders lift more, the chest widens a little
p[1] -= b * (5 * breathW + 4 * shoulder);
p[0] += (p[0] - BODY.chest.cx) * 0.012 * b * chest;
- p[0] += P.bodyAngleX / 10 * (7 + 9 * chest);
+ // full-body rigs (body.hip): the sideways sway is a hip shift that fades out towards
+ // the feet, so they stay planted
+ const hip = BODY.hip;
+ p[0] += P.bodyAngleX / 10 * (hip ? hip.shift * (1 - sstep(...hip.band, restY)) : 7 + 9 * chest);
// bottom rows stay put so no gap opens at the cut-off edge of the image
rotateAround(p, BODY.pivotX, BODY.pivotY, -P.bodyAngleZ / 10 * BODY.maxRoll * (1 - sstep(...BODY.rollBand, restY)));
}
diff --git a/packages/runtime/src/format/open.ts b/packages/runtime/src/format/open.ts
index bbaa471..492641d 100644
--- a/packages/runtime/src/format/open.ts
+++ b/packages/runtime/src/format/open.ts
@@ -21,8 +21,8 @@ function json(bytes: Uint8Array, path: string) {
try { return decode(bytes); }
catch { throw new Error(`${path}: invalid UTF-8 JSON`); }
}
-function assetNames(layers: { layers?: Record<string, unknown> }, sprites?: { layers?: Record<string, unknown> }) {
- return ['layers.json', 'base.png', 'hairmask.png', ...Object.keys(layers?.layers ?? {}).map(name => `${name}.png`),
+function assetNames(layers: { layers?: Record<string, unknown> }, sprites?: { layers?: Record<string, unknown> }, rig?: { cloth?: unknown[] }) {
+ return ['layers.json', 'base.png', 'hairmask.png', ...(rig?.cloth?.length ? ['base_cloth.png'] : []), ...Object.keys(layers?.layers ?? {}).map(name => `${name}.png`),
...(sprites ? ['sprites/sprites.json', ...Object.keys(sprites.layers ?? {}).map(name => `sprites/${name}.png`)] : [])];
}
function assertValid(files: Parameters<typeof validateAvatarFiles>[0]) {
@@ -39,7 +39,7 @@ function fromArchive(data: ArrayBuffer | Uint8Array): AvatarPackage {
const manifest = parseManifest(json(files['avatar.json'], 'avatar.json'));
const rig = parseRig(json(files['rig.json'], 'rig.json'));
const names = assetNames(json(files['built/layers.json'], 'built/layers.json'),
- files['built/sprites/sprites.json'] ? json(files['built/sprites/sprites.json'], 'built/sprites/sprites.json') : undefined);
+ files['built/sprites/sprites.json'] ? json(files['built/sprites/sprites.json'], 'built/sprites/sprites.json') : undefined, rig);
const assets: Record<string, string> = {}, urls: string[] = [];
const release = () => { urls.splice(0).forEach(url => URL.revokeObjectURL(url)); };
try {
@@ -92,7 +92,7 @@ export async function openAvatar(source: AvatarSource, options: OpenAvatarOption
});
}
files['rig.json'] = new TextEncoder().encode(JSON.stringify(raw));
- const names = assetNames(metadata, sprites);
+ const names = assetNames(metadata, sprites, raw);
// Folder images stay as URLs; the renderer (or editor preflight) checks image readability.
for (const name of names) if (name.endsWith('.png')) files[`built/${name}`] = { size: 1 };
assertValid(files);
diff --git a/packages/runtime/src/format/project-archive.ts b/packages/runtime/src/format/project-archive.ts
index 0ec39ea..1c3335c 100644
--- a/packages/runtime/src/format/project-archive.ts
+++ b/packages/runtime/src/format/project-archive.ts
@@ -18,6 +18,7 @@ export async function packProjectAvatar(
const source = manifest?.source ?? 'source.png', thumbnail = manifest?.thumbnail ?? 'thumbnail.png';
checkEntryName(source); checkEntryName(thumbnail);
wanted.add('built/base.png'); wanted.add('built/hairmask.png'); wanted.add(thumbnail);
+ if (json('rig.json').cloth?.length) wanted.add('built/base_cloth.png');
if (includeSource) wanted.add(source);
for (const [path, prefix] of [['built/layers.json', 'built/'], ['built/sprites/sprites.json', 'built/sprites/']]) {
if (!metadata[path]) continue;
diff --git a/packages/runtime/src/format/validate.ts b/packages/runtime/src/format/validate.ts
index 03ee9d0..ac89bf4 100644
--- a/packages/runtime/src/format/validate.ts
+++ b/packages/runtime/src/format/validate.ts
@@ -68,6 +68,7 @@ export function validateAvatarFiles(files: Record<string, FileData>): string[] {
if (!problems.length) rig = rawRig as unknown as Rig;
}
image('built/base.png'); image('built/hairmask.png');
+ if (rig?.cloth?.length) image('built/base_cloth.png');
const meta = json('built/layers.json');
if (meta && version(meta, 'built/layers.json')) {
build(meta, 'built/layers.json');
@@ -81,7 +82,8 @@ export function validateAvatarFiles(files: Record<string, FileData>): string[] {
const rectangles = layers(meta.layers, 'built/layers.json', 'built', size);
if (rig && rectangles) {
const required = [...rig.eyes.flatMap((_, i) => ['ball', 'low', 'crease', 'lash'].map(part => `eye${i}_${part}`)),
- ...(rig.hand ? ['hand'] : []), ...(rig.accessories ?? []).map(part => part.name)];
+ ...(rig.hand ? ['hand'] : []), ...(rig.accessories ?? []).map(part => part.name),
+ ...(rig.cloth ?? []).map(part => `cloth_${part.name}`)];
for (const name of required) if (!own(rectangles, name)) errors.push(`built/layers.json.layers.${name}: missing required layer`);
}
if (!Array.isArray(meta.eyes) || meta.eyes.length !== 2) {
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 2f0641e..9efd026 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,6 +1,6 @@
export { createMeshAvatar, LIVE_EXPRESSIONS } from './engine';
export type { MeshAvatar, MeshAvatarOptions, LiveExpression } from './engine';
-export type { Rig, Eye, Strand, Accessory, Hand, Ellipse, Point, Band } from './rig/types';
+export type { Rig, Eye, Strand, Accessory, Hand, Cloth, ClothTuning, Ellipse, Point, Band } from './rig/types';
export { validateRig, parseRig } from './rig/validate';
export { PARAMS } from './engine/rig.js';
export type { LightingSettings } from './lighting/settings';
diff --git a/packages/runtime/src/rig/numeric.ts b/packages/runtime/src/rig/numeric.ts
index a28b5f3..3ef3d37 100644
--- a/packages/runtime/src/rig/numeric.ts
+++ b/packages/runtime/src/rig/numeric.ts
@@ -1,5 +1,6 @@
// These values count pixels or cells; subpixel precision is useful for other geometry.
export function isIntegerField(path: string): boolean {
+ if (/^(?:cloth\.\d+\.(?:columns|rows|cohesion)|mesh\.clothCell)$/.test(path)) return true;
return /^(?:image\.(?:width|height)|accessories\.\d+\.box\.\d+|mesh\.(?:baseCell|handCell|tasselCell|eyeBallCell|eyeCell|spriteCell|fine\.(?:x0|x1|y0|y1|cell)))$/.test(path);
}
export function editorNumber(path: string, value: number): number {
diff --git a/packages/runtime/src/rig/types.ts b/packages/runtime/src/rig/types.ts
index 5fbdd20..6109d8a 100644
--- a/packages/runtime/src/rig/types.ts
+++ b/packages/runtime/src/rig/types.ts
@@ -24,6 +24,26 @@ export interface Accessory {
box: [number, number, number, number];
color: { redness: number; minRed: number };
}
+/** Optional garment that swings with the body (for example a skirt). */
+export interface ClothTuning {
+ swing: number;
+ stiffness: number;
+ damping: number;
+ follow: number;
+ cohesion: number;
+ wind: number;
+ max: number;
+}
+export interface Cloth extends Partial<ClothTuning> {
+ name: string;
+ outline: Point[];
+ waist: Point[];
+ hem: Point[];
+ columns?: number;
+ rows?: number;
+ behind?: boolean;
+ parent?: string;
+}
export interface Hand {
outline: Point[];
jaw: Point[];
@@ -51,6 +71,7 @@ export interface Rig {
body: {
pivotX: number; pivotY: number; maxRoll: number;
breathBand: Band; rollBand: Band; chest: Ellipse; shoulders: Ellipse[];
+ hip?: { shift: number; band: Band };
};
face: Record<'nose' | 'mouth' | 'eyeA' | 'eyeB' | 'earL' | 'earR', Ellipse> & {
brow: Ellipse & { band: Band };
@@ -66,11 +87,12 @@ export interface Rig {
strands?: Strand[];
accessories?: Accessory[];
hand?: Hand;
+ cloth?: Cloth[];
mesh: {
baseCell: number;
fine: { x0: number; x1: number; y0: number; y1: number; cell: number };
handCell: number; tasselCell: number; eyeBallCell: number;
- eyeCell: number; spriteCell: number;
+ eyeCell: number; spriteCell: number; clothCell?: number;
};
view: { padTop: number; padSide: number; gazeCenter?: Point };
}
diff --git a/packages/runtime/src/rig/validate.ts b/packages/runtime/src/rig/validate.ts
index f2f59c8..36cebe8 100644
--- a/packages/runtime/src/rig/validate.ts
+++ b/packages/runtime/src/rig/validate.ts
@@ -8,6 +8,14 @@ const positive: Check = (v, p, e) => {
number(v, p, e);
if (typeof v === 'number' && v <= 0) e.push(`${p}: must be positive`);
};
+const nonnegative: Check = (v, p, e) => {
+ number(v, p, e);
+ if (typeof v === 'number' && v < 0) e.push(`${p}: must be nonnegative`);
+};
+const cohesion: Check = (v, p, e) => {
+ nonnegative(v, p, e);
+ if (typeof v === 'number' && (!Number.isInteger(v) || v > 8)) e.push(`${p}: expected an integer from 0 to 8`);
+};
const integer: Check = (v, p, e) => {
positive(v, p, e);
if (typeof v === 'number' && !Number.isInteger(v)) e.push(`${p}: expected an integer`);
@@ -51,7 +59,8 @@ const schema = (draft: boolean) => object({
head: object({ ...ellipseFields, shiftX: number, shiftY: number, pivotX: number,
pivotY: number, maxRoll: number, weightBand: band, turnBand: band }),
body: object({ pivotX: number, pivotY: number, maxRoll: number, breathBand: band,
- rollBand: band, chest: ellipse, shoulders: array(ellipse) }),
+ rollBand: band, chest: ellipse, shoulders: array(ellipse),
+ hip: object({ shift: number, band }) }, ['hip']),
face: object({ nose: ellipse, mouth: ellipse, eyeA: ellipse, eyeB: ellipse,
earL: ellipse, earR: ellipse, brow: object({ ...ellipseFields, band }),
jaw: object({ ...ellipseFields, band }) }),
@@ -68,11 +77,17 @@ const schema = (draft: boolean) => object({
elbow: point, wrist: point, knuckle: point, contact: point, forearmShare: unit,
armBand: band, wristBand: band, handBand: band, fingerXBand: band,
fingerYBand: band, pinBand: band }),
+ cloth: array(object({ name: string, outline: polygon, waist: line, hem: line,
+ columns: integer, rows: integer, stiffness: positive, damping: positive, max: positive,
+ swing: positive, follow: unit, cohesion, wind: nonnegative,
+ behind: (v, p, e) => { if (typeof v !== 'boolean') e.push(`${p}: expected a boolean`); },
+ parent: string }, ['columns', 'rows', 'stiffness', 'damping', 'max', 'swing', 'follow', 'cohesion', 'wind', 'behind', 'parent'])),
mesh: object({ baseCell: integer, fine: object({ x0: wholeNumber, x1: wholeNumber,
y0: wholeNumber, y1: wholeNumber, cell: integer }), handCell: integer,
- tasselCell: integer, eyeBallCell: integer, eyeCell: integer, spriteCell: integer }),
+ tasselCell: integer, eyeBallCell: integer, eyeCell: integer, spriteCell: integer,
+ clothCell: integer }, ['clothCell']),
view: object({ padTop: number, padSide: number, gazeCenter: point }, ['gazeCenter']),
-}, ['buns', 'strands', 'accessories', 'hand']);
+}, ['buns', 'strands', 'accessories', 'hand', 'cloth']);
export function validateRig(value: unknown, options: { draft?: boolean } = {}): string[] {
const errors: string[] = [];
@@ -104,6 +119,16 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):
if (accessory.pivot.every((n, k) => n === accessory.tip[k])) errors.push(`rig.accessories[${i}].tip: must differ from pivot`);
if (accessory.box[0] >= accessory.box[2] || accessory.box[1] >= accessory.box[3]) errors.push(`rig.accessories[${i}].box: rectangle must have positive area`);
}
+ const clothNames = new Set<string>();
+ for (const [i, cloth] of (rig.cloth ?? []).entries()) {
+ if (!/^[A-Za-z0-9_-]+$/.test(cloth.name) || clothNames.has(cloth.name))
+ errors.push(`rig.cloth[${i}].name: must be a unique layer-safe name`);
+ if (cloth.parent !== undefined && !clothNames.has(cloth.parent))
+ errors.push(`rig.cloth[${i}].parent: must name an earlier cloth entry`);
+ if ((cloth.columns ?? 2) < 2 || (cloth.rows ?? 2) < 2)
+ errors.push(`rig.cloth[${i}]: columns and rows must be at least 2`);
+ clothNames.add(cloth.name);
+ }
return errors;
}
diff --git a/packages/runtime/tests/cli.test.ts b/packages/runtime/tests/cli.test.ts
index c1cb983..4823ef8 100644
--- a/packages/runtime/tests/cli.test.ts
+++ b/packages/runtime/tests/cli.test.ts
@@ -33,5 +33,15 @@ test('pack CLI selects playback files, honors --no-source and protects existing
const editable = resolve(root, 'editable.mavatar');
expect(command('pack-avatar', [root, '-o', editable]).status).toBe(0);
expect(unpackAvatar(readFileSync(editable))['original.png']).toEqual(new Uint8Array([2]));
+ const rigPath = resolve(root, 'rig.json'), rig = JSON.parse(readFileSync(rigPath, 'utf8'));
+ rig.cloth = [{ name: 'skirt', outline: [[0, 0], [100, 0], [100, 100]], waist: [[0, 0], [100, 0]], hem: [[0, 100], [100, 100]] }];
+ writeFileSync(rigPath, JSON.stringify(rig));
+ const metaPath = resolve(root, 'built/layers.json'), meta = JSON.parse(readFileSync(metaPath, 'utf8'));
+ meta.layers.cloth_skirt = [0, 0, 100, 100]; writeFileSync(metaPath, JSON.stringify(meta));
+ for (const file of ['base_cloth', 'cloth_skirt']) writeFileSync(resolve(root, `built/${file}.png`), new Uint8Array([3]));
+ const clothed = resolve(root, 'cloth.mavatar');
+ expect(command('pack-avatar', [root, '-o', clothed]).status).toBe(0);
+ expect(unpackAvatar(readFileSync(clothed))['built/base_cloth.png']).toEqual(new Uint8Array([3]));
+ expect(command('validate-avatar', [clothed]).status).toBe(0);
} finally { rmSync(root, { recursive: true, force: true }); }
-});
+}, 60000);
diff --git a/packages/runtime/tests/format.test.ts b/packages/runtime/tests/format.test.ts
index a46ec54..f253ea5 100644
--- a/packages/runtime/tests/format.test.ts
+++ b/packages/runtime/tests/format.test.ts
@@ -9,6 +9,16 @@ import sprites from '../../../samples/miko-qipao/built/sprites/sprites.json';
import manifest from '../../../samples/miko-qipao/avatar.json';
const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));
+test('cloth folders require both the bare base and the named garment layer', () => {
+ const files = fixture(), r = structuredClone(rig);
+ const cloth = { name: 'skirt', outline: [[0, 0], [100, 0], [50, 100]], waist: [[0, 0], [100, 0]], hem: [[0, 100], [100, 100]] };
+ files['rig.json'] = encode({ ...r, cloth: [cloth] });
+ expect(validateAvatarFiles(files).join()).toContain('built/base_cloth.png');
+ expect(validateAvatarFiles(files).join()).toContain('cloth_skirt');
+ files['built/base_cloth.png'] = { size: 1 }; files['built/cloth_skirt.png'] = { size: 1 };
+ files['built/layers.json'] = encode({ ...metadata, layers: { ...metadata.layers, cloth_skirt: [0, 0, 100, 100] } });
+ expect(validateAvatarFiles(files)).toEqual([]);
+});
function fixture(): Parameters<typeof validateAvatarFiles>[0] {
const files: Parameters<typeof validateAvatarFiles>[0] = {
'avatar.json': encode(manifest), 'rig.json': encode(rig),
diff --git a/packages/runtime/tests/open.test.ts b/packages/runtime/tests/open.test.ts
index 8a81b3c..1b5bfb4 100644
--- a/packages/runtime/tests/open.test.ts
+++ b/packages/runtime/tests/open.test.ts
@@ -34,6 +34,23 @@ test('archive input forms expose the same rig and asset keys as folder loading',
expect(fetch).toHaveBeenCalledTimes(4);
});
+test('cloth folder and archive expose the bare base and garment cutout for the renderer', async () => {
+ const rig = decode('rig.json'), meta = decode('built/layers.json');
+ rig.cloth = [{ name: 'skirt', outline: [[0, 0], [100, 0], [100, 100]], waist: [[0, 0], [100, 0]], hem: [[0, 100], [100, 100]] }];
+ meta.layers.cloth_skirt = [0, 0, 100, 100];
+ const extra = { 'rig.json': new TextEncoder().encode(JSON.stringify(rig)), 'built/layers.json': new TextEncoder().encode(JSON.stringify(meta)),
+ 'built/base_cloth.png': new Uint8Array([1]), 'built/cloth_skirt.png': new Uint8Array([2]) };
+ vi.stubGlobal('fetch', folderFetch(extra));
+ const folder = await openAvatar('https://example.test/avatar/');
+ const packed = await openAvatar(packAvatar({ ...files, ...extra }));
+ try {
+ expect(folder.assets['base_cloth.png']).toContain('/built/base_cloth.png');
+ expect(folder.assets['cloth_skirt.png']).toContain('/built/cloth_skirt.png');
+ expect(packed.assets['base_cloth.png']).toMatch(/^blob:/);
+ expect(Object.keys(packed.assets).sort()).toEqual(Object.keys(folder.assets).sort());
+ } finally { packed.release(); folder.release(); }
+});
+
test('fetches archive URLs with query strings and creates usable, revocable image and JSON URLs', async () => {
const fetch = vi.fn(async (_input: RequestInfo | URL) => new Response(new Uint8Array(archive))); vi.stubGlobal('fetch', fetch);
const loaded = await openAvatar('https://example.test/avatar.mavatar?download=1');
diff --git a/src/editor/RigFields.tsx b/src/editor/RigFields.tsx
index 4813eb5..1c25c76 100644
--- a/src/editor/RigFields.tsx
+++ b/src/editor/RigFields.tsx
@@ -2,6 +2,7 @@ import type { Rig } from 'mesh-avatar';
import { getAt } from './model';
import { NumericField } from './NumericField';
import { useI18n } from './i18n';
+import { CLOTH_DEFAULTS } from '../../packages/runtime/src/engine/cloth-tuning.js';
export function RigFields({ rig, path, scope = path, onChange }: {
rig: Rig; path: string; scope?: string; onChange: (path: string, value: number) => void;
@@ -17,7 +18,12 @@ export function RigFields({ rig, path, scope = path, onChange }: {
value={number} onChange={next => onChange(`${path}.${index}`, next)} />)}
</div><small>{path}</small></div>;
}
- const children = Object.entries(value).map(([key]) => <RigFields key={key} rig={rig} path={`${path}.${key}`} scope={scope} onChange={onChange} />);
+ const fields = /^cloth\.\d+$/.test(path) ? { ...CLOTH_DEFAULTS, ...value } : value;
+ const children = Object.entries(fields).map(([key, child]) =>
+ /^cloth\.\d+$/.test(path) && Object.hasOwn(CLOTH_DEFAULTS, key)
+ ? <NumericField key={key} path={`${path}.${key}`} label={title(key)} value={child as number} onChange={number => onChange(`${path}.${key}`, number)} />
+ : <RigFields key={key} rig={rig} path={`${path}.${key}`} scope={scope} onChange={onChange} />);
if (Array.isArray(value)) return <details open={path === 'eyes' || path === 'strands'}><summary>{label} ({value.length})</summary><div className="fields">{children}</div></details>;
+ if (/^cloth\.\d+$/.test(path)) return <details open><summary>{(value as { name: string }).name}</summary><div className="fields">{children}</div></details>;
return <>{children}</>;
}
diff --git a/src/editor/i18n-zh.ts b/src/editor/i18n-zh.ts
index a50c53a..e00032b 100644
--- a/src/editor/i18n-zh.ts
+++ b/src/editor/i18n-zh.ts
@@ -89,6 +89,7 @@ export const workflowZh: typeof workflowEn = {
};
export const partsZh: Record<PartGroup, [string, string, string]> = {
+ cloth: ['布料', '裙摆和垂布的摆动。', '调整腰线与下摆控制点,再调整频率、阻尼和风力。'],
head: ['头部转动', '转头或倾斜时跟随动作的区域。', '把中心放在面部中央,椭圆应覆盖包括头发在内的整个头部。'],
eyes: ['眼睛', '眼睛开口轮廓,用于眨眼和视线变化。', '沿睫毛内侧描出眼睛开口,在轮廓转弯处添加控制点。'],
mouth: ['嘴巴', '闭嘴时的线条及嘴型差分的作用区域。', '把线条对齐闭合的嘴巴,并将周围区域限制在嘴唇附近。'],
@@ -104,6 +105,8 @@ export const partsZh: Record<PartGroup, [string, string, string]> = {
};
export const fieldsZh: Record<string, string> = {
+ swing: '下摆频率 (Hz)', stiffness: '刚度倍率', damping: '阻尼倍率', follow: '上行跟随', cohesion: '横向平滑次数',
+ wind: '风力', waist: '腰线', hem: '下摆线', columns: '列数', rows: '行数', clothCell: '布料网格间距',
image: '原图', width: '宽度', height: '高度', name: '名称',
center: '中心', pivot: '支点', rx: '横向半径', ry: '纵向半径',
cx: '中心 X', cy: '中心 Y', shiftX: '横向位移', shiftY: '纵向位移',
diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsx
index 9e5f06b..0282e7e 100644
--- a/src/editor/i18n.tsx
+++ b/src/editor/i18n.tsx
@@ -96,10 +96,11 @@ const ja: typeof en = {
};
const zh: typeof en = { ...workflowZh, ...uiZh };
export const dictionaries = { en, ja, zh };
-export type PartGroup = 'head' | 'eyes' | 'mouth' | 'face' | 'cheeks' | 'strands' | 'buns' | 'accessories' | 'body' | 'hand' | 'mesh' | 'view';
+export type PartGroup = 'head' | 'eyes' | 'mouth' | 'face' | 'cheeks' | 'strands' | 'buns' | 'accessories' | 'body' | 'hand' | 'cloth' | 'mesh' | 'view';
const partText: Record<Language, Record<PartGroup, [string, string, string]>> = {
zh: partsZh,
en: {
+ cloth: ['Cloth', 'Skirts and draped fabric.', 'Place the waist and hem handles, then adjust swing, damping and wind.'],
head: ['Head turn', 'Area that moves when the face turns or tilts.', 'Place the centre in the middle of the face; the circle should cover the whole head including hair.'],
eyes: ['Eyes', 'Outline of each eye opening; drives blinking and gaze.', 'Trace the opening inside the eyelashes. Add dots where the contour changes direction.'],
mouth: ['Mouth', 'Closed-mouth line and the area for drawn mouth shapes.', 'Align the line with the closed mouth, and keep the surrounding area close to the lips.'],
@@ -114,6 +115,7 @@ const partText: Record<Language, Record<PartGroup, [string, string, string]>> =
view: ['Framing', 'Preview margins.', 'Adjust the margins so the head and accessories stay inside the preview.'],
},
ja: {
+ cloth: ['布・スカート', 'スカートや垂れ布の揺れ。', '腰と裾の点を合わせ、周期・減衰・風の強さを調整してください。'],
head: ['頭の向き', '顔を振ったり傾けたりするときに動く範囲。', '中心を顔の真ん中に置き、円が髪を含む頭全体を覆うように調整してください。'],
eyes: ['目', '目の開口部の輪郭。まばたきと視線に使う。', 'まつ毛の内側に沿って輪郭を置き、曲がる場所に点を追加してください。'],
mouth: ['口', '閉じた口の線と、口の形の差し替え範囲。', '線を閉じた口に合わせ、周囲の範囲を唇の近くに収めてください。'],
@@ -129,6 +131,10 @@ const partText: Record<Language, Record<PartGroup, [string, string, string]>> =
},
};
const fieldText: Record<string, [string, string]> = {
+ swing: ['Hem frequency (Hz)', '裾の周波数 (Hz)'], stiffness: ['Stiffness multiplier', 'ばねの倍率'],
+ damping: ['Damping multiplier', '減衰の倍率'], follow: ['Row follow', '上の段への追従'], cohesion: ['Smoothing passes', '列の平滑化回数'],
+ wind: ['Wind strength', '風の強さ'], waist: ['Waist line', '腰の線'], hem: ['Hem line', '裾の線'],
+ columns: ['Columns', '列数'], rows: ['Rows', '行数'], clothCell: ['Cloth cell size', '布の格子幅'],
image: ['Source image', '元画像'],
center: ['Centre', '中心'], pivot: ['Pivot', '支点'], rx: ['Horizontal radius', '横の半径'], ry: ['Vertical radius', '縦の半径'],
cx: ['Centre X', '中心の横位置'], cy: ['Centre Y', '中心の縦位置'], shiftX: ['Horizontal travel', '横の移動量'], shiftY: ['Vertical travel', '縦の移動量'],
diff --git a/src/editor/model.ts b/src/editor/model.ts
index a52ea20..f051157 100644
--- a/src/editor/model.ts
+++ b/src/editor/model.ts
@@ -100,7 +100,7 @@ export function buildOverlay(rig: Rig): { handles: Handle[]; shapes: Shape[] } {
if (value.length >= 2 && value.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number'))) {
const points = value as Point[];
const closed = ['opening', 'roi', 'outline', 'background'].includes(key);
- const editable = closed || ['nodes', 'jaw'].includes(key);
+ const editable = closed || ['nodes', 'jaw', 'waist', 'hem'].includes(key);
if (group !== 'cheeks') shapes.push({ item: path, group, kind: 'line', points, closed, editable });
points.forEach((point, index) => {
const item = group === 'strands' ? path.split('.').slice(0, 2).join('.') : path;
diff --git a/src/editor/parts.ts b/src/editor/parts.ts
index abc8315..c708929 100644
--- a/src/editor/parts.ts
+++ b/src/editor/parts.ts
@@ -1,15 +1,15 @@
import type { Rig } from 'mesh-avatar';
import type { PartGroup } from './i18n';
-export const GROUPS: PartGroup[] = ['head', 'eyes', 'mouth', 'face', 'cheeks', 'strands', 'buns', 'accessories', 'body', 'hand', 'mesh', 'view'];
+export const GROUPS: PartGroup[] = ['head', 'eyes', 'mouth', 'face', 'cheeks', 'strands', 'buns', 'accessories', 'body', 'hand', 'cloth', 'mesh', 'view'];
export const PART_COLORS: Record<PartGroup, string> = {
head: '#159447', body: '#7c4dce', face: '#d72c68', eyes: '#0098a8', mouth: '#ea671a',
cheeks: '#d05383', strands: '#ca9b00', accessories: '#cf3030', hand: '#6c55d8',
- buns: '#ba31ad', mesh: '#5a6a7c', view: '#2b69d5',
+ buns: '#ba31ad', cloth: '#e040a0', mesh: '#5a6a7c', view: '#2b69d5',
};
export const SECTIONS = [
{ key: 'faceSection', groups: ['head', 'eyes', 'mouth', 'face', 'cheeks'] },
{ key: 'hairSection', groups: ['strands', 'buns', 'accessories'] },
- { key: 'bodySection', groups: ['body', 'hand'] },
+ { key: 'bodySection', groups: ['body', 'hand', 'cloth'] },
{ key: 'advanced', groups: ['mesh', 'view'] },
] as const;
export function partPresent(rig: Rig, group: PartGroup) {
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 6bcf33e..c59e131 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -33,7 +33,7 @@ export async function openProjectFolder(files: File[]): Promise<ProjectAssets> {
const metadata = JSON.parse(new TextDecoder().decode(layerBytes)) as { layers?: Record<string, unknown> };
if (!metadata.layers || typeof metadata.layers !== 'object') throw new Error('layers.json must contain layer rectangles.');
const available = new Set(entries.filter(entry => entry.path.startsWith(prefix)).map(entry => entry.path.slice(prefix.length)));
- const required = ['base.png', 'hairmask.png', ...Object.keys(metadata.layers).map(name => `${name}.png`)];
+ const required = ['base.png', 'hairmask.png', ...(rig?.cloth?.length ? ['base_cloth.png'] : []), ...Object.keys(metadata.layers).map(name => `${name}.png`)];
const missing = required.filter(name => !available.has(name));
if (missing.length) throw new FolderOpenError('missingFolderFiles', missing.map(name => `${prefix}${name}`));
// Reading the bytes catches locked files before replacing the current project.
diff --git a/src/editor/stale.ts b/src/editor/stale.ts
index 79d463b..c03f0fa 100644
--- a/src/editor/stale.ts
+++ b/src/editor/stale.ts
@@ -14,5 +14,6 @@ export function layerSignature(rig: Rig) {
jawRange: rig.hand.jawRange, background: rig.hand.background,
} : null,
accessories: (rig.accessories ?? []).map(part => ({ name: part.name, box: part.box, color: part.color })),
+ cloth: (rig.cloth ?? []).map(part => ({ name: part.name, outline: part.outline, behind: part.behind ?? false })),
});
}
diff --git a/tests/cloth.test.ts b/tests/cloth.test.ts
new file mode 100644
index 0000000..b73a8fb
--- /dev/null
+++ b/tests/cloth.test.ts
@@ -0,0 +1,91 @@
+import { expect, test } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { parseRig, validateRig, type Cloth, type ClothTuning } from 'mesh-avatar';
+import { createCloth } from '../packages/runtime/src/engine/cloth.js';
+import { CLOTH_DEFAULTS } from '../packages/runtime/src/engine/cloth-tuning.js';
+import { buildOverlay, moveHandle } from '../src/editor/model';
+import { layerSignature } from '../src/editor/stale';
+
+const garment = (): Cloth => ({ name: 'skirt', outline: [[0, 0], [100, 0], [100, 100], [0, 100]], waist: [[0, 0], [100, 0]], hem: [[0, 100], [100, 100]], columns: 4, rows: 5, wind: 0 });
+function simulation(tuning: Partial<ClothTuning> = {}, parts = [garment()]) {
+ const rig = parseRig(fixture); rig.cloth = parts.map(c => ({ ...c, ...tuning }));
+ const engine = {
+ baseWeights: () => ({}),
+ deformBase(x: number, y: number, _w: unknown, P: { shift: number }, _phys: unknown, out: number[]) {
+ out[0] = x + P.shift; out[1] = y; return out;
+ },
+ } as unknown as Parameters<typeof createCloth>[0];
+ const { Cloth: Simulator, garments } = createCloth(engine, rig);
+ const cloth = new Simulator();
+ const step = (shift = 0, frames = 1) => { for (let i = 0; i < frames; i++) cloth.step({ shift }, 1 / 60, {}); };
+ return { cloth, garments, step, rig };
+}
+
+test('optional cloth/hip/clothCell validate, including all tuning bounds and parent ordering', () => {
+ const rig = parseRig(fixture); rig.cloth = [garment()]; rig.body.hip = { shift: 20, band: [700, 1200] }; rig.mesh.clothCell = 8;
+ expect(validateRig(rig)).toEqual([]);
+ for (const bad of [{ rows: 1 }, { columns: 1 }, { parent: 'later' }, { swing: 0 }, { stiffness: 0 }, { damping: -1 }, { max: 0 }, { follow: 1.1 }, { wind: -1 }, { cohesion: 1.5 }, { cohesion: 9 }]) {
+ const r = structuredClone(rig); Object.assign(r.cloth![0], bad); expect(validateRig(r).length, JSON.stringify(bad)).toBeGreaterThan(0);
+ }
+ rig.cloth.push({ ...garment(), name: 'tail', parent: 'skirt' }); expect(validateRig(rig)).toEqual([]);
+ rig.cloth[1].name = 'skirt'; expect(validateRig(rig).join()).toContain('unique');
+ rig.mesh.clothCell = 0; rig.body.hip.band = [100, 0]; expect(validateRig(rig).join()).toContain('hip.band'); expect(validateRig(rig).join()).toContain('clothCell');
+});
+
+test('empty cloth is a no-op and default tuning matches explicit defaults', () => {
+ const empty = simulation({}, []); empty.step(100, 60); empty.cloth.deform(); expect(empty.cloth.grids).toEqual([]);
+ const a = simulation(), b = simulation({ ...CLOTH_DEFAULTS, wind: 0 });
+ for (const s of [0, 20, -10, 0]) { a.step(s, 30); b.step(s, 30); }
+ expect(a.cloth.grids[0].nodes).toEqual(b.cloth.grids[0].nodes);
+});
+
+test('no-wind cloth converges to rest and is deterministic through motion and release', () => {
+ const a = simulation(), b = simulation();
+ for (const s of [0, 20, -30, 0]) { a.step(s, 25); b.step(s, 25); }
+ expect(a.cloth.grids[0].nodes).toEqual(b.cloth.grids[0].nodes);
+ a.step(0, 1200);
+ expect(Math.max(...a.garments[0].out.map((v, i) => Math.abs(v - a.garments[0].rest[i])))).toBeLessThan(0.5);
+});
+
+test('grid offsets stay within max, including amplified sway', () => {
+ for (const gain of [0, 0.5, 1, 3]) {
+ const a = simulation({ max: 12, wind: 2 }); a.cloth.gain = gain;
+ a.step();
+ for (const s of [200, -200, 0]) {
+ a.step(s, 60);
+ const g = a.garments[0];
+ for (let i = 0; i < g.out.length; i += 2) expect(Math.hypot(g.out[i] - g.target[i], g.out[i + 1] - g.target[i + 1])).toBeLessThanOrEqual(12.000001);
+ }
+ }
+});
+
+test('live tuning targets one or all garments, validates atomically and never edits rig', () => {
+ const a = simulation({}, [garment(), { ...garment(), name: 'tail', parent: 'skirt' }]); const before = structuredClone(a.rig);
+ a.cloth.setTuning('tail', { swing: 0.5 }); expect(a.garments.map(g => g.tuning.swing)).toEqual([1, 0.5]);
+ a.cloth.setTuning(null, { wind: 0.2, cohesion: 0 }); expect(a.garments.map(g => g.tuning.wind)).toEqual([0.2, 0.2]);
+ expect(() => a.cloth.setTuning(null, { swing: 2, follow: 10 })).toThrow(); expect(a.garments[0].tuning.swing).toBe(1);
+ expect(() => a.cloth.setTuning('missing', {})).toThrow(); expect(a.rig).toEqual(before);
+});
+
+test('frequency changes oscillation and damping changes release amplitude', () => {
+ const trace = (tuning: Partial<ClothTuning>) => {
+ const s = simulation(); s.step(); s.step(20, 20); s.cloth.setTuning(null, tuning);
+ const values: number[] = []; for (let i = 0; i < 240; i++) { s.step(); values.push(s.cloth.grids[0].nodes.at(-2)! - 100); }
+ return values;
+ };
+ const slow = trace({ swing: 0.5 }), fast = trace({ swing: 2 });
+ const crossings = (values: number[]) => values.slice(1).filter((v, i) => v * values[i] < 0).length;
+ expect(crossings(fast)).toBeGreaterThan(crossings(slow));
+ const light = trace({ damping: 0.3 }), heavy = trace({ damping: 2 });
+ const energy = (v: number[]) => v.slice(120).reduce((s, x) => s + x * x, 0);
+ expect(energy(heavy)).toBeLessThan(energy(light));
+});
+
+test('cloth geometry has editable handles and only cut-out changes stale layers', () => {
+ const s = simulation(); const initial = layerSignature(s.rig);
+ s.rig.cloth![0].swing = 0.5; expect(layerSignature(s.rig)).toBe(initial);
+ const h = buildOverlay(s.rig).handles.find(h => h.id === 'cloth.0.waist.0')!;
+ expect(h.vertex?.closed).toBe(false);
+ const moved = moveHandle(s.rig, h, [10, 5]); expect(moved.cloth![0].waist[0]).toEqual([10, 5]); expect(layerSignature(moved)).toBe(initial);
+ s.rig.cloth![0].outline[0][0]++; expect(layerSignature(s.rig)).not.toBe(initial);
+});
diff --git a/tools/build-layers.py b/tools/build-layers.py
index 3ef2883..f12fe2d 100755
--- a/tools/build-layers.py
+++ b/tools/build-layers.py
@@ -265,6 +265,8 @@ def hair_mask(rgba, rig):
excluded |= ellipse_mask(shape, rig["face"][key])
if rig.get("hand"):
excluded |= polygon_mask(shape, rig["hand"]["outline"]) > 0
+ for cloth in rig.get("cloth", []):
+ excluded |= polygon_mask(shape, cloth["outline"]) > 0
opaque = rgba[..., 3] > 200
lab = cv2.cvtColor(rgba[..., :3], cv2.COLOR_RGB2LAB).astype(np.float32)
sampling = (sample > 0) & opaque & ~excluded
@@ -390,6 +392,60 @@ def hand_prefill(rgba, remove, hand):
return prefill, painted
+def build_cloth(project, rig, rgba, base, store, images):
+ """Cut each garment into its own layer and write base_cloth.png without them.
+
+ base.png keeps the garments, so runtimes that do not know rig.cloth still draw them.
+ A garment is its outline. With source_under.png (the same drawing without the
+ garments) it also takes the edge pixels just outside the approximate outline that
+ are background in the under drawing, or differ strongly from it; base_cloth takes
+ the under drawing wherever the two differ. Without it, the outline area is inpainted.
+ """
+ h, w = rgba.shape[:2]
+ shape = (h, w)
+ under = None
+ under_path = project / "source_under.png"
+ if under_path.exists():
+ with Image.open(under_path) as image:
+ under = np.array(image.convert("RGBA"))
+ if under.shape != rgba.shape:
+ raise ValueError("source_under.png must match source.png dimensions")
+ under[..., 3] = np.where(under[..., 3] > 240, 255, under[..., 3])
+ diff = np.abs(rgba.astype(np.int16) - under.astype(np.int16)).max(2)
+ # small differences over the body are redrawing noise, not garment
+ changed = (
+ (diff > 24) & (rgba[..., 3] > 0) & ((under[..., 3] < 128) | (diff > 90))
+ ).astype(np.uint8) * 255
+ masks = {}
+ for cloth in rig["cloth"]:
+ outline = polygon_mask(shape, cloth["outline"])
+ if under is not None:
+ # the drawn outline is approximate: reach a little past it for garment edges
+ outline |= changed & cv2.dilate(outline, np.ones((31, 31), np.uint8))
+ masks[cloth["name"]] = outline
+ front = np.zeros(shape, np.uint8)
+ for cloth in rig["cloth"]:
+ if not cloth.get("behind"):
+ front |= masks[cloth["name"]]
+ taken = np.zeros(shape, np.uint8)
+ for cloth in rig["cloth"]:
+ # a garment behind another loses what the front one covers; overlapping
+ # outlines of the same depth keep each pixel in the first garment only
+ mask = masks[cloth["name"]] & ~taken
+ if cloth.get("behind"):
+ mask &= ~front
+ taken |= mask
+ store(f"cloth_{cloth['name']}", *crop_layer(rgba, mask))
+ if under is not None:
+ bare = base.copy()
+ replace = (diff > 0) | (cv2.dilate(taken, np.ones((3, 3), np.uint8)) > 0)
+ bare[replace] = under[replace]
+ else:
+ print("cloth: no source_under.png; filling the garment area by inpainting")
+ bare = inpaint_rgba(base, cv2.dilate(taken, np.ones((7, 7), np.uint8)))
+ images["base_cloth"] = bare
+
+
def validate_inputs(rig, rgba):
h, w = rgba.shape[:2]
if rig.get("version") != 1 or rig.get("image") != {"width": w, "height": h}:
@@ -499,6 +555,21 @@ def validate_inputs(rig, rgba):
colour = accessory["color"]
if not 0 <= colour["redness"] <= 1 or not 0 <= colour["minRed"] <= 255:
raise ValueError(f"accessories[{i}].color thresholds are out of range")
+ cloth_names = set()
+ for i, cloth in enumerate(rig.get("cloth", [])):
+ name = cloth["name"]
+ if (
+ not isinstance(name, str)
+ or not re.fullmatch(r"[A-Za-z0-9_-]+", name)
+ or name in cloth_names
+ or f"cloth_{name}" in names
+ ):
+ raise ValueError(f"cloth[{i}].name must be a unique, safe layer filename")
+ cloth_names.add(name)
+ names.add(f"cloth_{name}")
+ points(cloth["outline"], f"cloth[{i}].outline")
+ points(cloth["waist"], f"cloth[{i}].waist", 2)
+ points(cloth["hem"], f"cloth[{i}].hem", 2)
def build(project, rig_path):
@@ -591,6 +662,8 @@ def build(project, rig_path):
)
images["base"] = base
images["hairmask"] = hair_mask(rgba, rig)
+ if rig.get("cloth"):
+ build_cloth(project, rig, rgba, base, store, images)
# Calculate everything before replacing files. Keep sprites and unrelated
# assets intact; only filenames in this build's manifest are consumed.
diff --git a/tools/overlay.py b/tools/overlay.py
index e2f6b3a..1619eda 100644
--- a/tools/overlay.py
+++ b/tools/overlay.py
@@ -118,6 +118,8 @@ def overlay(project, rig_name, part, zoom, output):
.split("export const SECTIONS")[0]
)
colours = dict(re.findall(r"(\w+): '(#[0-9a-fA-F]+)'", colours_text))
+ # optional groups the editor does not colour yet (such as cloth)
+ colours.setdefault("cloth", "#e040a0")
if part and part.split(".")[0] not in colours:
raise ValueError("unknown part; use " + ", ".join(colours))
shapes = [
diff --git a/tools/render-poses.mjs b/tools/render-poses.mjs
index ceed620..d52c3ba 100644
--- a/tools/render-poses.mjs
+++ b/tools/render-poses.mjs
@@ -39,7 +39,7 @@ async function main() {
}
await asset('layers.json');
const layers = JSON.parse(await readFile(resolve(built, 'layers.json'), 'utf8'));
- await Promise.all(['base', 'hairmask', ...Object.keys(layers.layers)].map(name => asset(`${name}.png`)));
+ await Promise.all(['base', 'hairmask', ...(rig.cloth?.length ? ['base_cloth'] : []), ...Object.keys(layers.layers)].map(name => asset(`${name}.png`)));
try {
await asset('sprites/sprites.json');
} catch (error) {
@@ -97,6 +97,14 @@ async function main() {
av.advance(seconds, 60); pictures.push([`hair-sway-${i}`, canvas.toDataURL()]);
}
av.destroy();
+ if (rig.cloth?.length) {
+ // garments: lean and shift the body, let go, and follow the swing as it settles
+ const cl = await avatar();
+ cl.setParameters({ ...defaults, bodyAngleZ: -8, bodyAngleX: -8 }); cl.advance(0.6, 60);
+ cl.setParameters(defaults);
+ for (let i = 0; i < 10; i++) { cl.advance(0.12, 60); pictures.push([`cloth-sway-${i}`, canvas.toDataURL()]); }
+ cl.destroy();
+ }
const scale = Math.min(width / (rig.image.width * 1.2), height / (rig.image.height * 1.1));
const ox = (width - rig.image.width * scale) / 2, oy = height - rig.image.height * scale;
const bounds = points => {
@@ -140,7 +148,7 @@ async function main() {
for (const [name, url] of result.images) await writeFile(resolve(review, `${name}.png`), Buffer.from(url.split(',')[1], 'base64'));
const { images, ...metadata } = result;
await writeFile(resolve(review, 'poses.json'), JSON.stringify({ ...metadata, project: basename(project), fixedFps: 60, poseSeconds: 1, poses: poses.map(([name, parameters, expression]) => ({ name, parameters, ...(expression && { expression }) })), hairFrames: 6, files: images.map(([name]) => `${name}.png`) }, null, 2) + '\n');
- console.log(`Rendered ${poses.length + 6} poses, eye/mouth crops and contact-sheet.png in ${relative(root, review)}/`);
+ console.log(`Rendered ${result.images.length} review images in ${relative(root, review)}/`);
} finally {
await browser?.close();
await server.close();
diff --git a/tools/test_build_layers.py b/tools/test_build_layers.py
index 73832ee..569d14c 100644
--- a/tools/test_build_layers.py
+++ b/tools/test_build_layers.py
@@ -49,6 +49,36 @@ class BuildLayersTest(unittest.TestCase):
check=False,
)
+ def test_cloth_layers_keep_legacy_base_and_generate_bare_base(self):
+ self.rig['cloth'] = [{
+ 'name': 'skirt', 'outline': [[20, 45], [80, 45], [80, 70], [20, 70]],
+ 'waist': [[30, 45], [70, 45]], 'hem': [[20, 70], [80, 70]],
+ }]
+ self.draft.write_text(json.dumps(self.rig))
+ with Image.open(self.project / 'source.png') as source:
+ full = source.convert('RGBA')
+ ImageDraw.Draw(full).rectangle((20, 45, 80, 70), fill=(255, 80, 150, 255))
+ full.save(self.project / 'source.png')
+ for with_under in (False, True):
+ with self.subTest(with_under=with_under):
+ if with_under:
+ under = full.copy()
+ ImageDraw.Draw(under).rectangle((20, 45, 80, 70), fill=(120, 160, 200, 255))
+ under.save(self.project / 'source_under.png')
+ result = self.run_cli()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ meta = json.loads((self.project / 'built/layers.json').read_text())
+ self.assertIn('cloth_skirt', meta['layers'])
+ with Image.open(self.project / 'built/base.png') as image:
+ self.assertEqual(image.getpixel((50, 60)), (255, 80, 150, 255))
+ with Image.open(self.project / 'built/base_cloth.png') as image:
+ self.assertEqual(image.size, full.size)
+ self.assertNotEqual(image.getpixel((50, 60)), (255, 80, 150, 255))
+ if with_under:
+ self.assertEqual(image.getpixel((50, 60)), (120, 160, 200, 255))
+ with Image.open(self.project / 'built/cloth_skirt.png') as image:
+ self.assertGreater(image.getchannel('A').getextrema()[1], 0)
+
def test_draft_build_is_loadable_without_optional_parts_or_eye_curves(self):
before = self.draft.read_bytes()
sprites = self.project / "built/sprites"