@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.
package/dist/cli.js CHANGED
@@ -14,12 +14,12 @@ var __copyProps = (to, from, except, desc) => {
14
14
  }
15
15
  return to;
16
16
  };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
18
  // If the importer is in node compatibility mode or this is not an ESM
19
19
  // file that has been converted to a CommonJS file using a Babel-
20
20
  // compatible transform (i.e. "__esModule" has not been set), then set
21
21
  // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
23
23
  mod
24
24
  ));
25
25
 
@@ -34,12 +34,9 @@ var import_zod = require("zod");
34
34
  // src/tools.ts
35
35
  var import_node_fs4 = require("fs");
36
36
  var import_node_path4 = __toESM(require("path"));
37
- var import_format7 = require("@ikijs/format");
37
+ var import_format9 = require("@ikijs/format");
38
38
  var import_editor3 = require("@ikijs/editor");
39
39
 
40
- // src/fold-report.ts
41
- var import_editor = require("@ikijs/editor");
42
-
43
40
  // ../engine/src/math.ts
44
41
  function clamp(value, min, max) {
45
42
  return Math.max(min, Math.min(max, value));
@@ -47,6 +44,10 @@ function clamp(value, min, max) {
47
44
  function lerp(a, b, t) {
48
45
  return a + (b - a) * t;
49
46
  }
47
+ function smoothstep(x) {
48
+ const t = clamp(x, 0, 1);
49
+ return t * t * (3 - 2 * t);
50
+ }
50
51
 
51
52
  // ../engine/src/parameter-store.ts
52
53
  var ParameterStore = class {
@@ -452,54 +453,607 @@ function resolveDeformers(deformers, params) {
452
453
  var import_format = require("@ikijs/format");
453
454
 
454
455
  // ../engine/src/frame-clock.ts
456
+ var MAX_DT_MS = 100;
455
457
  var FIXED_DT_S = 1 / 60;
458
+ var MAX_SUBSTEPS = 6;
459
+ var FixedStepClock = class {
460
+ prevNowMs = void 0;
461
+ accumulatorS = 0;
462
+ /**
463
+ * True until the first {@link advance}. Drivers seed their rest pose on that
464
+ * frame and integrate nothing, so a model loaded mid-motion does not kick.
465
+ */
466
+ get isSeedFrame() {
467
+ return this.prevNowMs === void 0;
468
+ }
469
+ /**
470
+ * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}
471
+ * sub-steps to run this frame. On the seed frame it only records the
472
+ * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.
473
+ */
474
+ advance(nowMs) {
475
+ if (!Number.isFinite(nowMs)) return 0;
476
+ if (this.prevNowMs === void 0) {
477
+ this.prevNowMs = nowMs;
478
+ return 0;
479
+ }
480
+ const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);
481
+ this.prevNowMs = nowMs;
482
+ this.accumulatorS += dtMs / 1e3;
483
+ let steps = 0;
484
+ while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {
485
+ this.accumulatorS -= FIXED_DT_S;
486
+ steps++;
487
+ }
488
+ return steps;
489
+ }
490
+ };
456
491
 
457
492
  // ../engine/src/idle-motion.ts
493
+ var BLINK_INTERVAL_MIN_MS = 1500;
494
+ var BLINK_INTERVAL_MAX_MS = 6e3;
458
495
  var BLINK_CLOSE_MS = 60;
459
496
  var BLINK_HOLD_MS = 20;
460
497
  var BLINK_OPEN_MS = 100;
461
498
  var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
499
+ var BREATH_PERIOD_MS = 3500;
500
+ var GAZE_RADIUS = 0.3;
501
+ var GAZE_RETARGET_MIN_MS = 1200;
502
+ var GAZE_RETARGET_MAX_MS = 3e3;
503
+ var GAZE_EASE_RATE = 1e-3;
504
+ var SWAY_X_AMP_A_DEG = 2.2;
505
+ var SWAY_X_PERIOD_A_MS = 6100;
506
+ var SWAY_X_AMP_B_DEG = 1.3;
507
+ var SWAY_X_PERIOD_B_MS = 9700;
508
+ var SWAY_Y_AMP_DEG = 1.6;
509
+ var SWAY_Y_PERIOD_MS = 7300;
510
+ var SWAY_Z_AMP_DEG = 1.1;
511
+ var SWAY_Z_PERIOD_MS = 11300;
512
+ var AMBIENT_AMP_A = 0.6;
513
+ var AMBIENT_PERIOD_A_MS = 2900;
514
+ var AMBIENT_AMP_B = 0.4;
515
+ var AMBIENT_PERIOD_B_MS = 4300;
516
+ function blinkEnvelope(phase) {
517
+ const ms = phase * BLINK_DURATION_MS;
518
+ if (ms <= 0) return 1;
519
+ if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);
520
+ if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0;
521
+ if (ms < BLINK_DURATION_MS) {
522
+ const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;
523
+ return 1 - (1 - t) * (1 - t);
524
+ }
525
+ return 1;
526
+ }
527
+ function randomInDisk(rng, radius) {
528
+ const r = Math.sqrt(rng()) * radius;
529
+ const theta = rng() * 2 * Math.PI;
530
+ return [r * Math.cos(theta), r * Math.sin(theta)];
531
+ }
532
+ var IdleMotion = class {
533
+ /**
534
+ * Every parameter id {@link update} and `emitRestingPose` write, in write
535
+ * order. Published so a host (or IkiMotion) can restore them after it
536
+ * stops driving — keep in step with those two methods; the test suite
537
+ * pins this list to the actual emissions.
538
+ */
539
+ drivenParameterIds = [
540
+ import_format.StandardParameter.EyeOpenLeft,
541
+ import_format.StandardParameter.EyeOpenRight,
542
+ import_format.StandardParameter.Breath,
543
+ import_format.StandardParameter.EyeballX,
544
+ import_format.StandardParameter.EyeballY,
545
+ import_format.StandardParameter.AngleX,
546
+ import_format.StandardParameter.AngleY,
547
+ import_format.StandardParameter.AngleZ,
548
+ import_format.StandardParameter.AmbientSway
549
+ ];
550
+ sink;
551
+ rng;
552
+ // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.
553
+ // This is the only clock blink/breath/gaze scheduling reads.
554
+ clockMs = 0;
555
+ prevNowMs = void 0;
556
+ // Blink state
557
+ nextBlinkAtMs;
558
+ blinkStartMs = -1;
559
+ // -1 means not currently blinking
560
+ // Gaze state
561
+ gazeCurrentX = 0;
562
+ gazeCurrentY = 0;
563
+ gazeTargetX = 0;
564
+ gazeTargetY = 0;
565
+ nextGazeRetargetMs;
566
+ constructor(sink, options) {
567
+ this.sink = sink;
568
+ this.rng = options?.rng ?? Math.random;
569
+ this.nextBlinkAtMs = lerp(
570
+ BLINK_INTERVAL_MIN_MS,
571
+ BLINK_INTERVAL_MAX_MS,
572
+ this.rng()
573
+ );
574
+ this.nextGazeRetargetMs = lerp(
575
+ GAZE_RETARGET_MIN_MS,
576
+ GAZE_RETARGET_MAX_MS,
577
+ this.rng()
578
+ );
579
+ }
580
+ /**
581
+ * Advance the idle animation to the given wall-clock timestamp (milliseconds).
582
+ *
583
+ * On the first call: record prevNowMs, emit the resting pose, and return —
584
+ * no animation advance happens so there is no jump from time 0.
585
+ *
586
+ * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)
587
+ * and advance the internal clock by dt. A non-monotonic nowMs produces a
588
+ * negative raw delta that the clamp floors to 0 — no rewind.
589
+ */
590
+ update(nowMs) {
591
+ if (!Number.isFinite(nowMs)) return;
592
+ if (this.prevNowMs === void 0) {
593
+ this.prevNowMs = nowMs;
594
+ this.emitRestingPose();
595
+ return;
596
+ }
597
+ const rawDt = nowMs - this.prevNowMs;
598
+ const dt = clamp(rawDt, 0, MAX_DT_MS);
599
+ this.prevNowMs = nowMs;
600
+ this.clockMs += dt;
601
+ const eyeVal = this.advanceBlink();
602
+ this.sink(import_format.StandardParameter.EyeOpenLeft, eyeVal);
603
+ this.sink(import_format.StandardParameter.EyeOpenRight, eyeVal);
604
+ const breath = this.advanceBreath();
605
+ this.advanceGaze(dt);
606
+ this.sink(import_format.StandardParameter.Breath, breath);
607
+ this.sink(import_format.StandardParameter.EyeballX, this.gazeCurrentX);
608
+ this.sink(import_format.StandardParameter.EyeballY, this.gazeCurrentY);
609
+ this.sink(import_format.StandardParameter.AngleX, this.swayX());
610
+ this.sink(import_format.StandardParameter.AngleY, this.swayY());
611
+ this.sink(import_format.StandardParameter.AngleZ, this.swayZ());
612
+ this.sink(import_format.StandardParameter.AmbientSway, this.ambientSway());
613
+ }
614
+ // ---------------------------------------------------------------------------
615
+ // Private helpers
616
+ // ---------------------------------------------------------------------------
617
+ emitRestingPose() {
618
+ this.sink(import_format.StandardParameter.EyeOpenLeft, 1);
619
+ this.sink(import_format.StandardParameter.EyeOpenRight, 1);
620
+ this.sink(import_format.StandardParameter.Breath, 0.5);
621
+ this.sink(import_format.StandardParameter.EyeballX, 0);
622
+ this.sink(import_format.StandardParameter.EyeballY, 0);
623
+ this.sink(import_format.StandardParameter.AngleX, 0);
624
+ this.sink(import_format.StandardParameter.AngleY, 0);
625
+ this.sink(import_format.StandardParameter.AngleZ, 0);
626
+ this.sink(import_format.StandardParameter.AmbientSway, 0);
627
+ }
628
+ /** Returns the current eye-open value (0..1) and advances blink state. */
629
+ advanceBlink() {
630
+ const { clockMs } = this;
631
+ if (this.blinkStartMs >= 0) {
632
+ const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;
633
+ if (phase >= 1) {
634
+ this.blinkStartMs = -1;
635
+ this.nextBlinkAtMs = clockMs + lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());
636
+ return 1;
637
+ }
638
+ return blinkEnvelope(phase);
639
+ }
640
+ if (clockMs >= this.nextBlinkAtMs) {
641
+ this.blinkStartMs = clockMs;
642
+ return blinkEnvelope(0);
643
+ }
644
+ return 1;
645
+ }
646
+ advanceBreath() {
647
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * this.clockMs / BREATH_PERIOD_MS);
648
+ }
649
+ /** Horizontal head sway in degrees, pure function of the internal clock. */
650
+ swayX() {
651
+ const t = 2 * Math.PI * this.clockMs;
652
+ 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);
653
+ }
654
+ /** Vertical head sway in degrees, pure function of the internal clock. */
655
+ swayY() {
656
+ return SWAY_Y_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Y_PERIOD_MS);
657
+ }
658
+ /** Head roll sway in degrees, pure function of the internal clock. */
659
+ swayZ() {
660
+ return SWAY_Z_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Z_PERIOD_MS);
661
+ }
662
+ /** Ambient sway (-1..1), pure function of the internal clock. */
663
+ ambientSway() {
664
+ const t = 2 * Math.PI * this.clockMs;
665
+ return AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) + AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS);
666
+ }
667
+ /** Ease gaze current toward target; pick a new target on the internal clock. */
668
+ advanceGaze(dt) {
669
+ if (this.clockMs >= this.nextGazeRetargetMs) {
670
+ const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);
671
+ this.gazeTargetX = tx;
672
+ this.gazeTargetY = ty;
673
+ this.nextGazeRetargetMs = this.clockMs + lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());
674
+ }
675
+ const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);
676
+ this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);
677
+ this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);
678
+ }
679
+ };
680
+
681
+ // ../engine/src/physics-motion.ts
682
+ var import_format2 = require("@ikijs/format");
683
+ function signedNormalized(value, param) {
684
+ const rest = clamp(param.default, param.min, param.max);
685
+ const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));
686
+ if (den === 0) return 0;
687
+ return clamp((value - rest) / den, -1, 1);
688
+ }
689
+ var PhysicsMotion = class {
690
+ /** The output parameter of every rig, in rig order — what `emit` writes. */
691
+ drivenParameterIds;
692
+ /**
693
+ * Per rig: how many times the finiteness guard reset its state or `emit`
694
+ * replaced its non-finite product. Up to two per frame, so guard activations,
695
+ * not repaired frames. A diagnostic; emitted values are unchanged.
696
+ */
697
+ resets;
698
+ resetCounts;
699
+ rigs;
700
+ inputs;
701
+ read;
702
+ sink;
703
+ params;
704
+ // Integrator state, owned here — never stored in a ParameterStore.
705
+ state;
706
+ clock = new FixedStepClock();
707
+ constructor(rigs, params, read, sink) {
708
+ this.rigs = rigs;
709
+ this.inputs = rigs.map(
710
+ (rig) => (0, import_format2.physicsInputs)(rig).map(({ parameter, weight, mode }) => ({
711
+ parameter,
712
+ weight,
713
+ lag: mode === "lag"
714
+ }))
715
+ );
716
+ this.read = read;
717
+ this.sink = sink;
718
+ this.params = new Map(params.map((p) => [p.id, p]));
719
+ this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));
720
+ this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);
721
+ this.resetCounts = rigs.map(() => 0);
722
+ this.resets = this.resetCounts;
723
+ }
724
+ /**
725
+ * Advance every rig to the given wall-clock timestamp (milliseconds).
726
+ *
727
+ * First call: seed each spring to rest AT its current target (so a model
728
+ * loaded with a nonzero input does not kick: a lag input emits rest, a follow
729
+ * input its value), emit that output, and return without integrating —
730
+ * mirroring IdleMotion's first-frame behavior.
731
+ *
732
+ * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its
733
+ * last output from its stored state without reading its inputs.
734
+ *
735
+ * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into
736
+ * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;
737
+ * the spring advances that many semi-implicit Euler steps, then each rig emits
738
+ * its output once. The clock's dt clamp and sub-step cap plus the symplectic
739
+ * integrator are what keep it stable across hitches.
740
+ */
741
+ update(nowMs) {
742
+ if (this.clock.isSeedFrame) {
743
+ this.clock.advance(nowMs);
744
+ for (let i = 0; i < this.rigs.length; i++) {
745
+ const st = this.state[i];
746
+ const { target: target2, lag } = this.targetFor(i);
747
+ st.x = target2;
748
+ st.v = 0;
749
+ st.lag = lag;
750
+ this.emit(i, st);
751
+ }
752
+ return;
753
+ }
754
+ if (!Number.isFinite(nowMs)) {
755
+ for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);
756
+ return;
757
+ }
758
+ const steps = this.clock.advance(nowMs);
759
+ const targets = this.rigs.map((_, i) => this.targetFor(i));
760
+ for (let s = 0; s < steps; s++) {
761
+ for (let i = 0; i < this.rigs.length; i++) {
762
+ this.step(this.rigs[i], this.state[i], targets[i].target);
763
+ }
764
+ }
765
+ for (let i = 0; i < this.rigs.length; i++) {
766
+ const st = this.state[i];
767
+ const { target: target2, lag } = targets[i];
768
+ if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {
769
+ st.x = Number.isFinite(target2) ? target2 : 0;
770
+ st.v = 0;
771
+ this.resetCounts[i]++;
772
+ }
773
+ st.lag = lag;
774
+ this.emit(i, st);
775
+ }
776
+ }
777
+ /**
778
+ * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,
779
+ * and `L`, the lag inputs' share of it. Reads each input once.
780
+ */
781
+ targetFor(index) {
782
+ let target2 = 0;
783
+ let lag = 0;
784
+ for (const input of this.inputs[index]) {
785
+ const param = this.params.get(input.parameter);
786
+ const value = this.read(input.parameter);
787
+ const share = (param ? signedNormalized(value, param) : 0) * input.weight;
788
+ target2 += share;
789
+ if (input.lag) lag += share;
790
+ }
791
+ return { target: target2, lag };
792
+ }
793
+ /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */
794
+ step(rig, st, target2) {
795
+ const accel = (rig.stiffness * (target2 - st.x) - rig.damping * st.v) / rig.mass;
796
+ st.v += accel * FIXED_DT_S;
797
+ st.x += st.v * FIXED_DT_S;
798
+ }
799
+ /** Write outputDefault + (x − L) * scale onto the output param via the sink. */
800
+ emit(index, st) {
801
+ const rig = this.rigs[index];
802
+ const outParam = this.params.get(rig.output.parameter);
803
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
804
+ const value = outDefault + (st.x - st.lag) * rig.output.scale;
805
+ const finite = Number.isFinite(value);
806
+ if (!finite) this.resetCounts[index]++;
807
+ this.sink(rig.output.parameter, finite ? value : outDefault);
808
+ }
809
+ };
462
810
 
463
811
  // ../engine/src/hair-chain-motion.ts
464
812
  var DEG2RAD = Math.PI / 180;
465
813
  var RAD2DEG = 180 / Math.PI;
814
+ var HairChainMotion = class {
815
+ /** Every segment's output, chain by chain — what `emitSegment` writes. */
816
+ drivenParameterIds;
817
+ /**
818
+ * Per segment, in `drivenParameterIds` order: how many times the finiteness
819
+ * guard reset its state or `emitSegment` replaced its non-finite product. Up
820
+ * to two per frame, so guard activations, not repaired frames. A diagnostic;
821
+ * emitted values are unchanged.
822
+ */
823
+ resets;
824
+ resetCounts;
825
+ chainData;
826
+ params;
827
+ deformers;
828
+ store;
829
+ read;
830
+ sink;
831
+ clock = new FixedStepClock();
832
+ constructor(chains, params, deformers, read, sink) {
833
+ this.params = new Map(params.map((p) => [p.id, p]));
834
+ this.deformers = deformers;
835
+ this.store = new ParameterStore(params);
836
+ this.read = read;
837
+ this.sink = sink;
838
+ this.chainData = chains.map((chain) => ({
839
+ chain,
840
+ restAnglesRad: chain.segments.map(
841
+ (seg) => seg.restAngle !== void 0 ? seg.restAngle * DEG2RAD : 0
842
+ ),
843
+ state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 }))
844
+ }));
845
+ this.drivenParameterIds = chains.flatMap(
846
+ (c) => c.segments.map((s) => s.output.parameter)
847
+ );
848
+ this.resetCounts = this.drivenParameterIds.map(() => 0);
849
+ this.resets = this.resetCounts;
850
+ }
851
+ /**
852
+ * Advance every chain to the given wall-clock timestamp (milliseconds).
853
+ *
854
+ * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output
855
+ * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's
856
+ * first-frame behavior so a model loaded in motion does not kick.
857
+ *
858
+ * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into
859
+ * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE
860
+ * per update() — NOT per chain — so all chains share a consistent frame snapshot.
861
+ * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover
862
+ * time is carried to the next frame. Segments emit after substeps (even on zero
863
+ * substeps) with a non-finite guard.
864
+ */
865
+ update(nowMs) {
866
+ if (this.chainData.length === 0) return;
867
+ if (this.clock.isSeedFrame) {
868
+ this.clock.advance(nowMs);
869
+ let flat2 = 0;
870
+ for (const cd of this.chainData) {
871
+ for (let i = 0; i < cd.chain.segments.length; i++) {
872
+ cd.state[i].angle = 0;
873
+ cd.state[i].angularVelocity = 0;
874
+ this.emitSegment(flat2++, cd.chain.segments[i], cd.state[i]);
875
+ }
876
+ }
877
+ return;
878
+ }
879
+ const steps = this.clock.advance(nowMs);
880
+ for (const param of this.params.values()) {
881
+ this.store.set(param.id, this.read(param.id));
882
+ }
883
+ const worldMap = resolveDeformers(this.deformers, this.store).worlds;
884
+ const anchorAnglesRad = this.chainData.map(
885
+ (cd) => this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer)
886
+ );
887
+ for (let s = 0; s < steps; s++) {
888
+ for (let c = 0; c < this.chainData.length; c++) {
889
+ this.stepChain(this.chainData[c], anchorAnglesRad[c]);
890
+ }
891
+ }
892
+ let flat = 0;
893
+ for (const cd of this.chainData) {
894
+ for (let i = 0; i < cd.chain.segments.length; i++) {
895
+ const st = cd.state[i];
896
+ if (!Number.isFinite(st.angle) || !Number.isFinite(st.angularVelocity)) {
897
+ st.angle = 0;
898
+ st.angularVelocity = 0;
899
+ this.resetCounts[flat]++;
900
+ }
901
+ this.emitSegment(flat++, cd.chain.segments[i], st);
902
+ }
903
+ }
904
+ }
905
+ /**
906
+ * Extract world rotation (radians) from the anchor's Affine tuple.
907
+ * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).
908
+ *
909
+ * If the anchor id is absent from the map, THROWS an internal Error — the
910
+ * format validator guarantees the anchor exists, so absence is an invariant
911
+ * break (mirrors resolveDeformers' throw on an unresolved parent).
912
+ */
913
+ anchorWorldAngleRad(worldMap, anchorId) {
914
+ const world = worldMap.get(anchorId);
915
+ if (!world) {
916
+ throw new Error(
917
+ `HairChainMotion: anchor deformer "${anchorId}" not found in resolved world map \u2014 model not validated?`
918
+ );
919
+ }
920
+ return Math.atan2(world[1], world[0]);
921
+ }
922
+ /**
923
+ * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.
924
+ *
925
+ * Segments are integrated ROOT→TIP so each segment can read its upstream
926
+ * neighbor's current-substep state when computing the world angle Φ_i.
927
+ * (The chain is causal root-to-tip; reversing the order would use stale θ
928
+ * values from the previous substep for Φ_i computation.)
929
+ *
930
+ * Per-segment semi-implicit (symplectic) Euler:
931
+ * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)
932
+ * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i
933
+ * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)
934
+ * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)
935
+ *
936
+ * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear
937
+ * in the spring term, only in Φ_i for the gravity torque.
938
+ */
939
+ stepChain(cd, anchorAngleRad) {
940
+ const { chain, restAnglesRad, state } = cd;
941
+ const gravityAngleRad = chain.gravity.angle * DEG2RAD;
942
+ const strength = chain.gravity.strength;
943
+ let worldAngleAccumRad = anchorAngleRad;
944
+ for (let i = 0; i < chain.segments.length; i++) {
945
+ const seg = chain.segments[i];
946
+ const st = state[i];
947
+ worldAngleAccumRad += restAnglesRad[i] + st.angle;
948
+ const phi = worldAngleAccumRad;
949
+ const alpha = (-seg.stiffness * st.angle - strength * Math.sin(phi - gravityAngleRad) - seg.damping * st.angularVelocity) / seg.mass;
950
+ st.angularVelocity += alpha * FIXED_DT_S;
951
+ st.angle += st.angularVelocity * FIXED_DT_S;
952
+ }
953
+ }
954
+ /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */
955
+ emitSegment(flat, seg, st) {
956
+ const outParam = this.params.get(seg.output.parameter);
957
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
958
+ const value = outDefault + st.angle * RAD2DEG * seg.output.scale;
959
+ const finite = Number.isFinite(value);
960
+ if (!finite) this.resetCounts[flat]++;
961
+ this.sink(seg.output.parameter, finite ? value : outDefault);
962
+ }
963
+ };
466
964
 
467
965
  // ../engine/src/iki-motion.ts
468
- var import_format4 = require("@ikijs/format");
966
+ var import_format5 = require("@ikijs/format");
469
967
 
470
968
  // ../engine/src/clip-player.ts
471
- var import_format2 = require("@ikijs/format");
969
+ var import_format3 = require("@ikijs/format");
472
970
 
473
971
  // ../engine/src/expression-player.ts
474
- var import_format3 = require("@ikijs/format");
972
+ var import_format4 = require("@ikijs/format");
475
973
 
476
974
  // ../engine/src/iki-motion.ts
477
975
  var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
478
- import_format4.StandardParameter.AngleX,
479
- import_format4.StandardParameter.AngleY,
480
- import_format4.StandardParameter.AngleZ,
481
- import_format4.StandardParameter.EyeballX,
482
- import_format4.StandardParameter.EyeballY
976
+ import_format5.StandardParameter.AngleX,
977
+ import_format5.StandardParameter.AngleY,
978
+ import_format5.StandardParameter.AngleZ,
979
+ import_format5.StandardParameter.EyeballX,
980
+ import_format5.StandardParameter.EyeballY
483
981
  ]);
484
982
 
485
983
  // ../engine/src/folds.ts
486
- var import_format5 = require("@ikijs/format");
984
+ var import_format6 = require("@ikijs/format");
985
+
986
+ // ../engine/src/land.ts
987
+ function staticDeformers(model) {
988
+ return (model.deformers ?? []).map(
989
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
990
+ );
991
+ }
992
+ function placement(part, t) {
993
+ return multiply(
994
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
995
+ scale(part.width * t.scaleX, part.height * t.scaleY)
996
+ );
997
+ }
998
+ function landedPart(part, vertices, deformers, worlds, store) {
999
+ const warpDeformer = deformers.find(
1000
+ (d) => d.kind === "warp" && d.id === part.deformer
1001
+ );
1002
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
1003
+ const placed = placement(
1004
+ part,
1005
+ evaluateTransform(part.transform, void 0, store)
1006
+ );
1007
+ const restPoints = transformGridPoints(
1008
+ vertices,
1009
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
1010
+ new Float64Array(vertices.length)
1011
+ );
1012
+ return {
1013
+ part,
1014
+ warpDeformer,
1015
+ vertices: Float32Array.from(vertices),
1016
+ local: new Float32Array(vertices.length),
1017
+ landed: new Float32Array(vertices.length),
1018
+ restPoints
1019
+ };
1020
+ }
1021
+ function landPart(landing, store, { worlds, grids }) {
1022
+ const { part, warpDeformer, local, landed } = landing;
1023
+ applyWarps(landing.vertices, part.warps, store, local);
1024
+ const placed = placement(
1025
+ part,
1026
+ evaluateTransform(part.transform, part.bindings, store)
1027
+ );
1028
+ if (warpDeformer) {
1029
+ const grid = grids.get(warpDeformer.id);
1030
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
1031
+ } else if (part.deformer !== void 0) {
1032
+ const world = worlds.get(part.deformer);
1033
+ transformGridPoints(local, multiply(world, placed), landed);
1034
+ } else {
1035
+ transformGridPoints(local, placed, landed);
1036
+ }
1037
+ return landed;
1038
+ }
1039
+
1040
+ // ../engine/src/folds.ts
487
1041
  var FLIP = 0;
488
1042
  var COLLAPSE = 0.1;
489
1043
  var ANGLES = [
490
- import_format5.StandardParameter.AngleX,
491
- import_format5.StandardParameter.AngleY,
492
- import_format5.StandardParameter.AngleZ,
493
- import_format5.StandardParameter.BodyAngleX,
494
- import_format5.StandardParameter.BodyAngleY,
495
- import_format5.StandardParameter.BodyAngleZ
1044
+ import_format6.StandardParameter.AngleX,
1045
+ import_format6.StandardParameter.AngleY,
1046
+ import_format6.StandardParameter.AngleZ,
1047
+ import_format6.StandardParameter.BodyAngleX,
1048
+ import_format6.StandardParameter.BodyAngleY,
1049
+ import_format6.StandardParameter.BodyAngleZ
496
1050
  ];
497
1051
  var CROSSES = [
498
- [import_format5.StandardParameter.EyeOpenLeft],
499
- [import_format5.StandardParameter.EyeOpenRight],
500
- [import_format5.StandardParameter.MouthOpen],
501
- [import_format5.StandardParameter.ArmLeft, import_format5.StandardParameter.ArmRight],
502
- [import_format5.StandardParameter.ElbowLeft, import_format5.StandardParameter.ElbowRight]
1052
+ [import_format6.StandardParameter.EyeOpenLeft],
1053
+ [import_format6.StandardParameter.EyeOpenRight],
1054
+ [import_format6.StandardParameter.MouthOpen],
1055
+ [import_format6.StandardParameter.ArmLeft, import_format6.StandardParameter.ArmRight],
1056
+ [import_format6.StandardParameter.ElbowLeft, import_format6.StandardParameter.ElbowRight]
503
1057
  ];
504
1058
  function foldPoses(model) {
505
1059
  const byId = new Map(
@@ -547,11 +1101,6 @@ function poseName(values) {
547
1101
  if (ids.length === 0) return "rest";
548
1102
  return ids.map((id) => `${id}=${values[id]}`).join(" ");
549
1103
  }
550
- function staticDeformers(model) {
551
- return (model.deformers ?? []).map(
552
- (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
553
- );
554
- }
555
1104
  function cornerAreas(points, cols, rows) {
556
1105
  const stride = cols + 1;
557
1106
  const out = new Float64Array(cols * rows * 4);
@@ -583,12 +1132,6 @@ function triangleAreas(points, indices) {
583
1132
  }
584
1133
  return out;
585
1134
  }
586
- function placement(part, t) {
587
- return multiply(
588
- multiply(translate(t.x, t.y), rotate(t.rotation)),
589
- scale(part.width * t.scaleX, part.height * t.scaleY)
590
- );
591
- }
592
1135
  function keepLeast(sweep, areas, pose, expected) {
593
1136
  const slot = expected(sweep.target) ? "expected" : "worst";
594
1137
  for (let i = 0; i < areas.length; i++) {
@@ -601,50 +1144,15 @@ function keepLeast(sweep, areas, pose, expected) {
601
1144
  }
602
1145
  }
603
1146
  function partSweep(part, mesh, deformers, worlds, store) {
604
- const warpDeformer = deformers.find(
605
- (d) => d.kind === "warp" && d.id === part.deformer
606
- );
607
- const frame = warpDeformer ? warpDeformer.parent : part.deformer;
608
- const placed = placement(
609
- part,
610
- evaluateTransform(part.transform, void 0, store)
611
- );
612
- const restPoints = transformGridPoints(
613
- mesh.vertices,
614
- frame === void 0 ? placed : multiply(worlds.get(frame), placed),
615
- new Float64Array(mesh.vertices.length)
616
- );
1147
+ const landing = landedPart(part, mesh.vertices, deformers, worlds, store);
617
1148
  return {
1149
+ ...landing,
618
1150
  target: { kind: "part", id: part.id },
619
- restAreas: triangleAreas(restPoints, mesh.indices),
1151
+ restAreas: triangleAreas(landing.restPoints, mesh.indices),
620
1152
  tiny: 1e-9 * part.width * part.height,
621
- part,
622
- indices: mesh.indices,
623
- warpDeformer,
624
- vertices: Float32Array.from(mesh.vertices),
625
- local: new Float32Array(mesh.vertices.length),
626
- landed: new Float32Array(mesh.vertices.length),
627
- restPoints
1153
+ indices: mesh.indices
628
1154
  };
629
1155
  }
630
- function landPart(sweep, store, { worlds, grids }) {
631
- const { part, warpDeformer, local, landed } = sweep;
632
- applyWarps(sweep.vertices, part.warps, store, local);
633
- const placed = placement(
634
- part,
635
- evaluateTransform(part.transform, part.bindings, store)
636
- );
637
- if (warpDeformer) {
638
- const grid = grids.get(warpDeformer.id);
639
- applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
640
- } else if (part.deformer !== void 0) {
641
- const world = worlds.get(part.deformer);
642
- transformGridPoints(local, multiply(world, placed), landed);
643
- } else {
644
- transformGridPoints(local, placed, landed);
645
- }
646
- return landed;
647
- }
648
1156
  function checkFolds(model, options = {}) {
649
1157
  const poses = options.poses ?? foldPoses(model);
650
1158
  const deformers = model.deformers ?? [];
@@ -671,7 +1179,7 @@ function checkFolds(model, options = {}) {
671
1179
  const store = new ParameterStore(model.parameters);
672
1180
  for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
673
1181
  const value = (id) => store.get(id);
674
- const expected = (target) => options.expected?.(target, pose, value) === true;
1182
+ const expected = (target2) => options.expected?.(target2, pose, value) === true;
675
1183
  for (const sweep of gridSweeps) {
676
1184
  const { cols, rows } = sweep.deformer.grid;
677
1185
  const areas = cornerAreas(
@@ -762,7 +1270,414 @@ function classify(worst) {
762
1270
  return "ok";
763
1271
  }
764
1272
 
1273
+ // ../engine/src/physics-check.ts
1274
+ var import_format7 = require("@ikijs/format");
1275
+
1276
+ // ../engine/src/physics-runs.ts
1277
+ var FRAME_MS = FIXED_DT_S * 1e3 * (1 + 1e-9);
1278
+ var STEP_FRAMES = 300;
1279
+ var IDLE_FRAMES = 1800;
1280
+ var IDLE_SEED = 1;
1281
+ var MIN_TURN = 1e-9;
1282
+ function run(model, store, rigs, chains, frames, excite) {
1283
+ const raw = /* @__PURE__ */ new Map();
1284
+ const read = (id) => store.get(id);
1285
+ const sink = (id, value) => {
1286
+ let trace = raw.get(id);
1287
+ if (trace === void 0) raw.set(id, trace = []);
1288
+ trace.push(value);
1289
+ store.set(id, value);
1290
+ };
1291
+ const { parameters } = model;
1292
+ const drivers = [
1293
+ new PhysicsMotion(rigs, parameters, read, sink),
1294
+ new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink)
1295
+ ];
1296
+ for (let frame = 0; frame <= frames; frame++) {
1297
+ const nowMs = frame * FRAME_MS;
1298
+ excite(frame, nowMs);
1299
+ for (const driver of drivers) driver.update(nowMs);
1300
+ }
1301
+ const readings = /* @__PURE__ */ new Map();
1302
+ for (const driver of drivers) {
1303
+ driver.drivenParameterIds.forEach((id, i) => {
1304
+ const param = parameters.find((p) => p.id === id);
1305
+ readings.set(id, readTrace(raw.get(id), param, driver.resets[i]));
1306
+ });
1307
+ }
1308
+ return readings;
1309
+ }
1310
+ function readTrace(raw, param, resets) {
1311
+ const rest = clamp(param.default, param.min, param.max);
1312
+ const reading = {
1313
+ peak: 0,
1314
+ at: 0,
1315
+ final: rest,
1316
+ values: [],
1317
+ lo: rest,
1318
+ hi: rest,
1319
+ pinned: { frames: 0, end: "max" },
1320
+ resets
1321
+ };
1322
+ const seen = /* @__PURE__ */ new Set([rest]);
1323
+ let outside = 0;
1324
+ let end = "max";
1325
+ raw.forEach((value, frame) => {
1326
+ const held = clamp(value, param.min, param.max);
1327
+ if (Math.abs(held - rest) > Math.abs(reading.peak)) {
1328
+ reading.peak = held - rest;
1329
+ reading.at = frame * FIXED_DT_S;
1330
+ }
1331
+ if (!seen.has(held)) {
1332
+ seen.add(held);
1333
+ reading.values.push(held);
1334
+ }
1335
+ reading.lo = Math.min(reading.lo, held);
1336
+ reading.hi = Math.max(reading.hi, held);
1337
+ reading.final = held;
1338
+ if (value >= param.min && value <= param.max) {
1339
+ outside = 0;
1340
+ return;
1341
+ }
1342
+ const side = value < param.min ? "min" : "max";
1343
+ if (outside === 0 || side !== end) {
1344
+ outside = 0;
1345
+ end = side;
1346
+ }
1347
+ outside++;
1348
+ if (outside > reading.pinned.frames) {
1349
+ reading.pinned = { frames: outside, end };
1350
+ }
1351
+ });
1352
+ return reading;
1353
+ }
1354
+ function farEnd(param) {
1355
+ if (param.min === param.max) return void 0;
1356
+ const rest = clamp(param.default, param.min, param.max);
1357
+ return param.max - rest >= rest - param.min ? param.max : param.min;
1358
+ }
1359
+ function stepRun(model, rigs, chains, values) {
1360
+ const store = new ParameterStore(model.parameters);
1361
+ return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {
1362
+ if (frame !== 1) return;
1363
+ for (const [id, v] of Object.entries(values)) store.set(id, v);
1364
+ });
1365
+ }
1366
+ function idleRun(model) {
1367
+ const store = new ParameterStore(model.parameters);
1368
+ const idle = new IdleMotion((id, v) => store.set(id, v), {
1369
+ rng: lcg(IDLE_SEED)
1370
+ });
1371
+ return run(
1372
+ model,
1373
+ store,
1374
+ model.physics ?? [],
1375
+ model.physicsChains ?? [],
1376
+ IDLE_FRAMES,
1377
+ (_, nowMs) => idle.update(nowMs)
1378
+ );
1379
+ }
1380
+ function lcg(seed) {
1381
+ let state = seed >>> 0;
1382
+ return () => {
1383
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
1384
+ return state / 2 ** 32;
1385
+ };
1386
+ }
1387
+ function anchorInputs(model, chain) {
1388
+ const store = new ParameterStore(model.parameters);
1389
+ const angle = () => {
1390
+ const { worlds } = resolveDeformers(model.deformers ?? [], store);
1391
+ const world = worlds.get(chain.anchorDeformer);
1392
+ return Math.atan2(world[1], world[0]);
1393
+ };
1394
+ const rest = angle();
1395
+ const found = [];
1396
+ for (const p of model.parameters) {
1397
+ const probes = new Set(
1398
+ [p.max, p.min, ...stopsOf(model, p.id)].map(
1399
+ (v) => clamp(v, p.min, p.max)
1400
+ )
1401
+ );
1402
+ probes.delete(store.get(p.id));
1403
+ let most = 0;
1404
+ let best;
1405
+ for (const value of probes) {
1406
+ store.set(p.id, value);
1407
+ const d = angle() - rest;
1408
+ const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));
1409
+ if (turn <= most + MIN_TURN) continue;
1410
+ [most, best] = [turn, { parameter: p.id, value }];
1411
+ }
1412
+ store.reset();
1413
+ if (best) found.push(best);
1414
+ }
1415
+ return found;
1416
+ }
1417
+ function stopsOf(model, parameter) {
1418
+ const stops = /* @__PURE__ */ new Set();
1419
+ for (const d of model.deformers ?? []) {
1420
+ if (d.kind !== "warp") continue;
1421
+ for (const w of d.warps ?? []) {
1422
+ if (w.parameter !== parameter) continue;
1423
+ for (const k of w.keyforms) stops.add(k.value);
1424
+ }
1425
+ const { warp2d } = d;
1426
+ if (warp2d?.parameter === parameter) {
1427
+ for (const v of warp2d.valuesX) stops.add(v);
1428
+ }
1429
+ if (warp2d?.parameterY === parameter) {
1430
+ for (const v of warp2d.valuesY) stops.add(v);
1431
+ }
1432
+ }
1433
+ return [...stops].sort((a, b) => a - b);
1434
+ }
1435
+
1436
+ // ../engine/src/physics-check.ts
1437
+ var DISPLACEMENT_PX = 1;
1438
+ var PINNED_FRAMES = 60;
1439
+ var TOLERANCE = 1e-9;
1440
+ var UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];
1441
+ function checkPhysics(model) {
1442
+ const idle = idleRun(model);
1443
+ const displace = displacer(model);
1444
+ const idleExcitation = (output) => {
1445
+ const reading = idle.get(output.id);
1446
+ return {
1447
+ name: "the idle",
1448
+ reading,
1449
+ displacementPx: displace(output, reading.values)
1450
+ };
1451
+ };
1452
+ const param = (id) => model.parameters.find((p) => p.id === id);
1453
+ const springs = (model.physics ?? []).map((rig) => {
1454
+ const inputs = (0, import_format7.physicsInputs)(rig).map((i) => param(i.parameter));
1455
+ const ids = inputs.map((p) => p.id);
1456
+ const output = param(rig.output.parameter);
1457
+ const ranged = inputs.flatMap((input) => {
1458
+ const far = farEnd(input);
1459
+ return far === void 0 ? [] : [{ [input.id]: far }];
1460
+ });
1461
+ const settings = ranged.length === 0 ? [{}] : ranged;
1462
+ const steps = settings.map((values) => {
1463
+ const reading = stepRun(model, [rig], [], values).get(output.id);
1464
+ const setting = inputs.length === 1 ? [] : Object.entries(values).map(([id, v]) => `${id}=${v}`);
1465
+ return {
1466
+ name: ["the step", ...setting].join(" "),
1467
+ reading,
1468
+ displacementPx: displace(output, reading.values),
1469
+ values
1470
+ };
1471
+ });
1472
+ const atIdle = idleExcitation(output);
1473
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1474
+ return target(model, {
1475
+ rig: { kind: "spring", id: rig.id },
1476
+ input: ids,
1477
+ output,
1478
+ step: mostMoving(clean.length > 0 ? clean : steps),
1479
+ idle: atIdle,
1480
+ unstable: springWhy(rig) ?? unstableWhy(output, [...steps, atIdle]),
1481
+ inert: ranged.length === 0 ? `${ids.join(", ")} ${ids.length === 1 ? "has" : "have"} no range` : void 0
1482
+ });
1483
+ });
1484
+ const chains = (model.physicsChains ?? []).flatMap((chain) => {
1485
+ const candidates = anchorInputs(model, chain);
1486
+ const settings = candidates.length === 0 ? [{}] : candidates.map((c) => ({ [c.parameter]: c.value }));
1487
+ const runs = settings.map((values) => ({
1488
+ values,
1489
+ readings: stepRun(model, [], [chain], values)
1490
+ }));
1491
+ return chain.segments.map((segment, i) => {
1492
+ const output = param(segment.output.parameter);
1493
+ const steps = runs.map(({ values, readings }) => {
1494
+ const reading = readings.get(output.id);
1495
+ const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);
1496
+ return {
1497
+ name: ["the step", ...setting].join(" "),
1498
+ reading,
1499
+ displacementPx: displace(output, reading.values),
1500
+ values
1501
+ };
1502
+ });
1503
+ const atIdle = idleExcitation(output);
1504
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1505
+ return target(model, {
1506
+ rig: { kind: "chain", id: chain.id, segment: i },
1507
+ input: candidates.map((c) => c.parameter),
1508
+ output,
1509
+ step: mostMoving(clean.length > 0 ? clean : steps),
1510
+ idle: atIdle,
1511
+ unstable: unstableWhy(output, [...steps, atIdle]),
1512
+ inert: candidates.length === 0 ? `nothing turns anchor ${chain.anchorDeformer}` : void 0
1513
+ });
1514
+ });
1515
+ });
1516
+ const targets = [...springs, ...chains];
1517
+ return {
1518
+ thresholds: {
1519
+ displacementPx: DISPLACEMENT_PX,
1520
+ pinnedFrames: PINNED_FRAMES
1521
+ },
1522
+ targets,
1523
+ offenders: [
1524
+ ...targets.filter((t) => t.kind === "unstable"),
1525
+ ...targets.filter((t) => t.kind === "frozen")
1526
+ ]
1527
+ };
1528
+ }
1529
+ function target(model, t) {
1530
+ const { step, idle, output } = t;
1531
+ const drives = drivesOf(model, output.id);
1532
+ const px2 = Math.floor(step.displacementPx * 10) / 10;
1533
+ const still = step.displacementPx < DISPLACEMENT_PX ? `moves ${px2.toFixed(1)} model px over ${step.name}` : void 0;
1534
+ const frozen = drives.length === 0 ? "drives nothing" : t.inert ?? still;
1535
+ const { peak, at, final } = step.reading;
1536
+ return {
1537
+ rig: t.rig,
1538
+ input: t.input,
1539
+ output: output.id,
1540
+ drives,
1541
+ kind: t.unstable ? "unstable" : frozen ? "frozen" : "ok",
1542
+ why: t.unstable ?? frozen,
1543
+ step: {
1544
+ values: step.values,
1545
+ peak,
1546
+ at,
1547
+ final,
1548
+ displacementPx: step.displacementPx
1549
+ },
1550
+ idle: {
1551
+ peak: Math.abs(idle.reading.peak),
1552
+ at: idle.reading.at,
1553
+ displacementPx: idle.displacementPx
1554
+ }
1555
+ };
1556
+ }
1557
+ function mostMoving(steps) {
1558
+ return steps.reduce((best, s) => {
1559
+ if (s.displacementPx !== best.displacementPx) {
1560
+ return s.displacementPx > best.displacementPx ? s : best;
1561
+ }
1562
+ return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;
1563
+ });
1564
+ }
1565
+ function drivesOf(model, output) {
1566
+ const parts = model.parts.filter(
1567
+ (p) => [
1568
+ ...(p.bindings ?? []).map((b) => b.parameter),
1569
+ ...(p.warps ?? []).map((w) => w.parameter)
1570
+ ].includes(output)
1571
+ );
1572
+ const deformers = (model.deformers ?? []).filter(
1573
+ (d) => (d.kind === "warp" ? [
1574
+ ...(d.warps ?? []).map((w) => w.parameter),
1575
+ d.warp2d?.parameter,
1576
+ d.warp2d?.parameterY
1577
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output)
1578
+ );
1579
+ return [
1580
+ ...parts.map((p) => ({ kind: "part", id: p.id })),
1581
+ ...deformers.map((d) => ({ kind: "deformer", id: d.id }))
1582
+ ];
1583
+ }
1584
+ function springStepRadius({ mass, stiffness, damping }) {
1585
+ const k = FIXED_DT_S * FIXED_DT_S * stiffness / mass;
1586
+ const c = FIXED_DT_S * damping / mass;
1587
+ const trace = 2 - k - c;
1588
+ const det = 1 - c;
1589
+ const disc = trace * trace - 4 * det;
1590
+ const radius = disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);
1591
+ return { radius, k };
1592
+ }
1593
+ function springWhy(rig) {
1594
+ const { radius, k } = springStepRadius(rig);
1595
+ if (radius > 1 + TOLERANCE) {
1596
+ let digits = 2;
1597
+ while (Number(radius.toFixed(digits)) <= 1) digits++;
1598
+ return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;
1599
+ }
1600
+ if (rig.damping === 0 && k >= 4 - TOLERANCE) {
1601
+ return `spring on its undamped boundary, dt\xB2k/m ${k.toFixed(2)}`;
1602
+ }
1603
+ return void 0;
1604
+ }
1605
+ function unstableWhy(output, excitations) {
1606
+ for (const { name, reading } of excitations) {
1607
+ const n = reading.resets;
1608
+ if (n === 0) continue;
1609
+ return `finiteness guard reset it ${n} time${n === 1 ? "" : "s"} in ${name}`;
1610
+ }
1611
+ for (const { name, reading } of excitations) {
1612
+ const { frames, end } = reading.pinned;
1613
+ if (frames < PINNED_FRAMES) continue;
1614
+ return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;
1615
+ }
1616
+ return void 0;
1617
+ }
1618
+ function displacer(model) {
1619
+ const deformers = model.deformers ?? [];
1620
+ const store = new ParameterStore(model.parameters);
1621
+ const { worlds } = resolveDeformers(staticDeformers(model), store);
1622
+ const landings = model.parts.map(
1623
+ (part) => landedPart(
1624
+ part,
1625
+ part.mesh?.vertices ?? UNIT_QUAD,
1626
+ deformers,
1627
+ worlds,
1628
+ store
1629
+ )
1630
+ );
1631
+ const atRest = resolveDeformers(deformers, store);
1632
+ const baselines = landings.map(
1633
+ (l) => Float32Array.from(landPart(l, store, atRest))
1634
+ );
1635
+ return (output, values) => {
1636
+ let most = 0;
1637
+ const affected = affectedParts(model, output.id);
1638
+ for (const value of values) {
1639
+ store.set(output.id, value);
1640
+ const resolved = resolveDeformers(deformers, store);
1641
+ landings.forEach((landing, i) => {
1642
+ if (!affected.has(landing.part)) return;
1643
+ const landed = landPart(landing, store, resolved);
1644
+ const base = baselines[i];
1645
+ for (let j = 0; j < landed.length; j += 2) {
1646
+ const dx = landed[j] - base[j];
1647
+ const dy = landed[j + 1] - base[j + 1];
1648
+ most = Math.max(most, dx * dx + dy * dy);
1649
+ }
1650
+ });
1651
+ }
1652
+ store.reset();
1653
+ return Math.sqrt(most);
1654
+ };
1655
+ }
1656
+ function affectedParts(model, output) {
1657
+ const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));
1658
+ const reads = (d) => (d.kind === "warp" ? [
1659
+ ...(d.warps ?? []).map((w) => w.parameter),
1660
+ d.warp2d?.parameter,
1661
+ d.warp2d?.parameterY
1662
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output);
1663
+ const hung = (id) => {
1664
+ for (let d = id && deformers.get(id); d; d = d.parent && deformers.get(d.parent)) {
1665
+ if (reads(d)) return true;
1666
+ }
1667
+ return false;
1668
+ };
1669
+ return new Set(
1670
+ model.parts.filter(
1671
+ (p) => [
1672
+ ...(p.bindings ?? []).map((b) => b.parameter),
1673
+ ...(p.warps ?? []).map((w) => w.parameter)
1674
+ ].includes(output) || hung(p.deformer)
1675
+ )
1676
+ );
1677
+ }
1678
+
765
1679
  // src/fold-report.ts
1680
+ var import_editor = require("@ikijs/editor");
766
1681
  function checkModelFolds(model, extraValues = []) {
767
1682
  const declared = new Set(model.parameters.map((p) => p.id));
768
1683
  return checkFolds(model, {
@@ -770,9 +1685,9 @@ function checkModelFolds(model, extraValues = []) {
770
1685
  // The effective value, not the pose's overrides: the auto-rig's mouth
771
1686
  // rests shut at its default, so `rest` and the other parameters' singles
772
1687
  // are shut-mouth poses too.
773
- expected: (target, _pose, value) => {
774
- if (target.kind !== "part") return false;
775
- const shutBy = import_editor.SHUT_BY.get(target.id);
1688
+ expected: (target2, _pose, value) => {
1689
+ if (target2.kind !== "part") return false;
1690
+ const shutBy = import_editor.SHUT_BY.get(target2.id);
776
1691
  return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
777
1692
  }
778
1693
  });
@@ -811,7 +1726,7 @@ function ratioText(ratio) {
811
1726
  // src/render-poses.ts
812
1727
  var import_node_fs3 = require("fs");
813
1728
  var import_node_path3 = __toESM(require("path"));
814
- var import_format6 = require("@ikijs/format");
1729
+ var import_format8 = require("@ikijs/format");
815
1730
 
816
1731
  // src/limits.ts
817
1732
  var import_node_fs = __toESM(require("fs"));
@@ -1312,9 +2227,9 @@ function planRenders(model, requested) {
1312
2227
  }
1313
2228
  const bodyAngles = Object.fromEntries(
1314
2229
  [
1315
- import_format6.StandardParameter.BodyAngleX,
1316
- import_format6.StandardParameter.BodyAngleY,
1317
- import_format6.StandardParameter.BodyAngleZ
2230
+ import_format8.StandardParameter.BodyAngleX,
2231
+ import_format8.StandardParameter.BodyAngleY,
2232
+ import_format8.StandardParameter.BodyAngleZ
1318
2233
  ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
1319
2234
  );
1320
2235
  const poses = [
@@ -1400,7 +2315,7 @@ function planRenders(model, requested) {
1400
2315
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
1401
2316
  whole("full-elbow-r-90", { ParamElbowR: 90 })
1402
2317
  );
1403
- if (model.parameters.some((p) => p.id === import_format6.StandardParameter.ArmPoseRight)) {
2318
+ if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
1404
2319
  poses.push(
1405
2320
  whole("full-pose-l", { ParamArmPoseL: 1 }),
1406
2321
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -1465,7 +2380,7 @@ async function renderPoses(input) {
1465
2380
  input.modelPath
1466
2381
  );
1467
2382
  const outDir = resolveOutputDir(input.outDir);
1468
- const model = (0, import_format6.loadIkiModel)((0, import_node_fs3.readFileSync)(modelFile, "utf8"));
2383
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs3.readFileSync)(modelFile, "utf8"));
1469
2384
  const plan = planRenders(model, input.poses);
1470
2385
  const browser = findBrowser();
1471
2386
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
@@ -1474,6 +2389,7 @@ async function renderPoses(input) {
1474
2389
  model,
1475
2390
  input.poses?.map((p) => p.values)
1476
2391
  );
2392
+ const physics = checkPhysics(model);
1477
2393
  const { failedTextures, poses } = await withBrowser(
1478
2394
  browser,
1479
2395
  async (evaluate) => {
@@ -1510,10 +2426,11 @@ async function renderPoses(input) {
1510
2426
  failedTextures,
1511
2427
  poses,
1512
2428
  modelCanvas: model.canvas,
1513
- folds
2429
+ folds,
2430
+ physics
1514
2431
  };
1515
2432
  } catch (error) {
1516
- if (error instanceof AutoRigInputError || error instanceof import_format6.IkiFormatError) {
2433
+ if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
1517
2434
  return { ok: false, error: error.message };
1518
2435
  }
1519
2436
  throw error;
@@ -1590,10 +2507,10 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
1590
2507
  // src/tools.ts
1591
2508
  function coerceModel(model) {
1592
2509
  try {
1593
- const parsed = typeof model === "string" ? (0, import_format7.loadIkiModel)(model) : (0, import_format7.parseIkiModel)(model);
2510
+ const parsed = typeof model === "string" ? (0, import_format9.loadIkiModel)(model) : (0, import_format9.parseIkiModel)(model);
1594
2511
  return { ok: true, model: parsed };
1595
2512
  } catch (e) {
1596
- if (e instanceof import_format7.IkiFormatError) return { ok: false, error: e.message };
2513
+ if (e instanceof import_format9.IkiFormatError) return { ok: false, error: e.message };
1597
2514
  throw e;
1598
2515
  }
1599
2516
  }
@@ -1710,115 +2627,119 @@ function describeIkiAt(modelPath) {
1710
2627
  }
1711
2628
  var STANDARD_PARAMETER_INFO = [
1712
2629
  {
1713
- id: import_format7.StandardParameter.MouthOpen,
2630
+ id: import_format9.StandardParameter.MouthOpen,
1714
2631
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
1715
2632
  },
1716
2633
  {
1717
- id: import_format7.StandardParameter.MouthForm,
2634
+ id: import_format9.StandardParameter.MouthForm,
1718
2635
  description: "Mouth form / smile (-1 .. 1)."
1719
2636
  },
1720
2637
  {
1721
- id: import_format7.StandardParameter.EyeOpenLeft,
2638
+ id: import_format9.StandardParameter.EyeOpenLeft,
1722
2639
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
1723
2640
  },
1724
2641
  {
1725
- id: import_format7.StandardParameter.EyeOpenRight,
2642
+ id: import_format9.StandardParameter.EyeOpenRight,
1726
2643
  description: "Right eye open (0 closed .. 1 open)."
1727
2644
  },
1728
2645
  {
1729
- id: import_format7.StandardParameter.EyeballX,
2646
+ id: import_format9.StandardParameter.EyeballX,
1730
2647
  description: "Eyeball gaze, horizontal (-1 .. 1)."
1731
2648
  },
1732
2649
  {
1733
- id: import_format7.StandardParameter.EyeballY,
2650
+ id: import_format9.StandardParameter.EyeballY,
1734
2651
  description: "Eyeball gaze, vertical (-1 .. 1)."
1735
2652
  },
1736
2653
  {
1737
- id: import_format7.StandardParameter.AngleX,
2654
+ id: import_format9.StandardParameter.AngleX,
1738
2655
  description: "Head angle, horizontal degrees."
1739
2656
  },
1740
2657
  {
1741
- id: import_format7.StandardParameter.AngleY,
2658
+ id: import_format9.StandardParameter.AngleY,
1742
2659
  description: "Head angle, vertical degrees."
1743
2660
  },
1744
2661
  {
1745
- id: import_format7.StandardParameter.AngleZ,
2662
+ id: import_format9.StandardParameter.AngleZ,
1746
2663
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
1747
2664
  },
1748
2665
  {
1749
- id: import_format7.StandardParameter.BodyAngleX,
2666
+ id: import_format9.StandardParameter.BodyAngleX,
1750
2667
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
1751
2668
  },
1752
2669
  {
1753
- id: import_format7.StandardParameter.BodyAngleY,
2670
+ id: import_format9.StandardParameter.BodyAngleY,
1754
2671
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
1755
2672
  },
1756
2673
  {
1757
- id: import_format7.StandardParameter.BodyAngleZ,
2674
+ id: import_format9.StandardParameter.BodyAngleZ,
1758
2675
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
1759
2676
  },
1760
2677
  {
1761
- id: import_format7.StandardParameter.Breath,
2678
+ id: import_format9.StandardParameter.Breath,
1762
2679
  description: "Idle breath (0 .. 1), cycled by the host."
1763
2680
  },
1764
2681
  {
1765
- id: import_format7.StandardParameter.BrowLeftY,
2682
+ id: import_format9.StandardParameter.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
+ },
2685
+ {
2686
+ id: import_format9.StandardParameter.BrowLeftY,
1766
2687
  description: "Left brow raise/lower (-1 .. 1)."
1767
2688
  },
1768
2689
  {
1769
- id: import_format7.StandardParameter.BrowRightY,
2690
+ id: import_format9.StandardParameter.BrowRightY,
1770
2691
  description: "Right brow raise/lower (-1 .. 1)."
1771
2692
  },
1772
2693
  {
1773
- id: import_format7.StandardParameter.BrowLeftAngle,
2694
+ id: import_format9.StandardParameter.BrowLeftAngle,
1774
2695
  description: "Left brow tilt/angle (-1 .. 1)."
1775
2696
  },
1776
2697
  {
1777
- id: import_format7.StandardParameter.BrowRightAngle,
2698
+ id: import_format9.StandardParameter.BrowRightAngle,
1778
2699
  description: "Right brow tilt/angle (-1 .. 1)."
1779
2700
  },
1780
2701
  {
1781
- id: import_format7.StandardParameter.Cheek,
2702
+ id: import_format9.StandardParameter.Cheek,
1782
2703
  description: "Cheek blush strength (0 .. 1), raised by an expression."
1783
2704
  },
1784
2705
  {
1785
- id: import_format7.StandardParameter.HairSwayX,
2706
+ id: import_format9.StandardParameter.HairSwayX,
1786
2707
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
1787
2708
  },
1788
2709
  {
1789
- id: import_format7.StandardParameter.HairSwayZ,
2710
+ id: import_format9.StandardParameter.HairSwayZ,
1790
2711
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
1791
2712
  },
1792
2713
  {
1793
- id: import_format7.StandardParameter.ArmLeft,
2714
+ id: import_format9.StandardParameter.ArmLeft,
1794
2715
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
1795
2716
  },
1796
2717
  {
1797
- id: import_format7.StandardParameter.ArmRight,
2718
+ id: import_format9.StandardParameter.ArmRight,
1798
2719
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
1799
2720
  },
1800
2721
  {
1801
- id: import_format7.StandardParameter.ElbowLeft,
2722
+ id: import_format9.StandardParameter.ElbowLeft,
1802
2723
  description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
1803
2724
  },
1804
2725
  {
1805
- id: import_format7.StandardParameter.ElbowRight,
2726
+ id: import_format9.StandardParameter.ElbowRight,
1806
2727
  description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
1807
2728
  },
1808
2729
  {
1809
- id: import_format7.StandardParameter.ArmPoseLeft,
2730
+ id: import_format9.StandardParameter.ArmPoseLeft,
1810
2731
  description: "Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
1811
2732
  },
1812
2733
  {
1813
- id: import_format7.StandardParameter.ArmPoseRight,
2734
+ id: import_format9.StandardParameter.ArmPoseRight,
1814
2735
  description: "Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
1815
2736
  },
1816
2737
  {
1817
- id: import_format7.StandardParameter.ArmPoseAngleLeft,
2738
+ id: import_format9.StandardParameter.ArmPoseAngleLeft,
1818
2739
  description: "Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right)."
1819
2740
  },
1820
2741
  {
1821
- id: import_format7.StandardParameter.ArmPoseAngleRight,
2742
+ id: import_format9.StandardParameter.ArmPoseAngleRight,
1822
2743
  description: "Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left)."
1823
2744
  }
1824
2745
  ];
@@ -2018,9 +2939,10 @@ async function autoRigFromLayers(input) {
2018
2939
  patched.parts.find((p) => p.id === partId).texture.index = 1;
2019
2940
  }
2020
2941
  }
2021
- const finalModel = (0, import_format7.parseIkiModel)(patched);
2942
+ const finalModel = (0, import_format9.parseIkiModel)(patched);
2022
2943
  writeFileAtomic(outPath, JSON.stringify(finalModel));
2023
2944
  const folds = checkModelFolds(finalModel);
2945
+ const physics = checkPhysics(finalModel);
2024
2946
  return {
2025
2947
  ok: true,
2026
2948
  path: outPath,
@@ -2034,6 +2956,7 @@ async function autoRigFromLayers(input) {
2034
2956
  ...noseCore === void 0 ? {} : { noseCore },
2035
2957
  ...turn === void 0 ? {} : { turn },
2036
2958
  folds,
2959
+ physics,
2037
2960
  ...patches === void 0 ? {} : { patches }
2038
2961
  };
2039
2962
  } catch (err) {
@@ -3453,16 +4376,16 @@ async function layerStats(filePath) {
3453
4376
  let flatCutRun = 0;
3454
4377
  let flatCutY = -1;
3455
4378
  for (let y = minY + 1; y <= maxY; y++) {
3456
- let run = 0;
4379
+ let run2 = 0;
3457
4380
  for (let x = minX; x <= maxX; x++) {
3458
4381
  if (alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE && alpha(x, y) > FLAT_CUT_ALPHA_BELOW) {
3459
- run++;
3460
- if (run > flatCutRun) {
3461
- flatCutRun = run;
4382
+ run2++;
4383
+ if (run2 > flatCutRun) {
4384
+ flatCutRun = run2;
3462
4385
  flatCutY = y;
3463
4386
  }
3464
4387
  } else {
3465
- run = 0;
4388
+ run2 = 0;
3466
4389
  }
3467
4390
  }
3468
4391
  }
@@ -4710,6 +5633,22 @@ async function composeLayersFromParts(input) {
4710
5633
  }
4711
5634
  }
4712
5635
 
5636
+ // src/physics-report.ts
5637
+ function formatPhysicsReport(report) {
5638
+ if (report.targets.length === 0) return ["PHYSICS: no rigs"];
5639
+ return report.targets.map(targetLine);
5640
+ }
5641
+ function targetLine(t) {
5642
+ const inputs = t.input.join(", ");
5643
+ const rig = t.rig.kind === "chain" ? `${t.rig.id}/${t.rig.segment} [${inputs}]` : `${t.rig.id} ${inputs}`;
5644
+ const drives = t.drives.length === 0 ? "" : ` (${t.drives.map((d) => d.id).join(", ")})`;
5645
+ const { step, idle } = t;
5646
+ 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}`);
5647
+ }
5648
+ function pxText(px2) {
5649
+ return (Math.floor(px2 * 10) / 10).toFixed(1);
5650
+ }
5651
+
4713
5652
  // src/server.ts
4714
5653
  function formatPatchReports(reports) {
4715
5654
  return reports.map((r) => {
@@ -4719,7 +5658,7 @@ function formatPatchReports(reports) {
4719
5658
  });
4720
5659
  }
4721
5660
  function createIkiMcpServer() {
4722
- const server = new import_mcp.McpServer({ name: "iki", version: "0.26.1" });
5661
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.28.0" });
4723
5662
  server.registerTool(
4724
5663
  "validate_iki",
4725
5664
  {
@@ -4794,7 +5733,7 @@ function createIkiMcpServer() {
4794
5733
  server.registerTool(
4795
5734
  "auto_rig_from_layers",
4796
5735
  {
4797
- 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.",
5736
+ 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.",
4798
5737
  inputSchema: {
4799
5738
  layers: import_zod.z.array(
4800
5739
  import_zod.z.object({
@@ -4860,7 +5799,8 @@ function createIkiMcpServer() {
4860
5799
  const text = r.ok ? [
4861
5800
  r.path,
4862
5801
  ...formatPatchReports(r.patches ?? []),
4863
- ...formatFoldReport(r.folds, r.canvas)
5802
+ ...formatFoldReport(r.folds, r.canvas),
5803
+ ...formatPhysicsReport(r.physics)
4864
5804
  ].join("\n") : `INVALID: ${r.error}`;
4865
5805
  return { content: [{ type: "text", text }], structuredContent: r };
4866
5806
  } catch (err) {
@@ -4989,7 +5929,7 @@ function createIkiMcpServer() {
4989
5929
  server.registerTool(
4990
5930
  "render_poses",
4991
5931
  {
4992
- 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.",
5932
+ 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.",
4993
5933
  inputSchema: {
4994
5934
  modelPath: import_zod.z.string().describe(
4995
5935
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -5018,7 +5958,8 @@ function createIkiMcpServer() {
5018
5958
  const r = await renderPoses(args);
5019
5959
  const text = r.ok ? [
5020
5960
  ...r.poses.map((p) => p.path),
5021
- ...formatFoldReport(r.folds, r.modelCanvas)
5961
+ ...formatFoldReport(r.folds, r.modelCanvas),
5962
+ ...formatPhysicsReport(r.physics)
5022
5963
  ].join("\n") : `INVALID: ${r.error}`;
5023
5964
  return { content: [{ type: "text", text }], structuredContent: r };
5024
5965
  } catch (err) {