Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add optional hanging arms with small elbow and wrist motion
shinshin861674c25c2ed7
diff --git a/.changeset/optional-hanging-arms.md b/.changeset/optional-hanging-arms.mdnew file mode 100644index 0000000..e88e654--- /dev/null+++ b/.changeset/optional-hanging-arms.md@@ -0,0 +1,5 @@+---+"mesh-avatar": minor+---++Add optional two-bone arms with independent swing and elbow parameters, bounded motion, and subtle idle follow. Avatars without an arms rig retain their existing deformation.diff --git a/packages/runtime/src/engine/arms.js b/packages/runtime/src/engine/arms.jsnew file mode 100644index 0000000..8286b6f--- /dev/null+++ b/packages/runtime/src/engine/arms.js@@ -0,0 +1,68 @@+const clamp = (x, a, b) => Math.max(a, Math.min(b, x));+const finite = (x, fallback = 0) => Number.isFinite(x) ? x : fallback;+const smooth = (a, b, x) => {+ const t = clamp((x - a) / Math.max(1e-6, b - a), 0, 1);+ return t * t * (3 - 2 * t);+};+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];+};+export const ARM_DEFAULTS = Object.freeze({ swing: 4, bend: 6, inward: 0.4 });++/** Optional hanging arms, with image-left/right joints in source pixels. */+export function createArms(arms, body, _legs = null) {+ if (!arms) return null;+ const swing = clamp(finite(arms.swing, ARM_DEFAULTS.swing), 0, 10) * Math.PI / 180;+ const bend = clamp(finite(arms.bend, ARM_DEFAULTS.bend), 0, 12) * Math.PI / 180;+ const inward = clamp(finite(arms.inward, ARM_DEFAULTS.inward), 0, 1);+ const bones = [arms.left, arms.right];+ function splitX(line, y) {+ let i = 0;+ while (i < line.length - 2 && y > line[i + 1][1]) i++;+ const a = line[i], b = line[i + 1];+ const t = clamp((y - a[1]) / Math.max(1e-6, b[1] - a[1]), 0, 1);+ return a[0] + (b[0] - a[0]) * t;+ }+ function weights(x, y) {+ return bones.map((b, i) => {+ const upper = Math.max(1, b.elbow[1] - b.shoulder[1]);+ const lower = Math.max(1, b.wrist[1] - b.elbow[1]);+ const band = Math.max(1, Math.min(upper, lower, body.chest.ry) * 0.2);+ const boundary = splitX(b.split, y), outside = i ? x - boundary : boundary - x;+ // A hard boundary only in the gap. Approach it continuously inside the sleeve.+ const hard = Number(outside >= 0), soft = smooth(-band, band, outside);+ const gap = smooth(b.split[0][1] - band, b.split[0][1], y);+ const membership = soft + (hard - soft) * gap;+ return {+ arm: membership * smooth(b.shoulder[1], b.shoulder[1] + upper * 0.55, y)+ * (1 - smooth(b.split.at(-1)[1], b.split.at(-1)[1] + band, y)),+ forearm: smooth(b.elbow[1] - band, b.elbow[1] + band, y),+ };+ });+ }+ function frame(P, move = p => [...p]) {+ return bones.map((b, i) => {+ const side = i ? 'R' : 'L', sign = i ? -1 : 1;+ const value = clamp(finite(P[`armSwing${side}`]), -1, 1);+ return {+ shoulder: move(b.shoulder), elbow: move(b.elbow),+ swing: sign * swing * value * (value < 0 ? inward : 1),+ // Flex inward; negative values never hyper-extend the elbow.+ bend: -sign * bend * clamp(finite(P[`elbowBend${side}`]), 0, 1),+ };+ });+ }+ function apply(p, _x, _y, w, P, F = frame(P)) {+ const original = [...p];+ F.forEach((b, i) => {+ if (!w[i].arm || (!b.swing && !b.bend)) return;+ const upper = b.swing ? rotate(original, b.shoulder, b.swing) : original;+ const elbow = b.swing ? rotate(b.elbow, b.shoulder, b.swing) : b.elbow;+ const lower = b.bend ? rotate(upper, elbow, b.bend) : upper;+ p[0] += (upper[0] - original[0] + (lower[0] - upper[0]) * w[i].forearm) * w[i].arm;+ p[1] += (upper[1] - original[1] + (lower[1] - upper[1]) * w[i].forearm) * w[i].arm;+ });+ }+ return { weights, frame, apply };+}diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.jsindex 14237bb..f9cc301 100644--- a/packages/runtime/src/engine/createMeshAvatar.js+++ b/packages/runtime/src/engine/createMeshAvatar.js@@ -177,7 +177,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], !!rig.legs);+ const motion = new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy], !!rig.legs, rig.arms ? rig : null);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/motion.js b/packages/runtime/src/engine/motion.jsindex f622fd3..256179d 100644--- a/packages/runtime/src/engine/motion.js+++ b/packages/runtime/src/engine/motion.js@@ -1,6 +1,7 @@// Drives parameters: idle ("auto idle"), mouse follow, blinking, expressions, motions.import { resolveLipSync, lipMotionOptions } from './lip-sync.ts';import { PARAMS } from './rig.js';+import { ARM_DEFAULTS } from './arms.js';import { MOTIONS, IDLE_MOTIONS, ADDITIVE, sampleTrack } from './motions.js';import { VOWELS, kanaToMoras, sampleMoras } from './kana.js';@@ -69,8 +70,11 @@ export function weightTransfer(t) {}export class Motion {- /** @param {number[]} gazeCenter */- constructor(gazeCenter, planted = false) {+ /** @param {number[]} gazeCenter @param {boolean} [planted] @param {import('../rig/types').Rig|null} [armRig] */+ constructor(gazeCenter, planted = false, armRig = null) {+ this.armRig = armRig;+ this.armFollow = 0;+ this.armVelocity = 0;this.planted = planted;this.mode = 'auto'; // auto | mouse | manualthis.P = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));@@ -332,6 +336,28 @@ export class Motion {if (this.mode !== 'manual') T.angleY += T.breath * 1.6;+ if (this.armRig?.arms && this.mode !== 'manual') {+ const { arms, body, legs } = this.armRig;+ const tilt = -T.bodyAngleZ / 10 * body.maxRoll+ + (legs ? legs.tilt * (1 - (legs.spine ?? 0.7)) * T.weightShift : 0);+ // Damped gravity follow: relative rotation cancels part of the torso tilt,+ // with a small lag and no extra RNG calls on the legacy motion path.+ const time = clamp(dt, 0, 0.05), count = Math.ceil(time * 240);+ for (let i = 0; i < count; i++) {+ const h = time / count;+ this.armVelocity += (100 * (-tilt * 0.65 - this.armFollow) - 18 * this.armVelocity) * h;+ this.armFollow += this.armVelocity * h;+ }+ const swing = (arms.swing ?? ARM_DEFAULTS.swing) * Math.PI / 180;+ const inward = arms.inward ?? ARM_DEFAULTS.inward;+ for (const [side, sign] of [['L', 1], ['R', -1]]) {+ const relative = sign * this.armFollow;+ const limit = swing * (relative < 0 ? inward : 1);+ T[`armSwing${side}`] = clamp((limit > 0 ? relative / limit : 0) + (T.breath - 0.5) * 0.06, -1, 1);+ T[`elbowBend${side}`] = T.breath * 0.025;+ }+ }+// expression layer (smoothed so switching is not a jump)const E = EXPRESSIONS[this.expr].p;const keys = ['eyeOpen', 'eyeOpenL', 'eyeSmileL', 'eyeSmile', 'mouthOpen', 'mouthForm', 'blush', 'browY', 'browAngle', 'gx', 'gy'];diff --git a/packages/runtime/src/engine/rig.js b/packages/runtime/src/engine/rig.jsindex 32a9e15..464cbad 100644--- a/packages/runtime/src/engine/rig.js+++ b/packages/runtime/src/engine/rig.js@@ -1,4 +1,5 @@import { createLegs } from './legs.js';+import { createArms } from './arms.js';export const PARAMS = [{ id: 'angleX', label: 'Face angle X', min: -30, max: 30, def: 0, group: 'Head and body' },@@ -21,6 +22,10 @@ export const PARAMS = [{ 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' },+ ...['L', 'R'].flatMap(side => [+ { id: `armSwing${side}`, label: `Arm swing ${side}`, min: -1, max: 1, def: 0, group: 'Arms' },+ { id: `elbowBend${side}`, label: `Elbow bend ${side}`, min: 0, max: 1, def: 0, group: 'Arms' },+ ]),];// Reference algorithms are intentionally retained as JavaScript; the factory's rig input@@ -98,6 +103,7 @@ export function createRig(rig) {const HEAD = rig.head;const BODY = rig.body;const LEGS = createLegs(rig.legs, BODY, HEAD);+ const ARMS = createArms(rig.arms, BODY, rig.legs);const sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };@@ -163,6 +169,7 @@ export function createRig(rig) {breath: 1 - sstep(...BODY.breathBand, y),shoulder: BODY.shoulders.reduce((sum, area) => sum + gaussian(x, y, area), 0),...(LEGS && { legs: LEGS.weights(x, y) }),+ ...(ARMS && { arms: ARMS.weights(x, y) }),};}@@ -212,6 +219,8 @@ export function createRig(rig) {}}+ let armKey, armFrame;+// 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;@@ -243,6 +252,20 @@ export function createRig(rig) {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, w.legs);+ if (ARMS && w.arms.some(a => a.arm > 0)) {+ const key = [P.angleX, P.angleY, P.angleZ, P.bodyAngleX, P.bodyAngleZ, P.breath,+ P.armSwingL, P.armSwingR, P.elbowBendL, P.elbowBendR, LEGS?.frame(P)];+ if (!armKey || key.some((v, i) => v !== armKey[i])) {+ armKey = key;+ armFrame = ARMS.frame(P, point => {+ const q = [...point], a = baseWeights(...point, 0);+ applyHead(q, a.head, P, a.turn);+ applyBody(q, point[1], P, a.chest, a.breath, a.shoulder, a.legs);+ return q;+ });+ }+ ARMS.apply(p, x, y, w.arms, P, armFrame);+ }return p;}diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.tsindex bfb38a4..8ec4ac5 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, Leg, Legs, Cloth, ClothTuning, Ellipse, Point, Band } from './rig/types';+export type { Rig, Eye, Strand, Accessory, Hand, Arm, Arms, 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';@@ -12,3 +12,4 @@ export { validateAvatarFiles } from './format/validate';export { packAvatar, unpackAvatar } from './format/zip';export { openAvatar, loadMeshAvatar } from './format/open';export type { AvatarPackage, AvatarSource, OpenAvatarOptions } from './format/open';+export { ARM_DEFAULTS } from './engine/arms.js';diff --git a/packages/runtime/src/rig/types.ts b/packages/runtime/src/rig/types.tsindex ad0cb78..834ffa3 100644--- a/packages/runtime/src/rig/types.ts+++ b/packages/runtime/src/rig/types.ts@@ -72,6 +72,21 @@ export interface Hand {fingerYBand: Band;pinBand: Band;}+/** A hanging arm separated from the body by a transparent gap. */+export interface Arm {+ shoulder: Point;+ elbow: Point;+ wrist: Point;+ split: Point[];+}+/** Optional two-bone arms. Left/right refer to the image; amounts are degrees. */+export interface Arms {+ left: Arm;+ right: Arm;+ swing?: number;+ bend?: number;+ inward?: number;+}export interface Leg { hip: Point; knee: Point; ankle: Point }/** Optional planted-foot weight transfer. Left/right refer to the image. */export interface Legs {@@ -116,6 +131,7 @@ export interface Rig {hand?: Hand;cloth?: Cloth[];legs?: Legs;+ arms?: Arms;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.tsindex 280359f..ae36e6b 100644--- a/packages/runtime/src/rig/validate.ts+++ b/packages/runtime/src/rig/validate.ts@@ -86,12 +86,15 @@ const schema = (draft: boolean) => object({legs: object({ spine: unit, bob: nonnegative, twist: 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', 'twist']),+ arms: object({ swing: nonnegative, bend: nonnegative, inward: unit,+ left: object({ shoulder: point, elbow: point, wrist: point, split: line }),+ right: object({ shoulder: point, elbow: point, wrist: point, split: line }) }, ['swing', 'bend', 'inward']),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', 'legs']);+}, ['buns', 'strands', 'accessories', 'hand', 'cloth', 'legs', 'arms']);export function validateRig(value: unknown, options: { draft?: boolean } = {}): string[] {const errors: string[] = [];@@ -135,6 +138,32 @@ export function validateRig(value: unknown, options: { draft?: boolean } = {}):if (legs.split.some((p, i) => i > 0 && p[1] <= legs.split[i - 1][1]))errors.push('rig.legs.split: y coordinates must increase');}+ if (rig.arms) {+ if ((rig.arms.swing ?? 4) > 10) errors.push('rig.arms.swing: must be between 0 and 10 degrees');+ if ((rig.arms.bend ?? 6) > 12) errors.push('rig.arms.bend: must be between 0 and 12 degrees');+ for (const side of ['left', 'right'] as const) {+ const arm = rig.arms[side], path = `rig.arms.${side}`;+ if (!(arm.shoulder[1] < arm.elbow[1] && arm.elbow[1] < arm.wrist[1]))+ errors.push(`${path}: require shoulder y < elbow y < wrist y`);+ for (const [key, points] of Object.entries({ shoulder: [arm.shoulder], elbow: [arm.elbow], wrist: [arm.wrist], split: arm.split })) {+ if (points.some(([x, y]) => x < 0 || y < 0 || x >= rig.image.width || y >= rig.image.height))+ errors.push(`${path}.${key}: points must stay inside the image`);+ }+ if (arm.split.some((p, i) => i > 0 && p[1] <= arm.split[i - 1][1])) {+ errors.push(`${path}.split: y coordinates must increase`);+ } else {+ const splitX = (y: number) => {+ let i = 0;+ while (i < arm.split.length - 2 && y > arm.split[i + 1][1]) i++;+ const a = arm.split[i], b = arm.split[i + 1];+ const t = Math.max(0, Math.min(1, (y - a[1]) / (b[1] - a[1])));+ return a[0] + (b[0] - a[0]) * t;+ };+ if ([arm.elbow, arm.wrist].some(([x, y]) => side === 'left' ? splitX(y) <= x : splitX(y) >= x))+ errors.push(`${path}.split: must lie on the body side of elbow and wrist`);+ }+ }+ }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/tests/arms.test.ts b/tests/arms.test.tsnew file mode 100644index 0000000..6207cde--- /dev/null+++ b/tests/arms.test.ts@@ -0,0 +1,159 @@+import { expect, test, vi } from 'vitest';+import fixture from '../samples/miko-qipao/rig.json';+import { ARM_DEFAULTS, parseRig, validateRig, type Arms } from 'mesh-avatar';+import { createArms } from '../packages/runtime/src/engine/arms.js';+import { createRig, PARAMS } from '../packages/runtime/src/engine/rig.js';+import { Motion } from '../packages/runtime/src/engine/motion.js';++const arms: Arms = {+ left: { shoulder: [250, 650], elbow: [200, 800], wrist: [150, 950], split: [[265, 680], [235, 800], [200, 1030]] },+ right: { shoulder: [1004, 650], elbow: [1054, 800], wrist: [1104, 950], split: [[989, 680], [1019, 800], [1054, 1030]] },+};+const defaults = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));+const phys = { gain: 0, bunL: [0, 0], bunR: [0, 0], strands: [] };+function rigWithArms() { const rig = parseRig(fixture); rig.arms = structuredClone(arms); return rig; }++test('optional arms accept defaults and boundary settings; reject malformed geometry and tuning', () => {+ expect(ARM_DEFAULTS).toEqual({ swing: 4, bend: 6, inward: 0.4 });+ expect(validateRig(rigWithArms())).toEqual([]);+ for (const [swing, bend, inward] of [[0, 0, 0], [10, 12, 1]]) {+ const rig = rigWithArms(); Object.assign(rig.arms!, { swing, bend, inward });+ expect(validateRig(rig)).toEqual([]);+ }+ for (const change of [+ (a: Arms) => { a.left.elbow[1] = a.left.shoulder[1]; },+ (a: Arms) => { a.right.wrist[1] = a.right.elbow[1]; },+ (a: Arms) => { a.left.split[1][1] = a.left.split[0][1]; },+ (a: Arms) => { a.right.split = [[900, 680]]; },+ (a: Arms) => { a.left.split[1][0] = 190; },+ (a: Arms) => { a.right.split[1][0] = 1060; },+ (a: Arms) => { a.left.wrist[0] = -1; },+ (a: Arms) => { a.right.shoulder[0] = fixture.image.width; },+ (a: Arms) => { a.left.split[0][1] = -1; },+ (a: Arms) => { a.swing = -1; },+ (a: Arms) => { a.swing = 10.01; },+ (a: Arms) => { a.bend = 12.01; },+ (a: Arms) => { a.bend = -0.01; },+ (a: Arms) => { a.inward = 1.01; },+ (a: Arms) => { a.inward = -0.01; },+ (a: Arms) => { a.left.elbow[0] = NaN; },+ ]) {+ const rig = rigWithArms(); change(rig.arms!);+ expect(validateRig(rig).join()).toContain('rig.arms');+ }+});++test('legacy avatars ignore all new parameters and zero arms preserve every original point exactly', () => {+ const old = createRig(parseRig(fixture)), newer = createRig(rigWithArms());+ let maximum = 0;+ for (const pose of [{}, { bodyAngleZ: 8, bodyAngleX: -7, breath: 0.8, angleZ: 15 }, { angleX: -30, angleY: 15 }]) {+ const P = { ...defaults, ...pose };+ for (let y = 0; y <= fixture.image.height; y += 13) for (let x = 0; x <= fixture.image.width; x += 13) {+ const expected = old.deformBase(x, y, old.baseWeights(x, y, 0), P, phys, [0, 0]);+ expect(old.deformBase(x, y, old.baseWeights(x, y, 0), { ...P, armSwingL: 1, armSwingR: -1, elbowBendL: 1, elbowBendR: 1 }, phys, [0, 0])).toEqual(expected);+ const actual = newer.deformBase(x, y, newer.baseWeights(x, y, 0), P, phys, [0, 0]);+ maximum = Math.max(maximum, Math.hypot(actual[0] - expected[0], actual[1] - expected[1]));+ }+ }+ console.log(`Arms neutral regression: max delta ${maximum} px`);+ expect(maximum).toBe(0);+});++test('image sides swing outwards, inward swing is reduced, flex never hyperextends and controls clamp', () => {+ const model = createArms(arms, fixture.body)!;+ for (const [index, side] of (['L', 'R'] as const).entries()) {+ const rest = index ? arms.right : arms.left;+ const w = model.weights(...rest.wrist);+ const point = (value: number, bend = 0) => {+ const p = [...rest.wrist]; model.apply(p, ...rest.wrist, w, { [`armSwing${side}`]: value, [`elbowBend${side}`]: bend }); return p;+ };+ const outward = point(1), inward = point(-1);+ expect(index ? outward[0] > rest.wrist[0] : outward[0] < rest.wrist[0]).toBe(true);+ expect(index ? inward[0] < rest.wrist[0] : inward[0] > rest.wrist[0]).toBe(true);+ expect(Math.hypot(outward[0] - rest.wrist[0], outward[1] - rest.wrist[1]))+ .toBeGreaterThan(Math.hypot(inward[0] - rest.wrist[0], inward[1] - rest.wrist[1]) * 2);+ expect(point(10, 10)).toEqual(point(1, 1));+ expect(point(-10, -10)).toEqual(point(-1, 0));+ const f = model.frame({ [`armSwing${side}`]: 1, [`elbowBend${side}`]: 1 })[index];+ expect(Math.abs(f.swing)).toBeCloseTo(4 * Math.PI / 180, 12);+ expect(Math.abs(f.bend)).toBeCloseTo(6 * Math.PI / 180, 12);+ const bent = point(0, 1);+ expect(index ? bent[0] < rest.wrist[0] : bent[0] > rest.wrist[0]).toBe(true);+ // Forearm rotation retains its length, and the opposite side is untouched.+ expect(Math.hypot(bent[0] - rest.elbow[0], bent[1] - rest.elbow[1])).toBeCloseTo(Math.hypot(rest.wrist[0] - rest.elbow[0], rest.wrist[1] - rest.elbow[1]), 10);+ const other = index ? arms.left.wrist : arms.right.wrist, p = [...other];+ model.apply(p, ...other, model.weights(...other), { [`armSwing${side}`]: 1, [`elbowBend${side}`]: 1 });+ expect(p).toEqual(other);+ }+});++test('body-side vertices, shoulder seam and points below the arm stay fixed, elbow band is continuous', () => {+ const model = createArms(arms, fixture.body)!;+ const P = { armSwingL: 1, armSwingR: 1, elbowBendL: 1, elbowBendR: 1 };+ for (const rest of [[500, 850], arms.left.shoulder, arms.right.shoulder, [150, 1200]]) {+ const p = [...rest]; model.apply(p, rest[0], rest[1], model.weights(rest[0], rest[1]), P); expect(p).toEqual(rest);+ }+ const points = [799.999, 800, 800.001].map(y => {+ const p = [200, y]; model.apply(p, 200, y, model.weights(200, y), P); return p;+ });+ expect(Math.hypot(points[0][0] - points[2][0], points[0][1] - points[2][1])).toBeLessThan(0.003);+ const bad = structuredClone(arms); bad.left.elbow = [...bad.left.shoulder]; bad.left.wrist = [...bad.left.shoulder]; bad.left.split[1] = [...bad.left.split[0]];+ const degenerate = createArms(bad, fixture.body)!;+ const p = [200, 800]; degenerate.apply(p, 200, 800, degenerate.weights(200, 800), { ...P, armSwingL: NaN, elbowBendL: Infinity });+ expect(p.every(Number.isFinite)).toBe(true);+});++test('arms ride the deformed shoulder, including planted legs, with exact identity when disabled', () => {+ const rig = rigWithArms();+ rig.legs = { pelvis: [627, 900], band: [700, 940], shift: 12, tilt: 0.04, bend: 4,+ left: { hip: [570, 930], knee: [560, 1080], ankle: [550, 1210] },+ right: { hip: [680, 930], knee: [690, 1080], ankle: [700, 1210] }, split: [[627, 950], [627, 1250]] };+ const engine = createRig(rig), plainRig = structuredClone(rig); delete plainRig.arms;+ const plain = createRig(plainRig);+ for (let f = 0; f < 60; f++) {+ const P = { ...defaults, bodyAngleZ: 8, breath: 0.7, weightShift: f / 60 };+ engine.stepBody(P, 1 / 60); plain.stepBody(P, 1 / 60);+ const [x, y] = arms.left.shoulder;+ expect(engine.deformBase(x, y, engine.baseWeights(x, y, 0), { ...P, armSwingL: 1, elbowBendL: 1 }, phys, [0, 0]))+ .toEqual(plain.deformBase(x, y, plain.baseWeights(x, y, 0), P, phys, [0, 0]));+ for (const [px, py] of [arms.left.wrist, arms.right.wrist])+ expect(engine.deformBase(px, py, engine.baseWeights(px, py, 0), P, phys, [0, 0]))+ .toEqual(plain.deformBase(px, py, plain.baseWeights(px, py, 0), P, phys, [0, 0]));+ }+});++test('idle arms follow the torso with lag, consume no RNG, preserve legacy tracks, and respect manual rest', () => {+ const run = (withArms: boolean) => {+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);+ try {+ const m = new Motion([512, 180], false, withArms ? rigWithArms() : null);+ m.autoIdle = false; m.autoMotion = false;+ const samples = Array.from({ length: 600 }, () => m.update(1 / 60));+ return { samples, calls: random.mock.calls.length, m };+ } finally { random.mockRestore(); }+ };+ const old = run(false), newer = run(true);+ expect(newer.calls).toBe(old.calls);+ for (let i = 0; i < 600; i++) for (const key of Object.keys(old.samples[i]))+ if (!/^(armSwing|elbowBend)/.test(key)) expect(newer.samples[i][key]).toBe(old.samples[i][key]);+ expect(old.samples.every(p => p.armSwingL === 0 && p.elbowBendR === 0)).toBe(true);+ expect(newer.samples.some(p => Math.abs(p.armSwingL) > 0.02)).toBe(true);+ expect(newer.samples.every(p => Math.abs(p.armSwingL) <= 1 && p.elbowBendR >= 0 && p.elbowBendR <= 1)).toBe(true);+ newer.m.mode = 'manual';+ const rest = newer.m.update(1 / 60);+ for (const id of ['armSwingL', 'armSwingR', 'elbowBendL', 'elbowBendR']) expect(rest[id]).toBe(0);+ // Start within a planted hold: gravity follow approaches the fixed torso tilt+ // gradually instead of snapping on its first frame.+ const rig = rigWithArms(); rig.body.maxRoll = 0;+ rig.legs = { pelvis: [627, 900], band: [700, 940], shift: 12, tilt: 0.04, bend: 4,+ left: { hip: [570, 930], knee: [560, 1080], ankle: [550, 1210] },+ right: { hip: [680, 930], knee: [690, 1080], ankle: [700, 1210] }, split: [[627, 950], [627, 1250]] };+ const m = new Motion([512, 180], true, rig);+ m.autoIdle = false; m.autoMotion = false; m.t = 1;+ m.update(1 / 60); const initial = Math.abs(m.armFollow);+ for (let i = 0; i < 60; i++) m.update(1 / 60);+ const target = -rig.legs.tilt * 0.3 * 0.7 * 0.65;+ expect(initial).toBeLessThan(Math.abs(target) * 0.1);+ expect(m.armFollow).toBeCloseTo(target, 4);+ expect(Number.isFinite(m.update(1).armSwingL)).toBe(true);+});diff --git a/tools/render-poses.mjs b/tools/render-poses.mjsindex 784f1c4..0bc4503 100644--- a/tools/render-poses.mjs+++ b/tools/render-poses.mjs@@ -27,7 +27,18 @@ 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 reviewPoses = [...poses,+ ...(rig.legs ? [['weight-left', { weightShift: -0.6 }], ['weight-right', { weightShift: 0.6 }]] : []),+ ...(rig.arms ? [+ ['arms-out', { armSwingL: 1, armSwingR: 1 }],+ ['arms-in', { armSwingL: -1, armSwingR: -1 }],+ ['elbows-bent', { elbowBendL: 1, elbowBendR: 1 }],+ ['arm-left', { armSwingL: 1, elbowBendL: 0.5 }],+ ['arm-right', { armSwingR: 1, elbowBendR: 0.5 }],+ ['arms-body-left', { bodyAngleZ: -8, weightShift: -0.6, armSwingL: -1, armSwingR: 1, elbowBendL: 0.5, elbowBendR: 0.5 }],+ ['arms-body-right', { bodyAngleZ: 8, weightShift: 0.6, armSwingL: 1, armSwingR: -1, elbowBendL: 0.5, elbowBendR: 0.5 }],+ ] : []),+ ];const errors = validateRig(rig);if (errors.length) throw new Error(errors.join('\n'));const built = await realpath(resolve(project, 'built'));@@ -111,6 +122,25 @@ async function main() {}legs.destroy();}+ if (rig.arms) {+ const ar = await avatar();+ // Capture a complete outward/bend/return cycle, retaining body physics.+ for (let f = 0; f <= 180; f++) {+ const phase = f / 180 * Math.PI * 2;+ ar.setParameters({ ...defaults, armSwingL: Math.sin(phase), armSwingR: -Math.sin(phase),+ elbowBendL: (1 - Math.cos(phase)) * 0.5, elbowBendR: (1 - Math.cos(phase)) * 0.5 });+ ar.advance(1 / 60, 60);+ if (f % 20 === 0) pictures.push([`arm-cycle-${f / 20}`, canvas.toDataURL()]);+ }+ ar.destroy();+ const idle = await avatar();+ idle.setParameters({});+ for (let f = 0; f <= 300; f++) {+ idle.advance(1 / 60, 60);+ if (f % 30 === 0) pictures.push([`arm-idle-${f / 30}`, canvas.toDataURL()]);+ }+ idle.destroy();+ }if (rig.cloth?.length) {// garments: lean and shift the body, let go, and follow the swing as it settlesconst cl = await avatar();@@ -161,7 +191,7 @@ async function main() {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: 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');+ 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 }), ...(rig.arms && { armCycleFrames: 10, armIdleFrames: 11 }), 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();