@hackbuild/motion-net 0.0.0-stage → 0.2.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/host.js ADDED
@@ -0,0 +1,735 @@
1
+ // A quadruped gait host: turns a speed and turn command into network
2
+ // inputs, plays the predictions back in time, integrates root motion, pins
3
+ // planted paws, and fills the gait package's motor state.
4
+ //
5
+ // Frames. The network works in a left handed frame (x to the dog's right,
6
+ // y up, z forward, a positive yaw turning right). The host's public frame
7
+ // is the family one: right handed, +Z forward, +X to the dog's left, a
8
+ // positive yaw turning left, as in @hackbuild/gait. Everything inside this
9
+ // file is in the network frame; `out` mirrors x and negates yaw at the
10
+ // boundary, and bone axes are mirrored the same way.
11
+ import { BONE_COUNT, FRAME_DT, FRAMES, IN, OUT, PAW_CHAINS } from "./layout.js";
12
+ // Each value is chosen for a reason given beside it.
13
+ export const DEFAULT_TUNING = {
14
+ // 0.1 s: ten replans a second answer a command within one step, and each
15
+ // prediction covers 0.5 s, so a late one still has frames to play. At
16
+ // 0.05 s the seams between predictions moved the paws 20 percent more
17
+ // (measured); at 0.2 s the dog stuck in a gallop at 2 m/s (measured)
18
+ interval: 0.1,
19
+ // the training trajectories put sample 0 about 0.25 s ahead of the root
20
+ // and sample 15 about 0.5 s ahead (input_stats means over the mean
21
+ // forward speed); sampling the command at 0.25 + k/60 s matches that
22
+ trajStart: 0.25,
23
+ trajStep: 1 / 60,
24
+ // 0.2 s: the first samples continue the motion the dog already has, so a
25
+ // command step does not ask the network for a velocity jump
26
+ trajBlend: 0.2,
27
+ // 0.15 s: a dog reaches a new trot speed in roughly half a second; a
28
+ // shorter half life passes key taps straight through as speed steps
29
+ commandHalflife: 0.15,
30
+ // 0.06 s: consecutive predictions overlap by 0.4 s and differ by
31
+ // millimeters; 94 percent of a seam is gone within 0.24 s, shorter than
32
+ // a walking stance, so a pinned paw is not dragged by the blend
33
+ seamHalflife: 0.06,
34
+ // planted values sit near 1 and swing near 0. Inside a prediction a paw
35
+ // with a value of 0.85 or more moves under 7 mm per frame, one near 0.6
36
+ // moves 18 mm and one near 0.5 moves 33 mm (measured), so a paw pins
37
+ // above 0.8 and lets go below 0.6
38
+ contactOn: 0.8,
39
+ contactOff: 0.6,
40
+ // 0.12 m is about a quarter of the 0.45 m hip height; past that the leg
41
+ // solve bends the limb visibly out of the network's shape
42
+ maxPin: 0.12,
43
+ // inside its own predictions the network's stance paws drift forward
44
+ // about 0.08 m/s at a walk or trot (measured), so its root runs ahead of
45
+ // its feet. The root takes over 90 percent of that drift through a 0.08 s
46
+ // low pass, and a 0.25 s pull toward the pins removes what is left. A
47
+ // shorter low pass doubled the frame to frame speed change of the body
48
+ // (measured); a longer one let pinned paws slide at 1.6 m/s (measured)
49
+ plantFollow: 0.9,
50
+ plantHalflife: 0.25,
51
+ followHalflife: 0.08,
52
+ // the network's speeds come in bands (about 0.8 to 1.4, 1.9 to 2.0 and
53
+ // 3.2 to 3.3 m/s at a plain trajectory, measured); the speed loop leans
54
+ // the trajectory up to 2 m/s either way and reaches the command within
55
+ // about 0.05 m/s from 0.6 to 3.5 m/s (measured). A gain of 1.5 per second
56
+ // settles in about two seconds; 3 overshot at 2 and 3.5 m/s (measured)
57
+ speedGain: 1.5,
58
+ leanRange: 2,
59
+ // the style pose barely moves the speed (measured: Walk, Trot, Canter and
60
+ // Pace give the same speed bands); it picks the footfall pattern, so Walk
61
+ // below 1 m/s, Trot to 2.1 m/s where the second band sits, Canter above
62
+ walkAt: 0.15,
63
+ trotAt: 1.0,
64
+ canterAt: 2.1,
65
+ };
66
+ const N = BONE_COUNT * 3;
67
+ const LN2 = Math.LN2;
68
+ const decay = (dt, halflife) => Math.exp((-LN2 * dt) / Math.max(halflife, 1e-6));
69
+ const wallMs = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
70
+ const finite = (x) => (Number.isFinite(x) ? x : 0);
71
+ /** Pose in the root frame of the moment it describes. */
72
+ class Pose {
73
+ pos = new Float64Array(N);
74
+ zax = new Float64Array(N);
75
+ yax = new Float64Array(N);
76
+ vel = new Float64Array(N);
77
+ contacts = new Float64Array(4);
78
+ /** Root velocity in the root frame, m/s, and yaw rate, rad/s (network sign). */
79
+ vx = 0;
80
+ vz = 0;
81
+ w = 0;
82
+ copy(o) {
83
+ this.pos.set(o.pos);
84
+ this.zax.set(o.zax);
85
+ this.yax.set(o.yax);
86
+ this.vel.set(o.vel);
87
+ this.contacts.set(o.contacts);
88
+ this.vx = o.vx;
89
+ this.vz = o.vz;
90
+ this.w = o.w;
91
+ }
92
+ }
93
+ function sample(p, tau, out) {
94
+ const f = Math.min(Math.max(tau / FRAME_DT, 0), FRAMES - 1);
95
+ const k0 = Math.floor(f);
96
+ const k1 = Math.min(k0 + 1, FRAMES - 1);
97
+ const a = f - k0;
98
+ const F = p.frames;
99
+ const o0 = k0 * OUT.length;
100
+ const o1 = k1 * OUT.length;
101
+ const lerp = (i) => F[o0 + i] + (F[o1 + i] - F[o0 + i]) * a;
102
+ for (let i = 0; i < N; i++) {
103
+ out.pos[i] = lerp(OUT.positions + i);
104
+ out.zax[i] = lerp(OUT.axisZ + i);
105
+ out.yax[i] = lerp(OUT.axisY + i);
106
+ out.vel[i] = lerp(OUT.velocities + i);
107
+ }
108
+ for (let i = 0; i < 4; i++)
109
+ out.contacts[i] = lerp(OUT.contacts + i);
110
+ // frame k1's delta is the motion from frame k0 into k1
111
+ const d = k0 === k1 ? o0 : o1;
112
+ out.vx = F[d + OUT.dx] / FRAME_DT;
113
+ out.vz = F[d + OUT.dz] / FRAME_DT;
114
+ out.w = ((F[d + OUT.dyaw] / FRAME_DT) * Math.PI) / 180;
115
+ // past the window the prediction has nothing more to say: hold the last
116
+ // pose and let the root come to rest with a 0.1 s half life rather than
117
+ // slide a frozen pose along
118
+ const over = tau - (FRAMES - 1) * FRAME_DT;
119
+ if (over > 0) {
120
+ const k = decay(over, 0.1);
121
+ out.vx *= k;
122
+ out.vz *= k;
123
+ out.w *= k;
124
+ for (let i = 0; i < N; i++)
125
+ out.vel[i] *= k;
126
+ }
127
+ }
128
+ /** Rotation quaternion (x, y, z, w) from orthonormal columns X, Y, Z. */
129
+ function quatFromAxes(X, Y, Z, q, o) {
130
+ const [m00, m10, m20] = X;
131
+ const [m01, m11, m21] = Y;
132
+ const [m02, m12, m22] = Z;
133
+ const tr = m00 + m11 + m22;
134
+ let x, y, z, w;
135
+ if (tr > 0) {
136
+ const s = Math.sqrt(tr + 1) * 2;
137
+ w = 0.25 * s;
138
+ x = (m21 - m12) / s;
139
+ y = (m02 - m20) / s;
140
+ z = (m10 - m01) / s;
141
+ }
142
+ else if (m00 > m11 && m00 > m22) {
143
+ const s = Math.sqrt(1 + m00 - m11 - m22) * 2;
144
+ w = (m21 - m12) / s;
145
+ x = 0.25 * s;
146
+ y = (m01 + m10) / s;
147
+ z = (m02 + m20) / s;
148
+ }
149
+ else if (m11 > m22) {
150
+ const s = Math.sqrt(1 + m11 - m00 - m22) * 2;
151
+ w = (m02 - m20) / s;
152
+ x = (m01 + m10) / s;
153
+ y = 0.25 * s;
154
+ z = (m12 + m21) / s;
155
+ }
156
+ else {
157
+ const s = Math.sqrt(1 + m22 - m00 - m11) * 2;
158
+ w = (m10 - m01) / s;
159
+ x = (m02 + m20) / s;
160
+ y = (m12 + m21) / s;
161
+ z = 0.25 * s;
162
+ }
163
+ const n = Math.hypot(x, y, z, w) || 1;
164
+ q[o] = x / n;
165
+ q[o + 1] = y / n;
166
+ q[o + 2] = z / n;
167
+ q[o + 3] = w / n;
168
+ }
169
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
170
+ const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
171
+ const scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s];
172
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
173
+ const len = (a) => Math.sqrt(dot(a, a));
174
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
175
+ const norm = (a) => {
176
+ const l = len(a);
177
+ return l > 1e-9 ? scale(a, 1 / l) : [0, 0, 1];
178
+ };
179
+ /** Rotates v by the shortest arc that takes unit a to unit b. */
180
+ function rotateArc(v, a, b) {
181
+ const c = dot(a, b);
182
+ const k = cross(a, b);
183
+ if (c < -0.9999)
184
+ return v;
185
+ // Rodrigues with the unnormalized axis: v c + (k x v) + k (k.v) / (1 + c)
186
+ return add(add(scale(v, c), cross(k, v)), scale(k, dot(k, v) / (1 + c)));
187
+ }
188
+ /** Drives the quadruped network and fills the gait motor state. */
189
+ export class QuadrupedHost {
190
+ predictor;
191
+ styles;
192
+ capabilities = { turnInPlace: true, minStopDistance: 0.15, headPitchBias: 0 };
193
+ tuning;
194
+ /** Root in the host frame: position on the ground and yaw (positive left). */
195
+ root = { x: 0, z: 0, yaw: 0 };
196
+ /** Root velocity in the host frame, m/s, and turn rate, rad/s. */
197
+ rootVelocity = { x: 0, z: 0, turnRate: 0 };
198
+ /** World bone positions, host frame, x y z per bone. */
199
+ positions = new Float32Array(N);
200
+ /** World bone rotations, host frame, x y z w per bone. */
201
+ rotations = new Float32Array(BONE_COUNT * 4);
202
+ paws = [0, 1, 2, 3].map(() => ({ contact: 1, stance: true, pin: null, phase: 0 }));
203
+ style = "Idle";
204
+ /** Request to arrival of the last prediction, wall clock ms (measured). */
205
+ latencyMs = 0;
206
+ /** Request to first use of the last prediction, ms on the host clock: what playback skips (measured). */
207
+ lagMs = 0;
208
+ /** Evaluation time of the last prediction where it ran, ms (measured). */
209
+ evalMs = 0;
210
+ /** Seconds since the playing prediction was requested; past 0.5 the dog holds. */
211
+ predictionAge = 0;
212
+ /** Horizontal travel of each stance paw this frame, m, after pinning and before. */
213
+ footSlide = [0, 0, 0, 0];
214
+ rawFootSlide = [0, 0, 0, 0];
215
+ /** Distance from each pinned paw to where the network puts it, m; 0 when free. */
216
+ pinGap = [0, 0, 0, 0];
217
+ /** Predictions received and requests sent. */
218
+ received = 0;
219
+ requested = 0;
220
+ // network frame state
221
+ t = 0;
222
+ yaw = 0;
223
+ px = 0;
224
+ pz = 0;
225
+ cmdV = { x: 0, z: 0 };
226
+ cmdW = 0;
227
+ /** Speed added to the trajectory by the speed loop, m/s. */
228
+ lean = 0;
229
+ /** Ground speed of the root, smoothed over 0.1 s, m/s. */
230
+ speedNow = 0;
231
+ /** Turn rate of the root, smoothed over 0.1 s, rad/s (network sign). */
232
+ turnNow = 0;
233
+ turnLean = 0;
234
+ /** Pinned paw positions, network frame world. */
235
+ pins = [null, null, null, null];
236
+ /** The network's paw ends last frame, network frame world x z. */
237
+ follow = [0, 0];
238
+ /** Last knee bend direction per leg, root frame. */
239
+ bend = [null, null, null, null];
240
+ prevRaw = [null, null, null, null];
241
+ active = null;
242
+ pending = null;
243
+ lastRequest = -Infinity;
244
+ pose = new Pose();
245
+ fresh = new Pose();
246
+ seam = new Pose();
247
+ seamOn = false;
248
+ input = new Float32Array(IN.length);
249
+ lastSite = [null, null, null, null];
250
+ lastRawSite = [null, null, null, null];
251
+ release = [0, 1, 2, 3].map(() => [0, 0, 0]);
252
+ touch = [0, 1, 2, 3].map(() => ({ last: -1, period: 0, stanceStart: 0, duty: 0 }));
253
+ lastCmd = { speed: 0, turnRate: 0 };
254
+ constructor(predictor, styles, tuning = {}) {
255
+ this.predictor = predictor;
256
+ this.styles = styles;
257
+ this.tuning = { ...DEFAULT_TUNING, ...tuning };
258
+ // no history yet: the Idle style pose with zero velocity and rest axes
259
+ const idle = styles.Idle;
260
+ for (let i = 0; i < N; i++)
261
+ this.pose.pos[i] = idle[i] ?? 0;
262
+ for (let b = 0; b < BONE_COUNT; b++) {
263
+ this.pose.zax[b * 3 + 2] = 1;
264
+ this.pose.yax[b * 3 + 1] = 1;
265
+ }
266
+ this.pose.contacts.fill(1);
267
+ this.output(0);
268
+ }
269
+ /** Places the dog, host frame, and forgets any motion. */
270
+ reset(x, z, yaw) {
271
+ this.px = -x;
272
+ this.pz = z;
273
+ this.yaw = -yaw;
274
+ this.root = { x, z, yaw };
275
+ this.active = null;
276
+ this.seamOn = false;
277
+ this.paws.forEach((p) => (p.pin = null));
278
+ this.pins.fill(null);
279
+ this.prevRaw.fill(null);
280
+ this.lastSite.fill(null);
281
+ this.lastRawSite.fill(null);
282
+ }
283
+ update(dtIn, cmd) {
284
+ // a stalled or backward clock adds no time; a long gap (tab switch) is
285
+ // cut to 0.1 s so a stale prediction is not integrated for a second
286
+ const dt = Number.isFinite(dtIn) && dtIn > 0 ? Math.min(dtIn, 0.1) : 0;
287
+ this.lastCmd = cmd;
288
+ this.t += dt;
289
+ this.steer(dt, cmd);
290
+ this.schedule();
291
+ if (this.active) {
292
+ this.predictionAge = this.t - this.active.t0;
293
+ sample(this.active, this.predictionAge, this.fresh);
294
+ if (this.seamOn) {
295
+ const k = decay(dt, this.tuning.seamHalflife);
296
+ const s = this.seam;
297
+ for (let i = 0; i < N; i++) {
298
+ s.pos[i] *= k;
299
+ s.zax[i] *= k;
300
+ s.yax[i] *= k;
301
+ s.vel[i] *= k;
302
+ }
303
+ s.vx *= k;
304
+ s.vz *= k;
305
+ s.w *= k;
306
+ this.pose.copy(this.fresh);
307
+ for (let i = 0; i < N; i++) {
308
+ this.pose.pos[i] += s.pos[i];
309
+ this.pose.zax[i] += s.zax[i];
310
+ this.pose.yax[i] += s.yax[i];
311
+ this.pose.vel[i] += s.vel[i];
312
+ }
313
+ this.pose.vx += s.vx;
314
+ this.pose.vz += s.vz;
315
+ this.pose.w += s.w;
316
+ }
317
+ else
318
+ this.pose.copy(this.fresh);
319
+ }
320
+ // root: the network's own root motion
321
+ const p = this.pose;
322
+ const { vx, vz, w } = p;
323
+ const x0 = this.px;
324
+ const z0 = this.pz;
325
+ this.yaw += w * dt;
326
+ const sy = Math.sin(this.yaw);
327
+ const cy = Math.cos(this.yaw);
328
+ this.px += (cy * vx + sy * vz) * dt;
329
+ this.pz += (-sy * vx + cy * vz) * dt;
330
+ // then the root takes over the network's paw slip: the network's planted
331
+ // paws drift in the world (its root runs ahead of its feet), so the
332
+ // root moves back by the weighted drift of the paws in stance, each
333
+ // weighted by how firmly its contact value says it is down
334
+ const T = this.tuning;
335
+ const rawNow = PAW_CHAINS.map((ch) => {
336
+ const lx = p.pos[ch.site * 3];
337
+ const lz = p.pos[ch.site * 3 + 2];
338
+ return [this.px + cy * lx + sy * lz, this.pz - sy * lx + cy * lz];
339
+ });
340
+ if (dt > 0) {
341
+ let sx = 0;
342
+ let sz = 0;
343
+ let sw = 0;
344
+ let gx = 0;
345
+ let gz = 0;
346
+ let gn = 0;
347
+ PAW_CHAINS.forEach((_, i) => {
348
+ const prev = this.prevRaw[i];
349
+ const paw = this.paws[i];
350
+ if (prev && paw.stance) {
351
+ const wgt = Math.max(0, Math.min(1, (p.contacts[i] - T.contactOff) / Math.max(1e-3, T.contactOn - T.contactOff)));
352
+ sx += wgt * (rawNow[i][0] - prev[0]);
353
+ sz += wgt * (rawNow[i][1] - prev[1]);
354
+ sw += wgt;
355
+ }
356
+ const pin = this.pins[i];
357
+ if (pin) {
358
+ gx += pin[0] - rawNow[i][0];
359
+ gz += pin[2] - rawNow[i][1];
360
+ gn++;
361
+ }
362
+ });
363
+ // the drift is noisy frame to frame (frame interpolation, seams); the
364
+ // root takes it through a low pass and the pinned legs absorb the rest
365
+ const n = Math.max(1, sw);
366
+ const kf = 1 - decay(dt, T.followHalflife);
367
+ this.follow[0] += ((-T.plantFollow * sx) / n / dt - this.follow[0]) * kf;
368
+ this.follow[1] += ((-T.plantFollow * sz) / n / dt - this.follow[1]) * kf;
369
+ let mx = this.follow[0] * dt;
370
+ let mz = this.follow[1] * dt;
371
+ // and a slow pull toward the pins for what the follow leaves behind
372
+ if (gn > 0 && T.plantHalflife > 0) {
373
+ const k = 1 - decay(dt, T.plantHalflife);
374
+ mx += (gx / gn) * k;
375
+ mz += (gz / gn) * k;
376
+ }
377
+ this.px += mx;
378
+ this.pz += mz;
379
+ rawNow.forEach((r) => {
380
+ r[0] += mx;
381
+ r[1] += mz;
382
+ });
383
+ }
384
+ PAW_CHAINS.forEach((_, i) => (this.prevRaw[i] = rawNow[i]));
385
+ const wx = dt > 0 ? (this.px - x0) / dt : 0;
386
+ const wz = dt > 0 ? (this.pz - z0) / dt : 0;
387
+ if (dt > 0) {
388
+ const k = 1 - decay(dt, 0.1);
389
+ this.speedNow += (Math.hypot(wx, wz) - this.speedNow) * k;
390
+ this.turnNow += (w - this.turnNow) * k;
391
+ }
392
+ this.rootVelocity = { x: -wx, z: wz, turnRate: -w };
393
+ this.output(dt);
394
+ this.root = { x: -this.px, z: this.pz, yaw: -this.yaw };
395
+ return { x: this.root.x, z: this.root.z, yaw: this.root.yaw, speed: Math.hypot(wx, wz), turnRate: -w };
396
+ }
397
+ motorState() {
398
+ const lf = this.touch[0];
399
+ const standing = this.t - lf.last > 2 || lf.period === 0;
400
+ return {
401
+ source: "neural",
402
+ phase: this.paws[0].phase,
403
+ duty: standing ? 1 : this.touch.reduce((a, b) => a + b.duty, 0) / 4,
404
+ strideFrequency: standing ? 0 : 1 / lf.period,
405
+ contacts: this.paws.map((p) => p.stance),
406
+ };
407
+ }
408
+ /** Smooths the command into a network frame world velocity and yaw rate, and picks the style. */
409
+ steer(dt, cmd) {
410
+ let vx, vz, w;
411
+ const speed = finite(cmd.speed);
412
+ if (cmd.velocity) {
413
+ vx = -finite(cmd.velocity.x);
414
+ vz = finite(cmd.velocity.z);
415
+ }
416
+ else {
417
+ vx = Math.sin(this.yaw) * speed;
418
+ vz = Math.cos(this.yaw) * speed;
419
+ }
420
+ if (cmd.facing !== undefined && Number.isFinite(cmd.facing)) {
421
+ let d = -cmd.facing - this.yaw;
422
+ d = Math.atan2(Math.sin(d), Math.cos(d));
423
+ // close a facing error at up to 3 rad/s, about a dog's fast pivot
424
+ w = Math.max(-3, Math.min(3, d * 4));
425
+ }
426
+ else
427
+ w = -finite(cmd.turnRate);
428
+ const k = 1 - decay(dt, this.tuning.commandHalflife);
429
+ this.cmdV.x += (vx - this.cmdV.x) * k;
430
+ this.cmdV.z += (vz - this.cmdV.z) * k;
431
+ this.cmdW += (w - this.cmdW) * k;
432
+ // speed loop: the network's speeds come in bands, so lean the
433
+ // trajectory by the integral of the speed error; the lean is held
434
+ // between -1 and 1.5 m/s and drops to zero when the dog is asked to stop
435
+ const want = Math.hypot(this.cmdV.x, this.cmdV.z);
436
+ if (want < 0.1 || !this.active)
437
+ this.lean *= decay(dt, 0.2);
438
+ else {
439
+ const got = this.speedNow;
440
+ this.lean = Math.max(-this.tuning.leanRange, Math.min(this.tuning.leanRange, this.lean + this.tuning.speedGain * (want - got) * dt));
441
+ }
442
+ // the same loop on the turn rate: the network turns about 17 percent
443
+ // short of the trajectory (measured at 1 rad/s); the lean is held within
444
+ // 1.5 rad/s and drops when no turn is asked for
445
+ if (Math.abs(this.cmdW) < 0.05 || !this.active)
446
+ this.turnLean *= decay(dt, 0.2);
447
+ else
448
+ this.turnLean = Math.max(-1.5, Math.min(1.5, this.turnLean + this.tuning.speedGain * (this.cmdW - this.turnNow) * dt));
449
+ if (cmd.style && cmd.style !== "auto") {
450
+ this.style = cmd.style;
451
+ return;
452
+ }
453
+ // auto style with 0.1 m/s of hysteresis so a speed near a threshold does not flicker
454
+ const v = Math.hypot(this.cmdV.x, this.cmdV.z);
455
+ const T = this.tuning;
456
+ const h = 0.1;
457
+ const order = ["Idle", "Walk", "Trot", "Canter"];
458
+ const up = [T.walkAt, T.trotAt, T.canterAt];
459
+ let i = Math.max(0, order.indexOf(this.style));
460
+ if (!order.includes(this.style))
461
+ i = v < T.walkAt ? 0 : v < T.trotAt ? 1 : v < T.canterAt ? 2 : 3;
462
+ while (i < 3 && v > up[i] + h / 2)
463
+ i++;
464
+ while (i > 0 && v < up[i - 1] - h / 2)
465
+ i--;
466
+ // turning in place steps around at a walk
467
+ if (i === 0 && Math.abs(this.cmdW) > 0.3)
468
+ i = 1;
469
+ this.style = order[i];
470
+ }
471
+ toLocal(x, z) {
472
+ const s = Math.sin(this.yaw);
473
+ const c = Math.cos(this.yaw);
474
+ return [c * x - s * z, s * x + c * z];
475
+ }
476
+ schedule() {
477
+ const T = this.tuning;
478
+ // a request older than a second is treated as lost so the host can ask again
479
+ if (this.pending && this.t - this.pending.sent > 1)
480
+ this.pending = null;
481
+ if (this.pending || this.t - this.lastRequest < T.interval)
482
+ return;
483
+ this.buildInput();
484
+ const req = { t0: this.t, sent: this.t, wall: wallMs() };
485
+ this.pending = req;
486
+ this.lastRequest = this.t;
487
+ this.requested++;
488
+ this.predictor.predict(this.input).then((r) => this.land(r, req), () => {
489
+ if (this.pending === req)
490
+ this.pending = null;
491
+ });
492
+ }
493
+ land(r, req) {
494
+ if (this.pending === req)
495
+ this.pending = null;
496
+ if (this.active && req.t0 <= this.active.t0)
497
+ return;
498
+ if (!r.frames.every(Number.isFinite))
499
+ return;
500
+ const next = { frames: r.frames, t0: req.t0, latency: this.t - req.t0, evalMs: r.ms };
501
+ this.received++;
502
+ this.lagMs = next.latency * 1000;
503
+ this.latencyMs = wallMs() - req.wall;
504
+ this.evalMs = r.ms;
505
+ // the seam: what the dog shows now minus what the new prediction says for now
506
+ sample(next, this.t - next.t0, this.fresh);
507
+ if (this.active) {
508
+ const s = this.seam;
509
+ for (let i = 0; i < N; i++) {
510
+ s.pos[i] = this.pose.pos[i] - this.fresh.pos[i];
511
+ s.zax[i] = this.pose.zax[i] - this.fresh.zax[i];
512
+ s.yax[i] = this.pose.yax[i] - this.fresh.yax[i];
513
+ s.vel[i] = this.pose.vel[i] - this.fresh.vel[i];
514
+ }
515
+ s.vx = this.pose.vx - this.fresh.vx;
516
+ s.vz = this.pose.vz - this.fresh.vz;
517
+ s.w = this.pose.w - this.fresh.w;
518
+ this.seamOn = true;
519
+ }
520
+ this.active = next;
521
+ }
522
+ /** Current pose and velocities, the trajectory and the style pose, in the current root frame. */
523
+ buildInput() {
524
+ const u = this.input;
525
+ const p = this.pose;
526
+ for (let i = 0; i < N; i++) {
527
+ u[IN.positions + i] = p.pos[i];
528
+ u[IN.velocities + i] = p.vel[i];
529
+ }
530
+ // desired root velocity in the root frame, and the root's own velocity
531
+ const T = this.tuning;
532
+ const want = Math.hypot(this.cmdV.x, this.cmdV.z);
533
+ const gain = want > 1e-6 ? Math.max(0, want + this.lean) / want : 0;
534
+ const [dvx, dvz] = this.toLocal(this.cmdV.x * gain, this.cmdV.z * gain);
535
+ const w = this.cmdW + this.turnLean;
536
+ const v0x = p.vx;
537
+ const v0z = p.vz;
538
+ // the commanded velocity turns with the facing; the root's current
539
+ // velocity gives way to it over 0.2 s, a little longer than the command
540
+ // half life, so the first samples continue the motion the dog has
541
+ const velAt = (s) => {
542
+ const a = w * s;
543
+ const ca = Math.cos(a);
544
+ const sa = Math.sin(a);
545
+ const rx = ca * dvx + sa * dvz;
546
+ const rz = -sa * dvx + ca * dvz;
547
+ const b = T.trajBlend > 0 ? Math.exp(-s / T.trajBlend) : 0;
548
+ return [rx + (v0x - rx) * b, rz + (v0z - rz) * b];
549
+ };
550
+ let x = 0;
551
+ let z = 0;
552
+ let s = 0;
553
+ const h = 1 / 240;
554
+ for (let k = 0; k < 16; k++) {
555
+ const target = T.trajStart + k * T.trajStep;
556
+ while (s < target - 1e-9) {
557
+ const step = Math.min(h, target - s);
558
+ const [a, b] = velAt(s + step / 2);
559
+ x += a * step;
560
+ z += b * step;
561
+ s += step;
562
+ }
563
+ const [vx, vz] = velAt(target);
564
+ const yaw = w * target;
565
+ u[IN.trajPositions + 2 * k] = x;
566
+ u[IN.trajPositions + 2 * k + 1] = z;
567
+ u[IN.trajDirections + 2 * k] = Math.sin(yaw);
568
+ u[IN.trajDirections + 2 * k + 1] = Math.cos(yaw);
569
+ u[IN.trajVelocities + 2 * k] = vx;
570
+ u[IN.trajVelocities + 2 * k + 1] = vz;
571
+ }
572
+ const st = this.styles[this.style];
573
+ for (let i = 0; i < N; i++)
574
+ u[IN.style + i] = st[i] ?? 0;
575
+ }
576
+ /** World transforms, pins, phases and slide readouts from the current pose. */
577
+ output(dt) {
578
+ const p = this.pose;
579
+ const sy = Math.sin(this.yaw);
580
+ const cy = Math.cos(this.yaw);
581
+ const toWorld = (l) => [this.px + cy * l[0] + sy * l[2], l[1], this.pz - sy * l[0] + cy * l[2]];
582
+ const toRoot = (g) => {
583
+ const dx = g[0] - this.px;
584
+ const dz = g[2] - this.pz;
585
+ return [cy * dx - sy * dz, g[1], sy * dx + cy * dz];
586
+ };
587
+ const at = (a, b) => [a[b * 3], a[b * 3 + 1], a[b * 3 + 2]];
588
+ // root frame positions and axes, then pinned
589
+ const pos = Float64Array.from(p.pos);
590
+ const zax = Float64Array.from(p.zax);
591
+ const yax = Float64Array.from(p.yax);
592
+ const put = (a, b, v) => {
593
+ a[b * 3] = v[0];
594
+ a[b * 3 + 1] = v[1];
595
+ a[b * 3 + 2] = v[2];
596
+ };
597
+ const T = this.tuning;
598
+ PAW_CHAINS.forEach((ch, i) => {
599
+ const paw = this.paws[i];
600
+ const c = finite(p.contacts[i]);
601
+ paw.contact = c;
602
+ const rawSite = toWorld(at(pos, ch.site));
603
+ const was = paw.stance;
604
+ paw.stance = was ? c > T.contactOff : c > T.contactOn;
605
+ const tr = this.touch[i];
606
+ if (paw.stance && !was) {
607
+ // touchdown: a stride period between 0.15 and 2 s is a plausible dog stride
608
+ if (tr.last >= 0) {
609
+ const per = this.t - tr.last;
610
+ if (per > 0.15 && per < 2)
611
+ tr.period = per;
612
+ }
613
+ tr.last = this.t;
614
+ tr.stanceStart = this.t;
615
+ // pin where the paw is shown, which may still carry a release offset
616
+ this.pins[i] = toWorld(add(at(pos, ch.site), this.release[i]));
617
+ this.release[i] = [0, 0, 0];
618
+ }
619
+ if (!paw.stance && was) {
620
+ if (tr.period > 0)
621
+ tr.duty = Math.min(1, (this.t - tr.stanceStart) / tr.period);
622
+ const pin = this.pins[i];
623
+ if (pin)
624
+ this.release[i] = sub(toRoot(pin), at(pos, ch.site));
625
+ this.pins[i] = null;
626
+ }
627
+ paw.phase = tr.period > 0 && tr.last >= 0 ? Math.min(0.999, (this.t - tr.last) / tr.period) : 0;
628
+ // where the paw end should be, in the root frame
629
+ let target = null;
630
+ this.pinGap[i] = 0;
631
+ const pin = this.pins[i];
632
+ if (paw.stance && pin) {
633
+ const pinned = toRoot(pin);
634
+ this.pinGap[i] = len(sub(pinned, at(pos, ch.site)));
635
+ if (this.pinGap[i] > T.maxPin) {
636
+ // too far to hold: let go and blend back to the network's paw; no new pin before the next touchdown
637
+ this.release[i] = sub(pinned, at(pos, ch.site));
638
+ this.pins[i] = null;
639
+ }
640
+ else
641
+ target = pinned;
642
+ }
643
+ if (!this.pins[i]) {
644
+ this.release[i] = scale(this.release[i], decay(dt, 0.05));
645
+ if (len(this.release[i]) > 1e-5)
646
+ target = add(at(pos, ch.site), this.release[i]);
647
+ }
648
+ const held = this.pins[i];
649
+ paw.pin = held ? [-held[0], held[1], held[2]] : null;
650
+ if (target)
651
+ this.pinLeg(pos, zax, yax, ch, target, put, at);
652
+ const site = toWorld(at(pos, ch.site));
653
+ const slide = (a, b) => (a ? Math.hypot(b[0] - a[0], b[2] - a[2]) : 0);
654
+ this.footSlide[i] = paw.stance && was ? slide(this.lastSite[i], site) : 0;
655
+ this.rawFootSlide[i] = paw.stance && was ? slide(this.lastRawSite[i], rawSite) : 0;
656
+ this.lastSite[i] = site;
657
+ this.lastRawSite[i] = rawSite;
658
+ });
659
+ // world transforms in the host frame: mirror x
660
+ for (let b = 0; b < BONE_COUNT; b++) {
661
+ const g = toWorld(at(pos, b));
662
+ this.positions[b * 3] = -g[0];
663
+ this.positions[b * 3 + 1] = g[1];
664
+ this.positions[b * 3 + 2] = g[2];
665
+ // axes to world (network frame), then mirrored; X completes a right handed triad
666
+ const zl = norm(at(zax, b));
667
+ let yl = at(yax, b);
668
+ yl = norm(sub(yl, scale(zl, dot(yl, zl))));
669
+ const rot = (v) => [cy * v[0] + sy * v[2], v[1], -sy * v[0] + cy * v[2]];
670
+ const Z = rot(zl);
671
+ const Y = rot(yl);
672
+ const Zh = [-Z[0], Z[1], Z[2]];
673
+ const Yh = [-Y[0], Y[1], Y[2]];
674
+ const Xh = cross(Yh, Zh);
675
+ quatFromAxes(Xh, Yh, Zh, this.rotations, b * 4);
676
+ }
677
+ }
678
+ /** Moves the paw end to `target` (root frame) and bends the knee to keep both limb lengths. */
679
+ pinLeg(pos, zax, yax, ch, target, put, at) {
680
+ const a = at(pos, ch.upper);
681
+ const knee = at(pos, ch.lower);
682
+ const paw = at(pos, ch.paw);
683
+ const site = at(pos, ch.site);
684
+ const shift = sub(target, site);
685
+ let pawT = add(paw, shift);
686
+ const l1 = len(sub(knee, a));
687
+ const l2 = len(sub(paw, knee));
688
+ let d = sub(pawT, a);
689
+ let dl = len(d);
690
+ const lo = Math.abs(l1 - l2) + 1e-4;
691
+ const hi = l1 + l2 - 1e-4;
692
+ if (dl < 1e-6)
693
+ return;
694
+ if (dl > hi || dl < lo) {
695
+ // out of reach: the paw stops where the limb can put it
696
+ const c = Math.min(hi, Math.max(lo, dl));
697
+ pawT = add(a, scale(d, c / dl));
698
+ d = sub(pawT, a);
699
+ dl = c;
700
+ }
701
+ const u = scale(d, 1 / dl);
702
+ const x = (l1 * l1 - l2 * l2 + dl * dl) / (2 * dl);
703
+ const y = Math.sqrt(Math.max(0, l1 * l1 - x * x));
704
+ // bend toward the network's own knee. A nearly straight limb leaves that
705
+ // direction undefined, so last frame's bend counts as a 3 cm offset of
706
+ // the knee (about a fifth of a limb bone) and a 1 cm hint (elbows back,
707
+ // stifles forward) settles the first frame; the bend cannot flip
708
+ // between frames unless the network's knee moves well past the line
709
+ const leg = PAW_CHAINS.indexOf(ch);
710
+ const hint = [0, 0, ch.upper < 16 ? -0.01 : 0.01];
711
+ const kd = add(add(sub(knee, a), hint), scale(this.bend[leg] ?? [0, 0, 0], 0.03));
712
+ let n = sub(kd, scale(u, dot(kd, u)));
713
+ n = len(n) > 1e-6 ? norm(n) : norm(cross(u, [1, 0, 0]));
714
+ if (leg >= 0)
715
+ this.bend[leg] = n;
716
+ const kneeT = add(add(a, scale(u, x)), scale(n, y));
717
+ // turn the two limb bones' axes with their segments
718
+ const turn = (b, from, to) => {
719
+ const f = norm(from);
720
+ const t = norm(to);
721
+ put(zax, b, rotateArc(at(zax, b), f, t));
722
+ put(yax, b, rotateArc(at(yax, b), f, t));
723
+ };
724
+ turn(ch.upper, sub(knee, a), sub(kneeT, a));
725
+ turn(ch.lower, sub(paw, knee), sub(pawT, kneeT));
726
+ const move = sub(pawT, paw);
727
+ put(pos, ch.lower, kneeT);
728
+ put(pos, ch.paw, pawT);
729
+ put(pos, ch.site, add(site, move));
730
+ }
731
+ /** The last command passed to update. */
732
+ get command() {
733
+ return this.lastCmd;
734
+ }
735
+ }