@hackbuild/humanoid 0.2.0 → 0.2.2
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 +6 -6
- package/dist/files.d.ts +6 -2
- package/dist/files.js +32 -11
- package/dist/humanoid.iife.js +92 -34
- 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 +10 -3
- 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
|
|
|
@@ -102,7 +102,7 @@ The full reference is in [docs/api/humanoid](../../docs/api/humanoid/README.md).
|
|
|
102
102
|
| stepping | nothing more | 0.084 ms per 2 ms step for the G1, about 24 times real time (measured) |
|
|
103
103
|
| the policy | onnxruntime-web on wasm, one thread | 5.7 ms a 20 ms tick in headless Chrome on an Apple M1 (measured) |
|
|
104
104
|
| drawing | three.js 0.186 or later, WebGL | the G1 draws 35 meshes |
|
|
105
|
-
| single file build | `dist/humanoid.iife.js` | `HackbuildHumanoid` global with `THREE` from the page; MuJoCo still loads from its URL |
|
|
105
|
+
| single file build | `dist/humanoid.iife.js` | `HackbuildHumanoid` global with [`THREE`](../../docs/concepts.md#builds-that-run-from-file) from the page; MuJoCo still loads from its URL |
|
|
106
106
|
|
|
107
107
|
## Errors and troubleshooting
|
|
108
108
|
|
|
@@ -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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
var HackbuildHumanoid = (function(exports, three) {
|
|
2
|
+
if (!globalThis.THREE) throw new Error("@hackbuild/humanoid: no THREE on the page. import three in a module script, set globalThis.THREE, then load this file with defer.");
|
|
2
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
4
|
// src/runtime.ts
|
|
4
5
|
/**
|
|
@@ -30,10 +31,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
30
31
|
if (have) return have;
|
|
31
32
|
const p = (async () => {
|
|
32
33
|
let factory = o.factory;
|
|
33
|
-
const url = o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js";
|
|
34
|
+
const url = new URL(o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js", globalThis.location?.href).href;
|
|
34
35
|
if (!factory) try {
|
|
35
36
|
factory = (await import(
|
|
36
37
|
/* @vite-ignore */
|
|
38
|
+
/* webpackIgnore: true */
|
|
37
39
|
url
|
|
38
40
|
)).default;
|
|
39
41
|
} catch (e) {
|
|
@@ -61,10 +63,27 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
61
63
|
* its file, a texture by texturedir and its file. A file that does not
|
|
62
64
|
* arrive is listed in `missing`.
|
|
63
65
|
*/
|
|
64
|
-
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1], m[2]]));
|
|
65
|
-
const
|
|
66
|
+
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1], m[2] ?? m[3] ?? ""]));
|
|
67
|
+
const tidy = (path) => {
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const part of path.replace(/\\/g, "/").split("/")) if (part === "..") out.length && out[out.length - 1] !== ".." ? out.pop() : out.push("..");
|
|
70
|
+
else if (part && part !== ".") out.push(part);
|
|
71
|
+
return out.join("/");
|
|
72
|
+
};
|
|
73
|
+
const join = (dir, file) => tidy(dir ? `${dir}/${file}` : file);
|
|
74
|
+
const uncomment = (xml) => xml.replace(/<!--[\s\S]*?-->/g, "");
|
|
75
|
+
const FILE_ATTRS = [
|
|
76
|
+
"file",
|
|
77
|
+
"fileright",
|
|
78
|
+
"fileleft",
|
|
79
|
+
"fileup",
|
|
80
|
+
"filedown",
|
|
81
|
+
"filefront",
|
|
82
|
+
"fileback"
|
|
83
|
+
];
|
|
66
84
|
/** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
|
|
67
|
-
function referencedFiles(
|
|
85
|
+
function referencedFiles(text, dirs = {}) {
|
|
86
|
+
const xml = uncomment(text);
|
|
68
87
|
const d = { ...dirs };
|
|
69
88
|
for (const m of xml.matchAll(/<compiler\b[^>]*>/g)) {
|
|
70
89
|
const a = attrs(m[0]);
|
|
@@ -75,10 +94,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
75
94
|
const includes = [...xml.matchAll(/<include\b[^>]*>/g)].map((m) => attrs(m[0]).file).filter((f) => !!f);
|
|
76
95
|
const files = [];
|
|
77
96
|
for (const m of xml.matchAll(/<(mesh|skin|hfield|texture)\b[^>]*>/g)) {
|
|
78
|
-
const
|
|
79
|
-
if (!f) continue;
|
|
97
|
+
const a = attrs(m[0]);
|
|
80
98
|
const dir = m[1] === "texture" ? d.texturedir ?? d.assetdir : d.meshdir ?? d.assetdir;
|
|
81
|
-
files.push(join(dir,
|
|
99
|
+
for (const k of FILE_ATTRS) if (a[k]) files.push(join(dir, a[k]));
|
|
82
100
|
}
|
|
83
101
|
return {
|
|
84
102
|
includes,
|
|
@@ -88,7 +106,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
88
106
|
/** Compiler directories set anywhere in a set of MJCF texts: an included file's compiler applies to the whole model. */
|
|
89
107
|
function dirsOf(xmls) {
|
|
90
108
|
const d = {};
|
|
91
|
-
for (const x of xmls) for (const m of x.matchAll(/<compiler\b[^>]*>/g)) {
|
|
109
|
+
for (const x of xmls) for (const m of uncomment(x).matchAll(/<compiler\b[^>]*>/g)) {
|
|
92
110
|
const a = attrs(m[0]);
|
|
93
111
|
if (a.meshdir !== void 0) d.meshdir = a.meshdir;
|
|
94
112
|
if (a.texturedir !== void 0) d.texturedir = a.texturedir;
|
|
@@ -154,15 +172,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
154
172
|
};
|
|
155
173
|
return gather(url, read, o.onFile);
|
|
156
174
|
}
|
|
157
|
-
/**
|
|
175
|
+
/**
|
|
176
|
+
* A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder;
|
|
177
|
+
* loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked. The
|
|
178
|
+
* main MJCF is the one with a worldbody that no other file includes.
|
|
179
|
+
*/
|
|
158
180
|
async function filesFrom(list) {
|
|
159
181
|
const files = /* @__PURE__ */ new Map();
|
|
160
|
-
for (const f of list) files.set((f.webkitRelativePath || f.name)
|
|
182
|
+
for (const f of list) files.set(tidy(f.webkitRelativePath || f.name), f);
|
|
161
183
|
const xmls = [...files.keys()].filter((p) => /\.xml$/i.test(p));
|
|
162
184
|
const texts = /* @__PURE__ */ new Map();
|
|
163
185
|
for (const p of xmls) texts.set(p, await files.get(p).text());
|
|
164
186
|
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];
|
|
187
|
+
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
188
|
if (!main) throw new HumanoidError("no mjcf here: drop the robot's folder, with an .xml that has a worldbody.");
|
|
167
189
|
const root = main.split("/").slice(0, -1).join("/");
|
|
168
190
|
const read = async (path) => {
|
|
@@ -173,6 +195,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
173
195
|
}
|
|
174
196
|
// src/sim.ts
|
|
175
197
|
const FREE = 0;
|
|
198
|
+
const JOINT = 0;
|
|
176
199
|
const isArrayLike = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
|
|
177
200
|
/** A robot running in MuJoCo. */
|
|
178
201
|
var Humanoid = class Humanoid {
|
|
@@ -181,7 +204,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
181
204
|
data;
|
|
182
205
|
/** Joint names in model order (a free joint included). */
|
|
183
206
|
joints;
|
|
184
|
-
/** The joint each actuator drives, in actuator order
|
|
207
|
+
/** 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
208
|
actuated;
|
|
186
209
|
bodies;
|
|
187
210
|
keyframes;
|
|
@@ -196,11 +219,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
196
219
|
this.mj = mj;
|
|
197
220
|
this.model = model;
|
|
198
221
|
this.data = new mj.MjData(model);
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
222
|
+
const table = new Uint8Array(model.names.buffer, model.names.byteOffset, model.names.length);
|
|
223
|
+
const dec = new TextDecoder();
|
|
224
|
+
const name = (adr, i, kind) => {
|
|
225
|
+
const a = adr[i];
|
|
226
|
+
let e = a;
|
|
227
|
+
while (e < table.length && table[e] !== 0) e++;
|
|
228
|
+
return e > a ? dec.decode(table.subarray(a, e)) : `${kind} ${i}`;
|
|
229
|
+
};
|
|
230
|
+
this.joints = Array.from({ length: model.njnt }, (_, i) => name(model.name_jntadr, i, "joint"));
|
|
231
|
+
this.bodies = Array.from({ length: model.nbody }, (_, i) => name(model.name_bodyadr, i, "body"));
|
|
232
|
+
this.keyframes = Array.from({ length: model.nkey }, (_, i) => name(model.name_keyadr, i, "keyframe"));
|
|
233
|
+
this.actuated = Array.from({ length: model.nu }, (_, i) => model.actuator_trntype[i] === JOINT ? this.joints[model.actuator_trnid[i * 2]] ?? "" : "");
|
|
204
234
|
this.timestep = model.opt.timestep;
|
|
205
235
|
this.missing = missing;
|
|
206
236
|
mj.mj_forward(model, this.data);
|
|
@@ -245,16 +275,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
245
275
|
* jump in targets can topple a robot that a ramp of half a second leaves standing (measured on the G1).
|
|
246
276
|
*/
|
|
247
277
|
moveTo(targets, seconds = .5) {
|
|
248
|
-
const
|
|
249
|
-
const to =
|
|
250
|
-
if (isArrayLike(targets)) for (let i = 0; i < Math.min(
|
|
278
|
+
const idx = [];
|
|
279
|
+
const to = [];
|
|
280
|
+
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
281
|
else for (const [name, v] of Object.entries(targets)) {
|
|
252
282
|
const i = this.actuated.indexOf(name);
|
|
253
283
|
if (i < 0) throw new HumanoidError(`no actuator drives ${name}.`);
|
|
254
|
-
|
|
284
|
+
idx.push(i);
|
|
285
|
+
to.push(v);
|
|
255
286
|
}
|
|
256
287
|
this.ramp = {
|
|
257
|
-
|
|
288
|
+
idx,
|
|
289
|
+
from: idx.map((i) => this.data.ctrl[i]),
|
|
258
290
|
to,
|
|
259
291
|
t0: this.data.time,
|
|
260
292
|
dur: Math.max(0, seconds)
|
|
@@ -270,13 +302,15 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
270
302
|
if (!r) return;
|
|
271
303
|
const k = r.dur > 0 ? Math.min(1, (this.data.time - r.t0) / r.dur) : 1;
|
|
272
304
|
const e = k * k * (3 - 2 * k);
|
|
273
|
-
|
|
305
|
+
r.idx.forEach((i, k) => this.data.ctrl[i] = r.from[k] + (r.to[k] - r.from[k]) * e);
|
|
274
306
|
if (k >= 1) this.ramp = null;
|
|
275
307
|
}
|
|
276
|
-
/** Each actuated joint's target set to where the joint is now: the body holds its pose. */
|
|
308
|
+
/** Each actuated joint's target set to where the joint is now: the body holds its pose. Stops a running {@link moveTo}. */
|
|
277
309
|
hold() {
|
|
278
310
|
const { model, data } = this;
|
|
311
|
+
this.ramp = null;
|
|
279
312
|
for (let i = 0; i < model.nu; i++) {
|
|
313
|
+
if (model.actuator_trntype[i] !== JOINT) continue;
|
|
280
314
|
const j = model.actuator_trnid[i * 2];
|
|
281
315
|
data.ctrl[i] = data.qpos[model.jnt_qposadr[j]];
|
|
282
316
|
}
|
|
@@ -284,7 +318,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
284
318
|
/** 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
319
|
step(seconds, max = .1) {
|
|
286
320
|
if (this.gone) return 0;
|
|
287
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), max);
|
|
321
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), max);
|
|
288
322
|
const n = Math.floor(this.carry / this.timestep + 1e-6);
|
|
289
323
|
for (let i = 0; i < n; i++) {
|
|
290
324
|
this.applyRamp();
|
|
@@ -297,11 +331,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
297
331
|
run(n, control) {
|
|
298
332
|
if (this.gone) return;
|
|
299
333
|
for (let i = 0; i < n; i++) {
|
|
300
|
-
control?.(this);
|
|
301
334
|
this.applyRamp();
|
|
335
|
+
control?.(this);
|
|
302
336
|
this.mj.mj_step(this.model, this.data);
|
|
303
337
|
}
|
|
304
338
|
}
|
|
339
|
+
/** Recomputes positions and poses from qpos without stepping time: call it after writing qpos by hand. */
|
|
340
|
+
forward() {
|
|
341
|
+
if (!this.gone) this.mj.mj_forward(this.model, this.data);
|
|
342
|
+
}
|
|
343
|
+
/** True once {@link dispose} ran; the data's arrays must not be read after that. */
|
|
344
|
+
get disposed() {
|
|
345
|
+
return this.gone;
|
|
346
|
+
}
|
|
305
347
|
/** 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
348
|
address(joint) {
|
|
307
349
|
const j = this.joints.indexOf(joint);
|
|
@@ -460,7 +502,8 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
460
502
|
const geo = this.geometry(g, type);
|
|
461
503
|
if (!geo) continue;
|
|
462
504
|
const mat = m.geom_matid?.[g] ?? -1;
|
|
463
|
-
const
|
|
505
|
+
const own = m.geom_rgba.subarray(g * 4, g * 4 + 4);
|
|
506
|
+
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
507
|
const material = new three.MeshStandardMaterial({
|
|
465
508
|
roughness: .6,
|
|
466
509
|
metalness: .1,
|
|
@@ -507,8 +550,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
507
550
|
default: return null;
|
|
508
551
|
}
|
|
509
552
|
}
|
|
510
|
-
/** Moves every mesh to its geom's pose after the last step. */
|
|
553
|
+
/** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
|
|
511
554
|
update() {
|
|
555
|
+
if (this.sim.disposed) return;
|
|
512
556
|
const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
|
|
513
557
|
for (const { mesh, geom: g } of this.meshes) {
|
|
514
558
|
const a = g * 9, b = g * 3;
|
|
@@ -832,10 +876,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
832
876
|
static async load(o = {}) {
|
|
833
877
|
let ort = o.ort;
|
|
834
878
|
if (!ort) {
|
|
835
|
-
const url = o.ortUrl ?? "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
|
|
879
|
+
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
880
|
try {
|
|
837
881
|
ort = await import(
|
|
838
882
|
/* @vite-ignore */
|
|
883
|
+
/* webpackIgnore: true */
|
|
839
884
|
url
|
|
840
885
|
);
|
|
841
886
|
} catch (e) {
|
|
@@ -882,6 +927,8 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
882
927
|
carry = 0;
|
|
883
928
|
busy = false;
|
|
884
929
|
perTick;
|
|
930
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
931
|
+
generation = 0;
|
|
885
932
|
constructor(sonic, sim) {
|
|
886
933
|
this.sonic = sonic;
|
|
887
934
|
this.sim = sim;
|
|
@@ -893,6 +940,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
893
940
|
this.act = G1.joints.map((j) => {
|
|
894
941
|
const i = sim.actuated.indexOf(j);
|
|
895
942
|
if (i < 0) throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
943
|
+
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
944
|
return i;
|
|
897
945
|
});
|
|
898
946
|
this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
|
|
@@ -901,10 +949,13 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
901
949
|
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
902
950
|
reset() {
|
|
903
951
|
const { sim } = this;
|
|
952
|
+
if (sim.disposed) return;
|
|
953
|
+
this.generation++;
|
|
904
954
|
sim.reset();
|
|
905
955
|
const d = sim.data;
|
|
906
956
|
d.qpos[2] = .79;
|
|
907
957
|
for (let j = 0; j < 29; j++) d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
|
|
958
|
+
sim.forward();
|
|
908
959
|
this.targets = SONIC_JOINTS.defaults.slice();
|
|
909
960
|
this.last.fill(0);
|
|
910
961
|
this.carry = 0;
|
|
@@ -934,9 +985,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
934
985
|
])
|
|
935
986
|
};
|
|
936
987
|
}
|
|
937
|
-
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
|
|
988
|
+
/** 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
989
|
async tick() {
|
|
990
|
+
if (this.sim.disposed) return;
|
|
939
991
|
const d = this.sim.data;
|
|
992
|
+
const gen = this.generation;
|
|
940
993
|
const t0 = performance.now();
|
|
941
994
|
this.history.add(this.state(), this.last);
|
|
942
995
|
const anchor = anchorSix([
|
|
@@ -946,6 +999,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
946
999
|
d.qpos[6]
|
|
947
1000
|
]);
|
|
948
1001
|
const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
|
|
1002
|
+
if (gen !== this.generation || this.sim.disposed) return;
|
|
949
1003
|
this.inferenceMs = performance.now() - t0;
|
|
950
1004
|
this.last = Float32Array.from(a);
|
|
951
1005
|
const pi = SONIC_JOINTS.policyIndex;
|
|
@@ -958,13 +1012,17 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
958
1012
|
}
|
|
959
1013
|
});
|
|
960
1014
|
}
|
|
961
|
-
/**
|
|
1015
|
+
/**
|
|
1016
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
1017
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
1018
|
+
*/
|
|
962
1019
|
async advance(seconds) {
|
|
1020
|
+
if (this.sim.disposed) return 0;
|
|
1021
|
+
const per = 1 / SONIC.hz;
|
|
1022
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), .1);
|
|
963
1023
|
if (this.busy) return 0;
|
|
964
1024
|
this.busy = true;
|
|
965
1025
|
try {
|
|
966
|
-
const per = 1 / SONIC.hz;
|
|
967
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), .1);
|
|
968
1026
|
const n = Math.floor(this.carry / per + 1e-6);
|
|
969
1027
|
for (let i = 0; i < n; i++) await this.tick();
|
|
970
1028
|
this.carry = Math.max(0, this.carry - n * per);
|
|
@@ -997,4 +1055,4 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
997
1055
|
exports.referencedFiles = referencedFiles;
|
|
998
1056
|
exports.toPolicyOrder = toPolicyOrder;
|
|
999
1057
|
return exports;
|
|
1000
|
-
})({}, THREE);
|
|
1058
|
+
})({}, globalThis.THREE);
|
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
|
@@ -121,9 +121,11 @@ export interface SonicOptions {
|
|
|
121
121
|
ort?: Ort;
|
|
122
122
|
/** Where to load onnxruntime-web from. Default {@link ORT_URL}; its wasm is read beside it. */
|
|
123
123
|
ortUrl?: string;
|
|
124
|
-
/** The encoder
|
|
124
|
+
/** The encoder as a URL or bytes. Default {@link SONIC}'s pinned URL. */
|
|
125
125
|
encoder?: string | Uint8Array | ArrayBuffer;
|
|
126
|
+
/** The decoder as a URL or bytes. Default {@link SONIC}'s pinned URL. */
|
|
126
127
|
decoder?: string | Uint8Array | ArrayBuffer;
|
|
128
|
+
/** The fetch the policy files load through. Default the page's own. */
|
|
127
129
|
fetch?: typeof fetch;
|
|
128
130
|
/** Called with {@link SONIC}'s licence line when the weights load. */
|
|
129
131
|
onLicence?: (line: string) => void;
|
|
@@ -160,14 +162,19 @@ export declare class SonicDriver {
|
|
|
160
162
|
private carry;
|
|
161
163
|
private busy;
|
|
162
164
|
private perTick;
|
|
165
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
166
|
+
private generation;
|
|
163
167
|
constructor(sonic: Sonic, sim: Humanoid);
|
|
164
168
|
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
165
169
|
reset(): void;
|
|
166
170
|
/** The robot's state this tick, in the policy's order. */
|
|
167
171
|
state(): SonicState;
|
|
168
|
-
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
|
|
172
|
+
/** 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
173
|
tick(): Promise<void>;
|
|
170
|
-
/**
|
|
174
|
+
/**
|
|
175
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
176
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
177
|
+
*/
|
|
171
178
|
advance(seconds: number): Promise<number>;
|
|
172
179
|
}
|
|
173
180
|
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.2",
|
|
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",
|