@ikijs/mcp 0.30.0 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,10 @@
7
7
  function lerp(a, b, t) {
8
8
  return a + (b - a) * t;
9
9
  }
10
+ function smoothstep(x) {
11
+ const t = clamp(x, 0, 1);
12
+ return t * t * (3 - 2 * t);
13
+ }
10
14
 
11
15
  // ../engine/src/parameter-store.ts
12
16
  var ParameterStore = class {
@@ -1099,6 +1103,10 @@ void main() {
1099
1103
  return loc;
1100
1104
  }
1101
1105
 
1106
+ // ../format/src/animations.ts
1107
+ var IDLE_MOTION_GROUP = "Idle";
1108
+ var DEFAULT_FADE_SECONDS = 0.4;
1109
+
1102
1110
  // ../format/src/parameters.ts
1103
1111
  var StandardParameter = {
1104
1112
  /** Mouth open amount for lip-sync (0 closed .. 1 open). */
@@ -1170,6 +1178,11 @@ void main() {
1170
1178
  ArmPoseAngleRight: "ParamArmPoseAngleR"
1171
1179
  };
1172
1180
 
1181
+ // ../format/src/physics.ts
1182
+ function physicsInputs(rig) {
1183
+ return rig.inputs ?? [rig.input];
1184
+ }
1185
+
1173
1186
  // ../format/src/validate-animations.ts
1174
1187
  var IDLE_PROCEDURAL = /* @__PURE__ */ new Set([
1175
1188
  StandardParameter.EyeOpenLeft,
@@ -1179,17 +1192,854 @@ void main() {
1179
1192
  ]);
1180
1193
 
1181
1194
  // ../engine/src/frame-clock.ts
1195
+ var MAX_DT_MS = 100;
1182
1196
  var FIXED_DT_S = 1 / 60;
1197
+ var MAX_SUBSTEPS = 6;
1198
+ var FixedStepClock = class {
1199
+ prevNowMs = void 0;
1200
+ accumulatorS = 0;
1201
+ /**
1202
+ * True until the first {@link advance}. Drivers seed their rest pose on that
1203
+ * frame and integrate nothing, so a model loaded mid-motion does not kick.
1204
+ */
1205
+ get isSeedFrame() {
1206
+ return this.prevNowMs === void 0;
1207
+ }
1208
+ /**
1209
+ * Time carried in the accumulator, in seconds: how far the frame's timestamp is
1210
+ * past the last whole sub-step. Drivers extrapolate their state by it so what
1211
+ * they emit is the state at the frame's time, not at the last sub-step.
1212
+ */
1213
+ get remainderS() {
1214
+ return this.accumulatorS;
1215
+ }
1216
+ /**
1217
+ * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}
1218
+ * sub-steps to run this frame. On the seed frame it only records the
1219
+ * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.
1220
+ */
1221
+ advance(nowMs) {
1222
+ if (!Number.isFinite(nowMs)) return 0;
1223
+ if (this.prevNowMs === void 0) {
1224
+ this.prevNowMs = nowMs;
1225
+ return 0;
1226
+ }
1227
+ const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);
1228
+ this.prevNowMs = nowMs;
1229
+ this.accumulatorS += dtMs / 1e3;
1230
+ let steps = 0;
1231
+ while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {
1232
+ this.accumulatorS -= FIXED_DT_S;
1233
+ steps++;
1234
+ }
1235
+ return steps;
1236
+ }
1237
+ };
1183
1238
 
1184
1239
  // ../engine/src/idle-motion.ts
1240
+ var BLINK_INTERVAL_MIN_MS = 1500;
1241
+ var BLINK_INTERVAL_MAX_MS = 6e3;
1185
1242
  var BLINK_CLOSE_MS = 60;
1186
1243
  var BLINK_HOLD_MS = 20;
1187
1244
  var BLINK_OPEN_MS = 100;
1188
1245
  var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
1246
+ var BREATH_PERIOD_MS = 3500;
1247
+ var GAZE_RADIUS = 0.3;
1248
+ var GAZE_RETARGET_MIN_MS = 1200;
1249
+ var GAZE_RETARGET_MAX_MS = 3e3;
1250
+ var GAZE_EASE_RATE = 1e-3;
1251
+ var SWAY_X_AMP_A_DEG = 2.2;
1252
+ var SWAY_X_PERIOD_A_MS = 6100;
1253
+ var SWAY_X_AMP_B_DEG = 1.3;
1254
+ var SWAY_X_PERIOD_B_MS = 9700;
1255
+ var SWAY_Y_AMP_DEG = 1.6;
1256
+ var SWAY_Y_PERIOD_MS = 7300;
1257
+ var SWAY_Z_AMP_DEG = 1.1;
1258
+ var SWAY_Z_PERIOD_MS = 11300;
1259
+ var AMBIENT_AMP_A = 0.6;
1260
+ var AMBIENT_PERIOD_A_MS = 2900;
1261
+ var AMBIENT_AMP_B = 0.4;
1262
+ var AMBIENT_PERIOD_B_MS = 4300;
1263
+ function blinkEnvelope(phase) {
1264
+ const ms = phase * BLINK_DURATION_MS;
1265
+ if (ms <= 0) return 1;
1266
+ if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);
1267
+ if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0;
1268
+ if (ms < BLINK_DURATION_MS) {
1269
+ const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;
1270
+ return 1 - (1 - t) * (1 - t);
1271
+ }
1272
+ return 1;
1273
+ }
1274
+ function randomInDisk(rng, radius) {
1275
+ const r = Math.sqrt(rng()) * radius;
1276
+ const theta = rng() * 2 * Math.PI;
1277
+ return [r * Math.cos(theta), r * Math.sin(theta)];
1278
+ }
1279
+ var IdleMotion = class {
1280
+ /**
1281
+ * Every parameter id {@link update} and `emitRestingPose` write, in write
1282
+ * order. Published so a host (or IkiMotion) can restore them after it
1283
+ * stops driving — keep in step with those two methods; the test suite
1284
+ * pins this list to the actual emissions.
1285
+ */
1286
+ drivenParameterIds = [
1287
+ StandardParameter.EyeOpenLeft,
1288
+ StandardParameter.EyeOpenRight,
1289
+ StandardParameter.Breath,
1290
+ StandardParameter.EyeballX,
1291
+ StandardParameter.EyeballY,
1292
+ StandardParameter.AngleX,
1293
+ StandardParameter.AngleY,
1294
+ StandardParameter.AngleZ,
1295
+ StandardParameter.AmbientSway
1296
+ ];
1297
+ sink;
1298
+ rng;
1299
+ // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.
1300
+ // This is the only clock blink/breath/gaze scheduling reads.
1301
+ clockMs = 0;
1302
+ prevNowMs = void 0;
1303
+ // Blink state
1304
+ nextBlinkAtMs;
1305
+ blinkStartMs = -1;
1306
+ // -1 means not currently blinking
1307
+ // Gaze state
1308
+ gazeCurrentX = 0;
1309
+ gazeCurrentY = 0;
1310
+ gazeTargetX = 0;
1311
+ gazeTargetY = 0;
1312
+ nextGazeRetargetMs;
1313
+ constructor(sink, options) {
1314
+ this.sink = sink;
1315
+ this.rng = options?.rng ?? Math.random;
1316
+ this.nextBlinkAtMs = lerp(
1317
+ BLINK_INTERVAL_MIN_MS,
1318
+ BLINK_INTERVAL_MAX_MS,
1319
+ this.rng()
1320
+ );
1321
+ this.nextGazeRetargetMs = lerp(
1322
+ GAZE_RETARGET_MIN_MS,
1323
+ GAZE_RETARGET_MAX_MS,
1324
+ this.rng()
1325
+ );
1326
+ }
1327
+ /**
1328
+ * Advance the idle animation to the given wall-clock timestamp (milliseconds).
1329
+ *
1330
+ * On the first call: record prevNowMs, emit the resting pose, and return —
1331
+ * no animation advance happens so there is no jump from time 0.
1332
+ *
1333
+ * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)
1334
+ * and advance the internal clock by dt. A non-monotonic nowMs produces a
1335
+ * negative raw delta that the clamp floors to 0 — no rewind.
1336
+ */
1337
+ update(nowMs) {
1338
+ if (!Number.isFinite(nowMs)) return;
1339
+ if (this.prevNowMs === void 0) {
1340
+ this.prevNowMs = nowMs;
1341
+ this.emitRestingPose();
1342
+ return;
1343
+ }
1344
+ const rawDt = nowMs - this.prevNowMs;
1345
+ const dt = clamp(rawDt, 0, MAX_DT_MS);
1346
+ this.prevNowMs = nowMs;
1347
+ this.clockMs += dt;
1348
+ const eyeVal = this.advanceBlink();
1349
+ this.sink(StandardParameter.EyeOpenLeft, eyeVal);
1350
+ this.sink(StandardParameter.EyeOpenRight, eyeVal);
1351
+ const breath = this.advanceBreath();
1352
+ this.advanceGaze(dt);
1353
+ this.sink(StandardParameter.Breath, breath);
1354
+ this.sink(StandardParameter.EyeballX, this.gazeCurrentX);
1355
+ this.sink(StandardParameter.EyeballY, this.gazeCurrentY);
1356
+ this.sink(StandardParameter.AngleX, this.swayX());
1357
+ this.sink(StandardParameter.AngleY, this.swayY());
1358
+ this.sink(StandardParameter.AngleZ, this.swayZ());
1359
+ this.sink(StandardParameter.AmbientSway, this.ambientSway());
1360
+ }
1361
+ // ---------------------------------------------------------------------------
1362
+ // Private helpers
1363
+ // ---------------------------------------------------------------------------
1364
+ emitRestingPose() {
1365
+ this.sink(StandardParameter.EyeOpenLeft, 1);
1366
+ this.sink(StandardParameter.EyeOpenRight, 1);
1367
+ this.sink(StandardParameter.Breath, 0.5);
1368
+ this.sink(StandardParameter.EyeballX, 0);
1369
+ this.sink(StandardParameter.EyeballY, 0);
1370
+ this.sink(StandardParameter.AngleX, 0);
1371
+ this.sink(StandardParameter.AngleY, 0);
1372
+ this.sink(StandardParameter.AngleZ, 0);
1373
+ this.sink(StandardParameter.AmbientSway, 0);
1374
+ }
1375
+ /** Returns the current eye-open value (0..1) and advances blink state. */
1376
+ advanceBlink() {
1377
+ const { clockMs } = this;
1378
+ if (this.blinkStartMs >= 0) {
1379
+ const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;
1380
+ if (phase >= 1) {
1381
+ this.blinkStartMs = -1;
1382
+ this.nextBlinkAtMs = clockMs + lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());
1383
+ return 1;
1384
+ }
1385
+ return blinkEnvelope(phase);
1386
+ }
1387
+ if (clockMs >= this.nextBlinkAtMs) {
1388
+ this.blinkStartMs = clockMs;
1389
+ return blinkEnvelope(0);
1390
+ }
1391
+ return 1;
1392
+ }
1393
+ advanceBreath() {
1394
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * this.clockMs / BREATH_PERIOD_MS);
1395
+ }
1396
+ /** Horizontal head sway in degrees, pure function of the internal clock. */
1397
+ swayX() {
1398
+ const t = 2 * Math.PI * this.clockMs;
1399
+ return SWAY_X_AMP_A_DEG * Math.sin(t / SWAY_X_PERIOD_A_MS) + SWAY_X_AMP_B_DEG * Math.sin(t / SWAY_X_PERIOD_B_MS);
1400
+ }
1401
+ /** Vertical head sway in degrees, pure function of the internal clock. */
1402
+ swayY() {
1403
+ return SWAY_Y_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Y_PERIOD_MS);
1404
+ }
1405
+ /** Head roll sway in degrees, pure function of the internal clock. */
1406
+ swayZ() {
1407
+ return SWAY_Z_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Z_PERIOD_MS);
1408
+ }
1409
+ /** Ambient sway (-1..1), pure function of the internal clock. */
1410
+ ambientSway() {
1411
+ const t = 2 * Math.PI * this.clockMs;
1412
+ return AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) + AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS);
1413
+ }
1414
+ /** Ease gaze current toward target; pick a new target on the internal clock. */
1415
+ advanceGaze(dt) {
1416
+ if (this.clockMs >= this.nextGazeRetargetMs) {
1417
+ const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);
1418
+ this.gazeTargetX = tx;
1419
+ this.gazeTargetY = ty;
1420
+ this.nextGazeRetargetMs = this.clockMs + lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());
1421
+ }
1422
+ const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);
1423
+ this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);
1424
+ this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);
1425
+ }
1426
+ };
1427
+
1428
+ // ../engine/src/physics-motion.ts
1429
+ function signedNormalized(value, param) {
1430
+ const rest = clamp(param.default, param.min, param.max);
1431
+ const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));
1432
+ if (den === 0) return 0;
1433
+ return clamp((value - rest) / den, -1, 1);
1434
+ }
1435
+ var PhysicsMotion = class {
1436
+ /** The output parameter of every rig, in rig order — what `emit` writes. */
1437
+ drivenParameterIds;
1438
+ /**
1439
+ * Per rig: how many times the finiteness guard reset its state or `emit`
1440
+ * replaced its non-finite product. Up to two per frame, so guard activations,
1441
+ * not repaired frames. A diagnostic; emitted values are unchanged.
1442
+ */
1443
+ resets;
1444
+ resetCounts;
1445
+ rigs;
1446
+ inputs;
1447
+ read;
1448
+ sink;
1449
+ params;
1450
+ // Integrator state, owned here — never stored in a ParameterStore.
1451
+ state;
1452
+ clock = new FixedStepClock();
1453
+ constructor(rigs, params, read, sink) {
1454
+ this.rigs = rigs;
1455
+ this.inputs = rigs.map(
1456
+ (rig) => physicsInputs(rig).map(({ parameter, weight: weight2, mode }) => ({
1457
+ parameter,
1458
+ weight: weight2,
1459
+ lag: mode === "lag"
1460
+ }))
1461
+ );
1462
+ this.read = read;
1463
+ this.sink = sink;
1464
+ this.params = new Map(params.map((p) => [p.id, p]));
1465
+ this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));
1466
+ this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);
1467
+ this.resetCounts = rigs.map(() => 0);
1468
+ this.resets = this.resetCounts;
1469
+ }
1470
+ /**
1471
+ * Advance every rig to the given wall-clock timestamp (milliseconds).
1472
+ *
1473
+ * First call: seed each spring to rest AT its current target (so a model
1474
+ * loaded with a nonzero input does not kick: a lag input emits rest, a follow
1475
+ * input its value), emit that output, and return without integrating —
1476
+ * mirroring IdleMotion's first-frame behavior.
1477
+ *
1478
+ * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its
1479
+ * last output from its stored state without reading its inputs.
1480
+ *
1481
+ * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into
1482
+ * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;
1483
+ * the spring advances that many semi-implicit Euler steps, then each rig emits
1484
+ * its output once. The clock's dt clamp and sub-step cap plus the symplectic
1485
+ * integrator are what keep it stable across hitches.
1486
+ */
1487
+ update(nowMs) {
1488
+ if (this.clock.isSeedFrame) {
1489
+ this.clock.advance(nowMs);
1490
+ for (let i = 0; i < this.rigs.length; i++) {
1491
+ const st = this.state[i];
1492
+ const { target, lag } = this.targetFor(i);
1493
+ st.x = target;
1494
+ st.v = 0;
1495
+ st.lag = lag;
1496
+ this.emit(i, st);
1497
+ }
1498
+ return;
1499
+ }
1500
+ if (!Number.isFinite(nowMs)) {
1501
+ for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);
1502
+ return;
1503
+ }
1504
+ const steps = this.clock.advance(nowMs);
1505
+ const targets = this.rigs.map((_, i) => this.targetFor(i));
1506
+ for (let s = 0; s < steps; s++) {
1507
+ for (let i = 0; i < this.rigs.length; i++) {
1508
+ this.step(this.rigs[i], this.state[i], targets[i].target);
1509
+ }
1510
+ }
1511
+ for (let i = 0; i < this.rigs.length; i++) {
1512
+ const st = this.state[i];
1513
+ const { target, lag } = targets[i];
1514
+ if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {
1515
+ st.x = Number.isFinite(target) ? target : 0;
1516
+ st.v = 0;
1517
+ this.resetCounts[i]++;
1518
+ }
1519
+ st.lag = lag;
1520
+ this.emit(i, st);
1521
+ }
1522
+ }
1523
+ /**
1524
+ * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,
1525
+ * and `L`, the lag inputs' share of it. Reads each input once.
1526
+ */
1527
+ targetFor(index) {
1528
+ let target = 0;
1529
+ let lag = 0;
1530
+ for (const input of this.inputs[index]) {
1531
+ const param = this.params.get(input.parameter);
1532
+ const value = this.read(input.parameter);
1533
+ const share = (param ? signedNormalized(value, param) : 0) * input.weight;
1534
+ target += share;
1535
+ if (input.lag) lag += share;
1536
+ }
1537
+ return { target, lag };
1538
+ }
1539
+ /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */
1540
+ step(rig, st, target) {
1541
+ const accel = (rig.stiffness * (target - st.x) - rig.damping * st.v) / rig.mass;
1542
+ st.v += accel * FIXED_DT_S;
1543
+ st.x += st.v * FIXED_DT_S;
1544
+ }
1545
+ /** Write outputDefault + (x − L) * scale onto the output param via the sink. */
1546
+ emit(index, st) {
1547
+ const rig = this.rigs[index];
1548
+ const outParam = this.params.get(rig.output.parameter);
1549
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
1550
+ const x = st.x + st.v * this.clock.remainderS;
1551
+ const value = outDefault + (x - st.lag) * rig.output.scale;
1552
+ const finite = Number.isFinite(value);
1553
+ if (!finite) this.resetCounts[index]++;
1554
+ this.sink(rig.output.parameter, finite ? value : outDefault);
1555
+ }
1556
+ };
1189
1557
 
1190
1558
  // ../engine/src/hair-chain-motion.ts
1191
1559
  var DEG2RAD = Math.PI / 180;
1192
1560
  var RAD2DEG = 180 / Math.PI;
1561
+ var HairChainMotion = class {
1562
+ /** Every segment's output, chain by chain — what `emitSegment` writes. */
1563
+ drivenParameterIds;
1564
+ /**
1565
+ * Per segment, in `drivenParameterIds` order: how many times the finiteness
1566
+ * guard reset its state or `emitSegment` replaced its non-finite product. Up
1567
+ * to two per frame, so guard activations, not repaired frames. A diagnostic;
1568
+ * emitted values are unchanged.
1569
+ */
1570
+ resets;
1571
+ resetCounts;
1572
+ chainData;
1573
+ params;
1574
+ deformers;
1575
+ store;
1576
+ read;
1577
+ sink;
1578
+ clock = new FixedStepClock();
1579
+ constructor(chains, params, deformers, read, sink) {
1580
+ this.params = new Map(params.map((p) => [p.id, p]));
1581
+ this.deformers = deformers;
1582
+ this.store = new ParameterStore(params);
1583
+ this.read = read;
1584
+ this.sink = sink;
1585
+ this.chainData = chains.map((chain) => ({
1586
+ chain,
1587
+ restAnglesRad: chain.segments.map(
1588
+ (seg) => seg.restAngle !== void 0 ? seg.restAngle * DEG2RAD : 0
1589
+ ),
1590
+ state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 }))
1591
+ }));
1592
+ this.drivenParameterIds = chains.flatMap(
1593
+ (c) => c.segments.map((s) => s.output.parameter)
1594
+ );
1595
+ this.resetCounts = this.drivenParameterIds.map(() => 0);
1596
+ this.resets = this.resetCounts;
1597
+ }
1598
+ /**
1599
+ * Advance every chain to the given wall-clock timestamp (milliseconds).
1600
+ *
1601
+ * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output
1602
+ * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's
1603
+ * first-frame behavior so a model loaded in motion does not kick.
1604
+ *
1605
+ * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into
1606
+ * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE
1607
+ * per update() — NOT per chain — so all chains share a consistent frame snapshot.
1608
+ * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover
1609
+ * time is carried to the next frame. Segments emit after substeps (even on zero
1610
+ * substeps) with a non-finite guard.
1611
+ */
1612
+ update(nowMs) {
1613
+ if (this.chainData.length === 0) return;
1614
+ if (this.clock.isSeedFrame) {
1615
+ this.clock.advance(nowMs);
1616
+ let flat2 = 0;
1617
+ for (const cd of this.chainData) {
1618
+ for (let i = 0; i < cd.chain.segments.length; i++) {
1619
+ cd.state[i].angle = 0;
1620
+ cd.state[i].angularVelocity = 0;
1621
+ this.emitSegment(flat2++, cd.chain.segments[i], cd.state[i]);
1622
+ }
1623
+ }
1624
+ return;
1625
+ }
1626
+ const steps = this.clock.advance(nowMs);
1627
+ for (const param of this.params.values()) {
1628
+ this.store.set(param.id, this.read(param.id));
1629
+ }
1630
+ const worldMap = resolveDeformers(this.deformers, this.store).worlds;
1631
+ const anchorAnglesRad = this.chainData.map(
1632
+ (cd) => this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer)
1633
+ );
1634
+ for (let s = 0; s < steps; s++) {
1635
+ for (let c = 0; c < this.chainData.length; c++) {
1636
+ this.stepChain(this.chainData[c], anchorAnglesRad[c]);
1637
+ }
1638
+ }
1639
+ let flat = 0;
1640
+ for (const cd of this.chainData) {
1641
+ for (let i = 0; i < cd.chain.segments.length; i++) {
1642
+ const st = cd.state[i];
1643
+ if (!Number.isFinite(st.angle) || !Number.isFinite(st.angularVelocity)) {
1644
+ st.angle = 0;
1645
+ st.angularVelocity = 0;
1646
+ this.resetCounts[flat]++;
1647
+ }
1648
+ this.emitSegment(flat++, cd.chain.segments[i], st);
1649
+ }
1650
+ }
1651
+ }
1652
+ /**
1653
+ * Extract world rotation (radians) from the anchor's Affine tuple.
1654
+ * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).
1655
+ *
1656
+ * If the anchor id is absent from the map, THROWS an internal Error — the
1657
+ * format validator guarantees the anchor exists, so absence is an invariant
1658
+ * break (mirrors resolveDeformers' throw on an unresolved parent).
1659
+ */
1660
+ anchorWorldAngleRad(worldMap, anchorId) {
1661
+ const world = worldMap.get(anchorId);
1662
+ if (!world) {
1663
+ throw new Error(
1664
+ `HairChainMotion: anchor deformer "${anchorId}" not found in resolved world map \u2014 model not validated?`
1665
+ );
1666
+ }
1667
+ return Math.atan2(world[1], world[0]);
1668
+ }
1669
+ /**
1670
+ * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.
1671
+ *
1672
+ * Segments are integrated ROOT→TIP so each segment can read its upstream
1673
+ * neighbor's current-substep state when computing the world angle Φ_i.
1674
+ * (The chain is causal root-to-tip; reversing the order would use stale θ
1675
+ * values from the previous substep for Φ_i computation.)
1676
+ *
1677
+ * Per-segment semi-implicit (symplectic) Euler:
1678
+ * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)
1679
+ * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i
1680
+ * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)
1681
+ * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)
1682
+ *
1683
+ * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear
1684
+ * in the spring term, only in Φ_i for the gravity torque.
1685
+ */
1686
+ stepChain(cd, anchorAngleRad) {
1687
+ const { chain, restAnglesRad, state } = cd;
1688
+ const gravityAngleRad = chain.gravity.angle * DEG2RAD;
1689
+ const strength = chain.gravity.strength;
1690
+ let worldAngleAccumRad = anchorAngleRad;
1691
+ for (let i = 0; i < chain.segments.length; i++) {
1692
+ const seg = chain.segments[i];
1693
+ const st = state[i];
1694
+ worldAngleAccumRad += restAnglesRad[i] + st.angle;
1695
+ const phi = worldAngleAccumRad;
1696
+ const alpha = (-seg.stiffness * st.angle - strength * Math.sin(phi - gravityAngleRad) - seg.damping * st.angularVelocity) / seg.mass;
1697
+ st.angularVelocity += alpha * FIXED_DT_S;
1698
+ st.angle += st.angularVelocity * FIXED_DT_S;
1699
+ }
1700
+ }
1701
+ /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */
1702
+ emitSegment(flat, seg, st) {
1703
+ const outParam = this.params.get(seg.output.parameter);
1704
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
1705
+ const value = outDefault + st.angle * RAD2DEG * seg.output.scale;
1706
+ const finite = Number.isFinite(value);
1707
+ if (!finite) this.resetCounts[flat]++;
1708
+ this.sink(seg.output.parameter, finite ? value : outDefault);
1709
+ }
1710
+ };
1711
+
1712
+ // ../engine/src/clip-player.ts
1713
+ function curveSlopes(keys) {
1714
+ const slopes = keys.map(() => 0);
1715
+ for (let i = 1; i < keys.length - 1; i++) {
1716
+ const [t0, v0] = keys[i - 1];
1717
+ const [t1, v1] = keys[i];
1718
+ const [t2, v2] = keys[i + 1];
1719
+ const h0 = t1 - t0;
1720
+ const h1 = t2 - t1;
1721
+ const s0 = (v1 - v0) / h0;
1722
+ const s1 = (v2 - v1) / h1;
1723
+ const p = (s0 * h1 + s1 * h0) / (h0 + h1);
1724
+ slopes[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), Math.abs(p) / 2);
1725
+ }
1726
+ return slopes;
1727
+ }
1728
+ function sampleCurve(keys, t, slopes) {
1729
+ const first = keys[0];
1730
+ if (t <= first[0]) return first[1];
1731
+ const last = keys[keys.length - 1];
1732
+ if (t >= last[0]) return last[1];
1733
+ let i = 1;
1734
+ while (keys[i][0] <= t) i++;
1735
+ const [t0, v0] = keys[i - 1];
1736
+ const [t1, v1] = keys[i];
1737
+ const h = t1 - t0;
1738
+ const u = (t - t0) / h;
1739
+ if (!slopes) return lerp(v0, v1, u);
1740
+ return lerp(v0, v1, smoothstep(u)) + h * u * (1 - u) * (slopes[i - 1] * (1 - u) - slopes[i] * u);
1741
+ }
1742
+ function fadeWeights(clip, t) {
1743
+ const fallback = Math.min(DEFAULT_FADE_SECONDS, clip.duration / 2);
1744
+ const fadeIn = clip.fadeIn ?? fallback;
1745
+ const fadeOut = clip.fadeOut ?? fallback;
1746
+ return {
1747
+ wIn: fadeIn > 0 ? smoothstep(t / fadeIn) : 1,
1748
+ wOut: fadeOut > 0 ? smoothstep((clip.duration - t) / fadeOut) : 1
1749
+ };
1750
+ }
1751
+ var ClipPlayer = class {
1752
+ /** True when the model declares the {@link IDLE_MOTION_GROUP} group. */
1753
+ hasIdleLoop;
1754
+ /** Every curve parameter across all groups, deduplicated, insertion-ordered. */
1755
+ parameterIds;
1756
+ motions;
1757
+ params;
1758
+ /** Key slopes of every `"smooth"` curve; a linear curve has no entry. */
1759
+ slopes;
1760
+ idleClips;
1761
+ idleLength;
1762
+ idleIndex = 0;
1763
+ /** Seconds into the current Idle clip. */
1764
+ idleTime = 0;
1765
+ slot = void 0;
1766
+ constructor(motions, parameters) {
1767
+ this.motions = motions ?? {};
1768
+ this.params = new Map(parameters.map((p) => [p.id, p]));
1769
+ this.hasIdleLoop = Object.hasOwn(this.motions, IDLE_MOTION_GROUP);
1770
+ this.idleClips = this.hasIdleLoop ? this.motions[IDLE_MOTION_GROUP] : [];
1771
+ this.idleLength = this.idleClips.reduce((sum, c) => sum + c.duration, 0);
1772
+ const curves = Object.values(this.motions).flatMap(
1773
+ (clips) => clips.flatMap((c) => c.curves)
1774
+ );
1775
+ this.parameterIds = [...new Set(curves.map((curve) => curve.parameter))];
1776
+ this.slopes = new Map(
1777
+ curves.filter((curve) => curve.interpolation !== "linear").map((curve) => [curve, curveSlopes(curve.keys)])
1778
+ );
1779
+ }
1780
+ /**
1781
+ * Start clip `index` of `group` at once, replacing any running one-shot.
1782
+ * Returns false, and changes nothing, for a group the model does not declare
1783
+ * or an index that is not an integer in range. Any group plays one-shot,
1784
+ * Idle included.
1785
+ */
1786
+ play(group, index) {
1787
+ if (!Object.hasOwn(this.motions, group)) return false;
1788
+ const clips = this.motions[group];
1789
+ if (!Number.isInteger(index) || index < 0 || index >= clips.length) {
1790
+ return false;
1791
+ }
1792
+ const from = this.slot?.last ?? /* @__PURE__ */ new Map();
1793
+ this.slot = { clip: clips[index], t: 0, from, last: from };
1794
+ return true;
1795
+ }
1796
+ /**
1797
+ * Advance `dtS` seconds and write into `frame`: the Idle loop layer, then
1798
+ * the one-shot slot over it.
1799
+ *
1800
+ * `frame` holds what earlier stages wrote this update. An id's base is its
1801
+ * frame value, else `rest(id)` — the parameter's resting value,
1802
+ * `clamp(default, min, max)`. The base is never the store's current value,
1803
+ * so a clip cannot accumulate across frames.
1804
+ */
1805
+ apply(dtS, frame, rest) {
1806
+ if (this.hasIdleLoop) this.applyIdle(dtS, frame);
1807
+ if (this.slot) this.applySlot(this.slot, dtS, frame, rest);
1808
+ }
1809
+ /**
1810
+ * The Idle clips play as one continuous loop, so their fades are ignored:
1811
+ * fading each clip at its seams would dip the pose toward rest on every
1812
+ * clip boundary.
1813
+ */
1814
+ applyIdle(dtS, frame) {
1815
+ const clips = this.idleClips;
1816
+ let clip = clips[this.idleIndex];
1817
+ this.idleTime += dtS;
1818
+ if (this.idleTime >= clip.duration) {
1819
+ this.idleTime %= this.idleLength;
1820
+ for (let step = 0; step < clips.length && this.idleTime >= clip.duration; step++) {
1821
+ this.idleTime -= clip.duration;
1822
+ this.idleIndex = (this.idleIndex + 1) % clips.length;
1823
+ clip = clips[this.idleIndex];
1824
+ }
1825
+ }
1826
+ for (const curve of clip.curves) {
1827
+ frame.set(curve.parameter, this.sample(curve, this.idleTime));
1828
+ }
1829
+ }
1830
+ applySlot(slot, dtS, frame, rest) {
1831
+ const { clip, from } = slot;
1832
+ const base = (id) => frame.get(id) ?? rest(id);
1833
+ slot.t += dtS;
1834
+ if (slot.t >= clip.duration) {
1835
+ const ids = new Set(clip.curves.map((curve) => curve.parameter));
1836
+ for (const id of from.keys()) ids.add(id);
1837
+ for (const id of ids) frame.set(id, base(id));
1838
+ this.slot = void 0;
1839
+ return;
1840
+ }
1841
+ const { wIn, wOut } = fadeWeights(clip, slot.t);
1842
+ const last = /* @__PURE__ */ new Map();
1843
+ const write = (id, sample) => {
1844
+ const b = base(id);
1845
+ const f = from.get(id) ?? b;
1846
+ const value = lerp(b, lerp(f, sample ?? b, wIn), wOut);
1847
+ frame.set(id, value);
1848
+ last.set(id, this.displayed(id, value));
1849
+ };
1850
+ for (const curve of clip.curves) {
1851
+ write(curve.parameter, this.sample(curve, slot.t));
1852
+ }
1853
+ for (const id of from.keys()) if (!last.has(id)) write(id, void 0);
1854
+ slot.last = last;
1855
+ if (wIn >= 1) from.clear();
1856
+ }
1857
+ /** The curve at `t`, smooth unless it is marked `"linear"`. */
1858
+ sample(curve, t) {
1859
+ return sampleCurve(curve.keys, t, this.slopes.get(curve));
1860
+ }
1861
+ /**
1862
+ * The clip stage's output for an id, clamped to the parameter's range as
1863
+ * the store clamps every write. A replacing clip fades in from this, not
1864
+ * the raw value — a curve past the max would otherwise sit still on screen
1865
+ * until the fade got back inside the range.
1866
+ */
1867
+ displayed(id, value) {
1868
+ const param = this.params.get(id);
1869
+ return param ? clamp(value, param.min, param.max) : value;
1870
+ }
1871
+ };
1872
+
1873
+ // ../engine/src/expression-player.ts
1874
+ var BASE = { scale: 1, offset: 0 };
1875
+ function lineOf({ value, blend = "add" }) {
1876
+ switch (blend) {
1877
+ case "add":
1878
+ return { scale: 1, offset: value };
1879
+ case "multiply":
1880
+ return { scale: value, offset: 0 };
1881
+ case "overwrite":
1882
+ return { scale: 0, offset: value };
1883
+ }
1884
+ }
1885
+ function at({ scale: scale2, offset }, base) {
1886
+ return scale2 * base + offset;
1887
+ }
1888
+ function mix(a, b, t) {
1889
+ return t === 1 ? b : lerp(a, b, t);
1890
+ }
1891
+ var RELEASE = { expression: void 0, lines: /* @__PURE__ */ new Map() };
1892
+ function weight({ seconds, elapsed }) {
1893
+ return elapsed >= seconds ? 1 : smoothstep(elapsed / seconds);
1894
+ }
1895
+ var ExpressionPlayer = class {
1896
+ /** Every expression parameter, deduplicated, insertion-ordered. */
1897
+ parameterIds;
1898
+ poses;
1899
+ params;
1900
+ /** Undefined while nothing is held. */
1901
+ fade = void 0;
1902
+ /**
1903
+ * The pose on screen when {@link fade} began, a line per id; empty once the
1904
+ * fade has finished, since the screen is then its target alone.
1905
+ */
1906
+ from = /* @__PURE__ */ new Map();
1907
+ /** Every id `from` or the fade drives: what each apply writes. */
1908
+ held = [];
1909
+ constructor(expressions, parameters) {
1910
+ const list = expressions ?? [];
1911
+ this.params = new Map(parameters.map((p) => [p.id, p]));
1912
+ this.poses = new Map(
1913
+ list.map((expression) => [
1914
+ expression.id,
1915
+ {
1916
+ expression,
1917
+ lines: new Map(
1918
+ expression.parameters.map((p) => [p.parameter, lineOf(p)])
1919
+ )
1920
+ }
1921
+ ])
1922
+ );
1923
+ this.parameterIds = [
1924
+ ...new Set(list.flatMap((e) => e.parameters.map((p) => p.parameter)))
1925
+ ];
1926
+ }
1927
+ /**
1928
+ * Fade expression `id` in over its `fadeIn`, from what is on screen: the
1929
+ * base, or the output of the expression it replaces, or of a stop still
1930
+ * fading out. Returns false, and changes nothing, for an expression id the
1931
+ * model does not declare; playing the expression already fading in or held
1932
+ * changes nothing and returns true.
1933
+ */
1934
+ play(id) {
1935
+ const pose = this.poses.get(id);
1936
+ if (!pose) return false;
1937
+ if (this.fade?.pose === pose) return true;
1938
+ this.begin(pose, pose.expression.fadeIn ?? DEFAULT_FADE_SECONDS);
1939
+ return true;
1940
+ }
1941
+ /**
1942
+ * Fade back to base over the playing expression's `fadeOut`, from what is
1943
+ * on screen. Does nothing when nothing is playing or a stop is already
1944
+ * fading out.
1945
+ */
1946
+ stop() {
1947
+ const playing = this.fade?.pose.expression;
1948
+ if (!playing) return;
1949
+ this.begin(RELEASE, playing.fadeOut ?? DEFAULT_FADE_SECONDS);
1950
+ }
1951
+ /**
1952
+ * Freeze what is on screen into {@link from}, at the weight the current
1953
+ * fade has reached, and start a fade from it toward `pose`. Folding keeps
1954
+ * this to one `from` and one fade however fast the plays come.
1955
+ *
1956
+ * {@link apply} clamps each end before it mixes, so each end folds in as
1957
+ * the screen showed it at the last apply's base ({@link pinned}): the new
1958
+ * fade starts on what was on screen, an end held at a range limit stays
1959
+ * there as the base moves, and the rest still follow the live base. Should
1960
+ * the base move so far that the old pose would have left the limit, the
1961
+ * start holds it instead: a little off, but continuous, and it fades out.
1962
+ */
1963
+ begin(pose, seconds) {
1964
+ if (this.fade) {
1965
+ const { lines } = this.fade.pose;
1966
+ const w = weight(this.fade);
1967
+ const from = /* @__PURE__ */ new Map();
1968
+ for (const { id, base } of this.held) {
1969
+ const a = this.pinned(id, this.from.get(id) ?? BASE, base);
1970
+ const b = this.pinned(id, lines.get(id) ?? BASE, base);
1971
+ from.set(id, {
1972
+ scale: mix(a.scale, b.scale, w),
1973
+ offset: mix(a.offset, b.offset, w)
1974
+ });
1975
+ }
1976
+ this.from = from;
1977
+ }
1978
+ this.fade = { pose, seconds, elapsed: 0 };
1979
+ this.held = [.../* @__PURE__ */ new Set([...this.from.keys(), ...pose.lines.keys()])].map(
1980
+ (id) => ({ id, base: NaN })
1981
+ );
1982
+ }
1983
+ /**
1984
+ * Advance `dtS` seconds and write every held id into `frame`: the pose on
1985
+ * screen when the fade began, lerped toward the fade's target by its
1986
+ * weight, each end clamped to the parameter's range. An id the target does
1987
+ * not drive goes to base.
1988
+ *
1989
+ * `frame` holds what earlier stages wrote this update. A parameter id's base
1990
+ * is its frame value, else `rest(id)` — the parameter's resting value,
1991
+ * `clamp(default, min, max)`. The base is never the store's current value,
1992
+ * so an `add` cannot accumulate across frames.
1993
+ */
1994
+ apply(dtS, frame, rest) {
1995
+ const fade = this.fade;
1996
+ if (!fade) return;
1997
+ fade.elapsed += dtS;
1998
+ const w = weight(fade);
1999
+ const { lines } = fade.pose;
2000
+ for (const held of this.held) {
2001
+ const { id } = held;
2002
+ const base = frame.get(id) ?? rest(id);
2003
+ held.base = base;
2004
+ const start = this.displayed(id, at(this.from.get(id) ?? BASE, base));
2005
+ const end = this.displayed(id, at(lines.get(id) ?? BASE, base));
2006
+ frame.set(id, mix(start, end, w));
2007
+ }
2008
+ if (w < 1) return;
2009
+ if (!fade.pose.expression) {
2010
+ this.fade = void 0;
2011
+ this.from.clear();
2012
+ this.held = [];
2013
+ } else if (this.from.size > 0) {
2014
+ this.from.clear();
2015
+ this.held = this.held.filter(({ id }) => lines.has(id));
2016
+ }
2017
+ }
2018
+ /**
2019
+ * A value as the screen shows it: clamped to the parameter's range, as the
2020
+ * store clamps every write; an id the model does not declare as is. A fade
2021
+ * mixes these, so it leaves a value held past the max from the max at once
2022
+ * instead of sitting there until the mix gets back inside the range.
2023
+ */
2024
+ displayed(id, value) {
2025
+ const param = this.params.get(id);
2026
+ return param ? clamp(value, param.min, param.max) : value;
2027
+ }
2028
+ /**
2029
+ * `line`, or, where its value at `base` is past the parameter's range, the
2030
+ * constant line at the limit it crossed: the line as the screen shows it
2031
+ * there. An id the model does not declare pins nothing, and nor does a NaN
2032
+ * base (no apply yet), which compares false both ways.
2033
+ */
2034
+ pinned(id, line, base) {
2035
+ const param = this.params.get(id);
2036
+ if (!param) return line;
2037
+ const value = at(line, base);
2038
+ if (value > param.max) return { scale: 0, offset: param.max };
2039
+ if (value < param.min) return { scale: 0, offset: param.min };
2040
+ return line;
2041
+ }
2042
+ };
1193
2043
 
1194
2044
  // ../engine/src/iki-motion.ts
1195
2045
  var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
@@ -1199,6 +2049,129 @@ void main() {
1199
2049
  StandardParameter.EyeballX,
1200
2050
  StandardParameter.EyeballY
1201
2051
  ]);
2052
+ var IkiMotion = class {
2053
+ /**
2054
+ * Everything {@link update} may write, deduplicated, in this order: idle ids
2055
+ * (without head and gaze when the model declares an `Idle` group), the curve
2056
+ * parameters of every motion group, expression parameters, rig outputs,
2057
+ * then chain-segment outputs. May name ids the model lacks (idle writes the
2058
+ * standard ids regardless, and the player silently drops writes to unknown
2059
+ * ids) — intersect with the model's parameters if you mirror into your own
2060
+ * store.
2061
+ */
2062
+ drivenParameterIds;
2063
+ sink;
2064
+ idle;
2065
+ clips;
2066
+ expressions;
2067
+ physics;
2068
+ chains;
2069
+ /** Resting value per id; 0 for an undeclared id. */
2070
+ rest;
2071
+ /** This update's idle, clip and expression writes, in first-write order. */
2072
+ frame = /* @__PURE__ */ new Map();
2073
+ /** Bound once: `Map.forEach` hands it each entry without a tuple per id. */
2074
+ flush = (value, id) => this.sink(id, value);
2075
+ prevNowMs = void 0;
2076
+ constructor(model, read, sink) {
2077
+ const rigs = model.physics ?? [];
2078
+ const chains = model.physicsChains ?? [];
2079
+ const restPose = new ParameterStore(model.parameters);
2080
+ this.sink = sink;
2081
+ this.rest = (id) => restPose.get(id);
2082
+ this.clips = new ClipPlayer(model.motions, model.parameters);
2083
+ this.expressions = new ExpressionPlayer(
2084
+ model.expressions,
2085
+ model.parameters
2086
+ );
2087
+ const idleKeeps = this.clips.hasIdleLoop ? (id) => !HEAD_AND_GAZE.has(id) : () => true;
2088
+ this.idle = new IdleMotion((id, value) => {
2089
+ if (idleKeeps(id)) this.frame.set(id, value);
2090
+ });
2091
+ this.physics = new PhysicsMotion(rigs, model.parameters, read, sink);
2092
+ this.chains = new HairChainMotion(
2093
+ chains,
2094
+ model.parameters,
2095
+ model.deformers ?? [],
2096
+ read,
2097
+ sink
2098
+ );
2099
+ this.drivenParameterIds = [
2100
+ .../* @__PURE__ */ new Set([
2101
+ ...this.idle.drivenParameterIds.filter(idleKeeps),
2102
+ ...this.clips.parameterIds,
2103
+ ...this.expressions.parameterIds,
2104
+ ...this.physics.drivenParameterIds,
2105
+ ...this.chains.drivenParameterIds
2106
+ ])
2107
+ ];
2108
+ }
2109
+ /**
2110
+ * Make expression `id` active, fading it in over its `fadeIn` from the
2111
+ * current pose: it replaces the active one and blends from that one's
2112
+ * current output, as {@link playMotion} does, so nothing dips toward base on
2113
+ * the way. Returns false, and changes nothing, for an id the model does not
2114
+ * declare. Playing the active id again changes nothing and returns true; an
2115
+ * expression never stacks on itself.
2116
+ */
2117
+ playExpression(id) {
2118
+ return this.expressions.play(id);
2119
+ }
2120
+ /** Fade the active expression, if any, back to base over its `fadeOut`. */
2121
+ stopExpression() {
2122
+ this.expressions.stop();
2123
+ }
2124
+ /**
2125
+ * Start clip `index` of motion group `group` at once. A running one-shot
2126
+ * stops, and the new clip fades in from the old one's last pose. Returns
2127
+ * false, and changes nothing, for a group the model does not declare or an
2128
+ * index that is not an integer in range. Any group plays one-shot, `Idle`
2129
+ * included; there is no queue.
2130
+ */
2131
+ playMotion(group, index) {
2132
+ return this.clips.play(group, index);
2133
+ }
2134
+ /**
2135
+ * Advance everything to the same wall-clock timestamp (milliseconds), in
2136
+ * this order:
2137
+ *
2138
+ * 1. Idle writes blink, breath, the ambient sway (and head and gaze, unless
2139
+ * replaced) into this update's frame.
2140
+ * 2. The clip stage writes the `Idle` loop, then the one-shot over it.
2141
+ * 3. The expression stage writes the active expression, fading in from the
2142
+ * pose it replaced, or a stop fading back to base.
2143
+ * 4. The frame goes to `sink`, each id exactly once, in the order its first
2144
+ * writer gave it: an expression on EyeOpenL is flushed in idle's slot.
2145
+ * 5. Physics, then chains. They read their inputs through `read`, so the
2146
+ * springs lag the head this update put on screen (idle sway or clips),
2147
+ * and a chain resolves its anchor from that same pose (which may include
2148
+ * a physics output). Physics outputs are physics-owned: a clip or
2149
+ * expression that writes one is overwritten here.
2150
+ *
2151
+ * The host writes the signals it owns (lip-sync MouthOpen, gaze overrides)
2152
+ * AFTER update(); the last write wins. That is how lip-sync beats an
2153
+ * expression that opens the mouth.
2154
+ *
2155
+ * The clips and expressions advance by `clamp(now − prev, 0, MAX_DT_MS)`,
2156
+ * 0 on the first update. A non-finite `nowMs` is a dropped frame: idle and
2157
+ * both players write nothing and do not advance (physics and chains re-emit
2158
+ * their outputs unchanged), and the next finite frame measures from the
2159
+ * last finite one, as IdleMotion does.
2160
+ */
2161
+ update(nowMs) {
2162
+ this.frame.clear();
2163
+ this.idle.update(nowMs);
2164
+ if (Number.isFinite(nowMs)) {
2165
+ const dtS = this.prevNowMs === void 0 ? 0 : clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS) / 1e3;
2166
+ this.prevNowMs = nowMs;
2167
+ this.clips.apply(dtS, this.frame, this.rest);
2168
+ this.expressions.apply(dtS, this.frame, this.rest);
2169
+ }
2170
+ this.frame.forEach(this.flush);
2171
+ this.physics.update(nowMs);
2172
+ this.chains.update(nowMs);
2173
+ }
2174
+ };
1202
2175
 
1203
2176
  // ../engine/src/folds.ts
1204
2177
  var ANGLES = [
@@ -1228,6 +2201,25 @@ void main() {
1228
2201
  };
1229
2202
  var player;
1230
2203
  var canvas;
2204
+ var loaded;
2205
+ var sweep;
2206
+ var resetParameters = (p) => {
2207
+ for (const { id, default: d } of p.getParameters()) p.setParameter(id, d);
2208
+ };
2209
+ var frameCanvas = (c, crop) => {
2210
+ if (!crop) return c;
2211
+ const out = document.createElement("canvas");
2212
+ out.width = crop.dw;
2213
+ out.height = crop.dh;
2214
+ out.getContext("2d").drawImage(c, crop.sx, crop.sy, crop.sw, crop.sh, 0, 0, crop.dw, crop.dh);
2215
+ return out;
2216
+ };
2217
+ var newCanvas = (width, height) => {
2218
+ const c = document.createElement("canvas");
2219
+ c.width = width;
2220
+ c.height = height;
2221
+ return c;
2222
+ };
1231
2223
  window.__ikiRender = {
1232
2224
  async load(model, { canvas: size, view }) {
1233
2225
  canvas = document.createElement("canvas");
@@ -1236,6 +2228,7 @@ void main() {
1236
2228
  document.body.appendChild(canvas);
1237
2229
  player = new IkiPlayer(canvas);
1238
2230
  player.start();
2231
+ loaded = model;
1239
2232
  const { failedTextures } = await player.load(model);
1240
2233
  if (view) player.setView(view);
1241
2234
  await settle();
@@ -1255,22 +2248,101 @@ void main() {
1255
2248
  player.setParameter(id, value);
1256
2249
  }
1257
2250
  await settle();
1258
- if (!crop) return canvas.toDataURL("image/png");
1259
- const out = document.createElement("canvas");
1260
- out.width = crop.dw;
1261
- out.height = crop.dh;
1262
- out.getContext("2d").drawImage(
1263
- canvas,
1264
- crop.sx,
1265
- crop.sy,
1266
- crop.sw,
1267
- crop.sh,
2251
+ return frameCanvas(canvas, crop).toDataURL("image/png");
2252
+ },
2253
+ async sweepBegin(spec) {
2254
+ if (!player || !canvas || !loaded) {
2255
+ throw new Error("sweepBegin() called before load()");
2256
+ }
2257
+ const p = player;
2258
+ resetParameters(p);
2259
+ const outputs = new Set(spec.physicsOutputs);
2260
+ const motion = new IkiMotion(
2261
+ loaded,
2262
+ (id) => p.getParameter(id),
2263
+ (id, value) => {
2264
+ if (outputs.has(id)) p.setParameter(id, value);
2265
+ }
2266
+ );
2267
+ for (let step = 0; step < spec.warmup; step++) {
2268
+ p.setParameter(spec.parameter, spec.thetas[0]);
2269
+ motion.update(step * spec.frameMs);
2270
+ }
2271
+ const cells = /* @__PURE__ */ new Map();
2272
+ for (const k of spec.sheet.frames) {
2273
+ cells.set(k, newCanvas(spec.sheet.cell.w, spec.sheet.cell.h));
2274
+ }
2275
+ sweep = {
2276
+ spec,
2277
+ motion,
2278
+ cells,
2279
+ kymograph: newCanvas(spec.frame.width, spec.frames * spec.kymograph.band),
2280
+ nextStep: 0,
2281
+ frame: 0
2282
+ };
2283
+ },
2284
+ async sweepFrame() {
2285
+ if (!player || !canvas || !sweep) {
2286
+ throw new Error("sweepFrame() called before sweepBegin()");
2287
+ }
2288
+ const { spec, motion, cells, kymograph } = sweep;
2289
+ while (sweep.nextStep <= spec.captureEvery * sweep.frame) {
2290
+ player.setParameter(spec.parameter, spec.thetas[sweep.nextStep]);
2291
+ motion.update((spec.warmup + sweep.nextStep) * spec.frameMs);
2292
+ sweep.nextStep++;
2293
+ }
2294
+ await settle();
2295
+ const shot = frameCanvas(canvas, spec.crop);
2296
+ const cell = cells.get(sweep.frame);
2297
+ if (cell) {
2298
+ cell.getContext("2d").drawImage(shot, 0, 0, cell.width, cell.height);
2299
+ }
2300
+ const { row, band } = spec.kymograph;
2301
+ kymograph.getContext("2d").drawImage(
2302
+ shot,
1268
2303
  0,
2304
+ row - Math.floor(band / 2),
2305
+ shot.width,
2306
+ band,
1269
2307
  0,
1270
- crop.dw,
1271
- crop.dh
2308
+ sweep.frame * band,
2309
+ shot.width,
2310
+ band
2311
+ );
2312
+ sweep.frame++;
2313
+ const values = {
2314
+ [spec.parameter]: player.getParameter(spec.parameter)
2315
+ };
2316
+ for (const id of spec.physicsOutputs) values[id] = player.getParameter(id);
2317
+ return { png: shot.toDataURL("image/png"), values };
2318
+ },
2319
+ async sweepEnd() {
2320
+ if (!player || !sweep)
2321
+ throw new Error("sweepEnd() called before sweepBegin()");
2322
+ const { cell, margin, labelBand, labels } = sweep.spec.sheet;
2323
+ const sheet = newCanvas(
2324
+ 3 * cell.w + 2 * margin,
2325
+ 3 * (cell.h + labelBand) + 2 * margin
1272
2326
  );
1273
- return out.toDataURL("image/png");
2327
+ const g = sheet.getContext("2d");
2328
+ g.fillStyle = "#7f7f7f";
2329
+ g.fillRect(0, 0, sheet.width, sheet.height);
2330
+ g.fillStyle = "#ffffff";
2331
+ g.font = `${Math.round(labelBand * 0.6)}px sans-serif`;
2332
+ g.textBaseline = "middle";
2333
+ sweep.spec.sheet.frames.forEach((k, i) => {
2334
+ const x = margin + i % 3 * cell.w;
2335
+ const y = margin + Math.floor(i / 3) * (cell.h + labelBand);
2336
+ g.drawImage(sweep.cells.get(k), x, y);
2337
+ g.fillText(labels[i], x + 4, y + cell.h + labelBand / 2);
2338
+ });
2339
+ const out = {
2340
+ sheet: sheet.toDataURL("image/png"),
2341
+ kymograph: sweep.kymograph.toDataURL("image/png")
2342
+ };
2343
+ resetParameters(player);
2344
+ sweep = void 0;
2345
+ return out;
1274
2346
  }
1275
2347
  };
1276
2348
  })();