Mike0021 commited on
Commit
f8e35e1
·
verified ·
1 Parent(s): 2ed92b5

MotionBricks Playground: G1 in the browser

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/g1.glb filter=lfs diff=lfs merge=lfs -text
37
+ assets/g1_lite.glb filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,10 +1,81 @@
1
  ---
2
- title: Motionbricks Playground
3
- emoji: 🌍
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: static
 
7
  pinned: false
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: MotionBricks Playground
3
+ emoji: 🤖
4
+ colorFrom: indigo
5
+ colorTo: green
6
  sdk: static
7
+ app_file: index.html
8
  pinned: false
9
+ license: other
10
+ short_description: NVIDIA MotionBricks live in your browser (Unitree G1)
11
+ custom_headers:
12
+ cross-origin-embedder-policy: require-corp
13
+ cross-origin-opener-policy: same-origin
14
+ cross-origin-resource-policy: cross-origin
15
+ models:
16
+ - nvidia/MotionBricks
17
+ tags:
18
+ - motion-generation
19
+ - robotics
20
+ - onnxruntime-web
21
+ - three.js
22
  ---
23
 
24
+ # MotionBricks Playground
25
+
26
+ Drive a Unitree G1 humanoid whose every step is generated in real time by
27
+ [NVIDIA MotionBricks](https://github.com/NVlabs/motionbricks), entirely in your browser.
28
+
29
+ - **The model runs locally.** The official 195M-parameter G1 ONNX model (mixed FP16, 369 MB)
30
+ runs with ONNX Runtime Web (WASM, multi-threaded) in a Web Worker. A generation takes roughly
31
+ 50–250 ms depending on your CPU, and each one produces 0.6–1.9 s of motion.
32
+ - **Continuous locomotion.** Forward (walk → run), strafing, crouching and six styles
33
+ (Skipping, Vogue, Injured Torso, Injured Leg, Zombie, Combat). Targets are blended from a few
34
+ poses and placed ahead of the robot; the model fills in everything else.
35
+ - **Smart Primitives.** Walk into the Jump, Vault, Duck-under and Sit objects: target poses
36
+ authored around each object are aligned to your approach and the model generates the motion
37
+ through them.
38
+ - **See what the model sees.** Context poses (violet), target poses (teal), the generated root
39
+ path, transition points, foot contacts and a live generation log.
40
+
41
+ ## Controls
42
+
43
+ | Action | Keys |
44
+ | --- | --- |
45
+ | Move (camera relative) | W A S D / arrows, or click the floor (double-click to run) |
46
+ | Run | Shift (or Space) |
47
+ | Interact / stand up | E |
48
+ | Strafe / crouch / next style | Q / C / [ |
49
+ | Modes and styles | 1–9 |
50
+ | Camera | drag to orbit, scroll to zoom |
51
+
52
+ ## How it works
53
+
54
+ This is an independent JavaScript port of the MotionBricks G1 runtime (`motionbricks/model/unitree_g1`,
55
+ `motionbricks/runtime`, `app/runtime`): context/target encoding, decoding with root filtering and
56
+ endpoint correction, the motion recorder, blend spaces, movement springs, the idle / locomotion /
57
+ interaction state machine, pivots and Smart Primitive behaviors. The encode/decode path was checked
58
+ against a NumPy port to 1e-7.
59
+
60
+ The reference runtime generates synchronously in ~3 ms with TensorRT. In the browser a generation
61
+ takes 30–80× longer, so every request predicts the moment its motion will take over (now + measured
62
+ latency), builds the four context poses from what the robot will have shown by then, and places targets
63
+ and evaluates interactions from the robot's predicted position. When a result is on time the switch
64
+ is seamless; when it is late, a 0.15 s crossfade hides the gap.
65
+
66
+ ## Credits and licenses
67
+
68
+ - MotionBricks: Wang et al., *MotionBricks: Scalable Real-Time Motions with Modular Latent Generative
69
+ Model and Smart Primitives*, ACM TOG 45(4), SIGGRAPH 2026. [Paper](https://arxiv.org/abs/2604.24833) ·
70
+ [Code](https://github.com/NVlabs/motionbricks) · [Weights](https://huggingface.co/nvidia/MotionBricks)
71
+ - `models/mmm_v6_g1_fp16.onnx` is the unmodified ONNX model from the MotionBricks repository.
72
+ Licensed by NVIDIA Corporation under the
73
+ [NVIDIA Open Model Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-agreement/).
74
+ - Runtime code in this Space is ported from the Apache-2.0 MotionBricks code (see `licenses/`).
75
+ - Robot meshes are converted from the Unitree G1 model, © Unitree Robotics, BSD-3-Clause (see `licenses/`).
76
+ - The sample motion clips that the target poses are sampled from are **not** included here. The page
77
+ streams them at runtime from NVIDIA's repository (pinned commit), where they are provided under the
78
+ NVIDIA Sample Data Evaluation License for evaluating NVIDIA technologies.
79
+
80
+ This demo is not affiliated with or endorsed by NVIDIA or Unitree. Generated motion is kinematic and is
81
+ not a controller for a physical robot.
assets/g1.glb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a07d5fcf86b5d5ec2195c571b4a3df1de9235692f3cb9ad096e86763827df95
3
+ size 2262720
assets/g1_kinematics.json ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bodies": [
3
+ {
4
+ "name": "pelvis",
5
+ "parent": -1,
6
+ "pos": [
7
+ 0.0,
8
+ 0.0,
9
+ 0.793
10
+ ],
11
+ "quat_xyzw": [
12
+ 0.0,
13
+ 0.0,
14
+ 0.0,
15
+ 1.0
16
+ ],
17
+ "meshes": [
18
+ "pelvis__dark",
19
+ "pelvis__light"
20
+ ]
21
+ },
22
+ {
23
+ "name": "left_hip_pitch_link",
24
+ "parent": 0,
25
+ "pos": [
26
+ 0.0,
27
+ 0.064452,
28
+ -0.1027
29
+ ],
30
+ "quat_xyzw": [
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 1.0
35
+ ],
36
+ "joint": "left_hip_pitch_joint",
37
+ "axis": [
38
+ 0.0,
39
+ 1.0,
40
+ 0.0
41
+ ],
42
+ "meshes": [
43
+ "left_hip_pitch_link__dark"
44
+ ],
45
+ "dof": 0
46
+ },
47
+ {
48
+ "name": "left_hip_roll_link",
49
+ "parent": 1,
50
+ "pos": [
51
+ 0.0,
52
+ 0.052,
53
+ -0.030465
54
+ ],
55
+ "quat_xyzw": [
56
+ 0.0,
57
+ -0.0873386,
58
+ 0.0,
59
+ 0.996179
60
+ ],
61
+ "joint": "left_hip_roll_joint",
62
+ "axis": [
63
+ 1.0,
64
+ 0.0,
65
+ 0.0
66
+ ],
67
+ "meshes": [
68
+ "left_hip_roll_link__light"
69
+ ],
70
+ "dof": 1
71
+ },
72
+ {
73
+ "name": "left_hip_yaw_link",
74
+ "parent": 2,
75
+ "pos": [
76
+ 0.025001,
77
+ 0.0,
78
+ -0.12412
79
+ ],
80
+ "quat_xyzw": [
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 1.0
85
+ ],
86
+ "joint": "left_hip_yaw_joint",
87
+ "axis": [
88
+ 0.0,
89
+ 0.0,
90
+ 1.0
91
+ ],
92
+ "meshes": [
93
+ "left_hip_yaw_link__light"
94
+ ],
95
+ "dof": 2
96
+ },
97
+ {
98
+ "name": "left_knee_link",
99
+ "parent": 3,
100
+ "pos": [
101
+ -0.078273,
102
+ 0.0021489,
103
+ -0.17734
104
+ ],
105
+ "quat_xyzw": [
106
+ 0.0,
107
+ 0.0873386,
108
+ 0.0,
109
+ 0.996179
110
+ ],
111
+ "joint": "left_knee_joint",
112
+ "axis": [
113
+ 0.0,
114
+ 1.0,
115
+ 0.0
116
+ ],
117
+ "meshes": [
118
+ "left_knee_link__light"
119
+ ],
120
+ "dof": 3
121
+ },
122
+ {
123
+ "name": "left_ankle_pitch_link",
124
+ "parent": 4,
125
+ "pos": [
126
+ 0.0,
127
+ -9.4445e-05,
128
+ -0.30001
129
+ ],
130
+ "quat_xyzw": [
131
+ 0.0,
132
+ 0.0,
133
+ 0.0,
134
+ 1.0
135
+ ],
136
+ "joint": "left_ankle_pitch_joint",
137
+ "axis": [
138
+ 0.0,
139
+ 1.0,
140
+ 0.0
141
+ ],
142
+ "meshes": [
143
+ "left_ankle_pitch_link__light"
144
+ ],
145
+ "dof": 4
146
+ },
147
+ {
148
+ "name": "left_ankle_roll_link",
149
+ "parent": 5,
150
+ "pos": [
151
+ 0.0,
152
+ 0.0,
153
+ -0.017558
154
+ ],
155
+ "quat_xyzw": [
156
+ 0.0,
157
+ 0.0,
158
+ 0.0,
159
+ 1.0
160
+ ],
161
+ "joint": "left_ankle_roll_joint",
162
+ "axis": [
163
+ 1.0,
164
+ 0.0,
165
+ 0.0
166
+ ],
167
+ "meshes": [
168
+ "left_ankle_roll_link__dark"
169
+ ],
170
+ "dof": 5
171
+ },
172
+ {
173
+ "name": "right_hip_pitch_link",
174
+ "parent": 0,
175
+ "pos": [
176
+ 0.0,
177
+ -0.064452,
178
+ -0.1027
179
+ ],
180
+ "quat_xyzw": [
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 1.0
185
+ ],
186
+ "joint": "right_hip_pitch_joint",
187
+ "axis": [
188
+ 0.0,
189
+ 1.0,
190
+ 0.0
191
+ ],
192
+ "meshes": [
193
+ "right_hip_pitch_link__dark"
194
+ ],
195
+ "dof": 6
196
+ },
197
+ {
198
+ "name": "right_hip_roll_link",
199
+ "parent": 7,
200
+ "pos": [
201
+ 0.0,
202
+ -0.052,
203
+ -0.030465
204
+ ],
205
+ "quat_xyzw": [
206
+ 0.0,
207
+ -0.0873386,
208
+ 0.0,
209
+ 0.996179
210
+ ],
211
+ "joint": "right_hip_roll_joint",
212
+ "axis": [
213
+ 1.0,
214
+ 0.0,
215
+ 0.0
216
+ ],
217
+ "meshes": [
218
+ "right_hip_roll_link__light"
219
+ ],
220
+ "dof": 7
221
+ },
222
+ {
223
+ "name": "right_hip_yaw_link",
224
+ "parent": 8,
225
+ "pos": [
226
+ 0.025001,
227
+ 0.0,
228
+ -0.12412
229
+ ],
230
+ "quat_xyzw": [
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 1.0
235
+ ],
236
+ "joint": "right_hip_yaw_joint",
237
+ "axis": [
238
+ 0.0,
239
+ 0.0,
240
+ 1.0
241
+ ],
242
+ "meshes": [
243
+ "right_hip_yaw_link__light"
244
+ ],
245
+ "dof": 8
246
+ },
247
+ {
248
+ "name": "right_knee_link",
249
+ "parent": 9,
250
+ "pos": [
251
+ -0.078273,
252
+ -0.0021489,
253
+ -0.17734
254
+ ],
255
+ "quat_xyzw": [
256
+ 0.0,
257
+ 0.0873386,
258
+ 0.0,
259
+ 0.996179
260
+ ],
261
+ "joint": "right_knee_joint",
262
+ "axis": [
263
+ 0.0,
264
+ 1.0,
265
+ 0.0
266
+ ],
267
+ "meshes": [
268
+ "right_knee_link__light"
269
+ ],
270
+ "dof": 9
271
+ },
272
+ {
273
+ "name": "right_ankle_pitch_link",
274
+ "parent": 10,
275
+ "pos": [
276
+ 0.0,
277
+ 9.4445e-05,
278
+ -0.30001
279
+ ],
280
+ "quat_xyzw": [
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 1.0
285
+ ],
286
+ "joint": "right_ankle_pitch_joint",
287
+ "axis": [
288
+ 0.0,
289
+ 1.0,
290
+ 0.0
291
+ ],
292
+ "meshes": [
293
+ "right_ankle_pitch_link__light"
294
+ ],
295
+ "dof": 10
296
+ },
297
+ {
298
+ "name": "right_ankle_roll_link",
299
+ "parent": 11,
300
+ "pos": [
301
+ 0.0,
302
+ 0.0,
303
+ -0.017558
304
+ ],
305
+ "quat_xyzw": [
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 1.0
310
+ ],
311
+ "joint": "right_ankle_roll_joint",
312
+ "axis": [
313
+ 1.0,
314
+ 0.0,
315
+ 0.0
316
+ ],
317
+ "meshes": [
318
+ "right_ankle_roll_link__dark"
319
+ ],
320
+ "dof": 11
321
+ },
322
+ {
323
+ "name": "waist_yaw_link",
324
+ "parent": 0,
325
+ "pos": [
326
+ 0.0,
327
+ 0.0,
328
+ 0.0
329
+ ],
330
+ "quat_xyzw": [
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 1.0
335
+ ],
336
+ "joint": "waist_yaw_joint",
337
+ "axis": [
338
+ 0.0,
339
+ 0.0,
340
+ 1.0
341
+ ],
342
+ "meshes": [
343
+ "waist_yaw_link__light"
344
+ ],
345
+ "dof": 12
346
+ },
347
+ {
348
+ "name": "waist_roll_link",
349
+ "parent": 13,
350
+ "pos": [
351
+ -0.0039635,
352
+ 0.0,
353
+ 0.044
354
+ ],
355
+ "quat_xyzw": [
356
+ 0.0,
357
+ 0.0,
358
+ 0.0,
359
+ 1.0
360
+ ],
361
+ "joint": "waist_roll_joint",
362
+ "axis": [
363
+ 1.0,
364
+ 0.0,
365
+ 0.0
366
+ ],
367
+ "meshes": [
368
+ "waist_roll_link__light"
369
+ ],
370
+ "dof": 13
371
+ },
372
+ {
373
+ "name": "torso_link",
374
+ "parent": 14,
375
+ "pos": [
376
+ 0.0,
377
+ 0.0,
378
+ 0.0
379
+ ],
380
+ "quat_xyzw": [
381
+ 0.0,
382
+ 0.0,
383
+ 0.0,
384
+ 1.0
385
+ ],
386
+ "joint": "waist_pitch_joint",
387
+ "axis": [
388
+ 0.0,
389
+ 1.0,
390
+ 0.0
391
+ ],
392
+ "meshes": [
393
+ "torso_link__light",
394
+ "torso_link__dark"
395
+ ],
396
+ "dof": 14
397
+ },
398
+ {
399
+ "name": "left_shoulder_pitch_link",
400
+ "parent": 15,
401
+ "pos": [
402
+ 0.0039563,
403
+ 0.10022,
404
+ 0.24778
405
+ ],
406
+ "quat_xyzw": [
407
+ 0.139201,
408
+ 1.38722e-05,
409
+ -9.86868e-05,
410
+ 0.990264
411
+ ],
412
+ "joint": "left_shoulder_pitch_joint",
413
+ "axis": [
414
+ 0.0,
415
+ 1.0,
416
+ 0.0
417
+ ],
418
+ "meshes": [
419
+ "left_shoulder_pitch_link__light"
420
+ ],
421
+ "dof": 15
422
+ },
423
+ {
424
+ "name": "left_shoulder_roll_link",
425
+ "parent": 16,
426
+ "pos": [
427
+ 0.0,
428
+ 0.038,
429
+ -0.013831
430
+ ],
431
+ "quat_xyzw": [
432
+ -0.139172,
433
+ 0.0,
434
+ 0.0,
435
+ 0.990268
436
+ ],
437
+ "joint": "left_shoulder_roll_joint",
438
+ "axis": [
439
+ 1.0,
440
+ 0.0,
441
+ 0.0
442
+ ],
443
+ "meshes": [
444
+ "left_shoulder_roll_link__light"
445
+ ],
446
+ "dof": 16
447
+ },
448
+ {
449
+ "name": "left_shoulder_yaw_link",
450
+ "parent": 17,
451
+ "pos": [
452
+ 0.0,
453
+ 0.00624,
454
+ -0.1032
455
+ ],
456
+ "quat_xyzw": [
457
+ 0.0,
458
+ 0.0,
459
+ 0.0,
460
+ 1.0
461
+ ],
462
+ "joint": "left_shoulder_yaw_joint",
463
+ "axis": [
464
+ 0.0,
465
+ 0.0,
466
+ 1.0
467
+ ],
468
+ "meshes": [
469
+ "left_shoulder_yaw_link__light"
470
+ ],
471
+ "dof": 17
472
+ },
473
+ {
474
+ "name": "left_elbow_link",
475
+ "parent": 18,
476
+ "pos": [
477
+ 0.015783,
478
+ 0.0,
479
+ -0.080518
480
+ ],
481
+ "quat_xyzw": [
482
+ 0.0,
483
+ 0.0,
484
+ 0.0,
485
+ 1.0
486
+ ],
487
+ "joint": "left_elbow_joint",
488
+ "axis": [
489
+ 0.0,
490
+ 1.0,
491
+ 0.0
492
+ ],
493
+ "meshes": [
494
+ "left_elbow_link__light"
495
+ ],
496
+ "dof": 18
497
+ },
498
+ {
499
+ "name": "left_wrist_roll_link",
500
+ "parent": 19,
501
+ "pos": [
502
+ 0.1,
503
+ 0.00188791,
504
+ -0.01
505
+ ],
506
+ "quat_xyzw": [
507
+ 0.0,
508
+ 0.0,
509
+ 0.0,
510
+ 1.0
511
+ ],
512
+ "joint": "left_wrist_roll_joint",
513
+ "axis": [
514
+ 1.0,
515
+ 0.0,
516
+ 0.0
517
+ ],
518
+ "meshes": [
519
+ "left_wrist_roll_link__light"
520
+ ],
521
+ "dof": 19
522
+ },
523
+ {
524
+ "name": "left_wrist_pitch_link",
525
+ "parent": 20,
526
+ "pos": [
527
+ 0.038,
528
+ 0.0,
529
+ 0.0
530
+ ],
531
+ "quat_xyzw": [
532
+ 0.0,
533
+ 0.0,
534
+ 0.0,
535
+ 1.0
536
+ ],
537
+ "joint": "left_wrist_pitch_joint",
538
+ "axis": [
539
+ 0.0,
540
+ 1.0,
541
+ 0.0
542
+ ],
543
+ "meshes": [
544
+ "left_wrist_pitch_link__light"
545
+ ],
546
+ "dof": 20
547
+ },
548
+ {
549
+ "name": "left_wrist_yaw_link",
550
+ "parent": 21,
551
+ "pos": [
552
+ 0.046,
553
+ 0.0,
554
+ 0.0
555
+ ],
556
+ "quat_xyzw": [
557
+ 0.0,
558
+ 0.0,
559
+ 0.0,
560
+ 1.0
561
+ ],
562
+ "joint": "left_wrist_yaw_joint",
563
+ "axis": [
564
+ 0.0,
565
+ 0.0,
566
+ 1.0
567
+ ],
568
+ "meshes": [
569
+ "left_wrist_yaw_link__light"
570
+ ],
571
+ "dof": 21
572
+ },
573
+ {
574
+ "name": "right_shoulder_pitch_link",
575
+ "parent": 15,
576
+ "pos": [
577
+ 0.0039563,
578
+ -0.10021,
579
+ 0.24778
580
+ ],
581
+ "quat_xyzw": [
582
+ -0.139201,
583
+ 1.38722e-05,
584
+ 9.86868e-05,
585
+ 0.990264
586
+ ],
587
+ "joint": "right_shoulder_pitch_joint",
588
+ "axis": [
589
+ 0.0,
590
+ 1.0,
591
+ 0.0
592
+ ],
593
+ "meshes": [
594
+ "right_shoulder_pitch_link__light"
595
+ ],
596
+ "dof": 22
597
+ },
598
+ {
599
+ "name": "right_shoulder_roll_link",
600
+ "parent": 23,
601
+ "pos": [
602
+ 0.0,
603
+ -0.038,
604
+ -0.013831
605
+ ],
606
+ "quat_xyzw": [
607
+ 0.139172,
608
+ 0.0,
609
+ 0.0,
610
+ 0.990268
611
+ ],
612
+ "joint": "right_shoulder_roll_joint",
613
+ "axis": [
614
+ 1.0,
615
+ 0.0,
616
+ 0.0
617
+ ],
618
+ "meshes": [
619
+ "right_shoulder_roll_link__light"
620
+ ],
621
+ "dof": 23
622
+ },
623
+ {
624
+ "name": "right_shoulder_yaw_link",
625
+ "parent": 24,
626
+ "pos": [
627
+ 0.0,
628
+ -0.00624,
629
+ -0.1032
630
+ ],
631
+ "quat_xyzw": [
632
+ 0.0,
633
+ 0.0,
634
+ 0.0,
635
+ 1.0
636
+ ],
637
+ "joint": "right_shoulder_yaw_joint",
638
+ "axis": [
639
+ 0.0,
640
+ 0.0,
641
+ 1.0
642
+ ],
643
+ "meshes": [
644
+ "right_shoulder_yaw_link__light"
645
+ ],
646
+ "dof": 24
647
+ },
648
+ {
649
+ "name": "right_elbow_link",
650
+ "parent": 25,
651
+ "pos": [
652
+ 0.015783,
653
+ 0.0,
654
+ -0.080518
655
+ ],
656
+ "quat_xyzw": [
657
+ 0.0,
658
+ 0.0,
659
+ 0.0,
660
+ 1.0
661
+ ],
662
+ "joint": "right_elbow_joint",
663
+ "axis": [
664
+ 0.0,
665
+ 1.0,
666
+ 0.0
667
+ ],
668
+ "meshes": [
669
+ "right_elbow_link__light"
670
+ ],
671
+ "dof": 25
672
+ },
673
+ {
674
+ "name": "right_wrist_roll_link",
675
+ "parent": 26,
676
+ "pos": [
677
+ 0.1,
678
+ -0.00188791,
679
+ -0.01
680
+ ],
681
+ "quat_xyzw": [
682
+ 0.0,
683
+ 0.0,
684
+ 0.0,
685
+ 1.0
686
+ ],
687
+ "joint": "right_wrist_roll_joint",
688
+ "axis": [
689
+ 1.0,
690
+ 0.0,
691
+ 0.0
692
+ ],
693
+ "meshes": [
694
+ "right_wrist_roll_link__light"
695
+ ],
696
+ "dof": 26
697
+ },
698
+ {
699
+ "name": "right_wrist_pitch_link",
700
+ "parent": 27,
701
+ "pos": [
702
+ 0.038,
703
+ 0.0,
704
+ 0.0
705
+ ],
706
+ "quat_xyzw": [
707
+ 0.0,
708
+ 0.0,
709
+ 0.0,
710
+ 1.0
711
+ ],
712
+ "joint": "right_wrist_pitch_joint",
713
+ "axis": [
714
+ 0.0,
715
+ 1.0,
716
+ 0.0
717
+ ],
718
+ "meshes": [
719
+ "right_wrist_pitch_link__light"
720
+ ],
721
+ "dof": 27
722
+ },
723
+ {
724
+ "name": "right_wrist_yaw_link",
725
+ "parent": 28,
726
+ "pos": [
727
+ 0.046,
728
+ 0.0,
729
+ 0.0
730
+ ],
731
+ "quat_xyzw": [
732
+ 0.0,
733
+ 0.0,
734
+ 0.0,
735
+ 1.0
736
+ ],
737
+ "joint": "right_wrist_yaw_joint",
738
+ "axis": [
739
+ 0.0,
740
+ 0.0,
741
+ 1.0
742
+ ],
743
+ "meshes": [
744
+ "right_wrist_yaw_link__light"
745
+ ],
746
+ "dof": 28
747
+ }
748
+ ],
749
+ "joint_names": [
750
+ "left_hip_pitch_joint",
751
+ "left_hip_roll_joint",
752
+ "left_hip_yaw_joint",
753
+ "left_knee_joint",
754
+ "left_ankle_pitch_joint",
755
+ "left_ankle_roll_joint",
756
+ "right_hip_pitch_joint",
757
+ "right_hip_roll_joint",
758
+ "right_hip_yaw_joint",
759
+ "right_knee_joint",
760
+ "right_ankle_pitch_joint",
761
+ "right_ankle_roll_joint",
762
+ "waist_yaw_joint",
763
+ "waist_roll_joint",
764
+ "waist_pitch_joint",
765
+ "left_shoulder_pitch_joint",
766
+ "left_shoulder_roll_joint",
767
+ "left_shoulder_yaw_joint",
768
+ "left_elbow_joint",
769
+ "left_wrist_roll_joint",
770
+ "left_wrist_pitch_joint",
771
+ "left_wrist_yaw_joint",
772
+ "right_shoulder_pitch_joint",
773
+ "right_shoulder_roll_joint",
774
+ "right_shoulder_yaw_joint",
775
+ "right_elbow_joint",
776
+ "right_wrist_roll_joint",
777
+ "right_wrist_pitch_joint",
778
+ "right_wrist_yaw_joint"
779
+ ]
780
+ }
assets/g1_lite.glb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7dd829cedca41b9c23caf57db1131fa8c46f64e2e9da45a13b99de3a50dceef5
3
+ size 830460
css/style.css ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #0d0f14;
3
+ --panel: rgba(20, 23, 30, 0.72);
4
+ --line: rgba(255, 255, 255, 0.09);
5
+ --text: #e8eaee;
6
+ --muted: #9aa1ad;
7
+ --accent: #5eead4;
8
+ --ctx: #a78bfa;
9
+ --warn: #fbbf24;
10
+ --radius: 14px;
11
+ color-scheme: dark;
12
+ }
13
+ * { box-sizing: border-box; }
14
+ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font: 14px/1.45 Inter, system-ui, sans-serif; }
15
+ #stage, #stage canvas { position: fixed; inset: 0; display: block; touch-action: none; }
16
+ .glass { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); }
17
+ kbd { font: 600 11px 'JetBrains Mono', monospace; padding: 1px 5px; border-radius: 5px; border: 1px solid var(--line); background: rgba(255,255,255,0.06); color: var(--muted); }
18
+ button { font: inherit; color: inherit; cursor: pointer; }
19
+
20
+ #title { position: fixed; top: 18px; left: 22px; pointer-events: none; text-shadow: 0 2px 12px rgba(0,0,0,0.6); }
21
+ #title .brand { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; display: flex; align-items: center; gap: 10px; }
22
+ #title .brand small { font-weight: 500; color: var(--muted); font-size: 22px; }
23
+ #title .logo { width: 20px; height: 20px; border-radius: 5px; background: conic-gradient(from 45deg, var(--accent), var(--ctx), var(--accent)); box-shadow: 0 0 18px rgba(94,234,212,0.45); }
24
+ #title .sub { color: var(--muted); margin-top: 2px; font-size: 13px; }
25
+
26
+ #stats { position: fixed; top: 18px; right: 18px; display: flex; gap: 18px; padding: 10px 16px; }
27
+ #stats div { display: flex; flex-direction: column; min-width: 64px; }
28
+ #stats label { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); }
29
+ #stats span { font: 600 14px 'JetBrains Mono', monospace; white-space: nowrap; }
30
+ #stats #state { font-family: Inter, sans-serif; }
31
+ .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: rgba(255,255,255,0.15); margin-left: 4px; transition: background 0.1s; }
32
+ .dot.on { background: var(--accent); box-shadow: 0 0 10px var(--accent); }
33
+
34
+ #panel { position: fixed; left: 18px; top: 92px; width: 268px; max-height: calc(100% - 210px); overflow: auto; padding: 12px 14px 14px; transition: transform 0.25s, opacity 0.25s; }
35
+ #panel h3 { margin: 12px 0 7px; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); font-weight: 600; }
36
+ #panel h3:first-of-type { margin-top: 2px; }
37
+ #panel-toggle { position: absolute; top: 8px; right: 8px; border: 0; background: none; color: var(--muted); font-size: 16px; }
38
+ body.panel-collapsed #panel { transform: translateX(-232px); opacity: 0.85; }
39
+ body.panel-collapsed #panel .panel-body { visibility: hidden; }
40
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
41
+ .chips button { border: 1px solid var(--line); background: rgba(255,255,255,0.04); padding: 5px 9px; border-radius: 999px; font-size: 12.5px; display: inline-flex; gap: 6px; align-items: center; transition: all 0.12s; }
42
+ .chips button kbd { padding: 0 4px; font-size: 10px; }
43
+ .chips button:hover { border-color: rgba(255,255,255,0.25); }
44
+ .chips button.on { background: var(--accent); color: #062b25; border-color: var(--accent); font-weight: 600; }
45
+ .chips button.on kbd { color: #062b25; border-color: rgba(6,43,37,0.3); }
46
+ #toggles label { display: flex; align-items: center; gap: 8px; padding: 3px 0; color: #cfd3da; font-size: 13px; cursor: pointer; }
47
+ #toggles input { accent-color: var(--accent); }
48
+ ul.keys { list-style: none; padding: 0; margin: 0; color: #c3c8d0; font-size: 12.5px; }
49
+ ul.keys li { margin: 4px 0; }
50
+ .note { color: var(--muted); font-size: 12.5px; margin: 12px 0 0; }
51
+ .note b { color: var(--text); }
52
+
53
+ #log { position: fixed; right: 18px; top: 84px; width: 330px; font: 12px 'JetBrains Mono', monospace; color: #cbd5e1; text-align: right; pointer-events: none; }
54
+ #log div { padding: 3px 0; text-shadow: 0 1px 8px rgba(0,0,0,0.8); }
55
+ #log b { color: var(--accent); font-weight: 600; }
56
+
57
+ #timeline-wrap { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); width: min(560px, calc(100% - 36px)); padding: 10px 14px 9px; }
58
+ #timeline { position: relative; height: 10px; border-radius: 6px; background: linear-gradient(90deg, rgba(94,234,212,0.25), rgba(94,234,212,0.45)); overflow: visible; }
59
+ #timeline .ctx { position: absolute; left: -8px; top: 0; width: 8px; height: 10px; border-radius: 4px 0 0 4px; background: var(--ctx); }
60
+ #timeline .play { position: absolute; top: -4px; left: var(--play, 0%); width: 3px; height: 18px; background: #fff; border-radius: 2px; transform: translateX(-1px); box-shadow: 0 0 8px rgba(255,255,255,0.8); }
61
+ #timeline .trans { position: absolute; top: -2px; left: var(--trans, 100%); width: 10px; height: 14px; border-radius: 3px; border: 2px solid var(--accent); transform: translateX(-5px); }
62
+ #timeline.idle { background: rgba(255,255,255,0.08); }
63
+ #timeline.idle i { display: none; }
64
+ #tl-label { margin-top: 6px; font: 12px 'JetBrains Mono', monospace; color: #cbd5e1; text-align: center; }
65
+ .legend { display: flex; gap: 14px; justify-content: center; margin-top: 4px; font-size: 11px; color: var(--muted); }
66
+ .legend span::before { content: ''; display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 5px; vertical-align: -0.5px; }
67
+ .legend .l-ctx::before { background: var(--ctx); }
68
+ .legend .l-tgt::before { background: var(--accent); }
69
+ .legend .l-plan::before { background: var(--accent); height: 2px; vertical-align: 2px; }
70
+ .legend .l-tr::before { border: 2px solid var(--accent); background: none; width: 5px; height: 5px; }
71
+
72
+ #loading { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(520px, calc(100% - 32px)); padding: 26px 26px 20px; z-index: 10; transition: opacity 0.4s, transform 0.4s; }
73
+ #loading h1 { margin: 0 0 8px; font-size: 26px; letter-spacing: -0.02em; }
74
+ #loading h1 span { color: var(--accent); }
75
+ #loading p { color: #c3c8d0; margin: 0 0 16px; }
76
+ #loading .small, .small { font-size: 12px; color: var(--muted); }
77
+ .loadrow { display: grid; grid-template-columns: 120px 1fr 150px; align-items: center; gap: 10px; margin: 10px 0; font-size: 13px; }
78
+ .loadrow b { height: 6px; background: rgba(255,255,255,0.08); border-radius: 4px; overflow: hidden; }
79
+ .loadrow i { display: block; height: 100%; width: 0; background: var(--accent); transition: width 0.2s; }
80
+ .loadrow em { font: 11.5px 'JetBrains Mono', monospace; color: var(--muted); font-style: normal; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
81
+ .loadrow.err em, .err { color: #f87171; }
82
+ #start { margin-top: 6px; border: 1px solid var(--line); background: rgba(255,255,255,0.06); padding: 8px 14px; border-radius: 10px; }
83
+ body:not(.world-ready) #start { visibility: hidden; }
84
+ body.model-ready #loading, body.dismissed #loading { opacity: 0; transform: translate(-50%, -46%); pointer-events: none; }
85
+
86
+ #credits { position: fixed; right: 18px; bottom: 18px; color: var(--muted); font-size: 12px; text-decoration: none; }
87
+ #about { position: fixed; right: 18px; bottom: 44px; width: min(420px, calc(100% - 36px)); padding: 16px 18px; display: none; z-index: 12; }
88
+ #about.open { display: block; }
89
+ #about h3 { margin: 0 0 8px; }
90
+ #about p { color: #c3c8d0; font-size: 13px; margin: 0 0 10px; }
91
+ #about a { color: var(--accent); }
92
+ #about button { border: 1px solid var(--line); background: rgba(255,255,255,0.06); padding: 6px 12px; border-radius: 8px; }
93
+
94
+ #touch { display: none; }
95
+ @media (pointer: coarse) {
96
+ #touch { display: block; }
97
+ #joystick { position: fixed; left: 24px; bottom: 120px; width: 120px; height: 120px; border-radius: 50%; background: rgba(255,255,255,0.06); border: 1px solid var(--line); touch-action: none; }
98
+ #knob { position: absolute; left: 36px; top: 36px; width: 48px; height: 48px; border-radius: 50%; background: rgba(255,255,255,0.25); }
99
+ .touch-buttons { position: fixed; right: 18px; bottom: 120px; display: flex; flex-direction: column; gap: 10px; }
100
+ .touch-buttons button { width: 84px; height: 46px; border-radius: 12px; border: 1px solid var(--line); background: var(--panel); }
101
+ }
102
+ @media (max-width: 760px) {
103
+ #panel { top: auto; bottom: 110px; max-height: 40%; width: calc(100% - 36px); }
104
+ body:not(.panel-collapsed) #panel { }
105
+ #stats { top: auto; bottom: 96px; left: 18px; right: 18px; gap: 10px; flex-wrap: wrap; justify-content: space-between; display: none; }
106
+ #log { display: none; }
107
+ #title .brand, #title .brand small { font-size: 18px; }
108
+ .loadrow { grid-template-columns: 96px 1fr 110px; }
109
+ }
110
+
111
+ /* Capture mode: clean frame for video recording. */
112
+ body.capture #panel, body.capture #credits, body.capture #touch, body.capture #loading { display: none !important; }
index.html CHANGED
@@ -1,19 +1,91 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
6
+ <title>MotionBricks Playground</title>
7
+ <meta name="description" content="NVIDIA MotionBricks running live in your browser: drive a Unitree G1 humanoid whose every step is generated in real time by a 195M-parameter motion model.">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet" crossorigin="anonymous">
10
+ <link rel="stylesheet" href="css/style.css">
11
+ <script>window.MB_SPACE = 'Mike0021/motionbricks-playground';</script>
12
+ <script type="importmap">
13
+ { "imports": {
14
+ "three": "https://cdn.jsdelivr.net/npm/three@0.186.1/build/three.module.js",
15
+ "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.186.1/examples/jsm/"
16
+ } }
17
+ </script>
18
+ </head>
19
+ <body>
20
+ <div id="stage"></div>
21
+
22
+ <header id="title">
23
+ <div class="brand"><span class="logo"></span>MotionBricks <small>Playground</small></div>
24
+ <div class="sub">Unitree G1 · every step generated live, in your browser</div>
25
+ </header>
26
+
27
+ <section id="stats" class="glass">
28
+ <div><label>State</label><span id="state">–</span></div>
29
+ <div><label>Speed</label><span id="speed">–</span></div>
30
+ <div><label>Generations</label><span id="gens">0</span></div>
31
+ <div><label>Inference</label><span id="infer">–</span> <span id="busy" class="dot" title="generating"></span></div>
32
+ <div><label>Runtime</label><span id="threads">–</span></div>
33
+ </section>
34
+
35
+ <aside id="panel" class="glass">
36
+ <button id="panel-toggle" title="Hide panel">☰</button>
37
+ <div class="panel-body">
38
+ <h3>Locomotion</h3>
39
+ <div id="modes" class="chips"></div>
40
+ <h3>Styles</h3>
41
+ <div id="styles" class="chips"></div>
42
+ <h3>Show</h3>
43
+ <div id="toggles"></div>
44
+ <h3>Controls</h3>
45
+ <ul class="keys">
46
+ <li><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> move (camera relative)</li>
47
+ <li><kbd>Shift</kbd> run · <kbd>E</kbd> interact / stand up</li>
48
+ <li><kbd>Q</kbd> strafe · <kbd>C</kbd> crouch · <kbd>[</kbd> next style</li>
49
+ <li>Click the floor to walk there, double-click to run</li>
50
+ <li>Drag to orbit · scroll to zoom</li>
51
+ </ul>
52
+ <p class="note">Walk into the <b>Jump</b>, <b>Vault</b>, <b>Duck under</b> and <b>Sit</b> objects: Smart Primitives place target poses around them and the model generates the motion in between.</p>
53
+ </div>
54
+ </aside>
55
+
56
+ <div id="log"></div>
57
+
58
+ <footer id="timeline-wrap" class="glass">
59
+ <div id="timeline"><b class="ctx"></b><i class="play"></i><i class="trans"></i></div>
60
+ <div id="tl-label">–</div>
61
+ <div class="legend"><span class="l-ctx">context</span><span class="l-tgt">target</span><span class="l-plan">generated path</span><span class="l-tr">transition point</span></div>
62
+ </footer>
63
+
64
+ <div id="touch">
65
+ <div id="joystick"><div id="knob"></div></div>
66
+ <div class="touch-buttons"><button id="runbtn">Run</button><button id="interact">Interact</button></div>
67
+ </div>
68
+
69
+ <div id="loading" class="glass">
70
+ <h1>MotionBricks <span>in your browser</span></h1>
71
+ <p>NVIDIA's real-time motion model (195M parameters) runs locally with ONNX Runtime Web. Give it the robot's last four poses and up to four target poses; it generates the motion in between, about once a second, while you steer.</p>
72
+ <div class="loadrow" id="load-robot"><span>Robot</span><b><i></i></b><em>waiting…</em></div>
73
+ <div class="loadrow" id="load-clips"><span>Target poses</span><b><i></i></b><em>waiting…</em></div>
74
+ <div class="loadrow" id="load-model"><span>Model (369 MB)</span><b><i></i></b><em>waiting…</em></div>
75
+ <p class="small">The model downloads once and is cached by your browser. A desktop browser with 8 GB of RAM or more is recommended.</p>
76
+ <p id="load-error" class="err"></p>
77
+ <button id="start" onclick="document.body.classList.add('dismissed')">Explore while it loads</button>
78
+ </div>
79
+
80
+ <a id="credits" href="#" onclick="document.getElementById('about').classList.toggle('open');return false;">About</a>
81
+ <div id="about" class="glass">
82
+ <h3>About this demo</h3>
83
+ <p><a href="https://github.com/NVlabs/motionbricks" target="_blank" rel="noopener">MotionBricks</a> (Wang et al., SIGGRAPH 2026) is NVIDIA's modular latent generative model for real-time character and robot motion. This page is an independent browser port of its Unitree G1 runtime: the official ONNX model runs in a Web Worker with ONNX Runtime Web, and the locomotion, idle and Smart Primitive logic follows the reference Python runtime.</p>
84
+ <p>Because a browser generation takes ~50–250 ms instead of ~3 ms with TensorRT, each request predicts where the robot will be when its motion takes over and builds the context from the poses it will have shown by then.</p>
85
+ <p class="small">Model: NVIDIA Open Model Agreement. Runtime code: Apache-2.0. Sample motion clips are streamed from NVIDIA's repository under the NVIDIA Sample Data Evaluation License and are not redistributed here. Robot meshes: Unitree Robotics (BSD-3-Clause).</p>
86
+ <button onclick="document.getElementById('about').classList.remove('open')">Close</button>
87
+ </div>
88
+
89
+ <script type="module" src="js/main.js"></script>
90
+ </body>
91
  </html>
js/assets.js ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Loads the Smart Primitive documents, the G1 gym scene and the sample clips they reference.
2
+ // Clips are fetched at runtime from NVIDIA's MotionBricks repository (pinned commit), so this
3
+ // demo never rehosts the evaluation-licensed sample motions.
4
+
5
+ import { parseCsvClip } from './motion.js';
6
+ import { SmartPrimitive, clipPathsOfDocument, resolvePath, VelocityMatchingSequenceBehavior, SittingBehavior } from './primitives.js';
7
+ import { MODES, IDLE_CLIPS, CROUCH_IDLE_CLIPS, makeClipEntry, buildModeRuntimes } from './character.js';
8
+ import { xf } from './mathx.js';
9
+
10
+ export const COMMIT = '54fc563aeaaf819a753d72cc9fdc6713989cdd43';
11
+ const params = new URLSearchParams(location.search);
12
+ const LOCAL = params.get('src') === 'local';
13
+ const RAW = LOCAL ? '../repo/' : `https://raw.githubusercontent.com/NVlabs/motionbricks/${COMMIT}/`;
14
+ const MEDIA = LOCAL ? '../repo/' : `https://media.githubusercontent.com/media/NVlabs/motionbricks/${COMMIT}/`;
15
+
16
+ const SP_DIR = 'assets/smart_primitives/unitree_g1/';
17
+ const MOTION_DIR = 'assets/motions/unitree_g1/';
18
+ const SCENE = 'assets/scenes/g1_gym.scene.json';
19
+ const SIT_LOOP = 'assets/motions/unitree_g1/sitting/sit_on_chair_loop.csv';
20
+
21
+ async function getJson(path) {
22
+ const r = await fetch(RAW + path);
23
+ if (!r.ok) throw new Error(`${r.status} ${path}`);
24
+ return r.json();
25
+ }
26
+ async function getClip(path) {
27
+ const r = await fetch(MEDIA + path);
28
+ if (!r.ok) throw new Error(`${r.status} ${path}`);
29
+ return parseCsvClip(await r.text(), path.split('/').pop());
30
+ }
31
+
32
+ export async function loadWorld(onProgress = () => {}) {
33
+ const scene = await getJson(SCENE);
34
+ const docNames = new Set(MODES.map((m) => m.doc));
35
+ for (const inst of scene.smart_primitives) docNames.add(inst.reference.split('/').pop().replace('.smart_primitive.json', ''));
36
+ const docs = new Map();
37
+ await Promise.all([...docNames].map(async (name) => {
38
+ const path = `${SP_DIR}${name}.smart_primitive.json`;
39
+ docs.set(name, { path, doc: await getJson(path) });
40
+ }));
41
+
42
+ const clipPaths = new Set([SIT_LOOP, ...IDLE_CLIPS.map((p) => MOTION_DIR + p), ...CROUCH_IDLE_CLIPS.map((p) => MOTION_DIR + p)]);
43
+ for (const { path, doc } of docs.values()) for (const p of clipPathsOfDocument(doc, path)) clipPaths.add(p);
44
+ const clips = new Map();
45
+ let done = 0;
46
+ await Promise.all([...clipPaths].map(async (p) => {
47
+ clips.set(p, await getClip(p));
48
+ onProgress(++done, clipPaths.size);
49
+ }));
50
+
51
+ const primitives = new Map();
52
+ for (const [name, { path, doc }] of docs) primitives.set(name, new SmartPrimitive(doc, path, clips));
53
+ const modes = buildModeRuntimes(primitives);
54
+ const loopEntry = (p) => makeClipEntry(clips.get(p).copy().makeLoopable(), p.split('/').pop());
55
+ const idle = IDLE_CLIPS.map((p) => loopEntry(MOTION_DIR + p));
56
+ const crouchIdle = CROUCH_IDLE_CLIPS.map((p) => loopEntry(MOTION_DIR + p));
57
+ const sitLoop = loopEntry(SIT_LOOP);
58
+
59
+ // Scene instances: each gets its own Smart Primitive runtime placed by the scene.
60
+ const instances = scene.smart_primitives.map((inst) => {
61
+ const name = inst.reference.split('/').pop().replace('.smart_primitive.json', '');
62
+ const { path, doc } = docs.get(name);
63
+ const sp = new SmartPrimitive(doc, path, clips);
64
+ const placement = xf.fromJson(inst.transform);
65
+ sp.setNodeWorld(0, placement);
66
+ const behavior = inst.behavior === 'SittingBehavior' ? new SittingBehavior(sp, sitLoop) : new VelocityMatchingSequenceBehavior(sp);
67
+ return { id: inst.id, name: inst.name, doc: name, sp, behavior, placement, position: placement.p, interactable: false };
68
+ });
69
+ const byId = new Map(scene.smart_primitives.map((s) => [s.id, xf.fromJson(s.transform)]));
70
+ const cubes = scene.solid_cubes.map((c) => {
71
+ const local = xf.fromJson(c.transform);
72
+ const world = c.parent_id != null ? xf.mul(byId.get(c.parent_id), local) : local;
73
+ return { name: c.name, t: world, size: [c.dimensions.width, c.dimensions.depth, c.dimensions.height], color: c.color };
74
+ });
75
+ const start = xf.fromJson(scene.character_start.transform);
76
+ return { modes, idle, crouchIdle, instances, cubes, start, clipCount: clips.size };
77
+ }
78
+
79
+ export { resolvePath };
js/character.js ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Character runtime: movement smoothing, locomotion modes, idle / locomotion / interaction states,
2
+ // and an asynchronous motion player. Port of app/runtime/common for the Unitree G1 rig.
3
+ //
4
+ // The reference runtime generates synchronously (about 3 ms with TensorRT). In the browser a
5
+ // generation takes ~50-250 ms in a worker, so each request predicts the moment its motion will
6
+ // take over (now + expected latency), builds the context from the poses that will have been
7
+ // shown by then, and places the targets from the character's predicted position. When the result
8
+ // arrives on time the switch is seamless; when it is late, a short crossfade hides the gap.
9
+
10
+ import { quat, v3, xf, clamp, springDamper, springAngle } from './mathx.js';
11
+ import {
12
+ NQ, PPT, FPS, rootOf, writeRoot, blendPose, MotionRecorder, sampleHistory, buildFeeds, decodeOutput,
13
+ adjustTargetSpeed, placeTargets, BlendSpace, blendTargets,
14
+ } from './motion.js';
15
+ import { boxesOverlap } from './primitives.js';
16
+
17
+ const EPS = 1e-6;
18
+ const DEFAULT_TOKENS = [8, 9, 10, 11, 12, 13, 14];
19
+ const CLIP_FACING_YAW = -0.5 * Math.PI;
20
+ const CROSSFADE = 0.15;
21
+
22
+ export const SETTINGS = {
23
+ facingHalflife: 0.15, velocityDirectionHalflife: 0.2, speedAccelerationHalflife: 0.6, speedDecelerationHalflife: 0.4,
24
+ speedRegenerationFraction: 0.3, minimumSpeedRegenerationFraction: 0.1, directionRegenerationDot: 0.92,
25
+ maximumDirectionChangeSpeedReduction: 0.25,
26
+ };
27
+
28
+ const range = (a, b) => Array.from({ length: b - a + 1 }, (_, i) => a + i);
29
+ const style = (label, minimumSpeed, maxSpeed, extra = {}) => ({
30
+ name: `${label.toLowerCase().replace(/ /g, '_')}_1d`, label, doc: 'locomotion_style_variations_bs1_linear', type: 'linear',
31
+ targets: [['Idle', [0, 0]], [label, [1, 0]]], maxSpeed, defaultSpeed: maxSpeed, minimumSpeed,
32
+ transitionEarly: 2, allowed: range(6, 15), velocityScale: 1, positionScale: 1.5, ...extra,
33
+ });
34
+ const DIRECTIONAL_TARGETS = [['Idle', [0, 0]], ['Forward', [1, 0]], ['Backward', [-1, 0]], ['Left', [0, 1]], ['Right', [0, -1]]];
35
+
36
+ // G1 presets (app/runtime/unitree_g1/presets.py)
37
+ export const MODES = [
38
+ { name: 'linear_1d', label: 'Forward', doc: 'locomotion_bs1_linear', type: 'linear',
39
+ targets: [['Idle', [0, 0]], ['Walk', [1.3 / 3.4, 0]], ['Jog', [2.0 / 3.4, 0]], ['Run', [1, 0]]],
40
+ maxSpeed: 3.4, defaultSpeed: 1.3, minimumSpeed: 1.3, transitionEarly: 10, allowed: DEFAULT_TOKENS, velocityScale: 1, positionScale: 1 },
41
+ { name: 'directional_2d', label: 'Strafing', doc: 'locomotion_bs2_directional', type: 'directional', targets: DIRECTIONAL_TARGETS,
42
+ maxSpeed: 2.3, defaultSpeed: 1.3, minimumSpeed: 1.3, transitionEarly: 10, allowed: DEFAULT_TOKENS, velocityScale: 1, positionScale: 1 },
43
+ { name: 'crouch_directional_2d', label: 'Crouching', doc: 'locomotion_bs2_directional_crouch', type: 'directional', targets: DIRECTIONAL_TARGETS,
44
+ maxSpeed: 1.5, defaultSpeed: 0.8, minimumSpeed: 0.8, transitionEarly: 10, allowed: DEFAULT_TOKENS, velocityScale: 1, positionScale: 1 },
45
+ style('Skipping', 1.3, 1.45, { transitionEarly: 0 }),
46
+ style('Vogue', 0.8, 0.9, { positionScale: 1.3 }),
47
+ style('Injured Torso', 0.4, 0.45),
48
+ style('Injured Leg', 0.4, 0.6),
49
+ style('Zombie', 0.4, 0.45),
50
+ style('Combat', 0.65, 0.75),
51
+ ];
52
+ export const CROUCH_MODE = 'crouch_directional_2d';
53
+ export const IDLE_CLIPS = ['locomotion/idle/idle_loop_001__A268.csv', 'locomotion/idle/neutral_looking_around_R_001__A542.csv', 'locomotion/idle/legs_relax_002__A407.csv'];
54
+ export const CROUCH_IDLE_CLIPS = ['locomotion/idle/crouch_idle_001__A529.csv'];
55
+ export const PROBE = { width: 0.79, minDepth: 0.59, height: 1.26, near: 0.12, lookahead: 1.0, extraMinSpeed: 1.3, extraTime: 0.25 };
56
+
57
+ function groundDir(d, fallback) {
58
+ for (const c of [d, fallback]) {
59
+ const l = Math.hypot(c[0], c[1]);
60
+ if (Number.isFinite(l) && l > EPS) return [c[0] / l, c[1] / l, 0];
61
+ }
62
+ return [1, 0, 0];
63
+ }
64
+ const speedReduction = (speed, max, red) => 1 - red * clamp(speed / max, 0, 1);
65
+
66
+ // ------------------------------------------------------------------------------------------------ movement
67
+ export class MovementControl {
68
+ constructor(facing) {
69
+ const a = Math.atan2(facing[1], facing[0]);
70
+ this.inputSpeed = 0;
71
+ this.inputDir = [...facing];
72
+ this.desiredFacing = [...facing];
73
+ this.lastInputFacing = [...facing];
74
+ this.currentFacing = [...facing]; this.facingAngle = a; this.facingRate = 0;
75
+ this.velocityDir = [...facing]; this.velocityAngle = a; this.velocityRate = 0;
76
+ this.desiredSpeed = 0; this.desiredSpeedRate = 0;
77
+ this.desiredVelocity = [0, 0, 0];
78
+ }
79
+ update(cmd, mode, dt, previousMode) {
80
+ this._read(cmd, mode);
81
+ if (previousMode) this._easeSwitch(mode, previousMode);
82
+ this._smooth(mode, dt);
83
+ }
84
+ realign(velocity, mode) {
85
+ const speed = Math.hypot(velocity[0], velocity[1]);
86
+ const d = groundDir(velocity, this.currentFacing), a = Math.atan2(d[1], d[0]);
87
+ this.desiredSpeed = speed; this.desiredSpeedRate = 0;
88
+ this.velocityDir = d; this.velocityAngle = a; this.velocityRate = 0;
89
+ this.desiredVelocity = v3.scale(d, speed);
90
+ if (mode.type === 'linear') this._setFacing(d, a, 0);
91
+ }
92
+ face(d) {
93
+ this.desiredFacing = [...d]; this.lastInputFacing = [...d];
94
+ this._setFacing(d, Math.atan2(d[1], d[0]), 0);
95
+ }
96
+ resetDesiredVelocity() { this.desiredSpeed = 0; this.desiredSpeedRate = 0; this.desiredVelocity = [0, 0, 0]; }
97
+ // A copy advanced `ahead` seconds with the same input: the movement at the moment a requested
98
+ // generation takes over, which compensates for the inference latency.
99
+ predicted(mode, ahead) {
100
+ const m = Object.assign(Object.create(MovementControl.prototype), this);
101
+ m.currentFacing = [...this.currentFacing]; m.velocityDir = [...this.velocityDir]; m.desiredVelocity = [...this.desiredVelocity];
102
+ const steps = Math.max(1, Math.round(ahead * 60));
103
+ for (let i = 0; i < steps; i++) m._smooth(mode, ahead / steps);
104
+ return m;
105
+ }
106
+ _setFacing(d, a, r) { this.currentFacing = [d[0], d[1], 0]; this.facingAngle = a; this.facingRate = r; }
107
+ _read(cmd, mode) {
108
+ const facing = groundDir(cmd.facing, this.desiredFacing);
109
+ const amount = cmd.movement ? Math.hypot(cmd.movement[0], cmd.movement[1]) : 0;
110
+ if (!(amount > EPS)) {
111
+ if (mode.type === 'directional' || this.desiredSpeed <= 0) this.desiredFacing = facing;
112
+ this.inputSpeed = 0;
113
+ return;
114
+ }
115
+ const dir = groundDir(cmd.movement, this.inputDir);
116
+ this.inputDir = dir;
117
+ this.desiredFacing = mode.type === 'linear' ? dir : facing;
118
+ this.lastInputFacing = [...this.desiredFacing];
119
+ const requested = cmd.run ? mode.maxSpeed : mode.defaultSpeed;
120
+ this.inputSpeed = Math.max(requested * Math.min(amount, 1), mode.minimumSpeed);
121
+ }
122
+ _easeSwitch(mode, prev) {
123
+ if (mode.type === 'directional') this._setFacing(this.desiredFacing, Math.atan2(this.desiredFacing[1], this.desiredFacing[0]), 0);
124
+ if (mode.maxSpeed <= prev.maxSpeed) {
125
+ const s = speedReduction(this.desiredSpeed, mode.maxSpeed, SETTINGS.maximumDirectionChangeSpeedReduction);
126
+ this.desiredSpeed = Math.min(this.desiredSpeed * s, mode.maxSpeed);
127
+ this.desiredSpeedRate *= s;
128
+ }
129
+ }
130
+ _smooth(mode, dt) {
131
+ [this.velocityAngle, this.velocityRate] = springAngle(this.velocityAngle, this.velocityRate, this.inputDir, SETTINGS.velocityDirectionHalflife, dt);
132
+ this.velocityDir = [Math.cos(this.velocityAngle), Math.sin(this.velocityAngle), 0];
133
+ if (mode.type === 'linear') this._setFacing(this.velocityDir, this.velocityAngle, this.velocityRate);
134
+ else {
135
+ [this.facingAngle, this.facingRate] = springAngle(this.facingAngle, this.facingRate, this.desiredFacing, SETTINGS.facingHalflife, dt);
136
+ this.currentFacing = [Math.cos(this.facingAngle), Math.sin(this.facingAngle), 0];
137
+ }
138
+ let goal = this.inputSpeed;
139
+ if (v3.dot(this.velocityDir, this.inputDir) < SETTINGS.directionRegenerationDot) {
140
+ goal *= speedReduction(this.desiredSpeed, mode.maxSpeed, SETTINGS.maximumDirectionChangeSpeedReduction);
141
+ }
142
+ const hl = goal > this.desiredSpeed ? SETTINGS.speedAccelerationHalflife : SETTINGS.speedDecelerationHalflife;
143
+ [this.desiredSpeed, this.desiredSpeedRate] = springDamper(this.desiredSpeed, this.desiredSpeedRate, goal, hl, dt);
144
+ if (this.desiredSpeed > mode.maxSpeed) { this.desiredSpeed = mode.maxSpeed; this.desiredSpeedRate = Math.min(this.desiredSpeedRate, 0); }
145
+ this.desiredVelocity = v3.scale(this.velocityDir, this.desiredSpeed);
146
+ }
147
+ }
148
+
149
+ // ------------------------------------------------------------------------------------------------ clips placed in the world
150
+ export function makeClipEntry(clip, name) {
151
+ const r = rootOf(clip.frames, 0);
152
+ return { clip, name, sourceGround: xf.ground(r), rootOffset: xf.identity(), duration: clip.duration };
153
+ }
154
+
155
+ // ------------------------------------------------------------------------------------------------ states
156
+ class IdleState {
157
+ constructor(name, clips) { this.name = name; this.clips = clips; }
158
+ choose(ch) {
159
+ const c = this.clips.filter((e) => e !== ch.currentClip);
160
+ const pool = c.length ? c : this.clips;
161
+ return pool[Math.floor(Math.random() * pool.length)];
162
+ }
163
+ start(ch) { ch.movement.resetDesiredVelocity(); ch.initializeClipLoop(this.choose(ch)); }
164
+ enter(ch) { ch.movement.resetDesiredVelocity(); ch.generateClipTransition(this.choose(ch)); }
165
+ exit() {}
166
+ update(ch, sm, dt) {
167
+ if (ch.movement.inputSpeed > 0) { sm.transitionToLocomotion(ch); return; }
168
+ if (ch.clipTransitionEndsWithin(dt)) ch.startClip(ch.currentClip, { loop: true });
169
+ }
170
+ }
171
+
172
+ class LocomotionState {
173
+ constructor(name, modes, initial) {
174
+ this.name = name;
175
+ this.modes = new Map(modes.map((m) => [m.def.name, m]));
176
+ this.active = this.modes.get(initial);
177
+ this.prevVelocity = [0, 0, 0];
178
+ this.force = true;
179
+ }
180
+ get mode() { return this.active.def; }
181
+ select(name) {
182
+ const m = this.modes.get(name);
183
+ if (m && m !== this.active) { this.active = m; this.force = true; }
184
+ }
185
+ enter(ch) {
186
+ ch.movement.realign(ch.velocity, this.mode);
187
+ this.generate(ch);
188
+ // Starting from (near) rest: let the first speed-up regenerate right away.
189
+ if (v3.len(ch.velocity) < 0.15) this.prevVelocity = [0, 0, 0];
190
+ }
191
+ exit() {}
192
+ update(ch, sm, dt) {
193
+ if (ch.movement.inputSpeed <= 0) { sm.transitionToIdle(ch); return; }
194
+ if (this.force || ch.timeToTransition() <= dt + ch.lead() || this.needsRegeneration(ch.movement)) this.generate(ch);
195
+ }
196
+ // Blend the mode's targets for the desired velocity and place them ahead of `ground`.
197
+ evaluateTargets(ch, ground, mv = ch.movement) {
198
+ const m = this.active, def = m.def;
199
+ const speed = v3.len(mv.desiredVelocity);
200
+ let weights;
201
+ if (def.type === 'linear') weights = m.space.evaluate(speed / def.maxSpeed);
202
+ else {
203
+ const n = v3.scale(mv.desiredVelocity, 1 / def.maxSpeed);
204
+ const left = [-mv.currentFacing[1], mv.currentFacing[0], 0];
205
+ weights = m.space.evaluate(clamp(v3.dot(n, mv.currentFacing), -1, 1), clamp(v3.dot(n, left), -1, 1));
206
+ }
207
+ const blended = blendTargets(m.targets, weights, def.type === 'linear');
208
+ adjustTargetSpeed(blended, speed * def.velocityScale);
209
+ const g = v3.add(ground, v3.scale(mv.desiredVelocity, def.velocityScale * def.positionScale));
210
+ g[2] = 0;
211
+ return placeTargets(g, mv.currentFacing, blended);
212
+ }
213
+ generate(ch) {
214
+ this.prevVelocity = [...ch.movement.desiredVelocity];
215
+ this.force = false;
216
+ ch.requestGeneration((plan) => {
217
+ this.prevVelocity = [...ch.movement.desiredVelocity];
218
+ const def = this.mode;
219
+ const mv = ch.movement.predicted(def, plan.lead);
220
+ return { targets: this.evaluateTargets(ch, plan.ground, mv), numPoses: PPT, transitionEarly: def.transitionEarly, allowed: def.allowed, source: 'generated', label: def.label };
221
+ });
222
+ }
223
+ needsRegeneration(mv) {
224
+ const prev = v3.len(this.prevVelocity), max = this.mode.maxSpeed;
225
+ const started = mv.desiredSpeed > 0 && prev <= EPS;
226
+ const delta = mv.desiredSpeed - prev;
227
+ const remaining = delta > 0 ? max - prev : prev;
228
+ const threshold = Math.max(remaining * SETTINGS.speedRegenerationFraction, max * SETTINGS.minimumSpeedRegenerationFraction);
229
+ if (started || Math.abs(delta) > threshold) return true;
230
+ if (prev <= EPS) return false;
231
+ return v3.dot(mv.velocityDir, v3.scale(this.prevVelocity, 1 / prev)) < SETTINGS.directionRegenerationDot;
232
+ }
233
+ }
234
+
235
+ class InteractionState {
236
+ constructor() { this.name = 'Interaction'; this.behavior = null; this.index = -1; this.targets = []; this.playingClip = false; this.clipLoop = false; }
237
+ get isLooping() { return this.playingClip && this.clipLoop; }
238
+ enter(ch, sm) { this.character = ch; this.sm = sm; this.behavior.enter(this); }
239
+ exit(ch) { this._stop(); ch.facePose(); this.behavior = null; this.playingClip = false; this.targets = []; }
240
+ playTargets(list, onComplete, label = '') {
241
+ this._stop();
242
+ this.playingClip = false;
243
+ this.targets = list;
244
+ this.label = label;
245
+ this.index = 0;
246
+ this.onComplete = onComplete || (() => this.finish());
247
+ this._generateCurrent();
248
+ }
249
+ playSequence(sp, name, onComplete) {
250
+ const s = sp.sequenceIndex(name);
251
+ sp.alignSequencePivot(s, this.character.properties());
252
+ this.playTargets(sp.worldTargetsForSequence(s), onComplete, name);
253
+ }
254
+ playClip(entry, { loop = false, alignToCurrent = true, onComplete = null } = {}) {
255
+ this._stop();
256
+ this.character.startClip(entry, { loop, alignToCurrent });
257
+ this.playingClip = true;
258
+ this.clipLoop = loop;
259
+ this.onComplete = onComplete || (() => this.finish());
260
+ }
261
+ finish() { this.sm.resumeMovement(this.character); }
262
+ update(ch, sm, dt) {
263
+ if (this.playingClip) { if (ch.clipEndsWithin(dt)) this._complete(); return; }
264
+ if (this.index < 0) return;
265
+ const hasNext = this.index + 1 < this.targets.length;
266
+ if (ch.timeToTransition() > dt + (hasNext ? ch.lead() : 0)) return;
267
+ this.index++;
268
+ if (this.index < this.targets.length) this._generateCurrent(); else this._complete();
269
+ }
270
+ _complete() { const cb = this.onComplete; this.playingClip = false; this._stop(); cb && cb(); }
271
+ _stop() { this.index = -1; this.onComplete = null; }
272
+ _generateCurrent() {
273
+ const t = this.targets[this.index];
274
+ const label = `${this.label} ${this.index + 1}/${this.targets.length}`;
275
+ this.character.requestGeneration(() => ({ targets: t.poses, ...t.params, source: 'generated', label }));
276
+ }
277
+ }
278
+
279
+ class StateMachine {
280
+ constructor(modeRuntimes, standingIdle, crouchIdle) {
281
+ const byName = new Map(modeRuntimes.map((m) => [m.def.name, m]));
282
+ const standing = modeRuntimes.filter((m) => m.def.name !== CROUCH_MODE);
283
+ this.standingIdle = new IdleState('Idle', standingIdle);
284
+ this.standingLoco = new LocomotionState('Locomotion', standing, 'linear_1d');
285
+ this.crouchIdle = new IdleState('Crouching Idle', crouchIdle);
286
+ this.crouchLoco = new LocomotionState('Crouching Locomotion', [byName.get(CROUCH_MODE)], CROUCH_MODE);
287
+ this.interaction = new InteractionState();
288
+ this.standingPair = { idle: this.standingIdle, loco: this.standingLoco, probeScale: 1 };
289
+ this.crouchPair = { idle: this.crouchIdle, loco: this.crouchLoco, probeScale: 0.6 };
290
+ this.pair = this.standingPair;
291
+ this.state = this.pair.idle;
292
+ }
293
+ get loco() { return this.pair.loco; }
294
+ get isInteracting() { return this.state === this.interaction; }
295
+ get isLocomoting() { return this.state === this.standingLoco || this.state === this.crouchLoco; }
296
+ start(ch) { this.pair.idle.start(ch); }
297
+ transitionTo(ch, next) {
298
+ if (next === this.state) return;
299
+ this.state.exit(ch, this);
300
+ this.state = next;
301
+ next.enter(ch, this);
302
+ }
303
+ update(ch, dt, cmd) {
304
+ const prevPair = this.pair, prevMode = prevPair.loco.mode;
305
+ if (cmd.mode) {
306
+ this.pair = cmd.mode === CROUCH_MODE ? this.crouchPair : this.standingPair;
307
+ this.pair.loco.select(cmd.mode);
308
+ }
309
+ const mode = this.loco.mode;
310
+ ch.movement.update(cmd, mode, dt, mode !== prevMode ? prevMode : null);
311
+ if (prevPair !== this.pair && (this.state === prevPair.idle || this.state === prevPair.loco)) this.resumeMovement(ch);
312
+ this.state.update(ch, this, dt);
313
+ }
314
+ transitionToIdle(ch) { this.transitionTo(ch, this.pair.idle); }
315
+ transitionToLocomotion(ch) { this.transitionTo(ch, this.pair.loco); }
316
+ resumeMovement(ch) { if (ch.movement.inputSpeed > 0) this.transitionToLocomotion(ch); else this.transitionToIdle(ch); }
317
+ startInteraction(ch, behavior) {
318
+ if (this.isInteracting) return;
319
+ this.interaction.behavior = behavior;
320
+ this.transitionTo(ch, this.interaction);
321
+ }
322
+ interact() { if (this.isInteracting && this.interaction.behavior) this.interaction.behavior.interact(); }
323
+ }
324
+
325
+ // ------------------------------------------------------------------------------------------------ character
326
+ export class Character {
327
+ constructor({ inference, modes, idleClips, crouchIdleClips, start }) {
328
+ this.inference = inference;
329
+ this.movement = new MovementControl(start.facing);
330
+ this.ground = [start.position[0], start.position[1], 0];
331
+ this.velocity = [0, 0, 0];
332
+ this.pose = new Float32Array(NQ);
333
+ this.contacts = new Float32Array(4);
334
+ this.recorder = null;
335
+ this.source = 'clip';
336
+ this.seg = null;
337
+ this.playing = null; // {entry, time, loop}
338
+ this.currentClip = null;
339
+ this.inflight = null;
340
+ this.arrived = null;
341
+ this.ready = null;
342
+ this.queued = null;
343
+ this.fade = null;
344
+ this.simTime = 0;
345
+ this.latency = 0.18;
346
+ this.stats = { generations: 0, lastMs: 0, avgMs: 0, lastFrames: 0, lastTokens: 0, late: 0, label: '' };
347
+ this.lastRequest = null;
348
+ this.onGeneration = null;
349
+ this.sm = new StateMachine(modes, idleClips, crouchIdleClips);
350
+ this.sm.start(this);
351
+ }
352
+
353
+ // ---- timing
354
+ lead() { return clamp(this.latency * 1.35 + 0.03, 0.06, 1.0); }
355
+ timeToTransition() {
356
+ if (this.inflight || this.ready) return Infinity;
357
+ if (this.source === 'clip' || !this.seg) return 0;
358
+ const end = Math.max(0, this.seg.n - 1 - this.seg.transitionEarly) / FPS;
359
+ return Math.max(0, end - this.seg.time);
360
+ }
361
+ get busy() { return !!(this.inflight || this.ready); }
362
+
363
+ // ---- what the current source will show `ahead` seconds from now
364
+ peek(ahead, out = new Float32Array(NQ)) {
365
+ if (this.source === 'clip' && this.playing) {
366
+ const p = this.playing;
367
+ let t = p.time + ahead;
368
+ if (p.loop) t %= p.entry.duration;
369
+ return p.entry.clip.sample(t, out, p.entry.rootOffset);
370
+ }
371
+ if (this.seg) return this._sampleSeg(this.seg, this.seg.time + ahead, out);
372
+ out.set(this.pose);
373
+ return out;
374
+ }
375
+ _sampleSeg(seg, t, out, contacts = null) {
376
+ const x = clamp(t * FPS, 0, seg.n - 1), i = Math.floor(x), j = Math.min(i + 1, seg.n - 1), b = x - i;
377
+ blendPose(seg.poses, seg.poses, b, out, i * NQ, j * NQ);
378
+ if (contacts) for (let c = 0; c < 4; c++) contacts[c] = seg.contacts[i * 4 + c] * (1 - b) + seg.contacts[j * 4 + c] * b;
379
+ return out;
380
+ }
381
+
382
+ // ---- generation
383
+ requestGeneration(builder) {
384
+ if (!this.inference.ready) return;
385
+ if (this.inflight) { this.queued = builder; return; }
386
+ this._issue(builder);
387
+ }
388
+ _issue(builder) {
389
+ const L = this.lead();
390
+ // Virtual history: what was shown, then what the current source will show until the switch.
391
+ const steps = Math.max(1, Math.ceil(L * 60));
392
+ const h = L / steps;
393
+ const cap = this.recorder.capacity;
394
+ const poses = new Float32Array((cap + steps) * NQ), dts = new Float32Array(cap + steps);
395
+ poses.set(this.recorder.poses);
396
+ dts.set(this.recorder.dts);
397
+ const tmp = new Float32Array(NQ);
398
+ for (let k = 1; k <= steps; k++) {
399
+ dts[cap + k - 2] = h;
400
+ poses.set(this.peek(k * h, tmp), (cap + k - 1) * NQ);
401
+ }
402
+ dts[cap + steps - 1] = 0;
403
+ const context = sampleHistory(poses, dts);
404
+ const lastCtx = rootOf(context, (PPT - 1) * NQ);
405
+ const plan = { ground: [lastCtx.p[0], lastCtx.p[1], 0], lead: L };
406
+ const req = builder(plan);
407
+ if (!req) return;
408
+ const { feeds, align } = buildFeeds(context, req.targets, req.numPoses, req.allowed || DEFAULT_TOKENS);
409
+ if (req.clipEntry) this.currentClip = req.clipEntry;
410
+ this.inflight = { req, context, align, tSwitch: this.simTime + L, issuedAt: this.simTime };
411
+ this.lastRequest = { context, targets: req.targets, numPoses: req.numPoses, label: req.label || '' };
412
+ this.inference.run(feeds).then((res) => { this.arrived = { res, req: this.inflight }; });
413
+ }
414
+ _handleArrival() {
415
+ if (!this.arrived) return;
416
+ const { res, req } = this.arrived;
417
+ this.arrived = null;
418
+ this.inflight = null;
419
+ if (!req.cancelled && !res.error) {
420
+ const d = decodeOutput(res.pred_qpos, res.pred_foot_contacts, res.ntok[0], req.align, req.context, req.req.targets);
421
+ // Latency in simulation time, which is what decides whether the switch is on time.
422
+ this.latency = this.latency * 0.7 + (this.simTime - req.issuedAt) * 0.3;
423
+ this.stats.generations++;
424
+ this.stats.lastMs = res.ms;
425
+ this.stats.avgMs = this.stats.avgMs ? this.stats.avgMs * 0.8 + res.ms * 0.2 : res.ms;
426
+ this.stats.lastFrames = d.n;
427
+ this.stats.lastTokens = res.ntok[0];
428
+ this.stats.label = req.req.label || '';
429
+ this.ready = { ...d, tSwitch: req.tSwitch, source: req.req.source, transitionEarly: req.req.transitionEarly || 0 };
430
+ if (this.onGeneration) this.onGeneration(this.ready, req);
431
+ }
432
+ if (this.queued) { const b = this.queued; this.queued = null; this._issue(b); }
433
+ }
434
+ cancelPending() {
435
+ if (this.inflight) this.inflight.cancelled = true;
436
+ this.queued = null;
437
+ this.ready = null;
438
+ }
439
+
440
+ generateClipTransition(entry) {
441
+ this.requestGeneration((plan) => {
442
+ const ground = v3.add(plan.ground, this.velocity);
443
+ this._alignClip(entry, ground, this.movement.lastInputFacing);
444
+ const targets = new Float32Array(PPT * NQ), tmp = new Float32Array(NQ);
445
+ for (let f = 0; f < PPT; f++) targets.set(entry.clip.sample(f / FPS, tmp, entry.rootOffset), f * NQ);
446
+ return { targets, numPoses: PPT, transitionEarly: 0, allowed: DEFAULT_TOKENS, source: 'clip_transition', clipEntry: entry, label: 'Idle' };
447
+ });
448
+ }
449
+ _alignClip(entry, ground, facing) {
450
+ const yaw = Math.atan2(facing[1], facing[0]) - CLIP_FACING_YAW;
451
+ const target = { p: [ground[0], ground[1], 0], q: quat.mul(quat.yaw(yaw), entry.sourceGround.q) };
452
+ entry.rootOffset = xf.mul(target, xf.inv(entry.sourceGround));
453
+ }
454
+ startClip(entry, { loop = false, alignToCurrent = false } = {}) {
455
+ this.cancelPending();
456
+ if (alignToCurrent) {
457
+ const first = entry.clip.sample(0);
458
+ entry.rootOffset = xf.mul(rootOf(this.pose), xf.inv(rootOf(first)));
459
+ }
460
+ this.currentClip = entry;
461
+ this.playing = { entry, time: 0, loop };
462
+ this.source = 'clip';
463
+ this.fade = null;
464
+ entry.clip.sample(0, this.pose, entry.rootOffset);
465
+ this.contacts.fill(0);
466
+ this._updateGround();
467
+ }
468
+ initializeClipLoop(entry) {
469
+ this._alignClip(entry, this.ground, this.movement.lastInputFacing);
470
+ this.startClip(entry, { loop: true });
471
+ this.recorder = new MotionRecorder(this.pose);
472
+ }
473
+ clipTransitionEndsWithin(dt) { return this.source === 'clip_transition' && this.timeToTransition() <= dt; }
474
+ clipEndsWithin(dt) { return this.source === 'clip' && this.playing && !this.playing.loop && this.playing.time + dt >= this.playing.entry.duration; }
475
+
476
+ facePose() {
477
+ const f = quat.rotate(rootOf(this.pose).q, [1, 0, 0]);
478
+ this.movement.face(groundDir(f, this.movement.currentFacing));
479
+ }
480
+ // Where the character will be when a generation requested now takes over. Interactions are
481
+ // evaluated there, so the inference latency does not make the character overshoot them.
482
+ plannedGround() {
483
+ if (!this.inference.ready) return [...this.ground];
484
+ const p = this.peek(this.lead());
485
+ return [p[0], p[1], 0];
486
+ }
487
+ properties() {
488
+ const position = this.plannedGround();
489
+ return { position, velocity: [...this.velocity], facing: [...this.movement.currentFacing],
490
+ desiredVelocity: [...this.movement.desiredVelocity], probe: this.probeSegment(position) };
491
+ }
492
+ probeSegment(position = this.plannedGround()) {
493
+ const speed = Math.hypot(this.movement.desiredVelocity[0], this.movement.desiredVelocity[1]);
494
+ const dir = this.movement.velocityDir;
495
+ let reach = speed * PROBE.lookahead + Math.max(0, speed - PROBE.extraMinSpeed) * PROBE.extraTime;
496
+ const far = Math.max(PROBE.near + PROBE.minDepth, reach);
497
+ return [v3.add(position, v3.scale(dir, PROBE.near)), v3.add(position, v3.scale(dir, far))];
498
+ }
499
+ probeBox() {
500
+ const [a, b] = this.probeSegment();
501
+ const d = v3.sub(b, a), depth = v3.len(d), h = PROBE.height * this.sm.pair.probeScale;
502
+ const c = v3.scale(v3.add(a, b), 0.5); c[2] = 0.5 * h;
503
+ return { t: { p: c, q: quat.yaw(Math.atan2(d[1], d[0]) - Math.PI / 2) }, half: [0.5 * PROBE.width, 0.5 * depth, 0.5 * h] };
504
+ }
505
+
506
+ // ---- per frame
507
+ step(dt, cmd) {
508
+ this._handleArrival();
509
+ this.sm.update(this, dt, cmd);
510
+ const prev = [...this.ground];
511
+ this._samplePlayback(dt);
512
+ this.simTime += dt;
513
+ this.velocity = [(this.ground[0] - prev[0]) / dt, (this.ground[1] - prev[1]) / dt, 0];
514
+ this.recorder.record(dt, this.pose);
515
+ }
516
+ _samplePlayback(dt) {
517
+ const tNext = this.simTime + dt;
518
+ if (this.ready && tNext >= this.ready.tSwitch) {
519
+ const old = new Float32Array(NQ);
520
+ this._advanceCurrent(dt, old, null);
521
+ const r = this.ready;
522
+ this.ready = null;
523
+ this.seg = { poses: r.poses, contacts: r.contacts, n: r.n, time: tNext - r.tSwitch, transitionEarly: r.transitionEarly };
524
+ this.source = r.source;
525
+ this.playing = null;
526
+ this._sampleSeg(this.seg, this.seg.time, this.pose, this.contacts);
527
+ if (this.seg.time > 1.5 / 60) this.stats.late++;
528
+ // Crossfade from what the old source would have shown.
529
+ const ro = rootOf(old), rn = rootOf(this.pose);
530
+ const ang = new Float32Array(NQ);
531
+ for (let c = 7; c < NQ; c++) ang[c] = old[c] - this.pose[c];
532
+ this.fade = { dp: v3.sub(ro.p, rn.p), dq: quat.mul(quat.inv(rn.q), ro.q), ang, t: 0 };
533
+ this._applyFade(0);
534
+ } else {
535
+ this._advanceCurrent(dt, this.pose, this.contacts);
536
+ if (this.source !== 'clip') this._applyFade(dt);
537
+ }
538
+ this._updateGround();
539
+ }
540
+ _advanceCurrent(dt, out, contacts) {
541
+ if (this.source === 'clip' && this.playing) {
542
+ const p = this.playing;
543
+ p.time += dt;
544
+ if (p.loop) p.time %= p.entry.duration;
545
+ p.entry.clip.sample(p.time, out, p.entry.rootOffset);
546
+ if (contacts) contacts.fill(0);
547
+ } else if (this.seg) {
548
+ this.seg.time += dt;
549
+ this._sampleSeg(this.seg, this.seg.time, out, contacts);
550
+ if (out !== this.pose && this.fade) this._applyFadeTo(out, this.fade.t + dt);
551
+ } else if (out !== this.pose) out.set(this.pose);
552
+ }
553
+ _applyFade(dt) {
554
+ if (!this.fade) return;
555
+ this.fade.t += dt;
556
+ if (this.fade.t >= CROSSFADE) { this.fade = null; return; }
557
+ this._applyFadeTo(this.pose, this.fade.t);
558
+ }
559
+ _applyFadeTo(pose, t) {
560
+ const f = this.fade;
561
+ if (!f || t >= CROSSFADE) return;
562
+ const x = t / CROSSFADE, w = 1 - x * x * (3 - 2 * x);
563
+ const r = rootOf(pose);
564
+ writeRoot(pose, { p: v3.add(r.p, v3.scale(f.dp, w)), q: quat.mul(r.q, quat.slerp([0, 0, 0, 1], f.dq, w)) });
565
+ for (let c = 7; c < NQ; c++) pose[c] += f.ang[c] * w;
566
+ }
567
+ _updateGround() { this.ground = [this.pose[0], this.pose[1], 0]; }
568
+
569
+ // Remaining generated root path, for drawing the model's plan.
570
+ plannedPath(stepFrames = 2) {
571
+ if (this.source === 'clip' || !this.seg) return [];
572
+ const pts = [];
573
+ for (let f = Math.floor(this.seg.time * FPS); f < this.seg.n; f += stepFrames) pts.push([this.seg.poses[f * NQ], this.seg.poses[f * NQ + 1]]);
574
+ return pts;
575
+ }
576
+ }
577
+
578
+ // Build the locomotion runtimes (blend spaces + local target windows) from loaded primitives.
579
+ export function buildModeRuntimes(primitives) {
580
+ return MODES.map((def) => {
581
+ const sp = primitives.get(def.doc);
582
+ const targets = def.targets.map(([name]) => {
583
+ const i = sp.nodeIndex(name);
584
+ if (i < 0 || !sp.nodes[i].target) throw new Error(`${def.doc} has no target ${name}`);
585
+ return sp.localTarget(i);
586
+ });
587
+ return { def, targets, space: new BlendSpace(def.type, def.targets.map(([, v]) => v)) };
588
+ });
589
+ }
590
+
591
+ // Scene-level interaction: probe box against Smart Primitive interaction boxes.
592
+ export class InteractionDirector {
593
+ constructor(instances) { this.instances = instances; this.blocked = new Map(); this.active = null; this.nearest = null; this.auto = true; this.probe = null; }
594
+ update(ch, pressed, dt = 1 / 60) {
595
+ const probe = ch.probeBox();
596
+ this.probe = probe;
597
+ for (const inst of this.instances) inst.interactable = inst.sp.worldBoxes().some((b) => boxesOverlap(b, probe));
598
+ const sm = ch.sm;
599
+ if (this.active && !sm.isInteracting) { this.blocked.set(this.active.id, 0); this.active = null; }
600
+ // Auto Interact re-arms once the probe has left the object for a moment.
601
+ for (const inst of this.instances) {
602
+ if (!this.blocked.has(inst.id)) continue;
603
+ const clear = inst.interactable ? 0 : this.blocked.get(inst.id) + dt;
604
+ if (clear >= 0.4) this.blocked.delete(inst.id); else this.blocked.set(inst.id, clear);
605
+ }
606
+ let best = null, bd = Infinity;
607
+ const g = ch.plannedGround();
608
+ for (const inst of this.instances) {
609
+ if (!inst.interactable) continue;
610
+ const d = (inst.position[0] - g[0]) ** 2 + (inst.position[1] - g[1]) ** 2;
611
+ if (d < bd) { bd = d; best = inst; }
612
+ }
613
+ this.nearest = best;
614
+ if (sm.isInteracting) { if (pressed) sm.interact(); return; }
615
+ if (best && (pressed || (this.auto && !this.blocked.has(best.id)))) {
616
+ sm.startInteraction(ch, best.behavior);
617
+ this.active = best;
618
+ }
619
+ }
620
+ }
js/inference.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Main-thread client for the inference worker: one request at a time, promise per request.
2
+
3
+ export class Inference {
4
+ constructor(workerUrl) {
5
+ this.worker = new Worker(workerUrl);
6
+ this.ready = false;
7
+ this.threads = 0;
8
+ this.pending = new Map();
9
+ this.nextId = 1;
10
+ this.onStatus = () => {};
11
+ this.worker.onmessage = (e) => {
12
+ const m = e.data;
13
+ if (m.type === 'result') {
14
+ const resolve = this.pending.get(m.id);
15
+ this.pending.delete(m.id);
16
+ if (resolve) resolve(m);
17
+ } else {
18
+ if (m.type === 'ready') { this.ready = true; this.threads = m.threads; }
19
+ this.onStatus(m);
20
+ }
21
+ };
22
+ }
23
+ // Resolve against the page: a worker would resolve relative URLs against its own script.
24
+ load(urls) { this.worker.postMessage({ type: 'load', urls: urls.map((u) => new URL(u, location.href).href) }); }
25
+ run(feeds) {
26
+ const id = this.nextId++;
27
+ return new Promise((resolve) => {
28
+ this.pending.set(id, resolve);
29
+ this.worker.postMessage({ type: 'run', id, feeds });
30
+ });
31
+ }
32
+ }
js/main.js ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // MotionBricks G1 playground: three.js scene, input, HUD and the main loop.
2
+
3
+ import * as THREE from 'three';
4
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
5
+ import { loadRobotModel, Robot, heroMaterials, ghostMaterials } from './robot.js';
6
+ import { loadWorld } from './assets.js';
7
+ import { Inference } from './inference.js';
8
+ import { Character, InteractionDirector, MODES, CROUCH_MODE } from './character.js';
9
+ import { NQ, PPT, FPS } from './motion.js';
10
+ import { quat } from './mathx.js';
11
+
12
+ const params = new URLSearchParams(location.search);
13
+ const CAPTURE = params.has('capture');
14
+ const LOCAL = params.get('src') === 'local';
15
+ const SPACE = window.MB_SPACE || '';
16
+ const MODEL_FILE = 'mmm_v6_g1_fp16.onnx';
17
+ const MODEL_URLS = LOCAL ? ['models/g1_fp16.onnx']
18
+ : [SPACE ? `https://huggingface.co/spaces/${SPACE}/resolve/main/models/${MODEL_FILE}` : null, `models/${MODEL_FILE}`].filter(Boolean);
19
+
20
+ const $ = (id) => document.getElementById(id);
21
+ const COLORS = { context: 0xa78bfa, target: 0x5eead4, plan: 0x5eead4, trail: 0xffffff, goal: 0xfbbf24 };
22
+
23
+ // ---------------------------------------------------------------------------------------------- renderer
24
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: CAPTURE });
25
+ renderer.setPixelRatio(CAPTURE ? 1 : Math.min(devicePixelRatio, 2));
26
+ renderer.setSize(innerWidth, innerHeight);
27
+ renderer.shadowMap.enabled = true;
28
+ renderer.shadowMap.type = THREE.PCFShadowMap;
29
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
30
+ renderer.toneMappingExposure = 1.05;
31
+ $('stage').appendChild(renderer.domElement);
32
+
33
+ const scene = new THREE.Scene();
34
+ scene.background = new THREE.Color(0x0d0f14);
35
+ scene.fog = new THREE.Fog(0x0d0f14, 14, 42);
36
+ const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.05, 200);
37
+ camera.position.set(-10.4, 2.5, -0.6);
38
+ const controls = new OrbitControls(camera, renderer.domElement);
39
+ controls.enableDamping = true;
40
+ controls.dampingFactor = 0.08;
41
+ controls.minDistance = 1.5;
42
+ controls.maxDistance = 18;
43
+ controls.maxPolarAngle = Math.PI * 0.49;
44
+ controls.target.set(-6.3, 0.75, -3.1);
45
+
46
+ scene.add(new THREE.HemisphereLight(0xcfe3ff, 0x1a1c22, 0.9));
47
+ const sun = new THREE.DirectionalLight(0xffffff, 2.4);
48
+ sun.castShadow = true;
49
+ sun.shadow.mapSize.set(2048, 2048);
50
+ sun.shadow.camera.left = -6; sun.shadow.camera.right = 6; sun.shadow.camera.top = 6; sun.shadow.camera.bottom = -6;
51
+ sun.shadow.camera.near = 1; sun.shadow.camera.far = 30;
52
+ sun.shadow.bias = -0.0004;
53
+ sun.shadow.normalBias = 0.02;
54
+ scene.add(sun, sun.target);
55
+ const rim = new THREE.DirectionalLight(0x8fb8ff, 1.1);
56
+ rim.position.set(-6, 5, -8);
57
+ scene.add(rim);
58
+
59
+ // Z-up world: everything MotionBricks produces lives in here.
60
+ const world = new THREE.Group();
61
+ world.rotation.x = -Math.PI / 2;
62
+ scene.add(world);
63
+
64
+ function makeFloor() {
65
+ const size = 1024, c = document.createElement('canvas');
66
+ c.width = c.height = size;
67
+ const g = c.getContext('2d');
68
+ g.fillStyle = '#16191f'; g.fillRect(0, 0, size, size);
69
+ g.strokeStyle = 'rgba(255,255,255,0.05)'; g.lineWidth = 2;
70
+ for (let i = 0; i <= 8; i++) { const p = (i * size) / 8; g.beginPath(); g.moveTo(p, 0); g.lineTo(p, size); g.moveTo(0, p); g.lineTo(size, p); g.stroke(); }
71
+ g.strokeStyle = 'rgba(255,255,255,0.10)'; g.lineWidth = 3;
72
+ g.strokeRect(0, 0, size, size);
73
+ const tex = new THREE.CanvasTexture(c);
74
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
75
+ tex.repeat.set(30, 30);
76
+ tex.anisotropy = 8;
77
+ tex.colorSpace = THREE.SRGBColorSpace;
78
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(120, 120), new THREE.MeshStandardMaterial({ map: tex, roughness: 0.92, metalness: 0 }));
79
+ floor.receiveShadow = true;
80
+ floor.name = 'floor';
81
+ world.add(floor);
82
+ return floor;
83
+ }
84
+ const floor = makeFloor();
85
+
86
+ function label(text, color = '#e5e7eb') {
87
+ const c = document.createElement('canvas');
88
+ c.width = 512; c.height = 128;
89
+ const g = c.getContext('2d');
90
+ g.font = '600 56px Inter, system-ui, sans-serif';
91
+ g.textAlign = 'center'; g.textBaseline = 'middle';
92
+ g.fillStyle = 'rgba(13,15,20,0.72)';
93
+ const w = g.measureText(text).width + 64;
94
+ g.beginPath(); g.roundRect(256 - w / 2, 20, w, 88, 44); g.fill();
95
+ g.fillStyle = color; g.fillText(text, 256, 66);
96
+ const tex = new THREE.CanvasTexture(c);
97
+ tex.colorSpace = THREE.SRGBColorSpace;
98
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthWrite: false, transparent: true }));
99
+ s.scale.set(1.0, 0.25, 1);
100
+ return s;
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------------------------- state
104
+ let model, liteModel, hero, ctxGhost, tgtGhost, character, director, worldData;
105
+ const instanceGhosts = [];
106
+ const inference = CAPTURE ? null : new Inference('js/worker.js');
107
+ const ui = {
108
+ ghosts: true, plan: true, boxes: true, probe: false, contacts: true, trail: true, auto: true,
109
+ run: false, keys: new Set(), goal: null, goalRun: false, interact: false, mode: null, joystick: null,
110
+ };
111
+ const log = [];
112
+
113
+ // ---------------------------------------------------------------------------------------------- overlays
114
+ const planLine = new THREE.Line(new THREE.BufferGeometry(), new THREE.LineBasicMaterial({ color: COLORS.plan, transparent: true, opacity: 0.9 }));
115
+ const trailLine = new THREE.Line(new THREE.BufferGeometry(), new THREE.LineBasicMaterial({ color: COLORS.trail, transparent: true, opacity: 0.25 }));
116
+ const transitionDot = new THREE.Mesh(new THREE.CircleGeometry(0.06, 24), new THREE.MeshBasicMaterial({ color: COLORS.plan }));
117
+ const goalMarker = new THREE.Mesh(new THREE.RingGeometry(0.22, 0.3, 40), new THREE.MeshBasicMaterial({ color: COLORS.goal, transparent: true, opacity: 0.9 }));
118
+ const probeMesh = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)), new THREE.LineBasicMaterial({ color: 0xfbbf24, transparent: true, opacity: 0.5 }));
119
+ probeMesh.visible = false;
120
+ world.add(planLine, trailLine, transitionDot, goalMarker, probeMesh);
121
+ goalMarker.visible = false;
122
+ const contactDiscs = [0, 1, 2, 3].map(() => {
123
+ const m = new THREE.Mesh(new THREE.CircleGeometry(0.05, 20), new THREE.MeshBasicMaterial({ color: 0xfbbf24, transparent: true, opacity: 0 }));
124
+ world.add(m);
125
+ return m;
126
+ });
127
+ const trail = [];
128
+ const boxMeshes = [];
129
+
130
+ function buildProps(data) {
131
+ const propMat = (c) => new THREE.MeshStandardMaterial({ color: new THREE.Color(c[0], c[1], c[2]).multiplyScalar(0.55).addScalar(0.12), roughness: 0.55, metalness: 0.05 });
132
+ for (const cube of data.cubes) {
133
+ let mesh;
134
+ if (cube.name === 'Bar') {
135
+ // Visual only: a beam across the path at the authored clearance, on two posts.
136
+ const g = new THREE.Group();
137
+ const bottom = cube.t.p[2] - cube.size[2] / 2;
138
+ const beam = new THREE.Mesh(new THREE.BoxGeometry(0.18, 2.6, 0.14), propMat(cube.color));
139
+ beam.position.set(0, 0, bottom + 0.07);
140
+ g.add(beam);
141
+ for (const s of [-1, 1]) {
142
+ const post = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, bottom + 0.14), propMat([0.35, 0.37, 0.4]));
143
+ post.position.set(0, s * 1.3, (bottom + 0.14) / 2);
144
+ g.add(post);
145
+ }
146
+ g.traverse((o) => { o.castShadow = o.receiveShadow = true; });
147
+ g.position.set(cube.t.p[0], cube.t.p[1], 0);
148
+ const inst = data.instances.find((i) => i.name === 'AvoidanceSP');
149
+ if (inst) g.quaternion.set(...inst.placement.q);
150
+ mesh = g;
151
+ } else {
152
+ mesh = new THREE.Mesh(new THREE.BoxGeometry(...cube.size), propMat(cube.color));
153
+ mesh.position.set(...cube.t.p);
154
+ mesh.quaternion.set(...cube.t.q);
155
+ mesh.castShadow = mesh.receiveShadow = true;
156
+ }
157
+ world.add(mesh);
158
+ }
159
+ const names = { SmallJumpSP: 'Jump', MidJumpSP: 'Vault', SitSP: 'Sit', AvoidanceSP: 'Duck under' };
160
+ for (const inst of data.instances) {
161
+ const s = label(names[inst.name] || inst.name);
162
+ s.position.set(inst.position[0], inst.position[1], 2.05);
163
+ world.add(s);
164
+ for (const b of inst.sp.worldBoxes()) {
165
+ const m = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(b.half[0] * 2, b.half[1] * 2, b.half[2] * 2)),
166
+ new THREE.LineBasicMaterial({ color: 0x9ca3af, transparent: true, opacity: 0.35 }));
167
+ m.userData.inst = inst;
168
+ world.add(m);
169
+ boxMeshes.push({ mesh: m, inst, box: b });
170
+ }
171
+ }
172
+ }
173
+
174
+ function updateBoxes() {
175
+ for (const bm of boxMeshes) {
176
+ bm.mesh.visible = ui.boxes;
177
+ const b = bm.inst.sp.worldBoxes()[bm.inst.sp.worldBoxes().indexOf(bm.box)] || bm.box;
178
+ bm.mesh.position.set(...b.t.p);
179
+ bm.mesh.quaternion.set(...b.t.q);
180
+ const active = bm.inst.interactable;
181
+ bm.mesh.material.color.set(active ? 0x5eead4 : 0x9ca3af);
182
+ bm.mesh.material.opacity = active ? 0.9 : 0.35;
183
+ }
184
+ const p = director && director.probe;
185
+ probeMesh.visible = ui.probe && !!p;
186
+ if (p) {
187
+ probeMesh.position.set(...p.t.p);
188
+ probeMesh.quaternion.set(...p.t.q);
189
+ probeMesh.scale.set(p.half[0] * 2, p.half[1] * 2, p.half[2] * 2);
190
+ }
191
+ }
192
+
193
+ function setLine(line, pts, z) {
194
+ const arr = new Float32Array(pts.length * 3);
195
+ pts.forEach((p, i) => { arr[i * 3] = p[0]; arr[i * 3 + 1] = p[1]; arr[i * 3 + 2] = z; });
196
+ line.geometry.setAttribute('position', new THREE.BufferAttribute(arr, 3));
197
+ line.geometry.computeBoundingSphere();
198
+ }
199
+
200
+ const _v = new THREE.Vector3();
201
+ const _m = new THREE.Matrix4();
202
+ function updateOverlays(dt) {
203
+ const ch = character;
204
+ hero.setPose(ch.pose);
205
+ const req = ch.lastRequest;
206
+ ctxGhost.visible = tgtGhost.visible = ui.ghosts && !!req && ch.source !== 'clip';
207
+ if (req && ui.ghosts) {
208
+ ctxGhost.setPose(req.context.subarray((PPT - 1) * NQ, PPT * NQ));
209
+ tgtGhost.setPose(req.targets.subarray(0, NQ));
210
+ }
211
+ const path = ui.plan ? ch.plannedPath() : [];
212
+ planLine.visible = path.length > 1;
213
+ if (path.length > 1) setLine(planLine, path, 0.012);
214
+ transitionDot.visible = ui.plan && !!ch.seg && ch.source !== 'clip';
215
+ if (transitionDot.visible) {
216
+ const f = Math.max(0, ch.seg.n - 1 - ch.seg.transitionEarly);
217
+ transitionDot.position.set(ch.seg.poses[f * NQ], ch.seg.poses[f * NQ + 1], 0.013);
218
+ }
219
+ trail.push([ch.pose[0], ch.pose[1]]);
220
+ if (trail.length > 360) trail.shift();
221
+ trailLine.visible = ui.trail && trail.length > 1;
222
+ if (trailLine.visible) setLine(trailLine, trail, 0.01);
223
+ // Foot contacts at the ankle roll joints (heel) and 0.14 m ahead, 0.035 m below (toe).
224
+ hero.root.updateMatrixWorld(true);
225
+ const feet = ['left_ankle_roll_link', 'left_ankle_roll_link', 'right_ankle_roll_link', 'right_ankle_roll_link'];
226
+ for (let i = 0; i < 4; i++) {
227
+ const body = hero.byName.get(feet[i]);
228
+ _v.set(i % 2 ? 0.14 : 0, 0, i % 2 ? -0.035 : 0).applyMatrix4(_m.copy(world.matrixWorld).invert().multiply(body.matrixWorld));
229
+ const d = contactDiscs[i];
230
+ d.position.set(_v.x, _v.y, 0.008);
231
+ d.material.opacity = ui.contacts ? 0.85 * ch.contacts[i] : 0;
232
+ }
233
+ goalMarker.visible = !!ui.goal;
234
+ if (ui.goal) {
235
+ goalMarker.position.set(ui.goal[0], ui.goal[1], 0.015);
236
+ goalMarker.rotation.z += dt * 1.5;
237
+ }
238
+ updateBoxes();
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------------------------- camera follow
242
+ let lastFollow = null;
243
+ function followCamera() {
244
+ const p = new THREE.Vector3(character.pose[0], character.pose[2] * 0.9, -character.pose[1]);
245
+ if (!lastFollow) { lastFollow = p.clone(); return; }
246
+ const delta = p.clone().sub(lastFollow);
247
+ delta.y *= 0.3;
248
+ camera.position.add(delta);
249
+ controls.target.add(delta);
250
+ lastFollow.add(delta);
251
+ sun.position.set(p.x + 4, 9, p.z + 3);
252
+ sun.target.position.copy(p);
253
+ }
254
+ function cameraFacing() {
255
+ const d = new THREE.Vector3().subVectors(controls.target, camera.position);
256
+ const f = [d.x, -d.z];
257
+ const l = Math.hypot(f[0], f[1]) || 1;
258
+ return [f[0] / l, f[1] / l, 0];
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------------------------- input
262
+ const MOVE_KEYS = { KeyW: [0, 1], ArrowUp: [0, 1], KeyS: [0, -1], ArrowDown: [0, -1], KeyA: [-1, 0], ArrowLeft: [-1, 0], KeyD: [1, 0], ArrowRight: [1, 0] };
263
+ const STYLE_MODES = MODES.slice(3);
264
+ let lastStyle = STYLE_MODES[0].name;
265
+
266
+ function setMode(name) {
267
+ if (!character) return;
268
+ ui.mode = name;
269
+ if (STYLE_MODES.some((m) => m.name === name)) lastStyle = name;
270
+ renderModeButtons(name);
271
+ }
272
+ function currentModeName() { return character ? character.sm.loco.mode.name : 'linear_1d'; }
273
+
274
+ addEventListener('keydown', (e) => {
275
+ if (e.target.tagName === 'INPUT') return;
276
+ ui.keys.add(e.code);
277
+ if (MOVE_KEYS[e.code]) { ui.goal = null; e.preventDefault(); }
278
+ if (e.code === 'KeyE' || e.code === 'KeyI') ui.interact = true;
279
+ if (e.code === 'KeyC' || e.code === 'KeyP') setMode(currentModeName() === CROUCH_MODE ? 'linear_1d' : CROUCH_MODE);
280
+ if (e.code === 'KeyQ' || e.code === 'KeyO') setMode(currentModeName() === 'directional_2d' ? 'linear_1d' : 'directional_2d');
281
+ if (e.code === 'BracketLeft') {
282
+ const i = STYLE_MODES.findIndex((m) => m.name === currentModeName());
283
+ setMode(i < 0 ? lastStyle : STYLE_MODES[(i + 1) % STYLE_MODES.length].name);
284
+ }
285
+ if (e.code === 'Digit1') setMode('linear_1d');
286
+ if (e.code === 'Digit2') setMode('directional_2d');
287
+ if (e.code === 'Digit3') setMode(CROUCH_MODE);
288
+ const n = Number(e.key);
289
+ if (n >= 4 && n <= 9) setMode(STYLE_MODES[n - 4].name);
290
+ if (e.code === 'Space') e.preventDefault();
291
+ });
292
+ addEventListener('keyup', (e) => ui.keys.delete(e.code));
293
+ addEventListener('blur', () => ui.keys.clear());
294
+
295
+ // Click / tap on the floor to walk there (double click to run).
296
+ const raycaster = new THREE.Raycaster();
297
+ let downAt = null;
298
+ renderer.domElement.addEventListener('pointerdown', (e) => { downAt = [e.clientX, e.clientY, performance.now()]; });
299
+ renderer.domElement.addEventListener('pointerup', (e) => {
300
+ if (!downAt || !character) return;
301
+ const moved = Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]);
302
+ const quick = performance.now() - downAt[2] < 350;
303
+ downAt = null;
304
+ if (moved > 6 || !quick) return;
305
+ const ndc = new THREE.Vector2((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
306
+ raycaster.setFromCamera(ndc, camera);
307
+ const hit = raycaster.intersectObject(floor)[0];
308
+ if (!hit) return;
309
+ const local = world.worldToLocal(hit.point.clone());
310
+ const now = performance.now();
311
+ ui.goalRun = !!(ui.lastClick && now - ui.lastClick < 400);
312
+ ui.lastClick = now;
313
+ ui.goal = [local.x, local.y];
314
+ });
315
+
316
+ function buildCommand() {
317
+ const facing = cameraFacing();
318
+ const right = [facing[1], -facing[0], 0];
319
+ let ix = 0, iy = 0;
320
+ for (const k of ui.keys) if (MOVE_KEYS[k]) { ix += MOVE_KEYS[k][0]; iy += MOVE_KEYS[k][1]; }
321
+ if (ui.joystick) { ix += ui.joystick[0]; iy += ui.joystick[1]; }
322
+ let movement = null;
323
+ let run = ui.run || ui.keys.has('ShiftLeft') || ui.keys.has('ShiftRight') || ui.keys.has('Space') || (ui.joystick && Math.hypot(...ui.joystick) > 0.92);
324
+ if (ix || iy) {
325
+ const l = Math.max(1, Math.hypot(ix, iy));
326
+ movement = [(facing[0] * iy + right[0] * ix) / l, (facing[1] * iy + right[1] * ix) / l, 0];
327
+ } else if (ui.goal) {
328
+ const d = [ui.goal[0] - character.ground[0], ui.goal[1] - character.ground[1], 0];
329
+ const dist = Math.hypot(d[0], d[1]);
330
+ const speed = Math.hypot(...character.movement.desiredVelocity);
331
+ if (dist < Math.max(0.35, speed * 0.75)) ui.goal = null;
332
+ else { movement = [d[0] / dist, d[1] / dist, 0]; run = run || ui.goalRun; }
333
+ }
334
+ if (!inferenceReady()) movement = null;
335
+ const cmd = { facing, movement, run, mode: ui.mode };
336
+ ui.mode = null;
337
+ return cmd;
338
+ }
339
+
340
+ // Touch joystick
341
+ (function joystick() {
342
+ const pad = $('joystick'), knob = $('knob');
343
+ let id = null, cx = 0, cy = 0;
344
+ pad.addEventListener('pointerdown', (e) => { id = e.pointerId; const r = pad.getBoundingClientRect(); cx = r.left + r.width / 2; cy = r.top + r.height / 2; pad.setPointerCapture(id); move(e); });
345
+ pad.addEventListener('pointermove', (e) => { if (e.pointerId === id) move(e); });
346
+ const end = () => { id = null; ui.joystick = null; knob.style.transform = ''; };
347
+ pad.addEventListener('pointerup', end); pad.addEventListener('pointercancel', end);
348
+ function move(e) {
349
+ const dx = e.clientX - cx, dy = e.clientY - cy, r = 48, l = Math.hypot(dx, dy), k = l > r ? r / l : 1;
350
+ knob.style.transform = `translate(${dx * k}px, ${dy * k}px)`;
351
+ ui.joystick = [(dx * k) / r, (-dy * k) / r];
352
+ ui.goal = null;
353
+ }
354
+ })();
355
+
356
+ // ---------------------------------------------------------------------------------------------- UI
357
+ function renderModeButtons(active = currentModeName()) {
358
+ for (const b of document.querySelectorAll('[data-mode]')) b.classList.toggle('on', b.dataset.mode === active);
359
+ }
360
+ function buildPanel() {
361
+ const core = $('modes'), styles = $('styles');
362
+ MODES.forEach((m, i) => {
363
+ const b = document.createElement('button');
364
+ b.dataset.mode = m.name;
365
+ b.innerHTML = `${m.label}<kbd>${i + 1}</kbd>`;
366
+ b.onclick = () => setMode(m.name);
367
+ (i < 3 ? core : styles).appendChild(b);
368
+ });
369
+ const toggles = [['ghosts', 'Context & target poses'], ['plan', 'Generated path'], ['contacts', 'Foot contacts'], ['boxes', 'Interaction boxes'], ['probe', 'Probe box'], ['trail', 'Trail'], ['auto', 'Auto interact'], ['run', 'Always run']];
370
+ for (const [k, text] of toggles) {
371
+ const l = document.createElement('label');
372
+ l.innerHTML = `<input type="checkbox" ${ui[k] ? 'checked' : ''}><span>${text}</span>`;
373
+ l.querySelector('input').onchange = (e) => { ui[k] = e.target.checked; if (k === 'auto' && director) director.auto = ui.auto; };
374
+ $('toggles').appendChild(l);
375
+ }
376
+ $('interact').onclick = () => { ui.interact = true; };
377
+ $('runbtn').onpointerdown = () => { ui.run = true; };
378
+ $('runbtn').onpointerup = $('runbtn').onpointerleave = () => { ui.run = false; };
379
+ $('panel-toggle').onclick = () => document.body.classList.toggle('panel-collapsed');
380
+ renderModeButtons('linear_1d');
381
+ }
382
+
383
+ function pushLog(text) {
384
+ log.unshift({ text, t: performance.now() });
385
+ if (log.length > 6) log.pop();
386
+ $('log').innerHTML = log.map((l, i) => `<div style="opacity:${1 - i * 0.14}">${l.text}</div>`).join('');
387
+ }
388
+
389
+ let hudTimer = 0;
390
+ function updateHud(dt) {
391
+ hudTimer += dt;
392
+ if (hudTimer < 0.1) return;
393
+ hudTimer = 0;
394
+ const ch = character, s = ch.stats;
395
+ const mode = ch.sm.loco.mode;
396
+ $('state').textContent = ch.sm.isInteracting ? `Interaction · ${ch.sm.interaction.label || ''}` : `${ch.sm.state.name} · ${mode.label}`;
397
+ $('speed').textContent = `${Math.hypot(ch.velocity[0], ch.velocity[1]).toFixed(2)} m/s`;
398
+ $('gens').textContent = s.generations;
399
+ $('infer').textContent = s.avgMs ? `${s.avgMs.toFixed(0)} ms` : '–';
400
+ // Timeline of the segment being played.
401
+ const tl = $('timeline');
402
+ if (ch.seg && ch.source !== 'clip') {
403
+ const n = ch.seg.n, trans = Math.max(0, n - 1 - ch.seg.transitionEarly);
404
+ tl.style.setProperty('--play', `${Math.min(1, (ch.seg.time * FPS) / (n - 1)) * 100}%`);
405
+ tl.style.setProperty('--trans', `${(trans / (n - 1)) * 100}%`);
406
+ tl.classList.remove('idle');
407
+ $('tl-label').textContent = `${n} frames · ${(n / FPS).toFixed(2)} s · ${s.lastTokens} tokens`;
408
+ } else {
409
+ tl.classList.add('idle');
410
+ $('tl-label').textContent = ch.source === 'clip' ? `playing clip · ${ch.currentClip ? ch.currentClip.name.replace(/__A\d+.*$/, '').replace(/_/g, ' ') : ''}` : '';
411
+ }
412
+ $('busy').classList.toggle('on', ch.busy);
413
+ }
414
+
415
+ function inferenceReady() { return CAPTURE ? true : inference.ready; }
416
+
417
+ // ---------------------------------------------------------------------------------------------- loading
418
+ function setLoad(id, frac, text) {
419
+ const row = $(id);
420
+ row.querySelector('i').style.width = `${Math.round(frac * 100)}%`;
421
+ if (text) row.querySelector('em').textContent = text;
422
+ }
423
+
424
+ async function init() {
425
+ buildPanel();
426
+ setLoad('load-robot', 0.1, 'loading meshes…');
427
+ const robotPromise = Promise.all([
428
+ loadRobotModel('assets/g1.glb', 'assets/g1_kinematics.json'),
429
+ loadRobotModel('assets/g1_lite.glb', 'assets/g1_kinematics.json'),
430
+ ]).then(([m, lite]) => { setLoad('load-robot', 1, 'ready'); return [m, lite]; });
431
+ const worldPromise = loadWorld((done, total) => setLoad('load-clips', done / total, `${done}/${total} clips`));
432
+ if (inference) {
433
+ inference.onStatus = (m) => {
434
+ if (m.type === 'progress') {
435
+ const mb = (x) => (x / 1e6).toFixed(0);
436
+ setLoad('load-model', m.total ? (0.9 * m.received) / m.total : 0.3, m.cached ? 'from browser cache' : `${mb(m.received)} / ${mb(m.total)} MB`);
437
+ } else if (m.type === 'compiling') setLoad('load-model', 0.93, 'building the ONNX graph…');
438
+ else if (m.type === 'ready') {
439
+ setLoad('load-model', 1, `ready · ${m.threads} thread${m.threads > 1 ? 's' : ''}`);
440
+ $('threads').textContent = `${m.threads} × WASM`;
441
+ document.body.classList.add('model-ready');
442
+ pushLog(`Model ready (${(m.compileMs / 1000).toFixed(1)} s to build) — move with WASD or click the floor`);
443
+ } else if (m.type === 'error') {
444
+ setLoad('load-model', 0, `error: ${m.message}`);
445
+ $('load-model').classList.add('err');
446
+ }
447
+ };
448
+ inference.load(MODEL_URLS);
449
+ }
450
+ [[model, liteModel], worldData] = await Promise.all([robotPromise, worldPromise]);
451
+
452
+ hero = new Robot(model, heroMaterials());
453
+ ctxGhost = new Robot(liteModel, ghostMaterials(COLORS.context, 0.13), { castShadow: false });
454
+ tgtGhost = new Robot(liteModel, ghostMaterials(COLORS.target), { castShadow: false });
455
+ world.add(hero.root, ctxGhost.root, tgtGhost.root);
456
+ buildProps(worldData);
457
+
458
+ const yaw = quat.heading(worldData.start.q);
459
+ character = new Character({
460
+ inference: CAPTURE ? captureInference : inference, modes: worldData.modes, idleClips: worldData.idle, crouchIdleClips: worldData.crouchIdle,
461
+ start: { position: worldData.start.p, facing: [Math.cos(yaw), Math.sin(yaw), 0] },
462
+ });
463
+ character.onGeneration = (r, req) => {
464
+ pushLog(`<b>${req.req.label || 'motion'}</b> → ${r.n} frames (${(r.n / FPS).toFixed(2)} s) · ${character.stats.lastMs.toFixed(0)} ms`);
465
+ };
466
+ director = new InteractionDirector(worldData.instances);
467
+ hero.setPose(character.pose);
468
+ followCamera();
469
+ document.body.classList.add('world-ready');
470
+ if (!CAPTURE) requestAnimationFrame(loop);
471
+ window.MB = { character, director, ui, camera, controls, setMode, world, renderer, scene };
472
+ }
473
+
474
+ // ---------------------------------------------------------------------------------------------- loop
475
+ let last = performance.now();
476
+ function stepSim(dt) {
477
+ const cmd = buildCommand();
478
+ character.step(dt, cmd);
479
+ director.auto = ui.auto;
480
+ director.update(character, ui.interact, dt);
481
+ ui.interact = false;
482
+ followCamera();
483
+ updateOverlays(dt);
484
+ updateHud(dt);
485
+ }
486
+ function loop(now) {
487
+ const dt = Math.min(Math.max((now - last) / 1000, 1 / 240), 1 / 20);
488
+ last = now;
489
+ stepSim(dt);
490
+ controls.update();
491
+ renderer.render(scene, camera);
492
+ requestAnimationFrame(loop);
493
+ }
494
+
495
+ addEventListener('resize', () => {
496
+ camera.aspect = innerWidth / innerHeight;
497
+ camera.updateProjectionMatrix();
498
+ renderer.setSize(innerWidth, innerHeight);
499
+ });
500
+
501
+ // ---------------------------------------------------------------------------------------------- capture mode
502
+ // Deterministic stepping for video capture: inference results arrive after a fixed simulated
503
+ // latency, and the page advances only when the recorder asks for the next frame.
504
+ const captureInference = CAPTURE ? (() => {
505
+ const inf = new Inference('js/worker.js');
506
+ const pending = [];
507
+ const api = {
508
+ get ready() { return inf.ready; },
509
+ latency: 0.12,
510
+ run(feeds) {
511
+ const due = character ? character.simTime + api.latency : 0;
512
+ const p = inf.run(feeds);
513
+ return new Promise((resolve) => pending.push({ due, p, resolve }));
514
+ },
515
+ async deliver(simTime) {
516
+ for (let i = 0; i < pending.length; i++) {
517
+ const e = pending[i];
518
+ if (e.due <= simTime + 1e-9) { const r = await e.p; pending.splice(i--, 1); e.resolve(r); await null; }
519
+ }
520
+ },
521
+ inf,
522
+ };
523
+ inf.onStatus = (m) => { if (m.type === 'ready') document.body.classList.add('model-ready'); if (m.type === 'error') console.error(m.message); };
524
+ inf.load(MODEL_URLS);
525
+ return api;
526
+ })() : null;
527
+
528
+ window.MBCapture = CAPTURE ? {
529
+ async step(n = 1, dt = 1 / 30, hooks = null) {
530
+ for (let i = 0; i < n; i++) {
531
+ await captureInference.deliver(character.simTime + dt);
532
+ if (hooks) hooks(character.simTime);
533
+ stepSim(dt);
534
+ }
535
+ controls.update();
536
+ renderer.render(scene, camera);
537
+ },
538
+ ready: () => !!character && captureInference.ready,
539
+ } : null;
540
+
541
+ init().catch((e) => { console.error(e); $('load-error').textContent = String(e.message || e); });
js/mathx.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Small vector / quaternion / transform helpers on plain arrays.
2
+ // Quaternions are [x, y, z, w]; transforms are {p: [x, y, z], q: [x, y, z, w]}.
3
+
4
+ export const TAU = Math.PI * 2;
5
+
6
+ export function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }
7
+ export function lerp(a, b, t) { return a + (b - a) * t; }
8
+ export function smoothstep(e0, e1, x) { const t = clamp((x - e0) / (e1 - e0), 0, 1); return t * t * (3 - 2 * t); }
9
+ export function wrapAngle(a) { return ((a + Math.PI) % TAU + TAU) % TAU - Math.PI; }
10
+
11
+ export const v3 = {
12
+ add: (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]],
13
+ sub: (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
14
+ scale: (a, s) => [a[0] * s, a[1] * s, a[2] * s],
15
+ dot: (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
16
+ cross: (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]],
17
+ len: (a) => Math.hypot(a[0], a[1], a[2]),
18
+ lenSq: (a) => a[0] * a[0] + a[1] * a[1] + a[2] * a[2],
19
+ norm: (a) => { const l = Math.hypot(a[0], a[1], a[2]); return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; },
20
+ lerp: (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t],
21
+ };
22
+
23
+ export const quat = {
24
+ identity: () => [0, 0, 0, 1],
25
+ mul(a, b) {
26
+ const [ax, ay, az, aw] = a, [bx, by, bz, bw] = b;
27
+ return [
28
+ aw * bx + ax * bw + ay * bz - az * by,
29
+ aw * by - ax * bz + ay * bw + az * bx,
30
+ aw * bz + ax * by - ay * bx + az * bw,
31
+ aw * bw - ax * bx - ay * by - az * bz,
32
+ ];
33
+ },
34
+ inv: (q) => [-q[0], -q[1], -q[2], q[3]],
35
+ norm(q) {
36
+ const l = Math.hypot(q[0], q[1], q[2], q[3]);
37
+ return l > 0 ? [q[0] / l, q[1] / l, q[2] / l, q[3] / l] : [0, 0, 0, 1];
38
+ },
39
+ dot: (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3],
40
+ fromAxisAngle(axis, angle) {
41
+ const n = v3.norm(axis), s = Math.sin(angle / 2);
42
+ return [n[0] * s, n[1] * s, n[2] * s, Math.cos(angle / 2)];
43
+ },
44
+ yaw: (angle) => [0, 0, Math.sin(angle / 2), Math.cos(angle / 2)],
45
+ rotate(q, v) {
46
+ // v' = v + 2w (u x v) + 2 u x (u x v)
47
+ const u = [q[0], q[1], q[2]], w = q[3];
48
+ const uv = v3.cross(u, v), uuv = v3.cross(u, uv);
49
+ return [v[0] + 2 * (w * uv[0] + uuv[0]), v[1] + 2 * (w * uv[1] + uuv[1]), v[2] + 2 * (w * uv[2] + uuv[2])];
50
+ },
51
+ rotateInv(q, v) { return quat.rotate(quat.inv(q), v); },
52
+ slerp(a, b, t) {
53
+ a = quat.norm(a); b = quat.norm(b);
54
+ let d = quat.dot(a, b);
55
+ if (d < 0) { b = [-b[0], -b[1], -b[2], -b[3]]; d = -d; }
56
+ if (d > 0.9995) {
57
+ return quat.norm([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t]);
58
+ }
59
+ const th = Math.acos(clamp(d, -1, 1)), s = Math.sin(th);
60
+ const wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s;
61
+ return quat.norm([wa * a[0] + wb * b[0], wa * a[1] + wb * b[1], wa * a[2] + wb * b[2], wa * a[3] + wb * b[3]]);
62
+ },
63
+ // Swing-twist decomposition: the part of q that rotates about axis.
64
+ twist(axis, q) {
65
+ const n = v3.norm(axis);
66
+ const d = q[0] * n[0] + q[1] * n[1] + q[2] * n[2];
67
+ const t = [n[0] * d, n[1] * d, n[2] * d, q[3]];
68
+ const l = Math.hypot(t[0], t[1], t[2], t[3]);
69
+ return l < 1e-9 ? [0, 0, 0, 1] : [t[0] / l, t[1] / l, t[2] / l, t[3] / l];
70
+ },
71
+ // Heading angle of the local +X axis on the ground plane.
72
+ heading(q) { const f = quat.rotate(q, [1, 0, 0]); return Math.atan2(f[1], f[0]); },
73
+ toMat3(q) {
74
+ const [x, y, z, w] = q;
75
+ return [
76
+ [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
77
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
78
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
79
+ ];
80
+ },
81
+ fromEulerXYZExtrinsic(rx, ry, rz) {
82
+ // Extrinsic XYZ == intrinsic ZYX: q = qz * qy * qx
83
+ const qx = quat.fromAxisAngle([1, 0, 0], rx), qy = quat.fromAxisAngle([0, 1, 0], ry), qz = quat.fromAxisAngle([0, 0, 1], rz);
84
+ return quat.mul(qz, quat.mul(qy, qx));
85
+ },
86
+ };
87
+
88
+ export const xf = {
89
+ identity: () => ({ p: [0, 0, 0], q: [0, 0, 0, 1] }),
90
+ make: (p, q) => ({ p: [...p], q: quat.norm(q) }),
91
+ mul: (a, b) => ({ p: v3.add(a.p, quat.rotate(a.q, b.p)), q: quat.norm(quat.mul(a.q, b.q)) }),
92
+ inv(a) { const qi = quat.inv(a.q); return { p: v3.scale(quat.rotate(qi, a.p), -1), q: qi }; },
93
+ point: (a, v) => v3.add(a.p, quat.rotate(a.q, v)),
94
+ vector: (a, v) => quat.rotate(a.q, v),
95
+ blend: (a, b, t) => ({ p: v3.lerp(a.p, b.p, t), q: quat.slerp(a.q, b.q, t) }),
96
+ // Project onto the ground plane z = 0, keeping only the rotation about Z.
97
+ ground: (a) => ({ p: [a.p[0], a.p[1], 0], q: quat.twist([0, 0, 1], a.q) }),
98
+ fromJson: (j) => ({ p: [...j.translation], q: quat.norm(j.rotation_xyzw) }),
99
+ };
100
+
101
+ // Critically damped spring (exact), as in motionbricks.utils.math_utils.
102
+ export function springDamper(current, rate, goal, halflife, dt) {
103
+ const damping = (4 * Math.LN2) / (halflife + 1e-5);
104
+ const y = damping / 2;
105
+ const j0 = current - goal;
106
+ const j1 = rate + j0 * y;
107
+ const eydt = Math.exp(-y * dt);
108
+ const next = eydt * (j0 + j1 * dt) + goal;
109
+ const nextRate = eydt * (rate - j1 * y * dt);
110
+ if (Math.abs(next - goal) <= 1e-4 && Math.abs(nextRate) <= 1e-4) return [goal, 0];
111
+ return [next, nextRate];
112
+ }
113
+
114
+ export function springAngle(angle, rate, dir, halflife, dt) {
115
+ const desired = Math.atan2(dir[1], dir[0]);
116
+ const goal = angle + wrapAngle(desired - angle);
117
+ const [a, r] = springDamper(angle, rate, goal, halflife, dt);
118
+ return [wrapAngle(a), r];
119
+ }
120
+
121
+ export function quadraticFade(v) {
122
+ const t = clamp(v, 0, 1), r = 1 - t;
123
+ return t < 0.5 ? 1 - 2 * t * t : 2 * r * r;
124
+ }
js/motion.js ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Port of the MotionBricks Unitree G1 pose layout, clips, recorder and engine pre/post-processing.
2
+ // A pose is a Float32Array(36): root xyz, root quaternion xyzw, 29 joint angles (radians). World is Z up.
3
+
4
+ import { quat, v3, xf, clamp, quadraticFade } from './mathx.js';
5
+
6
+ export const NQ = 36;
7
+ export const ROOT = 7;
8
+ export const FPS = 30;
9
+ export const PPT = 4; // poses per token
10
+ export const BOUNDARY = 3;
11
+ export const MAX_VALID_FRAMES = 16 * PPT - 2 * BOUNDARY;
12
+ const ROOT_FILTER = [-0.0465, 0.0639, 0.2827, 0.3998, 0.2827, 0.0639, -0.0465];
13
+ const JOINT_FADE_FRAMES = 0.3 * FPS;
14
+ export const CSV_RATE = 120;
15
+
16
+ export const rootOf = (pose, o = 0) => ({
17
+ p: [pose[o], pose[o + 1], pose[o + 2]],
18
+ q: quat.norm([pose[o + 3], pose[o + 4], pose[o + 5], pose[o + 6]]),
19
+ });
20
+ export function writeRoot(pose, t, o = 0) {
21
+ const q = quat.norm(t.q);
22
+ pose[o] = t.p[0]; pose[o + 1] = t.p[1]; pose[o + 2] = t.p[2];
23
+ pose[o + 3] = q[0]; pose[o + 4] = q[1]; pose[o + 5] = q[2]; pose[o + 6] = q[3];
24
+ }
25
+
26
+ // Blend two poses: lerp positions and joint angles, slerp the root rotation.
27
+ export function blendPose(a, b, t, out = new Float32Array(NQ), ao = 0, bo = 0) {
28
+ if (t <= 0) { for (let i = 0; i < NQ; i++) out[i] = a[ao + i]; return out; }
29
+ if (t >= 1) { for (let i = 0; i < NQ; i++) out[i] = b[bo + i]; return out; }
30
+ const r = xf.blend(rootOf(a, ao), rootOf(b, bo), t);
31
+ writeRoot(out, r);
32
+ for (let i = ROOT; i < NQ; i++) out[i] = a[ao + i] + (b[bo + i] - a[ao + i]) * t;
33
+ return out;
34
+ }
35
+
36
+ // Apply a world transform to a pose's root. Joint angles are unchanged.
37
+ export function offsetRoot(pose, offset, out = new Float32Array(NQ)) {
38
+ if (out !== pose) out.set(pose);
39
+ writeRoot(out, xf.mul(offset, rootOf(pose)));
40
+ return out;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------------------------- clips
44
+ export class Clip {
45
+ constructor(frames, rate, name = '') {
46
+ this.frames = frames; // Float32Array(n * NQ)
47
+ this.rate = rate;
48
+ this.n = frames.length / NQ;
49
+ this.name = name;
50
+ }
51
+ get duration() { return Math.max(this.n - 1, 1) / this.rate; }
52
+ frame(i) { return this.frames.subarray(i * NQ, (i + 1) * NQ); }
53
+ sample(t, out = new Float32Array(NQ), rootOffset = null) {
54
+ const last = Math.max(0, this.n - 1);
55
+ const x = t * this.rate;
56
+ const i = clamp(Math.floor(x), 0, last);
57
+ const blend = i < last ? clamp(x - i, 0, 1) : 0;
58
+ blendPose(this.frames, this.frames, blend, out, i * NQ, Math.min(i + 1, last) * NQ);
59
+ if (rootOffset) writeRoot(out, xf.mul(rootOffset, rootOf(out)));
60
+ return out;
61
+ }
62
+ rootPositions() {
63
+ const r = new Float32Array(this.n * 3);
64
+ for (let i = 0; i < this.n; i++) for (let k = 0; k < 3; k++) r[i * 3 + k] = this.frames[i * NQ + k];
65
+ return r;
66
+ }
67
+ copy() { return new Clip(this.frames.slice(), this.rate, this.name); }
68
+ // Adjust the frames so the last pose matches the first (DOFAnimationBuffer.make_loopable).
69
+ makeLoopable() {
70
+ if (this.n < 2) return this;
71
+ const last = this.n - 1;
72
+ const first = rootOf(this.frames, 0), end = rootOf(this.frames, last * NQ);
73
+ const delta = rootEndpointDelta(end, first);
74
+ const angle = new Float32Array(NQ);
75
+ for (let c = ROOT; c < NQ; c++) angle[c] = this.frames[c] - this.frames[last * NQ + c];
76
+ const ident = xf.identity();
77
+ for (let f = 0; f < this.n; f++) {
78
+ const w = f / last, o = f * NQ;
79
+ writeRoot(this.frames, applyRootCorrection(rootOf(this.frames, o), ident, delta, w), o);
80
+ for (let c = ROOT; c < NQ; c++) this.frames[o + c] += angle[c] * w;
81
+ }
82
+ return this;
83
+ }
84
+ }
85
+
86
+ // Parse a G1 CSV clip: cm, degrees, extrinsic XYZ Euler root, 120 Hz.
87
+ export function parseCsvClip(text, name = '') {
88
+ const lines = text.split(/\r?\n/).filter((l) => l.trim().length);
89
+ const header = lines[0].replace(/^/, '').split(',');
90
+ if (header[0] !== 'Frame' || header.length !== 1 + 6 + 29) throw new Error(`Unexpected CSV header in ${name}`);
91
+ const n = lines.length - 1;
92
+ const frames = new Float32Array(n * NQ);
93
+ const d2r = Math.PI / 180;
94
+ for (let i = 0; i < n; i++) {
95
+ const v = lines[i + 1].split(',').map(Number);
96
+ const o = i * NQ;
97
+ frames[o] = v[1] * 0.01; frames[o + 1] = v[2] * 0.01; frames[o + 2] = v[3] * 0.01;
98
+ const q = quat.fromEulerXYZExtrinsic(v[4] * d2r, v[5] * d2r, v[6] * d2r);
99
+ frames[o + 3] = q[0]; frames[o + 4] = q[1]; frames[o + 5] = q[2]; frames[o + 6] = q[3];
100
+ for (let j = 0; j < 29; j++) frames[o + ROOT + j] = v[7 + j] * d2r;
101
+ }
102
+ return new Clip(frames, CSV_RATE, name);
103
+ }
104
+
105
+ // Sample four 30 Hz poses starting at t0 into a Float32Array(4 * NQ).
106
+ export function sampleWindow(clip, t0, rootOffset = null, out = new Float32Array(PPT * NQ)) {
107
+ const tmp = new Float32Array(NQ);
108
+ for (let k = 0; k < PPT; k++) { clip.sample(t0 + k / FPS, tmp, rootOffset); out.set(tmp, k * NQ); }
109
+ return out;
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------------------------- endpoint correction
113
+ export function rootEndpointDelta(generated, guide) {
114
+ return { p: v3.sub(guide.p, generated.p), q: quat.norm(quat.mul(quat.inv(quat.norm(generated.q)), quat.norm(guide.q))) };
115
+ }
116
+ export function applyRootCorrection(root, start, end, endWeight) {
117
+ const sw = 1 - endWeight;
118
+ const I = [0, 0, 0, 1];
119
+ const q = quat.mul(quat.mul(root.q, quat.slerp(I, start.q, sw)), quat.slerp(I, end.q, endWeight));
120
+ return { p: v3.add(root.p, v3.add(v3.scale(start.p, sw), v3.scale(end.p, endWeight))), q: quat.norm(q) };
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------------------------- recorder
124
+ export class MotionRecorder {
125
+ constructor(pose, capacity = 32) {
126
+ this.capacity = capacity;
127
+ this.poses = new Float32Array(capacity * NQ);
128
+ this.dts = new Float32Array(capacity);
129
+ this.fill(pose);
130
+ }
131
+ fill(pose) {
132
+ for (let i = 0; i < this.capacity; i++) this.poses.set(pose, i * NQ);
133
+ this.dts.fill(0);
134
+ }
135
+ record(dt, pose) {
136
+ this.dts[this.capacity - 1] = dt;
137
+ this.dts.copyWithin(0, 1);
138
+ this.dts[this.capacity - 1] = 0;
139
+ this.poses.copyWithin(0, NQ);
140
+ this.poses.set(pose, (this.capacity - 1) * NQ);
141
+ }
142
+ latest() { return this.poses.subarray((this.capacity - 1) * NQ); }
143
+ }
144
+
145
+ // Sample `count` poses at `rate` ending at the latest pose of a history (motionbricks.utils.time_utils).
146
+ export function sampleHistory(poses, dts, count = PPT, rate = FPS, out = new Float32Array(count * NQ)) {
147
+ const n = dts.length;
148
+ const times = new Float64Array(n);
149
+ for (let f = n - 2; f >= 0; f--) times[f] = times[f + 1] - dts[f];
150
+ const first = -(count - 1) / rate;
151
+ const tmp = new Float32Array(NQ);
152
+ for (let s = 0; s < count; s++) {
153
+ const t = first + s / rate;
154
+ let upper = 0;
155
+ while (upper < n && times[upper] <= t) upper++;
156
+ upper = Math.min(upper, n - 1);
157
+ let lower = Math.max(upper - 1, 0);
158
+ const span = times[upper] - times[lower];
159
+ let blend = 0;
160
+ if (span > 0) blend = (t - times[lower]) / span; else lower = upper;
161
+ blendPose(poses, poses, clamp(blend, 0, 1), tmp, lower * NQ, upper * NQ);
162
+ out.set(tmp, s * NQ);
163
+ }
164
+ return out;
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------------------------- engine pre/post
168
+ // Build the ONNX feeds for one request. context: 4 poses, target: 1..4 poses (Float32Array k * NQ), world space.
169
+ export function buildFeeds(context, target, numTarget, allowed, heading = [1, 0]) {
170
+ const last = rootOf(context, (PPT - 1) * NQ);
171
+ const cur = quat.heading(last.q);
172
+ const des = Math.atan2(heading[1], heading[0]);
173
+ const align = { p: [last.p[0], last.p[1], 0], q: quat.yaw(cur - des) };
174
+ const qi = quat.inv(align.q);
175
+ const encode = (src, count) => {
176
+ const out = new Float32Array(PPT * NQ);
177
+ for (let k = 0; k < PPT; k++) {
178
+ const s = Math.min(k, count - 1) * NQ, o = k * NQ;
179
+ const r = rootOf(src, s);
180
+ const rel = quat.rotate(qi, v3.sub(r.p, align.p));
181
+ const q = quat.norm(quat.mul(qi, r.q));
182
+ out[o] = rel[0]; out[o + 1] = rel[1]; out[o + 2] = r.p[2];
183
+ out[o + 3] = q[0]; out[o + 4] = q[1]; out[o + 5] = q[2]; out[o + 6] = q[3];
184
+ for (let c = ROOT; c < NQ; c++) out[o + c] = src[s + c];
185
+ }
186
+ return out;
187
+ };
188
+ const given = new Int32Array(8), local = new Int32Array(8);
189
+ for (let i = 0; i < 8; i++) {
190
+ given[i] = i < PPT + numTarget ? 1 : 0;
191
+ local[i] = i === PPT - 1 || i === PPT + numTarget - 1 ? 0 : given[i];
192
+ }
193
+ const allowedMask = new Int32Array(11);
194
+ for (const c of allowed) if (c >= 6 && c <= 16) allowedMask[c - 6] = 1;
195
+ return {
196
+ feeds: {
197
+ context_qpos: encode(context, PPT),
198
+ target_qpos: encode(target, numTarget),
199
+ has_global_root_values: given,
200
+ has_local_root_values: local,
201
+ has_local_poses: given,
202
+ allowed_pred_num_tokens: allowedMask,
203
+ },
204
+ align,
205
+ };
206
+ }
207
+
208
+ // Decode the raw model output into world-space poses, with endpoint correction.
209
+ export function decodeOutput(predQpos, predContacts, ntok, align, context, target, correct = true) {
210
+ const rawCount = clamp(ntok * PPT, 0, 64);
211
+ const n = Math.max(0, rawCount - 2 * BOUNDARY);
212
+ const poses = new Float32Array(n * NQ);
213
+ const contacts = new Float32Array(n * 4);
214
+ const radius = ROOT_FILTER.length >> 1;
215
+ for (let f = 0; f < n; f++) {
216
+ const raw = f + BOUNDARY;
217
+ for (let c = 0; c < 4; c++) contacts[f * 4 + c] = clamp(predContacts[raw * 4 + c], 0, 1);
218
+ const pos = [0, 0, 0];
219
+ for (let t = 0; t < ROOT_FILTER.length; t++) {
220
+ const src = clamp(raw + t - radius, 0, rawCount - 1) * NQ;
221
+ for (let k = 0; k < 3; k++) pos[k] += ROOT_FILTER[t] * predQpos[src + k];
222
+ }
223
+ const q = quat.norm([predQpos[raw * NQ + 3], predQpos[raw * NQ + 4], predQpos[raw * NQ + 5], predQpos[raw * NQ + 6]]);
224
+ const wpos = v3.add(align.p, quat.rotate(align.q, pos));
225
+ writeRoot(poses, { p: [wpos[0], wpos[1], pos[2]], q: quat.mul(align.q, q) }, f * NQ);
226
+ for (let c = ROOT; c < NQ; c++) poses[f * NQ + c] = predQpos[raw * NQ + c];
227
+ }
228
+ if (correct && n >= 2) {
229
+ const ctxO = (PPT - 1) * NQ;
230
+ const d = [[0, context, ctxO], [n - 1, target, 0]].map(([frame, guide, go]) => {
231
+ const root = rootEndpointDelta(rootOf(poses, frame * NQ), rootOf(guide, go));
232
+ const ang = new Float32Array(NQ);
233
+ for (let c = ROOT; c < NQ; c++) ang[c] = guide[go + c] - poses[frame * NQ + c];
234
+ return { root, ang };
235
+ });
236
+ const fade = Math.min(JOINT_FADE_FRAMES, 0.5 * (n - 1));
237
+ for (let f = 0; f < n; f++) {
238
+ const ew = f / (n - 1), o = f * NQ;
239
+ writeRoot(poses, applyRootCorrection(rootOf(poses, o), d[0].root, d[1].root, ew), o);
240
+ const ws = quadraticFade(f / fade), we = quadraticFade((n - 1 - f) / fade);
241
+ for (let c = ROOT; c < NQ; c++) poses[o + c] += d[0].ang[c] * ws + d[1].ang[c] * we;
242
+ }
243
+ }
244
+ return { poses, contacts, n };
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------------------------- targets
248
+ // Scale the root's ground motion to a desired mean speed (adjust_target_dof_speed).
249
+ export function adjustTargetSpeed(poses, speed, count = PPT) {
250
+ const s = rootOf(poses, 0).p, e = rootOf(poses, (count - 1) * NQ).p;
251
+ const vx = (e[0] - s[0]) * FPS / (count - 1), vy = (e[1] - s[1]) * FPS / (count - 1);
252
+ const src = Math.hypot(vx, vy);
253
+ const scale = src <= 1e-6 ? 1 : speed / src;
254
+ for (let f = 1; f < count; f++) {
255
+ poses[f * NQ] = s[0] + (poses[f * NQ] - s[0]) * scale;
256
+ poses[f * NQ + 1] = s[1] + (poses[f * NQ + 1] - s[1]) * scale;
257
+ }
258
+ }
259
+
260
+ // Place blended local targets at a ground position, turned to a facing direction (place_target_dof).
261
+ export function placeTargets(groundPos, facing, blended, out = new Float32Array(blended.length), count = PPT) {
262
+ const placement = { p: [groundPos[0], groundPos[1], groundPos[2] || 0], q: quat.yaw(Math.atan2(facing[1], facing[0])) };
263
+ for (let f = 0; f < count; f++) {
264
+ out.set(blended.subarray(f * NQ, (f + 1) * NQ), f * NQ);
265
+ writeRoot(out, xf.mul(placement, rootOf(blended, f * NQ)), f * NQ);
266
+ }
267
+ return out;
268
+ }
269
+
270
+ // ---------------------------------------------------------------------------------------------- blend spaces
271
+ export class BlendSpace {
272
+ constructor(type, values) {
273
+ this.type = type; // 'linear' | 'directional'
274
+ this.values = values; // [[x, y], ...] in data order
275
+ if (type === 'linear') {
276
+ this.order = values.map((_, i) => i).sort((a, b) => values[a][0] - values[b][0]);
277
+ this.keys = this.order.map((i) => values[i][0]);
278
+ } else {
279
+ this.center = values.findIndex((v) => v[0] === 0 && v[1] === 0);
280
+ const order = values.map((_, i) => i).filter((i) => i !== this.center)
281
+ .sort((a, b) => Math.atan2(values[a][1], values[a][0]) - Math.atan2(values[b][1], values[b][0]));
282
+ this.angles = order.map((i) => Math.atan2(values[i][1], values[i][0]));
283
+ this.sectors = order.map((b, upper) => {
284
+ const a = order[(upper - 1 + order.length) % order.length];
285
+ const gap = ((this.angles[upper] - this.angles[(upper - 1 + order.length) % order.length]) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI);
286
+ const [ax, ay] = values[a], [bx, by] = values[b];
287
+ const det = ax * by - ay * bx;
288
+ if (gap >= Math.PI || det <= 0) return null;
289
+ return { a, b, inv: [by / det, -bx / det, -ay / det, ax / det] };
290
+ });
291
+ }
292
+ }
293
+ // Returns [[dataIndex, weight], ...]
294
+ evaluate(x, y = 0) {
295
+ if (this.values.length === 1) return [[0, 1]];
296
+ if (this.type === 'linear') {
297
+ x = clamp(x, this.keys[0], this.keys[this.keys.length - 1]);
298
+ let k = 0;
299
+ while (k < this.keys.length - 2 && x > this.keys[k + 1]) k++;
300
+ const a = this.order[k], b = this.order[k + 1];
301
+ const t = (x - this.keys[k]) / (this.keys[k + 1] - this.keys[k]);
302
+ return [[a, 1 - t], [b, t]];
303
+ }
304
+ if (Math.abs(x) > 1e-6 || Math.abs(y) > 1e-6) {
305
+ const ang = Math.atan2(y, x);
306
+ let upper = this.angles.findIndex((a) => a >= ang);
307
+ if (upper < 0) upper = 0;
308
+ const s = this.sectors[upper];
309
+ if (s) {
310
+ let wa = Math.max(0, s.inv[0] * x + s.inv[1] * y);
311
+ let wb = Math.max(0, s.inv[2] * x + s.inv[3] * y);
312
+ const total = Math.max(1, wa + wb);
313
+ wa /= total; wb /= total;
314
+ return [[s.a, wa], [s.b, wb], [this.center, Math.max(0, 1 - wa - wb)]];
315
+ }
316
+ }
317
+ return [[this.center, 1]];
318
+ }
319
+ }
320
+
321
+ // Weighted blend of target windows (each Float32Array(4 * NQ)) -> Float32Array(4 * NQ).
322
+ export function blendTargets(targets, weights, linear, out = new Float32Array(PPT * NQ)) {
323
+ if (linear) {
324
+ const [[a, wa], [b, wb]] = weights;
325
+ for (let f = 0; f < PPT; f++) {
326
+ const tmp = blendPose(targets[a], targets[b], wb, new Float32Array(NQ), f * NQ, f * NQ);
327
+ out.set(tmp, f * NQ);
328
+ }
329
+ return out;
330
+ }
331
+ for (let f = 0; f < PPT; f++) {
332
+ const o = f * NQ;
333
+ let acc = [0, 0, 0, 0], pos = [0, 0, 0], wsum = 0;
334
+ for (let c = ROOT; c < NQ; c++) out[o + c] = 0;
335
+ for (const [i, w] of weights) {
336
+ if (w <= 0) continue;
337
+ const r = rootOf(targets[i], o);
338
+ const q = quat.dot(acc, r.q) < 0 ? r.q.map((v) => -v) : r.q;
339
+ for (let k = 0; k < 4; k++) acc[k] += q[k] * w;
340
+ for (let k = 0; k < 3; k++) pos[k] += r.p[k] * w;
341
+ for (let c = ROOT; c < NQ; c++) out[o + c] += targets[i][o + c] * w;
342
+ wsum += w;
343
+ }
344
+ writeRoot(out, { p: pos, q: quat.norm(acc) }, o);
345
+ }
346
+ return out;
347
+ }
js/primitives.js ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Smart Primitives: target poses placed around an object, with sequences, pivots and interaction boxes.
2
+ // Port of motionbricks/runtime/smart_primitive.py, pivot.py and the app's behaviors for the G1 rig.
3
+
4
+ import { quat, v3, xf, clamp, wrapAngle } from './mathx.js';
5
+ import { NQ, PPT, FPS, rootOf, writeRoot, sampleWindow } from './motion.js';
6
+
7
+ const AXES = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
8
+
9
+ // Resolve "../../motions/unitree_g1/x.csv" relative to "assets/smart_primitives/unitree_g1/doc.json".
10
+ export function resolvePath(base, rel) {
11
+ const parts = base.split('/').slice(0, -1);
12
+ for (const p of rel.split('/')) {
13
+ if (p === '..') parts.pop(); else if (p !== '.') parts.push(p);
14
+ }
15
+ return parts.join('/');
16
+ }
17
+
18
+ export function clipPathsOfDocument(doc, docPath) {
19
+ const out = new Set();
20
+ const walk = (n) => {
21
+ for (const c of n.components || []) if (c.type === 'target_pose' && c.clip) out.add(resolvePath(docPath, c.clip));
22
+ for (const ch of n.children || []) walk(ch);
23
+ };
24
+ walk(doc.root);
25
+ return [...out];
26
+ }
27
+
28
+ export class Pivot {
29
+ constructor(c) {
30
+ const d = c.motion_direction || [0, 1, 0];
31
+ this.motion = v3.norm(d);
32
+ this.order = c.operation_order || 'translation_then_rotation';
33
+ this.tAxis = c.translation_axis || 'none';
34
+ this.tCon = c.translation_constraint || 'unconstrained';
35
+ this.lineMin = c.line_min_offset ?? -0.5;
36
+ this.lineMax = c.line_max_offset ?? 0.5;
37
+ this.rAxis = c.rotation_axis || 'none';
38
+ this.rCon = c.rotation_constraint || 'unconstrained';
39
+ this.cone = ((c.cone_half_angle_degrees ?? 45) * Math.PI) / 180;
40
+ this.coneSide = c.cone_side || 'forward';
41
+ }
42
+ aligned(authored, current, ch) {
43
+ let limits = authored, pos = current.p, rot = current.q;
44
+ if (this.order === 'rotation_then_translation') {
45
+ rot = this._rotation(limits, rot, ch);
46
+ if (this.rAxis !== 'none') limits = { p: limits.p, q: rot };
47
+ pos = this._position(limits, pos, ch);
48
+ } else {
49
+ pos = this._position(limits, pos, ch);
50
+ rot = this._rotation(limits, rot, ch);
51
+ }
52
+ return { p: pos, q: rot };
53
+ }
54
+ _position(limits, current, ch) {
55
+ if (this.tAxis === 'none') return current;
56
+ const axis = v3.norm(xf.vector(limits, AXES[this.tAxis]));
57
+ if (this.tCon === 'line_projection') {
58
+ const a = v3.add(limits.p, v3.scale(axis, this.lineMin)), b = v3.add(limits.p, v3.scale(axis, this.lineMax));
59
+ return closestPointToSegment(a, b, ch.probe[0], ch.probe[1]);
60
+ }
61
+ const origin = limits.p, rel = v3.sub(ch.position, origin);
62
+ const nearest = v3.dot(rel, axis);
63
+ let offset = nearest;
64
+ const speed = v3.len(ch.desiredVelocity);
65
+ if (speed > 1e-6) {
66
+ const ray = v3.scale(ch.desiredVelocity, 1 / speed);
67
+ const cos = v3.dot(axis, ray), den = 1 - cos * cos;
68
+ if (den > 1e-6) offset = (nearest - cos * v3.dot(rel, ray)) / den;
69
+ if (v3.dot(v3.sub(v3.add(origin, v3.scale(axis, offset)), ch.position), ray) < 0) offset = nearest;
70
+ }
71
+ return v3.add(origin, v3.scale(axis, offset));
72
+ }
73
+ _rotation(limits, current, ch) {
74
+ if (this.rAxis === 'none') return current;
75
+ const axis = v3.norm(xf.vector(limits, AXES[this.rAxis]));
76
+ let motion = xf.vector(limits, this.motion);
77
+ motion = v3.sub(motion, v3.scale(axis, v3.dot(motion, axis)));
78
+ let desired = v3.sub(ch.desiredVelocity, v3.scale(axis, v3.dot(ch.desiredVelocity, axis)));
79
+ if (v3.len(motion) <= 1e-6 || v3.len(desired) <= 1e-6) return current;
80
+ let angle = Math.atan2(v3.dot(axis, v3.cross(motion, desired)), v3.dot(motion, desired));
81
+ if (this.rCon === 'cone') {
82
+ const centers = this.coneSide === 'both' ? [0, Math.PI] : [this.coneSide === 'mirrored' ? Math.PI : 0];
83
+ let best = null;
84
+ for (const c of centers) {
85
+ const delta = wrapAngle(angle - c);
86
+ const cl = clamp(delta, -this.cone, this.cone);
87
+ const cand = [Math.abs(delta - cl), c + cl];
88
+ if (!best || cand[0] < best[0]) best = cand;
89
+ }
90
+ angle = best[1];
91
+ }
92
+ return quat.norm(quat.mul(quat.fromAxisAngle(axis, angle), limits.q));
93
+ }
94
+ }
95
+
96
+ function closestPointOnSegment(s, e, p) {
97
+ const seg = v3.sub(e, s);
98
+ const t = v3.dot(v3.sub(p, s), seg) / (v3.lenSq(seg) + 1e-6);
99
+ return v3.add(s, v3.scale(seg, clamp(t, 0, 1)));
100
+ }
101
+ function closestPointToSegment(s, e, os, oe) {
102
+ const hl = (a, b) => { const v = v3.sub(b, a), l = v3.len(v); return [0.5 * l, l > 0 ? v3.scale(v, 1 / l) : v]; };
103
+ const [h, d] = hl(s, e), [oh, od] = hl(os, oe);
104
+ const c = v3.add(s, v3.scale(d, h)), oc = v3.add(os, v3.scale(od, oh));
105
+ const off = v3.sub(c, oc);
106
+ const cos = v3.dot(d, od), along = v3.dot(d, off), oalong = v3.dot(od, off);
107
+ const t = (cos * oalong - along) / (1 - cos * cos + 1e-6);
108
+ const ot = oalong + cos * t;
109
+ const point = v3.add(c, v3.scale(d, clamp(t, -h, h)));
110
+ const opoint = v3.add(oc, v3.scale(od, clamp(ot, -oh, oh)));
111
+ const proj = closestPointOnSegment(s, e, opoint);
112
+ const oproj = closestPointOnSegment(os, oe, point);
113
+ return v3.lenSq(v3.sub(opoint, proj)) < v3.lenSq(v3.sub(point, oproj)) ? proj : point;
114
+ }
115
+
116
+ // Oriented box overlap on all 15 separating axes. Boxes are {t: xf, half: [x, y, z]}.
117
+ export function boxesOverlap(a, b) {
118
+ const ra = quat.toMat3(a.t.q), rb = quat.toMat3(b.t.q);
119
+ const r = [[0, 0, 0], [0, 0, 0], [0, 0, 0]], ar = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
120
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
121
+ r[i][j] = ra[0][i] * rb[0][j] + ra[1][i] * rb[1][j] + ra[2][i] * rb[2][j];
122
+ ar[i][j] = Math.abs(r[i][j]) + 1e-6;
123
+ }
124
+ const dp = v3.sub(b.t.p, a.t.p);
125
+ const t = [0, 1, 2].map((i) => ra[0][i] * dp[0] + ra[1][i] * dp[1] + ra[2][i] * dp[2]);
126
+ const ea = a.half, eb = b.half;
127
+ for (let i = 0; i < 3; i++) if (Math.abs(t[i]) > ea[i] + eb[0] * ar[i][0] + eb[1] * ar[i][1] + eb[2] * ar[i][2]) return false;
128
+ for (let j = 0; j < 3; j++) {
129
+ const d = Math.abs(t[0] * r[0][j] + t[1] * r[1][j] + t[2] * r[2][j]);
130
+ if (d > ea[0] * ar[0][j] + ea[1] * ar[1][j] + ea[2] * ar[2][j] + eb[j]) return false;
131
+ }
132
+ for (let i = 0; i < 3; i++) {
133
+ const i1 = (i + 1) % 3, i2 = (i + 2) % 3;
134
+ for (let j = 0; j < 3; j++) {
135
+ const j1 = (j + 1) % 3, j2 = (j + 2) % 3;
136
+ const raa = ea[i1] * ar[i2][j] + ea[i2] * ar[i1][j];
137
+ const rbb = eb[j1] * ar[i][j2] + eb[j2] * ar[i][j1];
138
+ if (Math.abs(t[i2] * r[i1][j] - t[i1] * r[i2][j]) > raa + rbb) return false;
139
+ }
140
+ }
141
+ return true;
142
+ }
143
+
144
+ // One Smart Primitive instance built from a document and the clips it samples.
145
+ export class SmartPrimitive {
146
+ constructor(doc, docPath, clips) {
147
+ this.name = doc.name;
148
+ this.nodes = [];
149
+ const byId = new Map();
150
+ const walk = (n, parent) => {
151
+ const index = this.nodes.length;
152
+ const node = { id: n.id, name: n.name, parent, local: xf.fromJson(n.local_transform), target: null, box: null, pivot: null };
153
+ this.nodes.push(node);
154
+ byId.set(n.id, index);
155
+ for (const c of n.components || []) {
156
+ if (c.type === 'target_pose') node.target = this._sampleTarget(c, docPath, clips);
157
+ else if (c.type === 'interaction_box') node.box = { half: [0.5 * c.width, 0.5 * c.depth, 0.5 * c.height] };
158
+ else if (c.type === 'pivot') node.pivot = new Pivot(c);
159
+ }
160
+ for (const ch of n.children || []) walk(ch, index);
161
+ };
162
+ walk(doc.root, -1);
163
+ this.sequences = (doc.sequences || []).map((s) => {
164
+ const nodes = s.node_ids.map((id) => byId.get(id));
165
+ return { name: s.name, nodes, pivot: s.pivot_node_id != null ? byId.get(s.pivot_node_id) : -1, startSpeed: this.nodes[nodes[0]].target.speed };
166
+ });
167
+ this.authoredPivots = null;
168
+ this._world = null;
169
+ }
170
+
171
+ _sampleTarget(c, docPath, clips) {
172
+ const path = resolvePath(docPath, c.clip);
173
+ const clip = clips.get(path);
174
+ if (!clip) throw new Error(`Missing clip ${path}`);
175
+ const t = c.playback_mode === 'frames' ? c.frame_index / clip.rate : c.sample_time_seconds;
176
+ let offset = null;
177
+ if (c.hips_constrained) {
178
+ const p = clip.sample(t);
179
+ offset = { p: [-p[0], -p[1], 0], q: [0, 0, 0, 1] };
180
+ }
181
+ const window = sampleWindow(clip, t, offset);
182
+ const r0 = rootOf(window, 0).p, r1 = rootOf(window, NQ).p;
183
+ const speed = c.num_poses_to_use === 1 ? 0 : v3.len(v3.sub(r1, r0)) * FPS;
184
+ const allowed = [];
185
+ for (let k = c.min_tokens; k <= c.max_tokens; k++) allowed.push(k);
186
+ return {
187
+ window,
188
+ speed,
189
+ params: { numPoses: c.num_poses_to_use, transitionEarly: c.transition_early_by_frames, allowed },
190
+ };
191
+ }
192
+
193
+ nodeIndex(name) { return this.nodes.findIndex((n) => n.name === name); }
194
+ sequenceIndex(name) { return this.sequences.findIndex((s) => s.name === name); }
195
+
196
+ world() {
197
+ if (!this._world) {
198
+ this._world = this.nodes.map(() => null);
199
+ this.nodes.forEach((n, i) => { this._world[i] = n.parent < 0 ? n.local : xf.mul(this._world[n.parent], n.local); });
200
+ }
201
+ return this._world;
202
+ }
203
+ setNodeWorld(i, t) {
204
+ const n = this.nodes[i];
205
+ n.local = n.parent < 0 ? xf.make(t.p, t.q) : xf.mul(xf.inv(this.world()[n.parent]), t);
206
+ this._world = null;
207
+ }
208
+
209
+ // Poses of a node's target relative to its parent (locomotion blend targets).
210
+ localTarget(i) { return this._placeWindow(this.nodes[i].target.window, this.nodes[i].local); }
211
+ worldTarget(i) { return this._placeWindow(this.nodes[i].target.window, this.world()[i]); }
212
+ _placeWindow(window, t) {
213
+ const out = new Float32Array(window.length);
214
+ for (let f = 0; f < PPT; f++) {
215
+ out.set(window.subarray(f * NQ, (f + 1) * NQ), f * NQ);
216
+ writeRoot(out, xf.mul(t, rootOf(window, f * NQ)), f * NQ);
217
+ }
218
+ return out;
219
+ }
220
+
221
+ alignSequencePivot(s, ch) {
222
+ const node = this.sequences[s].pivot;
223
+ if (node < 0) return;
224
+ const w = this.world();
225
+ if (!this.authoredPivots) {
226
+ this.authoredPivots = new Map();
227
+ this.nodes.forEach((n, i) => { if (n.pivot) this.authoredPivots.set(i, xf.make(w[i].p, w[i].q)); });
228
+ }
229
+ this.setNodeWorld(node, this.nodes[node].pivot.aligned(this.authoredPivots.get(node), w[node], ch));
230
+ }
231
+ worldTargetsForSequence(s) {
232
+ return this.sequences[s].nodes.map((i) => ({ poses: this.worldTarget(i), params: this.nodes[i].target.params, node: i }));
233
+ }
234
+ worldBoxes() {
235
+ const w = this.world();
236
+ return this.nodes.map((n, i) => (n.box ? { t: w[i], half: n.box.half } : null)).filter(Boolean);
237
+ }
238
+ }
239
+
240
+ // ------------------------------------------------------------------------------------------- behaviors
241
+ export class VelocityMatchingSequenceBehavior {
242
+ constructor(sp) { this.sp = sp; }
243
+ enter(state) {
244
+ const ch = state.character.properties();
245
+ const speed = v3.len(ch.velocity);
246
+ let best = 0;
247
+ this.sp.sequences.forEach((s, i) => { if (Math.abs(s.startSpeed - speed) < Math.abs(this.sp.sequences[best].startSpeed - speed)) best = i; });
248
+ this.sp.alignSequencePivot(best, ch);
249
+ state.playTargets(this.sp.worldTargetsForSequence(best), null, this.sp.sequences[best].name);
250
+ }
251
+ interact() {}
252
+ }
253
+
254
+ export class SittingBehavior {
255
+ constructor(sp, sitLoopClip) { this.sp = sp; this.loop = sitLoopClip; }
256
+ enter(state) {
257
+ this.state = state;
258
+ state.playSequence(this.sp, 'Sit', () => state.playClip(this.loop, { loop: true, alignToCurrent: true }));
259
+ }
260
+ interact() {
261
+ if (this.state && this.state.isLooping) this.state.playSequence(this.sp, 'Stand');
262
+ }
263
+ }
js/robot.js ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Unitree G1 for three.js: GLB meshes per MJCF body, posed from 36 joint coordinates.
2
+ // Robots live inside a Z-up group (see main.js), so poses are applied in model space directly.
3
+
4
+ import * as THREE from 'three';
5
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
6
+ import { toCreasedNormals } from 'three/addons/utils/BufferGeometryUtils.js';
7
+
8
+ export async function loadRobotModel(glbUrl, kinUrl) {
9
+ const [gltf, kin] = await Promise.all([
10
+ new GLTFLoader().loadAsync(glbUrl),
11
+ fetch(kinUrl).then((r) => r.json()),
12
+ ]);
13
+ const geometries = new Map();
14
+ gltf.scene.traverse((o) => {
15
+ if (!o.isMesh) return;
16
+ const g = toCreasedNormals(o.geometry, (35 * Math.PI) / 180);
17
+ g.applyMatrix4(o.matrix);
18
+ g.computeBoundingSphere();
19
+ geometries.set(o.name, g);
20
+ });
21
+ return { geometries, bodies: kin.bodies, jointNames: kin.joint_names };
22
+ }
23
+
24
+ export function heroMaterials() {
25
+ return {
26
+ light: new THREE.MeshPhysicalMaterial({ color: 0xe9ebee, roughness: 0.3, metalness: 0.05, clearcoat: 0.6, clearcoatRoughness: 0.25 }),
27
+ dark: new THREE.MeshStandardMaterial({ color: 0x1f2227, roughness: 0.45, metalness: 0.4 }),
28
+ };
29
+ }
30
+
31
+ export function ghostMaterials(color, opacity = 0.22) {
32
+ const m = new THREE.MeshStandardMaterial({
33
+ color, emissive: color, emissiveIntensity: 0.55, transparent: true, opacity, depthWrite: false, roughness: 0.6,
34
+ });
35
+ return { light: m, dark: m };
36
+ }
37
+
38
+ const _q = new THREE.Quaternion();
39
+ const _axis = new THREE.Vector3();
40
+
41
+ export class Robot {
42
+ constructor(model, materials, { castShadow = true } = {}) {
43
+ this.root = new THREE.Group();
44
+ this.links = [];
45
+ this.byName = new Map();
46
+ for (const b of model.bodies) {
47
+ const obj = new THREE.Group();
48
+ obj.name = b.name;
49
+ obj.position.fromArray(b.pos);
50
+ const q0 = new THREE.Quaternion(b.quat_xyzw[0], b.quat_xyzw[1], b.quat_xyzw[2], b.quat_xyzw[3]);
51
+ obj.quaternion.copy(q0);
52
+ for (const meshName of b.meshes || []) {
53
+ const geo = model.geometries.get(meshName);
54
+ if (!geo) continue;
55
+ const mesh = new THREE.Mesh(geo, meshName.endsWith('__dark') ? materials.dark : materials.light);
56
+ mesh.castShadow = castShadow;
57
+ mesh.receiveShadow = castShadow;
58
+ obj.add(mesh);
59
+ }
60
+ (b.parent < 0 ? this.root : this.links[b.parent].obj).add(obj);
61
+ this.links.push({ obj, q0, axis: b.axis ? new THREE.Vector3().fromArray(b.axis) : null, dof: b.dof ?? -1 });
62
+ this.byName.set(b.name, obj);
63
+ }
64
+ this.pelvis = this.links[0].obj;
65
+ }
66
+ setPose(q) {
67
+ const p = this.pelvis;
68
+ p.position.set(q[0], q[1], q[2]);
69
+ p.quaternion.set(q[3], q[4], q[5], q[6]).normalize();
70
+ for (let i = 1; i < this.links.length; i++) {
71
+ const l = this.links[i];
72
+ if (l.dof < 0) continue;
73
+ _q.setFromAxisAngle(_axis.copy(l.axis), q[7 + l.dof]);
74
+ l.obj.quaternion.copy(l.q0).multiply(_q);
75
+ }
76
+ }
77
+ set visible(v) { this.root.visible = v; }
78
+ get visible() { return this.root.visible; }
79
+ }
js/worker.js ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Runs the MotionBricks G1 ONNX model with onnxruntime-web (WASM) off the main thread.
2
+ /* global ort */
3
+ importScripts('https://cdn.jsdelivr.net/npm/onnxruntime-web@1.30.0/dist/ort.wasm.min.js');
4
+
5
+ let session = null;
6
+
7
+ async function cachedFetch(url, onProgress) {
8
+ let cache = null;
9
+ try { cache = await caches.open('motionbricks-models-v1'); } catch (e) { cache = null; }
10
+ if (cache) {
11
+ const hit = await cache.match(url);
12
+ if (hit) {
13
+ onProgress(1, 1, true);
14
+ return new Uint8Array(await hit.arrayBuffer());
15
+ }
16
+ }
17
+ const response = await fetch(url, { mode: 'cors' });
18
+ if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
19
+ const total = Number(response.headers.get('content-length')) || 0;
20
+ const reader = response.body.getReader();
21
+ const chunks = [];
22
+ let received = 0;
23
+ for (;;) {
24
+ const { done, value } = await reader.read();
25
+ if (done) break;
26
+ chunks.push(value);
27
+ received += value.length;
28
+ onProgress(received, total, false);
29
+ }
30
+ const bytes = new Uint8Array(received);
31
+ let offset = 0;
32
+ for (const c of chunks) { bytes.set(c, offset); offset += c.length; }
33
+ if (cache) {
34
+ try { await cache.put(url, new Response(bytes, { headers: { 'content-type': 'application/octet-stream' } })); } catch (e) { /* quota */ }
35
+ }
36
+ return bytes;
37
+ }
38
+
39
+ self.onmessage = async (event) => {
40
+ const msg = event.data;
41
+ if (msg.type === 'load') {
42
+ try {
43
+ const threads = self.crossOriginIsolated ? Math.max(1, Math.min(8, (navigator.hardwareConcurrency || 4) - 1)) : 1;
44
+ ort.env.wasm.numThreads = threads;
45
+ ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.30.0/dist/';
46
+ let bytes = null;
47
+ let lastError = null;
48
+ for (const url of msg.urls) {
49
+ try {
50
+ bytes = await cachedFetch(url, (r, t, cached) => self.postMessage({ type: 'progress', received: r, total: t, cached }));
51
+ break;
52
+ } catch (e) { lastError = e; }
53
+ }
54
+ if (!bytes) throw lastError || new Error('Model download failed');
55
+ self.postMessage({ type: 'compiling' });
56
+ const t0 = performance.now();
57
+ session = await ort.InferenceSession.create(bytes, { executionProviders: ['wasm'], graphOptimizationLevel: 'all' });
58
+ self.postMessage({ type: 'ready', threads, compileMs: performance.now() - t0 });
59
+ } catch (e) {
60
+ self.postMessage({ type: 'error', message: String(e && e.message ? e.message : e) });
61
+ }
62
+ return;
63
+ }
64
+ if (msg.type === 'run') {
65
+ const f = msg.feeds;
66
+ const n = f.n || 1;
67
+ const t0 = performance.now();
68
+ try {
69
+ const out = await session.run({
70
+ context_qpos: new ort.Tensor('float32', f.context_qpos, [n, 4, 36]),
71
+ target_qpos: new ort.Tensor('float32', f.target_qpos, [n, 4, 36]),
72
+ has_global_root_values: new ort.Tensor('int32', f.has_global_root_values, [n, 8]),
73
+ has_local_root_values: new ort.Tensor('int32', f.has_local_root_values, [n, 8]),
74
+ has_local_poses: new ort.Tensor('int32', f.has_local_poses, [n, 8]),
75
+ allowed_pred_num_tokens: new ort.Tensor('int32', f.allowed_pred_num_tokens, [n, 11]),
76
+ });
77
+ const pred_qpos = out.pred_qpos.data, pred_foot_contacts = out.pred_foot_contacts.data;
78
+ const ntok = Array.from(out.pred_num_tokens.data, Number);
79
+ self.postMessage({ type: 'result', id: msg.id, pred_qpos, pred_foot_contacts, ntok, ms: performance.now() - t0 },
80
+ [pred_qpos.buffer, pred_foot_contacts.buffer]);
81
+ } catch (e) {
82
+ self.postMessage({ type: 'result', id: msg.id, error: String(e && e.message ? e.message : e) });
83
+ }
84
+ }
85
+ };
licenses/motionbricks-Apache-2.0.txt ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ This code is dual-licensed with documentation/skills/assets under the CC-BY-4.0 AND source code under Apache-2.0 license terms.
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
205
+
206
+ ===============================================================================
207
+ NVIDIA RIG ASSETS
208
+ ===============================================================================
209
+
210
+ NVIDIA's contributions to the following rig assets are licensed under the Apache
211
+ License, Version 2.0, above:
212
+
213
+ motionbricks/assets/human/soma_base_skel_minimal_no_root.usd
214
+ tools/onnx/assets/g1_model_rig.npz
215
+ tools/onnx/assets/soma_model_rig.npz
216
+
217
+ The SOMA asset is adapted from the minimal rig in NVIDIA SOMA Retargeter. The NPZ
218
+ files contain rig offsets and conversion data prepared by NVIDIA for the ONNX
219
+ exporter. These assets are separate from pretrained models and sample motion data.
220
+
221
+ The Unitree robot-description and mesh assets retain the third-party terms below.
222
+
223
+ ===============================================================================
224
+ SAMPLE MOTION DATA
225
+ ===============================================================================
226
+
227
+ The BVH files in assets/motions/soma/ and CSV files in
228
+ assets/motions/unitree_g1/ listed in assets/motions/README.md are provided under
229
+ the NVIDIA Sample Data Evaluation License in assets/motions/LICENSE.txt,
230
+ separately from the Apache 2.0 source-code license above.
231
+
232
+ This notice covers only those listed motion files. It does not apply the sample
233
+ license to model weights, ONNX models, robot assets, rig metadata, Smart Primitive
234
+ documents, or scene files.
235
+
236
+ ===============================================================================
237
+ THIRD-PARTY ROBOT ASSET LICENSES
238
+ ===============================================================================
239
+
240
+ Unitree robot assets
241
+ Applies to:
242
+ motionbricks/assets/robots/unitree_g1/**
243
+ License copy: licenses/unitree-LICENSE.txt
244
+
245
+ BSD 3-Clause License
246
+
247
+ Copyright (c) 2016-2022 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")
248
+ All rights reserved.
249
+
250
+ Redistribution and use in source and binary forms, with or without
251
+ modification, are permitted provided that the following conditions are met:
252
+
253
+ * Redistributions of source code must retain the above copyright notice, this
254
+ list of conditions and the following disclaimer.
255
+
256
+ * Redistributions in binary form must reproduce the above copyright notice,
257
+ this list of conditions and the following disclaimer in the documentation
258
+ and/or other materials provided with the distribution.
259
+
260
+ * Neither the name of the copyright holder nor the names of its
261
+ contributors may be used to endorse or promote products derived from
262
+ this software without specific prior written permission.
263
+
264
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
265
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
266
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
267
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
268
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
269
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
270
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
271
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
272
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
273
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
274
+
275
+ ===============================================================================
276
+ NVIDIA-AUTHORED DOCUMENTATION AND MEDIA
277
+ ===============================================================================
278
+
279
+ NVIDIA-authored documentation text and media (images, screenshots, and videos,
280
+ including the files in docs/media/) are licensed under Creative Commons Attribution
281
+ 4.0 International (CC-BY-4.0), reproduced below. Source code, code examples, and
282
+ code snippets remain under the Apache License, Version 2.0.
283
+
284
+ This license does not change the separate terms for models, sample motion data,
285
+ rig assets, or third-party materials described in this repository.
286
+
287
+ Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
288
+
289
+
290
+ Attribution 4.0 International
291
+
292
+ =======================================================================
293
+
294
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
295
+ does not provide legal services or legal advice. Distribution of
296
+ Creative Commons public licenses does not create a lawyer-client or
297
+ other relationship. Creative Commons makes its licenses and related
298
+ information available on an "as-is" basis. Creative Commons gives no
299
+ warranties regarding its licenses, any material licensed under their
300
+ terms and conditions, or any related information. Creative Commons
301
+ disclaims all liability for damages resulting from their use to the
302
+ fullest extent possible.
303
+
304
+ Using Creative Commons Public Licenses
305
+
306
+ Creative Commons public licenses provide a standard set of terms and
307
+ conditions that creators and other rights holders may use to share
308
+ original works of authorship and other material subject to copyright
309
+ and certain other rights specified in the public license below. The
310
+ following considerations are for informational purposes only, are not
311
+ exhaustive, and do not form part of our licenses.
312
+
313
+ Considerations for licensors: Our public licenses are
314
+ intended for use by those authorized to give the public
315
+ permission to use material in ways otherwise restricted by
316
+ copyright and certain other rights. Our licenses are
317
+ irrevocable. Licensors should read and understand the terms
318
+ and conditions of the license they choose before applying it.
319
+ Licensors should also secure all rights necessary before
320
+ applying our licenses so that the public can reuse the
321
+ material as expected. Licensors should clearly mark any
322
+ material not subject to the license. This includes other CC-
323
+ licensed material, or material used under an exception or
324
+ limitation to copyright. More considerations for licensors:
325
+ wiki.creativecommons.org/Considerations_for_licensors
326
+
327
+ Considerations for the public: By using one of our public
328
+ licenses, a licensor grants the public permission to use the
329
+ licensed material under specified terms and conditions. If
330
+ the licensor's permission is not necessary for any reason--for
331
+ example, because of any applicable exception or limitation to
332
+ copyright--then that use is not regulated by the license. Our
333
+ licenses grant only permissions under copyright and certain
334
+ other rights that a licensor has authority to grant. Use of
335
+ the licensed material may still be restricted for other
336
+ reasons, including because others have copyright or other
337
+ rights in the material. A licensor may make special requests,
338
+ such as asking that all changes be marked or described.
339
+ Although not required by our licenses, you are encouraged to
340
+ respect those requests where reasonable. More considerations
341
+ for the public:
342
+ wiki.creativecommons.org/Considerations_for_licensees
343
+
344
+ =======================================================================
345
+
346
+ Creative Commons Attribution 4.0 International Public License
347
+
348
+ By exercising the Licensed Rights (defined below), You accept and agree
349
+ to be bound by the terms and conditions of this Creative Commons
350
+ Attribution 4.0 International Public License ("Public License"). To the
351
+ extent this Public License may be interpreted as a contract, You are
352
+ granted the Licensed Rights in consideration of Your acceptance of
353
+ these terms and conditions, and the Licensor grants You such rights in
354
+ consideration of benefits the Licensor receives from making the
355
+ Licensed Material available under these terms and conditions.
356
+
357
+
358
+ Section 1 -- Definitions.
359
+
360
+ a. Adapted Material means material subject to Copyright and Similar
361
+ Rights that is derived from or based upon the Licensed Material
362
+ and in which the Licensed Material is translated, altered,
363
+ arranged, transformed, or otherwise modified in a manner requiring
364
+ permission under the Copyright and Similar Rights held by the
365
+ Licensor. For purposes of this Public License, where the Licensed
366
+ Material is a musical work, performance, or sound recording,
367
+ Adapted Material is always produced where the Licensed Material is
368
+ synched in timed relation with a moving image.
369
+
370
+ b. Adapter's License means the license You apply to Your Copyright
371
+ and Similar Rights in Your contributions to Adapted Material in
372
+ accordance with the terms and conditions of this Public License.
373
+
374
+ c. Copyright and Similar Rights means copyright and/or similar rights
375
+ closely related to copyright including, without limitation,
376
+ performance, broadcast, sound recording, and Sui Generis Database
377
+ Rights, without regard to how the rights are labeled or
378
+ categorized. For purposes of this Public License, the rights
379
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
380
+ Rights.
381
+
382
+ d. Effective Technological Measures means those measures that, in the
383
+ absence of proper authority, may not be circumvented under laws
384
+ fulfilling obligations under Article 11 of the WIPO Copyright
385
+ Treaty adopted on December 20, 1996, and/or similar international
386
+ agreements.
387
+
388
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
389
+ any other exception or limitation to Copyright and Similar Rights
390
+ that applies to Your use of the Licensed Material.
391
+
392
+ f. Licensed Material means the artistic or literary work, database,
393
+ or other material to which the Licensor applied this Public
394
+ License.
395
+
396
+ g. Licensed Rights means the rights granted to You subject to the
397
+ terms and conditions of this Public License, which are limited to
398
+ all Copyright and Similar Rights that apply to Your use of the
399
+ Licensed Material and that the Licensor has authority to license.
400
+
401
+ h. Licensor means the individual(s) or entity(ies) granting rights
402
+ under this Public License.
403
+
404
+ i. Share means to provide material to the public by any means or
405
+ process that requires permission under the Licensed Rights, such
406
+ as reproduction, public display, public performance, distribution,
407
+ dissemination, communication, or importation, and to make material
408
+ available to the public including in ways that members of the
409
+ public may access the material from a place and at a time
410
+ individually chosen by them.
411
+
412
+ j. Sui Generis Database Rights means rights other than copyright
413
+ resulting from Directive 96/9/EC of the European Parliament and of
414
+ the Council of 11 March 1996 on the legal protection of databases,
415
+ as amended and/or succeeded, as well as other essentially
416
+ equivalent rights anywhere in the world.
417
+
418
+ k. You means the individual or entity exercising the Licensed Rights
419
+ under this Public License. Your has a corresponding meaning.
420
+
421
+
422
+ Section 2 -- Scope.
423
+
424
+ a. License grant.
425
+
426
+ 1. Subject to the terms and conditions of this Public License,
427
+ the Licensor hereby grants You a worldwide, royalty-free,
428
+ non-sublicensable, non-exclusive, irrevocable license to
429
+ exercise the Licensed Rights in the Licensed Material to:
430
+
431
+ a. reproduce and Share the Licensed Material, in whole or
432
+ in part; and
433
+
434
+ b. produce, reproduce, and Share Adapted Material.
435
+
436
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
437
+ Exceptions and Limitations apply to Your use, this Public
438
+ License does not apply, and You do not need to comply with
439
+ its terms and conditions.
440
+
441
+ 3. Term. The term of this Public License is specified in Section
442
+ 6(a).
443
+
444
+ 4. Media and formats; technical modifications allowed. The
445
+ Licensor authorizes You to exercise the Licensed Rights in
446
+ all media and formats whether now known or hereafter created,
447
+ and to make technical modifications necessary to do so. The
448
+ Licensor waives and/or agrees not to assert any right or
449
+ authority to forbid You from making technical modifications
450
+ necessary to exercise the Licensed Rights, including
451
+ technical modifications necessary to circumvent Effective
452
+ Technological Measures. For purposes of this Public License,
453
+ simply making modifications authorized by this Section 2(a)
454
+ (4) never produces Adapted Material.
455
+
456
+ 5. Downstream recipients.
457
+
458
+ a. Offer from the Licensor -- Licensed Material. Every
459
+ recipient of the Licensed Material automatically
460
+ receives an offer from the Licensor to exercise the
461
+ Licensed Rights under the terms and conditions of this
462
+ Public License.
463
+
464
+ b. No downstream restrictions. You may not offer or impose
465
+ any additional or different terms or conditions on, or
466
+ apply any Effective Technological Measures to, the
467
+ Licensed Material if doing so restricts exercise of the
468
+ Licensed Rights by any recipient of the Licensed
469
+ Material.
470
+
471
+ 6. No endorsement. Nothing in this Public License constitutes or
472
+ may be construed as permission to assert or imply that You
473
+ are, or that Your use of the Licensed Material is, connected
474
+ with, or sponsored, endorsed, or granted official status by,
475
+ the Licensor or others designated to receive attribution as
476
+ provided in Section 3(a)(1)(A)(i).
477
+
478
+ b. Other rights.
479
+
480
+ 1. Moral rights, such as the right of integrity, are not
481
+ licensed under this Public License, nor are publicity,
482
+ privacy, and/or other similar personality rights; however, to
483
+ the extent possible, the Licensor waives and/or agrees not to
484
+ assert any such rights held by the Licensor to the limited
485
+ extent necessary to allow You to exercise the Licensed
486
+ Rights, but not otherwise.
487
+
488
+ 2. Patent and trademark rights are not licensed under this
489
+ Public License.
490
+
491
+ 3. To the extent possible, the Licensor waives any right to
492
+ collect royalties from You for the exercise of the Licensed
493
+ Rights, whether directly or through a collecting society
494
+ under any voluntary or waivable statutory or compulsory
495
+ licensing scheme. In all other cases the Licensor expressly
496
+ reserves any right to collect such royalties.
497
+
498
+
499
+ Section 3 -- License Conditions.
500
+
501
+ Your exercise of the Licensed Rights is expressly made subject to the
502
+ following conditions.
503
+
504
+ a. Attribution.
505
+
506
+ 1. If You Share the Licensed Material (including in modified
507
+ form), You must:
508
+
509
+ a. retain the following if it is supplied by the Licensor
510
+ with the Licensed Material:
511
+
512
+ i. identification of the creator(s) of the Licensed
513
+ Material and any others designated to receive
514
+ attribution, in any reasonable manner requested by
515
+ the Licensor (including by pseudonym if
516
+ designated);
517
+
518
+ ii. a copyright notice;
519
+
520
+ iii. a notice that refers to this Public License;
521
+
522
+ iv. a notice that refers to the disclaimer of
523
+ warranties;
524
+
525
+ v. a URI or hyperlink to the Licensed Material to the
526
+ extent reasonably practicable;
527
+
528
+ b. indicate if You modified the Licensed Material and
529
+ retain an indication of any previous modifications; and
530
+
531
+ c. indicate the Licensed Material is licensed under this
532
+ Public License, and include the text of, or the URI or
533
+ hyperlink to, this Public License.
534
+
535
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
536
+ reasonable manner based on the medium, means, and context in
537
+ which You Share the Licensed Material. For example, it may be
538
+ reasonable to satisfy the conditions by providing a URI or
539
+ hyperlink to a resource that includes the required
540
+ information.
541
+
542
+ 3. If requested by the Licensor, You must remove any of the
543
+ information required by Section 3(a)(1)(A) to the extent
544
+ reasonably practicable.
545
+
546
+ 4. If You Share Adapted Material You produce, the Adapter's
547
+ License You apply must not prevent recipients of the Adapted
548
+ Material from complying with this Public License.
549
+
550
+
551
+ Section 4 -- Sui Generis Database Rights.
552
+
553
+ Where the Licensed Rights include Sui Generis Database Rights that
554
+ apply to Your use of the Licensed Material:
555
+
556
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
557
+ to extract, reuse, reproduce, and Share all or a substantial
558
+ portion of the contents of the database;
559
+
560
+ b. if You include all or a substantial portion of the database
561
+ contents in a database in which You have Sui Generis Database
562
+ Rights, then the database in which You have Sui Generis Database
563
+ Rights (but not its individual contents) is Adapted Material; and
564
+
565
+ c. You must comply with the conditions in Section 3(a) if You Share
566
+ all or a substantial portion of the contents of the database.
567
+
568
+ For the avoidance of doubt, this Section 4 supplements and does not
569
+ replace Your obligations under this Public License where the Licensed
570
+ Rights include other Copyright and Similar Rights.
571
+
572
+
573
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
574
+
575
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
576
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
577
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
578
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
579
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
580
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
581
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
582
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
583
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
584
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
585
+
586
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
587
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
588
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
589
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
590
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
591
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
592
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
593
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
594
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
595
+
596
+ c. The disclaimer of warranties and limitation of liability provided
597
+ above shall be interpreted in a manner that, to the extent
598
+ possible, most closely approximates an absolute disclaimer and
599
+ waiver of all liability.
600
+
601
+
602
+ Section 6 -- Term and Termination.
603
+
604
+ a. This Public License applies for the term of the Copyright and
605
+ Similar Rights licensed here. However, if You fail to comply with
606
+ this Public License, then Your rights under this Public License
607
+ terminate automatically.
608
+
609
+ b. Where Your right to use the Licensed Material has terminated under
610
+ Section 6(a), it reinstates:
611
+
612
+ 1. automatically as of the date the violation is cured, provided
613
+ it is cured within 30 days of Your discovery of the
614
+ violation; or
615
+
616
+ 2. upon express reinstatement by the Licensor.
617
+
618
+ For the avoidance of doubt, this Section 6(b) does not affect any
619
+ right the Licensor may have to seek remedies for Your violations
620
+ of this Public License.
621
+
622
+ c. For the avoidance of doubt, the Licensor may also offer the
623
+ Licensed Material under separate terms or conditions or stop
624
+ distributing the Licensed Material at any time; however, doing so
625
+ will not terminate this Public License.
626
+
627
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
628
+ License.
629
+
630
+
631
+ Section 7 -- Other Terms and Conditions.
632
+
633
+ a. The Licensor shall not be bound by any additional or different
634
+ terms or conditions communicated by You unless expressly agreed.
635
+
636
+ b. Any arrangements, understandings, or agreements regarding the
637
+ Licensed Material not stated herein are separate from and
638
+ independent of the terms and conditions of this Public License.
639
+
640
+
641
+ Section 8 -- Interpretation.
642
+
643
+ a. For the avoidance of doubt, this Public License does not, and
644
+ shall not be interpreted to, reduce, limit, restrict, or impose
645
+ conditions on any use of the Licensed Material that could lawfully
646
+ be made without permission under this Public License.
647
+
648
+ b. To the extent possible, if any provision of this Public License is
649
+ deemed unenforceable, it shall be automatically reformed to the
650
+ minimum extent necessary to make it enforceable. If the provision
651
+ cannot be reformed, it shall be severed from this Public License
652
+ without affecting the enforceability of the remaining terms and
653
+ conditions.
654
+
655
+ c. No term or condition of this Public License will be waived and no
656
+ failure to comply consented to unless expressly agreed to by the
657
+ Licensor.
658
+
659
+ d. Nothing in this Public License constitutes or may be interpreted
660
+ as a limitation upon, or waiver of, any privileges and immunities
661
+ that apply to the Licensor or You, including from the legal
662
+ processes of any jurisdiction or authority.
663
+
664
+
665
+ =======================================================================
666
+
667
+ Creative Commons is not a party to its public
668
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
669
+ its public licenses to material it publishes and in those instances
670
+ will be considered the “Licensor.” The text of the Creative Commons
671
+ public licenses is dedicated to the public domain under the CC0 Public
672
+ Domain Dedication. Except for the limited purpose of indicating that
673
+ material is shared under a Creative Commons public license or as
674
+ otherwise permitted by the Creative Commons policies published at
675
+ creativecommons.org/policies, Creative Commons does not authorize the
676
+ use of the trademark "Creative Commons" or any other trademark or logo
677
+ of Creative Commons without its prior written consent including,
678
+ without limitation, in connection with any unauthorized modifications
679
+ to any of its public licenses or any other arrangements,
680
+ understandings, or agreements concerning use of licensed material. For
681
+ the avoidance of doubt, this paragraph does not form part of the
682
+ public licenses.
683
+
684
+ Creative Commons may be contacted at creativecommons.org.
licenses/unitree-BSD-3-Clause.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2016-2022 HangZhou YuShu TECHNOLOGY CO.,LTD. ("Unitree Robotics")
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
models/LICENSE.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model license
2
+
3
+ The MotionBricks ONNX models in this folder are licensed under the
4
+ [NVIDIA Open Model Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-agreement/).
5
+ This covers the SOMA models in [soma](soma) and the Unitree G1 models in [unitree_g1](unitree_g1).
6
+
7
+ Licensed by NVIDIA Corporation under the NVIDIA Open Model Agreement.
8
+
9
+ This file identifies the applicable license. The linked agreement contains its terms. The source
10
+ code in this repository and other bundled assets have their own licenses.
models/mmm_v6_g1_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ddfc4d7305b805005d782d3db0bd95941f0d3111118865821c6800785a0aa5a
3
+ size 368832561