@hackbuild/humanoid 0.2.2 → 0.4.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.
@@ -454,6 +454,263 @@ var HackbuildHumanoid = (function(exports, three) {
454
454
  "right_wrist_yaw_joint"
455
455
  ]
456
456
  };
457
+ // src/follow.ts
458
+ const side = (s) => {
459
+ const S = s === "left" ? "left" : "right";
460
+ return {
461
+ bones: {
462
+ [`${s}UpperLeg`]: `${S}_hip_yaw_link`,
463
+ [`${s}LowerLeg`]: `${S}_knee_link`,
464
+ [`${s}Foot`]: `${S}_ankle_roll_link`,
465
+ [`${s}UpperArm`]: `${S}_shoulder_yaw_link`,
466
+ [`${s}LowerArm`]: `${S}_elbow_link`,
467
+ [`${s}Hand`]: `${S}_wrist_yaw_link`
468
+ },
469
+ segments: [
470
+ {
471
+ bone: `${s}UpperLeg`,
472
+ child: `${s}LowerLeg`,
473
+ from: `${S}_hip_roll_link`,
474
+ to: `${S}_knee_link`
475
+ },
476
+ {
477
+ bone: `${s}LowerLeg`,
478
+ child: `${s}Foot`,
479
+ from: `${S}_knee_link`,
480
+ to: `${S}_ankle_pitch_link`
481
+ },
482
+ {
483
+ bone: `${s}UpperArm`,
484
+ child: `${s}LowerArm`,
485
+ from: `${S}_shoulder_roll_link`,
486
+ to: `${S}_elbow_link`
487
+ },
488
+ {
489
+ bone: `${s}LowerArm`,
490
+ child: `${s}Hand`,
491
+ from: `${S}_elbow_link`,
492
+ to: `${S}_wrist_roll_link`
493
+ }
494
+ ]
495
+ };
496
+ };
497
+ const L = side("left");
498
+ const R = side("right");
499
+ /**
500
+ * The Unitree G1, both models (MuJoCo Menagerie's and the gear-sonic deploy model share
501
+ * these body names). At its zero pose the legs hang straight, the arms hang at the sides and
502
+ * the forearms point forward, elbows at a right angle (measured).
503
+ */
504
+ const G1_FOLLOW = {
505
+ bones: {
506
+ hips: "pelvis",
507
+ spine: "torso_link",
508
+ ...L.bones,
509
+ ...R.bones
510
+ },
511
+ root: "hips",
512
+ segments: [...L.segments, ...R.segments]
513
+ };
514
+ // src/rest.ts
515
+ /** Quaternion product a b, both [w, x, y, z]. */
516
+ function qmul(a, b) {
517
+ return [
518
+ a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
519
+ a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2],
520
+ a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1],
521
+ a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0]
522
+ ];
523
+ }
524
+ /** v turned by the unit quaternion q ([w, x, y, z]). */
525
+ function qrotate(q, v) {
526
+ const [w, x, y, z] = q;
527
+ const tx = 2 * (y * v[2] - z * v[1]), ty = 2 * (z * v[0] - x * v[2]), tz = 2 * (x * v[1] - y * v[0]);
528
+ return [
529
+ v[0] + w * tx + (y * tz - z * ty),
530
+ v[1] + w * ty + (z * tx - x * tz),
531
+ v[2] + w * tz + (x * ty - y * tx)
532
+ ];
533
+ }
534
+ /**
535
+ * Every body's world pose at qpos0 (hinge and slide joints at their reference, a free root
536
+ * where the model places it), from the chain of body offsets. Body 0 is the world.
537
+ */
538
+ function restPoses(model) {
539
+ const out = [{
540
+ pos: [
541
+ 0,
542
+ 0,
543
+ 0
544
+ ],
545
+ quat: [
546
+ 1,
547
+ 0,
548
+ 0,
549
+ 0
550
+ ]
551
+ }];
552
+ for (let i = 1; i < model.nbody; i++) {
553
+ const parent = out[model.body_parentid[i]];
554
+ const p = model.body_pos, q = model.body_quat;
555
+ const local = [
556
+ q[i * 4],
557
+ q[i * 4 + 1],
558
+ q[i * 4 + 2],
559
+ q[i * 4 + 3]
560
+ ];
561
+ const off = qrotate(parent.quat, [
562
+ p[i * 3],
563
+ p[i * 3 + 1],
564
+ p[i * 3 + 2]
565
+ ]);
566
+ out.push({
567
+ pos: [
568
+ parent.pos[0] + off[0],
569
+ parent.pos[1] + off[1],
570
+ parent.pos[2] + off[2]
571
+ ],
572
+ quat: qmul(parent.quat, local)
573
+ });
574
+ }
575
+ return out;
576
+ }
577
+ // src/frame.ts
578
+ /** Turn about +Y that brings each forward axis to +Z, after z up becomes y up. */
579
+ const TURN = {
580
+ x: -Math.PI / 2,
581
+ "-x": Math.PI / 2,
582
+ y: Math.PI,
583
+ "-y": 0
584
+ };
585
+ /** MuJoCo world to humanoid space as one rotation: z up to y up, then the forward axis to +Z. */
586
+ function frameTurn(forward = "x") {
587
+ return new three.Quaternion().setFromEuler(new three.Euler(0, TURN[forward], 0)).multiply(new three.Quaternion().setFromEuler(new three.Euler(-Math.PI / 2, 0, 0)));
588
+ }
589
+ // src/follow-three.ts
590
+ /**
591
+ * A humanoid body (a VRM, a GLB person, any rig with VRM 1.0 bone names)
592
+ * that follows a robot in MuJoCo. Once, it turns the body's limbs to the
593
+ * robot's zero pose (a T pose's arms come down to the sides, the forearms
594
+ * forward); then each frame it gives every mapped bone the rotation its
595
+ * robot body has made since that pose, and moves the hips with the pelvis,
596
+ * scaled to the body's height. Rotations are worked in the body's root
597
+ * space, so the body may stand anywhere, turned any way.
598
+ */
599
+ /** Drives a humanoid body from a {@link Humanoid}: call `update` after each step. */
600
+ var BodyFollow = class {
601
+ sim;
602
+ body;
603
+ /** Bones of the map the body lacks, robot bodies the robot lacks, and segments that could not be posed for want of either; those are left as they are. */
604
+ missing = [];
605
+ entries = [];
606
+ saved = /* @__PURE__ */ new Map();
607
+ turn;
608
+ turnInv;
609
+ rootEntry = null;
610
+ hipsRest = new three.Vector3();
611
+ bodyRest = new three.Vector3();
612
+ scale = 1;
613
+ travel;
614
+ _q = new three.Quaternion();
615
+ _r = new three.Quaternion();
616
+ _p = new three.Quaternion();
617
+ _root = new three.Quaternion();
618
+ _v = new three.Vector3();
619
+ _w = new three.Vector3();
620
+ constructor(sim, body, o = {}) {
621
+ this.sim = sim;
622
+ this.body = body;
623
+ const map = o.map ?? G1_FOLLOW;
624
+ this.travel = o.travel ?? true;
625
+ this.turn = frameTurn(o.forward);
626
+ this.turnInv = this.turn.clone().invert();
627
+ const rest = restPoses(sim.model);
628
+ const id = (name) => sim.bodies.indexOf(name);
629
+ for (const [bone, link] of Object.entries(map.bones)) {
630
+ const node = body.bones[bone], i = id(link);
631
+ if (!node) this.missing.push(bone);
632
+ if (i < 0) this.missing.push(link);
633
+ if (!node || i < 0) continue;
634
+ const [w, x, y, z] = rest[i].quat;
635
+ this.entries.push({
636
+ bone,
637
+ node,
638
+ body: i,
639
+ restInv: new three.Quaternion(x, y, z, w).invert(),
640
+ posed: new three.Quaternion()
641
+ });
642
+ }
643
+ for (const s of map.segments) for (const b of [s.bone, s.child]) if (body.bones[b]) this.keep(body.bones[b]);
644
+ for (const e of this.entries) this.keep(e.node);
645
+ body.root.updateMatrixWorld(true);
646
+ for (const s of map.segments) {
647
+ const node = body.bones[s.bone], child = body.bones[s.child], a = id(s.from), b = id(s.to);
648
+ if (!node || !child || a < 0 || b < 0) {
649
+ if (node) this.missing.push(`${s.bone} to ${s.child} segment`);
650
+ continue;
651
+ }
652
+ const pa = rest[a].pos, pb = rest[b].pos;
653
+ const want = this._w.set(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).applyQuaternion(this.turn).normalize();
654
+ const have = this.rootPos(child, this._v).sub(this.rootPos(node, new three.Vector3())).normalize();
655
+ if (have.lengthSq() === 0 || want.lengthSq() === 0) continue;
656
+ this.setRootQuat(node, this._q.setFromUnitVectors(have, want).multiply(this.rootQuat(node, this._r)));
657
+ }
658
+ for (const e of this.entries) this.rootQuat(e.node, e.posed);
659
+ this.rootEntry = this.entries.find((e) => e.bone === map.root) ?? null;
660
+ if (this.rootEntry) {
661
+ this.rootPos(this.rootEntry.node, this.hipsRest);
662
+ const p = rest[this.rootEntry.body].pos;
663
+ this.bodyRest.set(p[0], p[1], p[2]).applyQuaternion(this.turn);
664
+ this.scale = this.bodyRest.y > 0 ? this.hipsRest.y / this.bodyRest.y : 1;
665
+ }
666
+ }
667
+ /** Poses the body from the robot's last step; does nothing once the robot is disposed. */
668
+ update() {
669
+ if (this.sim.disposed) return;
670
+ this.body.root.updateMatrixWorld(true);
671
+ const q = this.sim.data.xquat;
672
+ for (const e of this.entries) {
673
+ const k = e.body * 4;
674
+ this._q.set(q[k + 1], q[k + 2], q[k + 3], q[k]);
675
+ this._q.premultiply(this.turn).multiply(e.restInv).multiply(this.turnInv);
676
+ this.setRootQuat(e.node, this._q.multiply(e.posed));
677
+ if (e === this.rootEntry && this.travel) {
678
+ const x = this.sim.data.xpos, b = e.body * 3;
679
+ this._v.set(x[b], x[b + 1], x[b + 2]).applyQuaternion(this.turn).sub(this.bodyRest).multiplyScalar(this.scale).add(this.hipsRest);
680
+ this.setRootPos(e.node, this._v);
681
+ }
682
+ }
683
+ }
684
+ /** Puts every bone this follower touched back as it found it. */
685
+ reset() {
686
+ for (const [node, s] of this.saved) node.quaternion.copy(s.q), node.position.copy(s.p);
687
+ this.body.root.updateMatrixWorld(true);
688
+ }
689
+ keep(node) {
690
+ if (!this.saved.has(node)) this.saved.set(node, {
691
+ q: node.quaternion.clone(),
692
+ p: node.position.clone()
693
+ });
694
+ }
695
+ /** A node's world rotation in the body's root space. */
696
+ rootQuat(node, out) {
697
+ return node.getWorldQuaternion(out).premultiply(this.body.root.getWorldQuaternion(this._root).invert());
698
+ }
699
+ rootPos(node, out) {
700
+ return this.body.root.worldToLocal(node.getWorldPosition(out));
701
+ }
702
+ /** Gives a node a rotation in root space, through its parent's. */
703
+ setRootQuat(node, q) {
704
+ const parent = node.parent ? this.rootQuat(node.parent, this._p) : this._p.identity();
705
+ node.quaternion.copy(parent.invert().multiply(q));
706
+ node.updateMatrixWorld(true);
707
+ }
708
+ setRootPos(node, p) {
709
+ const world = this.body.root.localToWorld(this._w.copy(p));
710
+ node.position.copy(node.parent ? node.parent.worldToLocal(world) : world);
711
+ node.updateMatrixWorld(true);
712
+ }
713
+ };
457
714
  // src/three.ts
458
715
  /**
459
716
  * The robot in three.js: one mesh per visible geom (spheres, capsules,
@@ -470,12 +727,6 @@ var HackbuildHumanoid = (function(exports, three) {
470
727
  const CYLINDER = 5;
471
728
  const BOX = 6;
472
729
  const MESH = 7;
473
- const TURN = {
474
- x: -Math.PI / 2,
475
- "-x": Math.PI / 2,
476
- y: Math.PI,
477
- "-y": 0
478
- };
479
730
  /** A three.js group that follows a {@link Humanoid}; add `root` to a scene and call `update` after each step. */
480
731
  var HumanoidView = class {
481
732
  sim;
@@ -571,23 +822,113 @@ var HackbuildHumanoid = (function(exports, three) {
571
822
  this.meshes = [];
572
823
  }
573
824
  };
574
- // src/sonic.ts
825
+ // src/sonic-obs.ts
826
+ /** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
827
+ function intoBody(q, v) {
828
+ const [w, x, y, z] = q;
829
+ const r = [
830
+ [
831
+ 1 - 2 * (y * y + z * z),
832
+ 2 * (x * y - w * z),
833
+ 2 * (x * z + w * y)
834
+ ],
835
+ [
836
+ 2 * (x * y + w * z),
837
+ 1 - 2 * (x * x + z * z),
838
+ 2 * (y * z - w * x)
839
+ ],
840
+ [
841
+ 2 * (x * z - w * y),
842
+ 2 * (y * z + w * x),
843
+ 1 - 2 * (x * x + y * y)
844
+ ]
845
+ ];
846
+ return [
847
+ 0,
848
+ 1,
849
+ 2
850
+ ].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
851
+ }
575
852
  /**
576
- * GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
577
- * page: an encoder turns a reference motion into a 64 number token, a decoder
578
- * turns the token and ten ticks of the robot's state into 29 joint actions,
579
- * 50 times a second; a PD loop here turns actions into motor torques at every
580
- * MuJoCo step. Written for this library from the published deployment
581
- * description and parameters (observation names, sizes and order, joint
582
- * orders, gains from motor armature, action scale, default angles). The
583
- * details the description leaves open were settled by trial on the deploy
584
- * model: joint positions relative to the default angles, the reference in
585
- * absolute angles, histories oldest first, a rotation's first two columns
586
- * row by row, and the anchor as the base's tilt against an upright reference
587
- * that follows the robot's heading (measured: only that combination stands).
588
- * The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
589
- * run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
853
+ * The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
854
+ * the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
855
+ * reference, read row by row.
856
+ */
857
+ function anchorSix(base) {
858
+ const [w, x, y, z] = base;
859
+ const n = Math.max(Math.hypot(w, z), 1e-9);
860
+ const hw = w / n, hz = z / n;
861
+ const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
862
+ return [
863
+ 1 - 2 * (ry * ry + rz * rz),
864
+ 2 * (rx * ry - rw * rz),
865
+ 2 * (rx * ry + rw * rz),
866
+ 1 - 2 * (rx * rx + rz * rz),
867
+ 2 * (rx * rz - rw * ry),
868
+ 2 * (ry * rz + rw * rx)
869
+ ];
870
+ }
871
+ /**
872
+ * The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
873
+ * angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
874
+ * stay zero. `ref` holds 10 frames, or 1 repeated.
590
875
  */
876
+ function encoderInput(ref, anchor) {
877
+ const e = /* @__PURE__ */ new Float32Array(1762);
878
+ const frame = (f) => ref[Math.min(f, ref.length - 1)];
879
+ let o = 4;
880
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).q[k];
881
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).dq?.[k] ?? 0;
882
+ o += 17;
883
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 6; k++) e[o++] = anchor[k];
884
+ return e;
885
+ }
886
+ /** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
887
+ var SonicHistory = class {
888
+ av = [];
889
+ q = [];
890
+ dq = [];
891
+ act = [];
892
+ g = [];
893
+ /** Fills all ten ticks with one state and zero actions. */
894
+ prime(s) {
895
+ for (const k of [
896
+ "av",
897
+ "q",
898
+ "dq",
899
+ "act",
900
+ "g"
901
+ ]) this[k] = [];
902
+ for (let i = 0; i < 10; i++) this.add(s, new Array(29).fill(0));
903
+ }
904
+ /** Adds a tick's state, with the actions the last tick produced. */
905
+ add(s, lastAction) {
906
+ const keep = (a, v) => {
907
+ a.push(v);
908
+ if (a.length > 10) a.shift();
909
+ };
910
+ keep(this.av, s.angularVelocity);
911
+ keep(this.q, s.q);
912
+ keep(this.dq, s.dq);
913
+ keep(this.act, Array.from(lastAction));
914
+ keep(this.g, s.gravity);
915
+ }
916
+ /** The decoder's 994 inputs: the token, then each history oldest first. */
917
+ decoderInput(token) {
918
+ const d = /* @__PURE__ */ new Float32Array(994);
919
+ let p = 0;
920
+ for (let k = 0; k < 64; k++) d[p++] = token[k];
921
+ for (const h of [
922
+ this.av,
923
+ this.q,
924
+ this.dq,
925
+ this.act,
926
+ this.g
927
+ ]) for (const tick of h) for (const v of tick) d[p++] = v;
928
+ return d;
929
+ }
930
+ };
931
+ // src/sonic-tables.ts
591
932
  /** The policy files and their terms. */
592
933
  const SONIC = {
593
934
  name: "gear-sonic, the default g1 controller",
@@ -736,111 +1077,85 @@ var HackbuildHumanoid = (function(exports, three) {
736
1077
  for (let j = 0; j < 29; j++) out[SONIC_JOINTS.policyIndex[j]] = v[j];
737
1078
  return out;
738
1079
  }
739
- /** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
740
- function intoBody(q, v) {
741
- const [w, x, y, z] = q;
742
- const r = [
743
- [
744
- 1 - 2 * (y * y + z * z),
745
- 2 * (x * y - w * z),
746
- 2 * (x * z + w * y)
747
- ],
748
- [
749
- 2 * (x * y + w * z),
750
- 1 - 2 * (x * x + z * z),
751
- 2 * (y * z - w * x)
752
- ],
753
- [
754
- 2 * (x * z - w * y),
755
- 2 * (y * z + w * x),
756
- 1 - 2 * (x * x + y * y)
757
- ]
758
- ];
759
- return [
760
- 0,
761
- 1,
762
- 2
763
- ].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
764
- }
1080
+ // src/sonic-motion.ts
1081
+ const positive = (name, v) => {
1082
+ if (!(Number.isFinite(v) && v > 0)) throw new HumanoidError(`${name} must be a positive number of seconds or waves; it was ${v}.`);
1083
+ return v;
1084
+ };
1085
+ const at = (name) => G1.joints.indexOf(name);
1086
+ /** Smoothstep from 0 to 1 over `seconds`, so a motion starts from the standing angles without a jump. */
1087
+ const ease = (t, seconds) => {
1088
+ const x = Math.min(1, Math.max(0, t / seconds));
1089
+ return x * x * (3 - 2 * x);
1090
+ };
765
1091
  /**
766
- * The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
767
- * the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
768
- * reference, read row by row.
1092
+ * The encoder's ten reference frames for a motion at time `t`: angles at t, t + step, and so on,
1093
+ * with velocities by central difference (one sided at 0), both in policy order.
769
1094
  */
770
- function anchorSix(base) {
771
- const [w, x, y, z] = base;
772
- const n = Math.max(Math.hypot(w, z), 1e-9);
773
- const hw = w / n, hz = z / n;
774
- const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
775
- return [
776
- 1 - 2 * (ry * ry + rz * rz),
777
- 2 * (rx * ry - rw * rz),
778
- 2 * (rx * ry + rw * rz),
779
- 1 - 2 * (rx * rx + rz * rz),
780
- 2 * (rx * rz - rw * ry),
781
- 2 * (ry * rz + rw * rx)
1095
+ function referenceFrames(motion, t, step = .1, count = 10) {
1096
+ const h = .01;
1097
+ return Array.from({ length: count }, (_, f) => {
1098
+ const tf = t + step * f;
1099
+ const lo = Math.max(0, tf - h), hi = tf + h;
1100
+ const a = motion(hi), b = motion(lo);
1101
+ return {
1102
+ q: toPolicyOrder(motion(tf)),
1103
+ dq: toPolicyOrder(a.map((v, k) => (v - b[k]) / (hi - lo)))
1104
+ };
1105
+ });
1106
+ }
1107
+ /** Squats from the standing angles to the crouch and back, again and again. */
1108
+ function squat(o = {}) {
1109
+ const period = positive("period", o.period ?? 3), depth = Math.min(1, Math.max(0, o.depth ?? 1));
1110
+ const low = [
1111
+ ["hip_pitch", -.7],
1112
+ ["knee", 1.3],
1113
+ ["ankle_pitch", -.6]
782
1114
  ];
1115
+ return (t) => {
1116
+ const s = depth * (1 - Math.cos(2 * Math.PI * t / period)) / 2;
1117
+ const q = SONIC_JOINTS.defaults.slice();
1118
+ for (const side of ["left", "right"]) for (const [joint, v] of low) {
1119
+ const j = at(`${side}_${joint}_joint`);
1120
+ q[j] = q[j] + s * (v - q[j]);
1121
+ }
1122
+ return q;
1123
+ };
783
1124
  }
784
1125
  /**
785
- * The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
786
- * angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
787
- * stay zero. `ref` holds 10 frames, or 1 repeated.
1126
+ * Raises one arm out to the side with the forearm up over 0.8 s, then waves it by the elbow.
1127
+ * On the G1 a negative shoulder roll takes the right arm out, a negative shoulder yaw then turns
1128
+ * its forearm up, and the elbow tips the forearm out and in; the left arm mirrors roll and yaw.
788
1129
  */
789
- function encoderInput(ref, anchor) {
790
- const e = /* @__PURE__ */ new Float32Array(1762);
791
- const frame = (f) => ref[Math.min(f, ref.length - 1)];
792
- let o = 4;
793
- for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).q[k];
794
- for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).dq?.[k] ?? 0;
795
- o += 17;
796
- for (let f = 0; f < 10; f++) for (let k = 0; k < 6; k++) e[o++] = anchor[k];
797
- return e;
1130
+ function wave(o = {}) {
1131
+ const s = o.side ?? "right", sign = s === "right" ? -1 : 1;
1132
+ const hz = positive("hz", o.hz ?? 1), swing = Math.min(1, Math.max(0, o.swing ?? .6));
1133
+ const roll = at(`${s}_shoulder_roll_joint`), yaw = at(`${s}_shoulder_yaw_joint`), elbow = at(`${s}_elbow_joint`);
1134
+ return (t) => {
1135
+ const e = ease(t, .8), q = SONIC_JOINTS.defaults.slice();
1136
+ q[roll] = q[roll] + e * (sign * 1.3 - q[roll]);
1137
+ q[yaw] = q[yaw] + e * (sign * 1.5 - q[yaw]);
1138
+ q[elbow] = q[elbow] + e * (swing * Math.sin(2 * Math.PI * hz * Math.max(0, t - .8)) - q[elbow]);
1139
+ return q;
1140
+ };
798
1141
  }
799
- /** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
800
- var SonicHistory = class {
801
- av = [];
802
- q = [];
803
- dq = [];
804
- act = [];
805
- g = [];
806
- /** Fills all ten ticks with one state and zero actions. */
807
- prime(s) {
808
- for (const k of [
809
- "av",
810
- "q",
811
- "dq",
812
- "act",
813
- "g"
814
- ]) this[k] = [];
815
- for (let i = 0; i < 10; i++) this.add(s, new Array(29).fill(0));
816
- }
817
- /** Adds a tick's state, with the actions the last tick produced. */
818
- add(s, lastAction) {
819
- const keep = (a, v) => {
820
- a.push(v);
821
- if (a.length > 10) a.shift();
822
- };
823
- keep(this.av, s.angularVelocity);
824
- keep(this.q, s.q);
825
- keep(this.dq, s.dq);
826
- keep(this.act, Array.from(lastAction));
827
- keep(this.g, s.gravity);
828
- }
829
- /** The decoder's 994 inputs: the token, then each history oldest first. */
830
- decoderInput(token) {
831
- const d = /* @__PURE__ */ new Float32Array(994);
832
- let p = 0;
833
- for (let k = 0; k < 64; k++) d[p++] = token[k];
834
- for (const h of [
835
- this.av,
836
- this.q,
837
- this.dq,
838
- this.act,
839
- this.g
840
- ]) for (const tick of h) for (const v of tick) d[p++] = v;
841
- return d;
842
- }
843
- };
1142
+ // src/sonic.ts
1143
+ /**
1144
+ * GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
1145
+ * page: an encoder turns a reference motion into a 64 number token, a decoder
1146
+ * turns the token and ten ticks of the robot's state into 29 joint actions,
1147
+ * 50 times a second; a PD loop here turns actions into motor torques at every
1148
+ * MuJoCo step. Written for this library from the published deployment
1149
+ * description and parameters (observation names, sizes and order, joint
1150
+ * orders, gains from motor armature, action scale, default angles). The
1151
+ * details the description leaves open were settled by trial on the deploy
1152
+ * model: joint positions relative to the default angles, the reference in
1153
+ * absolute angles, histories oldest first, a rotation's first two columns
1154
+ * row by row, and the anchor as the base's tilt against an upright reference
1155
+ * that follows the robot's heading (measured: only that combination stands).
1156
+ * The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
1157
+ * run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
1158
+ */
844
1159
  /** Where onnxruntime-web loads from when no module is given. */
845
1160
  const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
846
1161
  async function bytesOf(src, f, progress) {
@@ -915,8 +1230,11 @@ var HackbuildHumanoid = (function(exports, three) {
915
1230
  var SonicDriver = class {
916
1231
  sonic;
917
1232
  sim;
918
- /** The reference pose the policy tracks, absolute angles in the model's joint order. Default the standing angles. */
919
- reference = SONIC_JOINTS.defaults.slice();
1233
+ still = SONIC_JOINTS.defaults.slice();
1234
+ motion = null;
1235
+ clock = 0;
1236
+ /** Bumped by play, so a tick that awaited inference across a restart does not move the new clock. */
1237
+ plays = 0;
920
1238
  /** Milliseconds the last tick's inference took (measured). */
921
1239
  inferenceMs = 0;
922
1240
  adr;
@@ -946,10 +1264,44 @@ var HackbuildHumanoid = (function(exports, three) {
946
1264
  this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
947
1265
  this.reset();
948
1266
  }
949
- /** The robot back at the standing angles, upright at the origin, and the history primed. */
1267
+ /**
1268
+ * The reference pose the policy tracks, absolute angles in the model's joint order: the standing
1269
+ * angles by default, or where a playing motion is now. Setting it ends a motion.
1270
+ */
1271
+ get reference() {
1272
+ return this.motion ? this.motion(this.clock) : this.still;
1273
+ }
1274
+ set reference(pose) {
1275
+ this.motion = null;
1276
+ this.still = pose;
1277
+ }
1278
+ /**
1279
+ * Plays a moving reference from its start: each tick the encoder reads its next second as ten
1280
+ * frames 0.1 s apart, with velocities. On the G1 a squat tracks within 2.8 degrees on average and a
1281
+ * wave's elbow swings about 70 percent of its range (measured). Setting `reference` or `stop` ends it.
1282
+ */
1283
+ play(motion) {
1284
+ this.motion = motion;
1285
+ this.clock = 0;
1286
+ this.plays++;
1287
+ }
1288
+ /** Ends a motion, holding the pose it had reached. */
1289
+ stop() {
1290
+ if (this.motion) this.reference = this.motion(this.clock);
1291
+ }
1292
+ /** Whether a motion is playing. */
1293
+ get playing() {
1294
+ return this.motion !== null;
1295
+ }
1296
+ /** Seconds into the playing motion, 0 when none plays. */
1297
+ get motionTime() {
1298
+ return this.motion ? this.clock : 0;
1299
+ }
1300
+ /** The robot back at the standing angles, upright at the origin, and the history primed. A playing motion ends there, the reference back at the standing angles; a still reference is kept. */
950
1301
  reset() {
951
1302
  const { sim } = this;
952
1303
  if (sim.disposed) return;
1304
+ if (this.motion) this.reference = SONIC_JOINTS.defaults.slice();
953
1305
  this.generation++;
954
1306
  sim.reset();
955
1307
  const d = sim.data;
@@ -998,8 +1350,11 @@ var HackbuildHumanoid = (function(exports, three) {
998
1350
  d.qpos[5],
999
1351
  d.qpos[6]
1000
1352
  ]);
1001
- const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
1353
+ const motion = this.motion, plays = this.plays;
1354
+ const ref = motion ? referenceFrames(motion, this.clock) : [{ q: toPolicyOrder(this.still) }];
1355
+ const a = await this.sonic.act(encoderInput(ref, anchor), this.history);
1002
1356
  if (gen !== this.generation || this.sim.disposed) return;
1357
+ if (motion && this.plays === plays && this.motion === motion) this.clock += 1 / SONIC.hz;
1003
1358
  this.inferenceMs = performance.now() - t0;
1004
1359
  this.last = Float32Array.from(a);
1005
1360
  const pi = SONIC_JOINTS.policyIndex;
@@ -1032,7 +1387,9 @@ var HackbuildHumanoid = (function(exports, three) {
1032
1387
  }
1033
1388
  }
1034
1389
  };
1390
+ exports.BodyFollow = BodyFollow;
1035
1391
  exports.G1 = G1;
1392
+ exports.G1_FOLLOW = G1_FOLLOW;
1036
1393
  exports.G1_SONIC = G1_SONIC;
1037
1394
  exports.Humanoid = Humanoid;
1038
1395
  exports.HumanoidError = HumanoidError;
@@ -1052,7 +1409,11 @@ var HackbuildHumanoid = (function(exports, three) {
1052
1409
  exports.filesFrom = filesFrom;
1053
1410
  exports.intoBody = intoBody;
1054
1411
  exports.loadMujoco = loadMujoco;
1412
+ exports.referenceFrames = referenceFrames;
1055
1413
  exports.referencedFiles = referencedFiles;
1414
+ exports.restPoses = restPoses;
1415
+ exports.squat = squat;
1056
1416
  exports.toPolicyOrder = toPolicyOrder;
1417
+ exports.wave = wave;
1057
1418
  return exports;
1058
1419
  })({}, globalThis.THREE);