@hackbuild/humanoid 0.2.0 → 0.2.1
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/README.md +5 -5
- package/dist/files.d.ts +6 -2
- package/dist/files.js +32 -11
- package/dist/humanoid.iife.js +90 -33
- package/dist/runtime.d.ts +10 -0
- package/dist/runtime.js +3 -2
- package/dist/sim.d.ts +6 -2
- package/dist/sim.js +40 -17
- package/dist/sonic.d.ts +7 -2
- package/dist/sonic.js +26 -6
- package/dist/three.d.ts +1 -1
- package/dist/three.js +7 -2
- package/llms.md +11 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Run a physics humanoid in the page: MuJoCo simulates a robot from its MJCF files, NVIDIA's GEAR-SONIC policy balances the Unitree G1, and you pose it, shove it and draw it.
|
|
4
4
|
|
|
5
|
-
[](https://www.npmjs.com/package/@hackbuild/humanoid) [](../../LICENSE) ](https://www.npmjs.com/package/@hackbuild/humanoid) [](../../LICENSE)  
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
@@ -73,7 +73,7 @@ GEAR-SONIC turns a reference motion into a token (the encoder) and the token plu
|
|
|
73
73
|
|
|
74
74
|
### the robot
|
|
75
75
|
|
|
76
|
-
`Humanoid.open` compiles the files in MuJoCo's virtual file system. `targets` is the actuators' control array, a live view: for a position actuator it is the joint's target angle. `moveTo` eases targets in over simulated time; a sudden jump can topple a robot that a ramp of half a second leaves standing. `step(seconds)` runs whole timesteps and carries the remainder, at most 0.1 s a call, so a slow frame does not run away. Poses come back in MuJoCo's frame: z up, meters, quaternions w x y z.
|
|
76
|
+
`Humanoid.open` compiles the files in MuJoCo's virtual file system. `targets` is the actuators' control array, a live view: for a position actuator it is the joint's target angle. `moveTo` eases the targets it names in over simulated time and leaves the others alone; a sudden jump can topple a robot that a ramp of half a second leaves standing. After writing `qpos` by hand, call `forward()` before reading poses; after `dispose()` the data's arrays must not be read (`disposed` says so). `step(seconds)` runs whole timesteps and carries the remainder, at most 0.1 s a call, so a slow frame does not run away. Poses come back in MuJoCo's frame: z up, meters, quaternions w x y z.
|
|
77
77
|
|
|
78
78
|
## API overview
|
|
79
79
|
|
|
@@ -130,7 +130,7 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
|
|
|
130
130
|
|
|
131
131
|
| check | result |
|
|
132
132
|
|---|---|
|
|
133
|
-
| `npx vitest run packages/humanoid` |
|
|
133
|
+
| `npx vitest run packages/humanoid` | 18 of 18 tests pass: the 7 below; unnamed parts named by kind and index, a tendon actuator kept out of the joints, an ease leaving other targets and a controller's output alone, a NaN frame, quoted and commented references and cube faces, a mesh folder reached with `..`, a view after dispose; and for the policy the gains and action scale from motor armature, the policy joint order, gravity in the body frame, the anchor ignoring heading, the encoder and decoder layouts, ten ticks oldest first, a driver on a 29 joint model with a stand in runtime, the refusal of a robot without the G1's joints or with them on servos, and a reset or dispose landing while a tick awaits inference (counted) |
|
|
134
134
|
| the 7 runtime and view tests | 7 of 7 tests pass on MuJoCo 4.0.1 in node: references and compiler directories, a dropped folder with an include and a missing mesh, compiling through the virtual files, names, uneven frames stepped at the timestep, a fall under gravity, a keyframe's pose and controls, an actuator reaching its target, an eased move, hold, a push, the compile error naming missing files, the three.js view's meshes and their motion (counted) |
|
|
135
135
|
| the G1 from MuJoCo Menagerie in headless Chrome on an Apple M1 | MuJoCo loads in 206 ms, the G1's 36 files (19.7 MB) arrive in 886 ms with none missing, it compiles with 29 actuated joints and draws 35 meshes; on its stand keyframe the pelvis holds 0.792 m for 5 s; 0.084 ms per step (measured) |
|
|
136
136
|
| the demo page's own check, headless, MuJoCo from jsDelivr | loads in 362 ms, the G1's files in 528 ms; it stands at 0.792 m and eases into a crouch at 0.671 m at 59.9 frames a second (measured) |
|
|
@@ -150,8 +150,8 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
|
|
|
150
150
|
|
|
151
151
|
| file | gzip (measured) | ceiling |
|
|
152
152
|
|---|---|---|
|
|
153
|
-
| `dist/index.js` (main entry, imports external) | 6,
|
|
154
|
-
| `dist/humanoid.iife.js` (single file build) | 12,
|
|
153
|
+
| `dist/index.js` (main entry, imports external) | 6,576 bytes | 6,904 bytes |
|
|
154
|
+
| `dist/humanoid.iife.js` (single file build) | 12,862 bytes | 13,505 bytes |
|
|
155
155
|
|
|
156
156
|
Measured 2026-11-30 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
|
|
157
157
|
tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
|
package/dist/files.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface ModelFiles {
|
|
|
16
16
|
missing: string[];
|
|
17
17
|
}
|
|
18
18
|
/** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
|
|
19
|
-
export declare function referencedFiles(
|
|
19
|
+
export declare function referencedFiles(text: string, dirs?: {
|
|
20
20
|
meshdir?: string;
|
|
21
21
|
texturedir?: string;
|
|
22
22
|
assetdir?: string;
|
|
@@ -34,5 +34,9 @@ export declare function fetchModel(url: string, o?: {
|
|
|
34
34
|
assetBase?: string;
|
|
35
35
|
onFile?: (path: string, done: number, of: number) => void;
|
|
36
36
|
}): Promise<ModelFiles>;
|
|
37
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder;
|
|
39
|
+
* loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked. The
|
|
40
|
+
* main MJCF is the one with a worldbody that no other file includes.
|
|
41
|
+
*/
|
|
38
42
|
export declare function filesFrom(list: Iterable<File>): Promise<ModelFiles>;
|
package/dist/files.js
CHANGED
|
@@ -7,10 +7,27 @@
|
|
|
7
7
|
* arrive is listed in `missing`.
|
|
8
8
|
*/
|
|
9
9
|
import { HumanoidError } from "./runtime.js";
|
|
10
|
-
|
|
11
|
-
const
|
|
10
|
+
// attributes in single or double quotes
|
|
11
|
+
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1], m[2] ?? m[3] ?? ""]));
|
|
12
|
+
// a path with "." and ".." segments resolved, as MuJoCo and a URL would
|
|
13
|
+
const tidy = (path) => {
|
|
14
|
+
const out = [];
|
|
15
|
+
for (const part of path.replace(/\\/g, "/").split("/")) {
|
|
16
|
+
if (part === "..")
|
|
17
|
+
out.length && out[out.length - 1] !== ".." ? out.pop() : out.push("..");
|
|
18
|
+
else if (part && part !== ".")
|
|
19
|
+
out.push(part);
|
|
20
|
+
}
|
|
21
|
+
return out.join("/");
|
|
22
|
+
};
|
|
23
|
+
const join = (dir, file) => tidy(dir ? `${dir}/${file}` : file);
|
|
24
|
+
// XML comments hide tags: a commented out compiler or mesh must not count
|
|
25
|
+
const uncomment = (xml) => xml.replace(/<!--[\s\S]*?-->/g, "");
|
|
26
|
+
// a texture names one file, or six for a cube's faces
|
|
27
|
+
const FILE_ATTRS = ["file", "fileright", "fileleft", "fileup", "filedown", "filefront", "fileback"];
|
|
12
28
|
/** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
|
|
13
|
-
export function referencedFiles(
|
|
29
|
+
export function referencedFiles(text, dirs = {}) {
|
|
30
|
+
const xml = uncomment(text);
|
|
14
31
|
const d = { ...dirs };
|
|
15
32
|
for (const m of xml.matchAll(/<compiler\b[^>]*>/g)) {
|
|
16
33
|
const a = attrs(m[0]);
|
|
@@ -24,11 +41,11 @@ export function referencedFiles(xml, dirs = {}) {
|
|
|
24
41
|
const includes = [...xml.matchAll(/<include\b[^>]*>/g)].map((m) => attrs(m[0]).file).filter((f) => !!f);
|
|
25
42
|
const files = [];
|
|
26
43
|
for (const m of xml.matchAll(/<(mesh|skin|hfield|texture)\b[^>]*>/g)) {
|
|
27
|
-
const
|
|
28
|
-
if (!f)
|
|
29
|
-
continue;
|
|
44
|
+
const a = attrs(m[0]);
|
|
30
45
|
const dir = m[1] === "texture" ? (d.texturedir ?? d.assetdir) : (d.meshdir ?? d.assetdir);
|
|
31
|
-
|
|
46
|
+
for (const k of FILE_ATTRS)
|
|
47
|
+
if (a[k])
|
|
48
|
+
files.push(join(dir, a[k]));
|
|
32
49
|
}
|
|
33
50
|
return { includes, files: [...new Set(files)] };
|
|
34
51
|
}
|
|
@@ -36,7 +53,7 @@ export function referencedFiles(xml, dirs = {}) {
|
|
|
36
53
|
function dirsOf(xmls) {
|
|
37
54
|
const d = {};
|
|
38
55
|
for (const x of xmls)
|
|
39
|
-
for (const m of x.matchAll(/<compiler\b[^>]*>/g)) {
|
|
56
|
+
for (const m of uncomment(x).matchAll(/<compiler\b[^>]*>/g)) {
|
|
40
57
|
const a = attrs(m[0]);
|
|
41
58
|
if (a.meshdir !== undefined)
|
|
42
59
|
d.meshdir = a.meshdir;
|
|
@@ -107,18 +124,22 @@ export function fetchModel(url, o = {}) {
|
|
|
107
124
|
};
|
|
108
125
|
return gather(url, read, o.onFile);
|
|
109
126
|
}
|
|
110
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder;
|
|
129
|
+
* loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked. The
|
|
130
|
+
* main MJCF is the one with a worldbody that no other file includes.
|
|
131
|
+
*/
|
|
111
132
|
export async function filesFrom(list) {
|
|
112
133
|
const files = new Map();
|
|
113
134
|
for (const f of list)
|
|
114
|
-
files.set((f.webkitRelativePath || f.name)
|
|
135
|
+
files.set(tidy(f.webkitRelativePath || f.name), f);
|
|
115
136
|
// paths relative to the folder that holds the main file
|
|
116
137
|
const xmls = [...files.keys()].filter((p) => /\.xml$/i.test(p));
|
|
117
138
|
const texts = new Map();
|
|
118
139
|
for (const p of xmls)
|
|
119
140
|
texts.set(p, await files.get(p).text());
|
|
120
141
|
const included = new Set([...texts].flatMap(([p, t]) => referencedFiles(t).includes.map((i) => join(p.split("/").slice(0, -1).join("/"), i))));
|
|
121
|
-
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];
|
|
142
|
+
const main = xmls.filter((p) => !included.has(p) && /<worldbody/.test(uncomment(texts.get(p)))).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length)[0];
|
|
122
143
|
if (!main)
|
|
123
144
|
throw new HumanoidError("no mjcf here: drop the robot's folder, with an .xml that has a worldbody.");
|
|
124
145
|
const root = main.split("/").slice(0, -1).join("/");
|
package/dist/humanoid.iife.js
CHANGED
|
@@ -30,10 +30,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
30
30
|
if (have) return have;
|
|
31
31
|
const p = (async () => {
|
|
32
32
|
let factory = o.factory;
|
|
33
|
-
const url = o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js";
|
|
33
|
+
const url = new URL(o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js", globalThis.location?.href).href;
|
|
34
34
|
if (!factory) try {
|
|
35
35
|
factory = (await import(
|
|
36
36
|
/* @vite-ignore */
|
|
37
|
+
/* webpackIgnore: true */
|
|
37
38
|
url
|
|
38
39
|
)).default;
|
|
39
40
|
} catch (e) {
|
|
@@ -61,10 +62,27 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
61
62
|
* its file, a texture by texturedir and its file. A file that does not
|
|
62
63
|
* arrive is listed in `missing`.
|
|
63
64
|
*/
|
|
64
|
-
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1], m[2]]));
|
|
65
|
-
const
|
|
65
|
+
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1], m[2] ?? m[3] ?? ""]));
|
|
66
|
+
const tidy = (path) => {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const part of path.replace(/\\/g, "/").split("/")) if (part === "..") out.length && out[out.length - 1] !== ".." ? out.pop() : out.push("..");
|
|
69
|
+
else if (part && part !== ".") out.push(part);
|
|
70
|
+
return out.join("/");
|
|
71
|
+
};
|
|
72
|
+
const join = (dir, file) => tidy(dir ? `${dir}/${file}` : file);
|
|
73
|
+
const uncomment = (xml) => xml.replace(/<!--[\s\S]*?-->/g, "");
|
|
74
|
+
const FILE_ATTRS = [
|
|
75
|
+
"file",
|
|
76
|
+
"fileright",
|
|
77
|
+
"fileleft",
|
|
78
|
+
"fileup",
|
|
79
|
+
"filedown",
|
|
80
|
+
"filefront",
|
|
81
|
+
"fileback"
|
|
82
|
+
];
|
|
66
83
|
/** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
|
|
67
|
-
function referencedFiles(
|
|
84
|
+
function referencedFiles(text, dirs = {}) {
|
|
85
|
+
const xml = uncomment(text);
|
|
68
86
|
const d = { ...dirs };
|
|
69
87
|
for (const m of xml.matchAll(/<compiler\b[^>]*>/g)) {
|
|
70
88
|
const a = attrs(m[0]);
|
|
@@ -75,10 +93,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
75
93
|
const includes = [...xml.matchAll(/<include\b[^>]*>/g)].map((m) => attrs(m[0]).file).filter((f) => !!f);
|
|
76
94
|
const files = [];
|
|
77
95
|
for (const m of xml.matchAll(/<(mesh|skin|hfield|texture)\b[^>]*>/g)) {
|
|
78
|
-
const
|
|
79
|
-
if (!f) continue;
|
|
96
|
+
const a = attrs(m[0]);
|
|
80
97
|
const dir = m[1] === "texture" ? d.texturedir ?? d.assetdir : d.meshdir ?? d.assetdir;
|
|
81
|
-
files.push(join(dir,
|
|
98
|
+
for (const k of FILE_ATTRS) if (a[k]) files.push(join(dir, a[k]));
|
|
82
99
|
}
|
|
83
100
|
return {
|
|
84
101
|
includes,
|
|
@@ -88,7 +105,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
88
105
|
/** Compiler directories set anywhere in a set of MJCF texts: an included file's compiler applies to the whole model. */
|
|
89
106
|
function dirsOf(xmls) {
|
|
90
107
|
const d = {};
|
|
91
|
-
for (const x of xmls) for (const m of x.matchAll(/<compiler\b[^>]*>/g)) {
|
|
108
|
+
for (const x of xmls) for (const m of uncomment(x).matchAll(/<compiler\b[^>]*>/g)) {
|
|
92
109
|
const a = attrs(m[0]);
|
|
93
110
|
if (a.meshdir !== void 0) d.meshdir = a.meshdir;
|
|
94
111
|
if (a.texturedir !== void 0) d.texturedir = a.texturedir;
|
|
@@ -154,15 +171,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
154
171
|
};
|
|
155
172
|
return gather(url, read, o.onFile);
|
|
156
173
|
}
|
|
157
|
-
/**
|
|
174
|
+
/**
|
|
175
|
+
* A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder;
|
|
176
|
+
* loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked. The
|
|
177
|
+
* main MJCF is the one with a worldbody that no other file includes.
|
|
178
|
+
*/
|
|
158
179
|
async function filesFrom(list) {
|
|
159
180
|
const files = /* @__PURE__ */ new Map();
|
|
160
|
-
for (const f of list) files.set((f.webkitRelativePath || f.name)
|
|
181
|
+
for (const f of list) files.set(tidy(f.webkitRelativePath || f.name), f);
|
|
161
182
|
const xmls = [...files.keys()].filter((p) => /\.xml$/i.test(p));
|
|
162
183
|
const texts = /* @__PURE__ */ new Map();
|
|
163
184
|
for (const p of xmls) texts.set(p, await files.get(p).text());
|
|
164
185
|
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];
|
|
186
|
+
const main = xmls.filter((p) => !included.has(p) && /<worldbody/.test(uncomment(texts.get(p)))).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length)[0];
|
|
166
187
|
if (!main) throw new HumanoidError("no mjcf here: drop the robot's folder, with an .xml that has a worldbody.");
|
|
167
188
|
const root = main.split("/").slice(0, -1).join("/");
|
|
168
189
|
const read = async (path) => {
|
|
@@ -173,6 +194,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
173
194
|
}
|
|
174
195
|
// src/sim.ts
|
|
175
196
|
const FREE = 0;
|
|
197
|
+
const JOINT = 0;
|
|
176
198
|
const isArrayLike = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
|
|
177
199
|
/** A robot running in MuJoCo. */
|
|
178
200
|
var Humanoid = class Humanoid {
|
|
@@ -181,7 +203,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
181
203
|
data;
|
|
182
204
|
/** Joint names in model order (a free joint included). */
|
|
183
205
|
joints;
|
|
184
|
-
/** The joint each actuator drives, in actuator order
|
|
206
|
+
/** The joint each actuator drives, in actuator order (`targets[i]` is that joint's target for a position actuator); "" for an actuator on a tendon or a site. */
|
|
185
207
|
actuated;
|
|
186
208
|
bodies;
|
|
187
209
|
keyframes;
|
|
@@ -196,11 +218,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
196
218
|
this.mj = mj;
|
|
197
219
|
this.model = model;
|
|
198
220
|
this.data = new mj.MjData(model);
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
221
|
+
const table = new Uint8Array(model.names.buffer, model.names.byteOffset, model.names.length);
|
|
222
|
+
const dec = new TextDecoder();
|
|
223
|
+
const name = (adr, i, kind) => {
|
|
224
|
+
const a = adr[i];
|
|
225
|
+
let e = a;
|
|
226
|
+
while (e < table.length && table[e] !== 0) e++;
|
|
227
|
+
return e > a ? dec.decode(table.subarray(a, e)) : `${kind} ${i}`;
|
|
228
|
+
};
|
|
229
|
+
this.joints = Array.from({ length: model.njnt }, (_, i) => name(model.name_jntadr, i, "joint"));
|
|
230
|
+
this.bodies = Array.from({ length: model.nbody }, (_, i) => name(model.name_bodyadr, i, "body"));
|
|
231
|
+
this.keyframes = Array.from({ length: model.nkey }, (_, i) => name(model.name_keyadr, i, "keyframe"));
|
|
232
|
+
this.actuated = Array.from({ length: model.nu }, (_, i) => model.actuator_trntype[i] === JOINT ? this.joints[model.actuator_trnid[i * 2]] ?? "" : "");
|
|
204
233
|
this.timestep = model.opt.timestep;
|
|
205
234
|
this.missing = missing;
|
|
206
235
|
mj.mj_forward(model, this.data);
|
|
@@ -245,16 +274,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
245
274
|
* jump in targets can topple a robot that a ramp of half a second leaves standing (measured on the G1).
|
|
246
275
|
*/
|
|
247
276
|
moveTo(targets, seconds = .5) {
|
|
248
|
-
const
|
|
249
|
-
const to =
|
|
250
|
-
if (isArrayLike(targets)) for (let i = 0; i < Math.min(
|
|
277
|
+
const idx = [];
|
|
278
|
+
const to = [];
|
|
279
|
+
if (isArrayLike(targets)) for (let i = 0; i < Math.min(this.data.ctrl.length, targets.length); i++) idx.push(i), to.push(targets[i]);
|
|
251
280
|
else for (const [name, v] of Object.entries(targets)) {
|
|
252
281
|
const i = this.actuated.indexOf(name);
|
|
253
282
|
if (i < 0) throw new HumanoidError(`no actuator drives ${name}.`);
|
|
254
|
-
|
|
283
|
+
idx.push(i);
|
|
284
|
+
to.push(v);
|
|
255
285
|
}
|
|
256
286
|
this.ramp = {
|
|
257
|
-
|
|
287
|
+
idx,
|
|
288
|
+
from: idx.map((i) => this.data.ctrl[i]),
|
|
258
289
|
to,
|
|
259
290
|
t0: this.data.time,
|
|
260
291
|
dur: Math.max(0, seconds)
|
|
@@ -270,13 +301,15 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
270
301
|
if (!r) return;
|
|
271
302
|
const k = r.dur > 0 ? Math.min(1, (this.data.time - r.t0) / r.dur) : 1;
|
|
272
303
|
const e = k * k * (3 - 2 * k);
|
|
273
|
-
|
|
304
|
+
r.idx.forEach((i, k) => this.data.ctrl[i] = r.from[k] + (r.to[k] - r.from[k]) * e);
|
|
274
305
|
if (k >= 1) this.ramp = null;
|
|
275
306
|
}
|
|
276
|
-
/** Each actuated joint's target set to where the joint is now: the body holds its pose. */
|
|
307
|
+
/** Each actuated joint's target set to where the joint is now: the body holds its pose. Stops a running {@link moveTo}. */
|
|
277
308
|
hold() {
|
|
278
309
|
const { model, data } = this;
|
|
310
|
+
this.ramp = null;
|
|
279
311
|
for (let i = 0; i < model.nu; i++) {
|
|
312
|
+
if (model.actuator_trntype[i] !== JOINT) continue;
|
|
280
313
|
const j = model.actuator_trnid[i * 2];
|
|
281
314
|
data.ctrl[i] = data.qpos[model.jnt_qposadr[j]];
|
|
282
315
|
}
|
|
@@ -284,7 +317,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
284
317
|
/** 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
318
|
step(seconds, max = .1) {
|
|
286
319
|
if (this.gone) return 0;
|
|
287
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), max);
|
|
320
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), max);
|
|
288
321
|
const n = Math.floor(this.carry / this.timestep + 1e-6);
|
|
289
322
|
for (let i = 0; i < n; i++) {
|
|
290
323
|
this.applyRamp();
|
|
@@ -297,11 +330,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
297
330
|
run(n, control) {
|
|
298
331
|
if (this.gone) return;
|
|
299
332
|
for (let i = 0; i < n; i++) {
|
|
300
|
-
control?.(this);
|
|
301
333
|
this.applyRamp();
|
|
334
|
+
control?.(this);
|
|
302
335
|
this.mj.mj_step(this.model, this.data);
|
|
303
336
|
}
|
|
304
337
|
}
|
|
338
|
+
/** Recomputes positions and poses from qpos without stepping time: call it after writing qpos by hand. */
|
|
339
|
+
forward() {
|
|
340
|
+
if (!this.gone) this.mj.mj_forward(this.model, this.data);
|
|
341
|
+
}
|
|
342
|
+
/** True once {@link dispose} ran; the data's arrays must not be read after that. */
|
|
343
|
+
get disposed() {
|
|
344
|
+
return this.gone;
|
|
345
|
+
}
|
|
305
346
|
/** 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
347
|
address(joint) {
|
|
307
348
|
const j = this.joints.indexOf(joint);
|
|
@@ -460,7 +501,8 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
460
501
|
const geo = this.geometry(g, type);
|
|
461
502
|
if (!geo) continue;
|
|
462
503
|
const mat = m.geom_matid?.[g] ?? -1;
|
|
463
|
-
const
|
|
504
|
+
const own = m.geom_rgba.subarray(g * 4, g * 4 + 4);
|
|
505
|
+
const rgba = own[0] === .5 && own[1] === .5 && own[2] === .5 && own[3] === 1 && mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : own;
|
|
464
506
|
const material = new three.MeshStandardMaterial({
|
|
465
507
|
roughness: .6,
|
|
466
508
|
metalness: .1,
|
|
@@ -507,8 +549,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
507
549
|
default: return null;
|
|
508
550
|
}
|
|
509
551
|
}
|
|
510
|
-
/** Moves every mesh to its geom's pose after the last step. */
|
|
552
|
+
/** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
|
|
511
553
|
update() {
|
|
554
|
+
if (this.sim.disposed) return;
|
|
512
555
|
const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
|
|
513
556
|
for (const { mesh, geom: g } of this.meshes) {
|
|
514
557
|
const a = g * 9, b = g * 3;
|
|
@@ -832,10 +875,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
832
875
|
static async load(o = {}) {
|
|
833
876
|
let ort = o.ort;
|
|
834
877
|
if (!ort) {
|
|
835
|
-
const url = o.ortUrl ?? "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
|
|
878
|
+
const url = new URL(o.ortUrl ?? "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs", globalThis.location?.href).href;
|
|
836
879
|
try {
|
|
837
880
|
ort = await import(
|
|
838
881
|
/* @vite-ignore */
|
|
882
|
+
/* webpackIgnore: true */
|
|
839
883
|
url
|
|
840
884
|
);
|
|
841
885
|
} catch (e) {
|
|
@@ -882,6 +926,8 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
882
926
|
carry = 0;
|
|
883
927
|
busy = false;
|
|
884
928
|
perTick;
|
|
929
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
930
|
+
generation = 0;
|
|
885
931
|
constructor(sonic, sim) {
|
|
886
932
|
this.sonic = sonic;
|
|
887
933
|
this.sim = sim;
|
|
@@ -893,6 +939,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
893
939
|
this.act = G1.joints.map((j) => {
|
|
894
940
|
const i = sim.actuated.indexOf(j);
|
|
895
941
|
if (i < 0) throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
942
|
+
if (sim.model.actuator_biastype[i] !== 0) throw new HumanoidError(`${j} is on a servo actuator, not a motor; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
896
943
|
return i;
|
|
897
944
|
});
|
|
898
945
|
this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
|
|
@@ -901,10 +948,13 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
901
948
|
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
902
949
|
reset() {
|
|
903
950
|
const { sim } = this;
|
|
951
|
+
if (sim.disposed) return;
|
|
952
|
+
this.generation++;
|
|
904
953
|
sim.reset();
|
|
905
954
|
const d = sim.data;
|
|
906
955
|
d.qpos[2] = .79;
|
|
907
956
|
for (let j = 0; j < 29; j++) d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
|
|
957
|
+
sim.forward();
|
|
908
958
|
this.targets = SONIC_JOINTS.defaults.slice();
|
|
909
959
|
this.last.fill(0);
|
|
910
960
|
this.carry = 0;
|
|
@@ -934,9 +984,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
934
984
|
])
|
|
935
985
|
};
|
|
936
986
|
}
|
|
937
|
-
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
|
|
987
|
+
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. A tick that a reset or dispose overtakes does nothing more. */
|
|
938
988
|
async tick() {
|
|
989
|
+
if (this.sim.disposed) return;
|
|
939
990
|
const d = this.sim.data;
|
|
991
|
+
const gen = this.generation;
|
|
940
992
|
const t0 = performance.now();
|
|
941
993
|
this.history.add(this.state(), this.last);
|
|
942
994
|
const anchor = anchorSix([
|
|
@@ -946,6 +998,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
946
998
|
d.qpos[6]
|
|
947
999
|
]);
|
|
948
1000
|
const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
|
|
1001
|
+
if (gen !== this.generation || this.sim.disposed) return;
|
|
949
1002
|
this.inferenceMs = performance.now() - t0;
|
|
950
1003
|
this.last = Float32Array.from(a);
|
|
951
1004
|
const pi = SONIC_JOINTS.policyIndex;
|
|
@@ -958,13 +1011,17 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
958
1011
|
}
|
|
959
1012
|
});
|
|
960
1013
|
}
|
|
961
|
-
/**
|
|
1014
|
+
/**
|
|
1015
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
1016
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
1017
|
+
*/
|
|
962
1018
|
async advance(seconds) {
|
|
1019
|
+
if (this.sim.disposed) return 0;
|
|
1020
|
+
const per = 1 / SONIC.hz;
|
|
1021
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), .1);
|
|
963
1022
|
if (this.busy) return 0;
|
|
964
1023
|
this.busy = true;
|
|
965
1024
|
try {
|
|
966
|
-
const per = 1 / SONIC.hz;
|
|
967
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), .1);
|
|
968
1025
|
const n = Math.floor(this.carry / per + 1e-6);
|
|
969
1026
|
for (let i = 0; i < n; i++) await this.tick();
|
|
970
1027
|
this.carry = Math.max(0, this.carry - n * per);
|
package/dist/runtime.d.ts
CHANGED
|
@@ -30,6 +30,16 @@ export interface MjModel {
|
|
|
30
30
|
jnt_dofadr: Int32Array;
|
|
31
31
|
jnt_bodyid: Int32Array;
|
|
32
32
|
actuator_trnid: Int32Array;
|
|
33
|
+
/** What each actuator moves: 0 a joint. */
|
|
34
|
+
actuator_trntype: Int32Array;
|
|
35
|
+
/** Each actuator's bias: 0 none (a motor), 1 affine (a position or velocity servo). */
|
|
36
|
+
actuator_biastype: Int32Array;
|
|
37
|
+
/** All names, zero terminated, and where each kind's names start. */
|
|
38
|
+
names: Int8Array;
|
|
39
|
+
name_bodyadr: Int32Array;
|
|
40
|
+
name_jntadr: Int32Array;
|
|
41
|
+
name_keyadr: Int32Array;
|
|
42
|
+
name_actuatoradr: Int32Array;
|
|
33
43
|
geom_type: Int32Array;
|
|
34
44
|
geom_size: Float64Array;
|
|
35
45
|
geom_rgba: Float32Array;
|
package/dist/runtime.js
CHANGED
|
@@ -28,10 +28,11 @@ export function loadMujoco(o = {}) {
|
|
|
28
28
|
return have;
|
|
29
29
|
const p = (async () => {
|
|
30
30
|
let factory = o.factory;
|
|
31
|
-
|
|
31
|
+
// a relative url resolves against the page, as a script tag's would, not against this file
|
|
32
|
+
const url = new URL(o.url ?? MUJOCO_URL, globalThis.location?.href).href;
|
|
32
33
|
if (!factory) {
|
|
33
34
|
try {
|
|
34
|
-
factory = (await import(/* @vite-ignore */ url)).default;
|
|
35
|
+
factory = (await import(/* @vite-ignore */ /* webpackIgnore: true */ url)).default;
|
|
35
36
|
}
|
|
36
37
|
catch (e) {
|
|
37
38
|
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.`);
|
package/dist/sim.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare class Humanoid {
|
|
|
19
19
|
readonly data: MjData;
|
|
20
20
|
/** Joint names in model order (a free joint included). */
|
|
21
21
|
readonly joints: string[];
|
|
22
|
-
/** The joint each actuator drives, in actuator order
|
|
22
|
+
/** The joint each actuator drives, in actuator order (`targets[i]` is that joint's target for a position actuator); "" for an actuator on a tendon or a site. */
|
|
23
23
|
readonly actuated: string[];
|
|
24
24
|
readonly bodies: string[];
|
|
25
25
|
readonly keyframes: string[];
|
|
@@ -50,12 +50,16 @@ export declare class Humanoid {
|
|
|
50
50
|
/** True while a {@link moveTo} is still easing. */
|
|
51
51
|
get moving(): boolean;
|
|
52
52
|
private applyRamp;
|
|
53
|
-
/** Each actuated joint's target set to where the joint is now: the body holds its pose. */
|
|
53
|
+
/** Each actuated joint's target set to where the joint is now: the body holds its pose. Stops a running {@link moveTo}. */
|
|
54
54
|
hold(): void;
|
|
55
55
|
/** 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. */
|
|
56
56
|
step(seconds: number, max?: number): number;
|
|
57
57
|
/** Runs `n` timesteps, calling `control` before each so a controller can set the actuators every step (a PD loop on motor actuators). */
|
|
58
58
|
run(n: number, control?: (sim: Humanoid) => void): void;
|
|
59
|
+
/** Recomputes positions and poses from qpos without stepping time: call it after writing qpos by hand. */
|
|
60
|
+
forward(): void;
|
|
61
|
+
/** True once {@link dispose} ran; the data's arrays must not be read after that. */
|
|
62
|
+
get disposed(): boolean;
|
|
59
63
|
/** Where a hinge or slide joint keeps its position in qpos and its velocity in qvel, or null for a name the model lacks. */
|
|
60
64
|
address(joint: string): {
|
|
61
65
|
qpos: number;
|
package/dist/sim.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { HumanoidError } from "./runtime.js";
|
|
9
9
|
const FREE = 0;
|
|
10
|
+
const JOINT = 0;
|
|
10
11
|
const isArrayLike = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
|
|
11
12
|
/** A robot running in MuJoCo. */
|
|
12
13
|
export class Humanoid {
|
|
@@ -15,7 +16,7 @@ export class Humanoid {
|
|
|
15
16
|
data;
|
|
16
17
|
/** Joint names in model order (a free joint included). */
|
|
17
18
|
joints;
|
|
18
|
-
/** The joint each actuator drives, in actuator order
|
|
19
|
+
/** The joint each actuator drives, in actuator order (`targets[i]` is that joint's target for a position actuator); "" for an actuator on a tendon or a site. */
|
|
19
20
|
actuated;
|
|
20
21
|
bodies;
|
|
21
22
|
keyframes;
|
|
@@ -30,11 +31,20 @@ export class Humanoid {
|
|
|
30
31
|
this.mj = mj;
|
|
31
32
|
this.model = model;
|
|
32
33
|
this.data = new mj.MjData(model);
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
// names read from the model's name table: the binding's mj_id2name gives a stray string for unnamed objects
|
|
35
|
+
const table = new Uint8Array(model.names.buffer, model.names.byteOffset, model.names.length);
|
|
36
|
+
const dec = new TextDecoder();
|
|
37
|
+
const name = (adr, i, kind) => {
|
|
38
|
+
const a = adr[i];
|
|
39
|
+
let e = a;
|
|
40
|
+
while (e < table.length && table[e] !== 0)
|
|
41
|
+
e++;
|
|
42
|
+
return e > a ? dec.decode(table.subarray(a, e)) : `${kind} ${i}`;
|
|
43
|
+
};
|
|
44
|
+
this.joints = Array.from({ length: model.njnt }, (_, i) => name(model.name_jntadr, i, "joint"));
|
|
45
|
+
this.bodies = Array.from({ length: model.nbody }, (_, i) => name(model.name_bodyadr, i, "body"));
|
|
46
|
+
this.keyframes = Array.from({ length: model.nkey }, (_, i) => name(model.name_keyadr, i, "keyframe"));
|
|
47
|
+
this.actuated = Array.from({ length: model.nu }, (_, i) => (model.actuator_trntype[i] === JOINT ? (this.joints[model.actuator_trnid[i * 2]] ?? "") : ""));
|
|
38
48
|
this.timestep = model.opt.timestep;
|
|
39
49
|
this.missing = missing;
|
|
40
50
|
mj.mj_forward(model, this.data);
|
|
@@ -86,19 +96,20 @@ export class Humanoid {
|
|
|
86
96
|
* jump in targets can topple a robot that a ramp of half a second leaves standing (measured on the G1).
|
|
87
97
|
*/
|
|
88
98
|
moveTo(targets, seconds = 0.5) {
|
|
89
|
-
const
|
|
90
|
-
const to =
|
|
99
|
+
const idx = [];
|
|
100
|
+
const to = [];
|
|
91
101
|
if (isArrayLike(targets))
|
|
92
|
-
for (let i = 0; i < Math.min(
|
|
93
|
-
|
|
102
|
+
for (let i = 0; i < Math.min(this.data.ctrl.length, targets.length); i++)
|
|
103
|
+
(idx.push(i), to.push(targets[i]));
|
|
94
104
|
else
|
|
95
105
|
for (const [name, v] of Object.entries(targets)) {
|
|
96
106
|
const i = this.actuated.indexOf(name);
|
|
97
107
|
if (i < 0)
|
|
98
108
|
throw new HumanoidError(`no actuator drives ${name}.`);
|
|
99
|
-
|
|
109
|
+
idx.push(i);
|
|
110
|
+
to.push(v);
|
|
100
111
|
}
|
|
101
|
-
this.ramp = { from, to, t0: this.data.time, dur: Math.max(0, seconds) };
|
|
112
|
+
this.ramp = { idx, from: idx.map((i) => this.data.ctrl[i]), to, t0: this.data.time, dur: Math.max(0, seconds) };
|
|
102
113
|
if (seconds <= 0)
|
|
103
114
|
this.applyRamp();
|
|
104
115
|
}
|
|
@@ -112,15 +123,17 @@ export class Humanoid {
|
|
|
112
123
|
return;
|
|
113
124
|
const k = r.dur > 0 ? Math.min(1, (this.data.time - r.t0) / r.dur) : 1;
|
|
114
125
|
const e = k * k * (3 - 2 * k);
|
|
115
|
-
|
|
116
|
-
this.data.ctrl[i] = r.from[i] + (r.to[i] - r.from[i]) * e;
|
|
126
|
+
r.idx.forEach((i, k) => (this.data.ctrl[i] = r.from[k] + (r.to[k] - r.from[k]) * e));
|
|
117
127
|
if (k >= 1)
|
|
118
128
|
this.ramp = null;
|
|
119
129
|
}
|
|
120
|
-
/** Each actuated joint's target set to where the joint is now: the body holds its pose. */
|
|
130
|
+
/** Each actuated joint's target set to where the joint is now: the body holds its pose. Stops a running {@link moveTo}. */
|
|
121
131
|
hold() {
|
|
122
132
|
const { model, data } = this;
|
|
133
|
+
this.ramp = null;
|
|
123
134
|
for (let i = 0; i < model.nu; i++) {
|
|
135
|
+
if (model.actuator_trntype[i] !== JOINT)
|
|
136
|
+
continue;
|
|
124
137
|
const j = model.actuator_trnid[i * 2];
|
|
125
138
|
data.ctrl[i] = data.qpos[model.jnt_qposadr[j]];
|
|
126
139
|
}
|
|
@@ -129,7 +142,7 @@ export class Humanoid {
|
|
|
129
142
|
step(seconds, max = 0.1) {
|
|
130
143
|
if (this.gone)
|
|
131
144
|
return 0;
|
|
132
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), max);
|
|
145
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), max);
|
|
133
146
|
// counted by division, so float drift in the carry never drops a step
|
|
134
147
|
const n = Math.floor(this.carry / this.timestep + 1e-6);
|
|
135
148
|
for (let i = 0; i < n; i++) {
|
|
@@ -144,11 +157,21 @@ export class Humanoid {
|
|
|
144
157
|
if (this.gone)
|
|
145
158
|
return;
|
|
146
159
|
for (let i = 0; i < n; i++) {
|
|
147
|
-
|
|
160
|
+
// the ramp first, so a controller's output is what steps
|
|
148
161
|
this.applyRamp();
|
|
162
|
+
control?.(this);
|
|
149
163
|
this.mj.mj_step(this.model, this.data);
|
|
150
164
|
}
|
|
151
165
|
}
|
|
166
|
+
/** Recomputes positions and poses from qpos without stepping time: call it after writing qpos by hand. */
|
|
167
|
+
forward() {
|
|
168
|
+
if (!this.gone)
|
|
169
|
+
this.mj.mj_forward(this.model, this.data);
|
|
170
|
+
}
|
|
171
|
+
/** True once {@link dispose} ran; the data's arrays must not be read after that. */
|
|
172
|
+
get disposed() {
|
|
173
|
+
return this.gone;
|
|
174
|
+
}
|
|
152
175
|
/** Where a hinge or slide joint keeps its position in qpos and its velocity in qvel, or null for a name the model lacks. */
|
|
153
176
|
address(joint) {
|
|
154
177
|
const j = this.joints.indexOf(joint);
|
package/dist/sonic.d.ts
CHANGED
|
@@ -160,14 +160,19 @@ export declare class SonicDriver {
|
|
|
160
160
|
private carry;
|
|
161
161
|
private busy;
|
|
162
162
|
private perTick;
|
|
163
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
164
|
+
private generation;
|
|
163
165
|
constructor(sonic: Sonic, sim: Humanoid);
|
|
164
166
|
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
165
167
|
reset(): void;
|
|
166
168
|
/** The robot's state this tick, in the policy's order. */
|
|
167
169
|
state(): SonicState;
|
|
168
|
-
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
|
|
170
|
+
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. A tick that a reset or dispose overtakes does nothing more. */
|
|
169
171
|
tick(): Promise<void>;
|
|
170
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
174
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
175
|
+
*/
|
|
171
176
|
advance(seconds: number): Promise<number>;
|
|
172
177
|
}
|
|
173
178
|
export {};
|
package/dist/sonic.js
CHANGED
|
@@ -198,9 +198,10 @@ export class Sonic {
|
|
|
198
198
|
static async load(o = {}) {
|
|
199
199
|
let ort = o.ort;
|
|
200
200
|
if (!ort) {
|
|
201
|
-
|
|
201
|
+
// a relative url resolves against the page, not against this file
|
|
202
|
+
const url = new URL(o.ortUrl ?? ORT_URL, globalThis.location?.href).href;
|
|
202
203
|
try {
|
|
203
|
-
ort = (await import(/* @vite-ignore */ url));
|
|
204
|
+
ort = (await import(/* @vite-ignore */ /* webpackIgnore: true */ url));
|
|
204
205
|
}
|
|
205
206
|
catch (e) {
|
|
206
207
|
throw new HumanoidError(`onnxruntime-web did not load from ${url}: ${e instanceof Error ? e.message : String(e)}.`);
|
|
@@ -246,6 +247,8 @@ export class SonicDriver {
|
|
|
246
247
|
carry = 0;
|
|
247
248
|
busy = false;
|
|
248
249
|
perTick;
|
|
250
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
251
|
+
generation = 0;
|
|
249
252
|
constructor(sonic, sim) {
|
|
250
253
|
this.sonic = sonic;
|
|
251
254
|
this.sim = sim;
|
|
@@ -259,6 +262,9 @@ export class SonicDriver {
|
|
|
259
262
|
const i = sim.actuated.indexOf(j);
|
|
260
263
|
if (i < 0)
|
|
261
264
|
throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
265
|
+
// a position or velocity servo would read the torques as targets
|
|
266
|
+
if (sim.model.actuator_biastype[i] !== 0)
|
|
267
|
+
throw new HumanoidError(`${j} is on a servo actuator, not a motor; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
262
268
|
return i;
|
|
263
269
|
});
|
|
264
270
|
this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
|
|
@@ -267,11 +273,15 @@ export class SonicDriver {
|
|
|
267
273
|
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
268
274
|
reset() {
|
|
269
275
|
const { sim } = this;
|
|
276
|
+
if (sim.disposed)
|
|
277
|
+
return;
|
|
278
|
+
this.generation++;
|
|
270
279
|
sim.reset();
|
|
271
280
|
const d = sim.data;
|
|
272
281
|
d.qpos[2] = 0.79;
|
|
273
282
|
for (let j = 0; j < 29; j++)
|
|
274
283
|
d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
|
|
284
|
+
sim.forward();
|
|
275
285
|
this.targets = SONIC_JOINTS.defaults.slice();
|
|
276
286
|
this.last.fill(0);
|
|
277
287
|
this.carry = 0;
|
|
@@ -288,13 +298,18 @@ export class SonicDriver {
|
|
|
288
298
|
gravity: intoBody(quat, [0, 0, -1]),
|
|
289
299
|
};
|
|
290
300
|
}
|
|
291
|
-
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
|
|
301
|
+
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. A tick that a reset or dispose overtakes does nothing more. */
|
|
292
302
|
async tick() {
|
|
303
|
+
if (this.sim.disposed)
|
|
304
|
+
return;
|
|
293
305
|
const d = this.sim.data;
|
|
306
|
+
const gen = this.generation;
|
|
294
307
|
const t0 = performance.now();
|
|
295
308
|
this.history.add(this.state(), this.last);
|
|
296
309
|
const anchor = anchorSix([d.qpos[3], d.qpos[4], d.qpos[5], d.qpos[6]]);
|
|
297
310
|
const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
|
|
311
|
+
if (gen !== this.generation || this.sim.disposed)
|
|
312
|
+
return;
|
|
298
313
|
this.inferenceMs = performance.now() - t0;
|
|
299
314
|
this.last = Float32Array.from(a);
|
|
300
315
|
const pi = SONIC_JOINTS.policyIndex;
|
|
@@ -308,14 +323,19 @@ export class SonicDriver {
|
|
|
308
323
|
}
|
|
309
324
|
});
|
|
310
325
|
}
|
|
311
|
-
/**
|
|
326
|
+
/**
|
|
327
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
328
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
329
|
+
*/
|
|
312
330
|
async advance(seconds) {
|
|
331
|
+
if (this.sim.disposed)
|
|
332
|
+
return 0;
|
|
333
|
+
const per = 1 / SONIC.hz;
|
|
334
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), 0.1);
|
|
313
335
|
if (this.busy)
|
|
314
336
|
return 0;
|
|
315
337
|
this.busy = true;
|
|
316
338
|
try {
|
|
317
|
-
const per = 1 / SONIC.hz;
|
|
318
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), 0.1);
|
|
319
339
|
const n = Math.floor(this.carry / per + 1e-6);
|
|
320
340
|
for (let i = 0; i < n; i++)
|
|
321
341
|
await this.tick();
|
package/dist/three.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export declare class HumanoidView {
|
|
|
27
27
|
private owned;
|
|
28
28
|
constructor(sim: Humanoid, o?: HumanoidViewOptions);
|
|
29
29
|
private geometry;
|
|
30
|
-
/** Moves every mesh to its geom's pose after the last step. */
|
|
30
|
+
/** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
|
|
31
31
|
update(): void;
|
|
32
32
|
/** Meshes drawn. */
|
|
33
33
|
get count(): number;
|
package/dist/three.js
CHANGED
|
@@ -32,8 +32,11 @@ export class HumanoidView {
|
|
|
32
32
|
const geo = this.geometry(g, type);
|
|
33
33
|
if (!geo)
|
|
34
34
|
continue;
|
|
35
|
+
// a geom's own rgba wins; MuJoCo's default rgba (0.5 0.5 0.5 1) gives way to the geom's material
|
|
35
36
|
const mat = m.geom_matid?.[g] ?? -1;
|
|
36
|
-
const
|
|
37
|
+
const own = m.geom_rgba.subarray(g * 4, g * 4 + 4);
|
|
38
|
+
const plain = own[0] === 0.5 && own[1] === 0.5 && own[2] === 0.5 && own[3] === 1;
|
|
39
|
+
const rgba = plain && mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : own;
|
|
37
40
|
const material = new MeshStandardMaterial({ roughness: 0.6, metalness: 0.1, transparent: rgba[3] < 1, opacity: rgba[3] });
|
|
38
41
|
material.color.setRGB(rgba[0], rgba[1], rgba[2]);
|
|
39
42
|
this.owned.push(material);
|
|
@@ -81,8 +84,10 @@ export class HumanoidView {
|
|
|
81
84
|
return null;
|
|
82
85
|
}
|
|
83
86
|
}
|
|
84
|
-
/** Moves every mesh to its geom's pose after the last step. */
|
|
87
|
+
/** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
|
|
85
88
|
update() {
|
|
89
|
+
if (this.sim.disposed)
|
|
90
|
+
return;
|
|
86
91
|
const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
|
|
87
92
|
for (const { mesh, geom: g } of this.meshes) {
|
|
88
93
|
const a = g * 9, b = g * 3;
|
package/llms.md
CHANGED
|
@@ -43,7 +43,7 @@ A robot from the URL of its main MJCF; every file it names is fetched beside it,
|
|
|
43
43
|
function filesFrom(list: Iterable<File>): Promise<ModelFiles>
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
A robot from
|
|
46
|
+
A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder; loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked.
|
|
47
47
|
|
|
48
48
|
```ts
|
|
49
49
|
const G1: { readonly bytes: 19666440; readonly joints: readonly ["left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint"]; readonly keyframe: "stand"; readonly 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."; readonly name: "unitree g1, 29 joints"; readonly url: "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/98a70c569c4c1b6da467a20012f766ee1f8dc521/unitree_g1/scene.xml" }
|
|
@@ -61,12 +61,14 @@ class Humanoid {
|
|
|
61
61
|
readonly missing: string[];
|
|
62
62
|
readonly model: MjModel;
|
|
63
63
|
readonly timestep: number;
|
|
64
|
+
readonly disposed: boolean;
|
|
64
65
|
readonly moving: boolean;
|
|
65
66
|
readonly rootBody: string | null;
|
|
66
67
|
readonly targets: Float64Array;
|
|
67
68
|
readonly time: number;
|
|
68
69
|
address(joint: string): { qpos: number; qvel: number } | null;
|
|
69
70
|
dispose(): void;
|
|
71
|
+
forward(): void;
|
|
70
72
|
hold(): void;
|
|
71
73
|
joint(name: string): { dq: number; q: number } | null;
|
|
72
74
|
moveTo(targets: ArrayLike<number> | Record<string, number>, seconds?: number): void;
|
|
@@ -113,7 +115,9 @@ A model's state; the arrays are views on the wasm heap, live after each step.
|
|
|
113
115
|
|
|
114
116
|
```ts
|
|
115
117
|
interface MjModel {
|
|
118
|
+
actuator_biastype: Int32Array;
|
|
116
119
|
actuator_trnid: Int32Array;
|
|
120
|
+
actuator_trntype: Int32Array;
|
|
117
121
|
geom_dataid: Int32Array;
|
|
118
122
|
geom_group: Int32Array;
|
|
119
123
|
geom_rgba: Float32Array;
|
|
@@ -129,6 +133,11 @@ interface MjModel {
|
|
|
129
133
|
mesh_vert: Float32Array;
|
|
130
134
|
mesh_vertadr: Int32Array;
|
|
131
135
|
mesh_vertnum: Int32Array;
|
|
136
|
+
name_actuatoradr: Int32Array;
|
|
137
|
+
name_bodyadr: Int32Array;
|
|
138
|
+
name_jntadr: Int32Array;
|
|
139
|
+
name_keyadr: Int32Array;
|
|
140
|
+
names: Int8Array;
|
|
132
141
|
nbody: number;
|
|
133
142
|
ngeom: number;
|
|
134
143
|
njnt: number;
|
|
@@ -218,7 +227,7 @@ interface Pose {
|
|
|
218
227
|
A body's world pose: position x y z and quaternion w x y z, in MuJoCo's frame.
|
|
219
228
|
|
|
220
229
|
```ts
|
|
221
|
-
function referencedFiles(
|
|
230
|
+
function referencedFiles(text: string, dirs?: { assetdir?: string; meshdir?: string; texturedir?: string }): { files: string[]; includes: string[] }
|
|
222
231
|
```
|
|
223
232
|
|
|
224
233
|
The files one MJCF names, split into includes and the rest, joined onto its compiler's directories.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hackbuild/humanoid",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "A physics humanoid in the page: MuJoCo (Google DeepMind's WebAssembly build, loaded at run time and never bundled) runs a robot from its MJCF files, holds joint targets with its position actuators, and gives the body's pose to a three.js view. Starts with the Unitree G1, and runs NVIDIA's GEAR-SONIC policy on it so it balances (weights and onnxruntime-web loaded at run time).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|