Skip to content

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

Add planted legs, trunk coordination and pendulum cloth physics

shinshin8624a97691fceb
diff --git a/.changeset/cloth-prototype.md b/.changeset/cloth-prototype.md
index 3cbda21..b8bb37e 100644
--- a/.changeset/cloth-prototype.md
+++ b/.changeset/cloth-prototype.md
@@ -5,3 +5,11 @@
---
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.
+
+Add optional planted-leg rig data and the `weightShift` parameter for five-second idle weight transfer, with fixed feet and soft knee flexion. Avatars without `legs` retain their existing deformation.
+
+Replace the unreleased cloth row-chain simulation with acceleration-driven column pendulums, coherent wind, hem arc motion and a small bend controlled by `follow`. Keep cloth-free avatars unchanged.
+
+Derive cloth pendulum frequencies from source scale, column length and gravity, with optional millimetres-per-pixel `cloth.scale`. Interpret `swing` as a physical frequency multiplier and include vertical pivot acceleration in apparent gravity.
+
+Add optional planted-rig spine stabilization and transfer dip, with delayed chest/head response and held weight transfers. Replace cloth columns with physically coupled two-link pendulums and add optional `responseGain` for clearly labelled render-only cloth exaggeration. Preserve cloth-free, leg-free deformation and motion.
diff --git a/docs/agent-guide.md b/docs/agent-guide.md
index 273200e..5765706 100644
--- a/docs/agent-guide.md
+++ b/docs/agent-guide.md
@@ -236,6 +236,35 @@ 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.
+## Optional — Legs
+
+Add `rig.legs` only when the illustration has two visible legs and planted feet
+(see [Rig fields](rig-fields.md#optional-planted-legs)). Use the calibrated source
+coordinates, zoomed grids and an overlay from the earlier steps. Left and right
+mean image-left and image-right. Place `pelvis` at the pelvic rotation centre,
+each `hip` at the top of the thigh, each `knee` at the drawn knee joint and each
+`ankle` at the fixed foot attachment. Keep hip, knee and ankle y increasing.
+Trace `split` down the gap between the legs, starting inside the crotch gap and
+continuing below both ankles, with strictly increasing y. Avoid putting this
+boundary through a leg. Place `band` above the hips where the pelvis motion should
+blend into the torso; its start must be above both hips.
+
+Start with modest `shift` (pixels), `tilt` (radians) and `bend` (pixels). Validate
+the draft before using it, then run `render-poses` as in Step 5. Compare `rest`,
+`weight-left`, `weight-right` and every `weight-shift-0..9` frame. Inspect the
+crotch, knees, ankles and any garment attachments at full resolution: feet must
+stay planted, knees must bend smoothly without reversing and the split must not
+produce a tear or overlap. The solver preserves bone lengths in 3D, so their
+projected lengths can shorten. Also check body sway and head movement together.
+
+In Studio, select **Legs**, align the pelvis and joint handles, and edit the split
+vertices (double-click an edge to add a point; Alt-click a vertex to remove
+it). Pause idle motion and test the **Weight shift** slider in both directions.
+Joint, split and tuning edits recalculate mesh weights; they do not require a
+layer rebuild. Save and reopen to confirm persistence. Omit `legs` to preserve an
+existing avatar's deformation. Idle targets follow a five-second sine with an
+amplitude of 0.7; the slider accepts the full `-1..1` parameter range.
+
## Step 7 — Hand over
Tell the person:
diff --git a/docs/rig-fields.md b/docs/rig-fields.md
index 569f926..efacac5 100644
--- a/docs/rig-fields.md
+++ b/docs/rig-fields.md
@@ -162,24 +162,77 @@ Coordinates are source-image pixels, with x increasing right and y increasing do
| `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[*].scale` | Optional positive image scale, millimetres per source pixel. If omitted, infer 0.8m from mean hip-to-ankle length when `legs` exists; otherwise assume image height represents 1.6m. Supply this for cropped or unusually proportioned art. |
| `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[*].responseGain` | Positive rendered-response exaggeration; default `1` (physical). `1.6` amplifies cloth angles only. Child solvers use the unexaggerated parent grid, while visible attachments follow the exaggerated grid. |
+| `cloth[*].swing` | Positive multiplier on the physical pendulum frequency; default `1`. A value of `1` uses the source scale, column length and gravity. |
+| `cloth[*].stiffness` | Positive restoring-force multiplier; default `1`. Effective angular frequency is `√(g / (0.8L)) × swing × √stiffness`, with g and L in source-pixel units. |
+| `cloth[*].damping` | Positive damping multiplier; default `1`. Effective angular damping ratio is `0.25 × damping`; larger values suppress oscillations. |
+| `cloth[*].follow` | Column rigidity, `0..1`; default `0.85`. At `1` each of the two links is rigid; lower values add up to 10% within-link quadratic bend, without a delayed row chain. |
+| `cloth[*].cohesion` | Integer smoothing passes over column angles and angular velocities, `0..8`; default `3`. |
+| `cloth[*].wind` | Nonnegative coherent breeze strength as a fraction of `max`; default `0.05`, `0` disables wind. All columns receive the same phase. |
+| `cloth[*].max` | Positive soft limit on grid displacement from the body-carried shape, px; default `20`. Limits rotation at the hem and reserves up to 10% for weak vertical bounce. 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
+Each column has two equal-length pendulum links, driven by the attachment's
+horizontal acceleration. Gravity is 9.80665m/s², converted to source pixels.
+Each link uses an effective length of 0.8 times its source length, between a uniform rigid strip
+(2L/3) and a tip-heavy point mass (L), approximating a ruffled hem.
+Upward attachment acceleration increases apparent gravity; source y points down,
+so the implementation uses `g - accelerationY`. The angle is relative to the world
+rest shape, so the cloth retains its hanging orientation as the pelvis tilts. The two absolute angles are solved together using the equal-mass double-pendulum mass matrix, gravity and Coriolis forces. Link masses are proportional to their equal half-lengths. Rayleigh damping sets both small-angle modes to `0.25 × damping`; their frequencies follow the link lengths rather than hand-tuned rows. Each rendered link retains its length, with a small within-link bend controlled by `follow`.
+Each link endpoint retains its distance from that link's pivot; a separate weak, critically damped vertical response can change it slightly during vertical acceleration. Parent
+accelerations are evaluated on the parent's unexaggerated physical grid; visible attachments follow its rendered grid. No additional
+random samples are used.
+
+`setClothTuning(name, tuning)` accepts a `Partial<ClothTuning>` containing the
+tuning 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`.
+
+## Optional planted legs
+
+Omit `legs` to retain the existing deformation exactly. `weightShift` is an optional
+parameter in `-1..1`, default `0`: negative supports the image-left leg, positive
+supports the image-right leg. For rigs with `legs`, idle weight transfer uses a five-second cycle: a 0.9-second quintic S transition and 1.6-second hold in each half-cycle, targeting `±0.7`. The existing body spring smooths it. Rigs without `legs` retain the previous deterministic sine and deformation.
+
+| Field | Meaning |
+| --- | --- |
+| `legs.spine` | Optional stabilization fraction `0..1`, default `0.7`; the upper torso retains a small opposite pelvic inclination of `1 - spine`, blended through the spine. Chest and head follow serial springs rather than a rigid translating trunk. |
+| `legs.bob` | Optional nonnegative extra pelvis dip in source px, default `2`; driven by transfer speed and returning to zero during a hold. Included in the planted-foot IK. |
+| `legs.pelvis` | Bone rotation centre `[x,y]` in source pixels. |
+| `legs.shift` | Nonnegative sideways travel in px at full weight transfer. |
+| `legs.tilt` | Nonnegative pelvic tilt in radians at full transfer; the free side lowers. |
+| `legs.bend` | Nonnegative inward-flexion scale in px. The free knee gets an extra inward offset of `bend * weightShift²`; the remaining flexion goes towards the camera. Also sets the small soft-IK settling scale. |
+| `legs.band` | Increasing source-y interval for counter-rotation; the spine blends towards the chest; shoulder inclination is partly countered rather than fully cancelled. |
+| `legs.left`, `legs.right` | Image-side joints, each with `hip`, `knee`, `ankle` source points. Require band start < hip y < knee y < ankle y. The rest knee determines which way the leg bends. |
+| `legs.split` | Polyline dividing the legs, with strictly increasing y. Put its start inside the crotch gap: the split is hard below this point and blends over eight pixels above it. |
+
+The IK is solved in 3D, with a forward pole, then projected onto the drawing. Bone
+lengths are preserved in 3D; the projected bones may shorten. The source knee's
+inward offset relative to the hip–ankle axis travels with that axis, retaining the
+drawn rest shape. Rest forward depth is 5% of the shorter projected bone. A smooth
+pelvis drop keeps both legs within reach without sudden knee extension; calibrate
+modest shift/tilt values for each illustration. At neutral, the added deformation is zero.
+With legs, `bodyAngleX` enters the same pelvis/IK transform, using `body.hip.shift`
+when supplied, and does not also apply the legacy hip shear. Breath and body roll
+remain in their existing order, fading to zero over the last 55 px before the ankles.
+Vertices at and below the higher ankle stay exactly fixed. Cloth attachments follow
+the pelvis through the usual base deformer, with their existing lag.
+
+Studio exposes the pelvis and joint handles, an editable split polyline, and the
+shift, tilt, bend and band fields under **Legs**. These edits recalculate weights
+without marking image layers stale. Pause idle motion to test the **Weight shift**
+slider, then save the rig to persist the geometry and tuning.
+
+`render-poses` adds `weight-left`, `weight-right` at `±0.6`, plus
+`weight-shift-0..9` over one five-second cycle when `legs` is present.
+
+For planted rigs, the chest drive lags the pelvis by approximately 0.1–0.2s; head stabilization follows one spring later and preserves intentional head gestures. Independent idle body noise is reduced to 35% without changing random-number consumption.
diff --git a/e2e/legs.spec.ts b/e2e/legs.spec.ts
new file mode 100644
index 0000000..6d6b2b0
--- /dev/null
+++ b/e2e/legs.spec.ts
@@ -0,0 +1,61 @@
+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 { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+test('leg handles and tuning update the paused preview without stale layers and persist on reopen', async ({ page }) => {
+ test.setTimeout(120000);
+ test.skip(!samplePresent, sampleSkipReason);
+ await mkdir('projects', { recursive: true });
+ const directory = await mkdtemp(join(resolve('projects'), 'legs-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.legs = {
+ pelvis: [640, 800], shift: 20, tilt: 0.06, bend: 10, band: [750, 850],
+ left: { hip: [520, 850], knee: [530, 1000], ankle: [520, 1200] },
+ right: { hip: [740, 850], knee: [730, 1000], ankle: [740, 1200] },
+ split: [[630, 840], [630, 1254]],
+ };
+ await writeFile(rigPath, JSON.stringify(rig));
+ 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-legs').click();
+ await page.locator('.inspector details').evaluateAll(nodes => nodes.forEach(node => { (node as HTMLDetailsElement).open = true; }));
+ };
+ await open();
+ await page.getByTestId('idle-toggle').click();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ const slider = page.getByRole('slider', { name: 'Weight shift', exact: true });
+ const preview = page.getByTestId('preview');
+ const pixels = () => preview.evaluate(node => (node as HTMLCanvasElement).toDataURL());
+ const rest = await pixels();
+ await slider.fill('0.7');
+ await expect.poll(pixels).not.toBe(rest);
+ const before = await pixels(), revision = Number(await preview.getAttribute('data-revision'));
+ const canvas = page.getByTestId('editor'), box = (await canvas.boundingBox())!;
+ const scale = Number(await canvas.getAttribute('data-scale'));
+ const x = box.x + Number(await canvas.getAttribute('data-offset-x')) + 530 * scale;
+ const y = box.y + Number(await canvas.getAttribute('data-offset-y')) + 1000 * scale;
+ await page.mouse.move(x, y); await page.mouse.down();
+ await page.mouse.move(x + 20 * scale, y + 10 * scale, { steps: 4 }); await page.mouse.up();
+ const knee = page.getByRole('spinbutton', { name: 'legs.left.knee.0', exact: true });
+ await expect(knee).toHaveValue('550');
+ await expect.poll(async () => Number(await preview.getAttribute('data-revision'))).toBeGreaterThan(revision);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await expect.poll(pixels).not.toBe(before);
+ await page.getByTestId('part-legs').click();
+ await page.locator('.inspector details').evaluateAll(nodes => nodes.forEach(node => { (node as HTMLDetailsElement).open = true; }));
+ for (const [path, value] of [['shift', '18'], ['tilt', '0.05'], ['bend', '9'], ['band.0', '740'], ['split.0.0', '632']])
+ await page.getByRole('spinbutton', { name: `legs.${path}`, exact: true }).fill(value);
+ await expect(page.getByTestId('stale-banner')).toHaveCount(0);
+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();
+ await expect.poll(async () => JSON.parse(await readFile(rigPath, 'utf8')).legs.left.knee).toEqual([550, 1010]);
+ await open(); await expect(knee).toHaveValue('550');
+ await expect(page.getByRole('spinbutton', { name: 'legs.shift', exact: true })).toHaveValue('18');
+ await expect(page.getByRole('spinbutton', { name: 'legs.split.0.0', exact: true })).toHaveValue('632');
+ await expect(page.getByTestId('stale-banner')).toHaveCount(0);
+ } finally { await rm(directory, { recursive: true, force: true }); }
+});
diff --git a/packages/runtime/src/engine/cloth-tuning.js b/packages/runtime/src/engine/cloth-tuning.js
index bebfc4b..900a556 100644
--- a/packages/runtime/src/engine/cloth-tuning.js
+++ b/packages/runtime/src/engine/cloth-tuning.js
@@ -1,6 +1,6 @@
/** @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,
+ responseGain: 1, 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. */
@@ -9,7 +9,7 @@ export function checkClothTuning(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 (['responseGain', '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
index 4cd37a6..f346b09 100644
--- a/packages/runtime/src/engine/cloth.js
+++ b/packages/runtime/src/engine/cloth.js
@@ -1,7 +1,6 @@
-// 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.
+// Each column is a coupled two-link pendulum driven by its waist acceleration.
+// Link masses are proportional to their lengths; both halves have the same
+// fabric density. Rendered links retain their source lengths.
import { CLOTH_DEFAULTS, checkClothTuning } from './cloth-tuning.js';
@@ -24,7 +23,17 @@ function resample(line, n) {
* @param {import('../rig/types').Rig} rig */
export function createCloth(engine, rig) {
const { baseWeights, deformBase } = engine;
- const TUNE = { waistHz: 2.6, zeta: 0.32 };
+ const TUNE = { bounceHz: 2.6, zeta: 0.25 };
+
+ // Adult hip-to-ankle length≈0.8m; if joints are unavailable, assume the
+ // illustration spans a 1.6m figure. Cropped/stylized art can override mm/px.
+ const metersPerPixel = rig.legs
+ ? 0.8 / ((Math.hypot(...rig.legs.left.ankle.map((v, i) => v - rig.legs.left.hip[i]))
+ + Math.hypot(...rig.legs.right.ankle.map((v, i) => v - rig.legs.right.hip[i]))) / 2)
+ : 1.6 / rig.image.height;
+ // Effective length 2L/3 for a uniform rigid strip, L for a tip-heavy point
+ // mass. 0.8L approximates fabric with extra mass in a ruffled hem.
+ const inertiaLength = 0.8;
const garments = (rig.cloth ?? []).map(c => {
const cols = c.columns ?? 8, rows = c.rows ?? 5;
@@ -36,10 +45,14 @@ export function createCloth(engine, rig) {
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])),
+ c, gravity: 9.80665 / (c.scale === undefined ? metersPerPixel : c.scale / 1000),
+ 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: [],
+ target: new Float64Array(rest.length), previous: null, pivotVelocity: new Float64Array(cols * 2),
+ angle: new Float64Array(cols), angularVelocity: new Float64Array(cols),
+ lowerAngle: new Float64Array(cols), lowerAngularVelocity: new Float64Array(cols),
+ bounce: new Float64Array(cols), bounceVelocity: new Float64Array(cols),
+ out: Float64Array.from(rest), physicalOut: Float64Array.from(rest), parent: null, parentLoc: null, meshes: [],
};
});
const byName = Object.fromEntries(garments.map(g => [g.c.name, g]));
@@ -80,13 +93,6 @@ export function createCloth(engine, rig) {
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;
@@ -108,60 +114,110 @@ export function createCloth(engine, rig) {
}
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];
+ if (dt < 0) return;
+ const elapsed = Math.min(dt, 0.05), sub = Math.max(1, Math.ceil(elapsed * 240)), h = elapsed / sub;
+ const 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
+ const { cols, rows, rest, target, out, angle, angularVelocity, lowerAngle, lowerAngularVelocity, bounce, bounceVelocity } = g;
+ const { stiffness, damping, max, swing, follow, cohesion, wind, responseGain } = g.tuning;
+ const gain = this.gain * (responseGain ?? 1);
+ const pivots = new Float64Array(cols * 2), renderPivots = new Float64Array(cols * 2), acceleration = new Float64Array(cols * 2);
for (let k = 0; k < cols; k++) {
- if (g.parent) place(g.parent.out, g.parentLoc[k], a);
+ if (g.parent) place(g.parent.physicalOut, 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];
+ pivots[k * 2] = a[0]; pivots[k * 2 + 1] = a[1];
+ // Parent response exaggeration affects the visible attachment only;
+ // the child solver receives the unexaggerated physical acceleration.
+ if (g.parent) place(g.parent.out, g.parentLoc[k], a);
+ renderPivots[k * 2] = a[0]; renderPivots[k * 2 + 1] = a[1];
+ for (let axis = 0; axis < 2; axis++) {
+ const i = k * 2 + axis;
+ const velocity = g.previous && elapsed > 0 ? (pivots[i] - g.previous[i]) / elapsed : 0;
+ acceleration[i] = elapsed > 0 ? (velocity - g.pivotVelocity[i]) / elapsed : 0;
+ g.pivotVelocity[i] = velocity;
+ }
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;
+ target[i] = rest[i] + a[0] - g.top[k][0];
+ target[i + 1] = rest[i + 1] + a[1] - g.top[k][1];
}
}
- 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; }
+ g.previous = pivots;
+ const frequencyMultiplier = swing * Math.sqrt(stiffness);
+ const verticalOmega = 2 * Math.PI * TUNE.bounceHz;
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;
- }
+ const t = this.time + (n + 1) * h;
+ // One coherent breeze for the whole sheet, never a travelling wave.
+ const breeze = (Math.sin(t * 1.1) * 0.6 + Math.sin(t * 2.3) * 0.4) * max * wind;
+ for (let k = 0; k < cols; k++) {
+ const i = k * 2, bottom = ((rows - 1) * cols + k) * 2;
+ const length = Math.max(1, Math.hypot(rest[bottom] - rest[i], rest[bottom + 1] - rest[i + 1]));
+ // Source y points down: upward pivot acceleration adds apparent
+ // gravity, so g_eff=g-a_y. A small floor guards downward teleports.
+ const effectiveGravity = Math.max(g.gravity * 0.1, g.gravity - acceleration[i + 1]);
+ const link = inertiaLength * length / 2;
+ const omega2 = effectiveGravity / link * frequencyMultiplier * frequencyMultiplier;
+ const omega = Math.sqrt(omega2), zeta = TUNE.zeta * damping;
+ const low = omega * Math.sqrt(2 - Math.SQRT2), high = omega * Math.sqrt(2 + Math.SQRT2);
+ // Rayleigh damping gives both small-angle normal modes the same
+ // damping ratio. M=[[2,cos(delta)],[cos(delta),1]], equal half masses.
+ const alpha = 2 * zeta * low * high / (low + high), beta = 2 * zeta / (low + high);
+ const delta = angle[k] - lowerAngle[k], c = Math.cos(delta), s = Math.sin(delta);
+ const v1 = angularVelocity[k], v2 = lowerAngularVelocity[k];
+ // Only discontinuous teleports can exceed8g; keep these finite
+ // without limiting accelerations in the reviewed motion range.
+ const ax = Math.max(-8 * g.gravity, Math.min(8 * g.gravity, acceleration[i]));
+ const force = (ax - effectiveGravity * breeze / length) / link;
+ const damp1 = alpha * (2 * v1 + c * v2) + beta * 2 * omega2 * v1;
+ const damp2 = alpha * (c * v1 + v2) + beta * omega2 * v2;
+ const b1 = -2 * omega2 * Math.sin(angle[k]) - s * v2 * v2 - 2 * force * Math.cos(angle[k]) - damp1;
+ const b2 = -omega2 * Math.sin(lowerAngle[k]) + s * v1 * v1 - force * Math.cos(lowerAngle[k]) - damp2;
+ const determinant = 2 - c * c;
+ angularVelocity[k] += (b1 - c * b2) / determinant * h;
+ lowerAngularVelocity[k] += (2 * b2 - c * b1) / determinant * h;
+ angle[k] += angularVelocity[k] * h;
+ lowerAngle[k] += lowerAngularVelocity[k] * h;
+ // A much smaller, heavily damped vertical response to pivot acceleration.
+ bounceVelocity[k] += (-verticalOmega * verticalOmega * bounce[k] - 2 * verticalOmega * bounceVelocity[k]
+ - acceleration[i + 1] * 0.15) * h;
+ bounce[k] += bounceVelocity[k] * 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);
+ // Smooth the column angles and their velocities, rather than delayed rows.
+ for (let pass = 0; elapsed > 0 && pass < cohesion; pass++) for (const values of [angle, angularVelocity, lowerAngle, lowerAngularVelocity]) {
+ const previous = values.slice();
+ for (let k = 0; k < cols; k++) values[k] = previous[k] * 0.5
+ + (previous[Math.max(0, k - 1)] + previous[Math.min(cols - 1, k + 1)]) * 0.25;
+ }
+ const render = (destination, anchors, renderGain) => {
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;
+ const top = k * 2, bottom = ((rows - 1) * cols + k) * 2;
+ const length = Math.max(1, Math.hypot(rest[bottom] - rest[top], rest[bottom + 1] - rest[top + 1]));
+ const vertical = max * 0.1 * Math.tanh(bounce[k] * renderGain / (max * 0.1));
+ const limit = 2 * Math.asin(Math.min(0.95, (max - Math.abs(vertical)) / (2 * length)));
+ const theta = limit * Math.tanh(angle[k] * renderGain / limit);
+ const lower = limit * Math.tanh(lowerAngle[k] * renderGain / limit);
+ // Angles are relative to the world-rest shape, not the rotating
+ // waist line: the cloth counter-rotates relative to a tilted pelvis.
+ // follow=1 is rigid; lower values allow up to 10% extra quadratic bend.
+ const bend = 0.1 * (1 - follow);
+ const halfX = (rest[bottom] - rest[top]) / 2, halfY = (rest[bottom + 1] - rest[top + 1]) / 2;
+ const jointX = anchors[top] + halfX * Math.cos(theta) + halfY * Math.sin(theta);
+ const jointY = anchors[top + 1] - halfX * Math.sin(theta) + halfY * Math.cos(theta);
+ for (let r = 0; r < rows; r++) {
+ const v = r / (rows - 1), i = (r * cols + k) * 2, first = v <= 0.5;
+ const u = first ? v * 2 : (v - 0.5) * 2;
+ const rotation = (first ? theta : lower) * (1 - bend + bend * u), c = Math.cos(rotation), s = Math.sin(rotation);
+ const x = halfX * u, y = halfY * u;
+ destination[i] = (first ? anchors[top] : jointX) + x * c + y * s;
+ destination[i + 1] = (first ? anchors[top + 1] : jointY) - x * s + y * c + vertical * v;
}
}
- 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;
+ };
+ render(g.physicalOut, pivots, 1);
+ render(out, renderPivots, gain);
}
- this.time += dt;
+ this.time += elapsed;
}
deform() {
diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.js
index 05b24b4..8b11678 100644
--- a/packages/runtime/src/engine/createMeshAvatar.js
+++ b/packages/runtime/src/engine/createMeshAvatar.js
@@ -157,7 +157,7 @@ export async function createMeshAvatarImpl(canvas, options) {
if (rig.hand) R.addLayer('hand', imgs.hand, handMesh);
const physics = new Physics();
- const motion = new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy]);
+ const motion = new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy], !!rig.legs);
if (options.lipSync !== undefined) motion.setLipSync(options.lipSync);
const listeners = new Set();
motion.onMotion = id => { for (const fn of listeners) fn(id); };
diff --git a/packages/runtime/src/engine/legs.js b/packages/runtime/src/engine/legs.js
new file mode 100644
index 0000000..de44cab
--- /dev/null
+++ b/packages/runtime/src/engine/legs.js
@@ -0,0 +1,163 @@
+const clamp = (x, a, b) => Math.max(a, Math.min(b, x));
+const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
+const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
+const rotate = (p, o, a) => {
+ const x = p[0] - o[0], y = p[1] - o[1], c = Math.cos(a), s = Math.sin(a);
+ return [o[0] + x * c - y * s, o[1] + x * s + y * c];
+};
+// Affine projection of a 3D bone: permit lengthwise foreshortening, retaining
+// the illustration's width perpendicular to the projected bone.
+function boneMatrix(a, b, targetA, targetB) {
+ const length = distance(a, b), targetLength = distance(targetA, targetB);
+ const ux = (b[0] - a[0]) / length, uy = (b[1] - a[1]) / length;
+ const vx = (targetB[0] - targetA[0]) / targetLength, vy = (targetB[1] - targetA[1]) / targetLength;
+ const scale = targetLength / length;
+ const m = [vx * scale * ux + vy * uy, vx * scale * uy - vy * ux,
+ vy * scale * ux - vx * uy, vy * scale * uy + vx * ux];
+ return [...m, targetA[0] - m[0] * a[0] - m[1] * a[1], targetA[1] - m[2] * a[0] - m[3] * a[1]];
+}
+const transform = (p, m) => [m[0] * p[0] + m[1] * p[1] + m[4], m[2] * p[0] + m[3] * p[1] + m[5]];
+
+/** Optional planted, two-bone legs. All coordinates are in source pixels. */
+export const LEG_DEFAULTS = Object.freeze({ spine: 0.7, bob: 2 });
+
+/** @param {{pivotX:number, pivotY:number, weightBand:number[]}|null} [head] */
+export function createLegs(legs, body, head = null) {
+ if (!legs) return null;
+ const bones = [legs.left, legs.right].map((leg, i) => {
+ const projectedU = distance(leg.hip, leg.knee), projectedV = distance(leg.knee, leg.ankle);
+ // A small forward rest flex avoids a singular straight knee. The source
+ // drawing's complete projected rest shape, including its inward offset, stays.
+ const depth = Math.min(projectedU, projectedV) * 0.05;
+ const u = Math.hypot(projectedU, depth), v = Math.hypot(projectedV, depth);
+ const dx = leg.ankle[0] - leg.hip[0], dy = leg.ankle[1] - leg.hip[1];
+ const cross = dx * (leg.knee[1] - leg.hip[1]) - dy * (leg.knee[0] - leg.hip[0]);
+ return { ...leg, u, v, depth, lateral: cross / Math.hypot(dx, dy), side: Math.sign(cross) || (i ? 1 : -1) };
+ });
+ const drive = [0, 0, 0], velocity = [0, 0, 0];
+ let bob = 0, bobVelocity = 0, lastWeight = 0, version = 0, previousVersion;
+ function step(P, dt) {
+ const ws = clamp(P.weightShift ?? 0, -1, 1);
+ const time = Math.min(Math.max(dt, 0), 0.05);
+ if (!time) {
+ drive.fill(ws); velocity.fill(0); bob = 0; bobVelocity = 0;
+ } else {
+ const targetBob = (legs.bob ?? LEG_DEFAULTS.bob) * Math.min(1, Math.abs(ws - lastWeight) / time / 1.5);
+ const count = Math.ceil(time * 240), h = time / count;
+ for (let n = 0; n < count; n++) {
+ // Three serial, critically-near-damped stages: chest delay about0.15s,
+ // then head stabilization about0.075s later. No random driving forces.
+ for (let i = 0; i < 3; i++) {
+ const target = i ? drive[i - 1] : ws;
+ velocity[i] += (24 * 24 * (target - drive[i]) - 2 * 0.9 * 24 * velocity[i]) * h;
+ drive[i] += velocity[i] * h;
+ }
+ bobVelocity += (24 * 24 * (targetBob - bob) - 2 * 0.9 * 24 * bobVelocity) * h;
+ bob += bobVelocity * h;
+ }
+ }
+ lastWeight = ws; version++;
+ }
+ const ankleY = Math.min(...bones.map(b => b.ankle[1]));
+ let previousShift, previousBody, cached;
+ function frame(P) {
+ const ws = clamp(P.weightShift ?? 0, -1, 1), bx = clamp(P.bodyAngleX ?? 0, -10, 10);
+ if (ws === previousShift && bx === previousBody && version === previousVersion) return cached;
+ previousShift = ws; previousBody = bx; previousVersion = version;
+ const angle = -legs.tilt * ws, shift = legs.shift * ws + bx / 10 * (body.hip?.shift ?? legs.shift);
+ const pelvisPoint = p => { const q = rotate(p, legs.pelvis, angle); q[0] += shift; return q; };
+ const hips = bones.map(b => pelvisPoint(b.hip));
+ // Only the free leg gets an extra inward offset. Quadratic onset keeps the
+ // neutral derivative continuous; most flexion goes towards the camera (z).
+ const lateral = bones.map((b, i) => b.lateral + b.side * legs.bend * Math.max(0, i ? -ws : ws) ** 2);
+ // A smooth positive part starts correcting before full extension. Its width goes
+ // to zero quadratically at neutral, so the rest pose is exactly unchanged.
+ const strength = ws * ws + (bx / 10) ** 2;
+ const width = legs.bend ** 2 / Math.min(...bones.map(b => b.u + b.v)) * strength;
+ const positive = x => (x + Math.hypot(x, width)) / 2;
+ let drop = bob + legs.bend ** 2 / Math.min(...bones.map(b => b.u + b.v)) * ws * ws;
+ for (let i = 0; i < bones.length; i++) {
+ const b = bones[i], h = hips[i], dx = h[0] - b.ankle[0];
+ // Reserve the chosen image-plane offset; remaining flexion is in depth.
+ const reach = Math.sqrt(Math.max(0, b.u * b.u - lateral[i] ** 2)) + Math.sqrt(Math.max(0, b.v * b.v - lateral[i] ** 2));
+ const required = b.ankle[1] - Math.sqrt(Math.max(0, reach * reach - dx * dx)) - h[1];
+ drop += positive(required - drop);
+ }
+ const solved = bones.map((b, i) => {
+ const hip = [hips[i][0], hips[i][1] + drop], ankle = b.ankle;
+ if (!ws && !bx && !bob) return { hip: b.hip, knee: b.knee, ankle,
+ hip3: [...b.hip, 0], knee3: [...b.knee, b.depth], ankle3: [...ankle, 0],
+ upper: [1, 0, 0, 1, 0, 0], lower: [1, 0, 0, 1, 0, 0] };
+ const dx = ankle[0] - hip[0], dy = ankle[1] - hip[1], d = Math.hypot(dx, dy);
+ const along = (b.u * b.u - b.v * b.v + d * d) / (2 * d);
+ const height = Math.sqrt(Math.max(0, b.u * b.u - along * along));
+ const knee = [hip[0] + dx / d * along - dy / d * lateral[i],
+ hip[1] + dy / d * along + dx / d * lateral[i]];
+ const depth = Math.sqrt(Math.max(0, height * height - lateral[i] ** 2));
+ return { hip, knee, ankle, hip3: [...hip, 0], knee3: [...knee, depth], ankle3: [...ankle, 0],
+ upper: boneMatrix(b.hip, b.knee, hip, knee), lower: boneMatrix(b.knee, b.ankle, knee, ankle) };
+ });
+ cached = { ws, bx, angle, shift, drop, bones: solved,
+ trunk: { spine: drive[0], chest: drive[1], head: drive[2], bob } };
+ return cached;
+ }
+ function splitX(y) {
+ const line = legs.split;
+ let i = 0;
+ while (i < line.length - 2 && y > line[i + 1][1]) i++;
+ const a = line[i], b = line[i + 1], t = clamp((y - a[1]) / (b[1] - a[1]), 0, 1);
+ return a[0] + (b[0] - a[0]) * t;
+ }
+ function weights(x, y) {
+ // Split is hard only inside the transparent gap; above it, blend inside shorts.
+ const right = y >= legs.split[0][1] ? Number(x >= splitX(y)) : smooth(splitX(y) - 4, splitX(y) + 4, x);
+ const perBone = bones.map(b => ({
+ leg: smooth(legs.band[0], b.hip[1], y),
+ shin: smooth(b.knee[1] - 45, b.knee[1] + 45, y),
+ pin: 1 - smooth(b.ankle[1] - 55, b.ankle[1], y),
+ }));
+ return { right, perBone };
+ }
+ function apply(p, _x, y, w, P) {
+ const F = frame(P);
+ if (!F.ws && !F.bx && !F.trunk.chest && !F.trunk.head && !bob) return;
+ const pivot = [legs.pelvis[0] + F.shift, legs.pelvis[1] + F.drop];
+ const upper = 1 - smooth(Math.min(body.chest.cy, legs.pelvis[1] - 1), legs.pelvis[1], y);
+ const spineBlend = 1 - smooth(...legs.band, y);
+ const rejection = legs.spine ?? LEG_DEFAULTS.spine;
+ // A small opposite shoulder inclination, rather than cancelling the pelvis
+ // completely and leaving a translating rod. Blend the spine continuously.
+ const shoulderAngle = legs.tilt * (1 - rejection) * F.trunk.chest;
+ const chestShift = legs.shift * (1.12 * F.trunk.chest - F.ws)
+ + Math.sin(shoulderAngle) * Math.max(0, legs.pelvis[1] - body.chest.cy);
+ const bodyPoint = point => {
+ const q = rotate(point, legs.pelvis, F.angle);
+ q[0] += F.shift; q[1] += F.drop;
+ const result = rotate(q, pivot, (shoulderAngle - F.angle) * spineBlend);
+ result[0] += chestShift * upper;
+ return result;
+ };
+ const counter = bodyPoint(p);
+ if (head) {
+ const weight = 1 - smooth(...head.weightBand, y);
+ const center = bodyPoint([head.pivotX, head.pivotY]);
+ const correction = -legs.tilt * (1 - rejection) * F.trunk.head * weight;
+ const q = rotate(counter, center, correction);
+ counter[0] = q[0] + legs.shift * 1.12 * (F.trunk.head - F.trunk.chest) * weight; counter[1] = q[1];
+ }
+ let dx = 0, dy = 0;
+ bones.forEach((_b, i) => {
+ const f = F.bones[i], bw = w.perBone[i];
+ const thigh = transform(p, f.upper);
+ const shin = transform(p, f.lower);
+ const qx = thigh[0] + (shin[0] - thigh[0]) * bw.shin;
+ const qy = thigh[1] + (shin[1] - thigh[1]) * bw.shin;
+ const side = i ? w.right : 1 - w.right;
+ dx += ((counter[0] - p[0]) * (1 - bw.leg) + (qx - p[0]) * bw.leg) * bw.pin * side;
+ dy += ((counter[1] - p[1]) * (1 - bw.leg) + (qy - p[1]) * bw.leg) * bw.pin * side;
+ });
+ p[0] += dx; p[1] += dy;
+ }
+ function pin(y) { return 1 - smooth(ankleY - 55, ankleY, y); }
+ return { frame, weights, apply, pin, step };
+}
diff --git a/packages/runtime/src/engine/motion.js b/packages/runtime/src/engine/motion.js
index 78e624c..f622fd3 100644
--- a/packages/runtime/src/engine/motion.js
+++ b/packages/runtime/src/engine/motion.js
@@ -55,13 +55,23 @@ const EMOTIONS = {
const SPRINGS = {
gazeX: [260, 0.9], gazeY: [260, 0.9],
angleX: [55, 0.72], angleY: [55, 0.72], angleZ: [45, 0.75],
- bodyAngleX: [14, 0.9], bodyAngleZ: [12, 0.9],
+ bodyAngleX: [14, 0.9], bodyAngleZ: [12, 0.9], weightShift: [14, 0.9],
armAngle: [20, 0.85], handAngle: [30, 0.8],
};
+/** Five-second held transfer:0.9s quintic S,1.6s hold per half-cycle. */
+export function weightTransfer(t) {
+ const duration = 0.9, phase = (t + duration / 2) % 5;
+ const start = phase < 2.5 ? -0.7 : 0.7, end = -start, local = phase % 2.5;
+ if (local >= duration) return end;
+ const u = local / duration, s = u * u * u * (10 + u * (-15 + 6 * u));
+ return start + (end - start) * s;
+}
+
export class Motion {
/** @param {number[]} gazeCenter */
- constructor(gazeCenter) {
+ constructor(gazeCenter, planted = false) {
+ this.planted = planted;
this.mode = 'auto'; // auto | mouse | manual
this.P = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
this.manual = { ...this.P };
@@ -247,8 +257,11 @@ export class Motion {
T.angleX = fbm(t * 0.18, 1) * 10 + this.gaze.x * 11;
T.angleY = fbm(t * 0.15, 2) * 6 - 1 + this.gaze.y * 7;
T.angleZ = fbm(t * 0.12, 3) * 10;
- T.bodyAngleX = fbm(t * 0.1, 4) * 5;
- T.bodyAngleZ = fbm(t * 0.09, 5) * 4;
+ T.bodyAngleX = fbm(t * 0.1, 4) * 5 * (this.planted ? 0.35 : 1);
+ T.bodyAngleZ = fbm(t * 0.09, 5) * 4 * (this.planted ? 0.35 : 1);
+ // Held transfers for planted rigs, legacy sine otherwise. No RNG: idle tracks must
+ // consume exactly the same random sequence.
+ T.weightShift = this.planted ? weightTransfer(t) : 0.7 * Math.sin(t * Math.PI * 2 / 5);
T.armAngle = fbm(t * 0.14, 6) * 5;
T.handAngle = fbm(t * 0.21, 7) * 5;
// glances
@@ -334,6 +347,7 @@ export class Motion {
const X = this.exprMix;
// spring-damper towards the targets for body params
+ /** @type {Record<string, number>} */
const out = {};
for (const p of PARAMS) {
const id = p.id;
diff --git a/packages/runtime/src/engine/physics.js b/packages/runtime/src/engine/physics.js
index 9051f68..e7a4596 100644
--- a/packages/runtime/src/engine/physics.js
+++ b/packages/runtime/src/engine/physics.js
@@ -66,6 +66,7 @@ export function createPhysics(engine, rig) {
}
step(P, dt) {
+ engine.stepBody?.(P, dt);
const sub = Math.max(1, Math.ceil(dt / (1 / 240)));
const h = Math.min(dt, 0.05) / sub;
const roll = -P.angleZ / 30 * rig.head.maxRoll - P.bodyAngleZ / 10 * rig.body.maxRoll;
diff --git a/packages/runtime/src/engine/rig.js b/packages/runtime/src/engine/rig.js
index cbab833..32a9e15 100644
--- a/packages/runtime/src/engine/rig.js
+++ b/packages/runtime/src/engine/rig.js
@@ -1,3 +1,5 @@
+import { createLegs } from './legs.js';
+
export const PARAMS = [
{ id: 'angleX', label: 'Face angle X', min: -30, max: 30, def: 0, group: 'Head and body' },
{ id: 'angleY', label: 'Face angle Y', min: -30, max: 30, def: 0, group: 'Head and body' },
@@ -18,6 +20,7 @@ export const PARAMS = [
{ id: 'armAngle', label: 'Arm angle', min: -10, max: 10, def: 0, group: 'Hand' },
{ id: 'handAngle', label: 'Wrist angle', min: -10, max: 10, def: 0, group: 'Hand' },
{ id: 'fingerTap', label: 'Finger tap', min: 0, max: 1, def: 0, group: 'Hand' },
+ { id: 'weightShift', label: 'Weight shift', min: -1, max: 1, def: 0, group: 'Legs' },
];
// Reference algorithms are intentionally retained as JavaScript; the factory's rig input
@@ -94,6 +97,7 @@ export function createRig(rig) {
// face so its rim falls in the background, and its slope is zero at the rim.
const HEAD = rig.head;
const BODY = rig.body;
+ const LEGS = createLegs(rig.legs, BODY, HEAD);
const sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
@@ -158,6 +162,7 @@ export function createRig(rig) {
chest: gaussian(x, y, BODY.chest),
breath: 1 - sstep(...BODY.breathBand, y),
shoulder: BODY.shoulders.reduce((sum, area) => sum + gaussian(x, y, area), 0),
+ ...(LEGS && { legs: LEGS.weights(x, y) }),
};
}
@@ -187,7 +192,9 @@ export function createRig(rig) {
rotateAround(p, HEAD.pivotX, HEAD.pivotY, -P.angleZ / 30 * HEAD.maxRoll * w);
}
- function applyBody(p, restY, P, chest = 0, breathW = 1, shoulder = 0) {
+ function applyBody(p, restY, P, chest = 0, breathW = 1, shoulder = 0, legWeights) {
+ if (LEGS) LEGS.apply(p, p[0], restY, legWeights ?? LEGS.weights(p[0], restY), P);
+ const plantedX = p[0], plantedY = p[1];
const b = P.breath;
// inhale: everything above the cut-off rises, shoulders lift more, the chest widens a little
p[1] -= b * (5 * breathW + 4 * shoulder);
@@ -195,15 +202,21 @@ export function createRig(rig) {
// 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);
+ if (!LEGS) 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)));
+ if (LEGS) {
+ const pin = LEGS.pin(restY);
+ p[0] = plantedX + (p[0] - plantedX) * pin;
+ p[1] = plantedY + (p[1] - plantedY) * pin;
+ }
}
// Base layer: hair and face-part offsets are added in rest space, then head, then body.
function deformBase(x, y, w, P, phys, out) {
const p = out;
p[0] = x; p[1] = y;
+ if (LEGS && !LEGS.pin(y)) return p;
const g = phys.gain;
for (const [i, wi, t] of w.strands) {
const o = phys.strands?.[i];
@@ -229,7 +242,7 @@ export function createRig(rig) {
p[1] -= ay * (6 * w.nose + 3 * w.mouth);
p[1] += (y - rig.face.eyeA.cy) * -0.06 * Math.abs(ay) * w.eyeA + (y - rig.face.eyeB.cy) * -0.06 * Math.abs(ay) * w.eyeB;
applyHead(p, w.head, P, w.turn);
- applyBody(p, y, P, w.chest, w.breath, w.shoulder);
+ applyBody(p, y, P, w.chest, w.breath, w.shoulder, w.legs);
return p;
}
@@ -298,5 +311,5 @@ export function createRig(rig) {
const w = baseWeights(t.pivot[0], t.pivot[1]);
return deformBase(t.pivot[0], t.pivot[1], w, P, phys, out);
}
- return { IMG, EYES, MOUTH, CHEEKS, STRANDS, TASSELS, headWeight, turnWeight, baseWeights, deformBase, applyHead, applyBody, handWeights, handFrame, deformHand, eyePartY, eyePartAlpha, tasselAnchor };
+ return { legs: LEGS, stepBody: (P, dt) => LEGS?.step(P, dt), IMG, EYES, MOUTH, CHEEKS, STRANDS, TASSELS, headWeight, turnWeight, baseWeights, deformBase, applyHead, applyBody, handWeights, handFrame, deformHand, eyePartY, eyePartAlpha, tasselAnchor };
}
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 6b16fa6..bfb38a4 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,7 +1,7 @@
export { createMeshAvatar, LIVE_EXPRESSIONS } from './engine';
export type { MeshAvatar, MeshAvatarOptions, LiveExpression } from './engine';
export type { LipSyncSettings } from './engine/lip-sync';
-export type { Rig, Eye, Strand, Accessory, Hand, Cloth, ClothTuning, Ellipse, Point, Band } from './rig/types';
+export type { Rig, Eye, Strand, Accessory, Hand, Leg, Legs, 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/types.ts b/packages/runtime/src/rig/types.ts
index 6109d8a..b534d7d 100644
--- a/packages/runtime/src/rig/types.ts
+++ b/packages/runtime/src/rig/types.ts
@@ -26,6 +26,7 @@ export interface Accessory {
}
/** Optional garment that swings with the body (for example a skirt). */
export interface ClothTuning {
+ responseGain?: number;
swing: number;
stiffness: number;
damping: number;
@@ -35,6 +36,8 @@ export interface ClothTuning {
max: number;
}
export interface Cloth extends Partial<ClothTuning> {
+ /** Physical image scale in millimetres per source pixel; inferred if omitted. */
+ scale?: number;
name: string;
outline: Point[];
waist: Point[];
@@ -61,6 +64,20 @@ export interface Hand {
fingerYBand: Band;
pinBand: Band;
}
+export interface Leg { hip: Point; knee: Point; ankle: Point }
+/** Optional planted-foot weight transfer. Left/right refer to the image. */
+export interface Legs {
+ spine?: number;
+ bob?: number;
+ pelvis: Point;
+ shift: number;
+ tilt: number;
+ bend: number;
+ band: Band;
+ left: Leg;
+ right: Leg;
+ split: Point[];
+}
export interface Rig {
version: 1;
image: { width: number; height: number };
@@ -88,6 +105,7 @@ export interface Rig {
accessories?: Accessory[];
hand?: Hand;
cloth?: Cloth[];
+ legs?: Legs;
mesh: {
baseCell: number;
fine: { x0: number; x1: number; y0: number; y1: number; cell: number };
diff --git a/packages/runtime/src/rig/validate.ts b/packages/runtime/src/rig/validate.ts
index 36cebe8..f51659d 100644
--- a/packages/runtime/src/rig/validate.ts
+++ b/packages/runtime/src/rig/validate.ts
@@ -79,15 +79,18 @@ const schema = (draft: boolean) => object({
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,
+ responseGain: 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'])),
+ parent: string, scale: positive }, ['responseGain', 'columns', 'rows', 'stiffness', 'damping', 'max', 'swing', 'follow', 'cohesion', 'wind', 'behind', 'parent', 'scale'])),
+ legs: object({ spine: unit, bob: nonnegative, pelvis: point, shift: nonnegative, tilt: nonnegative, bend: nonnegative,
+ band, split: line, left: object({ hip: point, knee: point, ankle: point }),
+ right: object({ hip: point, knee: point, ankle: point }) }, ['spine', 'bob']),
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,
clothCell: integer }, ['clothCell']),
view: object({ padTop: number, padSide: number, gazeCenter: point }, ['gazeCenter']),
-}, ['buns', 'strands', 'accessories', 'hand', 'cloth']);
+}, ['buns', 'strands', 'accessories', 'hand', 'cloth', 'legs']);
export function validateRig(value: unknown, options: { draft?: boolean } = {}): string[] {
const errors: string[] = [];
@@ -120,6 +123,16 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):
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>();
+ if (rig.legs) {
+ const legs = rig.legs;
+ for (const side of ['left', 'right'] as const) {
+ const b = legs[side];
+ if (!(legs.band[0] < b.hip[1] && b.hip[1] < b.knee[1] && b.knee[1] < b.ankle[1]))
+ errors.push(`rig.legs.${side}: require band start < hip y < knee y < ankle y`);
+ }
+ if (legs.split.some((p, i) => i > 0 && p[1] <= legs.split[i - 1][1]))
+ errors.push('rig.legs.split: y coordinates must increase');
+ }
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`);
diff --git a/src/editor/Preview.tsx b/src/editor/Preview.tsx
index e5d930c..e806d88 100644
--- a/src/editor/Preview.tsx
+++ b/src/editor/Preview.tsx
@@ -15,6 +15,7 @@ const sliders = [
{ id: 'angleZ', label: 'tilt', min: -30, max: 30, def: 0 },
{ id: 'EyeOpen', label: 'eyeOpen', min: 0, max: 1.25, def: 1 },
{ id: 'mouthOpen', label: 'mouthOpen', min: 0, max: 1, def: 0 },
+ { id: 'weightShift', label: 'weightShift', min: -1, max: 1, def: 0 },
{ id: 'bodyAngleZ', label: 'bodyTilt', min: -10, max: 10, def: 0 },
] as const;
type Vowel = 'a' | 'i' | 'u' | 'e' | 'o' | 'n';
diff --git a/src/editor/RigFields.tsx b/src/editor/RigFields.tsx
index 1c25c76..3be9b68 100644
--- a/src/editor/RigFields.tsx
+++ b/src/editor/RigFields.tsx
@@ -2,13 +2,14 @@ import type { Rig } from 'mesh-avatar';
import { getAt } from './model';
import { NumericField } from './NumericField';
import { useI18n } from './i18n';
+import { LEG_DEFAULTS } from '../../packages/runtime/src/engine/legs.js';
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;
}) {
const { t, title } = useI18n();
- const label = title(path === scope ? path.split('.').at(-1)! : path.slice(scope.length + 1));
+ const label = title(path.startsWith('legs.split') ? path : path === scope ? path.split('.').at(-1)! : path.slice(scope.length + 1));
const value = getAt(rig, path);
if (typeof value === 'number') return <NumericField path={path} label={label} value={value} onChange={number => onChange(path, number)} />;
if (!value || typeof value !== 'object') return null;
@@ -18,9 +19,9 @@ export function RigFields({ rig, path, scope = path, onChange }: {
value={number} onChange={next => onChange(`${path}.${index}`, next)} />)}
</div><small>{path}</small></div>;
}
- const fields = /^cloth\.\d+$/.test(path) ? { ...CLOTH_DEFAULTS, ...value } : value;
+ const fields = /^cloth\.\d+$/.test(path) ? { ...CLOTH_DEFAULTS, ...value } : path === 'legs' ? { ...LEG_DEFAULTS, ...value } : value;
const children = Object.entries(fields).map(([key, child]) =>
- /^cloth\.\d+$/.test(path) && Object.hasOwn(CLOTH_DEFAULTS, key)
+ (/^cloth\.\d+$/.test(path) && Object.hasOwn(CLOTH_DEFAULTS, key)) || (path === 'legs' && Object.hasOwn(LEG_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>;
diff --git a/src/editor/i18n-zh.ts b/src/editor/i18n-zh.ts
index e00032b..81f8cbc 100644
--- a/src/editor/i18n-zh.ts
+++ b/src/editor/i18n-zh.ts
@@ -24,7 +24,7 @@ export const uiZh = {
lipSync: '嘴型测试', release: '松开嘴型', lipText: '日语假名文本', lipPlay: '播放', lipStop: '停止',
lipSpeed: '每秒音拍数', lipLoop: '循环', skippedKana: '已跳过的字符:', lipHelp: '支持日语假名和空格(あ=a、い=i、う=u、え=e、お=o)。仅预览嘴型,不播放声音。',
sweepTip: '让头部在完整角度范围内转动,检查图层之间的缝隙或破损',
- turn: '左右转头', look: '抬头/低头', tilt: '头部倾斜', eyeOpen: '眼睛开合', mouthOpen: '嘴巴开合', bodyTilt: '身体倾斜',
+ turn: '左右转头', look: '抬头/低头', tilt: '头部倾斜', eyeOpen: '眼睛开合', mouthOpen: '嘴巴开合', bodyTilt: '身体倾斜', weightShift: '重心转移',
loading: '正在加载本地素材…', updating: '正在更新预览…', ready: '预览已就绪', previewError: '无法加载预览',
selection: '选中部件', selectedItem: '选中的绑定项', selectPart: '选择一个部件进行编辑', tip: '调整提示',
guideTitle: '开始编辑,只需三步', guide1: '选择左侧的部件', guide2: '拖动原图上的控制点',
@@ -89,6 +89,7 @@ export const workflowZh: typeof workflowEn = {
};
export const partsZh: Record<PartGroup, [string, string, string]> = {
+ legs: ['双腿', '双脚固定时的重心转移。', '设置骨盆及图像左右的髋、膝、踝关节,描出双腿分界线,再检查左右重心转移。'],
cloth: ['布料', '裙摆和垂布的摆动。', '调整腰线与下摆控制点,再调整频率、阻尼和风力。'],
head: ['头部转动', '转头或倾斜时跟随动作的区域。', '把中心放在面部中央,椭圆应覆盖包括头发在内的整个头部。'],
eyes: ['眼睛', '眼睛开口轮廓,用于眨眼和视线变化。', '沿睫毛内侧描出眼睛开口,在轮廓转弯处添加控制点。'],
@@ -105,7 +106,10 @@ export const partsZh: Record<PartGroup, [string, string, string]> = {
};
export const fieldsZh: Record<string, string> = {
- swing: '下摆频率 (Hz)', stiffness: '刚度倍率', damping: '阻尼倍率', follow: '上行跟随', cohesion: '横向平滑次数',
+ spine: '脊柱稳定', bob: '换重心下沉 (px)', responseGain: '布料夸张倍率 (1 = 物理)',
+ pelvis: '骨盆', left: '图像左腿', right: '图像右腿', hip: '髋关节', knee: '膝盖', ankle: '脚踝',
+ shift: '横向位移 (px)', tilt: '骨盆倾角 (rad)', bend: '膝盖弯曲量 (px)',
+ scale: '图像比例 (mm/px)', swing: '频率倍率', stiffness: '刚度倍率', damping: '阻尼倍率', follow: '列刚性', cohesion: '横向平滑次数',
wind: '风力', waist: '腰线', hem: '下摆线', columns: '列数', rows: '行数', clothCell: '布料网格间距',
image: '原图', width: '宽度', height: '高度', name: '名称',
center: '中心', pivot: '支点', rx: '横向半径', ry: '纵向半径',
diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsx
index 0282e7e..dde61d2 100644
--- a/src/editor/i18n.tsx
+++ b/src/editor/i18n.tsx
@@ -32,7 +32,7 @@ const en = {
lipSync: 'Lip sync', release: 'Release', lipText: 'Kana text', lipPlay: 'Play', lipStop: 'Stop',
lipSpeed: 'Morae per second', lipLoop: 'Loop', skippedKana: 'Skipped characters:', lipHelp: 'Hiragana, katakana and spaces. Preview only; no audio.',
sweepTip: 'Swings the head through its full range to find tears',
- turn: 'Turn left/right', look: 'Look up/down', tilt: 'Tilt', eyeOpen: 'Eyes open', mouthOpen: 'Mouth open', bodyTilt: 'Body tilt',
+ turn: 'Turn left/right', look: 'Look up/down', tilt: 'Tilt', eyeOpen: 'Eyes open', mouthOpen: 'Mouth open', bodyTilt: 'Body tilt', weightShift: 'Weight shift',
loading: 'Loading local assets…', updating: 'Updating preview…', ready: 'Engine ready', previewError: 'Preview could not load',
selection: 'Selected part', selectedItem: 'Selected rig item', selectPart: 'Select a part to edit it', tip: 'Tip',
guideTitle: 'Three steps to your first edit', guide1: 'Pick a part on the left', guide2: 'Drag its dots on the image',
@@ -75,7 +75,7 @@ const ja: typeof en = {
lipSync: '口の動き', release: '解除', lipText: 'かなの文章', lipPlay: '再生', lipStop: '停止',
lipSpeed: '1秒あたりの拍数', lipLoop: '繰り返し', skippedKana: '読み飛ばす文字:', lipHelp: 'ひらがな・カタカナ・空白に対応。音声は再生しません。',
sweepTip: '頭を最大角度まで動かし、画像の隙間や破れを確認します',
- turn: '顔を左右に向ける', look: '顔を上下に向ける', tilt: '頭を傾ける', eyeOpen: '目の開き', mouthOpen: '口の開き', bodyTilt: '体を傾ける',
+ turn: '顔を左右に向ける', look: '顔を上下に向ける', tilt: '頭を傾ける', eyeOpen: '目の開き', mouthOpen: '口の開き', bodyTilt: '体を傾ける', weightShift: '体重移動',
loading: '画像を読み込み中…', updating: 'プレビューを更新中…', ready: 'プレビューの準備完了', previewError: 'プレビューを読み込めませんでした',
selection: '選択パーツ', selectedItem: '選択するパーツ', selectPart: 'パーツを選んで編集してください', tip: '調整のコツ',
guideTitle: '最初の編集は3ステップ', guide1: '左の一覧からパーツを選ぶ', guide2: '画像の点をドラッグする',
@@ -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' | 'cloth' | 'mesh' | 'view';
+export type PartGroup = 'head' | 'eyes' | 'mouth' | 'face' | 'cheeks' | 'strands' | 'buns' | 'accessories' | 'body' | 'hand' | 'legs' | 'cloth' | 'mesh' | 'view';
const partText: Record<Language, Record<PartGroup, [string, string, string]>> = {
zh: partsZh,
en: {
+ legs: ['Legs', 'Planted feet and weight transfer.', 'Place the pelvis and image-left/right hip, knee and ankle joints. Trace the split between the legs, then test both weight-shift directions.'],
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.'],
@@ -115,6 +116,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: {
+ legs: ['脚・体重移動', '足を接地させたまま体重を移す動き。', '骨盤と画像左右の股関節・膝・足首を合わせ、脚の境界線を置いてから左右の体重移動を確認してください。'],
cloth: ['布・スカート', 'スカートや垂れ布の揺れ。', '腰と裾の点を合わせ、周期・減衰・風の強さを調整してください。'],
head: ['頭の向き', '顔を振ったり傾けたりするときに動く範囲。', '中心を顔の真ん中に置き、円が髪を含む頭全体を覆うように調整してください。'],
eyes: ['目', '目の開口部の輪郭。まばたきと視線に使う。', 'まつ毛の内側に沿って輪郭を置き、曲がる場所に点を追加してください。'],
@@ -131,8 +133,14 @@ 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', '列の平滑化回数'],
+ pelvis: ['Pelvis', '骨盤'], left: ['Image-left leg', '画像左の脚'], right: ['Image-right leg', '画像右の脚'],
+ hip: ['Hip', '股関節'], knee: ['Knee', '膝'], ankle: ['Ankle', '足首'],
+ shift: ['Sideways travel (px)', '横の移動量 (px)'], tilt: ['Pelvic tilt (rad)', '骨盤の傾き (rad)'], bend: ['Knee flexion (px)', '膝の曲げ量 (px)'],
+ spine: ['Spine stabilization', '背骨の安定化'], bob: ['Transfer dip (px)', '乗せ替え時の沈み (px)'],
+ responseGain: ['Cloth exaggeration (1 = physical)', '布の誇張倍率 (1 = 物理どおり)'],
+ scale: ['Image scale (mm/px)', '画像の縮尺 (mm/px)'],
+ swing: ['Frequency multiplier', '周波数の倍率'], stiffness: ['Stiffness multiplier', 'ばねの倍率'],
+ damping: ['Damping multiplier', '減衰の倍率'], follow: ['Column rigidity', '列の剛性'], cohesion: ['Smoothing passes', '列の平滑化回数'],
wind: ['Wind strength', '風の強さ'], waist: ['Waist line', '腰の線'], hem: ['Hem line', '裾の線'],
columns: ['Columns', '列数'], rows: ['Rows', '行数'], clothCell: ['Cloth cell size', '布の格子幅'],
image: ['Source image', '元画像'],
@@ -168,6 +176,7 @@ export function fieldTitle(path: string, language: Language) {
if (key === 'accessories') return t.accessory;
if (key in parts) return parts[key as PartGroup][0];
}
+ if (key === 'split' && path.startsWith('legs.')) return { en: 'Leg boundary', ja: '脚の境界線', zh: '双腿分界线' }[language];
return language === 'zh' ? fieldsZh[key] ?? key : fieldText[key]?.[language === 'en' ? 0 : 1] ?? key;
}).join(' · ');
}
diff --git a/src/editor/model.ts b/src/editor/model.ts
index f051157..48ab913 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', 'waist', 'hem'].includes(key);
+ const editable = closed || ['nodes', 'jaw', 'waist', 'hem', ...(group === 'legs' ? ['split'] : [])].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;
@@ -166,5 +166,11 @@ export function buildOverlay(rig: Rig): { handles: Handle[]; shapes: Shape[] } {
Object.entries(object).forEach(([key, child]) => walk(child, `${path}.${key}`, group));
}
Object.entries(rig).forEach(([group, value]) => { if (group !== 'image') walk(value, group, group); });
+ if (rig.legs) {
+ for (const side of ['left', 'right'] as const) {
+ const leg = rig.legs[side];
+ shapes.push({ item: `legs.${side}`, group: 'legs', kind: 'line', points: [rig.legs.pelvis, leg.hip, leg.knee, leg.ankle] });
+ }
+ }
return { handles, shapes };
}
diff --git a/src/editor/parts.ts b/src/editor/parts.ts
index c708929..554d28c 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', 'cloth', 'mesh', 'view'];
+export const GROUPS: PartGroup[] = ['head', 'eyes', 'mouth', 'face', 'cheeks', 'strands', 'buns', 'accessories', 'body', 'hand', 'legs', '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', cloth: '#e040a0', mesh: '#5a6a7c', view: '#2b69d5',
+ buns: '#ba31ad', legs: '#16847e', 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', 'cloth'] },
+ { key: 'bodySection', groups: ['body', 'hand', 'legs', 'cloth'] },
{ key: 'advanced', groups: ['mesh', 'view'] },
] as const;
export function partPresent(rig: Rig, group: PartGroup) {
diff --git a/tests/cloth.test.ts b/tests/cloth.test.ts
index b73a8fb..4f2b21c 100644
--- a/tests/cloth.test.ts
+++ b/tests/cloth.test.ts
@@ -11,8 +11,10 @@ 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;
+ deformBase(x: number, y: number, _w: unknown, P: { shift: number; lift?: number; rotation?: number }, _phys: unknown, out: number[]) {
+ const angle = P.rotation ?? 0;
+ out[0] = x * Math.cos(angle) - y * Math.sin(angle) + P.shift;
+ out[1] = x * Math.sin(angle) + y * Math.cos(angle) + (P.lift ?? 0); return out;
},
} as unknown as Parameters<typeof createCloth>[0];
const { Cloth: Simulator, garments } = createCloth(engine, rig);
@@ -24,7 +26,7 @@ function simulation(tuning: Partial<ClothTuning> = {}, parts = [garment()]) {
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 }]) {
+ 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 }, { scale: 0 }, { scale: -1 }, { responseGain: 0 }]) {
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([]);
@@ -89,3 +91,107 @@ test('cloth geometry has editable handles and only cut-out changes stale layers'
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);
});
+
+test('both physical links retain length while the lower link can lag', () => {
+ const s = simulation({ wind: 0, follow: 1, cohesion: 0 }); s.step(); s.step(10);
+ let maxDifference = 0, lift = 0;
+ for (let f = 0; f < 120; f++) {
+ s.step(10); const g = s.garments[0];
+ maxDifference = Math.max(maxDifference, Math.abs(g.angle[0] - g.lowerAngle[0]));
+ for (let k = 0; k < g.cols; k++) {
+ const top = k * 2, joint = (2 * g.cols + k) * 2, hem = (4 * g.cols + k) * 2;
+ expect(Math.hypot(g.out[joint] - g.out[top], g.out[joint + 1] - g.out[top + 1])).toBeCloseTo(50, 8);
+ expect(Math.hypot(g.out[hem] - g.out[joint], g.out[hem + 1] - g.out[joint + 1])).toBeCloseTo(50, 8);
+ lift = Math.max(lift, g.target[hem + 1] - g.out[hem + 1]);
+ }
+ }
+ expect(maxDifference).toBeGreaterThan(0.001);
+ expect(lift).toBeGreaterThan(0.001);
+});
+
+test('a physical 13px step settles within two to three significant cycles', () => {
+ const s = simulation({ swing: 1, stiffness: 1, damping: 1, max: 35, follow: 0.95 }); s.step();
+ const values: number[] = [];
+ for (let f = 0; f < 600; f++) { s.step(13); const g = s.garments[0]; values.push(g.out.at(-2)! - g.target.at(-2)!); }
+ // The conventional2% settling band excludes infinitesimal damping tails.
+ const significant = values.filter(v => Math.abs(v) > 13 * 0.02);
+ const crossings = significant.slice(1).filter((v, i) => v * significant[i] < 0).length;
+ expect(crossings).toBeGreaterThanOrEqual(3);
+ expect(crossings).toBeLessThanOrEqual(6);
+ expect(Math.max(...values.slice(240).map(Math.abs))).toBeLessThan(13 * 0.02);
+});
+
+test('wind has no column phase offset and follows the moving parent attachment', () => {
+ const s = simulation({ wind: 0.4, cohesion: 0 }, [garment(), { ...garment(), name: 'tail', parent: 'skirt', waist: [[0, 100], [100, 100]], hem: [[0, 200], [100, 200]] }]);
+ for (let f = 0; f < 600; f++) {
+ s.step(); const g = s.garments[0];
+ for (let k = 1; k < g.cols; k++) expect(g.angle[k]).toBeCloseTo(g.angle[0], 12);
+ }
+ const [parent, tail] = s.garments;
+ for (let k = 0; k < parent.cols; k++) for (let axis = 0; axis < 2; axis++)
+ expect(tail.out[k * 2 + axis]).toBeCloseTo(parent.out[((parent.rows - 1) * parent.cols + k) * 2 + axis], 10);
+});
+
+test('paused redraw updates waist attachment without advancing pendulum time', () => {
+ const s = simulation(); s.step();
+ s.cloth.step({ shift: 13 }, 0, {});
+ expect(s.cloth.time).toBe(1 / 60);
+ expect(s.garments[0].out[0]).toBe(13);
+ expect(s.garments[0].angle.every(v => v === 0)).toBe(true);
+});
+
+test('source scale and gravity set the pendulum period, and vertical acceleration changes it', () => {
+ const s = simulation({ swing: 1, stiffness: 1, damping: 1, cohesion: 0 }, [{ ...garment(), scale: 2 }]); s.step();
+ // Equal half-links at2mm/px: the low coupled mode is1.306Hz
+ // after zeta0.25 damping (the high mode is3.152Hz).
+ s.step(3); const crossings: number[] = []; let previous = s.garments[0].angle[0];
+ for (let f = 0; f < 240; f++) { s.step(3); const angle = s.garments[0].angle[0]; if (angle > 0 && previous <= 0) crossings.push((f + 1) / 60); previous = angle; }
+ expect(crossings.length).toBeGreaterThanOrEqual(3);
+ const measured = 1 / (crossings[2] - crossings[1]);
+ expect(measured).toBeCloseTo(1.306, 1);
+ expect(s.garments[0].gravity).toBeCloseTo(4903.325, 5);
+ const up = simulation({ swing: 1, stiffness: 1, damping: 1, cohesion: 0 }, [{ ...garment(), scale: 2 }]); up.step();
+ const upCrossings: number[] = []; previous = 0;
+ for (let f = 0; f < 240; f++) {
+ const t = (f + 1) / 60;
+ up.cloth.step({ shift: 3, lift: -0.5 * 4903.325 * t * t }, 1 / 60, {});
+ const angle = up.garments[0].angle[0];
+ if (angle > 0 && previous <= 0) upCrossings.push(t);
+ previous = angle;
+ }
+ expect(1 / (upCrossings[2] - upCrossings[1])).toBeCloseTo(measured * Math.sqrt(2), 1);
+});
+
+
+test('a tilted waist leaves each column hanging in its world-rest orientation', () => {
+ const s = simulation({ wind: 0 });
+ s.cloth.step({ shift: 0, rotation: 0.3 }, 1 / 60, {});
+ const g = s.garments[0];
+ for (let k = 0; k < g.cols; k++) {
+ const top = k * 2, hem = ((g.rows - 1) * g.cols + k) * 2;
+ expect(g.out[hem] - g.out[top]).toBeCloseTo(0, 10);
+ expect(g.out[hem + 1] - g.out[top + 1]).toBeCloseTo(100, 10);
+ }
+});
+
+
+test('cloth exaggeration changes only rendered angles, not dynamics or link lengths', () => {
+ const a = simulation({ responseGain: 1, follow: 1 }), b = simulation({ responseGain: 1.6, follow: 1 });
+ a.step(); b.step(); a.step(2, 12); b.step(2, 12);
+ const ga = a.garments[0], gb = b.garments[0];
+ expect(gb.angle).toEqual(ga.angle); expect(gb.lowerAngle).toEqual(ga.lowerAngle);
+ const offset = (g: typeof ga) => g.out.at(-2)! - g.target.at(-2)!;
+ expect(Math.abs(offset(gb) / offset(ga))).toBeGreaterThan(1.5);
+ expect(Math.abs(offset(gb) / offset(ga))).toBeLessThan(1.7);
+});
+
+test('parent exaggeration does not feed back into child dynamics', () => {
+ const parts: Cloth[] = [garment(), { ...garment(), name: 'tail', parent: 'skirt', waist: [[0, 100], [100, 100]], hem: [[0, 200], [100, 200]] }];
+ const a = simulation({ responseGain: 1 }, parts), b = simulation({ responseGain: 1.6 }, parts);
+ for (let f = 0; f < 180; f++) { const x = Math.sin(f / 60 * 5) * 5; a.step(x); b.step(x); }
+ for (let g = 0; g < 2; g++) {
+ expect(b.garments[g].angle).toEqual(a.garments[g].angle);
+ expect(b.garments[g].lowerAngle).toEqual(a.garments[g].lowerAngle);
+ expect(b.garments[g].physicalOut).toEqual(a.garments[g].physicalOut);
+ }
+});
diff --git a/tests/editor.test.ts b/tests/editor.test.ts
index 7247e64..8edc2f4 100644
--- a/tests/editor.test.ts
+++ b/tests/editor.test.ts
@@ -46,3 +46,26 @@ test('integer rectangles and cells round in both handle moves and numeric edits
expect(moveHandle(rig, handles.find(h => h.id === 'head.center')!, [615.35, 400.24]).head).toMatchObject({ cx: 615.4, cy: 400.2 });
expect(validateRig(box)).toEqual([]); expect(validateRig(fine)).toEqual([]);
});
+
+test('leg joints and the editable split update weights without invalidating image layers', async () => {
+ const { layerSignature } = await import('../src/editor/stale');
+ let rig = parseRig(fixture);
+ rig.legs = {
+ pelvis: [640, 800], shift: 20, tilt: 0.06, bend: 10, band: [750, 850],
+ left: { hip: [520, 850], knee: [530, 1000], ankle: [520, 1200] },
+ right: { hip: [740, 850], knee: [730, 1000], ankle: [740, 1200] },
+ split: [[630, 840], [630, 1254]],
+ };
+ const baseline = layerSignature(rig), overlay = buildOverlay(rig);
+ for (const id of ['legs.pelvis', ...['left', 'right'].flatMap(side => ['hip', 'knee', 'ankle'].map(joint => `legs.${side}.${joint}`))])
+ expect(overlay.handles.some(handle => handle.id === id)).toBe(true);
+ expect(overlay.shapes.filter(shape => /^legs\.(left|right)$/.test(shape.item))).toHaveLength(2);
+ const knee = overlay.handles.find(handle => handle.id === 'legs.left.knee')!;
+ rig = moveHandle(rig, knee, [540, 1010]);
+ expect(rig.legs!.left.knee).toEqual([540, 1010]);
+ expect(overlay.handles.find(handle => handle.id === 'legs.split.0')!.vertex).toMatchObject({ path: 'legs.split', closed: false });
+ rig = changeVertex(rig, 'legs.split', 1, [635, 1000], false);
+ expect(rig.legs!.split).toHaveLength(3);
+ expect(layerSignature(rig)).toBe(baseline);
+ expect(validateRig(rig)).toEqual([]);
+});
diff --git a/tests/legs.test.ts b/tests/legs.test.ts
new file mode 100644
index 0000000..4c14a01
--- /dev/null
+++ b/tests/legs.test.ts
@@ -0,0 +1,203 @@
+import { expect, test, vi } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { parseRig, validateRig, type Legs } from 'mesh-avatar';
+import { createRig, PARAMS } from '../packages/runtime/src/engine/rig.js';
+import { createLegs } from '../packages/runtime/src/engine/legs.js';
+import { Motion } from '../packages/runtime/src/engine/motion.js';
+import { triangleMetrics } from '../tools/quality-metrics.mjs';
+
+const legs: Legs = {
+ pelvis: [512, 600], shift: 4, tilt: 0.002, bend: 2, band: [540, 700],
+ left: { hip: [440, 680], knee: [450, 1005], ankle: [435, 1235] },
+ right: { hip: [580, 680], knee: [570, 1005], ankle: [585, 1235] },
+ split: [[508, 670], [508, 1536]],
+};
+const defaults = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+const phys = { gain: 0, bunL: [0, 0], bunR: [0, 0], strands: [] };
+const length = (a: number[], b: number[]) => Math.hypot(...a.map((n, i) => n - b[i]));
+function rigWithLegs() { const rig = parseRig(fixture); rig.legs = structuredClone(legs); return rig; }
+
+test('optional legs validate and malformed joints, split and amounts are rejected', () => {
+ expect(validateRig(rigWithLegs())).toEqual([]);
+ for (const change of [
+ (l: Legs) => { l.left.knee[1] = l.left.ankle[1]; },
+ (l: Legs) => { l.split[1][1] = l.split[0][1]; },
+ (l: Legs) => { l.bend = -1; },
+ (l: Legs) => { l.shift = NaN; },
+ (l: Legs) => { l.spine = 1.1; },
+ (l: Legs) => { l.bob = -1; },
+ ]) {
+ const rig = rigWithLegs(); change(rig.legs!);
+ expect(validateRig(rig).join()).toContain('rig.legs');
+ }
+});
+
+test('weightShift never changes a legacy rig; neutral legs add exactly zero deformation', () => {
+ const old = createRig(parseRig(fixture)), newer = createRig(rigWithLegs());
+ const model = createLegs(legs, fixture.body)!;
+ for (let y = 0; y <= 1536; y += 12) for (let x = 350; x <= 670; x += 20) {
+ const w = old.baseWeights(x, y, 0), out = [0, 0];
+ const expected = [...old.deformBase(x, y, w, defaults, phys, out)];
+ for (const weightShift of [-1, 0, 1])
+ expect(old.deformBase(x, y, w, { ...defaults, weightShift }, phys, [0, 0])).toEqual(expected);
+ const p = [x, y];
+ model.apply(p, x, y, model.weights(x, y), defaults);
+ expect(p).toEqual([x, y]);
+ expect(newer.deformBase(x, y, newer.baseWeights(x, y, 0), defaults, phys, [0, 0])).toEqual(expected);
+ }
+});
+
+test('two-bone IK keeps both bone lengths, planted ankles and a continuous small pelvis correction', () => {
+ const model = createLegs(legs, fixture.body)!;
+ const neutral = model.frame({ weightShift: 0, bodyAngleX: 0 });
+ let previous: ReturnType<typeof model.frame> | undefined;
+ let maxDrop = 0;
+ for (let i = -1000; i <= 1000; i++) {
+ const weightShift = i / 1000;
+ const F = model.frame({ weightShift, bodyAngleX: 0 });
+ maxDrop = Math.max(maxDrop, F.drop);
+ for (const [j, side] of (['left', 'right'] as const).entries()) {
+ const rest = neutral.bones[j], b = F.bones[j];
+ expect(length(b.hip3, b.knee3)).toBeCloseTo(length(rest.hip3, rest.knee3), 8);
+ expect(length(b.knee3, b.ankle3)).toBeCloseTo(length(rest.knee3, rest.ankle3), 8);
+ expect(b.ankle).toEqual(legs[side].ankle);
+ if (previous) expect(length(b.knee, previous.bones[j].knee)).toBeLessThan(0.1);
+ }
+ previous = F;
+ }
+ expect(maxDrop).toBeLessThan(3);
+ const engine = createRig(rigWithLegs());
+ for (const weightShift of [-1, 0, 1]) for (const bodyAngleX of [-10, 10])
+ for (let y = 1235; y < 1536; y += 7) for (const x of [400, 435, 585, 620]) {
+ const P = { ...defaults, weightShift, bodyAngleX, bodyAngleZ: 10, breath: 1, angleX: 30 };
+ expect(engine.deformBase(x, y, engine.baseWeights(x, y), P, phys, [0, 0])).toEqual([x, y]);
+ }
+});
+
+test('weight transfers do not invert the hip, knee or ankle mesh', () => {
+ const engine = createRig(rigWithLegs());
+ const rest: number[] = [], tris: number[] = [];
+ // Separate leg strips keep triangles out of the transparent crotch gap.
+ for (const [x0, x1] of [[390, 495], [525, 630]]) {
+ const base = rest.length / 2, columns = 8, rows = 100;
+ for (let row = 0; row <= rows; row++) for (let col = 0; col <= columns; col++) rest.push(x0 + (x1 - x0) * col / columns, 550 + row * 8);
+ for (let row = 0; row < rows; row++) for (let col = 0; col < columns; col++) {
+ const a = base + row * (columns + 1) + col, b = a + columns + 1;
+ tris.push(a, a + 1, b, a + 1, b + 1, b);
+ }
+ }
+ const weights = Array.from({ length: rest.length / 2 }, (_, i) => engine.baseWeights(rest[i * 2], rest[i * 2 + 1], 0));
+ for (const weightShift of [-1, -0.6, 0, 0.6, 1]) for (const bodyAngleX of [-10, 0, 10]) {
+ const pos = weights.flatMap((w, i) => engine.deformBase(rest[i * 2], rest[i * 2 + 1], w, { ...defaults, weightShift, bodyAngleX }, phys, [0, 0]));
+ expect(triangleMetrics({ rest, pos, tris }).flipped).toBe(0);
+ }
+});
+
+test('soft extension engages before reach is exhausted without popping or stretching bones', () => {
+ const tuned = { ...legs, shift: 12, tilt: 0.035, bend: 6 };
+ const model = createLegs(tuned, fixture.body)!;
+ const neutral = model.frame({ weightShift: 0, bodyAngleX: 0 });
+ let previous = model.frame({ weightShift: -1, bodyAngleX: 0 });
+ let maxDrop = 0;
+ for (let i = -999; i <= 1000; i++) {
+ const F = model.frame({ weightShift: i / 1000, bodyAngleX: 0 });
+ maxDrop = Math.max(maxDrop, F.drop);
+ for (let j = 0; j < 2; j++) {
+ const b = F.bones[j], rest = neutral.bones[j];
+ expect(length(b.knee, previous.bones[j].knee)).toBeLessThan(0.5);
+ expect(length(b.hip3, b.knee3)).toBeCloseTo(length(rest.hip3, rest.knee3), 8);
+ expect(length(b.knee3, b.ankle3)).toBeCloseTo(length(rest.knee3, rest.ankle3), 8);
+ }
+ previous = F;
+ }
+ expect(maxDrop).toBeGreaterThan(0.5);
+ expect(maxDrop).toBeLessThan(3);
+});
+
+test('forward projection limits visible knee travel and skins the shortened bones to their joints', () => {
+ for (const [shift, tilt, bend] of [[8, 0.02, 4], [12, 0.035, 6], [16, 0.05, 8], [20, 0.06, 10]]) {
+ const tuned = { ...legs, shift, tilt, bend }, model = createLegs(tuned, fixture.body)!;
+ for (const weightShift of [-0.6, 0.6]) {
+ const P = { weightShift, bodyAngleX: 0 }, F = model.frame(P);
+ for (const [i, side] of (['left', 'right'] as const).entries()) {
+ const rest = tuned[side], bone = F.bones[i];
+ expect(length(bone.knee, rest.knee)).toBeLessThan(shift * 0.6);
+ for (const joint of ['hip', 'knee', 'ankle'] as const) {
+ const [x, y] = rest[joint], out = [x, y];
+ model.apply(out, x, y, model.weights(x, y), P);
+ expect(out[0]).toBeCloseTo(bone[joint][0], 8);
+ expect(out[1]).toBeCloseTo(bone[joint][1], 8);
+ }
+ const free = i === (weightShift > 0 ? 0 : 1);
+ if (free) {
+ expect(bone.knee3[2]).toBeGreaterThan(0);
+ expect(length(bone.hip, bone.knee)).toBeLessThan(length(rest.hip, rest.knee));
+ expect(length(bone.knee, bone.ankle)).toBeLessThan(length(rest.knee, rest.ankle));
+ }
+ }
+ }
+ }
+});
+
+test('idle weight transfer keeps moving through five-second cycles', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ try {
+ const motion = new Motion([512, 180]); motion.autoIdle = false; motion.autoMotion = false;
+ const samples: number[] = [];
+ for (let f = 0; f < 1440; f++) samples.push(motion.update(1 / 60).weightShift);
+ expect(Math.max(...samples)).toBeLessThanOrEqual(0.7);
+ expect(Math.min(...samples)).toBeGreaterThanOrEqual(-0.7);
+ expect(Math.max(...samples)).toBeGreaterThan(0.6);
+ expect(Math.min(...samples)).toBeLessThan(-0.6);
+ const crossings = samples.flatMap((v, i) => i > 180 && v > 0 && samples[i - 1] <= 0 ? [i] : []);
+ expect(crossings.length).toBeGreaterThanOrEqual(3);
+ for (let i = 1; i < crossings.length; i++) expect(crossings[i] - crossings[i - 1]).toBeCloseTo(300, 0);
+ const speeds = samples.slice(181).map((v, i) => Math.abs(v - samples[i + 180]) * 60);
+ expect(speeds.filter(v => v < 0.05).length / speeds.length).toBeLessThan(0.15);
+ } finally { random.mockRestore(); }
+});
+
+test('serial trunk response delays the chest, stabilizes the head and preserves planted feet', () => {
+ const body = structuredClone(fixture.body); body.chest.cy = legs.pelvis[1] - 150;
+ const head = { ...fixture.head, pivotX: 512, pivotY: 350, weightBand: [300, 360] };
+ const tuned = { ...legs, shift: 20, tilt: 0.06, bend: 10, spine: 0.7, bob: 2 };
+ const model = createLegs(tuned, body, head)!;
+ const samples: { ws: number; chest: number; head: number }[] = []; let maxBob = 0;
+ for (let f = 0; f < 900; f++) {
+ const ws = 0.7 * Math.sin((f + 1) / 60 * Math.PI * 2 / 5), P = { weightShift: ws, bodyAngleX: 0 };
+ model.step(P, 1 / 60); const F = model.frame(P);
+ samples.push({ ws, chest: F.trunk.chest, head: F.trunk.head }); maxBob = Math.max(maxBob, F.trunk.bob);
+ const foot = [435, 1300]; model.apply(foot, foot[0], foot[1], model.weights(foot[0], foot[1]), P); expect(foot).toEqual([435, 1300]);
+ }
+ const lag = (key: 'chest' | 'head') => {
+ const errors = Array.from({ length: 25 }, (_, delay) => samples.slice(350).reduce((s, value, i) => s + (value[key] - samples[i + 350 - delay].ws) ** 2, 0));
+ return errors.indexOf(Math.min(...errors));
+ };
+ expect(lag('chest') / 60).toBeGreaterThanOrEqual(0.1);
+ expect(lag('chest') / 60).toBeLessThanOrEqual(0.2);
+ expect(lag('head')).toBeGreaterThan(lag('chest'));
+ expect(maxBob).toBeGreaterThan(0.5); expect(maxBob).toBeLessThanOrEqual(2.01);
+ for (let f = 0; f < 240; f++) model.step({ weightShift: 0.7 }, 1 / 60);
+ const P = { weightShift: 0.7 }, F = model.frame(P);
+ expect(F.trunk.bob).toBeLessThan(0.01);
+ const line = (y: number) => [462, 562].map(x => { const q = [x, y]; model.apply(q, x, y, model.weights(x, y), P); return q; });
+ const angle = (line: number[][]) => Math.atan2(line[1][1] - line[0][1], line[1][0] - line[0][0]);
+ expect(angle(line(body.chest.cy)) * F.angle).toBeLessThan(0);
+ expect(Math.abs(angle(line(200)))).toBeLessThan(0.001);
+});
+
+test('planted motion uses held transfers without consuming additional random values', () => {
+ const run = (planted: boolean) => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5), motion = new Motion([512, 180], planted);
+ motion.autoIdle = false; motion.autoMotion = false; const values: ReturnType<typeof motion.update>[] = [];
+ try { for (let f = 0; f < 900; f++) values.push(motion.update(1 / 60)); return { values, calls: random.mock.calls.length }; }
+ finally { random.mockRestore(); }
+ };
+ const old = run(false), planted = run(true);
+ expect(planted.calls).toBe(old.calls);
+ for (let f = 0; f < 900; f++) for (const key of Object.keys(old.values[f]))
+ if (!['weightShift', 'bodyAngleX', 'bodyAngleZ'].includes(key)) expect(planted.values[f][key]).toBe(old.values[f][key]);
+ const values = planted.values.map(p => p.weightShift);
+ expect(Math.max(...values)).toBeLessThan(0.701);
+ expect(values.slice(300).filter(v => Math.abs(v) > 0.69).length / 600).toBeGreaterThan(0.25);
+});
diff --git a/tools/render-poses.mjs b/tools/render-poses.mjs
index d52c3ba..784f1c4 100644
--- a/tools/render-poses.mjs
+++ b/tools/render-poses.mjs
@@ -27,6 +27,7 @@ async function main() {
const project = await realpath(resolve(args[0]));
if (relative(root, project).startsWith('..')) throw new Error('project must stay inside the repository');
const rig = JSON.parse(await readFile(resolve(project, 'rig.json'), 'utf8'));
+ const reviewPoses = rig.legs ? [...poses, ['weight-left', { weightShift: -0.6 }], ['weight-right', { weightShift: 0.6 }]] : poses;
const errors = validateRig(rig);
if (errors.length) throw new Error(errors.join('\n'));
const built = await realpath(resolve(project, 'built'));
@@ -97,6 +98,19 @@ async function main() {
av.advance(seconds, 60); pictures.push([`hair-sway-${i}`, canvas.toDataURL()]);
}
av.destroy();
+ if (rig.legs) {
+ const legs = await avatar();
+ // One complete five-second sway cycle, including its neutral return. Keep cloth
+ // history across frames so the waist and tails visibly follow the pelvis.
+ const snapshots = new Map(Array.from({ length: 10 }, (_, i) => [Math.round(i * 300 / 9), i]));
+ for (let frame = 0; frame <= 300; frame++) {
+ const t = frame / 60;
+ legs.setParameters({ ...defaults, weightShift: 0.7 * Math.sin(t * Math.PI * 2 / 5) });
+ legs.advance(1 / 60, 60);
+ if (snapshots.has(frame)) pictures.push([`weight-shift-${snapshots.get(frame)}`, canvas.toDataURL()]);
+ }
+ legs.destroy();
+ }
if (rig.cloth?.length) {
// garments: lean and shift the body, let go, and follow the swing as it settles
const cl = await avatar();
@@ -141,13 +155,13 @@ async function main() {
ctx.fillStyle = '#171b23'; ctx.font = '16px sans-serif'; ctx.fillText(name, x + 8, y + 22);
}
return { images: [...pictures, ...crops, ['contact-sheet', sheet.toDataURL()]], width, height, cropBounds: { eyes, mouth }, padTop: 0.1, padSide: 0.1 };
- }, { rig, assets, poses });
+ }, { rig, assets, poses: reviewPoses });
if (browserErrors.length) throw new Error(browserErrors.join('\n'));
const review = resolve(project, 'review'); await mkdir(review, { recursive: true });
if (relative(project, await realpath(review)).startsWith('..')) throw new Error('review folder must stay inside the project');
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');
+ await writeFile(resolve(review, 'poses.json'), JSON.stringify({ ...metadata, project: basename(project), fixedFps: 60, poseSeconds: 1, poses: reviewPoses.map(([name, parameters, expression]) => ({ name, parameters, ...(expression && { expression }) })), hairFrames: 6, ...(rig.legs && { weightShiftFrames: 10, weightShiftSeconds: 5 }), files: images.map(([name]) => `${name}.png`) }, null, 2) + '\n');
console.log(`Rendered ${result.images.length} review images in ${relative(root, review)}/`);
} finally {
await browser?.close();