Skip to content

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

Add versioned rig schema and data-driven engine

shinshin861c012a585866
diff --git a/docs/rig-mapping.md b/docs/rig-mapping.md
new file mode 100644
index 0000000..a9f16c9
--- /dev/null
+++ b/docs/rig-mapping.md
@@ -0,0 +1,36 @@
+# Rig v1 mapping
+
+Coordinates use source-image pixels. Rotation angles use radians. Parameter ranges and
+spring/motion tuning remain engine behavior constants.
+
+| Rig fields | Reference source |
+| --- | --- |
+| image | rig.js IMG |
+| head | HEAD, headWeight, turnWeight |
+| body | BODY, breath/roll fade bands, chest and shoulder Gaussians |
+| face, buns | baseWeights Gaussians and brow/jaw bands |
+| eyes.opening, eyes.roi | build_layers.py EYES |
+| eyes.x0/x1/top/bot | built/layers.json eyes (24 samples, authoritative pre-cut curves) |
+| mouth | rig.js MOUTH and sprites.js MOUTH_AREA |
+| cheeks | rig.js CHEEKS |
+| strands | rig.js STRANDS |
+| accessories | rig.js TASSELS, build_layers.py search boxes and redness thresholds |
+| hand | rig.js bones, FOREARM_SHARE and weight bands; build_layers.py HAND_POLY, JAW_VISIBLE, JAW_X, BG_BEHIND_HAND |
+| mesh | createMeshAvatar.js layer cell sizes and fine rectangle; sprites.js sprite cell |
+| view | createMeshAvatar.js padTop/padSide defaults |
+| view.gazeCenter (optional) | motion.js pointer-follow origin; defaults to head center when omitted |
+
+The anatomical centers used by the deformation formulas (brow, eyes and chest) also come
+from the matching rig Gaussian centers. Bun spring anchors use their Gaussian centers.
+Optional groups are omitted or empty; no replacement miko-qipao coordinates are supplied.
+
+Changes to eye polygons, hand cut-out geometry and accessory boxes mark layers stale.
+Pre-cut eye curves and image rectangles are preserved until the planned layer builder runs;
+editing a cut-out polygon alone cannot regenerate the missing image pixels by editing coordinates alone.
+
+Strand polylines may have two or more nodes in the editor. Physics resamples their rest
+positions to four nodes so the reference four-node spring algorithm remains unchanged.
+The fixture's original four-node strands are used verbatim to preserve exact regression.
+
+The image-specific deformation constants are mapped above. Image-processing kernel sizes and
+color blending/inpainting algorithms belong to the planned layer builder.
diff --git a/samples/miko-qipao/rig.json b/samples/miko-qipao/rig.json
new file mode 100644
index 0000000..d97ed30
--- /dev/null
+++ b/samples/miko-qipao/rig.json
@@ -0,0 +1,1117 @@
+{
+ "version": 1,
+ "image": {
+ "width": 1254,
+ "height": 1254
+ },
+ "head": {
+ "cx": 615,
+ "cy": 400,
+ "rx": 430,
+ "ry": 470,
+ "shiftX": 50,
+ "shiftY": 40,
+ "pivotX": 640,
+ "pivotY": 700,
+ "maxRoll": 0.15707963267948966,
+ "weightBand": [
+ 630,
+ 800
+ ],
+ "turnBand": [
+ 640,
+ 900
+ ]
+ },
+ "body": {
+ "pivotX": 640,
+ "pivotY": 1650,
+ "maxRoll": 0.05235987755982988,
+ "breathBand": [
+ 1040,
+ 1254
+ ],
+ "rollBand": [
+ 950,
+ 1254
+ ],
+ "chest": {
+ "cx": 660,
+ "cy": 960,
+ "rx": 260,
+ "ry": 200
+ },
+ "shoulders": [
+ {
+ "cx": 230,
+ "cy": 800,
+ "rx": 160,
+ "ry": 120
+ },
+ {
+ "cx": 1040,
+ "cy": 870,
+ "rx": 160,
+ "ry": 120
+ }
+ ]
+ },
+ "face": {
+ "nose": {
+ "cx": 615,
+ "cy": 515,
+ "rx": 45,
+ "ry": 45
+ },
+ "mouth": {
+ "cx": 635,
+ "cy": 568,
+ "rx": 60,
+ "ry": 30
+ },
+ "eyeA": {
+ "cx": 493,
+ "cy": 478,
+ "rx": 80,
+ "ry": 55
+ },
+ "eyeB": {
+ "cx": 713,
+ "cy": 415,
+ "rx": 75,
+ "ry": 55
+ },
+ "earR": {
+ "cx": 828,
+ "cy": 400,
+ "rx": 35,
+ "ry": 60
+ },
+ "earL": {
+ "cx": 418,
+ "cy": 520,
+ "rx": 30,
+ "ry": 55
+ },
+ "brow": {
+ "cx": 700,
+ "cy": 326,
+ "rx": 78,
+ "ry": 20,
+ "band": [
+ 346,
+ 358
+ ]
+ },
+ "jaw": {
+ "cx": 632,
+ "cy": 625,
+ "rx": 100,
+ "ry": 55,
+ "band": [
+ 572,
+ 598
+ ]
+ }
+ },
+ "buns": {
+ "bunL": {
+ "cx": 262,
+ "cy": 250,
+ "rx": 105,
+ "ry": 115
+ },
+ "bunR": {
+ "cx": 820,
+ "cy": 110,
+ "rx": 115,
+ "ry": 105
+ }
+ },
+ "eyes": [
+ {
+ "opening": [
+ [
+ 446,
+ 488
+ ],
+ [
+ 450,
+ 472
+ ],
+ [
+ 458,
+ 464
+ ],
+ [
+ 468,
+ 457
+ ],
+ [
+ 480,
+ 452
+ ],
+ [
+ 495,
+ 450
+ ],
+ [
+ 510,
+ 450
+ ],
+ [
+ 522,
+ 452
+ ],
+ [
+ 532,
+ 457
+ ],
+ [
+ 538,
+ 464
+ ],
+ [
+ 541,
+ 475
+ ],
+ [
+ 541,
+ 488
+ ],
+ [
+ 535,
+ 495
+ ],
+ [
+ 520,
+ 501
+ ],
+ [
+ 505,
+ 506
+ ],
+ [
+ 488,
+ 508
+ ],
+ [
+ 470,
+ 507
+ ],
+ [
+ 457,
+ 503
+ ],
+ [
+ 449,
+ 497
+ ]
+ ],
+ "roi": [
+ [
+ 424,
+ 478
+ ],
+ [
+ 432,
+ 458
+ ],
+ [
+ 445,
+ 440
+ ],
+ [
+ 470,
+ 428
+ ],
+ [
+ 500,
+ 424
+ ],
+ [
+ 530,
+ 426
+ ],
+ [
+ 552,
+ 436
+ ],
+ [
+ 556,
+ 452
+ ],
+ [
+ 552,
+ 470
+ ],
+ [
+ 548,
+ 495
+ ],
+ [
+ 540,
+ 505
+ ],
+ [
+ 520,
+ 512
+ ],
+ [
+ 495,
+ 516
+ ],
+ [
+ 465,
+ 514
+ ],
+ [
+ 445,
+ 506
+ ],
+ [
+ 430,
+ 500
+ ]
+ ],
+ "x0": 446,
+ "x1": 541,
+ "top": [
+ 487.9,
+ 471.87,
+ 467.74,
+ 463.73,
+ 460.83,
+ 457.94,
+ 455.84,
+ 454.12,
+ 452.4,
+ 451.58,
+ 451.03,
+ 450.48,
+ 450.0,
+ 450.0,
+ 450.0,
+ 450.0,
+ 450.35,
+ 451.04,
+ 451.72,
+ 453.24,
+ 455.3,
+ 457.86,
+ 462.68,
+ 481.26
+ ],
+ "bot": [
+ 487.9,
+ 497.85,
+ 500.95,
+ 503.43,
+ 504.7,
+ 505.97,
+ 507.04,
+ 507.27,
+ 507.5,
+ 507.73,
+ 507.96,
+ 507.6,
+ 507.11,
+ 506.62,
+ 506.14,
+ 505.01,
+ 503.64,
+ 502.26,
+ 500.86,
+ 499.21,
+ 497.56,
+ 495.9,
+ 492.82,
+ 481.26
+ ]
+ },
+ {
+ "opening": [
+ [
+ 666,
+ 402
+ ],
+ [
+ 672,
+ 393
+ ],
+ [
+ 685,
+ 387
+ ],
+ [
+ 700,
+ 384
+ ],
+ [
+ 718,
+ 383
+ ],
+ [
+ 735,
+ 385
+ ],
+ [
+ 752,
+ 388
+ ],
+ [
+ 764,
+ 392
+ ],
+ [
+ 768,
+ 402
+ ],
+ [
+ 768,
+ 420
+ ],
+ [
+ 762,
+ 430
+ ],
+ [
+ 748,
+ 438
+ ],
+ [
+ 730,
+ 443
+ ],
+ [
+ 712,
+ 447
+ ],
+ [
+ 695,
+ 451
+ ],
+ [
+ 682,
+ 451
+ ],
+ [
+ 672,
+ 445
+ ],
+ [
+ 667,
+ 432
+ ],
+ [
+ 665,
+ 418
+ ]
+ ],
+ "roi": [
+ [
+ 648,
+ 400
+ ],
+ [
+ 652,
+ 380
+ ],
+ [
+ 665,
+ 366
+ ],
+ [
+ 690,
+ 356
+ ],
+ [
+ 720,
+ 354
+ ],
+ [
+ 748,
+ 358
+ ],
+ [
+ 763,
+ 366
+ ],
+ [
+ 766,
+ 390
+ ],
+ [
+ 766,
+ 402
+ ],
+ [
+ 764,
+ 428
+ ],
+ [
+ 758,
+ 440
+ ],
+ [
+ 740,
+ 448
+ ],
+ [
+ 715,
+ 454
+ ],
+ [
+ 690,
+ 458
+ ],
+ [
+ 672,
+ 456
+ ],
+ [
+ 658,
+ 442
+ ],
+ [
+ 650,
+ 420
+ ]
+ ],
+ "x0": 665,
+ "x1": 768,
+ "top": [
+ 417.07,
+ 396.78,
+ 392.1,
+ 390.03,
+ 387.96,
+ 386.52,
+ 385.63,
+ 384.73,
+ 383.95,
+ 383.71,
+ 383.46,
+ 383.21,
+ 383.09,
+ 383.61,
+ 384.14,
+ 384.67,
+ 385.29,
+ 386.08,
+ 386.87,
+ 387.66,
+ 388.86,
+ 390.35,
+ 391.84,
+ 410.91
+ ],
+ "bot": [
+ 417.07,
+ 438.44,
+ 446.17,
+ 448.86,
+ 451.0,
+ 451.0,
+ 451.0,
+ 450.68,
+ 449.63,
+ 448.58,
+ 447.52,
+ 446.5,
+ 445.5,
+ 444.51,
+ 443.51,
+ 442.4,
+ 441.15,
+ 439.91,
+ 438.66,
+ 436.81,
+ 434.25,
+ 431.69,
+ 427.46,
+ 410.91
+ ]
+ }
+ ],
+ "mouth": {
+ "cx": 635.5,
+ "cy": 567.5,
+ "angle": -0.30522313379392135,
+ "halfLen": 38.3,
+ "bow": 5.5,
+ "area": {
+ "cx": 636,
+ "cy": 574,
+ "rx": 62,
+ "ry": 34,
+ "angle": -0.24434609527920614
+ }
+ },
+ "cheeks": [
+ [
+ 488,
+ 532
+ ],
+ [
+ 748,
+ 468
+ ]
+ ],
+ "strands": [
+ {
+ "name": "bang1",
+ "nodes": [
+ [
+ 500,
+ 140
+ ],
+ [
+ 470,
+ 240
+ ],
+ [
+ 445,
+ 340
+ ],
+ [
+ 428,
+ 430
+ ]
+ ],
+ "sigma": 18,
+ "k": 1,
+ "max": 8
+ },
+ {
+ "name": "bang2",
+ "nodes": [
+ [
+ 530,
+ 130
+ ],
+ [
+ 505,
+ 240
+ ],
+ [
+ 485,
+ 340
+ ],
+ [
+ 468,
+ 438
+ ]
+ ],
+ "sigma": 18,
+ "k": 0.92,
+ "max": 8
+ },
+ {
+ "name": "bang3",
+ "nodes": [
+ [
+ 555,
+ 125
+ ],
+ [
+ 540,
+ 230
+ ],
+ [
+ 525,
+ 330
+ ],
+ [
+ 510,
+ 432
+ ]
+ ],
+ "sigma": 18,
+ "k": 1.06,
+ "max": 8
+ },
+ {
+ "name": "bang4",
+ "nodes": [
+ [
+ 575,
+ 130
+ ],
+ [
+ 568,
+ 230
+ ],
+ [
+ 558,
+ 330
+ ],
+ [
+ 550,
+ 422
+ ]
+ ],
+ "sigma": 18,
+ "k": 0.95,
+ "max": 8
+ },
+ {
+ "name": "bang5",
+ "nodes": [
+ [
+ 590,
+ 140
+ ],
+ [
+ 590,
+ 230
+ ],
+ [
+ 590,
+ 320
+ ],
+ [
+ 590,
+ 405
+ ]
+ ],
+ "sigma": 18,
+ "k": 1.03,
+ "max": 8
+ },
+ {
+ "name": "bang6",
+ "nodes": [
+ [
+ 600,
+ 160
+ ],
+ [
+ 608,
+ 220
+ ],
+ [
+ 618,
+ 280
+ ],
+ [
+ 628,
+ 335
+ ]
+ ],
+ "sigma": 16,
+ "k": 1.1,
+ "max": 7
+ },
+ {
+ "name": "sideL",
+ "nodes": [
+ [
+ 420,
+ 300
+ ],
+ [
+ 400,
+ 430
+ ],
+ [
+ 398,
+ 560
+ ],
+ [
+ 415,
+ 700
+ ]
+ ],
+ "sigma": 26,
+ "k": 0.55,
+ "max": 12
+ },
+ {
+ "name": "sideR",
+ "nodes": [
+ [
+ 770,
+ 260
+ ],
+ [
+ 782,
+ 380
+ ],
+ [
+ 792,
+ 480
+ ],
+ [
+ 800,
+ 580
+ ]
+ ],
+ "sigma": 22,
+ "k": 0.65,
+ "max": 10
+ }
+ ],
+ "accessories": [
+ {
+ "name": "tassel_l",
+ "pivot": [
+ 292,
+ 419
+ ],
+ "tip": [
+ 289,
+ 598
+ ],
+ "split": 0.4,
+ "box": [
+ 236,
+ 416,
+ 348,
+ 610
+ ],
+ "color": {
+ "redness": 0.5,
+ "minRed": 60
+ }
+ },
+ {
+ "name": "tassel_r",
+ "pivot": [
+ 868,
+ 282
+ ],
+ "tip": [
+ 903,
+ 462
+ ],
+ "split": 0.4,
+ "box": [
+ 856,
+ 279,
+ 952,
+ 474
+ ],
+ "color": {
+ "redness": 0.5,
+ "minRed": 60
+ }
+ }
+ ],
+ "hand": {
+ "outline": [
+ [
+ 472,
+ 609
+ ],
+ [
+ 492,
+ 608
+ ],
+ [
+ 515,
+ 618
+ ],
+ [
+ 535,
+ 633
+ ],
+ [
+ 552,
+ 653
+ ],
+ [
+ 566,
+ 668
+ ],
+ [
+ 575,
+ 690
+ ],
+ [
+ 579,
+ 715
+ ],
+ [
+ 577,
+ 745
+ ],
+ [
+ 575,
+ 772
+ ],
+ [
+ 565,
+ 772
+ ],
+ [
+ 550,
+ 762
+ ],
+ [
+ 546,
+ 790
+ ],
+ [
+ 547,
+ 830
+ ],
+ [
+ 543,
+ 870
+ ],
+ [
+ 536,
+ 920
+ ],
+ [
+ 521,
+ 975
+ ],
+ [
+ 506,
+ 1025
+ ],
+ [
+ 491,
+ 1075
+ ],
+ [
+ 476,
+ 1125
+ ],
+ [
+ 461,
+ 1175
+ ],
+ [
+ 448,
+ 1215
+ ],
+ [
+ 436,
+ 1254
+ ],
+ [
+ 241,
+ 1254
+ ],
+ [
+ 253,
+ 1215
+ ],
+ [
+ 273,
+ 1175
+ ],
+ [
+ 298,
+ 1130
+ ],
+ [
+ 326,
+ 1094
+ ],
+ [
+ 352,
+ 1082
+ ],
+ [
+ 380,
+ 1046
+ ],
+ [
+ 412,
+ 1004
+ ],
+ [
+ 440,
+ 952
+ ],
+ [
+ 462,
+ 904
+ ],
+ [
+ 464,
+ 860
+ ],
+ [
+ 458,
+ 815
+ ],
+ [
+ 445,
+ 780
+ ],
+ [
+ 430,
+ 748
+ ],
+ [
+ 421,
+ 715
+ ],
+ [
+ 426,
+ 690
+ ],
+ [
+ 441,
+ 660
+ ],
+ [
+ 458,
+ 630
+ ]
+ ],
+ "jaw": [
+ [
+ 470,
+ 585.5
+ ],
+ [
+ 476,
+ 585.5
+ ],
+ [
+ 482,
+ 592.5
+ ],
+ [
+ 488,
+ 598.5
+ ],
+ [
+ 502,
+ 610.5
+ ],
+ [
+ 514,
+ 618.5
+ ],
+ [
+ 526,
+ 624.5
+ ],
+ [
+ 538,
+ 628.5
+ ],
+ [
+ 550,
+ 634.5
+ ],
+ [
+ 560,
+ 638.5
+ ],
+ [
+ 566,
+ 640.5
+ ],
+ [
+ 572,
+ 641.5
+ ],
+ [
+ 578,
+ 644
+ ]
+ ],
+ "jawRange": [
+ 470,
+ 600
+ ],
+ "background": [
+ [
+ 440,
+ 560
+ ],
+ [
+ 560,
+ 626
+ ],
+ [
+ 556,
+ 638
+ ],
+ [
+ 552,
+ 665
+ ],
+ [
+ 535,
+ 700
+ ],
+ [
+ 440,
+ 700
+ ]
+ ],
+ "elbow": [
+ 300,
+ 1390
+ ],
+ "wrist": [
+ 505,
+ 850
+ ],
+ "knuckle": [
+ 497,
+ 652
+ ],
+ "contact": [
+ 530,
+ 628
+ ],
+ "forearmShare": 0.3,
+ "armBand": [
+ 1180,
+ 1300
+ ],
+ "wristBand": [
+ 790,
+ 900
+ ],
+ "handBand": [
+ 800,
+ 900
+ ],
+ "fingerXBand": [
+ 482,
+ 540
+ ],
+ "fingerYBand": [
+ 678,
+ 722
+ ],
+ "pinBand": [
+ 1180,
+ 1254
+ ]
+ },
+ "mesh": {
+ "baseCell": 14,
+ "fine": {
+ "x0": 340,
+ "x1": 880,
+ "y0": 60,
+ "y1": 760,
+ "cell": 7
+ },
+ "handCell": 9,
+ "tasselCell": 6,
+ "eyeBallCell": 4,
+ "eyeCell": 3,
+ "spriteCell": 4
+ },
+ "view": {
+ "padTop": -0.07,
+ "padSide": 0,
+ "gazeCenter": [
+ 615,
+ 470
+ ]
+ }
+}
diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.js
new file mode 100644
index 0000000..a8e96a5
--- /dev/null
+++ b/src/engine/createMeshAvatar.js
@@ -0,0 +1,241 @@
+// Mesh avatar engine: turns a pre-split single illustration (see public/avatar/miko-qipao/) into a
+// Live2D-like animated avatar on a WebGL2 canvas. No UI and no framework: the app drives it
+// through the small API returned by createMeshAvatar().
+import { createRig } from './rig.js';
+import { createRenderer } from './renderer.js';
+import { createPhysics } from './physics.js';
+import { createSpriteModule } from './sprites.js';
+import { Motion } from './motion.js';
+import { MOTIONS, IDLE_MOTIONS } from './motions.js';
+
+const EYE_PARTS = ['ball', 'low', 'crease', 'lash']; // back to front
+
+const imageCache = new Map();
+const jsonCache = new Map();
+async function loadJson(src) {
+ if (!jsonCache.has(src)) jsonCache.set(src, fetch(src).then(r => { if (!r.ok) throw new Error(`failed to load ${src}`); return r.json(); }));
+ return jsonCache.get(src);
+}
+function loadImage(src) {
+ if (imageCache.has(src)) return imageCache.get(src);
+ const result = new Promise((res, rej) => {
+ const i = new Image();
+ i.onload = () => res(i);
+ i.onerror = () => rej(new Error(`failed to load ${src}`));
+ i.src = src;
+ });
+ imageCache.set(src, result);
+ return result;
+}
+
+function channelOf(img, ch) {
+ const c = document.createElement('canvas');
+ c.width = img.width; c.height = img.height;
+ const g = c.getContext('2d');
+ g.drawImage(img, 0, 0);
+ const d = g.getImageData(0, 0, c.width, c.height).data;
+ const a = new Uint8Array(c.width * c.height);
+ for (let i = 0; i < a.length; i++) a[i] = d[i * 4 + ch];
+ return a;
+}
+const alphaOf = img => channelOf(img, 3);
+
+// Two-bone skinning along the tassel: top follows segment 1, lower part segment 2.
+function deformTassel(ch, mesh) {
+ const [px, py] = ch.t.pivot, d = ch.dir, P = ch.pts;
+ const sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+ const c1 = Math.cos(ch.phi[0]), s1 = Math.sin(ch.phi[0]);
+ const c2 = Math.cos(ch.phi[1]), s2 = Math.sin(ch.phi[1]);
+ const r = mesh.rest, o = mesh.pos;
+ for (let i = 0; i < r.length; i += 2) {
+ const vx = r[i] - px, vy = r[i + 1] - py;
+ const along = vx * d[0] + vy * d[1];
+ const ax = P[0][0] + vx * c1 - vy * s1, ay = P[0][1] + vx * s1 + vy * c1;
+ const ux = vx - d[0] * ch.L1, uy = vy - d[1] * ch.L1;
+ const bx = P[1][0] + ux * c2 - uy * s2, by = P[1][1] + ux * s2 + uy * c2;
+ const w = sstep(ch.L1 * 0.55, ch.L1 * 1.35, along);
+ o[i] = ax + (bx - ax) * w; o[i + 1] = ay + (by - ay) * w;
+ }
+}
+
+/** @param {HTMLCanvasElement} canvas
+ * @param {import('./index').MeshAvatarOptions} options */
+export async function createMeshAvatarImpl(canvas, options) {
+ const rig = options.rig;
+ const engine = createRig(rig);
+ const { IMG, EYES, baseWeights, deformBase, eyePartY, eyePartAlpha,
+ handWeights, handFrame, deformHand, TASSELS } = engine;
+ const { Renderer, buildGrid } = createRenderer(engine, rig);
+ const { Physics } = createPhysics(engine, rig);
+ const { createSprites } = createSpriteModule(engine, rig);
+ const base = (options.assetsBase ?? '/miko-qipao/built/').replace(/\/?$/, '/');
+ const asset = (name, build) => {
+ if (options.assets) {
+ if (!options.assets[name]) throw new Error(`Missing project asset: ${name}`);
+ return options.assets[name];
+ }
+ return `${base}${name}${build === undefined ? '' : `?b=${build}`}`;
+ };
+ const meta = await loadJson(asset('layers.json'));
+
+ const names = ['base', ...(rig.hand ? ['hand'] : []), ...TASSELS.map(t => t.name), ...[0, 1].flatMap(i => EYE_PARTS.map(p => `eye${i}_${p}`)), 'hairmask'];
+ const imgs = Object.fromEntries(await Promise.all(names.map(async n => [n, await loadImage(asset(`${n}.png`, meta.build))])));
+ const hairMask = channelOf(imgs.hairmask, 0);
+ const hairAt = (x, y) => hairMask[Math.min(IMG.h - 1, Math.max(0, Math.round(y))) * IMG.w + Math.min(IMG.w - 1, Math.max(0, Math.round(x)))] / 255;
+
+ // The source image is cut flat at its top edge (crown and right bun). A negative top margin
+ // keeps the top ~88px (7%) above the canvas, which the layout puts at the top of the panel:
+ // the cut stays off screen even at the deepest head tilt.
+ const R = new Renderer(canvas, { padTop: options.padTop ?? rig.view.padTop, padSide: options.padSide ?? rig.view.padSide });
+ const rects = { base: [0, 0, IMG.w, IMG.h], ...meta.layers };
+
+ // base layer, denser where hair strands bend and the face parts shift
+ const baseMesh = buildGrid(rects.base, rig.mesh.baseCell, alphaOf(imgs.base), imgs.base.width, rig.mesh.fine);
+ const baseW = [];
+ for (let i = 0; i < baseMesh.rest.length / 2; i++) {
+ const x = baseMesh.rest[i * 2], y = baseMesh.rest[i * 2 + 1];
+ baseW.push(baseWeights(x, y, hairAt(x, y)));
+ }
+ R.addLayer('base', imgs.base, baseMesh, { face: true });
+
+ // eyes: white+iris clipped by the lids, then the line layers on top
+ const eyeParts = [];
+ EYES.forEach((e, i) => {
+ for (const part of EYE_PARTS) {
+ const n = `eye${i}_${part}`;
+ const mesh = buildGrid(rects[n], part === 'ball' ? rig.mesh.eyeBallCell : rig.mesh.eyeCell, alphaOf(imgs[n]), imgs[n].width);
+ const W = [];
+ for (let k = 0; k < mesh.rest.length / 2; k++) W.push(baseWeights(mesh.rest[k * 2], mesh.rest[k * 2 + 1], 0));
+ const layer = R.addLayer(n, imgs[n], mesh, { eyeBall: part === 'ball' ? i : undefined });
+ eyeParts.push({ e, eye: i, part, mesh, W, layer });
+ }
+ });
+
+ // drawn eye / mouth variants (closed / half / smiling eyes, a/i/u/e/o mouths) over the face
+ let sprites = null;
+ try {
+ {
+ const sheet = await loadJson(asset('sprites/sprites.json'));
+ const simgs = Object.fromEntries(await Promise.all(Object.keys(sheet.layers).map(async n =>
+ [n, await loadImage(asset(`sprites/${n}.png`, sheet.build))])));
+ sprites = createSprites(R, sheet, simgs, buildGrid, alphaOf);
+ }
+ } catch (err) {
+ console.warn('eye / mouth sprites not loaded:', err);
+ }
+
+ const tassels = TASSELS.map(t => {
+ const mesh = buildGrid(rects[t.name], rig.mesh.tasselCell, alphaOf(imgs[t.name]), imgs[t.name].width);
+ return R.addLayer(t.name, imgs[t.name], mesh);
+ });
+
+ const handMesh = rig.hand ? buildGrid(rects.hand, rig.mesh.handCell, alphaOf(imgs.hand), imgs.hand.width) : { rest: [], pos: [] };
+ const handW = [];
+ for (let i = 0; i < handMesh.rest.length / 2; i++) handW.push(handWeights(handMesh.rest[i * 2], handMesh.rest[i * 2 + 1]));
+ 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 listeners = new Set();
+ motion.onMotion = id => { for (const fn of listeners) fn(id); };
+
+ let parameters = {};
+ const tmp = [0, 0];
+ function tick(dt) {
+ const P = { ...motion.update(dt), ...parameters };
+ const phys = physics.step(P, dt);
+
+ const bp = baseMesh.pos, br = baseMesh.rest;
+ for (let i = 0; i < baseW.length; i++) {
+ deformBase(br[i * 2], br[i * 2 + 1], baseW[i], P, phys, tmp);
+ bp[i * 2] = tmp[0]; bp[i * 2 + 1] = tmp[1];
+ }
+ // with drawn eye sprites the layered eye is only ever shown exactly as drawn: moving the
+ // cut-out lash leaves seams at its edges
+ const eyeOpenFor = v => (sprites ? 1 : v);
+ for (const ep of eyeParts) {
+ const open = eyeOpenFor(ep.eye === 0 ? P.ParamEyeROpen : P.ParamEyeLOpen);
+ const smile = ep.eye === 0 ? P.ParamEyeSmile : (P.eyeSmileL ?? P.ParamEyeSmile);
+ ep.layer.alpha = eyePartAlpha(ep.part, open, smile);
+ const r = ep.mesh.rest, o = ep.mesh.pos;
+ for (let k = 0; k < ep.W.length; k++) {
+ const x = r[k * 2], y = r[k * 2 + 1];
+ deformBase(x, eyePartY(ep.e, ep.part, x, y, open, smile), ep.W[k], P, phys, tmp);
+ o[k * 2] = tmp[0]; o[k * 2 + 1] = tmp[1];
+ }
+ }
+ const cover = sprites?.update(P, phys, dt);
+ if (cover) for (const ep of eyeParts) if (cover.eyes[ep.eye]) ep.layer.alpha = 0;
+ const hp = handMesh.pos, hr = handMesh.rest, HF = handFrame(P);
+ for (let i = 0; i < handW.length; i++) {
+ deformHand(hr[i * 2], hr[i * 2 + 1], handW[i], P, HF, tmp);
+ hp[i * 2] = tmp[0]; hp[i * 2 + 1] = tmp[1];
+ }
+ physics.chains.forEach((ch, k) => deformTassel(ch, tassels[k].mesh));
+
+ const ball = 7; // px of iris travel
+ R.draw({
+ eyes: [
+ eyeOpenFor(P.ParamEyeROpen), P.ParamEyeSmile, P.ParamEyeBallX * ball, -P.ParamEyeBallY * ball * 0.6,
+ eyeOpenFor(P.ParamEyeLOpen), P.eyeSmileL ?? P.ParamEyeSmile, P.ParamEyeBallX * ball * 0.85, -P.ParamEyeBallY * ball * 0.6,
+ ],
+ // with sprites the drawn mouths replace the shader-painted one
+ mouthOpen: sprites ? 0 : P.ParamMouthOpenY, mouthForm: P.ParamMouthForm, cheek: P.ParamCheek,
+ showMesh: false, originalAlpha: 0, joints: [],
+ });
+ }
+
+ // `manual: true` runs no animation loop: the caller advances time with advance()
+ // (offline video rendering, one call per frame)
+ let raf = 0, last = performance.now(), destroyed = false;
+ const frame = now => {
+ const dt = Math.min(0.05, (now - last) / 1000);
+ last = now;
+ tick(dt);
+ raf = requestAnimationFrame(frame);
+ };
+ if (!options.manual) raf = requestAnimationFrame(frame);
+
+ const motionList = [
+ ...Object.entries(MOTIONS).map(([id, m]) => ({ id, label: m.label, idle: false })),
+ ...Object.entries(IDLE_MOTIONS).map(([id, m]) => ({ id, label: m.label, idle: true })),
+ ];
+
+ return {
+ motions: motionList,
+ setParameters(values) { parameters = { ...values }; },
+ /** 0..1 loudness of the voice being played (e.g. normalised RMS). */
+ setVoiceLevel(v) { motion.setVoiceLevel(v); },
+ /** true while TTS audio is playing: idle motions pause and the head nods along. */
+ setSpeaking(on) { motion.setSpeaking(on); },
+ /** AITuber OnAir emotion tag: happy / sad / angry / surprised / relaxed / neutral (or null). */
+ setEmotion(tag, opts) { motion.setEmotion(tag, opts); },
+ /** How much the head moves with the voice while speaking (1 = default, calmer below). */
+ setTalkGain(g) { motion.talkGain = Math.max(0, Number(g) || 0); },
+ /** Play a motion or idle motion by id (see `motions`). */
+ play(id) { if (motion.hasMotion(id)) motion.playMotion(id); },
+ /** Move the mouth through the vowels of kana text (no audio; for previews). */
+ speakKana(text) { motion.speakKana(String(text ?? '')); },
+ setAutoIdle(on) { motion.autoIdle = !!on; },
+ setAutoMotion(on) { motion.autoMotion = !!on; },
+ /** Hair / tassel sway multiplier (1 = default). */
+ setSwayGain(g) { physics.gain = g; },
+ /** Called with the motion id when a motion starts and with null when it ends. */
+ onMotion(fn) { listeners.add(fn); return () => listeners.delete(fn); },
+ /** Advance the simulation by `sec` and draw (for tests / hidden tabs). */
+ advance(sec, fps = 60) {
+ if (destroyed) return;
+ if (sec === 0) tick(0);
+ else for (let i = 0; i < Math.round(sec * fps); i++) tick(1 / fps);
+ },
+ destroy() {
+ if (destroyed) return;
+ destroyed = true;
+ cancelAnimationFrame(raf);
+ listeners.clear();
+ R.destroy();
+ // the GL context is not lost on purpose: the canvas may already be reused by a new
+ // instance (React StrictMode mounts twice) and a canvas only ever has one context
+ },
+ };
+}
diff --git a/src/engine/index.ts b/src/engine/index.ts
new file mode 100644
index 0000000..918ef41
--- /dev/null
+++ b/src/engine/index.ts
@@ -0,0 +1,35 @@
+import type { Rig } from '../rig/types';
+import { parseRig } from '../rig/validate';
+import { createMeshAvatarImpl } from './createMeshAvatar.js';
+
+export interface MeshAvatarOptions {
+ rig: Rig;
+ assetsBase?: string;
+ assets?: Record<string, string>;
+ manual?: boolean;
+ padTop?: number;
+ padSide?: number;
+}
+export interface MeshAvatar {
+ readonly motions: { id: string; label: string; idle: boolean }[];
+ setParameters(parameters: Record<string, number>): void;
+ setVoiceLevel(value: number): void;
+ setSpeaking(on: boolean): void;
+ setEmotion(tag: string | null, options?: { playMotion?: boolean }): void;
+ setTalkGain(gain: number): void;
+ play(id: string): void;
+ speakKana(text: string): void;
+ setAutoIdle(on: boolean): void;
+ setAutoMotion(on: boolean): void;
+ setSwayGain(gain: number): void;
+ onMotion(listener: (id: string | null) => void): () => void;
+ advance(seconds: number, fps?: number): void;
+ destroy(): void;
+}
+
+export async function createMeshAvatar(
+ canvas: HTMLCanvasElement,
+ options: MeshAvatarOptions,
+): Promise<MeshAvatar> {
+ return createMeshAvatarImpl(canvas, { ...options, rig: parseRig(options.rig) });
+}
diff --git a/src/engine/kana.js b/src/engine/kana.js
new file mode 100644
index 0000000..aefa452
--- /dev/null
+++ b/src/engine/kana.js
@@ -0,0 +1,62 @@
+// Japanese text -> timed mouth shapes, for previewing lip sync without audio.
+// Only kana are read; other characters are skipped, punctuation makes a short pause.
+
+// open: how far the mouth opens, form: -1 wide (い) .. 0 (あ) .. +1 round (う)
+export const VOWELS = {
+ a: { open: 0.9, form: 0, label: 'あ' },
+ i: { open: 0.5, form: -0.85, label: 'い' },
+ u: { open: 0.4, form: 0.9, label: 'う' },
+ e: { open: 0.62, form: -0.4, label: 'え' },
+ o: { open: 0.75, form: 0.6, label: 'お' },
+ n: { open: 0, form: null, label: 'ん' }, // closes with the previous shape
+};
+
+const ROWS = {
+ a: 'あかさたなはまやらわがざだばぱぁ',
+ i: 'いきしちにひみりぎじぢびぴぃ',
+ u: 'うくすつぬふむゆるぐずづぶぷぅゔ',
+ e: 'えけせてねへめれげぜでべぺぇ',
+ o: 'おこそとのほもよろをごぞどぼぽぉ',
+};
+const VOWEL_OF = {};
+for (const [v, chars] of Object.entries(ROWS)) for (const c of chars) VOWEL_OF[c] = v;
+const LIPS_CLOSE = new Set([...'まみむめもばびぶべぼぱぴぷぺぽ']); // m / b / p close the lips first
+const PLAIN_VOWEL = new Set([...'あいうえおぁぃぅぇぉ']);
+const SMALL_Y = { ゃ: 'a', ゅ: 'u', ょ: 'o' };
+const PAUSE = new Set([...'、。,.,.!?!?  …']);
+
+const toHiragana = s => s.replace(/[ァ-ヶ]/g, c => String.fromCharCode(c.charCodeAt(0) - 0x60));
+
+/** -> [{ vowel, dur, onset }] where onset is 'lips' | 'consonant' | null */
+export function kanaToMoras(text, mora = 0.14) {
+ const out = [];
+ for (const c of toHiragana(text)) {
+ const last = out[out.length - 1];
+ if (SMALL_Y[c] && last) { last.vowel = SMALL_Y[c]; continue; }
+ if (c === 'ー' && last) { last.dur += mora; continue; }
+ if (c === 'っ') { out.push({ vowel: 'n', dur: mora * 0.8, onset: null }); continue; }
+ if (c === 'ん') { out.push({ vowel: 'n', dur: mora, onset: null }); continue; }
+ if (PAUSE.has(c)) { out.push({ vowel: 'n', dur: mora * 2.2, onset: null }); continue; }
+ const v = VOWEL_OF[c];
+ if (!v) continue;
+ out.push({ vowel: v, dur: mora, onset: LIPS_CLOSE.has(c) ? 'lips' : PLAIN_VOWEL.has(c) ? null : 'consonant' });
+ }
+ return out;
+}
+
+/** Mouth target at time t (s) of a mora timeline, or null when it is over. */
+export function sampleMoras(moras, t) {
+ let start = 0;
+ for (const m of moras) {
+ if (t < start + m.dur) {
+ const x = (t - start) / m.dur;
+ const v = VOWELS[m.vowel];
+ // consonants: the mouth is nearly shut (lips) or half shut at the start of the mora
+ const onset = m.onset === 'lips' ? 0.05 : m.onset === 'consonant' ? 0.45 : 1;
+ const k = x < 0.35 ? onset + (1 - onset) * (x / 0.35) : 1;
+ return { open: v.open * k, form: v.form, vowel: m.vowel };
+ }
+ start += m.dur;
+ }
+ return null;
+}
diff --git a/src/engine/motion.js b/src/engine/motion.js
new file mode 100644
index 0000000..0f3f005
--- /dev/null
+++ b/src/engine/motion.js
@@ -0,0 +1,362 @@
+// Drives parameters: idle ("auto idle"), mouse follow, blinking, expressions, motions.
+import { PARAMS } from './rig.js';
+import { MOTIONS, IDLE_MOTIONS, ADDITIVE, sampleTrack } from './motions.js';
+import { VOWELS, kanaToMoras, sampleMoras } from './kana.js';
+
+const ALL_MOTIONS = { ...MOTIONS, ...IDLE_MOTIONS };
+// scales the head / body / arm tracks of idle motions (they are authored at full size, so 1)
+// (gaze, eyes and brows are left alone)
+export const IDLE_GAIN = { amp: 1, stiff: 1.8 };
+const IDLE_SCALED = /^Param(Angle|BodyAngle|ArmAngle|HandAngle)/;
+
+// motion tracks that replace the expression (the rest are additive or body targets)
+const FACE_TRACKS = new Set(['eyeOpen', 'eyeOpenL', 'eyeSmileL', 'ParamEyeSmile', 'ParamMouthOpenY',
+ 'ParamMouthForm', 'ParamCheek', 'ParamBrowY', 'ParamBrowAngle']);
+const sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+
+// smooth 1D value noise
+function noise(t, seed) {
+ const i = Math.floor(t), f = t - i;
+ const h = n => { const x = Math.sin((n + seed * 57.3) * 127.1) * 43758.5453; return x - Math.floor(x); };
+ const u = f * f * (3 - 2 * f);
+ return (h(i) * (1 - u) + h(i + 1) * u) * 2 - 1;
+}
+const fbm = (t, s) => noise(t, s) * 0.7 + noise(t * 2.3, s + 9) * 0.3;
+const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
+
+export const EXPRESSIONS = {
+ normal: { label: 'Neutral', p: {} },
+ smile: { label: 'Smile', p: { eyeOpen: 0, ParamEyeSmile: 1, ParamCheek: 0.35, ParamBrowY: 0.2 } },
+ shy: { label: 'Blush', p: { eyeOpen: 0.78, ParamEyeSmile: 0.5, ParamCheek: 1, ParamBrowAngle: -0.5, ParamBrowY: -0.1, glance: [0.7, 0.35] } },
+ jito: { label: 'Half-lidded', p: { eyeOpen: 0.5, ParamBrowY: -0.5, ParamBrowAngle: 0.6 } },
+ surprise: { label: 'Surprise', p: { eyeOpen: 1.22, ParamBrowY: 1, ParamMouthOpenY: 0.6, ParamMouthForm: 0.6 } },
+ wink: { label: 'Wink', p: { eyeOpenL: 0, eyeSmileL: 1, ParamCheek: 0.3 } },
+ // talking faces for AITuber OnAir emotion tags: eyes stay mostly open (closed / ^^ eyes are
+ // what a single image fakes worst, and they would stay shut for a whole sentence)
+ happyTalk: { label: 'happy', p: { eyeOpen: 0.8, ParamEyeSmile: 0.45, ParamCheek: 0.35, ParamBrowY: 0.25, ParamMouthForm: -0.5 } },
+ sadTalk: { label: 'sad', p: { eyeOpen: 0.78, ParamBrowAngle: -0.8, ParamBrowY: -0.2, ParamMouthForm: 0.3, glance: [0, -0.35] } },
+ angryTalk: { label: 'angry', p: { eyeOpen: 0.72, ParamBrowAngle: 0.85, ParamBrowY: -0.55, ParamMouthForm: 0.2 } },
+ surprisedTalk: { label: 'surprised', p: { eyeOpen: 1.18, ParamBrowY: 0.9, ParamMouthForm: 0.9 } },
+ relaxedTalk: { label: 'relaxed', p: { eyeOpen: 0.82, ParamEyeSmile: 0.35, ParamCheek: 0.15, ParamBrowY: 0.1 } },
+};
+
+// emotion tag -> [expression, motion played when the line starts]
+const EMOTIONS = {
+ happy: ['happyTalk', 'nod'],
+ sad: ['sadTalk', 'sigh'],
+ angry: ['angryTalk', 'no'],
+ surprised: ['surprisedTalk', 'surprise'],
+ relaxed: ['relaxedTalk', 'sway'],
+ neutral: ['normal', null],
+};
+
+// [stiffness, damping ratio] of the parameter smoothing; unlisted params use [120, 0.95]
+const SPRINGS = {
+ ParamEyeBallX: [260, 0.9], ParamEyeBallY: [260, 0.9],
+ ParamAngleX: [55, 0.72], ParamAngleY: [55, 0.72], ParamAngleZ: [45, 0.75],
+ ParamBodyAngleX: [14, 0.9], ParamBodyAngleZ: [12, 0.9],
+ ParamArmAngle: [20, 0.85], ParamHandAngle: [30, 0.8],
+};
+
+export class Motion {
+ /** @param {number[]} gazeCenter */
+ constructor(gazeCenter) {
+ this.mode = 'auto'; // auto | mouse | manual
+ this.P = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+ this.manual = { ...this.P };
+ this.cur = { ...this.P }; // smoothed values
+ this.vel = Object.fromEntries(PARAMS.map(p => [p.id, 0]));
+ this.expr = 'normal';
+ this.exprMix = {}; // smoothed expression values
+ this.t = 0;
+ this.blink = { t: 0, start: 1.5, double: false };
+ this.gaze = { x: 0, y: 0, next: 0 };
+ this.tap = { next: 4, until: -1 };
+ this.pointer = null; // image px
+ this.faceCenter = [...gazeCenter];
+ this.lipOpen = null; // external mouth value from lip sync
+ this.lipForm = 0;
+ this.speaking = false; // TTS audio playing (setSpeaking)
+ this.voice = 0; // 0..1 loudness (setVoiceLevel)
+ this.mouth = 0;
+ this.vowel = 'a';
+ this.vowelForm = 0;
+ this.syllableArmed = true;
+ this.voicePeak = 0;
+ this.voiceTrough = 0;
+ this.kana = null;
+ this.emotionUntil = 0; // when the emotion face goes back to normal
+ this.talkGain = 1; // how much the head moves along with the voice
+ this.play = null; // { id, t } of the motion being played
+ this.autoMotion = true; // "auto idle" plays a reaction motion now and then
+ this.nextAuto = 14;
+ this.autoIdle = true; // ...and small idle motions more often
+ this.nextIdle = 3;
+ this.lastAuto = null;
+ this.onMotion = null; // UI callback (id or null)
+ }
+
+ setExpression(k) { this.expr = k; }
+
+ hasMotion(id) { return id in ALL_MOTIONS; }
+
+ // ---- speech (driven from outside, e.g. by the TTS audio analyser) ----
+ setVoiceLevel(v) { this.voice = Math.min(1, Math.max(0, Number(v) || 0)); }
+
+ setSpeaking(on) {
+ if (on === this.speaking) return;
+ this.speaking = !!on;
+ if (!on) {
+ // hold the emotion a moment after the line, then go back to the plain face
+ this.emotionUntil = this.t + 1.2;
+ this.voice = 0;
+ }
+ }
+
+ /** `playMotion: false` changes only the face (a caller that picks motions itself). */
+ setEmotion(tag, { playMotion = true } = {}) {
+ const e = EMOTIONS[tag] ?? EMOTIONS.neutral;
+ this.expr = e[0];
+ this.emotionUntil = Infinity;
+ if (e[1] && playMotion) this.playMotion(e[1]);
+ }
+
+ /** Mouth shapes from kana text, without audio (preview / tuning). */
+ speakKana(text) {
+ this.kana = { moras: kanaToMoras(text), t: 0 };
+ }
+
+ // Mouth from the TTS loudness. A volume signal has no vowel information, so each syllable
+ // (the voice dipping and rising again) gets one vowel at random, weighted towards a, and
+ // keeps it until the next syllable: the drawn mouths must not change shape mid-syllable.
+ // Syllables are found relative to the recent peak (not an absolute level), and the mouth
+ // is scaled by where the voice sits between the recent trough and peak, so it closes in
+ // the dip before each mora even when a loud voice never gets quiet.
+ speechMouth(dt) {
+ if (this.kana) {
+ this.kana.t += dt;
+ const m = sampleMoras(this.kana.moras, this.kana.t);
+ if (!m) { this.kana = null; return this.mouth > 0.01 ? [this.mouth *= 0.6, this.vowelForm] : null; }
+ const k = m.open > this.mouth ? 1 - Math.exp(-dt * 30) : 1 - Math.exp(-dt * 22);
+ this.mouth += (m.open - this.mouth) * k;
+ if (m.form !== null) this.vowelForm = m.form;
+ return [this.mouth, this.vowelForm];
+ }
+ const v = this.speaking ? this.voice : 0;
+ // recent peak / trough: follow at once, then relax over ~0.2 s
+ const relax = 1 - Math.exp(-dt * 5);
+ this.voicePeak = v > this.voicePeak ? v : this.voicePeak + (v - this.voicePeak) * relax;
+ this.voiceTrough = v < this.voiceTrough ? v : this.voiceTrough + (v - this.voiceTrough) * relax;
+ const peak = Math.max(this.voicePeak, 0.05);
+ if (v < peak * 0.6) this.syllableArmed = true;
+ else if (this.syllableArmed && v > peak * 0.8 && v > 0.1) {
+ this.syllableArmed = false;
+ const r = Math.random();
+ this.vowel = r < 0.4 ? 'a' : r < 0.58 ? 'o' : r < 0.74 ? 'e' : r < 0.88 ? 'i' : 'u';
+ }
+ const range = this.voicePeak - this.voiceTrough;
+ const rise = range < peak * 0.3 ? 1 : Math.max(0, (v - this.voiceTrough) / range);
+ const shape = VOWELS[this.vowel ?? 'a'];
+ const level = Math.min(1, Math.pow(v, 0.7) * 1.15) * Math.pow(rise, 0.3);
+ const target = this.speaking ? Math.min(0.95, level) * (0.45 + 0.55 * shape.open / 0.9) : 0;
+ // quick attack, quick release: the mouth has to shut between morae (~7 per second)
+ const k = target > this.mouth ? 1 - Math.exp(-dt * 40) : 1 - Math.exp(-dt * 32);
+ this.mouth += (target - this.mouth) * k;
+ if (this.speaking) this.vowelForm = shape.form; // after the line: close in the last shape
+ return this.speaking || this.mouth > 0.01 ? [this.mouth, this.vowelForm] : null;
+ }
+
+ // Breathing: inhale ~40% of the cycle, a slower exhale, a short pause at the bottom,
+ // and a period that drifts between ~3.2 and 4.6 s so it never looks metronomic.
+ breathValue(dt) {
+ this.breathPhase = (this.breathPhase ?? 0) + dt / (this.breathPeriod ?? 3.8);
+ if (this.breathPhase >= 1) { this.breathPhase -= 1; this.breathPeriod = 3.2 + Math.random() * 1.4; }
+ const x = this.breathPhase;
+ if (x < 0.4) return sstep(0, 0.4, x);
+ if (x < 0.88) return 1 - sstep(0.4, 0.88, x);
+ return 0;
+ }
+
+ // pick one at random, never the one that just played
+ playRandom(ids) {
+ const pool = ids.filter(k => k !== this.lastAuto);
+ this.playMotion(pool[Math.floor(Math.random() * pool.length)]);
+ }
+
+ playMotion(id) {
+ this.lastAuto = id;
+ this.play = { id, t: 0 };
+ this.onMotion?.(id);
+ }
+
+ blinkValue(dt) {
+ const b = this.blink;
+ b.t += dt;
+ if (b.t < b.start) return 1;
+ const x = (b.t - b.start) / 0.17;
+ if (x >= 1) {
+ if (b.double) { b.double = false; b.start = b.t + 0.07; }
+ else { b.start = b.t + 1.8 + Math.random() * 4.2; b.double = Math.random() < 0.18; }
+ return 1;
+ }
+ return x < 0.45 ? 1 - x / 0.45 : (x - 0.45) / 0.55;
+ }
+
+ update(dt) {
+ this.t += dt;
+ const t = this.t;
+ const T = {}; // targets
+ for (const p of PARAMS) T[p.id] = p.def;
+
+ if (this.mode === 'manual') {
+ Object.assign(T, this.manual);
+ } else if (this.mode === 'auto') {
+ // wandering plus following the gaze: the eyes jump first, the head turns after them
+ T.ParamAngleX = fbm(t * 0.18, 1) * 10 + this.gaze.x * 11;
+ T.ParamAngleY = fbm(t * 0.15, 2) * 6 - 1 + this.gaze.y * 7;
+ T.ParamAngleZ = fbm(t * 0.12, 3) * 10;
+ T.ParamBodyAngleX = fbm(t * 0.1, 4) * 5;
+ T.ParamBodyAngleZ = fbm(t * 0.09, 5) * 4;
+ T.ParamArmAngle = fbm(t * 0.14, 6) * 5;
+ T.ParamHandAngle = fbm(t * 0.21, 7) * 5;
+ // glances
+ if (t > this.gaze.next) {
+ const r = Math.random();
+ this.gaze.x = r < 0.45 ? 0 : (Math.random() * 2 - 1) * 0.8;
+ this.gaze.y = r < 0.45 ? 0 : (Math.random() * 2 - 1) * 0.5;
+ this.gaze.next = t + 0.8 + Math.random() * 2.5;
+ }
+ T.ParamEyeBallX = this.gaze.x + T.ParamAngleX / 60;
+ T.ParamEyeBallY = this.gaze.y + T.ParamAngleY / 60;
+ // occasional finger tapping on the chin
+ if (t > this.tap.next) { this.tap.until = t + 1.1; this.tap.next = t + 5 + Math.random() * 6; }
+ // random playback: reactions every ~15-25 s, small idle motions every few seconds in between
+ // while talking: no random motions, just nod along with the voice
+ if (this.speaking) {
+ this.nextIdle = Math.max(this.nextIdle, t + 2.5);
+ this.nextAuto = Math.max(this.nextAuto, t + 6);
+ const g = this.talkGain;
+ this.talkNod = (this.talkNod ?? 0) + (this.voice * 7 * g - (this.talkNod ?? 0)) * Math.min(1, dt * 6);
+ T.ParamAngleY -= this.talkNod;
+ T.ParamAngleX += fbm(t * 0.6, 11) * 5 * g;
+ T.ParamAngleZ += fbm(t * 0.5, 12) * 4 * g;
+ }
+ if (!this.speaking && t > this.emotionUntil) { this.expr = 'normal'; this.emotionUntil = Infinity; }
+ if (this.speaking) { /* no random playback */ }
+ else if (!this.play && this.autoMotion && t > this.nextAuto) {
+ this.playRandom(Object.keys(MOTIONS).filter(k => k !== 'surprise'));
+ this.nextAuto = t + 15 + Math.random() * 10;
+ this.nextIdle = Math.max(this.nextIdle, t + 5);
+ } else if (!this.play && this.autoIdle && t > this.nextIdle) {
+ this.playRandom(Object.keys(IDLE_MOTIONS));
+ this.nextIdle = t + 5 + Math.random() * 5; // counted from the start, so 1-5 s of plain idling after it
+ }
+ } else if (this.mode === 'mouse' && this.pointer) {
+ const dx = (this.pointer[0] - this.faceCenter[0]) / 500, dy = (this.pointer[1] - this.faceCenter[1]) / 500;
+ T.ParamAngleX = clamp(dx * 30, -30, 30);
+ T.ParamAngleY = clamp(-dy * 30, -30, 30);
+ T.ParamAngleZ = clamp(-dx * dy * 25, -12, 12);
+ T.ParamBodyAngleX = clamp(dx * 10, -10, 10) * 0.6;
+ T.ParamEyeBallX = clamp(dx * 1.4, -1, 1);
+ T.ParamEyeBallY = clamp(-dy * 1.4, -1, 1);
+ T.ParamHandAngle = clamp(dx * 4, -5, 5);
+ }
+ if (this.mode !== 'manual') {
+ T.ParamBreath = this.breathValue(dt);
+ if (t < this.tap.until) T.ParamFingerTap = Math.max(0, Math.sin((this.tap.until - t) * Math.PI * 3.6)) ** 2;
+ }
+
+ // motion: body/head tracks go into the targets, so the springs smooth them too
+ let M = null, mw = 0;
+ if (this.play) {
+ const def = ALL_MOTIONS[this.play.id];
+ this.play.t += dt;
+ if (this.play.t >= def.dur) { this.play = null; this.onMotion?.(null); }
+ else {
+ M = {};
+ for (const [id, keys] of Object.entries(def.tracks))
+ M[id] = sampleTrack(keys, this.play.t) * (def.idle && IDLE_SCALED.test(id) ? IDLE_GAIN.amp : 1);
+ mw = sstep(0, 0.15, this.play.t) * (1 - sstep(def.dur - 0.25, def.dur, this.play.t));
+ for (const [id, v] of Object.entries(M)) {
+ if (ADDITIVE.has(id)) T[id] += v;
+ else if (id === 'ParamBreath') T[id] += (v - T[id]) * mw; // a motion sets its own breathing
+ else if (!FACE_TRACKS.has(id)) T[id] = Math.max(T[id], Math.max(0, v));
+ }
+ }
+ }
+
+ if (this.mode !== 'manual') T.ParamAngleY += T.ParamBreath * 1.6;
+
+ // expression layer (smoothed so switching is not a jump)
+ const E = EXPRESSIONS[this.expr].p;
+ const keys = ['eyeOpen', 'eyeOpenL', 'eyeSmileL', 'ParamEyeSmile', 'ParamMouthOpenY', 'ParamMouthForm', 'ParamCheek', 'ParamBrowY', 'ParamBrowAngle', 'gx', 'gy'];
+ const target = { eyeOpen: E.eyeOpen ?? 1, eyeOpenL: E.eyeOpenL ?? E.eyeOpen ?? 1, eyeSmileL: E.eyeSmileL ?? E.ParamEyeSmile ?? 0,
+ ParamEyeSmile: E.ParamEyeSmile ?? 0, ParamMouthOpenY: E.ParamMouthOpenY ?? 0, ParamMouthForm: E.ParamMouthForm ?? 0,
+ ParamCheek: E.ParamCheek ?? 0, ParamBrowY: E.ParamBrowY ?? 0, ParamBrowAngle: E.ParamBrowAngle ?? 0,
+ gx: E.glance?.[0] ?? 0, gy: E.glance?.[1] ?? 0 };
+ const k = 1 - Math.exp(-dt * 9);
+ for (const key of keys) {
+ if (this.exprMix[key] === undefined) this.exprMix[key] = target[key];
+ this.exprMix[key] += (target[key] - this.exprMix[key]) * k;
+ }
+ const X = this.exprMix;
+
+ // spring-damper towards the targets for body params
+ const out = {};
+ for (const p of PARAMS) {
+ const id = p.id;
+ if (this.mode === 'manual' && !M) { out[id] = T[id]; this.cur[id] = T[id]; this.vel[id] = 0; continue; }
+ // eyes lead, the head follows with a slight overshoot, the body trails behind
+ let [stiff, zeta] = SPRINGS[id] ?? [120, 0.95];
+ // keyframed motions are already smooth; follow them more tightly than idle wandering
+ // keyframed motions are followed more tightly than the idle wandering; idle motions a
+ // bit less so they stay soft but still reach their poses
+ if (M && /^ParamAngle|^ParamBody/.test(id)) {
+ if (ALL_MOTIONS[this.play?.id ?? '']?.idle) { stiff *= IDLE_GAIN.stiff; zeta = 0.8; }
+ else if (/^ParamAngle/.test(id)) { stiff *= 4.5; zeta = 0.75; }
+ }
+ const damp = 2 * Math.sqrt(stiff) * zeta;
+ this.vel[id] += (stiff * (T[id] - this.cur[id]) - damp * this.vel[id]) * dt;
+ this.cur[id] += this.vel[id] * dt;
+ out[id] = this.cur[id];
+ }
+ let blink = 1;
+ if (this.mode !== 'manual') {
+ blink = this.blinkValue(dt);
+ out.ParamEyeROpen = X.eyeOpen * blink;
+ out.ParamEyeLOpen = X.eyeOpenL * blink;
+ out.ParamEyeSmile = X.ParamEyeSmile;
+ out.eyeSmileL = X.eyeSmileL;
+ out.ParamMouthOpenY = X.ParamMouthOpenY;
+ out.ParamMouthForm = X.ParamMouthForm;
+ out.ParamCheek = X.ParamCheek;
+ // brows dip a little with each blink and lift when looking up
+ out.ParamBrowY = X.ParamBrowY + (out.ParamAngleY > 0 ? out.ParamAngleY / 60 : 0) - (1 - blink) * 0.18;
+ out.ParamBrowAngle = X.ParamBrowAngle;
+ out.ParamEyeBallX = clamp(out.ParamEyeBallX + X.gx, -1, 1);
+ out.ParamEyeBallY = clamp(out.ParamEyeBallY + X.gy, -1, 1);
+ } else {
+ out.eyeSmileL = out.ParamEyeSmile;
+ }
+ if (M) {
+ const mix = (key, v) => { out[key] += (v - out[key]) * mw; };
+ const clampEye = v => Math.min(1.3, Math.max(0, v));
+ if ('eyeOpen' in M) { mix('ParamEyeROpen', clampEye(M.eyeOpen) * blink); if (!('eyeOpenL' in M)) mix('ParamEyeLOpen', clampEye(M.eyeOpen) * blink); }
+ if ('eyeOpenL' in M) mix('ParamEyeLOpen', clampEye(M.eyeOpenL) * blink);
+ if ('ParamEyeSmile' in M) { mix('ParamEyeSmile', M.ParamEyeSmile); if (!('eyeSmileL' in M)) mix('eyeSmileL', M.ParamEyeSmile); }
+ if ('eyeSmileL' in M) mix('eyeSmileL', M.eyeSmileL);
+ for (const id of ['ParamMouthOpenY', 'ParamMouthForm', 'ParamCheek', 'ParamBrowY', 'ParamBrowAngle'])
+ if (id in M) mix(id, id === 'ParamMouthOpenY' || id === 'ParamCheek' ? Math.max(0, M[id]) : M[id]);
+ }
+ const sm = this.speechMouth(dt);
+ if (sm) { this.lipOpen = sm[0]; this.lipForm = sm[1]; }
+ else if (this.lipOpen !== null && !this.speaking && !this.kana) this.lipOpen = null;
+ if (this.lipOpen !== null) {
+ out.ParamMouthOpenY = Math.max(out.ParamMouthOpenY * 0.3, this.lipOpen);
+ // while talking the voice decides the vowel; the expression's form would shift it
+ out.ParamMouthForm = clamp(this.lipForm, -1, 1);
+ }
+ this.P = out;
+ return out;
+ }
+}
diff --git a/src/engine/motions.js b/src/engine/motions.js
new file mode 100644
index 0000000..c588ee7
--- /dev/null
+++ b/src/engine/motions.js
@@ -0,0 +1,358 @@
+// Keyframed motions. Each track is [[time(s), value], ...] and is interpolated with a
+// smooth cubic curve. Head/body/eye-direction tracks are ADDED on top of whatever the
+// current mode is doing (idle, mouse follow); face tracks REPLACE the expression.
+// The result still goes through the parameter springs, which adds follow-through.
+
+export const ADDITIVE = new Set([
+ 'ParamAngleX', 'ParamAngleY', 'ParamAngleZ', 'ParamBodyAngleX', 'ParamBodyAngleZ',
+ 'ParamArmAngle', 'ParamHandAngle', 'ParamEyeBallX', 'ParamEyeBallY',
+]);
+
+export const MOTIONS = {
+ nod: {
+ label: 'Nod', dur: 1.7,
+ tracks: {
+ ParamAngleY: [[0, 0], [0.32, -13], [0.62, 2], [0.95, -9], [1.3, 1], [1.7, 0]],
+ ParamAngleZ: [[0, 0], [0.4, -2], [1.0, -1], [1.7, 0]],
+ ParamBodyAngleX: [[0, 0], [0.5, -1.5], [1.7, 0]],
+ ParamEyeSmile: [[0, 0], [0.3, 0.45], [1.3, 0.45], [1.7, 0]],
+ eyeOpen: [[0, 1], [0.3, 0.72], [1.3, 0.72], [1.7, 1]],
+ ParamMouthOpenY: [[0, 0], [0.3, 0.12], [1.3, 0.12], [1.7, 0]],
+ ParamMouthForm: [[0, 0], [0.3, -0.6], [1.7, -0.3]],
+ },
+ },
+ tilt: {
+ label: 'Head tilt', dur: 2.6,
+ tracks: {
+ ParamAngleZ: [[0, 0], [0.55, 17], [2.0, 15], [2.6, 0]],
+ ParamAngleX: [[0, 0], [0.6, 8], [2.0, 7], [2.6, 0]],
+ ParamAngleY: [[0, 0], [0.6, 4], [2.6, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.8, 3], [2.0, 3], [2.6, 0]],
+ ParamEyeBallX: [[0, 0], [0.4, 0.5], [2.1, 0.4], [2.6, 0]],
+ ParamEyeBallY: [[0, 0], [0.4, 0.35], [2.1, 0.3], [2.6, 0]],
+ ParamBrowAngle: [[0, 0], [0.5, -0.7], [2.1, -0.6], [2.6, 0]],
+ ParamBrowY: [[0, 0], [0.5, 0.35], [2.1, 0.3], [2.6, 0]],
+ // closed mouth: a barely open round mouth read as a squashed blob
+ },
+ },
+ think: {
+ label: 'Thinking', dur: 3.6,
+ tracks: {
+ ParamAngleX: [[0, 0], [0.7, -11], [3.0, -9], [3.6, 0]],
+ ParamAngleY: [[0, 0], [0.7, 9], [3.0, 8], [3.6, 0]],
+ ParamAngleZ: [[0, 0], [0.8, 6], [3.0, 5], [3.6, 0]],
+ ParamEyeBallX: [[0, 0], [0.35, -0.8], [3.1, -0.7], [3.6, 0]],
+ ParamEyeBallY: [[0, 0], [0.35, 0.7], [3.1, 0.6], [3.6, 0]],
+ ParamHandAngle: [[0, 0], [0.6, 3], [3.0, 3], [3.6, 0]],
+ ParamFingerTap: [[0, 0], [0.9, 0], [1.05, 1], [1.2, 0], [1.4, 1], [1.55, 0], [1.75, 1], [1.9, 0],
+ [2.3, 0], [2.45, 1], [2.6, 0], [3.6, 0]],
+ ParamBrowY: [[0, 0], [0.6, 0.25], [3.0, 0.2], [3.6, 0]],
+ ParamBrowAngle: [[0, 0], [0.6, -0.3], [3.0, -0.3], [3.6, 0]],
+ ParamMouthForm: [[0, 0], [0.6, 0.4], [3.6, 0]],
+ },
+ },
+ giggle: {
+ label: 'Chuckle', dur: 2.2,
+ tracks: {
+ eyeOpen: [[0, 1], [0.2, 0], [1.8, 0], [2.2, 1]],
+ ParamEyeSmile: [[0, 0], [0.2, 1], [1.8, 1], [2.2, 0]],
+ ParamMouthOpenY: [[0, 0], [0.2, 0.5], [0.45, 0.32], [0.7, 0.55], [0.95, 0.34], [1.2, 0.5], [1.8, 0.3], [2.1, 0]],
+ ParamMouthForm: [[0, 0], [0.2, -0.8], [2.2, -0.2]],
+ ParamCheek: [[0, 0], [0.3, 0.7], [1.8, 0.7], [2.2, 0.1]],
+ ParamAngleY: [[0, 0], [0.2, -5], [0.45, -1], [0.7, -6], [0.95, -2], [1.2, -5], [1.6, -2], [2.2, 0]],
+ ParamAngleZ: [[0, 0], [0.3, -6], [1.8, -5], [2.2, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.25, 2], [0.5, -1], [0.75, 2], [1.0, -1], [1.3, 1.5], [2.2, 0]],
+ ParamBrowY: [[0, 0], [0.3, 0.3], [1.8, 0.3], [2.2, 0]],
+ },
+ },
+ surprise: {
+ label: 'Surprise', dur: 2.0,
+ tracks: {
+ ParamAngleY: [[0, 0], [0.12, 10], [0.5, 6], [1.5, 5], [2.0, 0]],
+ ParamAngleX: [[0, 0], [0.12, -4], [2.0, 0]],
+ ParamBodyAngleX: [[0, 0], [0.15, -4], [1.5, -3], [2.0, 0]],
+ eyeOpen: [[0, 1], [0.1, 1.25], [1.5, 1.2], [2.0, 1]],
+ ParamBrowY: [[0, 0], [0.1, 1], [1.5, 0.9], [2.0, 0]],
+ ParamMouthOpenY: [[0, 0], [0.12, 0.6], [1.4, 0.45], [2.0, 0]],
+ ParamMouthForm: [[0, 0], [0.12, 0.6], [1.5, 0.55], [2.0, 0]], // o
+ ParamArmAngle: [[0, 0], [0.15, -4], [1.5, -3], [2.0, 0]],
+ },
+ },
+ shy: {
+ label: 'Shy', dur: 3.2,
+ tracks: {
+ ParamAngleX: [[0, 0], [0.6, 14], [2.6, 12], [3.2, 0]],
+ ParamAngleY: [[0, 0], [0.6, -9], [2.6, -8], [3.2, 0]],
+ ParamAngleZ: [[0, 0], [0.7, -8], [2.6, -7], [3.2, 0]],
+ ParamEyeBallX: [[0, 0], [0.3, 0.8], [1.6, 0.8], [1.9, -0.3], [2.2, 0.8], [2.8, 0.6], [3.2, 0]],
+ ParamEyeBallY: [[0, 0], [0.3, -0.5], [2.8, -0.4], [3.2, 0]],
+ eyeOpen: [[0, 1], [0.5, 0.75], [2.7, 0.75], [3.2, 1]],
+ ParamEyeSmile: [[0, 0], [0.5, 0.5], [2.7, 0.5], [3.2, 0]],
+ ParamCheek: [[0, 0], [0.8, 1], [2.7, 1], [3.2, 0]],
+ ParamBrowAngle: [[0, 0], [0.5, -0.6], [2.7, -0.5], [3.2, 0]],
+ ParamMouthForm: [[0, 0], [0.5, -0.4], [3.2, 0]],
+ ParamHandAngle: [[0, 0], [0.8, 4], [2.6, 4], [3.2, 0]],
+ },
+ },
+ no: {
+ label: 'Shake head', dur: 1.9,
+ tracks: {
+ ParamAngleX: [[0, 0], [0.2, 13], [0.45, -13], [0.7, 12], [0.95, -10], [1.2, 5], [1.5, 0]],
+ ParamAngleY: [[0, 0], [0.2, -3], [1.3, -3], [1.9, 0]],
+ ParamBodyAngleX: [[0, 0], [0.3, 1.5], [0.6, -1.5], [0.9, 1], [1.3, 0]],
+ eyeOpen: [[0, 1], [0.15, 0], [1.4, 0], [1.9, 1]],
+ ParamEyeSmile: [[0, 0], [0.15, 1], [1.4, 1], [1.9, 0]],
+ // closed mouth while shaking the head
+ ParamBrowAngle: [[0, 0], [0.2, -0.5], [1.4, -0.5], [1.9, 0]],
+ },
+ },
+ wink: {
+ label: 'Wink', dur: 2.0,
+ tracks: {
+ ParamAngleZ: [[0, 0], [0.35, -13], [1.5, -12], [2.0, 0]],
+ ParamAngleX: [[0, 0], [0.35, 9], [1.5, 8], [2.0, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.5, -2], [1.5, -2], [2.0, 0]],
+ eyeOpenL: [[0, 1], [0.25, 1], [0.4, 0], [1.4, 0], [1.6, 1]],
+ eyeSmileL: [[0, 0], [0.3, 1], [1.5, 1], [1.7, 0]],
+ ParamMouthOpenY: [[0, 0], [2.0, 0]], // wink with a closed smile
+ ParamMouthForm: [[0, 0], [0.35, -0.8], [2.0, 0]],
+ ParamCheek: [[0, 0], [0.4, 0.5], [1.6, 0.5], [2.0, 0]],
+ },
+ },
+ greet: {
+ label: 'Greeting', dur: 2.6,
+ tracks: {
+ ParamAngleY: [[0, 0], [0.7, -18], [1.2, -17], [1.9, 2], [2.6, 0]],
+ ParamBodyAngleX: [[0, 0], [0.8, 2], [1.8, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.8, 1.5], [2.0, 0]],
+ ParamArmAngle: [[0, 0], [0.8, 3], [2.0, 0]],
+ eyeOpen: [[0, 1], [0.5, 0], [1.4, 0], [1.8, 1]],
+ ParamEyeSmile: [[0, 0], [0.5, 1], [1.6, 1], [2.3, 0.4], [2.6, 0]],
+ ParamMouthOpenY: [[0, 0], [1.6, 0], [1.8, 0.3], [2.3, 0.2], [2.6, 0]],
+ ParamMouthForm: [[0, 0], [1.6, -0.8], [2.6, -0.3]],
+ ParamCheek: [[0, 0], [1.6, 0.3], [2.6, 0]],
+ },
+ },
+};
+
+// Idle motions: every one moves several parameters at once (breath, head, body, arm,
+// gaze, lids, brows) so the whole figure takes part, like a Live2D idle.
+// Eyes only go down to ~0.55 open and the mouth stays shut (a single image fakes those worst).
+// ParamBreath tracks replace the automatic breathing while the motion plays.
+export const IDLE_MOTIONS = {
+ lookAround: {
+ label: 'Look around', dur: 5.2, idle: true,
+ tracks: {
+ ParamEyeBallX: [[0, 0], [0.25, -0.85], [1.5, -0.8], [1.8, 0.1], [2.1, 0.85], [3.4, 0.8], [3.7, 0], [5.2, 0]],
+ ParamEyeBallY: [[0, 0], [0.25, 0.15], [1.8, 0.25], [2.1, 0.1], [3.7, 0], [5.2, 0]],
+ ParamAngleX: [[0, 0], [0.7, -20], [1.6, -18], [2.5, 19], [3.5, 17], [4.4, 0], [5.2, 0]],
+ ParamAngleY: [[0, 0], [0.7, 3], [1.8, 5], [2.5, 3], [4.4, 0]],
+ ParamAngleZ: [[0, 0], [0.8, 4], [1.8, 0], [2.6, -4], [4.4, 0]],
+ ParamBodyAngleX: [[0, 0], [1.0, -4], [2.8, 4], [4.6, 0]],
+ ParamBodyAngleZ: [[0, 0], [1.0, 1.5], [2.8, -1.5], [4.6, 0]],
+ ParamHandAngle: [[0, 0], [1.0, -2], [2.8, 2], [4.6, 0]],
+ ParamBrowY: [[0, 0], [0.5, 0.35], [3.6, 0.3], [4.4, 0]],
+ // curious: a quick inhale, held while looking, let out at the end
+ ParamBreath: [[0, 0.2], [0.6, 0.85], [3.6, 0.7], [4.6, 0], [5.2, 0.1]],
+ },
+ },
+ glance: {
+ label: 'Side glance', dur: 4.6, idle: true,
+ tracks: {
+ ParamEyeBallX: [[0, 0], [0.18, 0.9], [2.6, 0.85], [2.9, 0.15], [3.2, 0], [4.6, 0]],
+ ParamEyeBallY: [[0, 0], [0.18, 0.4], [2.6, 0.35], [3.2, 0]],
+ ParamAngleX: [[0, 0], [0.6, 13], [2.6, 11], [3.6, 0]],
+ ParamAngleY: [[0, 0], [0.6, 6], [2.6, 5], [3.6, 0]],
+ ParamAngleZ: [[0, 0], [0.7, -5], [2.6, -4], [3.6, 0]],
+ ParamBodyAngleX: [[0, 0], [1.0, 2.5], [2.8, 2], [4.0, 0]],
+ eyeOpen: [[0, 1], [0.3, 1.06], [2.5, 1.05], [2.8, 0.85], [3.4, 1]],
+ ParamBrowY: [[0, 0], [0.4, 0.4], [2.5, 0.35], [3.4, 0]],
+ ParamBrowAngle: [[0, 0], [0.4, -0.2], [2.5, -0.2], [3.4, 0]],
+ ParamBreath: [[0, 0], [0.5, 0.6], [2.6, 0.55], [3.8, 0], [4.6, 0.3]],
+ },
+ },
+ sway: {
+ label: 'Sway', dur: 7.0, idle: true,
+ tracks: {
+ ParamBodyAngleZ: [[0, 0], [1.6, 6], [3.4, -6], [5.2, 5], [7.0, 0]],
+ ParamBodyAngleX: [[0, 0], [1.6, 3], [3.4, -3], [5.2, 2.5], [7.0, 0]],
+ ParamAngleZ: [[0, 0], [1.8, -10], [3.6, 10], [5.4, -8], [7.0, 0]],
+ ParamAngleX: [[0, 0], [1.8, 6], [3.6, -6], [5.4, 5], [7.0, 0]],
+ ParamAngleY: [[0, 0], [0.9, 3], [1.8, 0], [2.7, 3], [3.6, 0], [4.5, 3], [5.4, 0], [7.0, 0]],
+ ParamArmAngle: [[0, 0], [1.6, 3], [3.4, -3], [5.2, 2], [7.0, 0]],
+ ParamHandAngle: [[0, 0], [1.8, -4], [3.6, 4], [5.4, -3], [7.0, 0]],
+ ParamEyeBallX: [[0, 0], [1.8, -0.3], [3.6, 0.3], [5.4, -0.2], [7.0, 0]],
+ eyeOpen: [[0, 1], [0.8, 0.82], [6.2, 0.82], [7.0, 1]],
+ ParamEyeSmile: [[0, 0], [0.8, 0.35], [6.2, 0.35], [7.0, 0]],
+ // slow, even breaths in time with the sway
+ ParamBreath: [[0, 0], [0.9, 1], [1.8, 0], [2.7, 1], [3.6, 0], [4.5, 1], [5.4, 0], [6.3, 0.8], [7.0, 0]],
+ },
+ },
+ sigh: {
+ label: 'Sigh', dur: 5.6, idle: true,
+ tracks: {
+ ParamBreath: [[0, 0], [1.3, 1.25], [1.9, 1.25], [3.6, 0], [5.6, 0]],
+ ParamAngleY: [[0, 0], [1.3, 9], [1.9, 9], [3.3, -9], [4.6, -6], [5.6, 0]],
+ ParamAngleZ: [[0, 0], [1.3, -3], [3.3, 5], [5.6, 0]],
+ ParamBodyAngleX: [[0, 0], [1.3, -2.5], [3.3, 2.5], [5.6, 0]],
+ ParamBodyAngleZ: [[0, 0], [1.9, 1], [3.3, -1.5], [5.6, 0]],
+ ParamArmAngle: [[0, 0], [1.3, -2.5], [3.3, 2], [5.6, 0]],
+ ParamEyeBallY: [[0, 0], [1.2, 0.4], [2.0, 0.3], [3.2, -0.4], [4.8, -0.2], [5.6, 0]],
+ eyeOpen: [[0, 1], [1.0, 0.95], [1.9, 0.6], [3.4, 0.6], [4.6, 0.78], [5.6, 1]],
+ ParamBrowY: [[0, 0], [1.3, 0.35], [3.2, -0.2], [5.6, 0]],
+ ParamBrowAngle: [[0, 0], [1.9, -0.4], [4.6, -0.35], [5.6, 0]],
+ },
+ },
+ doze: {
+ label: 'Drowsy', dur: 7.2, idle: true,
+ tracks: {
+ eyeOpen: [[0, 1], [1.8, 0.78], [3.2, 0.62], [4.5, 0.55], [4.75, 1.1], [5.6, 1.05], [7.2, 1]],
+ ParamAngleY: [[0, 0], [1.8, -6], [3.2, -9], [4.5, -17], [4.75, 5], [5.6, 2], [7.2, 0]],
+ ParamAngleZ: [[0, 0], [2.0, 4], [4.5, 10], [4.75, -2], [7.2, 0]],
+ ParamAngleX: [[0, 0], [4.5, -4], [4.75, 3], [5.4, -6], [6.2, 5], [7.2, 0]],
+ ParamBodyAngleZ: [[0, 0], [4.5, 3], [4.8, -2], [7.2, 0]],
+ ParamBodyAngleX: [[0, 0], [4.5, 2], [4.8, -1.5], [7.2, 0]],
+ ParamArmAngle: [[0, 0], [4.5, 3], [4.8, -2], [7.2, 0]],
+ ParamHandAngle: [[0, 0], [4.5, 5], [4.8, -1], [7.2, 0]],
+ ParamEyeBallY: [[0, 0], [4.5, -0.4], [4.75, 0.2], [7.2, 0]],
+ ParamEyeBallX: [[0, 0], [4.8, 0], [5.3, -0.6], [6.1, 0.6], [6.8, 0]],
+ ParamBrowY: [[0, 0], [4.5, -0.35], [4.75, 0.8], [5.8, 0.3], [7.2, 0]],
+ // long, slow, deepening breaths; a sharp inhale on waking
+ ParamBreath: [[0, 0], [1.1, 0.7], [2.6, 0], [3.8, 0.6], [4.5, 0.2], [4.8, 1.1], [6.0, 0.2], [7.2, 0]],
+ },
+ },
+ stretch: {
+ label: 'Stretch', dur: 6.2, idle: true,
+ tracks: {
+ ParamAngleZ: [[0, 0], [1.3, -22], [2.3, -21], [3.8, 20], [4.8, 19], [6.2, 0]],
+ ParamAngleY: [[0, 0], [1.3, 5], [2.3, 7], [3.1, -3], [3.8, 5], [4.8, 6], [6.2, 0]],
+ ParamAngleX: [[0, 0], [1.3, -5], [3.8, 5], [6.2, 0]],
+ ParamBodyAngleZ: [[0, 0], [1.3, 4], [3.8, -4], [6.2, 0]],
+ ParamBodyAngleX: [[0, 0], [1.3, -2], [3.8, 2], [6.2, 0]],
+ ParamArmAngle: [[0, 0], [1.3, 2], [3.8, -2], [6.2, 0]],
+ eyeOpen: [[0, 1], [0.8, 0.62], [4.9, 0.62], [5.6, 1]],
+ ParamBrowAngle: [[0, 0], [1.0, -0.3], [4.9, -0.3], [5.8, 0]],
+ ParamBreath: [[0, 0], [1.3, 1.1], [2.3, 0.9], [3.1, 0.2], [3.8, 1.1], [4.8, 0.9], [6.2, 0]],
+ },
+ },
+ lean: {
+ label: 'Peek', dur: 4.8, idle: true,
+ tracks: {
+ ParamBodyAngleX: [[0, 0], [0.9, 6], [3.4, 6], [4.4, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.9, -3], [3.4, -3], [4.4, 0]],
+ ParamAngleX: [[0, 0], [0.9, 9], [2.0, 7], [2.6, 10], [3.4, 8], [4.4, 0]],
+ ParamAngleY: [[0, 0], [0.9, -6], [3.4, -5], [4.4, 0]],
+ ParamAngleZ: [[0, 0], [0.9, 10], [2.2, 12], [3.4, 9], [4.4, 0]],
+ ParamArmAngle: [[0, 0], [0.9, -3], [3.4, -3], [4.4, 0]],
+ ParamHandAngle: [[0, 0], [0.9, 3], [3.4, 3], [4.4, 0]],
+ ParamEyeBallY: [[0, 0], [0.6, 0.45], [3.4, 0.4], [4.2, 0]],
+ ParamEyeBallX: [[0, 0], [1.5, 0], [1.8, -0.3], [2.3, 0.2], [2.8, 0], [4.2, 0]],
+ eyeOpen: [[0, 1], [0.6, 1.1], [3.4, 1.08], [4.2, 1]],
+ ParamBrowY: [[0, 0], [0.6, 0.45], [3.4, 0.4], [4.2, 0]],
+ ParamBrowAngle: [[0, 0], [0.6, -0.3], [3.4, -0.3], [4.2, 0]],
+ ParamCheek: [[0, 0], [1.2, 0.25], [3.4, 0.25], [4.4, 0]],
+ ParamBreath: [[0, 0], [0.8, 0.8], [3.4, 0.6], [4.4, 0], [4.8, 0.2]],
+ },
+ },
+ hum: {
+ label: 'Listen', dur: 5.6, idle: true,
+ tracks: {
+ ParamAngleY: [[0, 0], [0.45, -5], [0.9, 2], [1.35, -5], [1.8, 2], [2.25, -5], [2.7, 2], [3.15, -5], [3.6, 2], [4.05, -4], [4.8, 0]],
+ ParamAngleZ: [[0, 0], [0.9, 8], [1.8, -8], [2.7, 8], [3.6, -8], [4.6, 0]],
+ ParamAngleX: [[0, 0], [0.9, 4], [1.8, -4], [2.7, 4], [3.6, -4], [4.6, 0]],
+ ParamBodyAngleZ: [[0, 0], [0.9, -3], [1.8, 3], [2.7, -3], [3.6, 3], [4.6, 0]],
+ ParamBodyAngleX: [[0, 0], [1.8, 2], [3.6, -2], [4.8, 0]],
+ ParamHandAngle: [[0, 0], [0.9, 3], [1.8, -3], [2.7, 3], [3.6, -3], [4.6, 0]],
+ ParamFingerTap: [[0, 0], [0.45, 1], [0.9, 0], [1.35, 1], [1.8, 0], [2.25, 1], [2.7, 0], [3.15, 1], [3.6, 0], [5.6, 0]],
+ ParamEyeBallX: [[0, 0], [0.9, 0.3], [1.8, -0.3], [2.7, 0.3], [3.6, -0.3], [4.6, 0]],
+ eyeOpen: [[0, 1], [0.4, 0.72], [4.6, 0.72], [5.3, 1]],
+ ParamEyeSmile: [[0, 0], [0.4, 0.55], [4.6, 0.55], [5.3, 0]],
+ ParamCheek: [[0, 0], [0.8, 0.3], [4.6, 0.3], [5.6, 0]],
+ ParamBrowY: [[0, 0], [0.5, 0.25], [4.6, 0.25], [5.4, 0]],
+ ParamBreath: [[0, 0], [0.9, 0.9], [1.8, 0.2], [2.7, 0.9], [3.6, 0.2], [4.6, 0.8], [5.6, 0]],
+ },
+ },
+ tap: {
+ label: 'Tap', dur: 5.0, idle: true,
+ tracks: {
+ ParamEyeBallX: [[0, 0], [0.3, -0.6], [2.2, -0.5], [2.5, -0.1], [2.8, -0.6], [4.2, -0.5], [4.7, 0]],
+ ParamEyeBallY: [[0, 0], [0.3, 0.55], [4.2, 0.5], [4.7, 0]],
+ ParamAngleX: [[0, 0], [0.8, -11], [2.4, -9], [3.0, -12], [4.2, -10], [5.0, 0]],
+ ParamAngleY: [[0, 0], [0.8, 8], [4.2, 7], [5.0, 0]],
+ ParamAngleZ: [[0, 0], [0.8, 6], [2.4, 4], [3.0, 7], [4.2, 5], [5.0, 0]],
+ ParamBodyAngleX: [[0, 0], [1.0, -2], [4.2, -2], [5.0, 0]],
+ ParamHandAngle: [[0, 0], [0.8, 3], [4.2, 3], [5.0, 0]],
+ ParamFingerTap: [[0, 0], [0.9, 0], [1.05, 1], [1.2, 0], [1.4, 1], [1.55, 0], [1.75, 1], [1.9, 0],
+ [2.6, 0], [2.75, 1], [2.9, 0], [3.1, 1], [3.25, 0], [5.0, 0]],
+ ParamBrowY: [[0, 0], [0.6, 0.3], [4.2, 0.25], [5.0, 0]],
+ ParamBrowAngle: [[0, 0], [0.6, -0.35], [4.2, -0.3], [5.0, 0]],
+ eyeOpen: [[0, 1], [0.6, 0.9], [4.2, 0.9], [5.0, 1]],
+ ParamBreath: [[0, 0], [0.8, 0.7], [2.2, 0.4], [3.2, 0.8], [4.4, 0], [5.0, 0.2]],
+ },
+ },
+ readNote: {
+ label: 'Read script', dur: 2.6, idle: true,
+ tracks: {
+ // a quick look down at the notes on the desk and back to the camera
+ ParamEyeBallY: [[0, 0], [0.2, -0.85], [1.5, -0.8], [1.75, 0], [2.6, 0]],
+ ParamEyeBallX: [[0, 0], [0.2, -0.15], [1.5, -0.1], [1.75, 0]],
+ ParamAngleY: [[0, 0], [0.45, -9], [1.5, -8], [2.0, 1], [2.6, 0]],
+ ParamAngleZ: [[0, 0], [0.5, 2], [1.6, 2], [2.6, 0]],
+ eyeOpen: [[0, 1], [0.3, 0.78], [1.5, 0.78], [1.75, 1]],
+ ParamBreath: [[0, 0.3], [0.8, 0.5], [1.8, 0.2], [2.6, 0.4]],
+ },
+ },
+ waiting: {
+ label: 'Fidget', dur: 6.4, idle: true,
+ tracks: {
+ // shifts her weight, checks the viewer, looks away, shifts back
+ ParamBodyAngleZ: [[0, 0], [0.9, 5], [2.4, 4], [3.3, -5], [5.2, -4], [6.4, 0]],
+ ParamBodyAngleX: [[0, 0], [0.9, 3], [3.3, -3], [5.2, -2], [6.4, 0]],
+ ParamAngleZ: [[0, 0], [1.0, -6], [2.4, -4], [3.4, 6], [5.2, 5], [6.4, 0]],
+ ParamAngleX: [[0, 0], [1.2, -8], [2.2, 2], [3.6, 12], [5.0, 10], [6.2, 0]],
+ ParamAngleY: [[0, 0], [1.2, -3], [2.2, 2], [3.6, -2], [6.2, 0]],
+ ParamArmAngle: [[0, 0], [0.9, 3], [3.3, -3], [5.2, -2], [6.4, 0]],
+ ParamHandAngle: [[0, 0], [1.2, 3], [3.4, -3], [6.4, 0]],
+ ParamFingerTap: [[0, 0], [4.2, 0], [4.35, 1], [4.5, 0], [4.7, 1], [4.85, 0], [6.4, 0]],
+ ParamEyeBallX: [[0, 0], [0.9, -0.7], [1.9, -0.6], [2.1, 0], [2.7, 0], [2.9, 0.8], [5.0, 0.7], [5.4, 0], [6.4, 0]],
+ ParamEyeBallY: [[0, 0], [0.9, -0.2], [2.1, 0], [2.9, 0.3], [5.4, 0]],
+ eyeOpen: [[0, 1], [2.0, 1], [2.2, 1.06], [2.8, 1.05], [3.1, 0.85], [5.4, 0.85], [6.2, 1]],
+ ParamBrowAngle: [[0, 0], [0.9, -0.35], [2.0, -0.35], [2.3, 0], [3.1, -0.4], [5.4, -0.35], [6.4, 0]],
+ ParamBrowY: [[0, 0], [2.2, 0.4], [2.8, 0.35], [3.2, 0], [6.4, 0]],
+ ParamBreath: [[0, 0.3], [0.9, 0.8], [2.0, 0.3], [2.6, 0.9], [3.4, 0.2], [4.4, 0.8], [5.6, 0], [6.4, 0.2]],
+ },
+ },
+ spaceOut: {
+ label: 'Daydream', dur: 7.4, idle: true,
+ tracks: {
+ // gaze drifts up and away, breaths get slow and long, one slow blink
+ ParamEyeBallX: [[0, 0], [1.4, -0.55], [4.8, -0.6], [5.6, 0.1], [7.0, 0]],
+ ParamEyeBallY: [[0, 0], [1.4, 0.6], [4.8, 0.55], [5.6, 0], [7.0, 0]],
+ ParamAngleX: [[0, 0], [2.0, -9], [4.8, -10], [6.0, 2], [7.4, 0]],
+ ParamAngleY: [[0, 0], [2.0, 7], [4.8, 8], [6.0, -2], [7.4, 0]],
+ ParamAngleZ: [[0, 0], [2.0, 9], [4.8, 11], [6.0, 2], [7.4, 0]],
+ ParamBodyAngleZ: [[0, 0], [2.2, 3], [4.8, 3.5], [6.4, 0]],
+ ParamBodyAngleX: [[0, 0], [2.2, -2], [4.8, -2], [6.4, 0]],
+ ParamHandAngle: [[0, 0], [2.2, 4], [4.8, 5], [6.4, 0]],
+ ParamArmAngle: [[0, 0], [2.2, 2], [4.8, 2], [6.4, 0]],
+ eyeOpen: [[0, 1], [1.4, 0.8], [3.0, 0.8], [3.35, 0.56], [3.8, 0.8], [4.8, 0.8], [5.6, 1.04], [6.4, 1]],
+ ParamBrowY: [[0, 0], [1.6, 0.15], [4.8, 0.15], [5.6, 0.35], [6.6, 0]],
+ ParamBreath: [[0, 0], [1.6, 0.9], [3.4, 0], [5.0, 0.9], [6.2, 0.1], [7.4, 0]],
+ },
+ },
+};
+
+// Cubic Hermite through the keys (tangents from neighbours, flat at both ends).
+export function sampleTrack(keys, t) {
+ if (t <= keys[0][0]) return keys[0][1];
+ const n = keys.length - 1;
+ if (t >= keys[n][0]) return keys[n][1];
+ let i = 0;
+ while (t > keys[i + 1][0]) i++;
+ const [t0, v0] = keys[i], [t1, v1] = keys[i + 1];
+ const tan = j => (j <= 0 || j >= n) ? 0 : (keys[j + 1][1] - keys[j - 1][1]) / (keys[j + 1][0] - keys[j - 1][0]);
+ const h = t1 - t0, u = (t - t0) / h;
+ const m0 = tan(i) * h, m1 = tan(i + 1) * h;
+ const u2 = u * u, u3 = u2 * u;
+ return (2 * u3 - 3 * u2 + 1) * v0 + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * v1 + (u3 - u2) * m1;
+}
diff --git a/src/engine/physics.js b/src/engine/physics.js
new file mode 100644
index 0000000..97219b6
--- /dev/null
+++ b/src/engine/physics.js
@@ -0,0 +1,177 @@
+/** @param {ReturnType<import('./rig.js').createRig>} engine
+ * @param {import('../rig/types').Rig} rig */
+export function createPhysics(engine, rig) {
+ const { applyHead, applyBody, TASSELS, tasselAnchor } = engine;
+ const STRANDS = (rig.strands ?? []).map(strand => {
+ if (strand.nodes.length === 4) return strand;
+ const nodes = Array.from({ length: 4 }, (_, i) => {
+ const f = i / 3 * (strand.nodes.length - 1);
+ const k = Math.min(strand.nodes.length - 2, Math.floor(f));
+ const t = f - k;
+ return [0, 1].map(axis => strand.nodes[k][axis] + (strand.nodes[k + 1][axis] - strand.nodes[k][axis]) * t);
+ });
+ return { ...strand, nodes };
+ });
+ // Secondary motion: spring chains for hair strands, spring-mass points for the buns
+ // and 2-segment verlet chains for tassels.
+
+
+ // Strand chain tuning: stiffness per node (root .. tip), how much of the parent's lag each
+ // node inherits (this is what makes a swing travel down the strand), and damping.
+ const STRAND_K = [0, 300, 200, 140], STRAND_COUPLE = 0.9, STRAND_DAMP = 7;
+
+ // Overall hair feel, tuned against measured runs (see README). Once motions made the head
+ // move ~4x faster, the chains whipped and neighbouring strands split apart by up to 16px,
+ // which smeared the hair between them.
+ // stiff / damp / couple: scale the chain springs, damping and the root-to-tip lag
+ // reach: soft limit of the tip offset, as a share of each strand's `max`
+ // bind: smoothing passes across the fringe strands (more = moves more as one sheet)
+ const HAIR_TUNE = { stiff: 1.7, damp: 1.6, couple: 0.85, reach: 0.9, bind: 4 };
+ const FRINGE = Math.min(6, STRANDS.filter(s => s.name.startsWith('bang')).length);
+
+ // Tassel pendulum: swing frequency (Hz), damping ratio, how much head tilt it counters,
+ // how strongly knot acceleration pushes it, gentle wind (rad), limit (rad), accel smoothing (1/s)
+ const TASSEL_TUNE = { freq: 0.7, zeta: 0.22, hang: 0.85, inertia: 0.32, wind: 0.03, max: 0.55, smooth: 6 };
+ const rotV = (v, a) => [v[0] * Math.cos(a) - v[1] * Math.sin(a), v[0] * Math.sin(a) + v[1] * Math.cos(a)]; // STRANDS[0..5] are the fringe, 6 and 7 the side locks
+ const softLimit = (v, m) => { const l = Math.hypot(v[0], v[1]); if (l < 1e-6) return v; const k = m * Math.tanh(l / m) / l; return [v[0] * k, v[1] * k]; };
+
+ const HAIR = Object.fromEntries(Object.entries(rig.buns ?? {}).map(([key, area]) => [key, { at: [area.cx, area.cy], k: 260, c: 11, hang: 3, max: 4 }]));
+
+ const clampLen = (v, m) => { const l = Math.hypot(v[0], v[1]); if (l > m) { v[0] *= m / l; v[1] *= m / l; } };
+
+ class Physics {
+ constructor() {
+ this.gain = 1; // "sway gain"
+ this.out = { gain: 1, bunL: [0, 0], bunR: [0, 0] };
+ this.hair = {};
+ for (const k of Object.keys(HAIR)) {
+ this.hair[k] = { p: null, v: [0, 0] };
+ this.out[k] = [0, 0];
+ }
+ this.strands = STRANDS.map(() => ({ p: null, v: [[0, 0], [0, 0], [0, 0], [0, 0]] }));
+ this.out.strands = STRANDS.map(() => [[0, 0], [0, 0], [0, 0], [0, 0]]);
+ this.chains = TASSELS.map(t => {
+ const dx = t.tip[0] - t.pivot[0], dy = t.tip[1] - t.pivot[1], L = Math.hypot(dx, dy);
+ const dir = [dx / L, dy / L];
+ return { t, dir, L1: L * t.split, L2: L * (1 - t.split), pts: null, prev: null, phi: [0, 0], anchor: [0, 0] };
+ });
+ this.time = 0;
+ }
+
+ hairAnchor(at, P) {
+ const p = [at[0], at[1]];
+ applyHead(p, 1, P);
+ applyBody(p, at[1], P);
+ return p;
+ }
+
+ step(P, dt) {
+ const sub = Math.max(1, Math.ceil(dt / (1 / 240)));
+ const h = Math.min(dt, 0.05) / sub;
+ const roll = -P.ParamAngleZ / 30 * rig.head.maxRoll - P.ParamBodyAngleZ / 10 * rig.body.maxRoll;
+ const g = this.gain;
+
+ STRANDS.forEach((cfg, si) => {
+ const st = this.strands[si], out = this.out.strands[si];
+ const target = cfg.nodes.map(n => this.hairAnchor(n, P));
+ if (!st.p) st.p = target.map(t => [...t]);
+ const phase = si * 1.7;
+ for (let i = 0; i < sub; i++) {
+ const t = this.time + i * h;
+ for (let j = 1; j < 4; j++) {
+ // hanging hair stays vertical when the head rolls (grows with distance from the root)
+ const hang = Math.hypot(cfg.nodes[j][0] - cfg.nodes[0][0], cfg.nodes[j][1] - cfg.nodes[0][1]);
+ // mostly one shared breeze, with a little per-strand flutter
+ const wind = (Math.sin(t * 1.3) * 0.5 + Math.sin(t * 3.1) * 0.3 + Math.sin(t * 4.7 + phase) * 0.2) * cfg.max * 0.1 * j / 3;
+ const parent = [st.p[j - 1][0] - target[j - 1][0], st.p[j - 1][1] - target[j - 1][1]];
+ const tx = target[j][0] + parent[0] * STRAND_COUPLE * HAIR_TUNE.couple - Math.sin(roll) * hang * 0.12 + wind;
+ const ty = target[j][1] + parent[1] * STRAND_COUPLE * HAIR_TUNE.couple;
+ const k = STRAND_K[j] * cfg.k * HAIR_TUNE.stiff / Math.max(0.35, g), c = STRAND_DAMP * HAIR_TUNE.damp * Math.sqrt(HAIR_TUNE.stiff) / Math.max(0.5, Math.sqrt(g));
+ const v = st.v[j], q = st.p[j];
+ v[0] += (k * (tx - q[0]) - c * v[0]) * h;
+ v[1] += (k * (ty - q[1]) - c * v[1]) * h;
+ q[0] += v[0] * h; q[1] += v[1] * h;
+ }
+ st.p[0] = [...target[0]];
+ }
+ for (let j = 0; j < 4; j++) {
+ const o = [st.p[j][0] - target[j][0], st.p[j][1] - target[j][1]];
+ out[j] = softLimit(o, Math.max(0.5, cfg.max * HAIR_TUNE.reach * Math.max(1, g) * j / 3));
+ }
+ });
+
+ for (const [k, cfg] of Object.entries(HAIR)) {
+ const s = this.hair[k];
+ const a = this.hairAnchor(cfg.at, P);
+ // hanging hair keeps pointing down when the head rolls; plus a light breeze
+ const wind = Math.sin(this.time * 1.3 + cfg.at[0] * 0.01) * 0.6 + Math.sin(this.time * 2.9 + cfg.at[1] * 0.02) * 0.4;
+ const tx = a[0] - Math.sin(roll) * cfg.hang + wind * cfg.max * 0.12;
+ const ty = a[1];
+ if (!s.p) s.p = [tx, ty];
+ const k2 = cfg.k / Math.max(0.35, g), c2 = cfg.c / Math.max(0.5, Math.sqrt(g));
+ for (let i = 0; i < sub; i++) {
+ s.v[0] += (k2 * (tx - s.p[0]) - c2 * s.v[0]) * h;
+ s.v[1] += (k2 * (ty - s.p[1]) - c2 * s.v[1]) * h;
+ s.p[0] += s.v[0] * h; s.p[1] += s.v[1] * h;
+ }
+ const o = [s.p[0] - a[0], s.p[1] - a[1]];
+ clampLen(o, cfg.max * Math.max(1, g));
+ this.out[k] = o;
+ }
+ this.out.gain = 1;
+
+ // pull each fringe strand towards the average of its neighbours so the fringe moves
+ // as one sheet with a little variation, instead of strands splitting apart
+ const O = this.out.strands;
+ for (let pass = 0; pass < HAIR_TUNE.bind; pass++) for (let j = 1; j < 4; j++) {
+ const snap = O.slice(0, FRINGE).map(o => [...o[j]]);
+ for (let i = 0; i < FRINGE; i++) {
+ const l = snap[Math.max(0, i - 1)], r = snap[Math.min(FRINGE - 1, i + 1)];
+ for (const a of [0, 1]) O[i][j][a] = snap[i][a] * 0.5 + (l[a] + r[a]) * 0.25;
+ }
+ }
+
+ // Tassels: a two-joint angular pendulum. The old verlet chain was pulled back to its
+ // drawn shape every substep, which made it buzz (~10 direction changes/s, 1deg swing).
+ // Here each joint is a slow damped spring (~0.7 Hz) driven by the smoothed acceleration
+ // of the knot, so it swings in long arcs and lags behind the head like the hair does.
+ for (const ch of this.chains) {
+ const A = tasselAnchor(ch.t, P, this.out, [0, 0]);
+ if (!ch.st) ch.st = { th: [0, 0], w: [0, 0], pos: [...A], vel: [0, 0], acc: [0, 0] };
+ const st = ch.st, T = TASSEL_TUNE;
+ // knot velocity / acceleration, low-passed so spring overshoot of the head doesn't jitter it
+ const vel = [(A[0] - st.pos[0]) / Math.max(dt, 1e-3), (A[1] - st.pos[1]) / Math.max(dt, 1e-3)];
+ const kf = 1 - Math.exp(-dt * T.smooth);
+ const acc = [(vel[0] - st.vel[0]) / Math.max(dt, 1e-3), (vel[1] - st.vel[1]) / Math.max(dt, 1e-3)];
+ st.acc = [st.acc[0] + (acc[0] - st.acc[0]) * kf, st.acc[1] + (acc[1] - st.acc[1]) * kf];
+ st.vel = [st.vel[0] + (vel[0] - st.vel[0]) * kf, st.vel[1] + (vel[1] - st.vel[1]) * kf];
+ st.pos = [...A];
+ // perpendicular to the hanging direction: pushes the pendulum sideways
+ const nrm = [-ch.dir[1], ch.dir[0]];
+ const push = -(st.acc[0] * nrm[0] + st.acc[1] * nrm[1]) / (ch.L1 + ch.L2) * T.inertia;
+ const wind = (Math.sin(this.time * 0.9 + ch.t.pivot[0]) * 0.6 + Math.sin(this.time * 0.37 + ch.t.pivot[1]) * 0.4) * T.wind;
+ const target = -roll * T.hang + wind; // keeps hanging down when the head tilts
+ const w1 = 2 * Math.PI * T.freq / Math.sqrt(Math.max(0.4, g)), w2 = w1 * 1.35;
+ for (let i = 0; i < sub; i++) {
+ const a1 = -w1 * w1 * (st.th[0] - target) - 2 * T.zeta * w1 * st.w[0] + push;
+ st.w[0] += a1 * h; st.th[0] += st.w[0] * h;
+ // the lower half follows the upper one with its own lag (a soft whip at the tip)
+ const a2 = -w2 * w2 * (st.th[1] - st.th[0]) - 2 * T.zeta * w2 * st.w[1] + push * 0.4 + a1 * 0.5;
+ st.w[1] += a2 * h; st.th[1] += st.w[1] * h;
+ }
+ st.th[0] = Math.max(-T.max, Math.min(T.max, st.th[0]));
+ st.th[1] = Math.max(-T.max * 1.4, Math.min(T.max * 1.4, st.th[1]));
+ ch.phi = [st.th[0], st.th[1]];
+ // joint positions for skinning and the debug overlay
+ const d1 = rotV(ch.dir, st.th[0]), d2 = rotV(ch.dir, st.th[1]);
+ const p1 = [A[0] + d1[0] * ch.L1, A[1] + d1[1] * ch.L1];
+ ch.pts = [[...A], p1, [p1[0] + d2[0] * ch.L2, p1[1] + d2[1] * ch.L2]];
+ ch.anchor = A;
+ }
+ this.time += dt;
+ return this.out;
+ }
+ }
+
+ return { Physics };
+}
diff --git a/src/engine/renderer.js b/src/engine/renderer.js
new file mode 100644
index 0000000..0eaced5
--- /dev/null
+++ b/src/engine/renderer.js
@@ -0,0 +1,359 @@
+/** @param {ReturnType<import('./rig.js').createRig>} engine
+ * @param {import('../rig/types').Rig} rig */
+export function createRenderer(engine, _rig) {
+ const { IMG, EYES, MOUTH, CHEEKS } = engine;
+ // WebGL2 renderer: textured grid meshes whose vertices are deformed on the CPU,
+ // plus a fragment-shader pass for eyelids, eye balls, mouth and blush on the base layer.
+
+
+ const VS = `#version 300 es
+ in vec2 aPos; in vec2 aUv;
+ uniform vec2 uScale; uniform vec2 uOffset;
+ out vec2 vUv;
+ void main() { vUv = aUv; gl_Position = vec4(aPos * uScale + uOffset, 0.0, 1.0); }`;
+
+ const FS = `#version 300 es
+ precision highp float;
+ in vec2 vUv; out vec4 outColor;
+ uniform sampler2D uTex;
+ uniform vec4 uRect; // layer rect in source px
+ uniform int uFace;
+ uniform float uAlpha;
+ uniform vec4 uEyeBox[2]; // x0, x1, -, -
+ uniform float uEyeTop[48]; // 2 eyes x EYE_N samples
+ uniform float uEyeBot[48];
+ uniform vec4 uEyeState[2]; // open, smile, ballX(px), ballY(px)
+ uniform vec4 uMouth; // cx, cy, angle, halfLen
+ uniform vec4 uMouthState; // open, form, bow, -
+ uniform vec4 uCheeks; // x0, y0, x1, y1
+ uniform float uCheek;
+
+ const int EYE_N = 24;
+ float crv(int e, bool top, float u) {
+ float f = clamp(u, 0.0, 1.0) * float(EYE_N - 1);
+ int i = min(int(floor(f)), EYE_N - 2);
+ float t = f - float(i);
+ int k = e * EYE_N + i;
+ return top ? mix(uEyeTop[k], uEyeTop[k + 1], t) : mix(uEyeBot[k], uEyeBot[k + 1], t);
+ }
+
+ // Upper lid line and lower lid line of eye e at column u, for the current open/smile state.
+ // Must match eyeLids() in rig.js, which moves the lash meshes to the same lines.
+ // Must match eyeLidsRaw() / eyeLids() in rig.js.
+ vec2 eyeLidsRaw(int e, float u) {
+ u = clamp(u, 0.0, 1.0);
+ vec4 st = uEyeState[e];
+ float top = crv(e, true, u), bot = crv(e, false, u);
+ float b = 1.0 - st.x, smile = st.y, hump = 4.0 * u * (1.0 - u);
+ float H = crv(e, false, 0.5) - crv(e, true, 0.5);
+ float arc = mix(uEyeTop[e * EYE_N], uEyeTop[e * EYE_N + EYE_N - 1], u) - 0.3 * H * hump;
+ float closed = max(top, bot + 1.0 + (arc - bot - 1.0) * smile);
+ return vec2((closed - top) * max(b, -0.07), b > 0.0 ? (closed - bot) * b * smile : 0.0);
+ }
+
+ vec2 eyeLids(int e, float u, float top, float bot) {
+ vec4 box = uEyeBox[e];
+ float du = 5.0 / (box.y - box.x);
+ vec2 raw = eyeLidsRaw(e, u);
+ vec2 d = (eyeLidsRaw(e, u - 2.0 * du) + 2.0 * eyeLidsRaw(e, u - du) + 3.0 * raw
+ + 2.0 * eyeLidsRaw(e, u + du) + eyeLidsRaw(e, u + 2.0 * du)) / 9.0;
+ // for hiding the ball take whichever closes more: the smoothed lash can sit a little
+ // above the raw lid near the corners, and the gap must show lid skin, not eye white
+ return vec2(top + max(d.x, raw.x), bot + min(d.y, raw.y));
+ }
+
+ vec4 texAt(vec2 p) { return texture(uTex, (p - uRect.xy) / uRect.zw); }
+
+ // Eye white + iris layer: shown only between the lids (the lids cover it, it never squashes);
+ // the iris slides inside the opening for the gaze.
+ vec4 eyeBall(int e, vec2 p) {
+ vec4 box = uEyeBox[e]; vec4 st = uEyeState[e];
+ float u = clamp((p.x - box.x) / (box.y - box.x), 0.0, 1.0);
+ float top = crv(e, true, u), bot = crv(e, false, u);
+ vec2 lids = eyeLids(e, u, top, bot);
+ float v = clamp((p.y - top) / max(bot - top, 1.0), 0.0, 1.0);
+ float w = sqrt(4.0 * u * (1.0 - u)) * sqrt(4.0 * v * (1.0 - v));
+ vec4 c = texAt(p - vec2(st.z, st.w) * w);
+ // the lash covers ~2px of the ball's upper edge, so the cut can sit under it (no seam)
+ return c * smoothstep(lids.x - 1.0, lids.x + 0.5, p.y) * (1.0 - smoothstep(lids.y - 0.9, lids.y + 0.6, p.y));
+ }
+
+ vec4 mouth(vec2 p, vec4 base) {
+ float open = uMouthState.x;
+ if (open < 0.01) return base;
+ vec2 d = vec2(cos(uMouth.z), sin(uMouth.z)), n = vec2(-d.y, d.x);
+ vec2 r = p - uMouth.xy;
+ float s = dot(r, d) / uMouth.w, t = dot(r, n);
+ float form = uMouthState.y; // -1 wide "i" .. +1 round "o"
+ float wf = mix(0.78, 0.46, clamp(form * 0.5 + 0.5, 0.0, 1.0));
+ float k = 1.0 - (s / wf) * (s / wf);
+ if (k <= 0.0) return base;
+ float line = uMouthState.z * (1.0 - s * s);
+ float hk = pow(k, mix(0.55, 0.85, clamp(form, 0.0, 1.0)));
+ float H = mix(20.0, 26.0, clamp(form, 0.0, 1.0));
+ float up = line - 0.6 - open * 2.5 * hk;
+ float lo = line + open * H * hk;
+ float cov = smoothstep(-0.7, 0.7, t - up) * smoothstep(-0.7, 0.7, lo - t);
+ if (cov <= 0.0) return base;
+ float tv = clamp((t - up) / max(lo - up, 1.0), 0.0, 1.0);
+ vec3 col = mix(vec3(0.24, 0.05, 0.08), vec3(0.48, 0.15, 0.19), tv);
+ float tongue = smoothstep(0.5, 0.78, tv) * (1.0 - smoothstep(0.45, 0.8, abs(s) / wf));
+ col = mix(col, vec3(0.86, 0.44, 0.47), tongue * 0.9);
+ float teeth = (1.0 - smoothstep(0.12, 0.22, tv)) * smoothstep(0.25, 0.45, open) * (1.0 - smoothstep(0.55, 0.85, abs(s) / wf));
+ col = mix(col, vec3(0.99, 0.96, 0.94), teeth);
+ float rim = 1.0 - smoothstep(0.6, 1.8, lo - t);
+ col = mix(col, vec3(0.36, 0.09, 0.11), rim * 0.85);
+ return vec4(mix(base.rgb, col, cov), 1.0);
+ }
+
+ void main() {
+ vec2 p = uRect.xy + vUv * uRect.zw;
+ vec4 c;
+ if (uFace == 1) {
+ c = mouth(p, texAt(p));
+ float blush = exp(-dot((p - uCheeks.xy) / vec2(48.0, 22.0), (p - uCheeks.xy) / vec2(48.0, 22.0)))
+ + exp(-dot((p - uCheeks.zw) / vec2(40.0, 20.0), (p - uCheeks.zw) / vec2(40.0, 20.0)));
+ c.rgb = mix(c.rgb, c.rgb * vec3(1.0, 0.62, 0.64) , clamp(blush * uCheek * 0.55, 0.0, 1.0) * c.a);
+ } else if (uFace >= 2) {
+ c = eyeBall(uFace - 2, p);
+ } else {
+ c = texAt(p);
+ }
+ outColor = c * uAlpha;
+ }`;
+
+ const LINE_VS = `#version 300 es
+ in vec2 aPos; uniform vec2 uScale; uniform vec2 uOffset;
+ void main() { gl_Position = vec4(aPos * uScale + uOffset, 0.0, 1.0); gl_PointSize = 7.0; }`;
+ const LINE_FS = `#version 300 es
+ precision mediump float; uniform vec4 uColor; out vec4 o; void main() { o = uColor; }`;
+
+ function compile(gl, vs, fs) {
+ const prog = gl.createProgram();
+ for (const [type, src] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
+ const sh = gl.createShader(type);
+ gl.shaderSource(sh, src); gl.compileShader(sh);
+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh));
+ gl.attachShader(prog, sh);
+ gl.deleteShader(sh);
+ }
+ gl.linkProgram(prog);
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
+ const u = {};
+ const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS);
+ for (let i = 0; i < n; i++) {
+ const name = gl.getActiveUniform(prog, i).name.replace('[0]', '');
+ u[name] = gl.getUniformLocation(prog, name);
+ }
+ return { prog, u };
+ }
+
+ // Grid lines along one axis: `cell` spacing, `fine.cell` inside [fine.from, fine.to).
+ function axis(start, len, cell, fine) {
+ const out = [start];
+ let v = start;
+ while (v < start + len - 0.5) {
+ const c = fine && v >= fine.from && v < fine.to ? fine.cell : cell;
+ v = Math.min(start + len, v + c);
+ out.push(v);
+ }
+ return out;
+ }
+
+ // Grid mesh over a layer rect (optionally denser inside `fine`); cells that are fully
+ // transparent are dropped.
+ function buildGrid(rect, cell, alpha, alphaW, fine = null) {
+ const [rx, ry, rw, rh] = rect;
+ const xs = axis(rx, rw, cell, fine && { from: fine.x0, to: fine.x1, cell: fine.cell });
+ const ys = axis(ry, rh, cell, fine && { from: fine.y0, to: fine.y1, cell: fine.cell });
+ const cols = xs.length - 1, rows = ys.length - 1;
+ const nv = (cols + 1) * (rows + 1);
+ const rest = new Float32Array(nv * 2), uv = new Float32Array(nv * 2);
+ for (let j = 0; j <= rows; j++) for (let i = 0; i <= cols; i++) {
+ const k = j * (cols + 1) + i;
+ rest[k * 2] = xs[i]; rest[k * 2 + 1] = ys[j];
+ uv[k * 2] = (xs[i] - rx) / rw; uv[k * 2 + 1] = (ys[j] - ry) / rh;
+ }
+ const tris = [], lines = [];
+ const alphaH = alpha.length / alphaW;
+ // alpha may be a 1x1 stand-in (fully opaque quad)
+ const ax = alphaW === 1 ? 0 : 1;
+ for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) {
+ const x0 = Math.floor(xs[i] - rx) * ax - 2, x1 = Math.ceil(xs[i + 1] - rx) * ax + 2;
+ const y0 = Math.floor(ys[j] - ry) * ax - 2, y1 = Math.ceil(ys[j + 1] - ry) * ax + 2;
+ let any = false;
+ for (let y = Math.max(0, y0); y < Math.min(alphaH, y1) && !any; y += 1)
+ for (let x = Math.max(0, x0); x < Math.min(alphaW, x1); x += 1)
+ if (alpha[y * alphaW + x] > 3) { any = true; break; }
+ if (!any) continue;
+ const a = j * (cols + 1) + i, b = a + 1, c = a + cols + 1, d = c + 1;
+ tris.push(a, b, c, b, d, c);
+ lines.push(a, b, a, c, b, c);
+ if (i === cols - 1) lines.push(b, d);
+ if (j === rows - 1) lines.push(c, d);
+ }
+ return { rect, cols, rows, rest, uv, pos: new Float32Array(rest), tris: new Uint32Array(tris), lines: new Uint32Array(lines) };
+ }
+
+ class Renderer {
+ // padTop / padSide: margin around the image, as a share of its height / width. A negative
+ // padTop pushes the top of the image above the canvas (hides a cut-off top edge).
+ constructor(canvas, { padTop = 0, padSide = 0 } = {}) {
+ this.pad = { top: padTop, side: padSide };
+ const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: true, alpha: true, preserveDrawingBuffer: true });
+ if (!gl) throw new Error('WebGL2 is not available');
+ this.gl = gl; this.canvas = canvas;
+ this.main = compile(gl, VS, FS);
+ this.line = compile(gl, LINE_VS, LINE_FS);
+ this.layers = [];
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ texture(img) {
+ const gl = this.gl, t = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, t);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
+ gl.generateMipmap(gl.TEXTURE_2D);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ return t;
+ }
+
+ addLayer(name, img, mesh, opts = {}) {
+ const gl = this.gl;
+ const vao = gl.createVertexArray();
+ gl.bindVertexArray(vao);
+ const posBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, mesh.pos, gl.DYNAMIC_DRAW);
+ for (const prog of [this.main, this.line]) {
+ const loc = gl.getAttribLocation(prog.prog, 'aPos');
+ gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
+ }
+ const uvBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, uvBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, mesh.uv, gl.STATIC_DRAW);
+ const uvLoc = gl.getAttribLocation(this.main.prog, 'aUv');
+ gl.enableVertexAttribArray(uvLoc); gl.vertexAttribPointer(uvLoc, 2, gl.FLOAT, false, 0, 0);
+ const triBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, triBuf);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.tris, gl.STATIC_DRAW);
+ gl.bindVertexArray(null);
+ const lineBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, lineBuf);
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.lines, gl.STATIC_DRAW);
+ const layer = { name, mesh, tex: this.texture(img), vao, posBuf, uvBuf, triBuf, lineBuf, visible: true, face: !!opts.face, eyeBall: opts.eyeBall, color: opts.color || [1, 1, 1, 1] };
+ this.layers.push(layer);
+ return layer;
+ }
+
+ destroy() {
+ const gl = this.gl;
+ for (const layer of this.layers) {
+ gl.deleteTexture(layer.tex);
+ gl.deleteVertexArray(layer.vao);
+ for (const buffer of [layer.posBuf, layer.uvBuf, layer.triBuf, layer.lineBuf]) gl.deleteBuffer(buffer);
+ }
+ gl.deleteProgram(this.main.prog);
+ gl.deleteProgram(this.line.prog);
+ this.layers.length = 0;
+ }
+
+ resize() {
+ const c = this.canvas, dpr = Math.min(window.devicePixelRatio || 1, 2);
+ const w = Math.round(c.clientWidth * dpr), h = Math.round(c.clientHeight * dpr);
+ if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
+ // fit the source image, anchored to the bottom so the cut-off body stays at the edge
+ const s = Math.min(w / (IMG.w * (1 + 2 * this.pad.side)), h / (IMG.h * (1 + this.pad.top)));
+ const ox = (w - IMG.w * s) / 2, oy = h - IMG.h * s;
+ this.scale = [2 * s / w, -2 * s / h];
+ this.offset = [-1 + 2 * ox / w, 1 - 2 * oy / h];
+ this.pxScale = s; this.pxOff = [ox, oy];
+ }
+
+ draw(state) {
+ const gl = this.gl;
+ this.resize();
+ gl.viewport(0, 0, this.canvas.width, this.canvas.height);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ const m = this.main;
+ gl.useProgram(m.prog);
+ gl.uniform2fv(m.u.uScale, this.scale); gl.uniform2fv(m.u.uOffset, this.offset);
+ gl.uniform1i(m.u.uTex, 0);
+ gl.uniform4fv(m.u.uEyeBox, EYES.flatMap(e => [e.x0, e.x1, 0, 0]));
+ gl.uniform1fv(m.u.uEyeTop, EYES.flatMap(e => e.top));
+ gl.uniform1fv(m.u.uEyeBot, EYES.flatMap(e => e.bot));
+ gl.uniform4fv(m.u.uEyeState, state.eyes);
+ gl.uniform4f(m.u.uMouth, MOUTH.cx, MOUTH.cy, MOUTH.angle, MOUTH.halfLen);
+ gl.uniform4f(m.u.uMouthState, state.mouthOpen, state.mouthForm, MOUTH.bow, 0);
+ gl.uniform4f(m.u.uCheeks, CHEEKS[0][0], CHEEKS[0][1], CHEEKS[1][0], CHEEKS[1][1]);
+ gl.uniform1f(m.u.uCheek, state.cheek);
+ gl.activeTexture(gl.TEXTURE0);
+
+ for (const L of this.layers) {
+ if (!L.visible || L.overlay) continue;
+ this.drawLayer(L, L.alpha ?? 1);
+ }
+ if (this.original && state.originalAlpha > 0) this.drawLayer(this.original, state.originalAlpha);
+
+ if (state.showMesh) {
+ const l = this.line;
+ gl.useProgram(l.prog);
+ gl.uniform2fv(l.u.uScale, this.scale); gl.uniform2fv(l.u.uOffset, this.offset);
+ for (const L of this.layers) {
+ if (!L.visible || L.overlay) continue;
+ gl.bindVertexArray(L.vao);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, L.lineBuf);
+ gl.uniform4fv(l.u.uColor, L.color);
+ gl.drawElements(gl.LINES, L.mesh.lines.length, gl.UNSIGNED_INT, 0);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, L.triBuf);
+ }
+ if (state.joints?.length) this.drawPoints(state.joints);
+ gl.bindVertexArray(null);
+ }
+ }
+
+ drawLayer(L, alpha) {
+ const gl = this.gl, m = this.main;
+ gl.useProgram(m.prog);
+ gl.bindVertexArray(L.vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, L.posBuf);
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, L.mesh.pos);
+ gl.bindTexture(gl.TEXTURE_2D, L.tex);
+ gl.uniform4fv(m.u.uRect, L.mesh.rect);
+ gl.uniform1i(m.u.uFace, L.eyeBall !== undefined ? 2 + L.eyeBall : L.face ? 1 : 0);
+ gl.uniform1f(m.u.uAlpha, alpha);
+ gl.drawElements(gl.TRIANGLES, L.mesh.tris.length, gl.UNSIGNED_INT, 0);
+ }
+
+ drawPoints(pts) {
+ const gl = this.gl, l = this.line;
+ if (!this.pointBuf) {
+ this.pointBuf = gl.createBuffer();
+ this.pointVao = gl.createVertexArray();
+ gl.bindVertexArray(this.pointVao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.pointBuf);
+ const loc = gl.getAttribLocation(l.prog, 'aPos');
+ gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
+ }
+ gl.bindVertexArray(this.pointVao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.pointBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pts.flat()), gl.DYNAMIC_DRAW);
+ gl.uniform4f(l.u.uColor, 1, 0.85, 0.2, 1);
+ gl.drawArrays(gl.POINTS, 0, pts.length);
+ }
+
+ // canvas CSS px -> source image px
+ toImage(cx, cy) {
+ if (!this.pxOff) return null; // pointer moved before the first frame was drawn
+ const dpr = this.canvas.width / this.canvas.clientWidth;
+ return [(cx * dpr - this.pxOff[0]) / this.pxScale, (cy * dpr - this.pxOff[1]) / this.pxScale];
+ }
+ }
+ return { Renderer, buildGrid };
+}
diff --git a/src/engine/rig.js b/src/engine/rig.js
new file mode 100644
index 0000000..431f386
--- /dev/null
+++ b/src/engine/rig.js
@@ -0,0 +1,299 @@
+export const PARAMS = [
+ { id: 'ParamAngleX', label: 'Face angle X', min: -30, max: 30, def: 0, group: 'Head and body' },
+ { id: 'ParamAngleY', label: 'Face angle Y', min: -30, max: 30, def: 0, group: 'Head and body' },
+ { id: 'ParamAngleZ', label: 'Face roll', min: -30, max: 30, def: 0, group: 'Head and body' },
+ { id: 'ParamBodyAngleX', label: 'Body angle X', min: -10, max: 10, def: 0, group: 'Head and body' },
+ { id: 'ParamBodyAngleZ', label: 'Body roll', min: -10, max: 10, def: 0, group: 'Head and body' },
+ { id: 'ParamBreath', label: 'Breath', min: 0, max: 1, def: 0, group: 'Head and body' },
+ { id: 'ParamEyeLOpen', label: 'Left eye open', min: 0, max: 1.25, def: 1, group: 'Eyes and brows' },
+ { id: 'ParamEyeROpen', label: 'Right eye open', min: 0, max: 1.25, def: 1, group: 'Eyes and brows' },
+ { id: 'ParamEyeSmile', label: 'Eye smile', min: 0, max: 1, def: 0, group: 'Eyes and brows' },
+ { id: 'ParamEyeBallX', label: 'Gaze X', min: -1, max: 1, def: 0, group: 'Eyes and brows' },
+ { id: 'ParamEyeBallY', label: 'Gaze Y', min: -1, max: 1, def: 0, group: 'Eyes and brows' },
+ { id: 'ParamBrowY', label: 'Brow Y', min: -1, max: 1, def: 0, group: 'Eyes and brows' },
+ { id: 'ParamBrowAngle', label: 'Brow angle', min: -1, max: 1, def: 0, group: 'Eyes and brows' },
+ { id: 'ParamMouthOpenY', label: 'Mouth open', min: 0, max: 1, def: 0, group: 'Mouth and cheeks' },
+ { id: 'ParamMouthForm', label: 'Mouth form (i to o)', min: -1, max: 1, def: 0, group: 'Mouth and cheeks' },
+ { id: 'ParamCheek', label: 'Blush', min: 0, max: 1, def: 0, group: 'Mouth and cheeks' },
+ { id: 'ParamArmAngle', label: 'Arm angle', min: -10, max: 10, def: 0, group: 'Hand' },
+ { id: 'ParamHandAngle', label: 'Wrist angle', min: -10, max: 10, def: 0, group: 'Hand' },
+ { id: 'ParamFingerTap', label: 'Finger tap', min: 0, max: 1, def: 0, group: 'Hand' },
+];
+
+// Reference algorithms are intentionally retained as JavaScript; the factory's rig input
+// and public TypeScript adapter are typed, with numerical regression covering this port.
+/** @param {import('../rig/types').Rig} rig */
+export function createRig(rig) {
+ const IMG = { w: rig.image.width, h: rig.image.height };
+ const gaussian = (x, y, a) => a ? Math.exp(-(((x - a.cx) / a.rx) ** 2 + ((y - a.cy) / a.ry) ** 2)) : 0;
+ // ---- face features ----
+ // Eye openings come from layers.json ("eyes", written when the layers were cut): the top / bottom edge of
+ // the visible eye white + iris, sampled at EYE_N evenly spaced columns from corner to corner.
+ const EYE_N = 24;
+ const EYES = rig.eyes;
+
+ function sampled(arr, u) {
+ const f = Math.min(1, Math.max(0, u)) * (EYE_N - 1), i = Math.min(Math.floor(f), EYE_N - 2), t = f - i;
+ return arr[i] + (arr[i + 1] - arr[i]) * t;
+ }
+
+ // Raw lid lines at column u for the current state; must match eyeLidsRaw() in the shader.
+ // plain closing: the upper lid comes down onto the lower lid
+ // smiling (^^): both lids meet on an upward arc from corner to corner
+ function eyeLidsRaw(e, u, open, smile) {
+ u = Math.min(1, Math.max(0, u));
+ const top = sampled(e.top, u), bot = sampled(e.bot, u);
+ const b = 1 - open, hump = 4 * u * (1 - u);
+ const H = sampled(e.bot, 0.5) - sampled(e.top, 0.5);
+ const arc = e.top[0] + (e.top[EYE_N - 1] - e.top[0]) * u - 0.3 * H * hump;
+ const closed = Math.max(top, bot + 1 + (arc - bot - 1) * smile);
+ // wide-open (open > 1) only lifts the lash a few px: there is no drawn eye white above it
+ return [(closed - top) * Math.max(b, -0.07), b > 0 ? (closed - bot) * b * smile : 0];
+ }
+
+ // Lid movement is smoothed across columns: the opening's edge is very steep at the corners,
+ // and following it exactly bent the lash into a zigzag there.
+ const LID_TAPS = [[-2, 1], [-1, 2], [0, 3], [1, 2], [2, 1]], LID_STEP = 5;
+ function eyeLids(e, x, open, smile) {
+ let du = 0, db = 0;
+ for (const [k, w] of LID_TAPS) {
+ const [a, c] = eyeLidsRaw(e, (x + k * LID_STEP - e.x0) / (e.x1 - e.x0), open, smile);
+ du += a * w / 9; db += c * w / 9;
+ }
+ const u = Math.min(1, Math.max(0, (x - e.x0) / (e.x1 - e.x0)));
+ const top = sampled(e.top, u), bot = sampled(e.bot, u);
+ return { top, bot, b: 1 - open, lid: top + du, bc: bot + db };
+ }
+
+ // Rest-space y of an eye-part vertex for the current eye state. The upper lash slides down
+ // to the lid line and thins a little; the lower lash rises for smiling eyes; the crease
+ // follows the lid a little (the lid skin stretches).
+ function eyePartY(e, part, x, y, open, smile) {
+ const L = eyeLids(e, x, open, smile);
+ if (part === 'lash') return L.lid - (L.top - y) * (1 - 0.3 * Math.min(1, Math.max(0, L.b)));
+ if (part === 'low') return y + (L.bc - L.bot);
+ if (part === 'crease') return y + (L.lid - L.top) * 0.22;
+ return y;
+ }
+
+ // The lower lash fades out as smiling eyes close, so the arc reads as one line, not two;
+ // the crease softens as the lid stretches.
+ function eyePartAlpha(part, open, smile) {
+ const b = Math.min(1, Math.max(0, 1 - open));
+ if (part === 'low') return 1 - Math.min(1, b * smile * 1.2);
+ if (part === 'crease') return 1 - 0.45 * b;
+ return 1;
+ }
+
+ // Closed mouth line runs from (599,579) to (672,556) and bows down ~5.5px.
+ const MOUTH = rig.mouth;
+ const CHEEKS = rig.cheeks;
+
+ // ---- mesh deformers ----
+ // The turn field is a smooth bump over the head. It is deliberately larger than the
+ // 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 sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+
+ function headWeight(x, y) { return 1 - sstep(...HEAD.weightBand, y); }
+ // The turn bump already fades out towards its rim, so it only needs a gentle cut-off
+ // (stacking both fades is what sheared the neck).
+ function turnWeight(x, y) { return 1 - sstep(...HEAD.turnBand, y); }
+
+ // Hair strands: rest polylines root -> tip (4 nodes each), traced from the drawing.
+ // Each one is a small spring chain in physics.js; vertices follow the strands near them.
+ const STRANDS = rig.strands ?? [];
+
+ // distance to a polyline and the normalised position t (0 root .. 1 tip) of the closest point
+ function onPolyline(x, y, nodes) {
+ let best = Infinity, bt = 0;
+ const n = nodes.length - 1;
+ for (let i = 0; i < n; i++) {
+ const [ax, ay] = nodes[i], [bx, by] = nodes[i + 1];
+ const vx = bx - ax, vy = by - ay;
+ const u = Math.min(1, Math.max(0, ((x - ax) * vx + (y - ay) * vy) / (vx * vx + vy * vy)));
+ const d = Math.hypot(x - ax - vx * u, y - ay - vy * u);
+ if (d < best) { best = d; bt = (i + u) / n; }
+ }
+ return [best, bt];
+ }
+
+ // Sparse list of [strand index, weight, t]. Weights of overlapping strands are shared so
+ // the region between two strands blends their motions instead of adding them.
+ function strandWeights(x, y, hair) {
+ if (hair < 0.02) return [];
+ const hits = [];
+ let sum = 0;
+ STRANDS.forEach((s, i) => {
+ const [d, t] = onPolyline(x, y, s.nodes);
+ const g = Math.exp(-((d / s.sigma) ** 2));
+ if (g < 0.02) return;
+ hits.push([i, g, t]); sum += g;
+ });
+ const norm = Math.max(1, sum);
+ return hits.map(([i, g, t]) => [i, hair * g / norm * sstep(0.04, 0.55, t), t]);
+ }
+
+ // Per-vertex weights of the base layer, computed once from the rest position.
+ // hair: 0..1 from hairmask.png, so strands only move actual hair.
+ function baseWeights(x, y, hair = 1) {
+ return {
+ head: headWeight(x, y),
+ turn: turnWeight(x, y),
+ strands: strandWeights(x, y, hair),
+ bunL: gaussian(x, y, rig.buns?.bunL),
+ bunR: gaussian(x, y, rig.buns?.bunR),
+ brow: gaussian(x, y, rig.face.brow) * (1 - sstep(...rig.face.brow.band, y)),
+ // chin below the mouth line drops a little when the mouth opens
+ jaw: gaussian(x, y, rig.face.jaw) * sstep(...rig.face.jaw.band, y),
+ // per-feature depth for head turns (nose sticks out most, ears sit at the back)
+ nose: gaussian(x, y, rig.face.nose),
+ mouth: gaussian(x, y, rig.face.mouth),
+ eyeA: gaussian(x, y, rig.face.eyeA),
+ eyeB: gaussian(x, y, rig.face.eyeB),
+ earR: gaussian(x, y, rig.face.earR),
+ earL: gaussian(x, y, rig.face.earL),
+ chest: gaussian(x, y, BODY.chest),
+ breath: 1 - sstep(...BODY.breathBand, y),
+ shoulder: BODY.shoulders.reduce((sum, area) => sum + gaussian(x, y, area), 0),
+ };
+ }
+
+ // Head turn: features near the face centre travel further than the contour.
+ // (A sphere projection was tried first; its rim has an infinite slope and kinked
+ // the hair strands and fingers it crossed.)
+ function turnOffset(x, y, ax, ay) {
+ const nx = (x - HEAD.cx) / HEAD.rx, ny = (y - HEAD.cy) / HEAD.ry;
+ const t = 1 - nx * nx - ny * ny;
+ if (t <= 0) return [0, 0];
+ // flat top over eyes/nose/mouth (r < ~0.4) so they move as one piece; all the
+ // stretching needed for parallax happens on the cheeks, contour and hair
+ const d = sstep(0, 0.84, t);
+ return [ax * HEAD.shiftX * d, -ay * HEAD.shiftY * d];
+ }
+
+ function rotateAround(p, cx, cy, a) {
+ const c = Math.cos(a), s = Math.sin(a), dx = p[0] - cx, dy = p[1] - cy;
+ p[0] = cx + dx * c - dy * s; p[1] = cy + dx * s + dy * c;
+ }
+
+ // Head transform with weight w (0 = body, 1 = fully head). Mutates p.
+ function applyHead(p, w, P, wTurn = w) {
+ const o = turnOffset(p[0], p[1], P.ParamAngleX / 30, P.ParamAngleY / 30);
+ p[0] += o[0] * wTurn; p[1] += o[1] * wTurn;
+ if (w <= 0) return;
+ rotateAround(p, HEAD.pivotX, HEAD.pivotY, -P.ParamAngleZ / 30 * HEAD.maxRoll * w);
+ }
+
+ function applyBody(p, restY, P, chest = 0, breathW = 1, shoulder = 0) {
+ const b = P.ParamBreath;
+ // inhale: everything above the cut-off rises, shoulders lift more, the chest widens a little
+ p[1] -= b * (5 * breathW + 4 * shoulder);
+ p[0] += (p[0] - BODY.chest.cx) * 0.012 * b * chest;
+ p[0] += P.ParamBodyAngleX / 10 * (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.ParamBodyAngleZ / 10 * BODY.maxRoll * (1 - sstep(...BODY.rollBand, restY)));
+ }
+
+ // 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;
+ const g = phys.gain;
+ for (const [i, wi, t] of w.strands) {
+ const o = phys.strands?.[i];
+ if (!o) continue;
+ const f = t * 3, k = Math.min(2, Math.floor(f)), u = f - k;
+ p[0] += (o[k][0] + (o[k + 1][0] - o[k][0]) * u) * wi * g;
+ p[1] += (o[k][1] + (o[k + 1][1] - o[k][1]) * u) * wi * g;
+ }
+ p[0] += (phys.bunL[0] * w.bunL + phys.bunR[0] * w.bunR) * g;
+ p[1] += (phys.bunL[1] * w.bunL + phys.bunR[1] * w.bunR) * g;
+ // brows
+ p[1] -= P.ParamBrowY * 7 * w.brow;
+ if (w.brow > 0.01) {
+ const a = P.ParamBrowAngle * 0.12 * w.brow;
+ p[1] += (x - rig.face.brow.cx) * Math.sin(a);
+ }
+ p[1] += P.ParamMouthOpenY * 3.5 * w.jaw;
+ // head turn, per part: nose and mouth travel further than the eyes, the far eye
+ // narrows and the near eye widens, the ears and buns slide the other way
+ const ax = P.ParamAngleX / 30, ay = P.ParamAngleY / 30;
+ p[0] += ax * (8 * w.nose + 5 * w.mouth) + (x - rig.face.eyeA.cx) * 0.12 * ax * w.eyeA - (x - rig.face.eyeB.cx) * 0.12 * ax * w.eyeB
+ - ax * 9 * w.earR + ax * 4 * w.earL - ax * 10 * (w.bunL + w.bunR);
+ 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);
+ return p;
+ }
+
+ // ---- hand / forearm ----
+ // Two rigid bones (forearm about the elbow, hand about the wrist) instead of letting the
+ // head's warp field bend them. The forearm takes only part of the swing, because whatever
+ // it uncovers is inpainted; the wrist does the rest so the fingertips stay on the chin.
+ const H = rig.hand;
+ const ELBOW = H?.elbow ?? [0, 0], WRIST = H?.wrist ?? [0, 0];
+ const KNUCKLE = H?.knuckle ?? [0, 0], CONTACT = H?.contact ?? [0, 0];
+ const FOREARM_SHARE = H?.forearmShare ?? 0;
+
+ function handWeights(x, y) {
+ if (!H) return { arm: 0, wrist: 0, hand: 0, finger: 0, pinBottom: 0 };
+ return {
+ arm: 1 - sstep(...H.armBand, y),
+ wrist: 1 - sstep(...H.wristBand, y),
+ hand: 1 - sstep(...H.handBand, y),
+ finger: sstep(...H.fingerXBand, x) * (1 - sstep(...H.fingerYBand, y)),
+ pinBottom: sstep(...H.pinBand, y),
+ };
+ }
+
+ const rot = (p, o, c, s) => { const dx = p[0] - o[0], dy = p[1] - o[1]; return [o[0] + dx * c - dy * s, o[1] + dx * s + dy * c]; };
+ const angleOf = v => Math.atan2(v[1], v[0]);
+
+ // Per-frame bone transforms of the hand layer.
+ function handFrame(P) {
+ const c = [...CONTACT];
+ applyHead(c, headWeight(...CONTACT), P, turnWeight(...CONTACT));
+ applyBody(c, CONTACT[1], P, 0, 1, 0);
+ const e = [...ELBOW];
+ applyBody(e, ELBOW[1], P, 0, 0, 0);
+ const full = angleOf([c[0] - e[0], c[1] - e[1]]) - angleOf([CONTACT[0] - ELBOW[0], CONTACT[1] - ELBOW[1]]);
+ const a = full * FOREARM_SHARE;
+ const ca = Math.cos(a), sa = Math.sin(a);
+ const tr = p => { const q = rot(p, ELBOW, ca, sa); return [q[0] + e[0] - ELBOW[0], q[1] + e[1] - ELBOW[1]]; };
+ const w = tr(WRIST), c1 = tr(CONTACT);
+ const b = angleOf([c[0] - w[0], c[1] - w[1]]) - angleOf([c1[0] - w[0], c1[1] - w[1]]);
+ const k = Math.min(1.03, Math.max(0.97, Math.hypot(c[0] - w[0], c[1] - w[1]) / Math.hypot(c1[0] - w[0], c1[1] - w[1])));
+ return { tr, w, b, k };
+ }
+
+ function deformHand(x, y, w, P, F, out) {
+ let p = [x, y];
+ // kept small on purpose: anything the hand uncovers is only a blurry inpaint
+ p = rot(p, KNUCKLE, Math.cos(P.ParamFingerTap * 0.07 * w.finger), Math.sin(P.ParamFingerTap * 0.07 * w.finger));
+ const ha = -P.ParamHandAngle / 10 * 0.045 * w.wrist, aa = -P.ParamArmAngle / 10 * 0.015 * w.arm;
+ p = rot(p, WRIST, Math.cos(ha), Math.sin(ha));
+ p = rot(p, ELBOW, Math.cos(aa), Math.sin(aa));
+ p = F.tr(p);
+ // wrist bone, blended in across the wrist so the joint bends smoothly
+ const bw = F.b * w.hand, kw = 1 + (F.k - 1) * w.hand;
+ p = rot(p, F.w, Math.cos(bw) * kw, Math.sin(bw) * kw);
+ // the arm is cut by the image edge: keep that edge on the edge
+ p[1] += (y - p[1]) * w.pinBottom;
+ out[0] = p[0]; out[1] = p[1];
+ return out;
+ }
+
+ // ---- tassels (2-bone chains driven by physics) ----
+ const TASSELS = rig.accessories ?? [];
+
+ // Where the tassel hangs from, after head/body deformation.
+ function tasselAnchor(t, P, phys, out) {
+ 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 };
+}
diff --git a/src/engine/sprites.js b/src/engine/sprites.js
new file mode 100644
index 0000000..1cf7e2d
--- /dev/null
+++ b/src/engine/sprites.js
@@ -0,0 +1,171 @@
+/** @param {ReturnType<import('./rig.js').createRig>} engine
+ * @param {import('../rig/types').Rig} rig */
+export function createSpriteModule(engine, rig) {
+ const { baseWeights, deformBase, MOUTH } = engine;
+ // Drawn eye / mouth variants (public/avatar/miko-qipao/sprites/, cut from full-size drawings) laid over the
+ // face. Closed eyes and open mouths are what the single image does not contain, so instead of
+ // faking them with shaders these are swapped in like the frames of an anime blink / lip flap.
+ // The sprite meshes follow the same head / body deformation as the face.
+
+
+ const sstep = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+
+ // Mouth opening area (the region the mouth drawings were painted in): used to squash only
+ // the inside of the mouth sprite, the skin at its edge stays put.
+ const MOUTH_AREA = rig.mouth.area;
+ // Mouth shapes. ParamMouthForm is the vowel axis: -1 wide (i) .. 0 (a) .. +1 round (u/o);
+ // ParamMouthOpenY how far it opens. Each shape names the drawing it uses, the openness that
+ // drawing shows at full size, and a width factor (u is a narrowed o).
+ const MOUTH_SHAPES = {
+ a: { sprite: 'mouth_a', ref: 0.9, width: 1 },
+ aHalf: { sprite: 'mouth_a_half', ref: 0.55, width: 1 },
+ i: { sprite: 'mouth_i', ref: 0.55, width: 1 },
+ e: { sprite: 'mouth_a_half', ref: 0.65, width: 1.06 },
+ o: { sprite: 'mouth_o', ref: 0.75, width: 1 },
+ u: { sprite: 'mouth_o', ref: 0.75, width: 0.78 },
+ };
+ // below this the drawn closed mouth of the original image is shown (a barely open mouth
+ // drawing looked like a stuck, oddly shaped mouth)
+ const MOUTH_OPEN_MIN = 0.16;
+
+ // Vowel regions on the form axis, with a little hysteresis so the drawing does not flicker
+ // when the form hovers on a boundary.
+ function classifyVowel(form, prev) {
+ const pad = 0.07;
+ const inside = (v, lo, hi) => v >= lo - (prev ? pad : 0) && v < hi + (prev ? pad : 0);
+ const regions = [['i', -9, -0.55], ['e', -0.55, -0.2], ['a', -0.2, 0.35], ['o', 0.35, 0.75], ['u', 0.75, 9]];
+ const was = prev && regions.find(r => r[0] === prev || (prev === 'aHalf' && r[0] === 'a'));
+ if (was && inside(form, was[1], was[2])) return was[0];
+ return regions.find(r => form >= r[1] && form < r[2])[0];
+ }
+
+ // Eyes switch between drawings like anime frames: the original open eye (never with shifted
+ // lids: lowering the cut-out lash left seams at the corners), the drawn half-closed eye,
+ // and the drawn closed / smiling eye.
+ const EYE_OPEN_MIN = 0.75, EYE_CLOSED_MAX = 0.3, EYE_FADE_SEC = 0.06;
+
+ function eyeSprite(open, smile) {
+ if (open >= EYE_OPEN_MIN) return null;
+ if (open < EYE_CLOSED_MAX) return smile >= 0.5 ? 'eyes_smile' : 'eyes_closed';
+ return 'eyes_half';
+ }
+
+ function mouthShape(open, form, prev = null) {
+ if (open < MOUTH_OPEN_MIN) return null;
+ const v = classifyVowel(form, prev);
+ if (v === 'a') return open >= 0.6 ? 'a' : 'aHalf';
+ return v;
+ }
+
+ function mouthLineY(x) {
+ return MOUTH.cy + (x - MOUTH.cx) * Math.tan(MOUTH.angle);
+ }
+
+ function mouthCenterX() { return MOUTH_AREA.cx; }
+
+ function mouthInner(x, y) {
+ const c = Math.cos(-MOUTH_AREA.angle), s = Math.sin(-MOUTH_AREA.angle);
+ const dx = x - MOUTH_AREA.cx, dy = y - MOUTH_AREA.cy;
+ const u = (dx * c - dy * s) / MOUTH_AREA.rx, v = (dx * s + dy * c) / MOUTH_AREA.ry;
+ return 1 - sstep(0.55, 0.95, Math.hypot(u, v));
+ }
+
+ /**
+ * @param R Renderer
+ * @param sheet parsed sprites.json ({ build, layers: { name: [x, y, w, h] } })
+ * @param imgs { name: HTMLImageElement }
+ * @param buildGrid, alphaOf helpers from the renderer / page
+ */
+ function createSprites(R, sheet, imgs, buildGrid, alphaOf) {
+ const items = {};
+ // draw order matters for the cross-fades: half-closed under closed / smiling (the fade-in frame is drawn on top)
+ const order = n => (n.startsWith('eyes_half') ? 0 : n.startsWith('eyes_') ? 1 : 2);
+ const entries = Object.entries(sheet.layers).sort((x, y) => order(x[0]) - order(y[0]));
+ for (const [name, rect] of entries) {
+ const mesh = buildGrid(rect, rig.mesh.spriteCell, alphaOf(imgs[name]), imgs[name].width);
+ const W = [], inner = [];
+ for (let k = 0; k < mesh.rest.length / 2; k++) {
+ const x = mesh.rest[k * 2], y = mesh.rest[k * 2 + 1];
+ W.push(baseWeights(x, y, 0));
+ inner.push(name.startsWith('mouth') ? mouthInner(x, y) : 0);
+ }
+ const layer = R.addLayer(name, imgs[name], mesh, { color: [0.4, 1, 0.8, 0.6] });
+ layer.visible = false;
+ items[name] = { mesh, W, inner, layer };
+ }
+ const tmp = [0, 0];
+ let lastShape = null;
+ const eyeState = [0, 1].map(() => ({ cur: 'open', prev: 'open', t: 1 }));
+
+ function place(item, P, phys, squash, width = 1) {
+ const r = item.mesh.rest, o = item.mesh.pos;
+ for (let k = 0; k < item.W.length; k++) {
+ let x = r[k * 2];
+ let y = r[k * 2 + 1];
+ const w = item.inner[k];
+ if (w > 0) {
+ const line = mouthLineY(x);
+ y = line + (y - line) * (1 + (squash - 1) * w);
+ x = mouthCenterX() + (x - mouthCenterX()) * (1 + (width - 1) * w);
+ }
+ deformBase(x, y, item.W[k], P, phys, tmp);
+ o[k * 2] = tmp[0]; o[k * 2 + 1] = tmp[1];
+ }
+ }
+
+ return {
+ /**
+ * Show / hide and deform the sprites for this frame.
+ * Returns which eyes are covered by a sprite, so the layered eye parts can be hidden.
+ */
+ update(P, phys, dt = 1 / 60) {
+ for (const it of Object.values(items)) it.layer.visible = false;
+ const covered = [false, false];
+ const eyes = [
+ [P.ParamEyeROpen, P.ParamEyeSmile],
+ [P.ParamEyeLOpen, P.eyeSmileL ?? P.ParamEyeSmile],
+ ];
+ // the frame is picked by openness; when it changes, the new drawing fades in over
+ // EYE_FADE_SEC (a time-based cross-fade, so no double image is ever held)
+ eyes.forEach(([open, smile], i) => {
+ const st = eyeState[i];
+ const want = eyeSprite(open, smile) ?? 'open';
+ if (want !== st.cur) { st.prev = st.cur; st.cur = want; st.t = 0; }
+ st.t = Math.min(1, st.t + dt / EYE_FADE_SEC);
+ const k = sstep(0, 1, st.t);
+ const show = (name, alpha) => {
+ if (name === 'open' || alpha <= 0.001) return;
+ const it = items[`${name}_${i}`];
+ if (!it) return;
+ it.layer.visible = true;
+ it.layer.alpha = alpha;
+ place(it, P, phys, 1);
+ };
+ // the outgoing frame stays fully drawn underneath while the new one fades in on top;
+ // fading out to the open eye works the other way round
+ // whichever frame is drawn higher up (closed/smile above half, both above the open eye)
+ // does the fading, the lower one stays solid, so the eye is never see-through
+ const rank = n => (n === 'open' ? -1 : n === 'eyes_half' ? 0 : 1);
+ if (st.t >= 1) show(st.cur, 1);
+ else if (rank(st.cur) > rank(st.prev)) { show(st.prev, 1); show(st.cur, k); }
+ else { show(st.cur, 1); show(st.prev, 1 - k); }
+ covered[i] = st.cur !== 'open' && k >= 0.999;
+ });
+ const shape = mouthShape(P.ParamMouthOpenY, P.ParamMouthForm, lastShape);
+ lastShape = shape;
+ const def = shape && MOUTH_SHAPES[shape];
+ const mt = def && items[def.sprite];
+ if (mt) {
+ mt.layer.visible = true;
+ // fade in right above the threshold so the closed line hands over softly
+ mt.layer.alpha = sstep(MOUTH_OPEN_MIN, MOUTH_OPEN_MIN + 0.04, P.ParamMouthOpenY);
+ // never squash a drawing below half its height: flatter looked like a blob
+ const squash = Math.min(1.1, Math.max(0.5, P.ParamMouthOpenY / def.ref));
+ place(mt, P, phys, squash, def.width);
+ }
+ return { eyes: covered, mouth: shape };
+ },
+ };
+ }
+ return { createSprites, mouthShape, eyeSprite };
+}
diff --git a/src/rig/types.ts b/src/rig/types.ts
new file mode 100644
index 0000000..5fbdd20
--- /dev/null
+++ b/src/rig/types.ts
@@ -0,0 +1,76 @@
+export type Point = [number, number];
+export type Band = [number, number];
+export interface Ellipse { cx: number; cy: number; rx: number; ry: number }
+export interface Eye {
+ opening: Point[];
+ roi: Point[];
+ x0: number;
+ x1: number;
+ top: number[];
+ bot: number[];
+}
+export interface Strand {
+ name: string;
+ nodes: Point[];
+ sigma: number;
+ k: number;
+ max: number;
+}
+export interface Accessory {
+ name: string;
+ pivot: Point;
+ tip: Point;
+ split: number;
+ box: [number, number, number, number];
+ color: { redness: number; minRed: number };
+}
+export interface Hand {
+ outline: Point[];
+ jaw: Point[];
+ jawRange: Band;
+ background: Point[];
+ elbow: Point;
+ wrist: Point;
+ knuckle: Point;
+ contact: Point;
+ forearmShare: number;
+ armBand: Band;
+ wristBand: Band;
+ handBand: Band;
+ fingerXBand: Band;
+ fingerYBand: Band;
+ pinBand: Band;
+}
+export interface Rig {
+ version: 1;
+ image: { width: number; height: number };
+ head: Ellipse & {
+ shiftX: number; shiftY: number; pivotX: number; pivotY: number;
+ maxRoll: number; weightBand: Band; turnBand: Band;
+ };
+ body: {
+ pivotX: number; pivotY: number; maxRoll: number;
+ breathBand: Band; rollBand: Band; chest: Ellipse; shoulders: Ellipse[];
+ };
+ face: Record<'nose' | 'mouth' | 'eyeA' | 'eyeB' | 'earL' | 'earR', Ellipse> & {
+ brow: Ellipse & { band: Band };
+ jaw: Ellipse & { band: Band };
+ };
+ buns?: Partial<Record<'bunL' | 'bunR', Ellipse>>;
+ eyes: Eye[];
+ mouth: {
+ cx: number; cy: number; angle: number; halfLen: number; bow: number;
+ area: Ellipse & { angle: number };
+ };
+ cheeks: Point[];
+ strands?: Strand[];
+ accessories?: Accessory[];
+ hand?: Hand;
+ mesh: {
+ baseCell: number;
+ fine: { x0: number; x1: number; y0: number; y1: number; cell: number };
+ handCell: number; tasselCell: number; eyeBallCell: number;
+ eyeCell: number; spriteCell: number;
+ };
+ view: { padTop: number; padSide: number; gazeCenter?: Point };
+}
diff --git a/src/rig/validate.ts b/src/rig/validate.ts
new file mode 100644
index 0000000..5f87c93
--- /dev/null
+++ b/src/rig/validate.ts
@@ -0,0 +1,102 @@
+import type { Rig } from './types';
+
+type Check = (value: unknown, path: string, errors: string[]) => void;
+const number: Check = (v, p, e) => {
+ if (typeof v !== 'number' || !Number.isFinite(v)) e.push(`${p}: expected a finite number`);
+};
+const positive: Check = (v, p, e) => {
+ number(v, p, e);
+ if (typeof v === 'number' && v <= 0) e.push(`${p}: must be positive`);
+};
+const integer: Check = (v, p, e) => {
+ positive(v, p, e);
+ if (typeof v === 'number' && !Number.isInteger(v)) e.push(`${p}: expected an integer`);
+};
+const string: Check = (v, p, e) => {
+ if (typeof v !== 'string' || !v.trim()) e.push(`${p}: expected a non-empty string`);
+};
+const array = (item: Check, min = 0, max = Infinity): Check => (v, p, e) => {
+ if (!Array.isArray(v)) { e.push(`${p}: expected an array`); return; }
+ if (v.length < min || v.length > max) e.push(`${p}: expected ${min}..${max} items`);
+ v.forEach((x, i) => item(x, `${p}[${i}]`, e));
+};
+const point = array(number, 2, 2);
+const band: Check = (v, p, e) => {
+ point(v, p, e);
+ if (Array.isArray(v) && v.length === 2 && v[0] >= v[1]) e.push(`${p}: start must be less than end`);
+};
+const object = (fields: Record<string, Check>, optional: string[] = []): Check => (v, p, e) => {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) { e.push(`${p}: expected an object`); return; }
+ const record = v as Record<string, unknown>;
+ for (const [key, check] of Object.entries(fields)) {
+ if (record[key] === undefined && optional.includes(key)) continue;
+ check(record[key], `${p}.${key}`, e);
+ }
+};
+const ellipseFields = { cx: number, cy: number, rx: positive, ry: positive };
+const ellipse = object(ellipseFields);
+const polygon = array(point, 3);
+const line = array(point, 2);
+const unit: Check = (v, p, e) => {
+ number(v, p, e);
+ if (typeof v === 'number' && (v < 0 || v > 1)) e.push(`${p}: must be between 0 and 1`);
+};
+const schema = object({
+ version: (v, p, e) => { if (v !== 1) e.push(`${p}: only version 1 is supported`); },
+ image: object({ width: integer, height: integer }),
+ head: object({ ...ellipseFields, shiftX: number, shiftY: number, pivotX: number,
+ pivotY: number, maxRoll: number, weightBand: band, turnBand: band }),
+ body: object({ pivotX: number, pivotY: number, maxRoll: number, breathBand: band,
+ rollBand: band, chest: ellipse, shoulders: array(ellipse) }),
+ face: object({ nose: ellipse, mouth: ellipse, eyeA: ellipse, eyeB: ellipse,
+ earL: ellipse, earR: ellipse, brow: object({ ...ellipseFields, band }),
+ jaw: object({ ...ellipseFields, band }) }),
+ buns: object({ bunL: ellipse, bunR: ellipse }, ['bunL', 'bunR']),
+ eyes: array(object({ opening: polygon, roi: polygon, x0: number, x1: number,
+ top: array(number, 24, 24), bot: array(number, 24, 24) }), 2, 2),
+ mouth: object({ cx: number, cy: number, angle: number, halfLen: positive, bow: number,
+ area: object({ ...ellipseFields, angle: number }) }),
+ cheeks: array(point, 2, 2),
+ strands: array(object({ name: string, nodes: line, sigma: positive, k: positive, max: positive })),
+ accessories: array(object({ name: string, pivot: point, tip: point, split: unit,
+ box: array(number, 4, 4), color: object({ redness: unit, minRed: number }) })),
+ hand: object({ outline: polygon, jaw: line, jawRange: band, background: polygon,
+ elbow: point, wrist: point, knuckle: point, contact: point, forearmShare: unit,
+ armBand: band, wristBand: band, handBand: band, fingerXBand: band,
+ fingerYBand: band, pinBand: band }),
+ mesh: object({ baseCell: positive, fine: object({ x0: number, x1: number,
+ y0: number, y1: number, cell: positive }), handCell: positive,
+ tasselCell: positive, eyeBallCell: positive, eyeCell: positive, spriteCell: positive }),
+ view: object({ padTop: number, padSide: number, gazeCenter: point }, ['gazeCenter']),
+}, ['buns', 'strands', 'accessories', 'hand']);
+
+export function validateRig(value: unknown): string[] {
+ const errors: string[] = [];
+ schema(value, 'rig', errors);
+ if (errors.length) return errors;
+ const rig = value as Rig;
+ rig.eyes.forEach((eye, i) => {
+ if (eye.x0 >= eye.x1) errors.push(`rig.eyes[${i}].x1: must exceed x0`);
+ if (eye.top.some((y, k) => y > eye.bot[k])) errors.push(`rig.eyes[${i}].top: must not exceed bottom curve`);
+ });
+ if (rig.mesh.fine.x0 >= rig.mesh.fine.x1 || rig.mesh.fine.y0 >= rig.mesh.fine.y1)
+ errors.push('rig.mesh.fine: rectangle must have positive area');
+ if (rig.view.padTop <= -1 || rig.view.padTop >= 1 || rig.view.padSide <= -0.5)
+ errors.push('rig.view: margins must leave a positive viewport');
+ for (const [i, strand] of (rig.strands ?? []).entries()) {
+ if (strand.nodes.some((p, j) => j > 0 && p[0] === strand.nodes[j - 1][0] && p[1] === strand.nodes[j - 1][1]))
+ errors.push(`rig.strands[${i}].nodes: consecutive nodes must differ`);
+ }
+ for (const [i, accessory] of (rig.accessories ?? []).entries()) {
+ if (accessory.split <= 0 || accessory.split >= 1) errors.push(`rig.accessories[${i}].split: must be strictly between 0 and 1`);
+ if (accessory.pivot.every((n, k) => n === accessory.tip[k])) errors.push(`rig.accessories[${i}].tip: must differ from pivot`);
+ if (accessory.box[0] >= accessory.box[2] || accessory.box[1] >= accessory.box[3]) errors.push(`rig.accessories[${i}].box: rectangle must have positive area`);
+ }
+ return errors;
+}
+
+export function parseRig(value: unknown): Rig {
+ const errors = validateRig(value);
+ if (errors.length) throw new Error(`Invalid rig:\n${errors.join('\n')}`);
+ return structuredClone(value) as Rig;
+}
diff --git a/tests/engine.test.ts b/tests/engine.test.ts
new file mode 100644
index 0000000..844e3a9
--- /dev/null
+++ b/tests/engine.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { parseRig } from '../src/rig/validate';
+import { createRig, PARAMS } from '../src/engine/rig.js';
+import { createPhysics } from '../src/engine/physics.js';
+
+test('rig instances have isolated coordinates and physics state', () => {
+ const a = parseRig(fixture);
+ const b = parseRig(fixture);
+ b.head.shiftX += 100;
+ const first = createRig(a);
+ const second = createRig(b);
+ const P = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+ P.ParamAngleX = 30;
+ const x = [600, 400];
+ const y = [...x];
+ first.applyHead(x, 1, P);
+ second.applyHead(y, 1, P);
+ expect(x).not.toEqual(y);
+ const { Physics } = createPhysics(first, a);
+ expect(new Physics()).not.toBe(new Physics());
+});
+
+test('missing optional parts and variable strand lengths stay finite', () => {
+ const rig = parseRig(fixture);
+ delete rig.hand;
+ delete rig.buns;
+ rig.accessories = [];
+ rig.strands = [rig.strands![0]];
+ rig.strands[0].nodes.splice(1, 1);
+ const engine = createRig(rig);
+ const { Physics } = createPhysics(engine, rig);
+ const physics = new Physics();
+ const P = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+ const phys = physics.step(P, 1 / 60);
+ const out = engine.deformBase(500, 300, engine.baseWeights(500, 300), P, phys, [0, 0]);
+ expect(out.every(Number.isFinite)).toBe(true);
+ expect(physics.chains).toHaveLength(0);
+});
diff --git a/tests/regression.test.ts b/tests/regression.test.ts
new file mode 100644
index 0000000..90c6db4
--- /dev/null
+++ b/tests/regression.test.ts
@@ -0,0 +1,191 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { PNG } from 'pngjs';
+import { expect, test } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import metadata from '../samples/miko-qipao/built/layers.json';
+import sheet from '../samples/miko-qipao/built/sprites/sprites.json';
+import * as reference from '../reference/engine/rig.js';
+import { buildGrid as rawReferenceGrid } from '../reference/engine/renderer.js';
+import { createSprites as rawReferenceSprites } from '../reference/engine/sprites.js';
+import { Physics as ReferencePhysics } from '../reference/engine/physics.js';
+import type { Rig } from '../src/rig/types';
+import { parseRig } from '../src/rig/validate';
+import { createRig, PARAMS } from '../src/engine/rig.js';
+import { createRenderer } from '../src/engine/renderer.js';
+import { createSpriteModule } from '../src/engine/sprites.js';
+import { createPhysics } from '../src/engine/physics.js';
+
+const rig = parseRig(fixture);
+const engine = createRig(rig);
+type GridBuilder = (rect: number[], cell: number, alpha: Uint8Array, width: number, fine?: Rig['mesh']['fine'] | null) => ReturnType<typeof rawReferenceGrid>;
+// Reference JS defaults/JSDoc infer null/void too narrowly; use structural adapters without altering reference files.
+const referenceGrid = rawReferenceGrid as unknown as GridBuilder;
+const buildGrid = createRenderer(engine, rig).buildGrid as unknown as GridBuilder;
+reference.setEyes(metadata.eyes);
+const defaults: Record<string, number> = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+const poses: Record<string, number>[] = [
+ {},
+ ...[-30, -15, 15, 30].map(ParamAngleX => ({ ParamAngleX })),
+ ...[-15, 15].map(ParamAngleY => ({ ParamAngleY })),
+ ...[-15, 15].map(ParamAngleZ => ({ ParamAngleZ })),
+ { ParamAngleX: -20, ParamAngleY: 10, ParamAngleZ: 15, ParamBodyAngleZ: 8 },
+ { ParamBodyAngleX: 10, ParamBreath: 1 },
+ { ParamBrowY: 1, ParamBrowAngle: 1, ParamMouthOpenY: 1 },
+ { ParamHandAngle: 10, ParamArmAngle: 10, ParamFingerTap: 1 },
+ { ParamAngleX: 20, ParamAngleY: -10, ParamEyeLOpen: 0, ParamEyeROpen: 0.5, ParamEyeSmile: 1 },
+];
+const fixedPhysics = {
+ gain: 0.8,
+ bunL: [1.5, -2],
+ bunR: [-3, 1],
+ strands: rig.strands!.map((_, i) => [[0, 0], [i * 0.2, -0.5], [1, i * 0.1], [-1.3, 2]]),
+};
+const zeroPhysics = { ...fixedPhysics, gain: 0 };
+
+function load(name: string, sprites = false) {
+ return PNG.sync.read(readFileSync(new URL(`../samples/miko-qipao/built/${sprites ? 'sprites/' : ''}${name}.png`, import.meta.url)));
+}
+function alphaOf(image: PNG) {
+ return Uint8Array.from({ length: image.width * image.height }, (_, i) => image.data[i * 4 + 3]);
+}
+type Mesh = ReturnType<typeof referenceGrid>;
+const samplePaths = ['source.png', 'built/base.png', 'built/hairmask.png',
+ ...Object.keys(metadata.layers).map(name => `built/${name}.png`),
+ ...Object.keys(sheet.layers).map(name => `built/sprites/${name}.png`)];
+const samplePresent = samplePaths.every(path => existsSync(new URL(`../samples/miko-qipao/${path}`, import.meta.url)));
+if (!samplePresent) console.info('Matching sample images are not installed; image deformation and sprite regression checks are skipped.');
+const layerMeshes: { name: string; mesh: Mesh }[] = [];
+if (samplePresent) for (const [name, rect] of Object.entries({ base: [0, 0, 1254, 1254], ...metadata.layers, ...sheet.layers })) {
+ const sprites = name.startsWith('mouth') || name.startsWith('eyes_');
+ const image = load(name, sprites);
+ const cell = name === 'base' ? 14 : name === 'hand' ? 9 : name.startsWith('tassel') ? 6 : name.endsWith('ball') || sprites ? 4 : 3;
+ const fine = name === 'base' ? rig.mesh.fine : null;
+ const oldMesh = referenceGrid(rect, cell, alphaOf(image), image.width, fine);
+ const newMesh = buildGrid(rect, cell, alphaOf(image), image.width, fine);
+ expect(newMesh.rest).toEqual(oldMesh.rest);
+ expect(newMesh.tris).toEqual(oldMesh.tris);
+ layerMeshes.push({ name, mesh: oldMesh });
+}
+
+test.skipIf(!samplePresent)('14 poses: every 7px and every layer vertex match base, hand and eye deformation', () => {
+ const points: [number, number][] = [];
+ for (let y = 0; y <= rig.image.height; y += 7)
+ for (let x = 0; x <= rig.image.width; x += 7) points.push([x, y]);
+ for (const { mesh } of layerMeshes)
+ for (let i = 0; i < mesh.rest.length; i += 2) points.push([mesh.rest[i], mesh.rest[i + 1]]);
+ const hair = load('hairmask');
+ const hairAt = (x: number, y: number) => {
+ const i = Math.min(1253, Math.round(y)) * 1254 + Math.min(1253, Math.round(x));
+ return hair.data[i * 4] / 255;
+ };
+ let maximum = 0;
+ const a = [0, 0], b = [0, 0];
+ const compare = () => {
+ const delta = Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]));
+ if (!Number.isFinite(delta)) throw new Error('Non-finite regression output');
+ maximum = Math.max(maximum, delta);
+ };
+ const weights = points.map(([x, y]) => ({
+ old: reference.baseWeights(x, y, hairAt(x, y)),
+ new: engine.baseWeights(x, y, hairAt(x, y)),
+ oldHand: reference.handWeights(x, y),
+ newHand: engine.handWeights(x, y),
+ }));
+ poses.forEach((pose, poseIndex) => {
+ const P: Record<string, number> = { ...defaults, ...pose };
+ const phys = poseIndex === poses.length - 1 ? fixedPhysics : zeroPhysics;
+ const oldFrame = reference.handFrame(P), newFrame = engine.handFrame(P);
+ points.forEach(([x, y], i) => {
+ reference.deformBase(x, y, weights[i].old, P, phys, a);
+ engine.deformBase(x, y, weights[i].new, P, phys, b);
+ compare();
+ reference.deformHand(x, y, weights[i].oldHand, P, oldFrame, a);
+ engine.deformHand(x, y, weights[i].newHand, P, newFrame, b);
+ compare();
+ });
+ // Apply every lid mode on the full 7px grid and all fixture vertices as well.
+ rig.eyes.forEach((eye, eyeIndex) => {
+ const open = eyeIndex === 0 ? P.ParamEyeROpen : P.ParamEyeLOpen;
+ for (const part of ['ball', 'low', 'crease', 'lash']) {
+ points.forEach(([x, y], i) => {
+ reference.deformBase(x, reference.eyePartY(metadata.eyes[eyeIndex], part, x, y, open, P.ParamEyeSmile), weights[i].old, P, phys, a);
+ engine.deformBase(x, engine.eyePartY(eye, part, x, y, open, P.ParamEyeSmile), weights[i].new, P, phys, b);
+ compare();
+ });
+ }
+ });
+ });
+ console.log(`Regression: ${poses.length} poses, ${points.length} sample points, max delta ${maximum} px`);
+ expect(maximum).toBeLessThan(0.01);
+}, 120000);
+
+test.skipIf(!samplePresent)('all drawn eye and mouth sprite meshes match reference placement', () => {
+ const images = Object.fromEntries(Object.keys(sheet.layers).map(name => [name, load(name, true)]));
+ function capture() {
+ const items = new Map<string, { mesh: Mesh; visible: boolean; alpha: number }>();
+ return {
+ items,
+ addLayer(name: string, _image: PNG, mesh: Mesh) {
+ const item = { mesh, visible: true, alpha: 1 };
+ items.set(name, item);
+ return item;
+ },
+ };
+ }
+ type SpriteCreator = (renderer: ReturnType<typeof capture>, metadata: typeof sheet,
+ images: Record<string, PNG>, grid: GridBuilder, alpha: typeof alphaOf) => {
+ update(P: Record<string, number>, physics: typeof fixedPhysics, dt: number): unknown;
+ };
+ const makeSprites = createSpriteModule(engine, rig).createSprites as unknown as SpriteCreator;
+ const oldRenderer = capture(), newRenderer = capture();
+ const makeReferenceSprites = rawReferenceSprites as unknown as typeof makeSprites;
+ const oldSprites = makeReferenceSprites(oldRenderer, sheet, images, referenceGrid, alphaOf);
+ const newSprites = makeSprites(newRenderer, sheet, images, buildGrid, alphaOf);
+ let maximum = 0;
+ const seen = new Set<string>();
+ for (const pose of poses) for (const form of [-1, -0.3, 0, 0.5, 1]) for (const open of [0.25, 0.8]) {
+ const P: Record<string, number> = { ...defaults, ...pose, ParamMouthForm: form, ParamMouthOpenY: open };
+ for (const eyeOpen of [0, 0.5, 1]) {
+ P.ParamEyeLOpen = eyeOpen;
+ P.ParamEyeROpen = eyeOpen;
+ P.ParamEyeSmile = eyeOpen === 0 ? (form > 0 ? 1 : 0) : 0;
+ oldSprites.update(P, fixedPhysics, 0.1);
+ newSprites.update(P, fixedPhysics, 0.1);
+ for (const [name, old] of oldRenderer.items) {
+ const current = newRenderer.items.get(name)!;
+ expect(current.visible).toBe(old.visible);
+ if (!old.visible) continue;
+ seen.add(name);
+ for (let i = 0; i < old.mesh.pos.length; i++) maximum = Math.max(maximum, Math.abs(old.mesh.pos[i] - current.mesh.pos[i]));
+ }
+ }
+ }
+ expect(seen.size).toBe(Object.keys(sheet.layers).length);
+ console.log(`Sprite regression: ${seen.size} layers, max delta ${maximum} px`);
+ expect(maximum).toBeLessThan(0.01);
+}, 120000);
+
+test('physics offsets and tassel joint positions preserve the reference behavior', () => {
+ const old = new ReferencePhysics();
+ const { Physics } = createPhysics(engine, rig);
+ const current = new Physics();
+ let maximum = 0;
+ for (let frame = 0; frame < 120; frame++) {
+ const P = { ...defaults, ParamAngleX: Math.sin(frame / 20) * 30, ParamAngleZ: Math.cos(frame / 15) * 15 };
+ const a = old.step(P, 1 / 60) as unknown as typeof fixedPhysics;
+ const b = current.step(P, 1 / 60) as unknown as typeof fixedPhysics;
+ const flatten = (value: unknown): number[] => {
+ if (typeof value === 'number') return [value];
+ if (Array.isArray(value)) return value.flatMap(flatten);
+ return [];
+ };
+ for (const [first, second] of [[a.strands, b.strands], [a.bunL, b.bunL], [a.bunR, b.bunR],
+ [old.chains.map(c => c.pts), current.chains.map(c => c.pts)]]) {
+ const x = flatten(first), y = flatten(second);
+ expect(x.length).toBe(y.length);
+ x.forEach((v, i) => { maximum = Math.max(maximum, Math.abs(v - y[i])); });
+ }
+ }
+ console.log(`Physics regression: 120 frames, max delta ${maximum} px`);
+ expect(maximum).toBeLessThan(0.01);
+});
diff --git a/tests/rig.test.ts b/tests/rig.test.ts
new file mode 100644
index 0000000..08b7964
--- /dev/null
+++ b/tests/rig.test.ts
@@ -0,0 +1,31 @@
+import { expect, test } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { parseRig, validateRig } from '../src/rig/validate';
+
+test('accepts the reference fixture and optional groups', () => {
+ expect(validateRig(fixture)).toEqual([]);
+ const rig = parseRig(fixture);
+ delete rig.hand;
+ delete rig.buns;
+ delete rig.strands;
+ delete rig.accessories;
+ expect(validateRig(rig)).toEqual([]);
+});
+test('names missing fields and malformed polygons', () => {
+ const missing = { ...fixture, image: { width: 1254 } };
+ expect(validateRig(missing).join()).toContain('rig.image.height');
+ const malformed = structuredClone(fixture);
+ malformed.eyes[0].opening = [[1, 2], [3, 4]];
+ expect(validateRig(malformed).join()).toContain('rig.eyes[0].opening');
+});
+test('rejects nonfinite values, zero radii and degenerate strands', () => {
+ const rig = parseRig(fixture);
+ rig.head.rx = 0;
+ rig.body.pivotX = NaN;
+ expect(validateRig(rig).join()).toContain('rig.head.rx');
+ expect(validateRig(rig).join()).toContain('rig.body.pivotX');
+ rig.head.rx = 430;
+ rig.body.pivotX = 640;
+ rig.strands![0].nodes[1] = rig.strands![0].nodes[0];
+ expect(validateRig(rig).join()).toContain('rig.strands[0].nodes');
+});
diff --git a/tests/sensitivity.test.ts b/tests/sensitivity.test.ts
new file mode 100644
index 0000000..759e826
--- /dev/null
+++ b/tests/sensitivity.test.ts
@@ -0,0 +1,50 @@
+import { expect, test } from 'vitest';
+import fixture from '../samples/miko-qipao/rig.json';
+import { parseRig } from '../src/rig/validate';
+import type { Rig } from '../src/rig/types';
+import { createRig, PARAMS } from '../src/engine/rig.js';
+import { Motion } from '../src/engine/motion.js';
+
+const parameters: Record<string, number> = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+const physics = {
+ gain: 1,
+ bunL: [0, 0],
+ bunR: [0, 0],
+ strands: fixture.strands.map(() => [[0, 0], [4, -2], [7, 3], [8, -4]]),
+};
+
+const cases: { name: string; edit: (rig: Rig) => void; bounds: number[]; hand?: boolean }[] = [
+ { name: 'head turn center', edit: r => { r.head.cx += 20; }, bounds: [800, 950, 200, 550] },
+ { name: 'strand node', edit: r => { r.strands![0].nodes[2][0] += 20; }, bounds: [400, 490, 280, 450] },
+ { name: 'mouth Gaussian', edit: r => { r.face.mouth.cy += 10; }, bounds: [590, 680, 535, 600] },
+ { name: 'wrist bone', edit: r => { r.hand!.wrist[0] += 30; }, bounds: [450, 560, 610, 750], hand: true },
+];
+
+for (const item of cases) test(`${item.name} changes the expected region by more than 0.5px`, () => {
+ const original = parseRig(fixture);
+ const edited = parseRig(fixture);
+ item.edit(edited);
+ const a = createRig(original), b = createRig(edited);
+ const P = { ...parameters, ParamAngleX: 30, ParamHandAngle: 10 };
+ const fa = a.handFrame(P), fb = b.handFrame(P);
+ let maximum = 0;
+ const [x0, x1, y0, y1] = item.bounds;
+ for (let y = y0; y <= y1; y += 7) for (let x = x0; x <= x1; x += 7) {
+ const first = item.hand
+ ? a.deformHand(x, y, a.handWeights(x, y), P, fa, [0, 0])
+ : a.deformBase(x, y, a.baseWeights(x, y), P, physics, [0, 0]);
+ const second = item.hand
+ ? b.deformHand(x, y, b.handWeights(x, y), P, fb, [0, 0])
+ : b.deformBase(x, y, b.baseWeights(x, y), P, physics, [0, 0]);
+ maximum = Math.max(maximum, Math.abs(first[0] - second[0]), Math.abs(first[1] - second[1]));
+ }
+ console.log(`Sensitivity ${item.name}: ${maximum} px`);
+ expect(maximum).toBeGreaterThan(0.5);
+});
+
+test('gaze center comes from the rig or head center', () => {
+ const rig = parseRig(fixture);
+ expect(new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy]).faceCenter).toEqual([615, 470]);
+ delete rig.view.gazeCenter;
+ expect(new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy]).faceCenter).toEqual([615, 400]);
+});