@ikijs/mcp 0.26.1 → 0.28.0

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.
@@ -8,6 +8,10 @@ function clamp(value, min, max) {
8
8
  function lerp(a, b, t) {
9
9
  return a + (b - a) * t;
10
10
  }
11
+ function smoothstep(x) {
12
+ const t = clamp(x, 0, 1);
13
+ return t * t * (3 - 2 * t);
14
+ }
11
15
 
12
16
  // ../engine/src/parameter-store.ts
13
17
  var ParameterStore = class {
@@ -413,17 +417,516 @@ function resolveDeformers(deformers, params) {
413
417
  import { StandardParameter } from "@ikijs/format";
414
418
 
415
419
  // ../engine/src/frame-clock.ts
420
+ var MAX_DT_MS = 100;
416
421
  var FIXED_DT_S = 1 / 60;
422
+ var MAX_SUBSTEPS = 6;
423
+ var FixedStepClock = class {
424
+ prevNowMs = void 0;
425
+ accumulatorS = 0;
426
+ /**
427
+ * True until the first {@link advance}. Drivers seed their rest pose on that
428
+ * frame and integrate nothing, so a model loaded mid-motion does not kick.
429
+ */
430
+ get isSeedFrame() {
431
+ return this.prevNowMs === void 0;
432
+ }
433
+ /**
434
+ * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}
435
+ * sub-steps to run this frame. On the seed frame it only records the
436
+ * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.
437
+ */
438
+ advance(nowMs) {
439
+ if (!Number.isFinite(nowMs)) return 0;
440
+ if (this.prevNowMs === void 0) {
441
+ this.prevNowMs = nowMs;
442
+ return 0;
443
+ }
444
+ const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);
445
+ this.prevNowMs = nowMs;
446
+ this.accumulatorS += dtMs / 1e3;
447
+ let steps = 0;
448
+ while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {
449
+ this.accumulatorS -= FIXED_DT_S;
450
+ steps++;
451
+ }
452
+ return steps;
453
+ }
454
+ };
417
455
 
418
456
  // ../engine/src/idle-motion.ts
457
+ var BLINK_INTERVAL_MIN_MS = 1500;
458
+ var BLINK_INTERVAL_MAX_MS = 6e3;
419
459
  var BLINK_CLOSE_MS = 60;
420
460
  var BLINK_HOLD_MS = 20;
421
461
  var BLINK_OPEN_MS = 100;
422
462
  var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
463
+ var BREATH_PERIOD_MS = 3500;
464
+ var GAZE_RADIUS = 0.3;
465
+ var GAZE_RETARGET_MIN_MS = 1200;
466
+ var GAZE_RETARGET_MAX_MS = 3e3;
467
+ var GAZE_EASE_RATE = 1e-3;
468
+ var SWAY_X_AMP_A_DEG = 2.2;
469
+ var SWAY_X_PERIOD_A_MS = 6100;
470
+ var SWAY_X_AMP_B_DEG = 1.3;
471
+ var SWAY_X_PERIOD_B_MS = 9700;
472
+ var SWAY_Y_AMP_DEG = 1.6;
473
+ var SWAY_Y_PERIOD_MS = 7300;
474
+ var SWAY_Z_AMP_DEG = 1.1;
475
+ var SWAY_Z_PERIOD_MS = 11300;
476
+ var AMBIENT_AMP_A = 0.6;
477
+ var AMBIENT_PERIOD_A_MS = 2900;
478
+ var AMBIENT_AMP_B = 0.4;
479
+ var AMBIENT_PERIOD_B_MS = 4300;
480
+ function blinkEnvelope(phase) {
481
+ const ms = phase * BLINK_DURATION_MS;
482
+ if (ms <= 0) return 1;
483
+ if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);
484
+ if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0;
485
+ if (ms < BLINK_DURATION_MS) {
486
+ const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;
487
+ return 1 - (1 - t) * (1 - t);
488
+ }
489
+ return 1;
490
+ }
491
+ function randomInDisk(rng, radius) {
492
+ const r = Math.sqrt(rng()) * radius;
493
+ const theta = rng() * 2 * Math.PI;
494
+ return [r * Math.cos(theta), r * Math.sin(theta)];
495
+ }
496
+ var IdleMotion = class {
497
+ /**
498
+ * Every parameter id {@link update} and `emitRestingPose` write, in write
499
+ * order. Published so a host (or IkiMotion) can restore them after it
500
+ * stops driving — keep in step with those two methods; the test suite
501
+ * pins this list to the actual emissions.
502
+ */
503
+ drivenParameterIds = [
504
+ StandardParameter.EyeOpenLeft,
505
+ StandardParameter.EyeOpenRight,
506
+ StandardParameter.Breath,
507
+ StandardParameter.EyeballX,
508
+ StandardParameter.EyeballY,
509
+ StandardParameter.AngleX,
510
+ StandardParameter.AngleY,
511
+ StandardParameter.AngleZ,
512
+ StandardParameter.AmbientSway
513
+ ];
514
+ sink;
515
+ rng;
516
+ // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.
517
+ // This is the only clock blink/breath/gaze scheduling reads.
518
+ clockMs = 0;
519
+ prevNowMs = void 0;
520
+ // Blink state
521
+ nextBlinkAtMs;
522
+ blinkStartMs = -1;
523
+ // -1 means not currently blinking
524
+ // Gaze state
525
+ gazeCurrentX = 0;
526
+ gazeCurrentY = 0;
527
+ gazeTargetX = 0;
528
+ gazeTargetY = 0;
529
+ nextGazeRetargetMs;
530
+ constructor(sink, options) {
531
+ this.sink = sink;
532
+ this.rng = options?.rng ?? Math.random;
533
+ this.nextBlinkAtMs = lerp(
534
+ BLINK_INTERVAL_MIN_MS,
535
+ BLINK_INTERVAL_MAX_MS,
536
+ this.rng()
537
+ );
538
+ this.nextGazeRetargetMs = lerp(
539
+ GAZE_RETARGET_MIN_MS,
540
+ GAZE_RETARGET_MAX_MS,
541
+ this.rng()
542
+ );
543
+ }
544
+ /**
545
+ * Advance the idle animation to the given wall-clock timestamp (milliseconds).
546
+ *
547
+ * On the first call: record prevNowMs, emit the resting pose, and return —
548
+ * no animation advance happens so there is no jump from time 0.
549
+ *
550
+ * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)
551
+ * and advance the internal clock by dt. A non-monotonic nowMs produces a
552
+ * negative raw delta that the clamp floors to 0 — no rewind.
553
+ */
554
+ update(nowMs) {
555
+ if (!Number.isFinite(nowMs)) return;
556
+ if (this.prevNowMs === void 0) {
557
+ this.prevNowMs = nowMs;
558
+ this.emitRestingPose();
559
+ return;
560
+ }
561
+ const rawDt = nowMs - this.prevNowMs;
562
+ const dt = clamp(rawDt, 0, MAX_DT_MS);
563
+ this.prevNowMs = nowMs;
564
+ this.clockMs += dt;
565
+ const eyeVal = this.advanceBlink();
566
+ this.sink(StandardParameter.EyeOpenLeft, eyeVal);
567
+ this.sink(StandardParameter.EyeOpenRight, eyeVal);
568
+ const breath = this.advanceBreath();
569
+ this.advanceGaze(dt);
570
+ this.sink(StandardParameter.Breath, breath);
571
+ this.sink(StandardParameter.EyeballX, this.gazeCurrentX);
572
+ this.sink(StandardParameter.EyeballY, this.gazeCurrentY);
573
+ this.sink(StandardParameter.AngleX, this.swayX());
574
+ this.sink(StandardParameter.AngleY, this.swayY());
575
+ this.sink(StandardParameter.AngleZ, this.swayZ());
576
+ this.sink(StandardParameter.AmbientSway, this.ambientSway());
577
+ }
578
+ // ---------------------------------------------------------------------------
579
+ // Private helpers
580
+ // ---------------------------------------------------------------------------
581
+ emitRestingPose() {
582
+ this.sink(StandardParameter.EyeOpenLeft, 1);
583
+ this.sink(StandardParameter.EyeOpenRight, 1);
584
+ this.sink(StandardParameter.Breath, 0.5);
585
+ this.sink(StandardParameter.EyeballX, 0);
586
+ this.sink(StandardParameter.EyeballY, 0);
587
+ this.sink(StandardParameter.AngleX, 0);
588
+ this.sink(StandardParameter.AngleY, 0);
589
+ this.sink(StandardParameter.AngleZ, 0);
590
+ this.sink(StandardParameter.AmbientSway, 0);
591
+ }
592
+ /** Returns the current eye-open value (0..1) and advances blink state. */
593
+ advanceBlink() {
594
+ const { clockMs } = this;
595
+ if (this.blinkStartMs >= 0) {
596
+ const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;
597
+ if (phase >= 1) {
598
+ this.blinkStartMs = -1;
599
+ this.nextBlinkAtMs = clockMs + lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());
600
+ return 1;
601
+ }
602
+ return blinkEnvelope(phase);
603
+ }
604
+ if (clockMs >= this.nextBlinkAtMs) {
605
+ this.blinkStartMs = clockMs;
606
+ return blinkEnvelope(0);
607
+ }
608
+ return 1;
609
+ }
610
+ advanceBreath() {
611
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * this.clockMs / BREATH_PERIOD_MS);
612
+ }
613
+ /** Horizontal head sway in degrees, pure function of the internal clock. */
614
+ swayX() {
615
+ const t = 2 * Math.PI * this.clockMs;
616
+ 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);
617
+ }
618
+ /** Vertical head sway in degrees, pure function of the internal clock. */
619
+ swayY() {
620
+ return SWAY_Y_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Y_PERIOD_MS);
621
+ }
622
+ /** Head roll sway in degrees, pure function of the internal clock. */
623
+ swayZ() {
624
+ return SWAY_Z_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Z_PERIOD_MS);
625
+ }
626
+ /** Ambient sway (-1..1), pure function of the internal clock. */
627
+ ambientSway() {
628
+ const t = 2 * Math.PI * this.clockMs;
629
+ return AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) + AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS);
630
+ }
631
+ /** Ease gaze current toward target; pick a new target on the internal clock. */
632
+ advanceGaze(dt) {
633
+ if (this.clockMs >= this.nextGazeRetargetMs) {
634
+ const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);
635
+ this.gazeTargetX = tx;
636
+ this.gazeTargetY = ty;
637
+ this.nextGazeRetargetMs = this.clockMs + lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());
638
+ }
639
+ const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);
640
+ this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);
641
+ this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);
642
+ }
643
+ };
644
+
645
+ // ../engine/src/physics-motion.ts
646
+ import {
647
+ physicsInputs
648
+ } from "@ikijs/format";
649
+ function signedNormalized(value, param) {
650
+ const rest = clamp(param.default, param.min, param.max);
651
+ const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));
652
+ if (den === 0) return 0;
653
+ return clamp((value - rest) / den, -1, 1);
654
+ }
655
+ var PhysicsMotion = class {
656
+ /** The output parameter of every rig, in rig order — what `emit` writes. */
657
+ drivenParameterIds;
658
+ /**
659
+ * Per rig: how many times the finiteness guard reset its state or `emit`
660
+ * replaced its non-finite product. Up to two per frame, so guard activations,
661
+ * not repaired frames. A diagnostic; emitted values are unchanged.
662
+ */
663
+ resets;
664
+ resetCounts;
665
+ rigs;
666
+ inputs;
667
+ read;
668
+ sink;
669
+ params;
670
+ // Integrator state, owned here — never stored in a ParameterStore.
671
+ state;
672
+ clock = new FixedStepClock();
673
+ constructor(rigs, params, read, sink) {
674
+ this.rigs = rigs;
675
+ this.inputs = rigs.map(
676
+ (rig) => physicsInputs(rig).map(({ parameter, weight, mode }) => ({
677
+ parameter,
678
+ weight,
679
+ lag: mode === "lag"
680
+ }))
681
+ );
682
+ this.read = read;
683
+ this.sink = sink;
684
+ this.params = new Map(params.map((p) => [p.id, p]));
685
+ this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));
686
+ this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);
687
+ this.resetCounts = rigs.map(() => 0);
688
+ this.resets = this.resetCounts;
689
+ }
690
+ /**
691
+ * Advance every rig to the given wall-clock timestamp (milliseconds).
692
+ *
693
+ * First call: seed each spring to rest AT its current target (so a model
694
+ * loaded with a nonzero input does not kick: a lag input emits rest, a follow
695
+ * input its value), emit that output, and return without integrating —
696
+ * mirroring IdleMotion's first-frame behavior.
697
+ *
698
+ * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its
699
+ * last output from its stored state without reading its inputs.
700
+ *
701
+ * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into
702
+ * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;
703
+ * the spring advances that many semi-implicit Euler steps, then each rig emits
704
+ * its output once. The clock's dt clamp and sub-step cap plus the symplectic
705
+ * integrator are what keep it stable across hitches.
706
+ */
707
+ update(nowMs) {
708
+ if (this.clock.isSeedFrame) {
709
+ this.clock.advance(nowMs);
710
+ for (let i = 0; i < this.rigs.length; i++) {
711
+ const st = this.state[i];
712
+ const { target: target2, lag } = this.targetFor(i);
713
+ st.x = target2;
714
+ st.v = 0;
715
+ st.lag = lag;
716
+ this.emit(i, st);
717
+ }
718
+ return;
719
+ }
720
+ if (!Number.isFinite(nowMs)) {
721
+ for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);
722
+ return;
723
+ }
724
+ const steps = this.clock.advance(nowMs);
725
+ const targets = this.rigs.map((_, i) => this.targetFor(i));
726
+ for (let s = 0; s < steps; s++) {
727
+ for (let i = 0; i < this.rigs.length; i++) {
728
+ this.step(this.rigs[i], this.state[i], targets[i].target);
729
+ }
730
+ }
731
+ for (let i = 0; i < this.rigs.length; i++) {
732
+ const st = this.state[i];
733
+ const { target: target2, lag } = targets[i];
734
+ if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {
735
+ st.x = Number.isFinite(target2) ? target2 : 0;
736
+ st.v = 0;
737
+ this.resetCounts[i]++;
738
+ }
739
+ st.lag = lag;
740
+ this.emit(i, st);
741
+ }
742
+ }
743
+ /**
744
+ * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,
745
+ * and `L`, the lag inputs' share of it. Reads each input once.
746
+ */
747
+ targetFor(index) {
748
+ let target2 = 0;
749
+ let lag = 0;
750
+ for (const input of this.inputs[index]) {
751
+ const param = this.params.get(input.parameter);
752
+ const value = this.read(input.parameter);
753
+ const share = (param ? signedNormalized(value, param) : 0) * input.weight;
754
+ target2 += share;
755
+ if (input.lag) lag += share;
756
+ }
757
+ return { target: target2, lag };
758
+ }
759
+ /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */
760
+ step(rig, st, target2) {
761
+ const accel = (rig.stiffness * (target2 - st.x) - rig.damping * st.v) / rig.mass;
762
+ st.v += accel * FIXED_DT_S;
763
+ st.x += st.v * FIXED_DT_S;
764
+ }
765
+ /** Write outputDefault + (x − L) * scale onto the output param via the sink. */
766
+ emit(index, st) {
767
+ const rig = this.rigs[index];
768
+ const outParam = this.params.get(rig.output.parameter);
769
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
770
+ const value = outDefault + (st.x - st.lag) * rig.output.scale;
771
+ const finite = Number.isFinite(value);
772
+ if (!finite) this.resetCounts[index]++;
773
+ this.sink(rig.output.parameter, finite ? value : outDefault);
774
+ }
775
+ };
423
776
 
424
777
  // ../engine/src/hair-chain-motion.ts
425
778
  var DEG2RAD = Math.PI / 180;
426
779
  var RAD2DEG = 180 / Math.PI;
780
+ var HairChainMotion = class {
781
+ /** Every segment's output, chain by chain — what `emitSegment` writes. */
782
+ drivenParameterIds;
783
+ /**
784
+ * Per segment, in `drivenParameterIds` order: how many times the finiteness
785
+ * guard reset its state or `emitSegment` replaced its non-finite product. Up
786
+ * to two per frame, so guard activations, not repaired frames. A diagnostic;
787
+ * emitted values are unchanged.
788
+ */
789
+ resets;
790
+ resetCounts;
791
+ chainData;
792
+ params;
793
+ deformers;
794
+ store;
795
+ read;
796
+ sink;
797
+ clock = new FixedStepClock();
798
+ constructor(chains, params, deformers, read, sink) {
799
+ this.params = new Map(params.map((p) => [p.id, p]));
800
+ this.deformers = deformers;
801
+ this.store = new ParameterStore(params);
802
+ this.read = read;
803
+ this.sink = sink;
804
+ this.chainData = chains.map((chain) => ({
805
+ chain,
806
+ restAnglesRad: chain.segments.map(
807
+ (seg) => seg.restAngle !== void 0 ? seg.restAngle * DEG2RAD : 0
808
+ ),
809
+ state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 }))
810
+ }));
811
+ this.drivenParameterIds = chains.flatMap(
812
+ (c) => c.segments.map((s) => s.output.parameter)
813
+ );
814
+ this.resetCounts = this.drivenParameterIds.map(() => 0);
815
+ this.resets = this.resetCounts;
816
+ }
817
+ /**
818
+ * Advance every chain to the given wall-clock timestamp (milliseconds).
819
+ *
820
+ * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output
821
+ * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's
822
+ * first-frame behavior so a model loaded in motion does not kick.
823
+ *
824
+ * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into
825
+ * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE
826
+ * per update() — NOT per chain — so all chains share a consistent frame snapshot.
827
+ * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover
828
+ * time is carried to the next frame. Segments emit after substeps (even on zero
829
+ * substeps) with a non-finite guard.
830
+ */
831
+ update(nowMs) {
832
+ if (this.chainData.length === 0) return;
833
+ if (this.clock.isSeedFrame) {
834
+ this.clock.advance(nowMs);
835
+ let flat2 = 0;
836
+ for (const cd of this.chainData) {
837
+ for (let i = 0; i < cd.chain.segments.length; i++) {
838
+ cd.state[i].angle = 0;
839
+ cd.state[i].angularVelocity = 0;
840
+ this.emitSegment(flat2++, cd.chain.segments[i], cd.state[i]);
841
+ }
842
+ }
843
+ return;
844
+ }
845
+ const steps = this.clock.advance(nowMs);
846
+ for (const param of this.params.values()) {
847
+ this.store.set(param.id, this.read(param.id));
848
+ }
849
+ const worldMap = resolveDeformers(this.deformers, this.store).worlds;
850
+ const anchorAnglesRad = this.chainData.map(
851
+ (cd) => this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer)
852
+ );
853
+ for (let s = 0; s < steps; s++) {
854
+ for (let c = 0; c < this.chainData.length; c++) {
855
+ this.stepChain(this.chainData[c], anchorAnglesRad[c]);
856
+ }
857
+ }
858
+ let flat = 0;
859
+ for (const cd of this.chainData) {
860
+ for (let i = 0; i < cd.chain.segments.length; i++) {
861
+ const st = cd.state[i];
862
+ if (!Number.isFinite(st.angle) || !Number.isFinite(st.angularVelocity)) {
863
+ st.angle = 0;
864
+ st.angularVelocity = 0;
865
+ this.resetCounts[flat]++;
866
+ }
867
+ this.emitSegment(flat++, cd.chain.segments[i], st);
868
+ }
869
+ }
870
+ }
871
+ /**
872
+ * Extract world rotation (radians) from the anchor's Affine tuple.
873
+ * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).
874
+ *
875
+ * If the anchor id is absent from the map, THROWS an internal Error — the
876
+ * format validator guarantees the anchor exists, so absence is an invariant
877
+ * break (mirrors resolveDeformers' throw on an unresolved parent).
878
+ */
879
+ anchorWorldAngleRad(worldMap, anchorId) {
880
+ const world = worldMap.get(anchorId);
881
+ if (!world) {
882
+ throw new Error(
883
+ `HairChainMotion: anchor deformer "${anchorId}" not found in resolved world map \u2014 model not validated?`
884
+ );
885
+ }
886
+ return Math.atan2(world[1], world[0]);
887
+ }
888
+ /**
889
+ * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.
890
+ *
891
+ * Segments are integrated ROOT→TIP so each segment can read its upstream
892
+ * neighbor's current-substep state when computing the world angle Φ_i.
893
+ * (The chain is causal root-to-tip; reversing the order would use stale θ
894
+ * values from the previous substep for Φ_i computation.)
895
+ *
896
+ * Per-segment semi-implicit (symplectic) Euler:
897
+ * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)
898
+ * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i
899
+ * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)
900
+ * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)
901
+ *
902
+ * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear
903
+ * in the spring term, only in Φ_i for the gravity torque.
904
+ */
905
+ stepChain(cd, anchorAngleRad) {
906
+ const { chain, restAnglesRad, state } = cd;
907
+ const gravityAngleRad = chain.gravity.angle * DEG2RAD;
908
+ const strength = chain.gravity.strength;
909
+ let worldAngleAccumRad = anchorAngleRad;
910
+ for (let i = 0; i < chain.segments.length; i++) {
911
+ const seg = chain.segments[i];
912
+ const st = state[i];
913
+ worldAngleAccumRad += restAnglesRad[i] + st.angle;
914
+ const phi = worldAngleAccumRad;
915
+ const alpha = (-seg.stiffness * st.angle - strength * Math.sin(phi - gravityAngleRad) - seg.damping * st.angularVelocity) / seg.mass;
916
+ st.angularVelocity += alpha * FIXED_DT_S;
917
+ st.angle += st.angularVelocity * FIXED_DT_S;
918
+ }
919
+ }
920
+ /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */
921
+ emitSegment(flat, seg, st) {
922
+ const outParam = this.params.get(seg.output.parameter);
923
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
924
+ const value = outDefault + st.angle * RAD2DEG * seg.output.scale;
925
+ const finite = Number.isFinite(value);
926
+ if (!finite) this.resetCounts[flat]++;
927
+ this.sink(seg.output.parameter, finite ? value : outDefault);
928
+ }
929
+ };
427
930
 
428
931
  // ../engine/src/iki-motion.ts
429
932
  import { StandardParameter as StandardParameter2 } from "@ikijs/format";
@@ -452,6 +955,62 @@ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
452
955
  import {
453
956
  StandardParameter as P
454
957
  } from "@ikijs/format";
958
+
959
+ // ../engine/src/land.ts
960
+ function staticDeformers(model) {
961
+ return (model.deformers ?? []).map(
962
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
963
+ );
964
+ }
965
+ function placement(part, t) {
966
+ return multiply(
967
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
968
+ scale(part.width * t.scaleX, part.height * t.scaleY)
969
+ );
970
+ }
971
+ function landedPart(part, vertices, deformers, worlds, store) {
972
+ const warpDeformer = deformers.find(
973
+ (d) => d.kind === "warp" && d.id === part.deformer
974
+ );
975
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
976
+ const placed = placement(
977
+ part,
978
+ evaluateTransform(part.transform, void 0, store)
979
+ );
980
+ const restPoints = transformGridPoints(
981
+ vertices,
982
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
983
+ new Float64Array(vertices.length)
984
+ );
985
+ return {
986
+ part,
987
+ warpDeformer,
988
+ vertices: Float32Array.from(vertices),
989
+ local: new Float32Array(vertices.length),
990
+ landed: new Float32Array(vertices.length),
991
+ restPoints
992
+ };
993
+ }
994
+ function landPart(landing, store, { worlds, grids }) {
995
+ const { part, warpDeformer, local, landed } = landing;
996
+ applyWarps(landing.vertices, part.warps, store, local);
997
+ const placed = placement(
998
+ part,
999
+ evaluateTransform(part.transform, part.bindings, store)
1000
+ );
1001
+ if (warpDeformer) {
1002
+ const grid = grids.get(warpDeformer.id);
1003
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
1004
+ } else if (part.deformer !== void 0) {
1005
+ const world = worlds.get(part.deformer);
1006
+ transformGridPoints(local, multiply(world, placed), landed);
1007
+ } else {
1008
+ transformGridPoints(local, placed, landed);
1009
+ }
1010
+ return landed;
1011
+ }
1012
+
1013
+ // ../engine/src/folds.ts
455
1014
  var FLIP = 0;
456
1015
  var COLLAPSE = 0.1;
457
1016
  var ANGLES = [
@@ -515,11 +1074,6 @@ function poseName(values) {
515
1074
  if (ids.length === 0) return "rest";
516
1075
  return ids.map((id) => `${id}=${values[id]}`).join(" ");
517
1076
  }
518
- function staticDeformers(model) {
519
- return (model.deformers ?? []).map(
520
- (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
521
- );
522
- }
523
1077
  function cornerAreas(points, cols, rows) {
524
1078
  const stride = cols + 1;
525
1079
  const out = new Float64Array(cols * rows * 4);
@@ -551,12 +1105,6 @@ function triangleAreas(points, indices) {
551
1105
  }
552
1106
  return out;
553
1107
  }
554
- function placement(part, t) {
555
- return multiply(
556
- multiply(translate(t.x, t.y), rotate(t.rotation)),
557
- scale(part.width * t.scaleX, part.height * t.scaleY)
558
- );
559
- }
560
1108
  function keepLeast(sweep, areas, pose, expected) {
561
1109
  const slot = expected(sweep.target) ? "expected" : "worst";
562
1110
  for (let i = 0; i < areas.length; i++) {
@@ -569,50 +1117,15 @@ function keepLeast(sweep, areas, pose, expected) {
569
1117
  }
570
1118
  }
571
1119
  function partSweep(part, mesh, deformers, worlds, store) {
572
- const warpDeformer = deformers.find(
573
- (d) => d.kind === "warp" && d.id === part.deformer
574
- );
575
- const frame = warpDeformer ? warpDeformer.parent : part.deformer;
576
- const placed = placement(
577
- part,
578
- evaluateTransform(part.transform, void 0, store)
579
- );
580
- const restPoints = transformGridPoints(
581
- mesh.vertices,
582
- frame === void 0 ? placed : multiply(worlds.get(frame), placed),
583
- new Float64Array(mesh.vertices.length)
584
- );
1120
+ const landing = landedPart(part, mesh.vertices, deformers, worlds, store);
585
1121
  return {
1122
+ ...landing,
586
1123
  target: { kind: "part", id: part.id },
587
- restAreas: triangleAreas(restPoints, mesh.indices),
1124
+ restAreas: triangleAreas(landing.restPoints, mesh.indices),
588
1125
  tiny: 1e-9 * part.width * part.height,
589
- part,
590
- indices: mesh.indices,
591
- warpDeformer,
592
- vertices: Float32Array.from(mesh.vertices),
593
- local: new Float32Array(mesh.vertices.length),
594
- landed: new Float32Array(mesh.vertices.length),
595
- restPoints
1126
+ indices: mesh.indices
596
1127
  };
597
1128
  }
598
- function landPart(sweep, store, { worlds, grids }) {
599
- const { part, warpDeformer, local, landed } = sweep;
600
- applyWarps(sweep.vertices, part.warps, store, local);
601
- const placed = placement(
602
- part,
603
- evaluateTransform(part.transform, part.bindings, store)
604
- );
605
- if (warpDeformer) {
606
- const grid = grids.get(warpDeformer.id);
607
- applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
608
- } else if (part.deformer !== void 0) {
609
- const world = worlds.get(part.deformer);
610
- transformGridPoints(local, multiply(world, placed), landed);
611
- } else {
612
- transformGridPoints(local, placed, landed);
613
- }
614
- return landed;
615
- }
616
1129
  function checkFolds(model, options = {}) {
617
1130
  const poses = options.poses ?? foldPoses(model);
618
1131
  const deformers = model.deformers ?? [];
@@ -639,7 +1152,7 @@ function checkFolds(model, options = {}) {
639
1152
  const store = new ParameterStore(model.parameters);
640
1153
  for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
641
1154
  const value = (id) => store.get(id);
642
- const expected = (target) => options.expected?.(target, pose, value) === true;
1155
+ const expected = (target2) => options.expected?.(target2, pose, value) === true;
643
1156
  for (const sweep of gridSweeps) {
644
1157
  const { cols, rows } = sweep.deformer.grid;
645
1158
  const areas = cornerAreas(
@@ -730,6 +1243,414 @@ function classify(worst) {
730
1243
  return "ok";
731
1244
  }
732
1245
 
1246
+ // ../engine/src/physics-check.ts
1247
+ import {
1248
+ physicsInputs as physicsInputs2
1249
+ } from "@ikijs/format";
1250
+
1251
+ // ../engine/src/physics-runs.ts
1252
+ var FRAME_MS = FIXED_DT_S * 1e3 * (1 + 1e-9);
1253
+ var STEP_FRAMES = 300;
1254
+ var IDLE_FRAMES = 1800;
1255
+ var IDLE_SEED = 1;
1256
+ var MIN_TURN = 1e-9;
1257
+ function run(model, store, rigs, chains, frames, excite) {
1258
+ const raw = /* @__PURE__ */ new Map();
1259
+ const read = (id) => store.get(id);
1260
+ const sink = (id, value) => {
1261
+ let trace = raw.get(id);
1262
+ if (trace === void 0) raw.set(id, trace = []);
1263
+ trace.push(value);
1264
+ store.set(id, value);
1265
+ };
1266
+ const { parameters } = model;
1267
+ const drivers = [
1268
+ new PhysicsMotion(rigs, parameters, read, sink),
1269
+ new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink)
1270
+ ];
1271
+ for (let frame = 0; frame <= frames; frame++) {
1272
+ const nowMs = frame * FRAME_MS;
1273
+ excite(frame, nowMs);
1274
+ for (const driver of drivers) driver.update(nowMs);
1275
+ }
1276
+ const readings = /* @__PURE__ */ new Map();
1277
+ for (const driver of drivers) {
1278
+ driver.drivenParameterIds.forEach((id, i) => {
1279
+ const param = parameters.find((p) => p.id === id);
1280
+ readings.set(id, readTrace(raw.get(id), param, driver.resets[i]));
1281
+ });
1282
+ }
1283
+ return readings;
1284
+ }
1285
+ function readTrace(raw, param, resets) {
1286
+ const rest = clamp(param.default, param.min, param.max);
1287
+ const reading = {
1288
+ peak: 0,
1289
+ at: 0,
1290
+ final: rest,
1291
+ values: [],
1292
+ lo: rest,
1293
+ hi: rest,
1294
+ pinned: { frames: 0, end: "max" },
1295
+ resets
1296
+ };
1297
+ const seen = /* @__PURE__ */ new Set([rest]);
1298
+ let outside = 0;
1299
+ let end = "max";
1300
+ raw.forEach((value, frame) => {
1301
+ const held = clamp(value, param.min, param.max);
1302
+ if (Math.abs(held - rest) > Math.abs(reading.peak)) {
1303
+ reading.peak = held - rest;
1304
+ reading.at = frame * FIXED_DT_S;
1305
+ }
1306
+ if (!seen.has(held)) {
1307
+ seen.add(held);
1308
+ reading.values.push(held);
1309
+ }
1310
+ reading.lo = Math.min(reading.lo, held);
1311
+ reading.hi = Math.max(reading.hi, held);
1312
+ reading.final = held;
1313
+ if (value >= param.min && value <= param.max) {
1314
+ outside = 0;
1315
+ return;
1316
+ }
1317
+ const side = value < param.min ? "min" : "max";
1318
+ if (outside === 0 || side !== end) {
1319
+ outside = 0;
1320
+ end = side;
1321
+ }
1322
+ outside++;
1323
+ if (outside > reading.pinned.frames) {
1324
+ reading.pinned = { frames: outside, end };
1325
+ }
1326
+ });
1327
+ return reading;
1328
+ }
1329
+ function farEnd(param) {
1330
+ if (param.min === param.max) return void 0;
1331
+ const rest = clamp(param.default, param.min, param.max);
1332
+ return param.max - rest >= rest - param.min ? param.max : param.min;
1333
+ }
1334
+ function stepRun(model, rigs, chains, values) {
1335
+ const store = new ParameterStore(model.parameters);
1336
+ return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {
1337
+ if (frame !== 1) return;
1338
+ for (const [id, v] of Object.entries(values)) store.set(id, v);
1339
+ });
1340
+ }
1341
+ function idleRun(model) {
1342
+ const store = new ParameterStore(model.parameters);
1343
+ const idle = new IdleMotion((id, v) => store.set(id, v), {
1344
+ rng: lcg(IDLE_SEED)
1345
+ });
1346
+ return run(
1347
+ model,
1348
+ store,
1349
+ model.physics ?? [],
1350
+ model.physicsChains ?? [],
1351
+ IDLE_FRAMES,
1352
+ (_, nowMs) => idle.update(nowMs)
1353
+ );
1354
+ }
1355
+ function lcg(seed) {
1356
+ let state = seed >>> 0;
1357
+ return () => {
1358
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
1359
+ return state / 2 ** 32;
1360
+ };
1361
+ }
1362
+ function anchorInputs(model, chain) {
1363
+ const store = new ParameterStore(model.parameters);
1364
+ const angle = () => {
1365
+ const { worlds } = resolveDeformers(model.deformers ?? [], store);
1366
+ const world = worlds.get(chain.anchorDeformer);
1367
+ return Math.atan2(world[1], world[0]);
1368
+ };
1369
+ const rest = angle();
1370
+ const found = [];
1371
+ for (const p of model.parameters) {
1372
+ const probes = new Set(
1373
+ [p.max, p.min, ...stopsOf(model, p.id)].map(
1374
+ (v) => clamp(v, p.min, p.max)
1375
+ )
1376
+ );
1377
+ probes.delete(store.get(p.id));
1378
+ let most = 0;
1379
+ let best;
1380
+ for (const value of probes) {
1381
+ store.set(p.id, value);
1382
+ const d = angle() - rest;
1383
+ const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));
1384
+ if (turn <= most + MIN_TURN) continue;
1385
+ [most, best] = [turn, { parameter: p.id, value }];
1386
+ }
1387
+ store.reset();
1388
+ if (best) found.push(best);
1389
+ }
1390
+ return found;
1391
+ }
1392
+ function stopsOf(model, parameter) {
1393
+ const stops = /* @__PURE__ */ new Set();
1394
+ for (const d of model.deformers ?? []) {
1395
+ if (d.kind !== "warp") continue;
1396
+ for (const w of d.warps ?? []) {
1397
+ if (w.parameter !== parameter) continue;
1398
+ for (const k of w.keyforms) stops.add(k.value);
1399
+ }
1400
+ const { warp2d } = d;
1401
+ if (warp2d?.parameter === parameter) {
1402
+ for (const v of warp2d.valuesX) stops.add(v);
1403
+ }
1404
+ if (warp2d?.parameterY === parameter) {
1405
+ for (const v of warp2d.valuesY) stops.add(v);
1406
+ }
1407
+ }
1408
+ return [...stops].sort((a, b) => a - b);
1409
+ }
1410
+
1411
+ // ../engine/src/physics-check.ts
1412
+ var DISPLACEMENT_PX = 1;
1413
+ var PINNED_FRAMES = 60;
1414
+ var TOLERANCE = 1e-9;
1415
+ var UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];
1416
+ function checkPhysics(model) {
1417
+ const idle = idleRun(model);
1418
+ const displace = displacer(model);
1419
+ const idleExcitation = (output) => {
1420
+ const reading = idle.get(output.id);
1421
+ return {
1422
+ name: "the idle",
1423
+ reading,
1424
+ displacementPx: displace(output, reading.values)
1425
+ };
1426
+ };
1427
+ const param = (id) => model.parameters.find((p) => p.id === id);
1428
+ const springs = (model.physics ?? []).map((rig) => {
1429
+ const inputs = physicsInputs2(rig).map((i) => param(i.parameter));
1430
+ const ids = inputs.map((p) => p.id);
1431
+ const output = param(rig.output.parameter);
1432
+ const ranged = inputs.flatMap((input) => {
1433
+ const far = farEnd(input);
1434
+ return far === void 0 ? [] : [{ [input.id]: far }];
1435
+ });
1436
+ const settings = ranged.length === 0 ? [{}] : ranged;
1437
+ const steps = settings.map((values) => {
1438
+ const reading = stepRun(model, [rig], [], values).get(output.id);
1439
+ const setting = inputs.length === 1 ? [] : Object.entries(values).map(([id, v]) => `${id}=${v}`);
1440
+ return {
1441
+ name: ["the step", ...setting].join(" "),
1442
+ reading,
1443
+ displacementPx: displace(output, reading.values),
1444
+ values
1445
+ };
1446
+ });
1447
+ const atIdle = idleExcitation(output);
1448
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1449
+ return target(model, {
1450
+ rig: { kind: "spring", id: rig.id },
1451
+ input: ids,
1452
+ output,
1453
+ step: mostMoving(clean.length > 0 ? clean : steps),
1454
+ idle: atIdle,
1455
+ unstable: springWhy(rig) ?? unstableWhy(output, [...steps, atIdle]),
1456
+ inert: ranged.length === 0 ? `${ids.join(", ")} ${ids.length === 1 ? "has" : "have"} no range` : void 0
1457
+ });
1458
+ });
1459
+ const chains = (model.physicsChains ?? []).flatMap((chain) => {
1460
+ const candidates = anchorInputs(model, chain);
1461
+ const settings = candidates.length === 0 ? [{}] : candidates.map((c) => ({ [c.parameter]: c.value }));
1462
+ const runs = settings.map((values) => ({
1463
+ values,
1464
+ readings: stepRun(model, [], [chain], values)
1465
+ }));
1466
+ return chain.segments.map((segment, i) => {
1467
+ const output = param(segment.output.parameter);
1468
+ const steps = runs.map(({ values, readings }) => {
1469
+ const reading = readings.get(output.id);
1470
+ const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);
1471
+ return {
1472
+ name: ["the step", ...setting].join(" "),
1473
+ reading,
1474
+ displacementPx: displace(output, reading.values),
1475
+ values
1476
+ };
1477
+ });
1478
+ const atIdle = idleExcitation(output);
1479
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1480
+ return target(model, {
1481
+ rig: { kind: "chain", id: chain.id, segment: i },
1482
+ input: candidates.map((c) => c.parameter),
1483
+ output,
1484
+ step: mostMoving(clean.length > 0 ? clean : steps),
1485
+ idle: atIdle,
1486
+ unstable: unstableWhy(output, [...steps, atIdle]),
1487
+ inert: candidates.length === 0 ? `nothing turns anchor ${chain.anchorDeformer}` : void 0
1488
+ });
1489
+ });
1490
+ });
1491
+ const targets = [...springs, ...chains];
1492
+ return {
1493
+ thresholds: {
1494
+ displacementPx: DISPLACEMENT_PX,
1495
+ pinnedFrames: PINNED_FRAMES
1496
+ },
1497
+ targets,
1498
+ offenders: [
1499
+ ...targets.filter((t) => t.kind === "unstable"),
1500
+ ...targets.filter((t) => t.kind === "frozen")
1501
+ ]
1502
+ };
1503
+ }
1504
+ function target(model, t) {
1505
+ const { step, idle, output } = t;
1506
+ const drives = drivesOf(model, output.id);
1507
+ const px2 = Math.floor(step.displacementPx * 10) / 10;
1508
+ const still = step.displacementPx < DISPLACEMENT_PX ? `moves ${px2.toFixed(1)} model px over ${step.name}` : void 0;
1509
+ const frozen = drives.length === 0 ? "drives nothing" : t.inert ?? still;
1510
+ const { peak, at, final } = step.reading;
1511
+ return {
1512
+ rig: t.rig,
1513
+ input: t.input,
1514
+ output: output.id,
1515
+ drives,
1516
+ kind: t.unstable ? "unstable" : frozen ? "frozen" : "ok",
1517
+ why: t.unstable ?? frozen,
1518
+ step: {
1519
+ values: step.values,
1520
+ peak,
1521
+ at,
1522
+ final,
1523
+ displacementPx: step.displacementPx
1524
+ },
1525
+ idle: {
1526
+ peak: Math.abs(idle.reading.peak),
1527
+ at: idle.reading.at,
1528
+ displacementPx: idle.displacementPx
1529
+ }
1530
+ };
1531
+ }
1532
+ function mostMoving(steps) {
1533
+ return steps.reduce((best, s) => {
1534
+ if (s.displacementPx !== best.displacementPx) {
1535
+ return s.displacementPx > best.displacementPx ? s : best;
1536
+ }
1537
+ return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;
1538
+ });
1539
+ }
1540
+ function drivesOf(model, output) {
1541
+ const parts = model.parts.filter(
1542
+ (p) => [
1543
+ ...(p.bindings ?? []).map((b) => b.parameter),
1544
+ ...(p.warps ?? []).map((w) => w.parameter)
1545
+ ].includes(output)
1546
+ );
1547
+ const deformers = (model.deformers ?? []).filter(
1548
+ (d) => (d.kind === "warp" ? [
1549
+ ...(d.warps ?? []).map((w) => w.parameter),
1550
+ d.warp2d?.parameter,
1551
+ d.warp2d?.parameterY
1552
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output)
1553
+ );
1554
+ return [
1555
+ ...parts.map((p) => ({ kind: "part", id: p.id })),
1556
+ ...deformers.map((d) => ({ kind: "deformer", id: d.id }))
1557
+ ];
1558
+ }
1559
+ function springStepRadius({ mass, stiffness, damping }) {
1560
+ const k = FIXED_DT_S * FIXED_DT_S * stiffness / mass;
1561
+ const c = FIXED_DT_S * damping / mass;
1562
+ const trace = 2 - k - c;
1563
+ const det = 1 - c;
1564
+ const disc = trace * trace - 4 * det;
1565
+ const radius = disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);
1566
+ return { radius, k };
1567
+ }
1568
+ function springWhy(rig) {
1569
+ const { radius, k } = springStepRadius(rig);
1570
+ if (radius > 1 + TOLERANCE) {
1571
+ let digits = 2;
1572
+ while (Number(radius.toFixed(digits)) <= 1) digits++;
1573
+ return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;
1574
+ }
1575
+ if (rig.damping === 0 && k >= 4 - TOLERANCE) {
1576
+ return `spring on its undamped boundary, dt\xB2k/m ${k.toFixed(2)}`;
1577
+ }
1578
+ return void 0;
1579
+ }
1580
+ function unstableWhy(output, excitations) {
1581
+ for (const { name, reading } of excitations) {
1582
+ const n = reading.resets;
1583
+ if (n === 0) continue;
1584
+ return `finiteness guard reset it ${n} time${n === 1 ? "" : "s"} in ${name}`;
1585
+ }
1586
+ for (const { name, reading } of excitations) {
1587
+ const { frames, end } = reading.pinned;
1588
+ if (frames < PINNED_FRAMES) continue;
1589
+ return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;
1590
+ }
1591
+ return void 0;
1592
+ }
1593
+ function displacer(model) {
1594
+ const deformers = model.deformers ?? [];
1595
+ const store = new ParameterStore(model.parameters);
1596
+ const { worlds } = resolveDeformers(staticDeformers(model), store);
1597
+ const landings = model.parts.map(
1598
+ (part) => landedPart(
1599
+ part,
1600
+ part.mesh?.vertices ?? UNIT_QUAD,
1601
+ deformers,
1602
+ worlds,
1603
+ store
1604
+ )
1605
+ );
1606
+ const atRest = resolveDeformers(deformers, store);
1607
+ const baselines = landings.map(
1608
+ (l) => Float32Array.from(landPart(l, store, atRest))
1609
+ );
1610
+ return (output, values) => {
1611
+ let most = 0;
1612
+ const affected = affectedParts(model, output.id);
1613
+ for (const value of values) {
1614
+ store.set(output.id, value);
1615
+ const resolved = resolveDeformers(deformers, store);
1616
+ landings.forEach((landing, i) => {
1617
+ if (!affected.has(landing.part)) return;
1618
+ const landed = landPart(landing, store, resolved);
1619
+ const base = baselines[i];
1620
+ for (let j = 0; j < landed.length; j += 2) {
1621
+ const dx = landed[j] - base[j];
1622
+ const dy = landed[j + 1] - base[j + 1];
1623
+ most = Math.max(most, dx * dx + dy * dy);
1624
+ }
1625
+ });
1626
+ }
1627
+ store.reset();
1628
+ return Math.sqrt(most);
1629
+ };
1630
+ }
1631
+ function affectedParts(model, output) {
1632
+ const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));
1633
+ const reads = (d) => (d.kind === "warp" ? [
1634
+ ...(d.warps ?? []).map((w) => w.parameter),
1635
+ d.warp2d?.parameter,
1636
+ d.warp2d?.parameterY
1637
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output);
1638
+ const hung = (id) => {
1639
+ for (let d = id && deformers.get(id); d; d = d.parent && deformers.get(d.parent)) {
1640
+ if (reads(d)) return true;
1641
+ }
1642
+ return false;
1643
+ };
1644
+ return new Set(
1645
+ model.parts.filter(
1646
+ (p) => [
1647
+ ...(p.bindings ?? []).map((b) => b.parameter),
1648
+ ...(p.warps ?? []).map((w) => w.parameter)
1649
+ ].includes(output) || hung(p.deformer)
1650
+ )
1651
+ );
1652
+ }
1653
+
733
1654
  // src/fold-report.ts
734
1655
  function checkModelFolds(model, extraValues = []) {
735
1656
  const declared = new Set(model.parameters.map((p) => p.id));
@@ -738,9 +1659,9 @@ function checkModelFolds(model, extraValues = []) {
738
1659
  // The effective value, not the pose's overrides: the auto-rig's mouth
739
1660
  // rests shut at its default, so `rest` and the other parameters' singles
740
1661
  // are shut-mouth poses too.
741
- expected: (target, _pose, value) => {
742
- if (target.kind !== "part") return false;
743
- const shutBy = SHUT_BY.get(target.id);
1662
+ expected: (target2, _pose, value) => {
1663
+ if (target2.kind !== "part") return false;
1664
+ const shutBy = SHUT_BY.get(target2.id);
744
1665
  return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
745
1666
  }
746
1667
  });
@@ -1446,6 +2367,7 @@ async function renderPoses(input) {
1446
2367
  model,
1447
2368
  input.poses?.map((p) => p.values)
1448
2369
  );
2370
+ const physics = checkPhysics(model);
1449
2371
  const { failedTextures, poses } = await withBrowser(
1450
2372
  browser,
1451
2373
  async (evaluate) => {
@@ -1482,7 +2404,8 @@ async function renderPoses(input) {
1482
2404
  failedTextures,
1483
2405
  poses,
1484
2406
  modelCanvas: model.canvas,
1485
- folds
2407
+ folds,
2408
+ physics
1486
2409
  };
1487
2410
  } catch (error) {
1488
2411
  if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {
@@ -1755,6 +2678,10 @@ var STANDARD_PARAMETER_INFO = [
1755
2678
  id: StandardParameter4.Breath,
1756
2679
  description: "Idle breath (0 .. 1), cycled by the host."
1757
2680
  },
2681
+ {
2682
+ id: StandardParameter4.AmbientSway,
2683
+ description: "Ambient sway (-1 .. 1): a slow zero-mean drift the idle writes for physics rigs to follow (the auto-rig's hair in idle). Not a wind: no bias. Stays procedural under a declared Idle group, as Breath does."
2684
+ },
1758
2685
  {
1759
2686
  id: StandardParameter4.BrowLeftY,
1760
2687
  description: "Left brow raise/lower (-1 .. 1)."
@@ -2015,6 +2942,7 @@ async function autoRigFromLayers(input) {
2015
2942
  const finalModel = parseIkiModel(patched);
2016
2943
  writeFileAtomic(outPath, JSON.stringify(finalModel));
2017
2944
  const folds = checkModelFolds(finalModel);
2945
+ const physics = checkPhysics(finalModel);
2018
2946
  return {
2019
2947
  ok: true,
2020
2948
  path: outPath,
@@ -2028,6 +2956,7 @@ async function autoRigFromLayers(input) {
2028
2956
  ...noseCore === void 0 ? {} : { noseCore },
2029
2957
  ...turn === void 0 ? {} : { turn },
2030
2958
  folds,
2959
+ physics,
2031
2960
  ...patches === void 0 ? {} : { patches }
2032
2961
  };
2033
2962
  } catch (err) {
@@ -3477,16 +4406,16 @@ async function layerStats(filePath) {
3477
4406
  let flatCutRun = 0;
3478
4407
  let flatCutY = -1;
3479
4408
  for (let y = minY + 1; y <= maxY; y++) {
3480
- let run = 0;
4409
+ let run2 = 0;
3481
4410
  for (let x = minX; x <= maxX; x++) {
3482
4411
  if (alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE && alpha(x, y) > FLAT_CUT_ALPHA_BELOW) {
3483
- run++;
3484
- if (run > flatCutRun) {
3485
- flatCutRun = run;
4412
+ run2++;
4413
+ if (run2 > flatCutRun) {
4414
+ flatCutRun = run2;
3486
4415
  flatCutY = y;
3487
4416
  }
3488
4417
  } else {
3489
- run = 0;
4418
+ run2 = 0;
3490
4419
  }
3491
4420
  }
3492
4421
  }
@@ -4749,6 +5678,22 @@ async function composeLayersFromParts(input) {
4749
5678
  }
4750
5679
  }
4751
5680
 
5681
+ // src/physics-report.ts
5682
+ function formatPhysicsReport(report) {
5683
+ if (report.targets.length === 0) return ["PHYSICS: no rigs"];
5684
+ return report.targets.map(targetLine);
5685
+ }
5686
+ function targetLine(t) {
5687
+ const inputs = t.input.join(", ");
5688
+ const rig = t.rig.kind === "chain" ? `${t.rig.id}/${t.rig.segment} [${inputs}]` : `${t.rig.id} ${inputs}`;
5689
+ const drives = t.drives.length === 0 ? "" : ` (${t.drives.map((d) => d.id).join(", ")})`;
5690
+ const { step, idle } = t;
5691
+ return `PHYSICS ${t.kind} ${rig} -> ${t.output}: step ${foldPose(step.values).name} peak ${step.peak.toFixed(2)} at ${step.at.toFixed(2)} s, final ${step.final.toFixed(2)}, moves ${pxText(step.displacementPx)} model px${drives}; idle peak ${idle.peak.toFixed(2)} at ${idle.at.toFixed(2)} s, ${pxText(idle.displacementPx)} model px` + (t.why === void 0 ? "" : ` \u2014 ${t.why}`);
5692
+ }
5693
+ function pxText(px2) {
5694
+ return (Math.floor(px2 * 10) / 10).toFixed(1);
5695
+ }
5696
+
4752
5697
  // src/server.ts
4753
5698
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4754
5699
  import { z } from "zod";
@@ -4760,7 +5705,7 @@ function formatPatchReports(reports) {
4760
5705
  });
4761
5706
  }
4762
5707
  function createIkiMcpServer() {
4763
- const server = new McpServer({ name: "iki", version: "0.26.1" });
5708
+ const server = new McpServer({ name: "iki", version: "0.28.0" });
4764
5709
  server.registerTool(
4765
5710
  "validate_iki",
4766
5711
  {
@@ -4835,7 +5780,7 @@ function createIkiMcpServer() {
4835
5780
  server.registerTool(
4836
5781
  "auto_rig_from_layers",
4837
5782
  {
4838
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
5783
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
4839
5784
  inputSchema: {
4840
5785
  layers: z.array(
4841
5786
  z.object({
@@ -4901,7 +5846,8 @@ function createIkiMcpServer() {
4901
5846
  const text = r.ok ? [
4902
5847
  r.path,
4903
5848
  ...formatPatchReports(r.patches ?? []),
4904
- ...formatFoldReport(r.folds, r.canvas)
5849
+ ...formatFoldReport(r.folds, r.canvas),
5850
+ ...formatPhysicsReport(r.physics)
4905
5851
  ].join("\n") : `INVALID: ${r.error}`;
4906
5852
  return { content: [{ type: "text", text }], structuredContent: r };
4907
5853
  } catch (err) {
@@ -5030,7 +5976,7 @@ function createIkiMcpServer() {
5030
5976
  server.registerTool(
5031
5977
  "render_poses",
5032
5978
  {
5033
- description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
5979
+ description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output of the model's own rigs \u2014 `poses` do not enter it \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
5034
5980
  inputSchema: {
5035
5981
  modelPath: z.string().describe(
5036
5982
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -5059,7 +6005,8 @@ function createIkiMcpServer() {
5059
6005
  const r = await renderPoses(args);
5060
6006
  const text = r.ok ? [
5061
6007
  ...r.poses.map((p) => p.path),
5062
- ...formatFoldReport(r.folds, r.modelCanvas)
6008
+ ...formatFoldReport(r.folds, r.modelCanvas),
6009
+ ...formatPhysicsReport(r.physics)
5063
6010
  ].join("\n") : `INVALID: ${r.error}`;
5064
6011
  return { content: [{ type: "text", text }], structuredContent: r };
5065
6012
  } catch (err) {
@@ -5089,6 +6036,7 @@ export {
5089
6036
  measureLayers,
5090
6037
  formatMeasureReport,
5091
6038
  composeLayersFromParts,
6039
+ formatPhysicsReport,
5092
6040
  createIkiMcpServer
5093
6041
  };
5094
- //# sourceMappingURL=chunk-GPEGV2AT.mjs.map
6042
+ //# sourceMappingURL=chunk-D2OLX5S7.mjs.map