@hackbuild/humanoid 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.
@@ -0,0 +1,1000 @@
1
+ var HackbuildHumanoid = (function(exports, three) {
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ // src/runtime.ts
4
+ /**
5
+ * MuJoCo in the page: Google DeepMind's WebAssembly build (`@mujoco/mujoco`,
6
+ * Apache-2.0), the single threaded one, so the page needs no cross-origin
7
+ * isolation. This library never bundles it: pass the factory a bundler
8
+ * imported, or it loads at run time from a URL (default the pinned copy on
9
+ * jsDelivr, its wasm read beside it), and the page is told whose licence
10
+ * applies. The types here cover the part of its surface this library uses.
11
+ */
12
+ /** The @mujoco/mujoco version the default URL pins. */
13
+ const MUJOCO_VERSION = "4.0.1";
14
+ /** Where MuJoCo loads from when no factory is given. */
15
+ const MUJOCO_URL = `https://cdn.jsdelivr.net/npm/@mujoco/mujoco@${MUJOCO_VERSION}/mujoco.js`;
16
+ /** The line a page shows the first time MuJoCo loads. */
17
+ const MUJOCO_LICENCE = "mujoco by google deepmind, under the apache license 2.0 (https://github.com/google-deepmind/mujoco). it loads at run time and is not part of this library.";
18
+ /** A model or runtime this library cannot open, with the reason in words a page can show. */
19
+ var HumanoidError = class extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "HumanoidError";
23
+ }
24
+ };
25
+ const loads = /* @__PURE__ */ new Map();
26
+ /** Loads MuJoCo once per factory or URL and resolves to the module. */
27
+ function loadMujoco(o = {}) {
28
+ const key = o.factory ?? o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js";
29
+ const have = loads.get(key);
30
+ if (have) return have;
31
+ const p = (async () => {
32
+ let factory = o.factory;
33
+ const url = o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js";
34
+ if (!factory) try {
35
+ factory = (await import(
36
+ /* @vite-ignore */
37
+ url
38
+ )).default;
39
+ } catch (e) {
40
+ throw new HumanoidError(`mujoco did not load from ${url}: ${e instanceof Error ? e.message : String(e)}. check the connection, or pass the factory from @mujoco/mujoco.`);
41
+ }
42
+ const opts = {};
43
+ const w = o.wasm;
44
+ if (w instanceof ArrayBuffer || ArrayBuffer.isView(w)) opts.wasmBinary = w;
45
+ else if (typeof w === "string") opts.locateFile = () => w;
46
+ else if (!o.factory) opts.locateFile = (path) => new URL(path, url).href;
47
+ const mj = await factory(opts);
48
+ o.onLicence?.(MUJOCO_LICENCE);
49
+ return mj;
50
+ })();
51
+ loads.set(key, p);
52
+ p.catch(() => loads.delete(key));
53
+ return p;
54
+ }
55
+ // src/files.ts
56
+ /**
57
+ * A robot as files: its MJCF and every file it names (included MJCF, meshes,
58
+ * textures, height fields, skins), from a URL or from files the person
59
+ * dropped. Paths are keyed the way MuJoCo looks them up in its virtual file
60
+ * system: an include by its own path, a mesh by meshdir (or assetdir) and
61
+ * its file, a texture by texturedir and its file. A file that does not
62
+ * arrive is listed in `missing`.
63
+ */
64
+ const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1], m[2]]));
65
+ const join = (dir, file) => (dir ? `${dir.replace(/\/+$/, "")}/${file}` : file).replace(/^\.\//, "");
66
+ /** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
67
+ function referencedFiles(xml, dirs = {}) {
68
+ const d = { ...dirs };
69
+ for (const m of xml.matchAll(/<compiler\b[^>]*>/g)) {
70
+ const a = attrs(m[0]);
71
+ if (a.meshdir !== void 0) d.meshdir = a.meshdir;
72
+ if (a.texturedir !== void 0) d.texturedir = a.texturedir;
73
+ if (a.assetdir !== void 0) d.assetdir = a.assetdir;
74
+ }
75
+ const includes = [...xml.matchAll(/<include\b[^>]*>/g)].map((m) => attrs(m[0]).file).filter((f) => !!f);
76
+ const files = [];
77
+ for (const m of xml.matchAll(/<(mesh|skin|hfield|texture)\b[^>]*>/g)) {
78
+ const f = attrs(m[0]).file;
79
+ if (!f) continue;
80
+ const dir = m[1] === "texture" ? d.texturedir ?? d.assetdir : d.meshdir ?? d.assetdir;
81
+ files.push(join(dir, f));
82
+ }
83
+ return {
84
+ includes,
85
+ files: [...new Set(files)]
86
+ };
87
+ }
88
+ /** Compiler directories set anywhere in a set of MJCF texts: an included file's compiler applies to the whole model. */
89
+ function dirsOf(xmls) {
90
+ const d = {};
91
+ for (const x of xmls) for (const m of x.matchAll(/<compiler\b[^>]*>/g)) {
92
+ const a = attrs(m[0]);
93
+ if (a.meshdir !== void 0) d.meshdir = a.meshdir;
94
+ if (a.texturedir !== void 0) d.texturedir = a.texturedir;
95
+ if (a.assetdir !== void 0) d.assetdir = a.assetdir;
96
+ }
97
+ return d;
98
+ }
99
+ /** Reads an MJCF and everything it names through `read`, includes first; a file `read` cannot give is listed as missing. */
100
+ async function gather(main, read, onFile) {
101
+ const dec = new TextDecoder();
102
+ const first = await read(main);
103
+ if (!first) throw new HumanoidError(`the model file ${main} did not load.`);
104
+ const xml = dec.decode(first);
105
+ const assets = /* @__PURE__ */ new Map();
106
+ const missing = [];
107
+ const texts = [xml];
108
+ const queue = [...referencedFiles(xml).includes];
109
+ while (queue.length) {
110
+ const inc = queue.shift();
111
+ if (assets.has(inc)) continue;
112
+ const b = await read(inc);
113
+ if (!b) {
114
+ missing.push(inc);
115
+ continue;
116
+ }
117
+ assets.set(inc, b);
118
+ const t = dec.decode(b);
119
+ texts.push(t);
120
+ queue.push(...referencedFiles(t).includes);
121
+ }
122
+ const dirs = dirsOf(texts);
123
+ const wanted = [...new Set(texts.flatMap((t) => referencedFiles(t, dirs).files))].filter((f) => !assets.has(f));
124
+ let done = 0;
125
+ await Promise.all(wanted.map(async (f) => {
126
+ const b = await read(f);
127
+ if (b) assets.set(f, b);
128
+ else missing.push(f);
129
+ onFile?.(f, ++done, wanted.length);
130
+ }));
131
+ return {
132
+ xml,
133
+ assets,
134
+ missing
135
+ };
136
+ }
137
+ /**
138
+ * A robot from the URL of its main MJCF; every file it names is fetched beside it, or for files that
139
+ * are not MJCF beside `assetBase` when given (a repository whose meshes live on another host, such as
140
+ * Git LFS).
141
+ */
142
+ function fetchModel(url, o = {}) {
143
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
144
+ const here = globalThis.location?.href;
145
+ const base = new URL(url, here);
146
+ const assets = o.assetBase ? new URL(o.assetBase.endsWith("/") ? o.assetBase : `${o.assetBase}/`, here) : base;
147
+ const read = async (path) => {
148
+ try {
149
+ const r = await f(path === url ? base.href : new URL(path, /\.xml$/i.test(path) ? base : assets).href);
150
+ return r.ok ? new Uint8Array(await r.arrayBuffer()) : null;
151
+ } catch {
152
+ return null;
153
+ }
154
+ };
155
+ return gather(url, read, o.onFile);
156
+ }
157
+ /** A robot from dropped files (a folder keeps its paths): the main MJCF is the one with a worldbody that no other file includes. */
158
+ async function filesFrom(list) {
159
+ const files = /* @__PURE__ */ new Map();
160
+ for (const f of list) files.set((f.webkitRelativePath || f.name).replace(/\\/g, "/"), f);
161
+ const xmls = [...files.keys()].filter((p) => /\.xml$/i.test(p));
162
+ const texts = /* @__PURE__ */ new Map();
163
+ for (const p of xmls) texts.set(p, await files.get(p).text());
164
+ const included = new Set([...texts].flatMap(([p, t]) => referencedFiles(t).includes.map((i) => join(p.split("/").slice(0, -1).join("/"), i))));
165
+ const main = xmls.filter((p) => !included.has(p) && /<worldbody/.test(texts.get(p))).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length)[0];
166
+ if (!main) throw new HumanoidError("no mjcf here: drop the robot's folder, with an .xml that has a worldbody.");
167
+ const root = main.split("/").slice(0, -1).join("/");
168
+ const read = async (path) => {
169
+ const f = files.get(path === main ? main : join(root, path));
170
+ return f ? new Uint8Array(await f.arrayBuffer()) : null;
171
+ };
172
+ return gather(main, read);
173
+ }
174
+ // src/sim.ts
175
+ const FREE = 0;
176
+ const isArrayLike = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
177
+ /** A robot running in MuJoCo. */
178
+ var Humanoid = class Humanoid {
179
+ mj;
180
+ model;
181
+ data;
182
+ /** Joint names in model order (a free joint included). */
183
+ joints;
184
+ /** The joint each actuator drives, in actuator order: `targets[i]` is that joint's target for a position actuator. */
185
+ actuated;
186
+ bodies;
187
+ keyframes;
188
+ /** Files the model named that did not arrive. */
189
+ missing;
190
+ /** The model's timestep, seconds. */
191
+ timestep;
192
+ carry = 0;
193
+ gone = false;
194
+ ramp = null;
195
+ constructor(mj, model, missing) {
196
+ this.mj = mj;
197
+ this.model = model;
198
+ this.data = new mj.MjData(model);
199
+ const name = (type, i) => mj.mj_id2name(model, mj.mjtObj[type].value, i) || `${type.replace("mjOBJ_", "").toLowerCase()} ${i}`;
200
+ this.joints = Array.from({ length: model.njnt }, (_, i) => name("mjOBJ_JOINT", i));
201
+ this.bodies = Array.from({ length: model.nbody }, (_, i) => name("mjOBJ_BODY", i));
202
+ this.keyframes = Array.from({ length: model.nkey }, (_, i) => name("mjOBJ_KEY", i));
203
+ this.actuated = Array.from({ length: model.nu }, (_, i) => this.joints[model.actuator_trnid[i * 2]] ?? `actuator ${i}`);
204
+ this.timestep = model.opt.timestep;
205
+ this.missing = missing;
206
+ mj.mj_forward(model, this.data);
207
+ }
208
+ /** Compiles a robot from its files; a model MuJoCo cannot compile is an error with MuJoCo's reason. */
209
+ static open(mj, files) {
210
+ const vfs = new mj.MjVFS();
211
+ try {
212
+ for (const [path, bytes] of files.assets) vfs.addBuffer(path, bytes);
213
+ let model;
214
+ try {
215
+ model = mj.MjModel.from_xml_string(files.xml, vfs);
216
+ } catch (e) {
217
+ throw new HumanoidError(`mujoco could not compile the model: ${e instanceof Error ? e.message : String(e)}${files.missing?.length ? `. files it names that did not arrive: ${files.missing.slice(0, 3).join(", ")}` : ""}`);
218
+ }
219
+ return new Humanoid(mj, model, files.missing ?? []);
220
+ } finally {
221
+ vfs.delete();
222
+ }
223
+ }
224
+ /** Seconds simulated so far. */
225
+ get time() {
226
+ return this.data.time;
227
+ }
228
+ /** The actuators' controls: targets in radians for position actuators, a view on the model's data. */
229
+ get targets() {
230
+ return this.data.ctrl;
231
+ }
232
+ /** Back to a keyframe by name or index (its controls too), or to the model's rest state. */
233
+ reset(key) {
234
+ const k = typeof key === "string" ? this.keyframes.indexOf(key) : key;
235
+ if (typeof key === "string" && k < 0) throw new HumanoidError(`the model has no keyframe ${key}; it has ${this.keyframes.join(", ") || "none"}.`);
236
+ if (k === void 0) this.mj.mj_resetData(this.model, this.data);
237
+ else this.mj.mj_resetDataKeyframe(this.model, this.data, k);
238
+ this.mj.mj_forward(this.model, this.data);
239
+ this.carry = 0;
240
+ this.ramp = null;
241
+ }
242
+ /**
243
+ * Eases the targets named (by actuated joint, or an array in actuator order) from where they are to
244
+ * the new values over `seconds` of simulated time, on a smoothstep; others keep theirs. A sudden
245
+ * jump in targets can topple a robot that a ramp of half a second leaves standing (measured on the G1).
246
+ */
247
+ moveTo(targets, seconds = .5) {
248
+ const from = Float64Array.from(this.data.ctrl);
249
+ const to = Float64Array.from(from);
250
+ if (isArrayLike(targets)) for (let i = 0; i < Math.min(to.length, targets.length); i++) to[i] = targets[i];
251
+ else for (const [name, v] of Object.entries(targets)) {
252
+ const i = this.actuated.indexOf(name);
253
+ if (i < 0) throw new HumanoidError(`no actuator drives ${name}.`);
254
+ to[i] = v;
255
+ }
256
+ this.ramp = {
257
+ from,
258
+ to,
259
+ t0: this.data.time,
260
+ dur: Math.max(0, seconds)
261
+ };
262
+ if (seconds <= 0) this.applyRamp();
263
+ }
264
+ /** True while a {@link moveTo} is still easing. */
265
+ get moving() {
266
+ return this.ramp !== null;
267
+ }
268
+ applyRamp() {
269
+ const r = this.ramp;
270
+ if (!r) return;
271
+ const k = r.dur > 0 ? Math.min(1, (this.data.time - r.t0) / r.dur) : 1;
272
+ const e = k * k * (3 - 2 * k);
273
+ for (let i = 0; i < r.to.length; i++) this.data.ctrl[i] = r.from[i] + (r.to[i] - r.from[i]) * e;
274
+ if (k >= 1) this.ramp = null;
275
+ }
276
+ /** Each actuated joint's target set to where the joint is now: the body holds its pose. */
277
+ hold() {
278
+ const { model, data } = this;
279
+ for (let i = 0; i < model.nu; i++) {
280
+ const j = model.actuator_trnid[i * 2];
281
+ data.ctrl[i] = data.qpos[model.jnt_qposadr[j]];
282
+ }
283
+ }
284
+ /** Advances by `seconds` in steps of the model's timestep, carrying the remainder; at most `max` seconds a call (default 0.1). Returns the steps run. */
285
+ step(seconds, max = .1) {
286
+ if (this.gone) return 0;
287
+ this.carry = Math.min(this.carry + Math.max(0, seconds), max);
288
+ const n = Math.floor(this.carry / this.timestep + 1e-6);
289
+ for (let i = 0; i < n; i++) {
290
+ this.applyRamp();
291
+ this.mj.mj_step(this.model, this.data);
292
+ }
293
+ this.carry = Math.max(0, this.carry - n * this.timestep);
294
+ return n;
295
+ }
296
+ /** Runs `n` timesteps, calling `control` before each so a controller can set the actuators every step (a PD loop on motor actuators). */
297
+ run(n, control) {
298
+ if (this.gone) return;
299
+ for (let i = 0; i < n; i++) {
300
+ control?.(this);
301
+ this.applyRamp();
302
+ this.mj.mj_step(this.model, this.data);
303
+ }
304
+ }
305
+ /** Where a hinge or slide joint keeps its position in qpos and its velocity in qvel, or null for a name the model lacks. */
306
+ address(joint) {
307
+ const j = this.joints.indexOf(joint);
308
+ return j < 0 ? null : {
309
+ qpos: this.model.jnt_qposadr[j],
310
+ qvel: this.model.jnt_dofadr[j]
311
+ };
312
+ }
313
+ /** A body's world pose, or null for a name the model lacks. */
314
+ pose(body) {
315
+ const i = typeof body === "number" ? body : this.bodies.indexOf(body);
316
+ if (i < 0 || i >= this.model.nbody) return null;
317
+ const p = this.data.xpos, q = this.data.xquat;
318
+ return {
319
+ pos: [
320
+ p[i * 3],
321
+ p[i * 3 + 1],
322
+ p[i * 3 + 2]
323
+ ],
324
+ quat: [
325
+ q[i * 4],
326
+ q[i * 4 + 1],
327
+ q[i * 4 + 2],
328
+ q[i * 4 + 3]
329
+ ]
330
+ };
331
+ }
332
+ /** The body carried by the first free joint (a robot's pelvis), or null when the robot is fixed to the world. */
333
+ get rootBody() {
334
+ for (let j = 0; j < this.model.njnt; j++) if (this.model.jnt_type[j] === FREE) return this.bodies[this.model.jnt_bodyid[j]] ?? null;
335
+ return null;
336
+ }
337
+ /** A shove: adds a velocity in m/s, in MuJoCo's world frame, to the body on the first free joint. False when there is none. */
338
+ push(vx, vy, vz = 0) {
339
+ for (let j = 0; j < this.model.njnt; j++) {
340
+ if (this.model.jnt_type[j] !== FREE) continue;
341
+ const d = this.model.jnt_dofadr[j];
342
+ this.data.qvel[d] += vx;
343
+ this.data.qvel[d + 1] += vy;
344
+ this.data.qvel[d + 2] += vz;
345
+ return true;
346
+ }
347
+ return false;
348
+ }
349
+ /** A hinge or slide joint's position and velocity, or null for a name the model lacks. */
350
+ joint(name) {
351
+ const j = this.joints.indexOf(name);
352
+ if (j < 0) return null;
353
+ return {
354
+ q: this.data.qpos[this.model.jnt_qposadr[j]],
355
+ dq: this.data.qvel[this.model.jnt_dofadr[j]]
356
+ };
357
+ }
358
+ /** Frees the model and its data. */
359
+ dispose() {
360
+ if (this.gone) return;
361
+ this.gone = true;
362
+ this.data.delete();
363
+ this.model.delete();
364
+ }
365
+ };
366
+ // src/g1.ts
367
+ /**
368
+ * The Unitree G1 (29 joints) from MuJoCo Menagerie, pinned to one commit:
369
+ * its scene, model and 35 meshes load at run time from GitHub and are not
370
+ * part of this library. The model holds its pose with position actuators;
371
+ * its keyframe "stand" is the robot upright with its arms down.
372
+ */
373
+ /** The G1 from MuJoCo Menagerie, by URL, with its licence and download size. */
374
+ const G1 = {
375
+ name: "unitree g1, 29 joints",
376
+ /** The scene (floor and light) that includes the robot, at menagerie commit 98a70c5. */
377
+ url: "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/98a70c569c4c1b6da467a20012f766ee1f8dc521/unitree_g1/scene.xml",
378
+ licence: "unitree g1 model and meshes from mujoco menagerie, bsd-3-clause, copyright unitree robotics. they load at run time and are not part of this library.",
379
+ /** The meshes the model uses, in bytes (vendor: GitHub's sizes). */
380
+ bytes: 19666440,
381
+ keyframe: "stand",
382
+ /** The 29 actuated joints in the model's order: legs, waist, arms. */
383
+ joints: [
384
+ "left_hip_pitch_joint",
385
+ "left_hip_roll_joint",
386
+ "left_hip_yaw_joint",
387
+ "left_knee_joint",
388
+ "left_ankle_pitch_joint",
389
+ "left_ankle_roll_joint",
390
+ "right_hip_pitch_joint",
391
+ "right_hip_roll_joint",
392
+ "right_hip_yaw_joint",
393
+ "right_knee_joint",
394
+ "right_ankle_pitch_joint",
395
+ "right_ankle_roll_joint",
396
+ "waist_yaw_joint",
397
+ "waist_roll_joint",
398
+ "waist_pitch_joint",
399
+ "left_shoulder_pitch_joint",
400
+ "left_shoulder_roll_joint",
401
+ "left_shoulder_yaw_joint",
402
+ "left_elbow_joint",
403
+ "left_wrist_roll_joint",
404
+ "left_wrist_pitch_joint",
405
+ "left_wrist_yaw_joint",
406
+ "right_shoulder_pitch_joint",
407
+ "right_shoulder_roll_joint",
408
+ "right_shoulder_yaw_joint",
409
+ "right_elbow_joint",
410
+ "right_wrist_roll_joint",
411
+ "right_wrist_pitch_joint",
412
+ "right_wrist_yaw_joint"
413
+ ]
414
+ };
415
+ // src/three.ts
416
+ /**
417
+ * The robot in three.js: one mesh per visible geom (spheres, capsules,
418
+ * cylinders, boxes, ellipsoids, planes and MuJoCo's own meshes, each mesh's
419
+ * geometry shared), coloured from the geom's material or rgba, moved each
420
+ * frame from the geoms' world poses. MuJoCo is z up; the view's root turns
421
+ * that to y up and the robot's forward axis to +Z, the family's humanoid
422
+ * space. Collision geoms (group 3 and up) stay hidden unless asked for.
423
+ */
424
+ const PLANE = 0;
425
+ const SPHERE = 2;
426
+ const CAPSULE = 3;
427
+ const ELLIPSOID = 4;
428
+ const CYLINDER = 5;
429
+ const BOX = 6;
430
+ const MESH = 7;
431
+ const TURN = {
432
+ x: -Math.PI / 2,
433
+ "-x": Math.PI / 2,
434
+ y: Math.PI,
435
+ "-y": 0
436
+ };
437
+ /** A three.js group that follows a {@link Humanoid}; add `root` to a scene and call `update` after each step. */
438
+ var HumanoidView = class {
439
+ sim;
440
+ root = new three.Group();
441
+ inner = new three.Group();
442
+ meshes = [];
443
+ shared = /* @__PURE__ */ new Map();
444
+ owned = [];
445
+ constructor(sim, o = {}) {
446
+ this.sim = sim;
447
+ const m = sim.model;
448
+ const groups = new Set(o.groups ?? [
449
+ 0,
450
+ 1,
451
+ 2
452
+ ]);
453
+ this.root.name = "humanoid";
454
+ this.root.rotation.y = TURN[o.forward ?? "x"];
455
+ this.inner.rotation.x = -Math.PI / 2;
456
+ this.root.add(this.inner);
457
+ for (let g = 0; g < m.ngeom; g++) {
458
+ const type = m.geom_type[g];
459
+ if (!groups.has(m.geom_group[g]) || type === PLANE && !o.floor) continue;
460
+ const geo = this.geometry(g, type);
461
+ if (!geo) continue;
462
+ const mat = m.geom_matid?.[g] ?? -1;
463
+ const rgba = mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : m.geom_rgba.subarray(g * 4, g * 4 + 4);
464
+ const material = new three.MeshStandardMaterial({
465
+ roughness: .6,
466
+ metalness: .1,
467
+ transparent: rgba[3] < 1,
468
+ opacity: rgba[3]
469
+ });
470
+ material.color.setRGB(rgba[0], rgba[1], rgba[2]);
471
+ this.owned.push(material);
472
+ const mesh = new three.Mesh(geo, material);
473
+ mesh.matrixAutoUpdate = false;
474
+ mesh.castShadow = mesh.receiveShadow = type !== PLANE;
475
+ this.inner.add(mesh);
476
+ this.meshes.push({
477
+ mesh,
478
+ geom: g
479
+ });
480
+ }
481
+ this.update();
482
+ }
483
+ geometry(g, type) {
484
+ const m = this.sim.model;
485
+ const s = m.geom_size.subarray(g * 3, g * 3 + 3);
486
+ const own = (geo) => (this.owned.push(geo), geo);
487
+ switch (type) {
488
+ case SPHERE: return own(new three.SphereGeometry(s[0], 20, 14));
489
+ case ELLIPSOID: return own(new three.SphereGeometry(1, 20, 14).scale(s[0], s[1], s[2]));
490
+ case CAPSULE: return own(new three.CapsuleGeometry(s[0], 2 * s[1], 6, 16).rotateX(Math.PI / 2));
491
+ case CYLINDER: return own(new three.CylinderGeometry(s[0], s[0], 2 * s[1], 20).rotateX(Math.PI / 2));
492
+ case BOX: return own(new three.BoxGeometry(2 * s[0], 2 * s[1], 2 * s[2]));
493
+ case PLANE: return own(new three.PlaneGeometry(s[0] ? 2 * s[0] : 40, s[1] ? 2 * s[1] : 40));
494
+ case MESH: {
495
+ const id = m.geom_dataid[g];
496
+ if (id < 0) return null;
497
+ const have = this.shared.get(id);
498
+ if (have) return have;
499
+ const v = m.mesh_vertadr[id], nv = m.mesh_vertnum[id], f = m.mesh_faceadr[id], nf = m.mesh_facenum[id];
500
+ const geo = new three.BufferGeometry();
501
+ geo.setAttribute("position", new three.BufferAttribute(m.mesh_vert.slice(v * 3, (v + nv) * 3), 3));
502
+ geo.setIndex(new three.BufferAttribute(Uint32Array.from(m.mesh_face.subarray(f * 3, (f + nf) * 3)), 1));
503
+ geo.computeVertexNormals();
504
+ this.shared.set(id, geo);
505
+ return own(geo);
506
+ }
507
+ default: return null;
508
+ }
509
+ }
510
+ /** Moves every mesh to its geom's pose after the last step. */
511
+ update() {
512
+ const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
513
+ for (const { mesh, geom: g } of this.meshes) {
514
+ const a = g * 9, b = g * 3;
515
+ mesh.matrix.set(r[a], r[a + 1], r[a + 2], p[b], r[a + 3], r[a + 4], r[a + 5], p[b + 1], r[a + 6], r[a + 7], r[a + 8], p[b + 2], 0, 0, 0, 1);
516
+ mesh.matrixWorldNeedsUpdate = true;
517
+ }
518
+ }
519
+ /** Meshes drawn. */
520
+ get count() {
521
+ return this.meshes.length;
522
+ }
523
+ /** Removes the group and frees its geometries and materials. */
524
+ dispose() {
525
+ this.root.removeFromParent();
526
+ for (const o of this.owned) o.dispose();
527
+ this.meshes = [];
528
+ }
529
+ };
530
+ // src/sonic.ts
531
+ /**
532
+ * GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
533
+ * page: an encoder turns a reference motion into a 64 number token, a decoder
534
+ * turns the token and ten ticks of the robot's state into 29 joint actions,
535
+ * 50 times a second; a PD loop here turns actions into motor torques at every
536
+ * MuJoCo step. Written for this library from the published deployment
537
+ * description and parameters (observation names, sizes and order, joint
538
+ * orders, gains from motor armature, action scale, default angles). The
539
+ * details the description leaves open were settled by trial on the deploy
540
+ * model: joint positions relative to the default angles, the reference in
541
+ * absolute angles, histories oldest first, a rotation's first two columns
542
+ * row by row, and the anchor as the base's tilt against an upright reference
543
+ * that follows the robot's heading (measured: only that combination stands).
544
+ * The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
545
+ * run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
546
+ */
547
+ /** The policy files and their terms. */
548
+ const SONIC = {
549
+ name: "gear-sonic, the default g1 controller",
550
+ /** Hugging Face revision the URLs pin. */
551
+ revision: "6733128a3d8a523b1418b06bca3cdf61c8b0987f",
552
+ encoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_encoder.onnx",
553
+ decoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_decoder.onnx",
554
+ /** Encoder and decoder together, in bytes (vendor: Hugging Face's sizes). */
555
+ bytes: 91001201,
556
+ hz: 50,
557
+ licence: "gear-sonic weights by nvidia. licensed by nvidia corporation under the nvidia open model license (https://huggingface.co/nvidia/GEAR-SONIC/blob/main/LICENSE). they load at run time and are not part of this library."
558
+ };
559
+ /** The G1 model the policy was deployed on: motor actuators, its own joint damping, armature and friction. */
560
+ const G1_SONIC = {
561
+ name: "unitree g1, 29 joints, the gear-sonic deploy model",
562
+ /** The scene, at GR00T-WholeBodyControl commit 2a5e6a1; it includes the robot file beside it. */
563
+ url: "https://raw.githubusercontent.com/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/scene_29dof.xml",
564
+ /** The meshes are in Git LFS; pass this as `assetBase` to `fetchModel`. */
565
+ assetBase: "https://media.githubusercontent.com/media/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/",
566
+ licence: "g1 deploy model from nvidia's gr00t-wholebodycontrol (apache-2.0), meshes copyright unitree robotics (bsd-3-clause). they load at run time and are not part of this library."
567
+ };
568
+ const MOTORS = {
569
+ m22: [.025101925, 139],
570
+ m14: [.01017752, 88],
571
+ m5020: [.003609725, 25],
572
+ m4010: [.00425, 5]
573
+ };
574
+ const MOTOR_OF = [
575
+ "m22",
576
+ "m22",
577
+ "m14",
578
+ "m22",
579
+ "m5020",
580
+ "m5020",
581
+ "m22",
582
+ "m22",
583
+ "m14",
584
+ "m22",
585
+ "m5020",
586
+ "m5020",
587
+ "m14",
588
+ "m5020",
589
+ "m5020",
590
+ "m5020",
591
+ "m5020",
592
+ "m5020",
593
+ "m5020",
594
+ "m5020",
595
+ "m4010",
596
+ "m4010",
597
+ "m5020",
598
+ "m5020",
599
+ "m5020",
600
+ "m5020",
601
+ "m5020",
602
+ "m4010",
603
+ "m4010"
604
+ ];
605
+ const DOUBLED = /* @__PURE__ */ new Set([
606
+ 4,
607
+ 5,
608
+ 10,
609
+ 11,
610
+ 13,
611
+ 14
612
+ ]);
613
+ const OMEGA = 20 * Math.PI;
614
+ /** The deployment's joint tables, each in the model's joint order (`G1.joints`). */
615
+ const SONIC_JOINTS = {
616
+ /** Standing angles, radians. */
617
+ defaults: [
618
+ -.312,
619
+ 0,
620
+ 0,
621
+ .669,
622
+ -.363,
623
+ 0,
624
+ -.312,
625
+ 0,
626
+ 0,
627
+ .669,
628
+ -.363,
629
+ 0,
630
+ 0,
631
+ 0,
632
+ 0,
633
+ .2,
634
+ .2,
635
+ 0,
636
+ .6,
637
+ 0,
638
+ 0,
639
+ 0,
640
+ .2,
641
+ -.2,
642
+ 0,
643
+ .6,
644
+ 0,
645
+ 0,
646
+ 0
647
+ ],
648
+ /** Position gain, N m per rad: armature times (10 Hz in rad/s) squared (computed). */
649
+ kp: MOTOR_OF.map((m, j) => MOTORS[m][0] * OMEGA * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
650
+ /** Velocity gain, N m s per rad: 2 times damping ratio 2 times armature times omega (computed). */
651
+ kd: MOTOR_OF.map((m, j) => 4 * MOTORS[m][0] * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
652
+ /** Torque limit, N m. */
653
+ effort: MOTOR_OF.map((m) => MOTORS[m][1]),
654
+ /** Radians per unit of action: 0.25 times effort over stiffness (computed). */
655
+ scale: MOTOR_OF.map((m) => .25 * MOTORS[m][1] / (MOTORS[m][0] * OMEGA * OMEGA)),
656
+ /** The policy's (IsaacLab) index of each joint. */
657
+ policyIndex: [
658
+ 0,
659
+ 3,
660
+ 6,
661
+ 9,
662
+ 13,
663
+ 17,
664
+ 1,
665
+ 4,
666
+ 7,
667
+ 10,
668
+ 14,
669
+ 18,
670
+ 2,
671
+ 5,
672
+ 8,
673
+ 11,
674
+ 15,
675
+ 19,
676
+ 21,
677
+ 23,
678
+ 25,
679
+ 27,
680
+ 12,
681
+ 16,
682
+ 20,
683
+ 22,
684
+ 24,
685
+ 26,
686
+ 28
687
+ ]
688
+ };
689
+ /** A model order array (29) in the policy's order. */
690
+ function toPolicyOrder(v) {
691
+ const out = new Array(29).fill(0);
692
+ for (let j = 0; j < 29; j++) out[SONIC_JOINTS.policyIndex[j]] = v[j];
693
+ return out;
694
+ }
695
+ /** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
696
+ function intoBody(q, v) {
697
+ const [w, x, y, z] = q;
698
+ const r = [
699
+ [
700
+ 1 - 2 * (y * y + z * z),
701
+ 2 * (x * y - w * z),
702
+ 2 * (x * z + w * y)
703
+ ],
704
+ [
705
+ 2 * (x * y + w * z),
706
+ 1 - 2 * (x * x + z * z),
707
+ 2 * (y * z - w * x)
708
+ ],
709
+ [
710
+ 2 * (x * z - w * y),
711
+ 2 * (y * z + w * x),
712
+ 1 - 2 * (x * x + y * y)
713
+ ]
714
+ ];
715
+ return [
716
+ 0,
717
+ 1,
718
+ 2
719
+ ].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
720
+ }
721
+ /**
722
+ * The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
723
+ * the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
724
+ * reference, read row by row.
725
+ */
726
+ function anchorSix(base) {
727
+ const [w, x, y, z] = base;
728
+ const n = Math.max(Math.hypot(w, z), 1e-9);
729
+ const hw = w / n, hz = z / n;
730
+ const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
731
+ return [
732
+ 1 - 2 * (ry * ry + rz * rz),
733
+ 2 * (rx * ry - rw * rz),
734
+ 2 * (rx * ry + rw * rz),
735
+ 1 - 2 * (rx * rx + rz * rz),
736
+ 2 * (rx * rz - rw * ry),
737
+ 2 * (ry * rz + rw * rx)
738
+ ];
739
+ }
740
+ /**
741
+ * The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
742
+ * angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
743
+ * stay zero. `ref` holds 10 frames, or 1 repeated.
744
+ */
745
+ function encoderInput(ref, anchor) {
746
+ const e = /* @__PURE__ */ new Float32Array(1762);
747
+ const frame = (f) => ref[Math.min(f, ref.length - 1)];
748
+ let o = 4;
749
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).q[k];
750
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).dq?.[k] ?? 0;
751
+ o += 17;
752
+ for (let f = 0; f < 10; f++) for (let k = 0; k < 6; k++) e[o++] = anchor[k];
753
+ return e;
754
+ }
755
+ /** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
756
+ var SonicHistory = class {
757
+ av = [];
758
+ q = [];
759
+ dq = [];
760
+ act = [];
761
+ g = [];
762
+ /** Fills all ten ticks with one state and zero actions. */
763
+ prime(s) {
764
+ for (const k of [
765
+ "av",
766
+ "q",
767
+ "dq",
768
+ "act",
769
+ "g"
770
+ ]) this[k] = [];
771
+ for (let i = 0; i < 10; i++) this.add(s, new Array(29).fill(0));
772
+ }
773
+ /** Adds a tick's state, with the actions the last tick produced. */
774
+ add(s, lastAction) {
775
+ const keep = (a, v) => {
776
+ a.push(v);
777
+ if (a.length > 10) a.shift();
778
+ };
779
+ keep(this.av, s.angularVelocity);
780
+ keep(this.q, s.q);
781
+ keep(this.dq, s.dq);
782
+ keep(this.act, Array.from(lastAction));
783
+ keep(this.g, s.gravity);
784
+ }
785
+ /** The decoder's 994 inputs: the token, then each history oldest first. */
786
+ decoderInput(token) {
787
+ const d = /* @__PURE__ */ new Float32Array(994);
788
+ let p = 0;
789
+ for (let k = 0; k < 64; k++) d[p++] = token[k];
790
+ for (const h of [
791
+ this.av,
792
+ this.q,
793
+ this.dq,
794
+ this.act,
795
+ this.g
796
+ ]) for (const tick of h) for (const v of tick) d[p++] = v;
797
+ return d;
798
+ }
799
+ };
800
+ /** Where onnxruntime-web loads from when no module is given. */
801
+ const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
802
+ async function bytesOf(src, f, progress) {
803
+ if (typeof src !== "string") return src instanceof Uint8Array ? src : new Uint8Array(src);
804
+ const r = await f(src);
805
+ if (!r.ok || !r.body) throw new HumanoidError(`the policy file ${src} answered ${r.status}.`);
806
+ const reader = r.body.getReader();
807
+ const parts = [];
808
+ let n = 0;
809
+ for (;;) {
810
+ const { done, value } = await reader.read();
811
+ if (done) break;
812
+ parts.push(value);
813
+ n += value.byteLength;
814
+ progress(value.byteLength);
815
+ }
816
+ const out = new Uint8Array(n);
817
+ let o = 0;
818
+ for (const p of parts) out.set(p, o), o += p.byteLength;
819
+ return out;
820
+ }
821
+ /** The loaded policy: an encoder and a decoder session. Drive a G1 with {@link Sonic.drive}. */
822
+ var Sonic = class Sonic {
823
+ ort;
824
+ encoder;
825
+ decoder;
826
+ constructor(ort, encoder, decoder) {
827
+ this.ort = ort;
828
+ this.encoder = encoder;
829
+ this.decoder = decoder;
830
+ }
831
+ /** Loads onnxruntime-web and both policy files. */
832
+ static async load(o = {}) {
833
+ let ort = o.ort;
834
+ if (!ort) {
835
+ const url = o.ortUrl ?? "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
836
+ try {
837
+ ort = await import(
838
+ /* @vite-ignore */
839
+ url
840
+ );
841
+ } catch (e) {
842
+ throw new HumanoidError(`onnxruntime-web did not load from ${url}: ${e instanceof Error ? e.message : String(e)}.`);
843
+ }
844
+ ort.env.wasm.wasmPaths = new URL("./", url).href;
845
+ }
846
+ ort.env.wasm.numThreads = 1;
847
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
848
+ let loaded = 0;
849
+ const tick = (n) => o.onProgress?.(loaded += n, SONIC.bytes);
850
+ const [eb, db] = await Promise.all([bytesOf(o.encoder ?? SONIC.encoder, f, tick), bytesOf(o.decoder ?? SONIC.decoder, f, tick)]);
851
+ const [encoder, decoder] = await Promise.all([ort.InferenceSession.create(eb), ort.InferenceSession.create(db)]);
852
+ o.onLicence?.(SONIC.licence);
853
+ return new Sonic(ort, encoder, decoder);
854
+ }
855
+ /** The decoder's actions (policy order) for one tick. */
856
+ async act(encoderIn, history) {
857
+ const T = this.ort.Tensor;
858
+ const token = (await this.encoder.run({ obs_dict: new T("float32", encoderIn, [1, 1762]) })).encoded_tokens.data;
859
+ return (await this.decoder.run({ obs_dict: new T("float32", history.decoderInput(token), [1, 994]) })).action.data;
860
+ }
861
+ /** A driver for a G1 whose 29 joints are on motor actuators (the {@link G1_SONIC} model). */
862
+ drive(sim) {
863
+ return new SonicDriver(this, sim);
864
+ }
865
+ async dispose() {
866
+ await Promise.all([this.encoder.release?.(), this.decoder.release?.()]);
867
+ }
868
+ };
869
+ /** Runs the policy on one robot: 50 ticks a second, the PD loop at every timestep between. */
870
+ var SonicDriver = class {
871
+ sonic;
872
+ sim;
873
+ /** The reference pose the policy tracks, absolute angles in the model's joint order. Default the standing angles. */
874
+ reference = SONIC_JOINTS.defaults.slice();
875
+ /** Milliseconds the last tick's inference took (measured). */
876
+ inferenceMs = 0;
877
+ adr;
878
+ act;
879
+ history = new SonicHistory();
880
+ targets = SONIC_JOINTS.defaults.slice();
881
+ last = /* @__PURE__ */ new Float32Array(29);
882
+ carry = 0;
883
+ busy = false;
884
+ perTick;
885
+ constructor(sonic, sim) {
886
+ this.sonic = sonic;
887
+ this.sim = sim;
888
+ this.adr = G1.joints.map((j) => {
889
+ const a = sim.address(j);
890
+ if (!a) throw new HumanoidError(`the robot has no joint ${j}; the policy drives the unitree g1.`);
891
+ return a;
892
+ });
893
+ this.act = G1.joints.map((j) => {
894
+ const i = sim.actuated.indexOf(j);
895
+ if (i < 0) throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
896
+ return i;
897
+ });
898
+ this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
899
+ this.reset();
900
+ }
901
+ /** The robot back at the standing angles, upright at the origin, and the history primed. */
902
+ reset() {
903
+ const { sim } = this;
904
+ sim.reset();
905
+ const d = sim.data;
906
+ d.qpos[2] = .79;
907
+ for (let j = 0; j < 29; j++) d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
908
+ this.targets = SONIC_JOINTS.defaults.slice();
909
+ this.last.fill(0);
910
+ this.carry = 0;
911
+ this.history.prime(this.state());
912
+ }
913
+ /** The robot's state this tick, in the policy's order. */
914
+ state() {
915
+ const d = this.sim.data;
916
+ const quat = [
917
+ d.qpos[3],
918
+ d.qpos[4],
919
+ d.qpos[5],
920
+ d.qpos[6]
921
+ ];
922
+ return {
923
+ angularVelocity: [
924
+ d.qvel[3],
925
+ d.qvel[4],
926
+ d.qvel[5]
927
+ ],
928
+ q: toPolicyOrder(this.adr.map((a, j) => d.qpos[a.qpos] - SONIC_JOINTS.defaults[j])),
929
+ dq: toPolicyOrder(this.adr.map((a) => d.qvel[a.qvel])),
930
+ gravity: intoBody(quat, [
931
+ 0,
932
+ 0,
933
+ -1
934
+ ])
935
+ };
936
+ }
937
+ /** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
938
+ async tick() {
939
+ const d = this.sim.data;
940
+ const t0 = performance.now();
941
+ this.history.add(this.state(), this.last);
942
+ const anchor = anchorSix([
943
+ d.qpos[3],
944
+ d.qpos[4],
945
+ d.qpos[5],
946
+ d.qpos[6]
947
+ ]);
948
+ const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
949
+ this.inferenceMs = performance.now() - t0;
950
+ this.last = Float32Array.from(a);
951
+ const pi = SONIC_JOINTS.policyIndex;
952
+ for (let j = 0; j < 29; j++) this.targets[j] = SONIC_JOINTS.defaults[j] + a[pi[j]] * SONIC_JOINTS.scale[j];
953
+ const { kp, kd, effort } = SONIC_JOINTS;
954
+ this.sim.run(this.perTick, () => {
955
+ for (let j = 0; j < 29; j++) {
956
+ const tau = kp[j] * (this.targets[j] - d.qpos[this.adr[j].qpos]) - kd[j] * d.qvel[this.adr[j].qvel];
957
+ d.ctrl[this.act[j]] = Math.max(-effort[j], Math.min(effort[j], tau));
958
+ }
959
+ });
960
+ }
961
+ /** Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s a call; a call while one runs does nothing. Returns the ticks run. */
962
+ async advance(seconds) {
963
+ if (this.busy) return 0;
964
+ this.busy = true;
965
+ try {
966
+ const per = 1 / SONIC.hz;
967
+ this.carry = Math.min(this.carry + Math.max(0, seconds), .1);
968
+ const n = Math.floor(this.carry / per + 1e-6);
969
+ for (let i = 0; i < n; i++) await this.tick();
970
+ this.carry = Math.max(0, this.carry - n * per);
971
+ return n;
972
+ } finally {
973
+ this.busy = false;
974
+ }
975
+ }
976
+ };
977
+ exports.G1 = G1;
978
+ exports.G1_SONIC = G1_SONIC;
979
+ exports.Humanoid = Humanoid;
980
+ exports.HumanoidError = HumanoidError;
981
+ exports.HumanoidView = HumanoidView;
982
+ exports.MUJOCO_LICENCE = MUJOCO_LICENCE;
983
+ exports.MUJOCO_URL = MUJOCO_URL;
984
+ exports.MUJOCO_VERSION = MUJOCO_VERSION;
985
+ exports.ORT_URL = ORT_URL;
986
+ exports.SONIC = SONIC;
987
+ exports.SONIC_JOINTS = SONIC_JOINTS;
988
+ exports.Sonic = Sonic;
989
+ exports.SonicDriver = SonicDriver;
990
+ exports.SonicHistory = SonicHistory;
991
+ exports.anchorSix = anchorSix;
992
+ exports.encoderInput = encoderInput;
993
+ exports.fetchModel = fetchModel;
994
+ exports.filesFrom = filesFrom;
995
+ exports.intoBody = intoBody;
996
+ exports.loadMujoco = loadMujoco;
997
+ exports.referencedFiles = referencedFiles;
998
+ exports.toPolicyOrder = toPolicyOrder;
999
+ return exports;
1000
+ })({}, THREE);