VectorW commited on
Commit
5fc5f70
·
verified ·
1 Parent(s): b4eb479

Skills: the base plans its way around furniture to where an arm grasps well, grasps follow how objects lie; the tabletop gets the kitchen's objects

Browse files
README.md CHANGED
@@ -29,7 +29,10 @@ The robot model, its inverse kinematics and keyboard map, and the 3D Gaussian sp
29
  boxes, and a model of each built from its splat for the other renderers), its empty floor, or a kitchen
30
  with a dining room built for this Space (drawers, cabinet doors and a fridge that open, an oven and a
31
  range hood, a stocked fridge with glass shelves, crisper drawers and door bins, an island, objects to
32
- pick up, two of them in the fridge).
 
 
 
33
  - **Drive and teleoperate** with MuJoCo-GS-Web's keys: W/S and A/D for the dual-wheel base; for each arm
34
  rotation, end-effector height and reach, wrist pitch and roll, and the gripper; R/T and F/G for the head.
35
  - **Walk a Unitree G1**: choose it under Robot; W/S walk, A/D turn, Q/E step sideways. A locomotion
@@ -46,9 +49,12 @@ The robot model, its inverse kinematics and keyboard map, and the 3D Gaussian sp
46
  URL says `?theme=dark` or the embedding page sends `{type: "xlerobot-sim:theme", theme: "dark"}`
47
  (the page posts `{type: "xlerobot-sim:hello"}` to its parent when it starts).
48
  - **Watch the robot's cameras**: head and both wrists.
49
- - **Run skills**: go to an object, pick it (scripted grasp), place it in or on another object. A held
50
- object stays put: while a gripper squeezes something, MuJoCo's noslip solver keeps it from creeping out
51
- of the jaws (`src/robots/xlerobot.js`).
 
 
 
52
  - **Run a learned policy**: an ACT policy trained with LeRobot picks objects, in your browser with ONNX
53
  Runtime Web.
54
  - **Give the robot instructions in words**: an LLM agent calls the skills as tools. Sign in with Hugging
@@ -60,6 +66,32 @@ The robot model, its inverse kinematics and keyboard map, and the 3D Gaussian sp
60
  - **Script it**: `window.xlerobotSim` exposes the simulation and the agent's tools, so browser agents
61
  and tests can drive it, for example `await xlerobotSim.call("pick", {object: "orange"})`.
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  ## The learned policy
64
 
65
  | | |
@@ -67,10 +99,10 @@ The robot model, its inverse kinematics and keyboard map, and the 3D Gaussian sp
67
  | Task | lift an object from a table in front of one arm |
68
  | Inputs | the arm's 6 joint angles; the object's position from the arm's shoulder, its size, and a box's yaw (no camera images) |
69
  | Output | 6 joint targets, in chunks of 50 at 50 Hz, 25 executed per inference |
70
- | Data | 900 scripted picks in the tabletop scene with random object sizes, made in Node with the page's own physics (`tools/gen_demos.mjs`) |
71
  | Model | LeRobot ACT, 4.2 M parameters at inference, exported to ONNX (17 MB) |
72
  | Check | the ONNX graph matches LeRobot's own inference within 3e-6 rad |
73
- | Success | 75 of 100 unseen tabletop layouts (the scripted demonstrator manages 83%); in the kitchen, after the go-to skill, 1 of 3 objects |
74
 
75
  One policy serves both arms: its inputs are relative to the arm that acts.
76
 
@@ -80,11 +112,13 @@ One policy serves both arms: its inputs are relative to the arm that acts.
80
  assets/robots/ robots: MuJoCo-GS-Web's xlerobot.xml, objects.xml and meshes, plus robot.json
81
  (controller, cameras); index.json lists them
82
  assets/environments/ scenes: MuJoCo-GS-Web's tabletop, UFC and basic, with decor.xml models of the two
83
- splats (tools/make_decor.py); kitchen/ (tools/make_kitchen.py)
 
84
  assets/policies/ exported policies
85
  src/core/ loading, scene composition (as MuJoCo-GS-Web's SceneManager), the simulation loop
86
- src/robots/ xlerobot.js (MuJoCo-GS-Web's IK and keys), skills.js, g1.js (the G1's walking
87
- policy and keys), generic.js (uploaded robots)
 
88
  src/render/ three.js views: toon (outlines in toon.js), lit, 3DGS (Spark) and pixel (pixel.js;
89
  its colours in palette.js)
90
  src/policy/, src/tasks/ ONNX Runtime policy runner and the pick task's observation
@@ -109,9 +143,10 @@ python train/train_policy.py data/pick outputs/act_pick # ACT, about 25 mi
109
  python train/export_onnx.py outputs/act_pick/checkpoints/050000/pretrained_model assets/policies/xlerobot_pick --dataset data/pick
110
  node tools/eval_policy.mjs assets/policies/xlerobot_pick 100 # unseen tabletop layouts
111
  node tools/eval_kitchen.mjs # go to and pick kitchen objects with the policy
112
- npm run check # teleop, base speed loop, scripted picks, kitchen place
113
  npm run check:g1 # the G1 stands, walks, turns, steps sideways and stops
114
  python tools/make_kitchen.py # regenerate the kitchen
 
115
  python tools/make_decor.py # remodel the splat scenes (samples their colours)
116
  python tools/make_g1.py # the G1 and its policy from mjswan, set up as mjlab trained it
117
  python tools/publish.py space # upload (needs a Hugging Face write token)
 
29
  boxes, and a model of each built from its splat for the other renderers), its empty floor, or a kitchen
30
  with a dining room built for this Space (drawers, cabinet doors and a fridge that open, an oven and a
31
  range hood, a stocked fridge with glass shelves, crisper drawers and door bins, an island, objects to
32
+ pick up, two of them in the fridge). The tabletop kitchen has the same objects as that kitchen, set out
33
+ on its counters where the splat shows free worktop: fruit around a bowl, a plate, a mug and a glass on
34
+ the back counter, a can, a juice carton and a yogurt by the microwave, a bottle of oil and a block on
35
+ the left counter.
36
  - **Drive and teleoperate** with MuJoCo-GS-Web's keys: W/S and A/D for the dual-wheel base; for each arm
37
  rotation, end-effector height and reach, wrist pitch and roll, and the gripper; R/T and F/G for the head.
38
  - **Walk a Unitree G1**: choose it under Robot; W/S walk, A/D turn, Q/E step sideways. A locomotion
 
49
  URL says `?theme=dark` or the embedding page sends `{type: "xlerobot-sim:theme", theme: "dark"}`
50
  (the page posts `{type: "xlerobot-sim:hello"}` to its parent when it starts).
51
  - **Watch the robot's cameras**: head and both wrists.
52
+ - **Run skills**: go to an object, pick it (scripted grasp), place it in or on another object. Going to
53
+ an object drives around the furniture without touching it, to a spot from which an arm grasps the
54
+ object well (see below). A grasp closes across the object's narrow side however it lies: a box turned
55
+ any way, a banana or a bottle lying down, a mug clear of its handle. A held object stays put: while a
56
+ gripper squeezes something, MuJoCo's noslip solver keeps it from creeping out of the jaws
57
+ (`src/robots/xlerobot.js`).
58
  - **Run a learned policy**: an ACT policy trained with LeRobot picks objects, in your browser with ONNX
59
  Runtime Web.
60
  - **Give the robot instructions in words**: an LLM agent calls the skills as tools. Sign in with Hugging
 
66
  - **Script it**: `window.xlerobotSim` exposes the simulation and the agent's tools, so browser agents
67
  and tests can drive it, for example `await xlerobotSim.call("pick", {object: "orange"})`.
68
 
69
+ ## How the robot goes to an object
70
+
71
+ `src/robots/nav.js` plans and drives the base; `src/robots/skills.js` decides where to stand.
72
+
73
+ 1. **What the base can hit.** The scene's collision geoms, except the robot, become 2D shapes
74
+ (rectangles and circles) with a height range: counters, walls, chairs, open doors, and the objects
75
+ standing about. The robot is its chassis outline plus, for each arm, the links that reach beyond it,
76
+ each with its own height range. A shape only counts against the parts it overlaps in height, so an
77
+ arm can pass over a worktop that the chassis cannot. The free arms fold up before the base drives, so
78
+ nothing reaches beyond the chassis; an arm holding something stays as it is.
79
+ 2. **Where to stand.** Around the object, at every 5 degrees of heading and with either arm, the poses
80
+ from which the object is 0.23 to 0.43 m ahead and in line with the arm, clear of everything by 2 cm,
81
+ and from which the grasp planner finds a grasp. They are ranked by the length of the way there, how
82
+ comfortably the arm reaches, and how well the grasp goes: from above where it can, square to the
83
+ object's narrow side, the wrist turned little, a tall object held by its middle.
84
+ 3. **The path.** A hybrid A* search over the pose of the point between the wheels, which stays put when
85
+ the base turns in place: short straight drives and arcs, forward and backward, and turns in place,
86
+ each checked along its way with 3 cm to spare. It ends by lining up on the goal's heading and driving
87
+ straight in, so the base meets the counter square.
88
+ 4. **Driving it.** Pure pursuit on the path, slower near furniture, with turns that end on the planned
89
+ heading. A quarter of a second ahead, the base checks the pose it is heading for and stops before one
90
+ that would touch; then it plans again from where it is.
91
+
92
+ In the tabletop scene the robot goes to every object from its start and picks each one it can lift,
93
+ without the base touching a counter (`npm run check`).
94
+
95
  ## The learned policy
96
 
97
  | | |
 
99
  | Task | lift an object from a table in front of one arm |
100
  | Inputs | the arm's 6 joint angles; the object's position from the arm's shoulder, its size, and a box's yaw (no camera images) |
101
  | Output | 6 joint targets, in chunks of 50 at 50 Hz, 25 executed per inference |
102
+ | Data | 900 scripted picks in the tabletop scene, on MuJoCo-GS-Web's blocks and balls with random sizes, made in Node with the page's own physics (`tools/gen_demos.mjs`) |
103
  | Model | LeRobot ACT, 4.2 M parameters at inference, exported to ONNX (17 MB) |
104
  | Check | the ONNX graph matches LeRobot's own inference within 3e-6 rad |
105
+ | Success | 75 of 100 unseen tabletop layouts (the scripted demonstrator manages 83%); in the kitchen, after the go-to skill, 3 of 3 objects |
106
 
107
  One policy serves both arms: its inputs are relative to the arm that acts.
108
 
 
112
  assets/robots/ robots: MuJoCo-GS-Web's xlerobot.xml, objects.xml and meshes, plus robot.json
113
  (controller, cameras); index.json lists them
114
  assets/environments/ scenes: MuJoCo-GS-Web's tabletop, UFC and basic, with decor.xml models of the two
115
+ splats (tools/make_decor.py) and the tabletop's objects.xml (tools/make_tabletop.py);
116
+ kitchen/ (tools/make_kitchen.py); both kitchens' objects come from tools/objects.py
117
  assets/policies/ exported policies
118
  src/core/ loading, scene composition (as MuJoCo-GS-Web's SceneManager), the simulation loop
119
+ src/robots/ xlerobot.js (MuJoCo-GS-Web's IK and keys), skills.js, nav.js (the base's map,
120
+ planner and path follower), g1.js (the G1's walking policy and keys), generic.js
121
+ (uploaded robots)
122
  src/render/ three.js views: toon (outlines in toon.js), lit, 3DGS (Spark) and pixel (pixel.js;
123
  its colours in palette.js)
124
  src/policy/, src/tasks/ ONNX Runtime policy runner and the pick task's observation
 
143
  python train/export_onnx.py outputs/act_pick/checkpoints/050000/pretrained_model assets/policies/xlerobot_pick --dataset data/pick
144
  node tools/eval_policy.mjs assets/policies/xlerobot_pick 100 # unseen tabletop layouts
145
  node tools/eval_kitchen.mjs # go to and pick kitchen objects with the policy
146
+ npm run check # teleop, base speed loop, grasps, go-to and pick everywhere, kitchen place
147
  npm run check:g1 # the G1 stands, walks, turns, steps sideways and stops
148
  python tools/make_kitchen.py # regenerate the kitchen
149
+ python tools/make_tabletop.py # regenerate the tabletop's objects
150
  python tools/make_decor.py # remodel the splat scenes (samples their colours)
151
  python tools/make_g1.py # the G1 and its policy from mjswan, set up as mjlab trained it
152
  python tools/publish.py space # upload (needs a Hugging Face write token)
assets/environments/index.json CHANGED
@@ -1,67 +1,67 @@
1
- [
2
- {
3
- "id": "tabletop",
4
- "name": "Tabletop",
5
- "description": "MuJoCo-GS-Web's tabletop kitchen: a 3D Gaussian splat with collision boxes for the counters and walls, and a modelled stand-in for the Toon and Lit renderers.",
6
- "xml": "tabletop/scene.xml",
7
- "decor": "decor.xml",
8
- "splat": "tabletop/scene.spz",
9
- "objects": "robot",
10
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/tabletop",
11
- "lighting": {
12
- "key": [
13
- 0.9,
14
- 2.0,
15
- 2.6
16
- ],
17
- "probe": [
18
- 0,
19
- 0.1,
20
- 1.1
21
- ],
22
- "sky": "#cfc8bb",
23
- "keyIntensity": 1.1,
24
- "keyColor": "#fff3e3"
25
- }
26
- },
27
- {
28
- "id": "kitchen",
29
- "name": "Kitchen",
30
- "description": "A kitchen and dining room built from MuJoCo primitives, with drawers, cabinet doors and objects to pick up.",
31
- "xml": "kitchen/scene.xml",
32
- "objects": "scene"
33
- },
34
- {
35
- "id": "UFC",
36
- "name": "UFC arena",
37
- "description": "MuJoCo-GS-Web's boxing ring: a 3D Gaussian splat with collision walls, and a modelled stand-in for the Toon and Lit renderers.",
38
- "xml": "UFC/scene.xml",
39
- "decor": "decor.xml",
40
- "splat": "UFC/scene.spz",
41
- "objects": "robot",
42
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/UFC",
43
- "lighting": {
44
- "key": [
45
- 0.5,
46
- 0.8,
47
- 4.0
48
- ],
49
- "probe": [
50
- 0,
51
- 0,
52
- 1.2
53
- ],
54
- "sky": "#2b2727",
55
- "keyIntensity": 1.6,
56
- "keyColor": "#ffffff"
57
- }
58
- },
59
- {
60
- "id": "basic",
61
- "name": "Empty floor",
62
- "description": "MuJoCo-GS-Web's basic environment: a floor and a light.",
63
- "xml": "basic.xml",
64
- "objects": "robot",
65
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/blob/main/assets/environments/basic.xml"
66
- }
67
- ]
 
1
+ [
2
+ {
3
+ "id": "tabletop",
4
+ "name": "Tabletop",
5
+ "description": "MuJoCo-GS-Web's tabletop kitchen: a 3D Gaussian splat with collision boxes for the counters and walls, a modelled stand-in for the Toon and Lit renderers, and the Kitchen's objects on its counters.",
6
+ "xml": "tabletop/scene.xml",
7
+ "decor": "decor.xml",
8
+ "splat": "tabletop/scene.spz",
9
+ "objects": "objects.xml",
10
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/tabletop",
11
+ "lighting": {
12
+ "key": [
13
+ 0.9,
14
+ 2.0,
15
+ 2.6
16
+ ],
17
+ "probe": [
18
+ 0,
19
+ 0.1,
20
+ 1.1
21
+ ],
22
+ "sky": "#cfc8bb",
23
+ "keyIntensity": 1.1,
24
+ "keyColor": "#fff3e3"
25
+ }
26
+ },
27
+ {
28
+ "id": "kitchen",
29
+ "name": "Kitchen",
30
+ "description": "A kitchen and dining room built from MuJoCo primitives, with drawers, cabinet doors and objects to pick up.",
31
+ "xml": "kitchen/scene.xml",
32
+ "objects": "scene"
33
+ },
34
+ {
35
+ "id": "UFC",
36
+ "name": "UFC arena",
37
+ "description": "MuJoCo-GS-Web's boxing ring: a 3D Gaussian splat with collision walls, and a modelled stand-in for the Toon and Lit renderers.",
38
+ "xml": "UFC/scene.xml",
39
+ "decor": "decor.xml",
40
+ "splat": "UFC/scene.spz",
41
+ "objects": "robot",
42
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/UFC",
43
+ "lighting": {
44
+ "key": [
45
+ 0.5,
46
+ 0.8,
47
+ 4.0
48
+ ],
49
+ "probe": [
50
+ 0,
51
+ 0,
52
+ 1.2
53
+ ],
54
+ "sky": "#2b2727",
55
+ "keyIntensity": 1.6,
56
+ "keyColor": "#ffffff"
57
+ }
58
+ },
59
+ {
60
+ "id": "basic",
61
+ "name": "Empty floor",
62
+ "description": "MuJoCo-GS-Web's basic environment: a floor and a light.",
63
+ "xml": "basic.xml",
64
+ "objects": "robot",
65
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/blob/main/assets/environments/basic.xml"
66
+ }
67
+ ]
assets/environments/kitchen/scene.xml CHANGED
@@ -11,6 +11,19 @@
11
  <asset>
12
  <texture type="skybox" builtin="gradient" rgb1="0.85 0.87 0.9" rgb2="0.6 0.62 0.65" width="512" height="3072"/>
13
  <texture name="planks" type="2d" builtin="checker" width="512" height="512" rgb1="0.62 0.47 0.33" rgb2="0.58 0.43 0.3"/>
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  <material name="floor" texture="planks" texrepeat="6 30" texuniform="true"/>
15
  <material name="wall" rgba="0.93 0.91 0.87 1"/>
16
  <material name="tile" rgba="0.9 0.92 0.93 1"/>
@@ -25,17 +38,6 @@
25
  <material name="wood" rgba="0.55 0.38 0.24 1"/>
26
  <material name="fabric" rgba="0.33 0.38 0.47 1"/>
27
  <material name="rug" rgba="0.72 0.66 0.58 1"/>
28
- <material name="apple" rgba="0.75 0.1 0.08 1"/>
29
- <material name="orange" rgba="0.95 0.5 0.08 1"/>
30
- <material name="cube" rgba="0.95 0.78 0.1 1"/>
31
- <material name="can" rgba="0.8 0.1 0.15 1"/>
32
- <material name="mug" rgba="0.2 0.45 0.75 1"/>
33
- <material name="bowl" rgba="0.95 0.95 0.93 1"/>
34
- <material name="plate" rgba="0.97 0.97 0.95 1"/>
35
- <material name="banana" rgba="0.96 0.85 0.3 1"/>
36
- <material name="cup" rgba="0.3 0.7 0.5 1"/>
37
- <material name="bottle" rgba="0.15 0.45 0.3 1"/>
38
- <material name="book" rgba="0.6 0.15 0.2 1"/>
39
  <material name="oven" rgba="0.2 0.2 0.22 1"/>
40
  <material name="oven_glass" rgba="0.06 0.06 0.08 1"/>
41
  <material name="oven_knob" rgba="0.75 0.76 0.78 1"/>
@@ -64,8 +66,6 @@
64
  <material name="juice" rgba="0.98 0.6 0.1 1"/>
65
  <material name="sauce" rgba="0.55 0.25 0.1 1"/>
66
  <material name="egg" rgba="0.96 0.9 0.8 1"/>
67
- <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
68
- <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
69
  </asset>
70
 
71
  <default>
@@ -384,11 +384,11 @@
384
  <freejoint/>
385
  <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
386
  </body>
387
- <body name="can" pos="-1.38 -0.3 0.865">
388
  <freejoint/>
389
  <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
390
  </body>
391
- <body name="mug" pos="-1.35 0.35 0.86">
392
  <freejoint/>
393
  <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
394
  <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
@@ -411,15 +411,15 @@
411
  <freejoint/>
412
  <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
413
  </body>
414
- <body name="banana" pos="1 1.35 0.767">
415
  <freejoint/>
416
  <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
417
  </body>
418
- <body name="cup" pos="1.5 1.5 0.795">
419
  <freejoint/>
420
  <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
421
  </body>
422
- <body name="bottle" pos="-2.55 -0.45 0.985">
423
  <freejoint/>
424
  <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
425
  </body>
 
11
  <asset>
12
  <texture type="skybox" builtin="gradient" rgb1="0.85 0.87 0.9" rgb2="0.6 0.62 0.65" width="512" height="3072"/>
13
  <texture name="planks" type="2d" builtin="checker" width="512" height="512" rgb1="0.62 0.47 0.33" rgb2="0.58 0.43 0.3"/>
14
+ <material name="apple" rgba="0.75 0.1 0.08 1"/>
15
+ <material name="orange" rgba="0.95 0.5 0.08 1"/>
16
+ <material name="cube" rgba="0.95 0.78 0.1 1"/>
17
+ <material name="can" rgba="0.8 0.1 0.15 1"/>
18
+ <material name="mug" rgba="0.2 0.45 0.75 1"/>
19
+ <material name="bowl" rgba="0.95 0.95 0.93 1"/>
20
+ <material name="plate" rgba="0.97 0.97 0.95 1"/>
21
+ <material name="banana" rgba="0.96 0.85 0.3 1"/>
22
+ <material name="cup" rgba="0.3 0.7 0.5 1"/>
23
+ <material name="bottle" rgba="0.15 0.45 0.3 1"/>
24
+ <material name="book" rgba="0.6 0.15 0.2 1"/>
25
+ <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
26
+ <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
27
  <material name="floor" texture="planks" texrepeat="6 30" texuniform="true"/>
28
  <material name="wall" rgba="0.93 0.91 0.87 1"/>
29
  <material name="tile" rgba="0.9 0.92 0.93 1"/>
 
38
  <material name="wood" rgba="0.55 0.38 0.24 1"/>
39
  <material name="fabric" rgba="0.33 0.38 0.47 1"/>
40
  <material name="rug" rgba="0.72 0.66 0.58 1"/>
 
 
 
 
 
 
 
 
 
 
 
41
  <material name="oven" rgba="0.2 0.2 0.22 1"/>
42
  <material name="oven_glass" rgba="0.06 0.06 0.08 1"/>
43
  <material name="oven_knob" rgba="0.75 0.76 0.78 1"/>
 
66
  <material name="juice" rgba="0.98 0.6 0.1 1"/>
67
  <material name="sauce" rgba="0.55 0.25 0.1 1"/>
68
  <material name="egg" rgba="0.96 0.9 0.8 1"/>
 
 
69
  </asset>
70
 
71
  <default>
 
384
  <freejoint/>
385
  <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
386
  </body>
387
+ <body name="can" pos="-1.43 -0.3 0.865">
388
  <freejoint/>
389
  <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
390
  </body>
391
+ <body name="mug" pos="-1.42 0.35 0.86">
392
  <freejoint/>
393
  <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
394
  <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
 
411
  <freejoint/>
412
  <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
413
  </body>
414
+ <body name="banana" pos="0.52 1.3 0.767" quat="0.7961 0 0 0.6052">
415
  <freejoint/>
416
  <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
417
  </body>
418
+ <body name="cup" pos="0.52 1.62 0.795">
419
  <freejoint/>
420
  <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
421
  </body>
422
+ <body name="bottle" pos="-2.41 -0.45 0.985">
423
  <freejoint/>
424
  <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
425
  </body>
assets/environments/tabletop/objects.xml ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <mujoco model="tabletop objects">
2
+ <!-- Written by tools/make_tabletop.py: the kitchen environment's objects on MuJoCo-GS-Web's tabletop counters. -->
3
+ <asset>
4
+ <material name="apple" rgba="0.75 0.1 0.08 1"/>
5
+ <material name="orange" rgba="0.95 0.5 0.08 1"/>
6
+ <material name="cube" rgba="0.95 0.78 0.1 1"/>
7
+ <material name="can" rgba="0.8 0.1 0.15 1"/>
8
+ <material name="mug" rgba="0.2 0.45 0.75 1"/>
9
+ <material name="bowl" rgba="0.95 0.95 0.93 1"/>
10
+ <material name="plate" rgba="0.97 0.97 0.95 1"/>
11
+ <material name="banana" rgba="0.96 0.85 0.3 1"/>
12
+ <material name="cup" rgba="0.3 0.7 0.5 1"/>
13
+ <material name="bottle" rgba="0.15 0.45 0.3 1"/>
14
+ <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
15
+ <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
16
+ </asset>
17
+
18
+ <worldbody>
19
+ <body name="apple" pos="0.2 -0.36 0.845">
20
+ <freejoint/>
21
+ <geom type="sphere" size="0.025" material="apple" condim="6" friction="1.2 0.02 0.002" mass="0.08" contype="1" conaffinity="1"/>
22
+ </body>
23
+ <body name="bowl" pos="0.42 -0.39 0.823">
24
+ <freejoint/>
25
+ <geom type="cylinder" pos="0 0 0.004" size="0.05 0.004" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
26
+ <geom type="box" pos="0.062 0 0.028" euler="0 0 0.0000" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
27
+ <geom type="box" pos="0.05016 0.03644 0.028" euler="0 0 0.6283" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
28
+ <geom type="box" pos="0.01916 0.05897 0.028" euler="0 0 1.2566" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
29
+ <geom type="box" pos="-0.01916 0.05897 0.028" euler="0 0 1.8850" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
30
+ <geom type="box" pos="-0.05016 0.03644 0.028" euler="0 0 2.5133" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
31
+ <geom type="box" pos="-0.062 7.593e-18 0.028" euler="0 0 3.1416" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
32
+ <geom type="box" pos="-0.05016 -0.03644 0.028" euler="0 0 3.7699" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
33
+ <geom type="box" pos="-0.01916 -0.05897 0.028" euler="0 0 4.3982" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
34
+ <geom type="box" pos="0.01916 -0.05897 0.028" euler="0 0 5.0265" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
35
+ <geom type="box" pos="0.05016 -0.03644 0.028" euler="0 0 5.6549" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
36
+ </body>
37
+ <body name="orange" pos="0.64 -0.36 0.844">
38
+ <freejoint/>
39
+ <geom type="sphere" size="0.024" material="orange" condim="6" friction="1.2 0.02 0.002" mass="0.07" contype="1" conaffinity="1"/>
40
+ </body>
41
+ <body name="banana" pos="0.84 -0.365 0.837" quat="0.9847 0 0 0.1741">
42
+ <freejoint/>
43
+ <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
44
+ </body>
45
+ <body name="plate" pos="-0.06 -0.415 0.83">
46
+ <freejoint/>
47
+ <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
48
+ </body>
49
+ <body name="mug" pos="-0.42 -0.365 0.86" quat="0.7074 0 0 0.7068">
50
+ <freejoint/>
51
+ <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
52
+ <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
53
+ </body>
54
+ <body name="cup" pos="-0.58 -0.36 0.865">
55
+ <freejoint/>
56
+ <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
57
+ </body>
58
+ <body name="can" pos="1.06 -0.16 0.865">
59
+ <freejoint/>
60
+ <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
61
+ </body>
62
+ <body name="juice_box" pos="1.06 0 0.88" quat="0.995 0 0 0.09983">
63
+ <freejoint/>
64
+ <geom type="box" size="0.03 0.022 0.06" material="juice_box" condim="4" friction="1.2 0.05 0.01" mass="0.2" contype="1" conaffinity="1"/>
65
+ </body>
66
+ <body name="yogurt" pos="1.06 0.74 0.855">
67
+ <freejoint/>
68
+ <geom type="cylinder" size="0.03 0.035" material="yogurt" condim="6" friction="1.2 0.02 0.002" mass="0.12" contype="1" conaffinity="1"/>
69
+ </body>
70
+ <body name="bottle" pos="-1.07 0.2 0.905">
71
+ <freejoint/>
72
+ <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
73
+ </body>
74
+ <body name="cube" pos="-1.06 -0.1 0.84" quat="0.9801 0 0 0.1987">
75
+ <freejoint/>
76
+ <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
77
+ </body>
78
+ </worldbody>
79
+ </mujoco>
dist/assets/{__vite-browser-external-wfKY6rjk.js → __vite-browser-external-BjMDwyf-.js} RENAMED
@@ -1 +1 @@
1
- import{Y as e}from"./index-DCVbIUBW.js";var t=e(((e,t)=>{t.exports={}}));export default t();
 
1
+ import{Y as e}from"./index-BxuI995N.js";var t=e(((e,t)=>{t.exports={}}));export default t();
dist/assets/{index-DCVbIUBW.js → index-BxuI995N.js} RENAMED
The diff for this file is too large to render. See raw diff
 
dist/assets/{ort.wasm.bundle.min-B9FmhkYl.js → ort.wasm.bundle.min-U2P8l6E3.js} RENAMED
The diff for this file is too large to render. See raw diff
 
dist/assets/{spark.module-B_Oh32E1.js → spark.module-DadlTqrO.js} RENAMED
@@ -1,4 +1,4 @@
1
- import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,U as y,V as b,W as x,_ as ee,a as te,b as ne,c as S,d as C,f as w,g as re,h as ie,i as ae,j as oe,k as se,l as ce,m as le,n as T,o as ue,p as de,q as fe,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye,y as be,z as xe}from"./index-DCVbIUBW.js";var Se=new e(-1,1,1,-1,0,1),Ce=new class extends ue{constructor(){super(),this.setAttribute(`position`,new ie([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new ie([0,2,0,0,2,0],2))}},we=class{constructor(e){this._mesh=new i(Ce,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Se)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},E=Uint8Array,Te=Uint16Array,Ee=Int32Array,De=new E([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Oe=new E([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ke=new E([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ae=function(e,t){for(var n=new Te(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ee(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},je=Ae(De,2),Me=je.b,Ne=je.r;Me[28]=258,Ne[258]=28;var Pe=Ae(Oe,0),Fe=Pe.b;Pe.r;for(var Ie=new Te(32768),D=0;D<32768;++D){var Le=(D&43690)>>1|(D&21845)<<1;Le=(Le&52428)>>2|(Le&13107)<<2,Le=(Le&61680)>>4|(Le&3855)<<4,Ie[D]=((Le&65280)>>8|(Le&255)<<8)>>1}for(var Re=(function(e,t,n){for(var r=e.length,i=0,a=new Te(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Te(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Te(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ie[d]>>c]=l}else for(s=new Te(r),i=0;i<r;++i)e[i]&&(s[i]=Ie[o[e[i]-1]++]>>15-e[i]);return s}),ze=new E(288),D=0;D<144;++D)ze[D]=8;for(var D=144;D<256;++D)ze[D]=9;for(var D=256;D<280;++D)ze[D]=7;for(var D=280;D<288;++D)ze[D]=8;for(var Be=new E(32),D=0;D<32;++D)Be[D]=5;var Ve=Re(ze,9,1),He=Re(Be,5,1),Ue=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},O=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},We=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ge=function(e){return(e+7)/8|0},Ke=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new E(e.subarray(t,n))},qe=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],k=function(e,t,n){var r=Error(t||qe[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,k),!n)throw r;return r},Je=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new E(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new E(i*3));var l=function(e){var t=n.length;if(e>t){var r=new E(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=O(e,d,1);var v=O(e,d+1,3);if(d+=3,!v){var y=Ge(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&k(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Ve,m=He,h=9,g=5;else if(v==2){var ee=O(e,d,31)+257,te=O(e,d+10,15)+4,ne=ee+O(e,d+5,31)+1;d+=14;for(var S=new E(ne),C=new E(19),w=0;w<te;++w)C[ke[w]]=O(e,d+w*3,7);d+=te*3;for(var re=Ue(C),ie=(1<<re)-1,ae=Re(C,re,1),w=0;w<ne;){var oe=ae[O(e,d,ie)];d+=oe&15;var y=oe>>4;if(y<16)S[w++]=y;else{var se=0,ce=0;for(y==16?(ce=3+O(e,d,3),d+=2,se=S[w-1]):y==17?(ce=3+O(e,d,7),d+=3):y==18&&(ce=11+O(e,d,127),d+=7);ce--;)S[w++]=se}}var le=S.subarray(0,ee),T=S.subarray(ee);h=Ue(le),g=Ue(T),p=Re(le,h,1),m=Re(T,g,1)}else k(1);if(d>_){c&&k(0);break}}s&&l(f+131072);for(var ue=(1<<h)-1,de=(1<<g)-1,fe=d;;fe=d){var se=p[We(e,d)&ue],pe=se>>4;if(d+=se&15,d>_){c&&k(0);break}if(se||k(2),pe<256)n[f++]=pe;else if(pe==256){fe=d,p=null;break}else{var me=pe-254;if(pe>264){var w=pe-257,he=De[w];me=O(e,d,(1<<he)-1)+Me[w],d+=he}var ge=m[We(e,d)&de],_e=ge>>4;ge||k(3),d+=ge&15;var T=Fe[_e];if(_e>3){var he=Oe[_e];T+=We(e,d)&(1<<he)-1,d+=he}if(d>_){c&&k(0);break}s&&l(f+131072);var ve=f+me;if(f<T){var ye=a-T,be=Math.min(T,ve);for(ye+f<0&&k(3);f<be;++f)n[f]=r[ye+f]}for(;f<ve;++f)n[f]=n[f-T]}}t.l=p,t.p=fe,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Ke(n,0,f):n.subarray(0,f)},Ye=new E(0),A=function(e,t){return e[t]|e[t+1]<<8},j=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Xe=function(e,t){return j(e,t)+j(e,t+4)*4294967296},Ze=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&k(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Qe=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new E(32768),this.p=new E(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||k(5),this.d&&k(4),!this.p.length)this.p=e;else if(e.length){var t=new E(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=Je(this.p,this.s,this.o);this.ondata(Ke(n,t,this.s.b),this.d),this.o=Ke(n,this.s.b-32768),this.s.b=this.o.length,this.p=Ke(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();function $e(e,t){return Je(e,{i:2},t&&t.out,t&&t.dictionary)}var et=function(){function e(e,t){this.v=1,this.r=0,Qe.call(this,e,t)}return e.prototype.push=function(e,t){if(Qe.prototype.e.call(this,e),this.r+=e.length,this.v){var n=this.p.subarray(this.v-1),r=n.length>3?Ze(n):4;if(r>n.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-n.length);this.p=n.subarray(r),this.v=0}Qe.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=Ge(this.s.p)+9,this.s={i:0},this.o=new E(0),this.push(new E(0),t))},e}(),tt=typeof TextDecoder<`u`&&new TextDecoder;try{tt.decode(Ye,{stream:!0})}catch{}var nt=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:Ke(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function rt(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(tt)return tt.decode(e);var i=nt(e),a=i.s,n=i.r;return n.length&&k(8),a}var it=function(e,t){return t+30+A(e,t+26)+A(e,t+28)},at=function(e,t,n){var r=A(e,t+28),i=rt(e.subarray(t+46,t+46+r),!(A(e,t+8)&2048)),a=t+46+r,o=j(e,t+20),s=n&&o==4294967295?ot(e,a):[o,j(e,t+24),j(e,t+42)],c=s[0],l=s[1],u=s[2];return[A(e,t+10),c,l,i,a+A(e,t+30)+A(e,t+32),u]},ot=function(e,t){for(;A(e,t)!=1;t+=4+A(e,t+2));return[Xe(e,t+12),Xe(e,t+4),Xe(e,t+20)]};function st(e,t){for(var n={},r=e.length-22;j(e,r)!=101010256;--r)(!r||e.length-r>65558)&&k(13);var i=A(e,r+8);if(!i)return{};var a=j(e,r+16),o=a==4294967295||i==65535;if(o){var s=j(e,r-12);o=j(e,s)==101075792,o&&(i=j(e,s+32),a=j(e,s+48))}for(var c=t&&t.filter,l=0;l<i;++l){var u=at(e,a,o),d=u[0],f=u[1],p=u[2],m=u[3],h=u[4],g=u[5],_=it(e,g);a=h,(!c||c({name:m,size:f,originalSize:p,compression:d}))&&(d?d==8?n[m]=$e(e.subarray(_,_+f),{out:new E(p)}):k(14,`unknown compression type `+d):n[m]=Ke(e,_,_+f))}return n}var ct=Math.exp(-30),M=2048,N=2048,P=function(e){return e.PLY=`ply`,e.SPZ=`spz`,e.SPLAT=`splat`,e.KSPLAT=`ksplat`,e.PCSOGS=`pcsogs`,e.PCSOGSZIP=`pcsogszip`,e.RAD=`rad`,e}({}),lt={rgbMin:0,rgbMax:1,lnScaleMin:-12,lnScaleMax:9,sh1Max:1,sh2Max:1,sh3Max:1,lodOpacity:!1};function ut(e){return e===`int`||e===`ivec2`||e===`ivec3`||e===`ivec4`}function dt(e){return e===`uint`||e===`uvec2`||e===`uvec3`||e===`uvec4`}function ft(e){return e===`float`||e===`vec2`||e===`vec3`||e===`vec4`}function pt(e){return e===`mat2`||e===`mat2x2`||e===`mat2x3`||e===`mat2x4`||e===`mat3`||e===`mat3x2`||e===`mat3x3`||e===`mat3x4`||e===`mat4`||e===`mat4x2`||e===`mat4x3`||e===`mat4x4`}function mt(e){return ft(e)||pt(e)}function ht(e){return e===`mat2`||e===`mat2x2`}function gt(e){return e===`mat3`||e===`mat3x3`}function _t(e){return e===`mat4`||e===`mat4x4`}function F(e){return Math.trunc(e).toString()}function I(e){return`${Math.max(0,Math.trunc(e)).toString()}u`}function L(e){return e===1/0?`INFINITY`:e===-1/0?`-INFINITY`:Number.isInteger(e)?e.toFixed(1):e.toString()}function vt(e){return e instanceof yt?e.type:e.dynoOut().type}var yt=class{constructor(e){this.__isDynoValue=!0,this.type=e}},R=class extends yt{constructor(e,t){super(e.outTypes[t]),this.dyno=e,this.key=t}},bt=class extends yt{constructor(e,t){super(e),this.literal=t}getLiteral(){return this.literal}},xt=class extends bt{constructor(e,t){super(e,``),this.value=t}getLiteral(){let{type:e,value:t}=this;switch(e){case`bool`:return t?`true`:`false`;case`uint`:return I(t);case`int`:return F(t);case`float`:return L(t);case`bvec2`:{let e=t;return`bvec2(${e[0]}, ${e[1]})`}case`uvec2`:{if(t instanceof x)return`uvec2(${I(t.x)}, ${I(t.y)})`;let e=t;return`uvec2(${I(e[0])}, ${I(e[1])})`}case`ivec2`:{if(t instanceof x)return`ivec2(${F(t.x)}, ${F(t.y)})`;let e=t;return`ivec2(${F(e[0])}, ${F(e[1])})`}case`vec2`:{if(t instanceof x)return`vec2(${L(t.x)}, ${L(t.y)})`;let e=t;return`vec2(${L(e[0])}, ${L(e[1])})`}case`bvec3`:{let e=t;return`bvec3(${e[0]}, ${e[1]}, ${e[2]})`}case`uvec3`:{if(t instanceof o)return`uvec3(${I(t.x)}, ${I(t.y)}, ${I(t.z)})`;let e=t;return`uvec3(${I(e[0])}, ${I(e[1])}, ${I(e[2])})`}case`ivec3`:{if(t instanceof o)return`ivec3(${F(t.x)}, ${F(t.y)}, ${F(t.z)})`;let e=t;return`ivec3(${F(e[0])}, ${F(e[1])}, ${F(e[2])})`}case`vec3`:{if(t instanceof o)return`vec3(${L(t.x)}, ${L(t.y)}, ${L(t.z)})`;let e=t;return`vec3(${L(e[0])}, ${L(e[1])}, ${L(e[2])})`}case`bvec4`:{let e=t;return`bvec4(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`}case`uvec4`:{if(t instanceof u)return`uvec4(${I(t.x)}, ${I(t.y)}, ${I(t.z)}, ${I(t.w)})`;let e=t;return`uvec4(${I(e[0])}, ${I(e[1])}, ${I(e[2])}, ${I(e[3])})`}case`ivec4`:{if(t instanceof u)return`ivec4(${F(t.x)}, ${F(t.y)}, ${F(t.z)}, ${F(t.w)})`;let e=t;return`ivec4(${F(e[0])}, ${F(e[1])}, ${F(e[2])}, ${F(e[3])})`}case`vec4`:{if(t instanceof u||t instanceof f)return`vec4(${L(t.x)}, ${L(t.y)}, ${L(t.z)}, ${L(t.w)})`;let e=t;return`vec4(${L(e[0])}, ${L(e[1])}, ${L(e[2])}, ${L(e[3])})`}case`mat2`:case`mat2x2`:{let r=t,i=r instanceof n?r.elements:t;return`${e}(${[,,,,].fill(0).map((e,t)=>L(i[t])).join(`, `)})`}case`mat2x3`:{let n=t;return`${e}(${[,,,,,,].fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat2x4`:{let n=t;return`${e}(${Array(8).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat3`:case`mat3x3`:{let n=t,r=n instanceof ve?n.elements:t;return`${e}(${Array(9).fill(0).map((e,t)=>L(r[t])).join(`, `)})`}case`mat3x2`:{let n=t;return`${e}(${[,,,,,,].fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat3x4`:{let n=t;return`${e}(${Array(12).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat4`:case`mat4x4`:{let n=t,r=n instanceof v?n.elements:t;return`${e}(${Array(16).fill(0).map((e,t)=>L(r[t])).join(`, `)})`}case`mat4x2`:{let n=t;return`${e}(${Array(8).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat4x3`:{let n=t;return`${e}(${Array(12).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}default:throw Error(`Type not implemented: ${String(e)}`)}}};function St(e,t){return new xt(e,t)}var Ct=` `,wt=class{constructor({indent:e}={}){this.globals=new Set,this.statements=[],this.uniforms={},this.declares=new Set,this.updaters=[],this.sequence=0,this.indent=Ct,this.indent=e??Ct}nextSequence(){return this.sequence++}},z=class{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o}){this.inTypes=e??{},this.outTypes=t??{},this.inputs=n??{},this.update=r,this.globals=i,this.statements=a,this.generate=o??(({inputs:e,outputs:t,compile:n})=>({globals:this.globals?.({inputs:e,outputs:t,compile:n}),statements:this.statements?.({inputs:e,outputs:t,compile:n})}))}get outputs(){let e={};for(let t in this.outTypes)e[t]=new R(this,t);return e}apply(e){return Object.assign(this.inputs,e),this.outputs}compile({inputs:e,outputs:t,compile:n}){let r=[`// ${this.constructor.name}(${Object.values(e).join(`, `)}) => (${Object.values(t).join(`, `)})`],i=[];for(let e in t){let r=t[e];r&&!n.declares.has(r)&&(n.declares.add(r),i.push(e))}let{globals:a,statements:o,uniforms:s}=this.generate({inputs:e,outputs:t,compile:n});for(let e of a??[])n.globals.add(e);for(let e in s)n.uniforms[e]=s[e];this.update&&n.updaters.push(this.update);for(let e of i){let i=t[e];i&&(n.uniforms[i]||r.push(`${Dt(i,this.outTypes[e])};`))}return o?.length&&(r.push(`{`),r.push(...o.map(e=>n.indent+e)),r.push(`}`)),r}},Tt=class extends z{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,construct:a}){super({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,generate:e=>this.generateBlock(e)}),this.construct=a}generateBlock({inputs:e,outputs:t,compile:n}){let r={},i={};for(let t in e)e[t]!=null&&(r[t]=new bt(this.inTypes[t],e[t]));for(let e in t)t[e]!=null&&(i[e]=new yt(this.outTypes[e]));let a={roots:[]},o=this.construct(r,i,a);for(let r of this.globals?.({inputs:e,outputs:t,compile:n})??[])n.globals.add(r);let s=[],c=new Map;function l(e,t,r){let i=c.get(e);if(!i){i={sequence:n.nextSequence(),outNames:new Map,newOuts:new Set},c.set(e,i);for(let t in e.inputs){let n=e.inputs[t];for(;n;){if(n instanceof yt){n instanceof R&&l(n.dyno,n.key);break}if(typeof n.dynoOut!=`function`)throw Error(`dynoOut is not a function for ${n.constructor.name}`);n=n.dynoOut()}}s.push(e)}t&&(r||i.newOuts.add(t),i.outNames.set(t,r??`${t}_${i.sequence}`))}for(let e of a.roots)l(e);for(let e in i){let n=o?.[e]??i[e];for(;n;){if(n instanceof yt){n instanceof R&&l(n.dyno,n.key,t[e]);break}n=n.dynoOut()}i[e]=n}let u=[];for(let e of s){let t={},r={};for(let n in e.inputs){let r=e.inputs[n];for(;r;){if(r instanceof yt){if(r instanceof bt)t[n]=r.getLiteral();else if(r instanceof R){let e=c.get(r.dyno)?.outNames.get(r.key);if(!e)throw Error(`Source not found for ${r.dyno.constructor.name}.${r.key}`);t[n]=e}break}r=r.dynoOut()}}let i=c.get(e)??{outNames:new Map};for(let[e,t]of i.outNames.entries())r[e]=t;let a=e.compile({inputs:t,outputs:r,compile:n});u.push(a)}let d=[];for(let e in t)i[e]instanceof bt&&d.push(`${t[e]} = ${i[e].getLiteral()};`);return d.length>0&&u.push(d),{statements:u.flatMap((e,t)=>t===0?e:[``,...e])}}};function B(e,t,n,{update:r,globals:i}={}){return new Tt({inTypes:e,outTypes:t,construct:n,update:r,globals:i})}function Et({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o}){return new z({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o})}function Dt(e,t,n){let r=typeof t==`string`?t:t.type;if(!r)throw Error(`Invalid DynoType: ${String(t)}`);return`${r} ${e}${n==null?``:`[${n}]`}`}function V(e){let t=!1,n=e.split(`
2
  `).map(e=>{let n=e.trimEnd();return t?n:n.length>0?(t=!0,n):null}).filter(e=>e!=null);for(;n.length>0&&n[n.length-1].length===0;)n.pop();if(n.length===0)return[];let r=n[0].match(/^\s*/)?.[0];if(!r)return n;let i=RegExp(`^${r}`);return n.map(e=>e.replace(i,``))}function H(e){return V(e).join(`
3
  `)}var Ot=class extends z{constructor({a:e,outKey:t,outTypeFunc:n}){let r={a:vt(e)},i=n(vt(e));super({inTypes:r,outTypes:{[t]:i},inputs:{a:e}}),this.outKey=t}dynoOut(){return new R(this,this.outKey)}},kt=class extends z{constructor({a:e,b:t,outKey:n,outTypeFunc:r}){let i={a:vt(e),b:vt(t)},a=r(vt(e),vt(t));super({inTypes:i,outTypes:{[n]:a},inputs:{a:e,b:t}}),this.outKey=n}dynoOut(){return new R(this,this.outKey)}},At=Number.parseInt(`187`)>=179,jt=new Float32Array(1),Mt=new Uint32Array(jt.buffer),Nt=`Float16Array`in globalThis,Pt=Nt?new globalThis.Float16Array(1):null,Ft=new Uint16Array(Pt?.buffer);function It(e){return jt[0]=e,Mt[0]}function Lt(e){return Mt[0]=e,jt[0]}var U=Nt?Rt:zt,W=Nt?Bt:Vt;function Rt(e){return Pt[0]=e,Ft[0]}function zt(e){jt[0]=e;let t=Mt[0],n=t>>31&1,r=t>>23&255,i=t&8388607,a=n<<15;if(r===255)return i===0?a|31744:a|32767;let o=r-127+15;if(o>=31)return a|31744;if(o<=0)return o<-10?a:a|(i|8388608)>>1-o+13;let s=i>>13;return a|o<<10|s}function Bt(e){return Ft[0]=e,Pt[0]}function Vt(e){let t=e>>15&1,n=e>>10&31,r=e&1023,i;if(n===0){if(r===0)i=t<<31;else{let e=r,n=-14;for(;!(e&1024);)e<<=1,n--;e&=1023;let a=n+127,o=e<<13;i=t<<31|a<<23|o}}else if(n===31)i=r===0?t<<31|2139095040:t<<31|2143289344;else{let e=n-15+127,a=r<<13;i=t<<31|e<<23|a}return Mt[0]=i,jt[0]}function Ht(e){return Math.max(0,Math.min(255,Math.round(e*255)))}function Ut(e){let t=[],n=new Set;function r(e){e&&typeof e==`object`&&!n.has(e)&&(n.add(e),e instanceof ArrayBuffer?t.push(e):ArrayBuffer.isView(e)?t.push(e.buffer):Array.isArray(e)?e.forEach(r):Object.values(e).forEach(r))}return r(e),t}function Wt(e,t){return Array(e).fill(null).map((e,n)=>t(n))}function Gt(e,t){let n=0;for(let r of e)t(r)||(e[n++]=r);e.length=n}function Kt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=t*4,[_,v]=e;_[g]=It(n),_[g+1]=It(r),_[g+2]=It(i),_[g+3]=U(f),v[g]=U(p)|U(m)<<16,v[g+1]=U(h)|U(Math.log(a))<<16,v[g+2]=U(Math.log(o))|U(Math.log(s))<<16,v[g+3]=ln(c,l,u,d)}function qt(e,t){let n=Xt,r=t*4,[i,a]=e;return n.center.x=Lt(i[r]),n.center.y=Lt(i[r+1]),n.center.z=Lt(i[r+2]),n.opacity=W(i[r+3]&65535),n.color.r=W(a[r]&65535),n.color.g=W(a[r]>>>16),n.color.b=W(a[r+1]&65535),n.scales.x=Math.exp(W(a[r+1]>>>16)),n.scales.y=Math.exp(W(a[r+2]&65535)),n.scales.z=Math.exp(W(a[r+2]>>>16)),un(a[r+3],n.quaternion),n}function Jt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let _=g?.rgbMin??0,v=(g?.rgbMax??1)-_,y=Ht((p-_)/v),b=Ht((m-_)/v),x=Ht((h-_)/v),ee=Ht(g?.lodOpacity?.5*f:f),te=sn(Yt.set(c,l,u,d)),ne=te&255,S=te>>>8&255,C=te>>>16&255,w=g?.lnScaleMin??-12,re=254/((g?.lnScaleMax??9)-w),ie=a<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(a)-w)*re)+1)),ae=o<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(o)-w)*re)+1)),oe=s<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(s)-w)*re)+1)),se=U(n),ce=U(r),le=U(i),T=t*4;e[T]=y|b<<8|x<<16|ee<<24,e[T+1]=se|ce<<16,e[T+2]=le|ne<<16|S<<24,e[T+3]=ie|ae<<8|oe<<16|C<<24}var Yt=new f,Xt={center:new o,scales:new o,quaternion:new f,color:new S,opacity:0};function Zt(e,t,n){let r=Xt,i=t*4,a=e[i],o=e[i+1],s=e[i+2],c=e[i+3],l=n?.rgbMin??0,u=(n?.rgbMax??1)-l;r.color.set(l+(a&255)/255*u,l+(a>>>8&255)/255*u,l+(a>>>16&255)/255*u),r.opacity=(a>>>24&255)/255,n?.lodOpacity&&(r.opacity=2*r.opacity),r.center.set(W(o&65535),W(o>>>16&65535),W(s&65535));let d=n?.lnScaleMin??-12,f=((n?.lnScaleMax??9)-d)/254,p=c&255;r.scales.x=p===0?0:Math.exp(d+(p-1)*f);let m=c>>>8&255;r.scales.y=m===0?0:Math.exp(d+(m-1)*f);let h=c>>>16&255;return r.scales.z=h===0?0:Math.exp(d+(h-1)*f),cn(s>>>16&65535|c>>>8&16711680,r.quaternion),r}function G(e){let t=M,n=Math.max(1,Math.min(N,Math.ceil(e/t))),r=Math.ceil(e/(t*n));return{width:t,height:n,depth:r,maxSplats:t*n*r}}function Qt(){return navigator.platform.toLowerCase().startsWith(`win`)?!1:navigator.maxTouchPoints>0||/Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/.test(navigator.userAgent)}function $t(){return/Android/.test(navigator.userAgent)||/Tizen/.test(navigator.userAgent)}function en(){return!!navigator.xr&&/Oculus/.test(navigator.userAgent)}function tn(){return/iPhone|iPad/.test(navigator.userAgent)}function nn(){return!!navigator.xr&&tn()&&/Safari/.test(navigator.userAgent)&&Qt()}var rn=H(`
4
  precision highp float;
 
1
+ import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,U as y,V as b,W as x,_ as ee,a as te,b as ne,c as S,d as C,f as w,g as re,h as ie,i as ae,j as oe,k as se,l as ce,m as le,n as T,o as ue,p as de,q as fe,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye,y as be,z as xe}from"./index-BxuI995N.js";var Se=new e(-1,1,1,-1,0,1),Ce=new class extends ue{constructor(){super(),this.setAttribute(`position`,new ie([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new ie([0,2,0,0,2,0],2))}},we=class{constructor(e){this._mesh=new i(Ce,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Se)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},E=Uint8Array,Te=Uint16Array,Ee=Int32Array,De=new E([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Oe=new E([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ke=new E([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ae=function(e,t){for(var n=new Te(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ee(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},je=Ae(De,2),Me=je.b,Ne=je.r;Me[28]=258,Ne[258]=28;var Pe=Ae(Oe,0),Fe=Pe.b;Pe.r;for(var Ie=new Te(32768),D=0;D<32768;++D){var Le=(D&43690)>>1|(D&21845)<<1;Le=(Le&52428)>>2|(Le&13107)<<2,Le=(Le&61680)>>4|(Le&3855)<<4,Ie[D]=((Le&65280)>>8|(Le&255)<<8)>>1}for(var Re=(function(e,t,n){for(var r=e.length,i=0,a=new Te(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Te(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Te(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ie[d]>>c]=l}else for(s=new Te(r),i=0;i<r;++i)e[i]&&(s[i]=Ie[o[e[i]-1]++]>>15-e[i]);return s}),ze=new E(288),D=0;D<144;++D)ze[D]=8;for(var D=144;D<256;++D)ze[D]=9;for(var D=256;D<280;++D)ze[D]=7;for(var D=280;D<288;++D)ze[D]=8;for(var Be=new E(32),D=0;D<32;++D)Be[D]=5;var Ve=Re(ze,9,1),He=Re(Be,5,1),Ue=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},O=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},We=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ge=function(e){return(e+7)/8|0},Ke=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new E(e.subarray(t,n))},qe=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],k=function(e,t,n){var r=Error(t||qe[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,k),!n)throw r;return r},Je=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new E(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new E(i*3));var l=function(e){var t=n.length;if(e>t){var r=new E(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=O(e,d,1);var v=O(e,d+1,3);if(d+=3,!v){var y=Ge(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&k(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Ve,m=He,h=9,g=5;else if(v==2){var ee=O(e,d,31)+257,te=O(e,d+10,15)+4,ne=ee+O(e,d+5,31)+1;d+=14;for(var S=new E(ne),C=new E(19),w=0;w<te;++w)C[ke[w]]=O(e,d+w*3,7);d+=te*3;for(var re=Ue(C),ie=(1<<re)-1,ae=Re(C,re,1),w=0;w<ne;){var oe=ae[O(e,d,ie)];d+=oe&15;var y=oe>>4;if(y<16)S[w++]=y;else{var se=0,ce=0;for(y==16?(ce=3+O(e,d,3),d+=2,se=S[w-1]):y==17?(ce=3+O(e,d,7),d+=3):y==18&&(ce=11+O(e,d,127),d+=7);ce--;)S[w++]=se}}var le=S.subarray(0,ee),T=S.subarray(ee);h=Ue(le),g=Ue(T),p=Re(le,h,1),m=Re(T,g,1)}else k(1);if(d>_){c&&k(0);break}}s&&l(f+131072);for(var ue=(1<<h)-1,de=(1<<g)-1,fe=d;;fe=d){var se=p[We(e,d)&ue],pe=se>>4;if(d+=se&15,d>_){c&&k(0);break}if(se||k(2),pe<256)n[f++]=pe;else if(pe==256){fe=d,p=null;break}else{var me=pe-254;if(pe>264){var w=pe-257,he=De[w];me=O(e,d,(1<<he)-1)+Me[w],d+=he}var ge=m[We(e,d)&de],_e=ge>>4;ge||k(3),d+=ge&15;var T=Fe[_e];if(_e>3){var he=Oe[_e];T+=We(e,d)&(1<<he)-1,d+=he}if(d>_){c&&k(0);break}s&&l(f+131072);var ve=f+me;if(f<T){var ye=a-T,be=Math.min(T,ve);for(ye+f<0&&k(3);f<be;++f)n[f]=r[ye+f]}for(;f<ve;++f)n[f]=n[f-T]}}t.l=p,t.p=fe,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Ke(n,0,f):n.subarray(0,f)},Ye=new E(0),A=function(e,t){return e[t]|e[t+1]<<8},j=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Xe=function(e,t){return j(e,t)+j(e,t+4)*4294967296},Ze=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&k(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Qe=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new E(32768),this.p=new E(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||k(5),this.d&&k(4),!this.p.length)this.p=e;else if(e.length){var t=new E(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=Je(this.p,this.s,this.o);this.ondata(Ke(n,t,this.s.b),this.d),this.o=Ke(n,this.s.b-32768),this.s.b=this.o.length,this.p=Ke(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();function $e(e,t){return Je(e,{i:2},t&&t.out,t&&t.dictionary)}var et=function(){function e(e,t){this.v=1,this.r=0,Qe.call(this,e,t)}return e.prototype.push=function(e,t){if(Qe.prototype.e.call(this,e),this.r+=e.length,this.v){var n=this.p.subarray(this.v-1),r=n.length>3?Ze(n):4;if(r>n.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-n.length);this.p=n.subarray(r),this.v=0}Qe.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=Ge(this.s.p)+9,this.s={i:0},this.o=new E(0),this.push(new E(0),t))},e}(),tt=typeof TextDecoder<`u`&&new TextDecoder;try{tt.decode(Ye,{stream:!0})}catch{}var nt=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:Ke(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function rt(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(tt)return tt.decode(e);var i=nt(e),a=i.s,n=i.r;return n.length&&k(8),a}var it=function(e,t){return t+30+A(e,t+26)+A(e,t+28)},at=function(e,t,n){var r=A(e,t+28),i=rt(e.subarray(t+46,t+46+r),!(A(e,t+8)&2048)),a=t+46+r,o=j(e,t+20),s=n&&o==4294967295?ot(e,a):[o,j(e,t+24),j(e,t+42)],c=s[0],l=s[1],u=s[2];return[A(e,t+10),c,l,i,a+A(e,t+30)+A(e,t+32),u]},ot=function(e,t){for(;A(e,t)!=1;t+=4+A(e,t+2));return[Xe(e,t+12),Xe(e,t+4),Xe(e,t+20)]};function st(e,t){for(var n={},r=e.length-22;j(e,r)!=101010256;--r)(!r||e.length-r>65558)&&k(13);var i=A(e,r+8);if(!i)return{};var a=j(e,r+16),o=a==4294967295||i==65535;if(o){var s=j(e,r-12);o=j(e,s)==101075792,o&&(i=j(e,s+32),a=j(e,s+48))}for(var c=t&&t.filter,l=0;l<i;++l){var u=at(e,a,o),d=u[0],f=u[1],p=u[2],m=u[3],h=u[4],g=u[5],_=it(e,g);a=h,(!c||c({name:m,size:f,originalSize:p,compression:d}))&&(d?d==8?n[m]=$e(e.subarray(_,_+f),{out:new E(p)}):k(14,`unknown compression type `+d):n[m]=Ke(e,_,_+f))}return n}var ct=Math.exp(-30),M=2048,N=2048,P=function(e){return e.PLY=`ply`,e.SPZ=`spz`,e.SPLAT=`splat`,e.KSPLAT=`ksplat`,e.PCSOGS=`pcsogs`,e.PCSOGSZIP=`pcsogszip`,e.RAD=`rad`,e}({}),lt={rgbMin:0,rgbMax:1,lnScaleMin:-12,lnScaleMax:9,sh1Max:1,sh2Max:1,sh3Max:1,lodOpacity:!1};function ut(e){return e===`int`||e===`ivec2`||e===`ivec3`||e===`ivec4`}function dt(e){return e===`uint`||e===`uvec2`||e===`uvec3`||e===`uvec4`}function ft(e){return e===`float`||e===`vec2`||e===`vec3`||e===`vec4`}function pt(e){return e===`mat2`||e===`mat2x2`||e===`mat2x3`||e===`mat2x4`||e===`mat3`||e===`mat3x2`||e===`mat3x3`||e===`mat3x4`||e===`mat4`||e===`mat4x2`||e===`mat4x3`||e===`mat4x4`}function mt(e){return ft(e)||pt(e)}function ht(e){return e===`mat2`||e===`mat2x2`}function gt(e){return e===`mat3`||e===`mat3x3`}function _t(e){return e===`mat4`||e===`mat4x4`}function F(e){return Math.trunc(e).toString()}function I(e){return`${Math.max(0,Math.trunc(e)).toString()}u`}function L(e){return e===1/0?`INFINITY`:e===-1/0?`-INFINITY`:Number.isInteger(e)?e.toFixed(1):e.toString()}function vt(e){return e instanceof yt?e.type:e.dynoOut().type}var yt=class{constructor(e){this.__isDynoValue=!0,this.type=e}},R=class extends yt{constructor(e,t){super(e.outTypes[t]),this.dyno=e,this.key=t}},bt=class extends yt{constructor(e,t){super(e),this.literal=t}getLiteral(){return this.literal}},xt=class extends bt{constructor(e,t){super(e,``),this.value=t}getLiteral(){let{type:e,value:t}=this;switch(e){case`bool`:return t?`true`:`false`;case`uint`:return I(t);case`int`:return F(t);case`float`:return L(t);case`bvec2`:{let e=t;return`bvec2(${e[0]}, ${e[1]})`}case`uvec2`:{if(t instanceof x)return`uvec2(${I(t.x)}, ${I(t.y)})`;let e=t;return`uvec2(${I(e[0])}, ${I(e[1])})`}case`ivec2`:{if(t instanceof x)return`ivec2(${F(t.x)}, ${F(t.y)})`;let e=t;return`ivec2(${F(e[0])}, ${F(e[1])})`}case`vec2`:{if(t instanceof x)return`vec2(${L(t.x)}, ${L(t.y)})`;let e=t;return`vec2(${L(e[0])}, ${L(e[1])})`}case`bvec3`:{let e=t;return`bvec3(${e[0]}, ${e[1]}, ${e[2]})`}case`uvec3`:{if(t instanceof o)return`uvec3(${I(t.x)}, ${I(t.y)}, ${I(t.z)})`;let e=t;return`uvec3(${I(e[0])}, ${I(e[1])}, ${I(e[2])})`}case`ivec3`:{if(t instanceof o)return`ivec3(${F(t.x)}, ${F(t.y)}, ${F(t.z)})`;let e=t;return`ivec3(${F(e[0])}, ${F(e[1])}, ${F(e[2])})`}case`vec3`:{if(t instanceof o)return`vec3(${L(t.x)}, ${L(t.y)}, ${L(t.z)})`;let e=t;return`vec3(${L(e[0])}, ${L(e[1])}, ${L(e[2])})`}case`bvec4`:{let e=t;return`bvec4(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`}case`uvec4`:{if(t instanceof u)return`uvec4(${I(t.x)}, ${I(t.y)}, ${I(t.z)}, ${I(t.w)})`;let e=t;return`uvec4(${I(e[0])}, ${I(e[1])}, ${I(e[2])}, ${I(e[3])})`}case`ivec4`:{if(t instanceof u)return`ivec4(${F(t.x)}, ${F(t.y)}, ${F(t.z)}, ${F(t.w)})`;let e=t;return`ivec4(${F(e[0])}, ${F(e[1])}, ${F(e[2])}, ${F(e[3])})`}case`vec4`:{if(t instanceof u||t instanceof f)return`vec4(${L(t.x)}, ${L(t.y)}, ${L(t.z)}, ${L(t.w)})`;let e=t;return`vec4(${L(e[0])}, ${L(e[1])}, ${L(e[2])}, ${L(e[3])})`}case`mat2`:case`mat2x2`:{let r=t,i=r instanceof n?r.elements:t;return`${e}(${[,,,,].fill(0).map((e,t)=>L(i[t])).join(`, `)})`}case`mat2x3`:{let n=t;return`${e}(${[,,,,,,].fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat2x4`:{let n=t;return`${e}(${Array(8).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat3`:case`mat3x3`:{let n=t,r=n instanceof ve?n.elements:t;return`${e}(${Array(9).fill(0).map((e,t)=>L(r[t])).join(`, `)})`}case`mat3x2`:{let n=t;return`${e}(${[,,,,,,].fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat3x4`:{let n=t;return`${e}(${Array(12).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat4`:case`mat4x4`:{let n=t,r=n instanceof v?n.elements:t;return`${e}(${Array(16).fill(0).map((e,t)=>L(r[t])).join(`, `)})`}case`mat4x2`:{let n=t;return`${e}(${Array(8).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}case`mat4x3`:{let n=t;return`${e}(${Array(12).fill(0).map((e,t)=>L(n[t])).join(`, `)})`}default:throw Error(`Type not implemented: ${String(e)}`)}}};function St(e,t){return new xt(e,t)}var Ct=` `,wt=class{constructor({indent:e}={}){this.globals=new Set,this.statements=[],this.uniforms={},this.declares=new Set,this.updaters=[],this.sequence=0,this.indent=Ct,this.indent=e??Ct}nextSequence(){return this.sequence++}},z=class{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o}){this.inTypes=e??{},this.outTypes=t??{},this.inputs=n??{},this.update=r,this.globals=i,this.statements=a,this.generate=o??(({inputs:e,outputs:t,compile:n})=>({globals:this.globals?.({inputs:e,outputs:t,compile:n}),statements:this.statements?.({inputs:e,outputs:t,compile:n})}))}get outputs(){let e={};for(let t in this.outTypes)e[t]=new R(this,t);return e}apply(e){return Object.assign(this.inputs,e),this.outputs}compile({inputs:e,outputs:t,compile:n}){let r=[`// ${this.constructor.name}(${Object.values(e).join(`, `)}) => (${Object.values(t).join(`, `)})`],i=[];for(let e in t){let r=t[e];r&&!n.declares.has(r)&&(n.declares.add(r),i.push(e))}let{globals:a,statements:o,uniforms:s}=this.generate({inputs:e,outputs:t,compile:n});for(let e of a??[])n.globals.add(e);for(let e in s)n.uniforms[e]=s[e];this.update&&n.updaters.push(this.update);for(let e of i){let i=t[e];i&&(n.uniforms[i]||r.push(`${Dt(i,this.outTypes[e])};`))}return o?.length&&(r.push(`{`),r.push(...o.map(e=>n.indent+e)),r.push(`}`)),r}},Tt=class extends z{constructor({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,construct:a}){super({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,generate:e=>this.generateBlock(e)}),this.construct=a}generateBlock({inputs:e,outputs:t,compile:n}){let r={},i={};for(let t in e)e[t]!=null&&(r[t]=new bt(this.inTypes[t],e[t]));for(let e in t)t[e]!=null&&(i[e]=new yt(this.outTypes[e]));let a={roots:[]},o=this.construct(r,i,a);for(let r of this.globals?.({inputs:e,outputs:t,compile:n})??[])n.globals.add(r);let s=[],c=new Map;function l(e,t,r){let i=c.get(e);if(!i){i={sequence:n.nextSequence(),outNames:new Map,newOuts:new Set},c.set(e,i);for(let t in e.inputs){let n=e.inputs[t];for(;n;){if(n instanceof yt){n instanceof R&&l(n.dyno,n.key);break}if(typeof n.dynoOut!=`function`)throw Error(`dynoOut is not a function for ${n.constructor.name}`);n=n.dynoOut()}}s.push(e)}t&&(r||i.newOuts.add(t),i.outNames.set(t,r??`${t}_${i.sequence}`))}for(let e of a.roots)l(e);for(let e in i){let n=o?.[e]??i[e];for(;n;){if(n instanceof yt){n instanceof R&&l(n.dyno,n.key,t[e]);break}n=n.dynoOut()}i[e]=n}let u=[];for(let e of s){let t={},r={};for(let n in e.inputs){let r=e.inputs[n];for(;r;){if(r instanceof yt){if(r instanceof bt)t[n]=r.getLiteral();else if(r instanceof R){let e=c.get(r.dyno)?.outNames.get(r.key);if(!e)throw Error(`Source not found for ${r.dyno.constructor.name}.${r.key}`);t[n]=e}break}r=r.dynoOut()}}let i=c.get(e)??{outNames:new Map};for(let[e,t]of i.outNames.entries())r[e]=t;let a=e.compile({inputs:t,outputs:r,compile:n});u.push(a)}let d=[];for(let e in t)i[e]instanceof bt&&d.push(`${t[e]} = ${i[e].getLiteral()};`);return d.length>0&&u.push(d),{statements:u.flatMap((e,t)=>t===0?e:[``,...e])}}};function B(e,t,n,{update:r,globals:i}={}){return new Tt({inTypes:e,outTypes:t,construct:n,update:r,globals:i})}function Et({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o}){return new z({inTypes:e,outTypes:t,inputs:n,update:r,globals:i,statements:a,generate:o})}function Dt(e,t,n){let r=typeof t==`string`?t:t.type;if(!r)throw Error(`Invalid DynoType: ${String(t)}`);return`${r} ${e}${n==null?``:`[${n}]`}`}function V(e){let t=!1,n=e.split(`
2
  `).map(e=>{let n=e.trimEnd();return t?n:n.length>0?(t=!0,n):null}).filter(e=>e!=null);for(;n.length>0&&n[n.length-1].length===0;)n.pop();if(n.length===0)return[];let r=n[0].match(/^\s*/)?.[0];if(!r)return n;let i=RegExp(`^${r}`);return n.map(e=>e.replace(i,``))}function H(e){return V(e).join(`
3
  `)}var Ot=class extends z{constructor({a:e,outKey:t,outTypeFunc:n}){let r={a:vt(e)},i=n(vt(e));super({inTypes:r,outTypes:{[t]:i},inputs:{a:e}}),this.outKey=t}dynoOut(){return new R(this,this.outKey)}},kt=class extends z{constructor({a:e,b:t,outKey:n,outTypeFunc:r}){let i={a:vt(e),b:vt(t)},a=r(vt(e),vt(t));super({inTypes:i,outTypes:{[n]:a},inputs:{a:e,b:t}}),this.outKey=n}dynoOut(){return new R(this,this.outKey)}},At=Number.parseInt(`187`)>=179,jt=new Float32Array(1),Mt=new Uint32Array(jt.buffer),Nt=`Float16Array`in globalThis,Pt=Nt?new globalThis.Float16Array(1):null,Ft=new Uint16Array(Pt?.buffer);function It(e){return jt[0]=e,Mt[0]}function Lt(e){return Mt[0]=e,jt[0]}var U=Nt?Rt:zt,W=Nt?Bt:Vt;function Rt(e){return Pt[0]=e,Ft[0]}function zt(e){jt[0]=e;let t=Mt[0],n=t>>31&1,r=t>>23&255,i=t&8388607,a=n<<15;if(r===255)return i===0?a|31744:a|32767;let o=r-127+15;if(o>=31)return a|31744;if(o<=0)return o<-10?a:a|(i|8388608)>>1-o+13;let s=i>>13;return a|o<<10|s}function Bt(e){return Ft[0]=e,Pt[0]}function Vt(e){let t=e>>15&1,n=e>>10&31,r=e&1023,i;if(n===0){if(r===0)i=t<<31;else{let e=r,n=-14;for(;!(e&1024);)e<<=1,n--;e&=1023;let a=n+127,o=e<<13;i=t<<31|a<<23|o}}else if(n===31)i=r===0?t<<31|2139095040:t<<31|2143289344;else{let e=n-15+127,a=r<<13;i=t<<31|e<<23|a}return Mt[0]=i,jt[0]}function Ht(e){return Math.max(0,Math.min(255,Math.round(e*255)))}function Ut(e){let t=[],n=new Set;function r(e){e&&typeof e==`object`&&!n.has(e)&&(n.add(e),e instanceof ArrayBuffer?t.push(e):ArrayBuffer.isView(e)?t.push(e.buffer):Array.isArray(e)?e.forEach(r):Object.values(e).forEach(r))}return r(e),t}function Wt(e,t){return Array(e).fill(null).map((e,n)=>t(n))}function Gt(e,t){let n=0;for(let r of e)t(r)||(e[n++]=r);e.length=n}function Kt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=t*4,[_,v]=e;_[g]=It(n),_[g+1]=It(r),_[g+2]=It(i),_[g+3]=U(f),v[g]=U(p)|U(m)<<16,v[g+1]=U(h)|U(Math.log(a))<<16,v[g+2]=U(Math.log(o))|U(Math.log(s))<<16,v[g+3]=ln(c,l,u,d)}function qt(e,t){let n=Xt,r=t*4,[i,a]=e;return n.center.x=Lt(i[r]),n.center.y=Lt(i[r+1]),n.center.z=Lt(i[r+2]),n.opacity=W(i[r+3]&65535),n.color.r=W(a[r]&65535),n.color.g=W(a[r]>>>16),n.color.b=W(a[r+1]&65535),n.scales.x=Math.exp(W(a[r+1]>>>16)),n.scales.y=Math.exp(W(a[r+2]&65535)),n.scales.z=Math.exp(W(a[r+2]>>>16)),un(a[r+3],n.quaternion),n}function Jt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let _=g?.rgbMin??0,v=(g?.rgbMax??1)-_,y=Ht((p-_)/v),b=Ht((m-_)/v),x=Ht((h-_)/v),ee=Ht(g?.lodOpacity?.5*f:f),te=sn(Yt.set(c,l,u,d)),ne=te&255,S=te>>>8&255,C=te>>>16&255,w=g?.lnScaleMin??-12,re=254/((g?.lnScaleMax??9)-w),ie=a<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(a)-w)*re)+1)),ae=o<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(o)-w)*re)+1)),oe=s<ct?0:Math.min(255,Math.max(1,Math.round((Math.log(s)-w)*re)+1)),se=U(n),ce=U(r),le=U(i),T=t*4;e[T]=y|b<<8|x<<16|ee<<24,e[T+1]=se|ce<<16,e[T+2]=le|ne<<16|S<<24,e[T+3]=ie|ae<<8|oe<<16|C<<24}var Yt=new f,Xt={center:new o,scales:new o,quaternion:new f,color:new S,opacity:0};function Zt(e,t,n){let r=Xt,i=t*4,a=e[i],o=e[i+1],s=e[i+2],c=e[i+3],l=n?.rgbMin??0,u=(n?.rgbMax??1)-l;r.color.set(l+(a&255)/255*u,l+(a>>>8&255)/255*u,l+(a>>>16&255)/255*u),r.opacity=(a>>>24&255)/255,n?.lodOpacity&&(r.opacity=2*r.opacity),r.center.set(W(o&65535),W(o>>>16&65535),W(s&65535));let d=n?.lnScaleMin??-12,f=((n?.lnScaleMax??9)-d)/254,p=c&255;r.scales.x=p===0?0:Math.exp(d+(p-1)*f);let m=c>>>8&255;r.scales.y=m===0?0:Math.exp(d+(m-1)*f);let h=c>>>16&255;return r.scales.z=h===0?0:Math.exp(d+(h-1)*f),cn(s>>>16&65535|c>>>8&16711680,r.quaternion),r}function G(e){let t=M,n=Math.max(1,Math.min(N,Math.ceil(e/t))),r=Math.ceil(e/(t*n));return{width:t,height:n,depth:r,maxSplats:t*n*r}}function Qt(){return navigator.platform.toLowerCase().startsWith(`win`)?!1:navigator.maxTouchPoints>0||/Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/.test(navigator.userAgent)}function $t(){return/Android/.test(navigator.userAgent)||/Tizen/.test(navigator.userAgent)}function en(){return!!navigator.xr&&/Oculus/.test(navigator.userAgent)}function tn(){return/iPhone|iPad/.test(navigator.userAgent)}function nn(){return!!navigator.xr&&tn()&&/Safari/.test(navigator.userAgent)&&Qt()}var rn=H(`
4
  precision highp float;
dist/environments/index.json CHANGED
@@ -1,67 +1,67 @@
1
- [
2
- {
3
- "id": "tabletop",
4
- "name": "Tabletop",
5
- "description": "MuJoCo-GS-Web's tabletop kitchen: a 3D Gaussian splat with collision boxes for the counters and walls, and a modelled stand-in for the Toon and Lit renderers.",
6
- "xml": "tabletop/scene.xml",
7
- "decor": "decor.xml",
8
- "splat": "tabletop/scene.spz",
9
- "objects": "robot",
10
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/tabletop",
11
- "lighting": {
12
- "key": [
13
- 0.9,
14
- 2.0,
15
- 2.6
16
- ],
17
- "probe": [
18
- 0,
19
- 0.1,
20
- 1.1
21
- ],
22
- "sky": "#cfc8bb",
23
- "keyIntensity": 1.1,
24
- "keyColor": "#fff3e3"
25
- }
26
- },
27
- {
28
- "id": "kitchen",
29
- "name": "Kitchen",
30
- "description": "A kitchen and dining room built from MuJoCo primitives, with drawers, cabinet doors and objects to pick up.",
31
- "xml": "kitchen/scene.xml",
32
- "objects": "scene"
33
- },
34
- {
35
- "id": "UFC",
36
- "name": "UFC arena",
37
- "description": "MuJoCo-GS-Web's boxing ring: a 3D Gaussian splat with collision walls, and a modelled stand-in for the Toon and Lit renderers.",
38
- "xml": "UFC/scene.xml",
39
- "decor": "decor.xml",
40
- "splat": "UFC/scene.spz",
41
- "objects": "robot",
42
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/UFC",
43
- "lighting": {
44
- "key": [
45
- 0.5,
46
- 0.8,
47
- 4.0
48
- ],
49
- "probe": [
50
- 0,
51
- 0,
52
- 1.2
53
- ],
54
- "sky": "#2b2727",
55
- "keyIntensity": 1.6,
56
- "keyColor": "#ffffff"
57
- }
58
- },
59
- {
60
- "id": "basic",
61
- "name": "Empty floor",
62
- "description": "MuJoCo-GS-Web's basic environment: a floor and a light.",
63
- "xml": "basic.xml",
64
- "objects": "robot",
65
- "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/blob/main/assets/environments/basic.xml"
66
- }
67
- ]
 
1
+ [
2
+ {
3
+ "id": "tabletop",
4
+ "name": "Tabletop",
5
+ "description": "MuJoCo-GS-Web's tabletop kitchen: a 3D Gaussian splat with collision boxes for the counters and walls, a modelled stand-in for the Toon and Lit renderers, and the Kitchen's objects on its counters.",
6
+ "xml": "tabletop/scene.xml",
7
+ "decor": "decor.xml",
8
+ "splat": "tabletop/scene.spz",
9
+ "objects": "objects.xml",
10
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/tabletop",
11
+ "lighting": {
12
+ "key": [
13
+ 0.9,
14
+ 2.0,
15
+ 2.6
16
+ ],
17
+ "probe": [
18
+ 0,
19
+ 0.1,
20
+ 1.1
21
+ ],
22
+ "sky": "#cfc8bb",
23
+ "keyIntensity": 1.1,
24
+ "keyColor": "#fff3e3"
25
+ }
26
+ },
27
+ {
28
+ "id": "kitchen",
29
+ "name": "Kitchen",
30
+ "description": "A kitchen and dining room built from MuJoCo primitives, with drawers, cabinet doors and objects to pick up.",
31
+ "xml": "kitchen/scene.xml",
32
+ "objects": "scene"
33
+ },
34
+ {
35
+ "id": "UFC",
36
+ "name": "UFC arena",
37
+ "description": "MuJoCo-GS-Web's boxing ring: a 3D Gaussian splat with collision walls, and a modelled stand-in for the Toon and Lit renderers.",
38
+ "xml": "UFC/scene.xml",
39
+ "decor": "decor.xml",
40
+ "splat": "UFC/scene.spz",
41
+ "objects": "robot",
42
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/tree/main/assets/environments/UFC",
43
+ "lighting": {
44
+ "key": [
45
+ 0.5,
46
+ 0.8,
47
+ 4.0
48
+ ],
49
+ "probe": [
50
+ 0,
51
+ 0,
52
+ 1.2
53
+ ],
54
+ "sky": "#2b2727",
55
+ "keyIntensity": 1.6,
56
+ "keyColor": "#ffffff"
57
+ }
58
+ },
59
+ {
60
+ "id": "basic",
61
+ "name": "Empty floor",
62
+ "description": "MuJoCo-GS-Web's basic environment: a floor and a light.",
63
+ "xml": "basic.xml",
64
+ "objects": "robot",
65
+ "source": "https://github.com/Vector-Wangel/MuJoCo-GS-Web/blob/main/assets/environments/basic.xml"
66
+ }
67
+ ]
dist/environments/kitchen/scene.xml CHANGED
@@ -11,6 +11,19 @@
11
  <asset>
12
  <texture type="skybox" builtin="gradient" rgb1="0.85 0.87 0.9" rgb2="0.6 0.62 0.65" width="512" height="3072"/>
13
  <texture name="planks" type="2d" builtin="checker" width="512" height="512" rgb1="0.62 0.47 0.33" rgb2="0.58 0.43 0.3"/>
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  <material name="floor" texture="planks" texrepeat="6 30" texuniform="true"/>
15
  <material name="wall" rgba="0.93 0.91 0.87 1"/>
16
  <material name="tile" rgba="0.9 0.92 0.93 1"/>
@@ -25,17 +38,6 @@
25
  <material name="wood" rgba="0.55 0.38 0.24 1"/>
26
  <material name="fabric" rgba="0.33 0.38 0.47 1"/>
27
  <material name="rug" rgba="0.72 0.66 0.58 1"/>
28
- <material name="apple" rgba="0.75 0.1 0.08 1"/>
29
- <material name="orange" rgba="0.95 0.5 0.08 1"/>
30
- <material name="cube" rgba="0.95 0.78 0.1 1"/>
31
- <material name="can" rgba="0.8 0.1 0.15 1"/>
32
- <material name="mug" rgba="0.2 0.45 0.75 1"/>
33
- <material name="bowl" rgba="0.95 0.95 0.93 1"/>
34
- <material name="plate" rgba="0.97 0.97 0.95 1"/>
35
- <material name="banana" rgba="0.96 0.85 0.3 1"/>
36
- <material name="cup" rgba="0.3 0.7 0.5 1"/>
37
- <material name="bottle" rgba="0.15 0.45 0.3 1"/>
38
- <material name="book" rgba="0.6 0.15 0.2 1"/>
39
  <material name="oven" rgba="0.2 0.2 0.22 1"/>
40
  <material name="oven_glass" rgba="0.06 0.06 0.08 1"/>
41
  <material name="oven_knob" rgba="0.75 0.76 0.78 1"/>
@@ -64,8 +66,6 @@
64
  <material name="juice" rgba="0.98 0.6 0.1 1"/>
65
  <material name="sauce" rgba="0.55 0.25 0.1 1"/>
66
  <material name="egg" rgba="0.96 0.9 0.8 1"/>
67
- <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
68
- <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
69
  </asset>
70
 
71
  <default>
@@ -384,11 +384,11 @@
384
  <freejoint/>
385
  <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
386
  </body>
387
- <body name="can" pos="-1.38 -0.3 0.865">
388
  <freejoint/>
389
  <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
390
  </body>
391
- <body name="mug" pos="-1.35 0.35 0.86">
392
  <freejoint/>
393
  <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
394
  <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
@@ -411,15 +411,15 @@
411
  <freejoint/>
412
  <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
413
  </body>
414
- <body name="banana" pos="1 1.35 0.767">
415
  <freejoint/>
416
  <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
417
  </body>
418
- <body name="cup" pos="1.5 1.5 0.795">
419
  <freejoint/>
420
  <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
421
  </body>
422
- <body name="bottle" pos="-2.55 -0.45 0.985">
423
  <freejoint/>
424
  <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
425
  </body>
 
11
  <asset>
12
  <texture type="skybox" builtin="gradient" rgb1="0.85 0.87 0.9" rgb2="0.6 0.62 0.65" width="512" height="3072"/>
13
  <texture name="planks" type="2d" builtin="checker" width="512" height="512" rgb1="0.62 0.47 0.33" rgb2="0.58 0.43 0.3"/>
14
+ <material name="apple" rgba="0.75 0.1 0.08 1"/>
15
+ <material name="orange" rgba="0.95 0.5 0.08 1"/>
16
+ <material name="cube" rgba="0.95 0.78 0.1 1"/>
17
+ <material name="can" rgba="0.8 0.1 0.15 1"/>
18
+ <material name="mug" rgba="0.2 0.45 0.75 1"/>
19
+ <material name="bowl" rgba="0.95 0.95 0.93 1"/>
20
+ <material name="plate" rgba="0.97 0.97 0.95 1"/>
21
+ <material name="banana" rgba="0.96 0.85 0.3 1"/>
22
+ <material name="cup" rgba="0.3 0.7 0.5 1"/>
23
+ <material name="bottle" rgba="0.15 0.45 0.3 1"/>
24
+ <material name="book" rgba="0.6 0.15 0.2 1"/>
25
+ <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
26
+ <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
27
  <material name="floor" texture="planks" texrepeat="6 30" texuniform="true"/>
28
  <material name="wall" rgba="0.93 0.91 0.87 1"/>
29
  <material name="tile" rgba="0.9 0.92 0.93 1"/>
 
38
  <material name="wood" rgba="0.55 0.38 0.24 1"/>
39
  <material name="fabric" rgba="0.33 0.38 0.47 1"/>
40
  <material name="rug" rgba="0.72 0.66 0.58 1"/>
 
 
 
 
 
 
 
 
 
 
 
41
  <material name="oven" rgba="0.2 0.2 0.22 1"/>
42
  <material name="oven_glass" rgba="0.06 0.06 0.08 1"/>
43
  <material name="oven_knob" rgba="0.75 0.76 0.78 1"/>
 
66
  <material name="juice" rgba="0.98 0.6 0.1 1"/>
67
  <material name="sauce" rgba="0.55 0.25 0.1 1"/>
68
  <material name="egg" rgba="0.96 0.9 0.8 1"/>
 
 
69
  </asset>
70
 
71
  <default>
 
384
  <freejoint/>
385
  <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
386
  </body>
387
+ <body name="can" pos="-1.43 -0.3 0.865">
388
  <freejoint/>
389
  <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
390
  </body>
391
+ <body name="mug" pos="-1.42 0.35 0.86">
392
  <freejoint/>
393
  <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
394
  <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
 
411
  <freejoint/>
412
  <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
413
  </body>
414
+ <body name="banana" pos="0.52 1.3 0.767" quat="0.7961 0 0 0.6052">
415
  <freejoint/>
416
  <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
417
  </body>
418
+ <body name="cup" pos="0.52 1.62 0.795">
419
  <freejoint/>
420
  <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
421
  </body>
422
+ <body name="bottle" pos="-2.41 -0.45 0.985">
423
  <freejoint/>
424
  <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
425
  </body>
dist/environments/tabletop/objects.xml ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <mujoco model="tabletop objects">
2
+ <!-- Written by tools/make_tabletop.py: the kitchen environment's objects on MuJoCo-GS-Web's tabletop counters. -->
3
+ <asset>
4
+ <material name="apple" rgba="0.75 0.1 0.08 1"/>
5
+ <material name="orange" rgba="0.95 0.5 0.08 1"/>
6
+ <material name="cube" rgba="0.95 0.78 0.1 1"/>
7
+ <material name="can" rgba="0.8 0.1 0.15 1"/>
8
+ <material name="mug" rgba="0.2 0.45 0.75 1"/>
9
+ <material name="bowl" rgba="0.95 0.95 0.93 1"/>
10
+ <material name="plate" rgba="0.97 0.97 0.95 1"/>
11
+ <material name="banana" rgba="0.96 0.85 0.3 1"/>
12
+ <material name="cup" rgba="0.3 0.7 0.5 1"/>
13
+ <material name="bottle" rgba="0.15 0.45 0.3 1"/>
14
+ <material name="yogurt" rgba="0.95 0.95 0.98 1"/>
15
+ <material name="juice_box" rgba="0.95 0.55 0.1 1"/>
16
+ </asset>
17
+
18
+ <worldbody>
19
+ <body name="apple" pos="0.2 -0.36 0.845">
20
+ <freejoint/>
21
+ <geom type="sphere" size="0.025" material="apple" condim="6" friction="1.2 0.02 0.002" mass="0.08" contype="1" conaffinity="1"/>
22
+ </body>
23
+ <body name="bowl" pos="0.42 -0.39 0.823">
24
+ <freejoint/>
25
+ <geom type="cylinder" pos="0 0 0.004" size="0.05 0.004" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
26
+ <geom type="box" pos="0.062 0 0.028" euler="0 0 0.0000" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
27
+ <geom type="box" pos="0.05016 0.03644 0.028" euler="0 0 0.6283" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
28
+ <geom type="box" pos="0.01916 0.05897 0.028" euler="0 0 1.2566" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
29
+ <geom type="box" pos="-0.01916 0.05897 0.028" euler="0 0 1.8850" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
30
+ <geom type="box" pos="-0.05016 0.03644 0.028" euler="0 0 2.5133" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
31
+ <geom type="box" pos="-0.062 7.593e-18 0.028" euler="0 0 3.1416" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
32
+ <geom type="box" pos="-0.05016 -0.03644 0.028" euler="0 0 3.7699" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
33
+ <geom type="box" pos="-0.01916 -0.05897 0.028" euler="0 0 4.3982" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
34
+ <geom type="box" pos="0.01916 -0.05897 0.028" euler="0 0 5.0265" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
35
+ <geom type="box" pos="0.05016 -0.03644 0.028" euler="0 0 5.6549" size="0.006 0.021 0.022" material="bowl" condim="4" mass="0.02727" contype="1" conaffinity="1"/>
36
+ </body>
37
+ <body name="orange" pos="0.64 -0.36 0.844">
38
+ <freejoint/>
39
+ <geom type="sphere" size="0.024" material="orange" condim="6" friction="1.2 0.02 0.002" mass="0.07" contype="1" conaffinity="1"/>
40
+ </body>
41
+ <body name="banana" pos="0.84 -0.365 0.837" quat="0.9847 0 0 0.1741">
42
+ <freejoint/>
43
+ <geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" condim="6" friction="1.2 0.02 0.002" mass="0.1" contype="1" conaffinity="1"/>
44
+ </body>
45
+ <body name="plate" pos="-0.06 -0.415 0.83">
46
+ <freejoint/>
47
+ <geom type="cylinder" size="0.1 0.006" material="plate" condim="4" mass="0.25" contype="1" conaffinity="1"/>
48
+ </body>
49
+ <body name="mug" pos="-0.42 -0.365 0.86" quat="0.7074 0 0 0.7068">
50
+ <freejoint/>
51
+ <geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
52
+ <geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01" mass="0.045" contype="1" conaffinity="1"/>
53
+ </body>
54
+ <body name="cup" pos="-0.58 -0.36 0.865">
55
+ <freejoint/>
56
+ <geom type="cylinder" size="0.03 0.045" material="cup" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
57
+ </body>
58
+ <body name="can" pos="1.06 -0.16 0.865">
59
+ <freejoint/>
60
+ <geom type="cylinder" size="0.025 0.045" material="can" condim="6" friction="1.2 0.02 0.002" mass="0.06" contype="1" conaffinity="1"/>
61
+ </body>
62
+ <body name="juice_box" pos="1.06 0 0.88" quat="0.995 0 0 0.09983">
63
+ <freejoint/>
64
+ <geom type="box" size="0.03 0.022 0.06" material="juice_box" condim="4" friction="1.2 0.05 0.01" mass="0.2" contype="1" conaffinity="1"/>
65
+ </body>
66
+ <body name="yogurt" pos="1.06 0.74 0.855">
67
+ <freejoint/>
68
+ <geom type="cylinder" size="0.03 0.035" material="yogurt" condim="6" friction="1.2 0.02 0.002" mass="0.12" contype="1" conaffinity="1"/>
69
+ </body>
70
+ <body name="bottle" pos="-1.07 0.2 0.905">
71
+ <freejoint/>
72
+ <geom type="cylinder" size="0.03 0.085" material="bottle" condim="6" friction="1.2 0.02 0.002" mass="0.2" contype="1" conaffinity="1"/>
73
+ </body>
74
+ <body name="cube" pos="-1.06 -0.1 0.84" quat="0.9801 0 0 0.1987">
75
+ <freejoint/>
76
+ <geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01" mass="0.04" contype="1" conaffinity="1"/>
77
+ </body>
78
+ </worldbody>
79
+ </mujoco>
dist/index.html CHANGED
@@ -20,7 +20,7 @@
20
  })();
21
  </script>
22
  <meta name="description" content="XLeRobot in your browser: MuJoCo 4.0 physics, MuJoCo-GS-Web's robot and 3D Gaussian splat scenes, a kitchen, a learned policy and an LLM agent." />
23
- <script type="module" crossorigin src="./assets/index-DCVbIUBW.js"></script>
24
  <link rel="stylesheet" crossorigin href="./assets/index-DjoJ12Ya.css">
25
  </head>
26
  <body>
 
20
  })();
21
  </script>
22
  <meta name="description" content="XLeRobot in your browser: MuJoCo 4.0 physics, MuJoCo-GS-Web's robot and 3D Gaussian splat scenes, a kitchen, a learned policy and an LLM agent." />
23
+ <script type="module" crossorigin src="./assets/index-BxuI995N.js"></script>
24
  <link rel="stylesheet" crossorigin href="./assets/index-DjoJ12Ya.css">
25
  </head>
26
  <body>
src/agent/tools.js CHANGED
@@ -1,242 +1,256 @@
1
- // Tools an LLM agent (or any script) can call to control XLeRobot in the simulation. Each tool has a
2
- // JSON schema (OpenAI function-calling format) and an implementation that runs a skill in the
3
- // simulation loop and resolves with a short JSON-able result.
4
- //
5
- // Positions given to and returned by the tools are in the robot frame: forward, left, up in metres from
6
- // the robot's base. Angles are in degrees; positive turns are to the left.
7
- import { approach, comfortable, drive, gripper, graspPlan, holding, homeArm, lookAt, objectInfo, pick, place, reach, turn, wait } from "../robots/skills.js";
8
- import { policyPick } from "../policy/runner.js";
9
-
10
- const round = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
11
-
12
- export const TOOL_SPECS = [
13
- {
14
- name: "observe",
15
- description:
16
- "Describe the scene: the robot's pose, what each gripper holds, and every movable object with its position relative to the robot (forward/left/up in metres), its size, and whether an arm can grasp it from where the robot is.",
17
- parameters: { type: "object", properties: {} },
18
- },
19
- {
20
- name: "look",
21
- description: "Take a picture with the robot's head camera and see it (only for models that accept images).",
22
- parameters: { type: "object", properties: {} },
23
- vision: true,
24
- },
25
- {
26
- name: "go_to",
27
- description: "Drive until the named object is within reach of one arm (drives around nothing: furniture in the way stops the robot). Use before pick when an object is out of reach.",
28
- parameters: { type: "object", properties: { object: { type: "string", description: "object name from observe" } }, required: ["object"] },
29
- },
30
- {
31
- name: "drive",
32
- description: "Drive straight forward (positive) or backward (negative) by a distance in metres. Stops early if blocked.",
33
- parameters: { type: "object", properties: { distance_m: { type: "number" } }, required: ["distance_m"] },
34
- },
35
- {
36
- name: "turn",
37
- description: "Turn in place by an angle in degrees (positive = left, negative = right).",
38
- parameters: { type: "object", properties: { degrees: { type: "number" } }, required: ["degrees"] },
39
- },
40
- {
41
- name: "pick",
42
- description:
43
- "Grasp an object within reach and lift it 10 cm. method 'script' uses the scripted grasp; method 'policy' uses the learned ACT policy (trained for objects on a table in front of an arm). The arm is chosen automatically unless given.",
44
- parameters: {
45
- type: "object",
46
- properties: {
47
- object: { type: "string" },
48
- arm: { type: "string", enum: ["left", "right"] },
49
- method: { type: "string", enum: ["script", "policy"] },
50
- },
51
- required: ["object"],
52
- },
53
- },
54
- {
55
- name: "place",
56
- description:
57
- "Put down the object held in a gripper: into or onto another object (e.g. a bowl or plate) when 'on' is given, otherwise at a spot given as forward/left in metres relative to the robot, on the surface it stands on.",
58
- parameters: {
59
- type: "object",
60
- properties: {
61
- arm: { type: "string", enum: ["left", "right"] },
62
- on: { type: "string", description: "object to put it in or on" },
63
- forward_m: { type: "number" },
64
- left_m: { type: "number" },
65
- },
66
- required: ["arm"],
67
- },
68
- },
69
- {
70
- name: "gripper",
71
- description: "Open or close one gripper.",
72
- parameters: { type: "object", properties: { arm: { type: "string", enum: ["left", "right"] }, open: { type: "boolean" } }, required: ["arm", "open"] },
73
- },
74
- {
75
- name: "move_arm",
76
- description: "Move a wrist to a point relative to the robot (forward/left/up in metres) with the gripper pitched down by pitch_deg (90 = pointing straight down).",
77
- parameters: {
78
- type: "object",
79
- properties: {
80
- arm: { type: "string", enum: ["left", "right"] },
81
- forward_m: { type: "number" },
82
- left_m: { type: "number" },
83
- up_m: { type: "number" },
84
- pitch_deg: { type: "number" },
85
- },
86
- required: ["arm", "forward_m", "left_m", "up_m"],
87
- },
88
- },
89
- {
90
- name: "home_arms",
91
- description: "Move both arms back to their resting pose (grippers keep their state).",
92
- parameters: { type: "object", properties: {} },
93
- },
94
- {
95
- name: "look_at",
96
- description: "Point the head camera at an object.",
97
- parameters: { type: "object", properties: { object: { type: "string" } }, required: ["object"] },
98
- },
99
- {
100
- name: "wait",
101
- description: "Wait a number of seconds of simulated time.",
102
- parameters: { type: "object", properties: { seconds: { type: "number" } }, required: ["seconds"] },
103
- },
104
- ];
105
-
106
- /**
107
- * Bind the tools to the running app: `app` provides {sim, robot, skills, objects(), loadPolicy(),
108
- * snapshot(name), envInfo()}. Returns {specs(vision), call(name, args)}.
109
- */
110
- export function createTools(app) {
111
- const byName = (name) => {
112
- const list = app.objects();
113
- const want = String(name ?? "").trim().toLowerCase().replace(/^the\s+/, "");
114
- const found = list.find((o) => o.name.toLowerCase() === want) ?? list.find((o) => o.name.toLowerCase().includes(want));
115
- if (!found) throw new Error(`no object named "${name}"; objects: ${list.map((o) => o.name).join(", ")}`);
116
- return found;
117
- };
118
- const run = (label, generator) => app.skills.start(label, generator);
119
- const heldBy = (side) => app.objects().find((o) => holding(app.robot, side, o.id))?.name ?? null;
120
-
121
- const impl = {
122
- observe() {
123
- const { robot, sim } = app;
124
- const [x, y, yaw] = robot.pose();
125
- const objects = app.objects().map((o) => {
126
- const info = objectInfo(sim, o.id);
127
- const p = robot.toRobot(info.center);
128
- const check = comfortable(robot, o.id);
129
- const plan = check.plan;
130
- return {
131
- name: o.name,
132
- forward_m: round(p[0]),
133
- left_m: round(p[1]),
134
- up_m: round(p[2]),
135
- distance_m: round(Math.hypot(p[0], p[1])),
136
- size_cm: [round(info.width * 100, 0), round(info.height * 100, 0)],
137
- graspable_now: !plan.reason,
138
- arm: plan.reason ? null : plan.side,
139
- note: plan.reason ?? (check.ok ? "in reach" : "at the edge of reach"),
140
- };
141
- });
142
- objects.sort((a, b) => a.distance_m - b.distance_m);
143
- return {
144
- scene: app.envInfo(),
145
- robot: { x_m: round(x), y_m: round(y), heading_deg: round((yaw * 180) / Math.PI, 0) },
146
- grippers: Object.fromEntries(["left", "right"].map((s) => [s, { open: robot.gripperOpening(s) > 0.5, holding: heldBy(s) }])),
147
- objects,
148
- };
149
- },
150
- async look() {
151
- const image = await app.snapshot("head");
152
- if (!image) return { ok: false, message: "this robot has no head camera" };
153
- return { ok: true, message: "head camera image attached", image };
154
- },
155
- async go_to({ object }) {
156
- const o = byName(object);
157
- return run(`go to ${o.name}`, approach(app.robot, o.id));
158
- },
159
- async drive({ distance_m }) {
160
- const d = Math.max(-3, Math.min(3, Number(distance_m)));
161
- return run(`drive ${d} m`, drive(app.robot, d));
162
- },
163
- async turn({ degrees }) {
164
- const a = Math.max(-360, Math.min(360, Number(degrees)));
165
- return run(`turn ${a}°`, turn(app.robot, (a * Math.PI) / 180));
166
- },
167
- async pick({ object, arm, method = "script" }) {
168
- const o = byName(object);
169
- const plan = graspPlan(app.robot, o.id, arm);
170
- if (plan.reason) return { ok: false, message: `cannot grasp ${o.name}: ${plan.reason}. Try go_to first.` };
171
- if (method === "policy") {
172
- const runner = await app.loadPolicy();
173
- const side = arm ?? plan.side;
174
- return run(`policy pick ${o.name}`, policyPick(app.robot, runner, o.id, side));
175
- }
176
- return run(`pick ${o.name}`, pick(app.robot, o.id, { side: arm }));
177
- },
178
- async place({ arm, on, forward_m, left_m }) {
179
- const { robot, sim } = app;
180
- const heldName = heldBy(arm);
181
- const held = heldName ? app.objects().find((o) => o.name === heldName) : null;
182
- let point;
183
- let target = null;
184
- if (on) {
185
- target = byName(on);
186
- const info = objectInfo(sim, target.id);
187
- const c = robot.toRobot(info.center);
188
- point = [c[0], c[1], robot.toRobot([0, 0, info.bottom])[2] + 0.012];
189
- } else if (forward_m !== undefined && left_m !== undefined) {
190
- // On the furniture under that spot (the floor if none).
191
- point = [Number(forward_m), Number(left_m), 0];
192
- const below = app.surfaceBelow?.(robot.toWorld([point[0], point[1], 2]));
193
- point[2] = robot.toRobot([0, 0, below ?? 0])[2];
194
- } else return { ok: false, message: "give 'on' or forward_m and left_m" };
195
- const result = await run(`place`, place(robot, arm, point, held?.id));
196
- if (target && held) {
197
- // In or on a container counts when the object ends within its footprint.
198
- const t = objectInfo(sim, target.id);
199
- const a = robot.toRobot(t.center);
200
- const b = robot.toRobot(sim.bodyPos(held.id));
201
- const inside = Math.hypot(a[0] - b[0], a[1] - b[1]) < Math.max(0.03, t.width / 2 - 0.005);
202
- return { ...result, ok: inside, message: inside ? `put the ${held.name} in/on the ${target.name}` : `the ${held.name} missed the ${target.name} (${result.message})` };
203
- }
204
- return result;
205
- },
206
- async gripper({ arm, open }) {
207
- return run(`${open ? "open" : "close"} ${arm} gripper`, gripper(app.robot, arm, Boolean(open)));
208
- },
209
- async move_arm({ arm, forward_m, left_m, up_m, pitch_deg = 90 }) {
210
- return run(`move ${arm} arm`, reach(app.robot, arm, [Number(forward_m), Number(left_m), Number(up_m)], { pitch: (Number(pitch_deg) * Math.PI) / 180, duration: 1.4 }));
211
- },
212
- async home_arms() {
213
- const robot = app.robot;
214
- return run("home arms", (function* () {
215
- yield* homeArm(robot, "left");
216
- yield* homeArm(robot, "right");
217
- return { ok: true, message: "arms at rest" };
218
- })());
219
- },
220
- async look_at({ object }) {
221
- const o = byName(object);
222
- return run(`look at ${o.name}`, lookAt(app.robot, app.sim.bodyPos(o.id)));
223
- },
224
- async wait({ seconds }) {
225
- return run(`wait`, wait(app.robot, Math.max(0, Math.min(20, Number(seconds)))));
226
- },
227
- };
228
-
229
- return {
230
- specs: (vision = true) => TOOL_SPECS.filter((t) => vision || !t.vision),
231
- async call(name, args = {}) {
232
- const fn = impl[name];
233
- if (!fn) return { ok: false, message: `unknown tool ${name}` };
234
- if (!app.robot?.arms) return { ok: false, message: "these tools drive XLeRobot, and another robot is loaded (XLeRobot can be chosen under Scene, Robot)" };
235
- try {
236
- return await fn(args);
237
- } catch (error) {
238
- return { ok: false, message: error.message };
239
- }
240
- },
241
- };
242
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Tools an LLM agent (or any script) can call to control XLeRobot in the simulation. Each tool has a
2
+ // JSON schema (OpenAI function-calling format) and an implementation that runs a skill in the
3
+ // simulation loop and resolves with a short JSON-able result.
4
+ //
5
+ // Positions given to and returned by the tools are in the robot frame: forward, left, up in metres from
6
+ // the robot's base. Angles are in degrees; positive turns are to the left.
7
+ import { approach, clearDrive, clearTurn, comfortable, drive, gripper, graspPlan, holding, homeArm, lookAt, objectInfo, pick, place, reach, restArm, turn, wait } from "../robots/skills.js";
8
+ import { policyPick } from "../policy/runner.js";
9
+
10
+ const round = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
11
+
12
+ export const TOOL_SPECS = [
13
+ {
14
+ name: "observe",
15
+ description:
16
+ "Describe the scene: the robot's pose, what each gripper holds, and every movable object with its position relative to the robot (forward/left/up in metres), its size, and whether an arm can grasp it from where the robot is.",
17
+ parameters: { type: "object", properties: {} },
18
+ },
19
+ {
20
+ name: "look",
21
+ description: "Take a picture with the robot's head camera and see it (only for models that accept images).",
22
+ parameters: { type: "object", properties: {} },
23
+ vision: true,
24
+ },
25
+ {
26
+ name: "go_to",
27
+ description: "Drive around the furniture to where one arm reaches the named object, facing it so it can be grasped well. Use before pick when an object is out of reach, and before place to go to a bowl or plate.",
28
+ parameters: { type: "object", properties: { object: { type: "string", description: "object name from observe" } }, required: ["object"] },
29
+ },
30
+ {
31
+ name: "drive",
32
+ description: "Drive straight forward (positive) or backward (negative) by a distance in metres. Stops short of furniture in the way.",
33
+ parameters: { type: "object", properties: { distance_m: { type: "number" } }, required: ["distance_m"] },
34
+ },
35
+ {
36
+ name: "turn",
37
+ description: "Turn in place by an angle in degrees (positive = left, negative = right). Stops short of furniture the robot would swing into.",
38
+ parameters: { type: "object", properties: { degrees: { type: "number" } }, required: ["degrees"] },
39
+ },
40
+ {
41
+ name: "pick",
42
+ description:
43
+ "Grasp an object within reach and lift it 10 cm. method 'script' uses the scripted grasp; method 'policy' uses the learned ACT policy (trained for objects on a table in front of an arm). The arm is chosen automatically unless given.",
44
+ parameters: {
45
+ type: "object",
46
+ properties: {
47
+ object: { type: "string" },
48
+ arm: { type: "string", enum: ["left", "right"] },
49
+ method: { type: "string", enum: ["script", "policy"] },
50
+ },
51
+ required: ["object"],
52
+ },
53
+ },
54
+ {
55
+ name: "place",
56
+ description:
57
+ "Put down the object held in a gripper: into or onto another object (e.g. a bowl or plate) when 'on' is given, otherwise at a spot given as forward/left in metres relative to the robot, on the surface it stands on.",
58
+ parameters: {
59
+ type: "object",
60
+ properties: {
61
+ arm: { type: "string", enum: ["left", "right"] },
62
+ on: { type: "string", description: "object to put it in or on" },
63
+ forward_m: { type: "number" },
64
+ left_m: { type: "number" },
65
+ },
66
+ required: ["arm"],
67
+ },
68
+ },
69
+ {
70
+ name: "gripper",
71
+ description: "Open or close one gripper.",
72
+ parameters: { type: "object", properties: { arm: { type: "string", enum: ["left", "right"] }, open: { type: "boolean" } }, required: ["arm", "open"] },
73
+ },
74
+ {
75
+ name: "move_arm",
76
+ description: "Move a wrist to a point relative to the robot (forward/left/up in metres) with the gripper pitched down by pitch_deg (90 = pointing straight down).",
77
+ parameters: {
78
+ type: "object",
79
+ properties: {
80
+ arm: { type: "string", enum: ["left", "right"] },
81
+ forward_m: { type: "number" },
82
+ left_m: { type: "number" },
83
+ up_m: { type: "number" },
84
+ pitch_deg: { type: "number" },
85
+ },
86
+ required: ["arm", "forward_m", "left_m", "up_m"],
87
+ },
88
+ },
89
+ {
90
+ name: "home_arms",
91
+ description: "Move both arms back to their resting pose (grippers keep their state).",
92
+ parameters: { type: "object", properties: {} },
93
+ },
94
+ {
95
+ name: "look_at",
96
+ description: "Point the head camera at an object.",
97
+ parameters: { type: "object", properties: { object: { type: "string" } }, required: ["object"] },
98
+ },
99
+ {
100
+ name: "wait",
101
+ description: "Wait a number of seconds of simulated time.",
102
+ parameters: { type: "object", properties: { seconds: { type: "number" } }, required: ["seconds"] },
103
+ },
104
+ ];
105
+
106
+ /**
107
+ * Bind the tools to the running app: `app` provides {sim, robot, skills, objects(), loadPolicy(),
108
+ * snapshot(name), envInfo()}. Returns {specs(vision), call(name, args)}.
109
+ */
110
+ export function createTools(app) {
111
+ const byName = (name) => {
112
+ const list = app.objects();
113
+ const want = String(name ?? "").trim().toLowerCase().replace(/^the\s+/, "");
114
+ const found = list.find((o) => o.name.toLowerCase() === want) ?? list.find((o) => o.name.toLowerCase().includes(want));
115
+ if (!found) throw new Error(`no object named "${name}"; objects: ${list.map((o) => o.name).join(", ")}`);
116
+ return found;
117
+ };
118
+ const run = (label, generator) => app.skills.start(label, generator);
119
+ const heldBy = (side) => app.objects().find((o) => holding(app.robot, side, o.id))?.name ?? null;
120
+
121
+ const impl = {
122
+ observe() {
123
+ const { robot, sim } = app;
124
+ const [x, y, yaw] = robot.pose();
125
+ const objects = app.objects().map((o) => {
126
+ const info = objectInfo(sim, o.id);
127
+ const p = robot.toRobot(info.center);
128
+ const check = comfortable(robot, o.id);
129
+ const plan = check.plan;
130
+ return {
131
+ name: o.name,
132
+ forward_m: round(p[0]),
133
+ left_m: round(p[1]),
134
+ up_m: round(p[2]),
135
+ distance_m: round(Math.hypot(p[0], p[1])),
136
+ size_cm: [round(info.width * 100, 0), round(info.height * 100, 0)],
137
+ graspable_now: !plan.reason,
138
+ arm: plan.reason ? null : plan.side,
139
+ note: plan.reason ?? (check.ok ? "in reach" : "at the edge of reach"),
140
+ };
141
+ });
142
+ objects.sort((a, b) => a.distance_m - b.distance_m);
143
+ return {
144
+ scene: app.envInfo(),
145
+ robot: { x_m: round(x), y_m: round(y), heading_deg: round((yaw * 180) / Math.PI, 0) },
146
+ grippers: Object.fromEntries(["left", "right"].map((s) => [s, { open: robot.gripperOpening(s) > 0.5, holding: heldBy(s) }])),
147
+ objects,
148
+ };
149
+ },
150
+ async look() {
151
+ const image = await app.snapshot("head");
152
+ if (!image) return { ok: false, message: "this robot has no head camera" };
153
+ return { ok: true, message: "head camera image attached", image };
154
+ },
155
+ async go_to({ object }) {
156
+ const o = byName(object);
157
+ return run(`go to ${o.name}`, approach(app.robot, o.id));
158
+ },
159
+ async drive({ distance_m }) {
160
+ const asked = Math.max(-3, Math.min(3, Number(distance_m)));
161
+ const clear = clearDrive(app.robot, asked);
162
+ if (Math.abs(clear.distance) < 0.01) return { ok: false, message: `cannot drive ${asked > 0 ? "forward" : "backward"}: the ${clear.blockedBy} is in the way` };
163
+ const result = await run(`drive ${round(clear.distance)} m`, drive(app.robot, clear.distance));
164
+ return clear.blockedBy ? { ...result, message: `${result.message}, stopping short of the ${clear.blockedBy}` } : result;
165
+ },
166
+ async turn({ degrees }) {
167
+ const asked = (Math.max(-360, Math.min(360, Number(degrees))) * Math.PI) / 180;
168
+ const clear = clearTurn(app.robot, asked);
169
+ if (Math.abs(clear.angle) < 0.02) return { ok: false, message: `cannot turn ${asked > 0 ? "left" : "right"}: the robot would swing into the ${clear.blockedBy}` };
170
+ const result = await run(`turn ${round((clear.angle * 180) / Math.PI, 0)}°`, turn(app.robot, clear.angle));
171
+ return clear.blockedBy ? { ...result, message: `${result.message}, stopping short of the ${clear.blockedBy}` } : result;
172
+ },
173
+ async pick({ object, arm, method = "script" }) {
174
+ const o = byName(object);
175
+ const plan = graspPlan(app.robot, o.id, arm);
176
+ if (plan.reason) return { ok: false, message: `cannot grasp ${o.name}: ${plan.reason}. Try go_to first.` };
177
+ if (method === "policy") {
178
+ const runner = await app.loadPolicy();
179
+ const side = arm ?? plan.side;
180
+ const robot = app.robot;
181
+ // The policy learned to pick starting with the arm at rest.
182
+ return run(`policy pick ${o.name}`, (function* () {
183
+ yield* restArm(robot, side);
184
+ return yield* policyPick(robot, runner, o.id, side);
185
+ })());
186
+ }
187
+ return run(`pick ${o.name}`, pick(app.robot, o.id, { side: arm }));
188
+ },
189
+ async place({ arm, on, forward_m, left_m }) {
190
+ const { robot, sim } = app;
191
+ const heldName = heldBy(arm);
192
+ const held = heldName ? app.objects().find((o) => o.name === heldName) : null;
193
+ let point;
194
+ let target = null;
195
+ let slack = 0;
196
+ if (on) {
197
+ target = byName(on);
198
+ const info = objectInfo(sim, target.id);
199
+ const c = robot.toRobot(info.center);
200
+ point = [c[0], c[1], robot.toRobot([0, 0, info.bottom])[2] + 0.012];
201
+ // Anywhere near the middle of a wide container will do: the arm aims at the nearer part of it.
202
+ slack = Math.max(0, info.width / 2 - (held ? objectInfo(sim, held.id).width / 2 : 0.025) - 0.02);
203
+ } else if (forward_m !== undefined && left_m !== undefined) {
204
+ // On the furniture under that spot (the floor if none).
205
+ point = [Number(forward_m), Number(left_m), 0];
206
+ const below = app.surfaceBelow?.(robot.toWorld([point[0], point[1], 2]));
207
+ point[2] = robot.toRobot([0, 0, below ?? 0])[2];
208
+ } else return { ok: false, message: "give 'on' or forward_m and left_m" };
209
+ const result = await run(`place`, place(robot, arm, point, held?.id, { slack }));
210
+ if (target && held) {
211
+ // In or on a container counts when the object ends within its footprint.
212
+ const t = objectInfo(sim, target.id);
213
+ const a = robot.toRobot(t.center);
214
+ const b = robot.toRobot(sim.bodyPos(held.id));
215
+ const inside = Math.hypot(a[0] - b[0], a[1] - b[1]) < Math.max(0.03, t.width / 2 - 0.005);
216
+ return { ...result, ok: inside, message: inside ? `put the ${held.name} in/on the ${target.name}` : `the ${held.name} missed the ${target.name} (${result.message})` };
217
+ }
218
+ return result;
219
+ },
220
+ async gripper({ arm, open }) {
221
+ return run(`${open ? "open" : "close"} ${arm} gripper`, gripper(app.robot, arm, Boolean(open)));
222
+ },
223
+ async move_arm({ arm, forward_m, left_m, up_m, pitch_deg = 90 }) {
224
+ return run(`move ${arm} arm`, reach(app.robot, arm, [Number(forward_m), Number(left_m), Number(up_m)], { pitch: (Number(pitch_deg) * Math.PI) / 180, duration: 1.4 }));
225
+ },
226
+ async home_arms() {
227
+ const robot = app.robot;
228
+ return run("home arms", (function* () {
229
+ yield* homeArm(robot, "left");
230
+ yield* homeArm(robot, "right");
231
+ return { ok: true, message: "arms at rest" };
232
+ })());
233
+ },
234
+ async look_at({ object }) {
235
+ const o = byName(object);
236
+ return run(`look at ${o.name}`, lookAt(app.robot, app.sim.bodyPos(o.id)));
237
+ },
238
+ async wait({ seconds }) {
239
+ return run(`wait`, wait(app.robot, Math.max(0, Math.min(20, Number(seconds)))));
240
+ },
241
+ };
242
+
243
+ return {
244
+ specs: (vision = true) => TOOL_SPECS.filter((t) => vision || !t.vision),
245
+ async call(name, args = {}) {
246
+ const fn = impl[name];
247
+ if (!fn) return { ok: false, message: `unknown tool ${name}` };
248
+ if (!app.robot?.arms) return { ok: false, message: "these tools drive XLeRobot, and another robot is loaded (XLeRobot can be chosen under Scene, Robot)" };
249
+ try {
250
+ return await fn(args);
251
+ } catch (error) {
252
+ return { ok: false, message: error.message };
253
+ }
254
+ },
255
+ };
256
+ }
src/main.js CHANGED
@@ -71,11 +71,15 @@ function showError(error) {
71
  // ---------------------------------------------------------------------------------------------
72
  // Scenes
73
 
74
- /** The environment's XML, and its decor (a modelled stand-in for its splat) to include, if it has one. */
 
 
 
75
  async function envSource(env) {
76
  const dir = env.xml.slice(0, env.xml.lastIndexOf("/") + 1);
77
- const [xml, decor] = await Promise.all([text(`${BASE}environments/${env.xml}`), env.decor ? download(`${BASE}environments/${dir}${env.decor}`) : null]);
78
- return decor ? { xml, files: [[env.decor, decor]], includes: [env.decor] } : { xml };
 
79
  }
80
 
81
  /** Compose `envId` with the robot `robotId`, compile, settle and show it. */
@@ -104,7 +108,12 @@ async function loadScene(envId, robotId) {
104
  app.envId = env.id;
105
  app.robotId = robotId;
106
  app.teleop = robot instanceof XLeRobot ? new XLeRobotTeleop(robot) : robot instanceof G1Robot ? new G1Teleop(robot) : null;
107
- sim.reset(() => robot.home());
 
 
 
 
 
108
  // Objects settle where the scene drops them; a walking robot stands on its joint servos meanwhile.
109
  sim.run(robot instanceof G1Robot ? 0.3 : 1.0, () => robot.update());
110
  if (walking) robot.setPolicy(walking.ort, walking.session);
 
71
  // ---------------------------------------------------------------------------------------------
72
  // Scenes
73
 
74
+ /**
75
+ * The environment's XML, and the files next to it to include: its decor (a modelled stand-in for its
76
+ * splat) and its objects ("objects" naming a file), if it has them.
77
+ */
78
  async function envSource(env) {
79
  const dir = env.xml.slice(0, env.xml.lastIndexOf("/") + 1);
80
+ const extra = [env.decor, env.objects?.endsWith(".xml") ? env.objects : null].filter(Boolean);
81
+ const [xml, ...files] = await Promise.all([text(`${BASE}environments/${env.xml}`), ...extra.map((f) => download(`${BASE}environments/${dir}${f}`))]);
82
+ return { xml, files: extra.map((f, k) => [f, files[k]]), includes: extra };
83
  }
84
 
85
  /** Compose `envId` with the robot `robotId`, compile, settle and show it. */
 
108
  app.envId = env.id;
109
  app.robotId = robotId;
110
  app.teleop = robot instanceof XLeRobot ? new XLeRobotTeleop(robot) : robot instanceof G1Robot ? new G1Teleop(robot) : null;
111
+ // XLeRobot's arms start in their resting pose: rising to it from the model's zero pose, they would
112
+ // sweep objects off a counter beside the robot.
113
+ sim.reset(() => {
114
+ robot.home();
115
+ if (robot instanceof XLeRobot) robot.snapJoints();
116
+ });
117
  // Objects settle where the scene drops them; a walking robot stands on its joint servos meanwhile.
118
  sim.run(robot instanceof G1Robot ? 0.3 : 1.0, () => robot.update());
119
  if (walking) robot.setPolicy(walking.ort, walking.session);
src/robots/nav.js ADDED
@@ -0,0 +1,930 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Navigation for XLeRobot's base: a map of what the base can hit, a planner for paths around it, and a
2
+ // path follower. The go-to and place skills (skills.js) use it.
3
+ //
4
+ // The map is 2D shapes (oriented rectangles and circles), each with a height range, made from the
5
+ // scene's collision geoms that are neither the robot nor free objects: counters, walls, chairs, doors.
6
+ // The robot is a few rectangles in its own frame, each with its own height range: the chassis (with the
7
+ // arm bases inside its outline), and for each arm the links that reach out beyond it. A shape only
8
+ // counts against the parts it overlaps in height, so the arms pass over a worktop the chassis cannot.
9
+ //
10
+ // The planner is a hybrid A* over the pose of the point midway between the wheels, which stays put when
11
+ // the base turns in place. Its moves are short straight drives and arcs, forward and backward, and turns
12
+ // in place; every pose along a move is checked against the map. The heuristic is the shortest path of a
13
+ // disc that fits inside the chassis, found by a grid search outward from the goal.
14
+ //
15
+ // Poses given to and returned by this module are the chassis pose [x, y, yaw] that robot.pose() reports.
16
+
17
+ const TAU = 2 * Math.PI;
18
+ const wrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));
19
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
20
+
21
+ // ---------------------------------------------------------------------------------------------
22
+ // The map
23
+
24
+ /** Bodies that belong to the robot rooted at `root`. */
25
+ function subtree(model, root) {
26
+ const inside = new Uint8Array(model.nbody);
27
+ for (let b = 1; b < model.nbody; b++) {
28
+ for (let x = b; x > 0; x = model.body_parentid[x]) {
29
+ if (x === root) {
30
+ inside[b] = 1;
31
+ break;
32
+ }
33
+ }
34
+ }
35
+ return inside;
36
+ }
37
+
38
+ /** Bodies with a free joint (objects): they are pushed aside or picked up, not driven around. */
39
+ function freeBodies(model) {
40
+ const free = new Uint8Array(model.nbody);
41
+ for (let j = 0; j < model.njnt; j++) if (model.jnt_type[j] === 0) free[model.jnt_bodyid[j]] = 1;
42
+ return free;
43
+ }
44
+
45
+ /** A geom's box in its own frame: centre and half sizes (MuJoCo's geom_aabb). */
46
+ function localBox(model, g) {
47
+ const a = model.geom_aabb.subarray(6 * g, 6 * g + 6);
48
+ return [a[0], a[1], a[2], a[3], a[4], a[5]];
49
+ }
50
+
51
+ /**
52
+ * The 2D footprint and height range of a geom, or null if it has no extent to speak of.
53
+ * Shapes: {round: false, x, y, ux, uy, hx, hy, z0, z1} (a rectangle with unit axis u) or
54
+ * {round: true, x, y, r, z0, z1}.
55
+ */
56
+ export function geomShape(model, data, g) {
57
+ const type = model.geom_type[g];
58
+ const R = data.geom_xmat.subarray(9 * g, 9 * g + 9); // row-major; column c is local axis c
59
+ const p = data.geom_xpos.subarray(3 * g, 3 * g + 3);
60
+ const size = model.geom_size.subarray(3 * g, 3 * g + 3);
61
+ if (type === 2) return { round: true, x: p[0], y: p[1], r: size[0], z0: p[2] - size[0], z1: p[2] + size[0] };
62
+ let half;
63
+ let offset = [0, 0, 0];
64
+ if (type === 6 || type === 4) half = [size[0], size[1], size[2]]; // box, ellipsoid
65
+ else if (type === 5) half = [size[0], size[0], size[1]]; // cylinder along local z
66
+ else if (type === 3) half = [size[0], size[0], size[1] + size[0]]; // capsule
67
+ else {
68
+ const b = localBox(model, g);
69
+ offset = [b[0], b[1], b[2]];
70
+ half = [b[3], b[4], b[5]];
71
+ }
72
+ const c = [0, 1, 2].map((r) => p[r] + R[3 * r] * offset[0] + R[3 * r + 1] * offset[1] + R[3 * r + 2] * offset[2]);
73
+ const zHalf = Math.abs(R[6]) * half[0] + Math.abs(R[7]) * half[1] + Math.abs(R[8]) * half[2];
74
+ const z0 = c[2] - zHalf;
75
+ const z1 = c[2] + zHalf;
76
+ // Upright cylinders and capsules are circles; lying ones are rectangles along their axis.
77
+ if ((type === 5 || type === 3) && Math.abs(R[8]) > 0.995) return { round: true, x: c[0], y: c[1], r: size[0], z0, z1 };
78
+ if ((type === 5 || type === 3) && Math.abs(R[8]) < 0.1) {
79
+ const n = Math.hypot(R[2], R[5]);
80
+ return { round: false, x: c[0], y: c[1], ux: R[2] / n, uy: R[5] / n, hx: half[2], hy: size[0], z0, z1 };
81
+ }
82
+ // A local axis that is vertical leaves the other two as an oriented rectangle.
83
+ for (const k of [2, 0, 1]) {
84
+ if (Math.abs(R[6 + k]) < 0.995) continue;
85
+ const i = (k + 1) % 3;
86
+ const j = (k + 2) % 3;
87
+ const n = Math.hypot(R[i], R[3 + i]) || 1;
88
+ return { round: false, x: c[0], y: c[1], ux: R[i] / n, uy: R[3 + i] / n, hx: half[i], hy: half[j], z0, z1 };
89
+ }
90
+ // Otherwise the world-aligned box around it.
91
+ const hx = Math.abs(R[0]) * half[0] + Math.abs(R[1]) * half[1] + Math.abs(R[2]) * half[2];
92
+ const hy = Math.abs(R[3]) * half[0] + Math.abs(R[4]) * half[1] + Math.abs(R[5]) * half[2];
93
+ return { round: false, x: c[0], y: c[1], ux: 1, uy: 0, hx, hy, z0, z1 };
94
+ }
95
+
96
+ /** What the base can hit, from the scene as it is now (open doors included). */
97
+ export class ObstacleMap {
98
+ /**
99
+ * `robotRoot` is the robot's root body, which is left out. Free bodies (objects) are left out too
100
+ * unless `objects` is true; then all but `except` (what the grippers hold) are in.
101
+ */
102
+ constructor(sim, robotRoot, { objects = false, except = [] } = {}) {
103
+ const { model, data } = sim;
104
+ const inRobot = subtree(model, robotRoot);
105
+ const free = freeBodies(model);
106
+ const skip = new Set(except);
107
+ this.shapes = [];
108
+ for (let g = 0; g < model.ngeom; g++) {
109
+ const b = model.geom_bodyid[g];
110
+ if (inRobot[b] || skip.has(b) || (free[b] && !objects)) continue;
111
+ if (!model.geom_contype[g] && !model.geom_conaffinity[g]) continue;
112
+ const type = model.geom_type[g];
113
+ if (type === 0 || type === 1) continue; // plane, height field
114
+ const s = geomShape(model, data, g);
115
+ if (s && s.z1 > 0.015) {
116
+ s.body = sim.bodyNames[b];
117
+ this.shapes.push(s);
118
+ }
119
+ }
120
+ this.#index();
121
+ }
122
+
123
+ #index() {
124
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
125
+ for (const s of this.shapes) {
126
+ const [a, b, c, d] = shapeBox(s);
127
+ s.box = [a, b, c, d];
128
+ x0 = Math.min(x0, a); y0 = Math.min(y0, b); x1 = Math.max(x1, c); y1 = Math.max(y1, d);
129
+ }
130
+ if (!this.shapes.length) [x0, y0, x1, y1] = [-1, -1, 1, 1];
131
+ this.bounds = [x0, y0, x1, y1];
132
+ this.cell = 0.25;
133
+ this.ox = x0 - 1;
134
+ this.oy = y0 - 1;
135
+ this.nx = Math.ceil((x1 - x0 + 2) / this.cell) + 1;
136
+ this.ny = Math.ceil((y1 - y0 + 2) / this.cell) + 1;
137
+ this.cells = Array.from({ length: this.nx * this.ny }, () => []);
138
+ this.shapes.forEach((s, k) => {
139
+ const [i0, j0, i1, j1] = this.#range(...s.box);
140
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) this.cells[j * this.nx + i].push(k);
141
+ });
142
+ this.stamp = new Uint32Array(this.shapes.length);
143
+ this.visit = 0;
144
+ }
145
+
146
+ #range(x0, y0, x1, y1) {
147
+ const c = this.cell;
148
+ return [
149
+ clamp(Math.floor((x0 - this.ox) / c), 0, this.nx - 1),
150
+ clamp(Math.floor((y0 - this.oy) / c), 0, this.ny - 1),
151
+ clamp(Math.floor((x1 - this.ox) / c), 0, this.nx - 1),
152
+ clamp(Math.floor((y1 - this.oy) / c), 0, this.ny - 1),
153
+ ];
154
+ }
155
+
156
+ /** Call `fn(shape)` once for every shape whose box meets [x0, y0, x1, y1]; stops when fn returns true. */
157
+ near(x0, y0, x1, y1, fn) {
158
+ const [i0, j0, i1, j1] = this.#range(x0, y0, x1, y1);
159
+ const v = ++this.visit;
160
+ for (let j = j0; j <= j1; j++) {
161
+ for (let i = i0; i <= i1; i++) {
162
+ for (const k of this.cells[j * this.nx + i]) {
163
+ if (this.stamp[k] === v) continue;
164
+ this.stamp[k] = v;
165
+ const s = this.shapes[k];
166
+ if (s.box[0] > x1 || s.box[2] < x0 || s.box[1] > y1 || s.box[3] < y0) continue;
167
+ if (fn(s)) return true;
168
+ }
169
+ }
170
+ }
171
+ return false;
172
+ }
173
+ }
174
+
175
+ function shapeBox(s) {
176
+ if (s.round) return [s.x - s.r, s.y - s.r, s.x + s.r, s.y + s.r];
177
+ const ex = Math.abs(s.ux) * s.hx + Math.abs(s.uy) * s.hy;
178
+ const ey = Math.abs(s.uy) * s.hx + Math.abs(s.ux) * s.hy;
179
+ return [s.x - ex, s.y - ey, s.x + ex, s.y + ey];
180
+ }
181
+
182
+ /**
183
+ * Separation between a rectangle (centre, unit axis u, half sizes) and a shape: positive when apart.
184
+ * For two rectangles this is the largest gap along their four axes, a lower bound of their distance.
185
+ */
186
+ function gap(x, y, ux, uy, hx, hy, s) {
187
+ if (s.round) {
188
+ const dx = s.x - x;
189
+ const dy = s.y - y;
190
+ const lx = Math.abs(dx * ux + dy * uy) - hx;
191
+ const ly = Math.abs(-dx * uy + dy * ux) - hy;
192
+ const outside = Math.hypot(Math.max(lx, 0), Math.max(ly, 0));
193
+ return (outside > 0 ? outside : Math.max(lx, ly)) - s.r;
194
+ }
195
+ const dx = s.x - x;
196
+ const dy = s.y - y;
197
+ const vx = -uy, vy = ux;
198
+ const sux = s.ux, suy = s.uy, svx = -s.uy, svy = s.ux;
199
+ // along this rectangle's axes
200
+ const g1 = Math.abs(dx * ux + dy * uy) - hx - s.hx * Math.abs(sux * ux + suy * uy) - s.hy * Math.abs(svx * ux + svy * uy);
201
+ const g2 = Math.abs(dx * vx + dy * vy) - hy - s.hx * Math.abs(sux * vx + suy * vy) - s.hy * Math.abs(svx * vx + svy * vy);
202
+ // along the shape's axes
203
+ const g3 = Math.abs(dx * sux + dy * suy) - s.hx - hx * Math.abs(ux * sux + uy * suy) - hy * Math.abs(vx * sux + vy * suy);
204
+ const g4 = Math.abs(dx * svx + dy * svy) - s.hy - hx * Math.abs(ux * svx + uy * svy) - hy * Math.abs(vx * svx + vy * svy);
205
+ return Math.max(g1, g2, g3, g4);
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------------------------
209
+ // The robot
210
+
211
+ /**
212
+ * A geom's box in the robot frame: [x0, y0, z0, x1, y1, z1], z in the world. Spheres, cylinders,
213
+ * capsules and boxes exactly (a wheel's box does not grow as it spins); other geoms by the corners of
214
+ * their own box.
215
+ */
216
+ function boxInRobot(robot, g, zc) {
217
+ const { model, data } = robot.sim;
218
+ const R = data.geom_xmat.subarray(9 * g, 9 * g + 9);
219
+ const p = data.geom_xpos.subarray(3 * g, 3 * g + 3);
220
+ const type = model.geom_type[g];
221
+ if (type === 2 || type === 3 || type === 5 || type === 6) {
222
+ const size = model.geom_size.subarray(3 * g, 3 * g + 3);
223
+ const c = robot.toRobot(Array.from(p));
224
+ c[2] += zc;
225
+ // the robot frame's axes in the world: forward, left, up
226
+ const m = robot.sim.bodyMat(robot.root);
227
+ const axes = [[-m[0], -m[3], -m[6]], [-m[1], -m[4], -m[7]], [m[2], m[5], m[8]]];
228
+ const out = [0, 0, 0, 0, 0, 0];
229
+ axes.forEach((e, k) => {
230
+ // the geom's local axes' components along e
231
+ const a = [R[0] * e[0] + R[3] * e[1] + R[6] * e[2], R[1] * e[0] + R[4] * e[1] + R[7] * e[2], R[2] * e[0] + R[5] * e[1] + R[8] * e[2]];
232
+ let half;
233
+ if (type === 2) half = size[0];
234
+ else if (type === 6) half = Math.abs(a[0]) * size[0] + Math.abs(a[1]) * size[1] + Math.abs(a[2]) * size[2];
235
+ else half = Math.abs(a[2]) * size[1] + size[0] * Math.sqrt(Math.max(0, 1 - a[2] * a[2])) + (type === 3 ? size[0] * Math.abs(a[2]) : 0);
236
+ out[k] = c[k] - half;
237
+ out[3 + k] = c[k] + half;
238
+ });
239
+ return out;
240
+ }
241
+ const b = localBox(model, g);
242
+ const lo = [Infinity, Infinity, Infinity];
243
+ const hi = [-Infinity, -Infinity, -Infinity];
244
+ for (const sx of [-1, 1]) {
245
+ for (const sy of [-1, 1]) {
246
+ for (const sz of [-1, 1]) {
247
+ const l = [b[0] + sx * b[3], b[1] + sy * b[4], b[2] + sz * b[5]];
248
+ const w = [0, 1, 2].map((r) => p[r] + R[3 * r] * l[0] + R[3 * r + 1] * l[1] + R[3 * r + 2] * l[2]);
249
+ const q = robot.toRobot(w);
250
+ q[2] += zc;
251
+ for (let k = 0; k < 3; k++) {
252
+ lo[k] = Math.min(lo[k], q[k]);
253
+ hi[k] = Math.max(hi[k], q[k]);
254
+ }
255
+ }
256
+ }
257
+ }
258
+ return [lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]];
259
+ }
260
+
261
+ /**
262
+ * The robot's outline as it stands now: rectangles in its frame (x forward, y left, from the chassis
263
+ * origin) with world height ranges. `held` are free bodies the grippers hold: they travel with the arms.
264
+ * Also the axle offset: how far ahead of the chassis origin the wheels' axle is.
265
+ */
266
+ export function robotFootprint(robot, held = []) {
267
+ const { sim } = robot;
268
+ const { model } = sim;
269
+ const zc = sim.bodyPos(robot.root)[2];
270
+ const inRobot = subtree(model, robot.root);
271
+ const boxes = [];
272
+ for (let g = 0; g < model.ngeom; g++) {
273
+ const b = model.geom_bodyid[g];
274
+ if (!inRobot[b] || (!model.geom_contype[g] && !model.geom_conaffinity[g])) continue;
275
+ boxes.push({ box: boxInRobot(robot, g, zc), base: b === robot.root || /wheel/i.test(sim.bodyNames[b]) });
276
+ }
277
+ for (const id of held) {
278
+ for (let g = model.body_geomadr[id]; g < model.body_geomadr[id] + model.body_geomnum[id]; g++) boxes.push({ box: boxInRobot(robot, g, zc), base: false });
279
+ }
280
+ // The chassis outline: its own geoms and the wheels.
281
+ const o = [Infinity, Infinity, -Infinity, -Infinity];
282
+ for (const { box, base } of boxes) {
283
+ if (!base) continue;
284
+ o[0] = Math.min(o[0], box[0]); o[1] = Math.min(o[1], box[1]);
285
+ o[2] = Math.max(o[2], box[3]); o[3] = Math.max(o[3], box[4]);
286
+ }
287
+ const tol = 0.005;
288
+ const inside = (b) => b[0] >= o[0] - tol && b[1] >= o[1] - tol && b[3] <= o[2] + tol && b[4] <= o[3] + tol;
289
+ let top = 0;
290
+ const reach = { left: null, right: null };
291
+ for (const { box } of boxes) {
292
+ if (inside(box)) {
293
+ top = Math.max(top, box[5]);
294
+ continue;
295
+ }
296
+ const side = (box[1] + box[4]) / 2 >= 0 ? "left" : "right";
297
+ const r = (reach[side] ??= [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity]);
298
+ for (let k = 0; k < 3; k++) {
299
+ r[k] = Math.min(r[k], box[k]);
300
+ r[3 + k] = Math.max(r[3 + k], box[3 + k]);
301
+ }
302
+ }
303
+ const part = (x0, y0, x1, y1, z0, z1) => ({ cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, hx: (x1 - x0) / 2, hy: (y1 - y0) / 2, z0, z1 });
304
+ const parts = [part(o[0], o[1], o[2], o[3], 0, top)];
305
+ for (const r of Object.values(reach)) if (r) parts.push(part(r[0], r[1], r[3], r[4], r[2], r[5]));
306
+ // The drive wheels' axle, ahead of the chassis origin on XLeRobot.
307
+ let axle = 0;
308
+ const wheels = sim.bodyNames.map((n, b) => (/^(left|right)_wheel$/.test(n) ? b : -1)).filter((b) => b >= 0);
309
+ if (wheels.length) axle = wheels.reduce((s, b) => s + robot.toRobot(sim.bodyPos(b))[0], 0) / wheels.length;
310
+ return { parts, axle, outline: o, radius: Math.min(-o[0], o[2], -o[1], o[3]) };
311
+ }
312
+
313
+ /** Collision tests of the robot's footprint against a map. */
314
+ export class Footprint {
315
+ constructor(map, footprint) {
316
+ this.map = map;
317
+ this.fp = footprint;
318
+ // For each part, the shapes that overlap it in height (1 cm apart counts as clear).
319
+ this.relevant = footprint.parts.map((p) => new Set(map.shapes.filter((s) => s.z1 > p.z0 + 0.01 && s.z0 < p.z1 - 0.01)));
320
+ this.reach = Math.max(...footprint.parts.map((p) => Math.hypot(Math.abs(p.cx) + p.hx, Math.abs(p.cy) + p.hy)));
321
+ }
322
+
323
+ /** Smallest gap between the robot at chassis pose (x, y, yaw) and the map, up to `cap`. */
324
+ clearance(x, y, yaw, cap = 0.3) {
325
+ const c = Math.cos(yaw);
326
+ const s = Math.sin(yaw);
327
+ let best = cap;
328
+ this.fp.parts.forEach((p, k) => {
329
+ const px = x + c * p.cx - s * p.cy;
330
+ const py = y + s * p.cx + c * p.cy;
331
+ const e = Math.abs(c) * p.hx + Math.abs(s) * p.hy + best;
332
+ const f = Math.abs(s) * p.hx + Math.abs(c) * p.hy + best;
333
+ const rel = this.relevant[k];
334
+ this.map.near(px - e, py - f, px + e, py + f, (shape) => {
335
+ if (!rel.has(shape)) return false;
336
+ best = Math.min(best, gap(px, py, c, s, p.hx, p.hy, shape));
337
+ return best < -0.05;
338
+ });
339
+ });
340
+ return best;
341
+ }
342
+
343
+ /** The first shape closer than `margin` to the robot at chassis pose (x, y, yaw), or null. */
344
+ hit(x, y, yaw, margin = 0.02) {
345
+ const c = Math.cos(yaw);
346
+ const s = Math.sin(yaw);
347
+ let found = null;
348
+ for (let k = 0; k < this.fp.parts.length && !found; k++) {
349
+ const p = this.fp.parts[k];
350
+ const px = x + c * p.cx - s * p.cy;
351
+ const py = y + s * p.cx + c * p.cy;
352
+ const e = Math.abs(c) * p.hx + Math.abs(s) * p.hy + margin;
353
+ const f = Math.abs(s) * p.hx + Math.abs(c) * p.hy + margin;
354
+ const rel = this.relevant[k];
355
+ this.map.near(px - e, py - f, px + e, py + f, (shape) => {
356
+ if (rel.has(shape) && gap(px, py, c, s, p.hx, p.hy, shape) < margin) found = shape;
357
+ return Boolean(found);
358
+ });
359
+ }
360
+ return found;
361
+ }
362
+
363
+ /** True if the robot at chassis pose (x, y, yaw) keeps at least `margin` from the map. */
364
+ free(x, y, yaw, margin = 0.02) {
365
+ const c = Math.cos(yaw);
366
+ const s = Math.sin(yaw);
367
+ for (let k = 0; k < this.fp.parts.length; k++) {
368
+ const p = this.fp.parts[k];
369
+ const px = x + c * p.cx - s * p.cy;
370
+ const py = y + s * p.cx + c * p.cy;
371
+ const e = Math.abs(c) * p.hx + Math.abs(s) * p.hy + margin;
372
+ const f = Math.abs(s) * p.hx + Math.abs(c) * p.hy + margin;
373
+ const rel = this.relevant[k];
374
+ const hit = this.map.near(px - e, py - f, px + e, py + f, (shape) => rel.has(shape) && gap(px, py, c, s, p.hx, p.hy, shape) < margin);
375
+ if (hit) return false;
376
+ }
377
+ return true;
378
+ }
379
+ }
380
+
381
+ // ---------------------------------------------------------------------------------------------
382
+ // Grid distances for a disc that fits inside the chassis
383
+
384
+ /** Shortest distances over a grid for a disc of radius `radius`, from [x, y]; Infinity where it cannot go. */
385
+ export class DiscField {
386
+ constructor(footprint, origin, { radius, res = 0.05, extra = [] } = {}) {
387
+ const map = footprint.map;
388
+ this.res = res;
389
+ const pts = [origin, ...extra];
390
+ let [x0, y0, x1, y1] = map.bounds;
391
+ for (const p of pts) {
392
+ x0 = Math.min(x0, p[0] - 1); y0 = Math.min(y0, p[1] - 1);
393
+ x1 = Math.max(x1, p[0] + 1); y1 = Math.max(y1, p[1] + 1);
394
+ }
395
+ this.ox = x0;
396
+ this.oy = y0;
397
+ this.nx = Math.ceil((x1 - x0) / res) + 1;
398
+ this.ny = Math.ceil((y1 - y0) / res) + 1;
399
+ const n = this.nx * this.ny;
400
+ const blocked = new Uint8Array(n);
401
+ const body = footprint.relevant[0]; // the chassis part
402
+ const r = radius ?? footprint.fp.radius - 0.045;
403
+ for (let j = 0; j < this.ny; j++) {
404
+ for (let i = 0; i < this.nx; i++) {
405
+ const cx = x0 + i * res;
406
+ const cy = y0 + j * res;
407
+ blocked[j * this.nx + i] = map.near(cx - r, cy - r, cx + r, cy + r, (s) => body.has(s) && gap(cx, cy, 1, 0, 0, 0, s) < r) ? 1 : 0;
408
+ }
409
+ }
410
+ this.blocked = blocked;
411
+ this.dist = new Float64Array(n).fill(Infinity); // 64-bit: the heap's keys are compared with these
412
+ const start = this.#index(origin[0], origin[1]);
413
+ if (start < 0) return;
414
+ // Dijkstra, 8-connected. The start cell is allowed even if blocked (the goal sits close to furniture).
415
+ const heap = new Heap();
416
+ this.dist[start] = 0;
417
+ heap.push(start, 0);
418
+ const steps = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, Math.SQRT2], [1, -1, Math.SQRT2], [-1, 1, Math.SQRT2], [-1, -1, Math.SQRT2]];
419
+ while (heap.size) {
420
+ const [k, d] = heap.pop();
421
+ if (d > this.dist[k]) continue;
422
+ const i = k % this.nx;
423
+ const j = (k - i) / this.nx;
424
+ for (const [di, dj, w] of steps) {
425
+ const a = i + di;
426
+ const b = j + dj;
427
+ if (a < 0 || b < 0 || a >= this.nx || b >= this.ny) continue;
428
+ const m = b * this.nx + a;
429
+ if (blocked[m]) continue;
430
+ const nd = d + w * res;
431
+ if (nd < this.dist[m]) {
432
+ this.dist[m] = nd;
433
+ heap.push(m, nd);
434
+ }
435
+ }
436
+ }
437
+ }
438
+
439
+ #index(x, y) {
440
+ const i = Math.round((x - this.ox) / this.res);
441
+ const j = Math.round((y - this.oy) / this.res);
442
+ if (i < 0 || j < 0 || i >= this.nx || j >= this.ny) return -1;
443
+ return j * this.nx + i;
444
+ }
445
+
446
+ /**
447
+ * Distance from the origin to [x, y]: the best of the nearest cells, or of the cells around them when
448
+ * those are all blocked (a pose right next to furniture can sit in blocked cells).
449
+ */
450
+ at(x, y) {
451
+ const fi = (x - this.ox) / this.res;
452
+ const fj = (y - this.oy) / this.res;
453
+ for (const reach of [1, 3]) {
454
+ let best = Infinity;
455
+ for (let i = Math.ceil(fi) - reach; i <= Math.floor(fi) + reach; i++) {
456
+ for (let j = Math.ceil(fj) - reach; j <= Math.floor(fj) + reach; j++) {
457
+ if (i < 0 || j < 0 || i >= this.nx || j >= this.ny) continue;
458
+ const d = this.dist[j * this.nx + i] + Math.hypot(x - (this.ox + i * this.res), y - (this.oy + j * this.res));
459
+ best = Math.min(best, d);
460
+ }
461
+ }
462
+ if (Number.isFinite(best)) return best;
463
+ }
464
+ return Infinity;
465
+ }
466
+ }
467
+
468
+ /** A binary min-heap of [item, key]. */
469
+ class Heap {
470
+ constructor() {
471
+ this.items = [];
472
+ this.keys = [];
473
+ }
474
+
475
+ get size() {
476
+ return this.items.length;
477
+ }
478
+
479
+ push(item, key) {
480
+ const { items, keys } = this;
481
+ let i = items.length;
482
+ items.push(item);
483
+ keys.push(key);
484
+ while (i > 0) {
485
+ const p = (i - 1) >> 1;
486
+ if (keys[p] <= key) break;
487
+ items[i] = items[p];
488
+ keys[i] = keys[p];
489
+ i = p;
490
+ }
491
+ items[i] = item;
492
+ keys[i] = key;
493
+ }
494
+
495
+ pop() {
496
+ const { items, keys } = this;
497
+ const top = [items[0], keys[0]];
498
+ const item = items.pop();
499
+ const key = keys.pop();
500
+ if (items.length) {
501
+ let i = 0;
502
+ const n = items.length;
503
+ for (;;) {
504
+ let c = 2 * i + 1;
505
+ if (c >= n) break;
506
+ if (c + 1 < n && keys[c + 1] < keys[c]) c++;
507
+ if (keys[c] >= key) break;
508
+ items[i] = items[c];
509
+ keys[i] = keys[c];
510
+ i = c;
511
+ }
512
+ items[i] = item;
513
+ keys[i] = key;
514
+ }
515
+ return top;
516
+ }
517
+ }
518
+
519
+ // ---------------------------------------------------------------------------------------------
520
+ // Planning
521
+
522
+ const STEP = 0.1; // length of a drive move (m)
523
+ const ARC = 0.25; // heading change of an arc move over STEP (rad): radius 0.4 m
524
+ const HEADINGS = 48;
525
+ // [kind, distance, heading change]; kind 0 forward, 1 backward, 2 turn in place
526
+ const MOVES = [
527
+ [0, STEP, 0], [0, STEP, ARC], [0, STEP, -ARC],
528
+ [1, -STEP, 0], [1, -STEP, ARC], [1, -STEP, -ARC],
529
+ [2, 0, Math.PI / 12], [2, 0, -Math.PI / 12], [2, 0, Math.PI / 4], [2, 0, -Math.PI / 4],
530
+ ];
531
+ const COST = { backward: 2.0, turn: 0.3, arc: 0.01, switchTurn: 0.04, switchGear: 0.4, clearance: 0.12, nearby: 0.6 };
532
+
533
+ /** Axle point of a chassis pose, and back. */
534
+ export const axleOf = (pose, d) => [pose[0] + d * Math.cos(pose[2]), pose[1] + d * Math.sin(pose[2]), pose[2]];
535
+ export const chassisOf = (x, y, th, d) => [x - d * Math.cos(th), y - d * Math.sin(th), th];
536
+
537
+ /** The axle point after a move of `ds` metres that turns the heading by `dth`. */
538
+ function moveEnd(x, y, th, ds, dth) {
539
+ if (ds === 0) return [x, y, th + dth];
540
+ if (Math.abs(dth) < 1e-9) return [x + ds * Math.cos(th), y + ds * Math.sin(th), th];
541
+ const r = ds / dth;
542
+ return [x + r * (Math.sin(th + dth) - Math.sin(th)), y - r * (Math.cos(th + dth) - Math.cos(th)), th + dth];
543
+ }
544
+
545
+ /**
546
+ * Plan a path for the chassis from `start` to `goal` (chassis poses [x, y, yaw]). A generator: it yields
547
+ * every `slice` milliseconds so a long search does not hold up the page, and returns
548
+ * {ok, moves, length, message}. `moves` are {kind: "turn", heading} and {kind: "drive", dir, points}
549
+ * (axle points [x, y, heading], from the move's start).
550
+ */
551
+ export function* planPath(fp, start, goal, { margin = 0.02, goalMargin = margin, maxExpansions = 60000, slice = 8 } = {}) {
552
+ const d = fp.fp.axle;
553
+ // A start closer to furniture than the margin (the base stopped short of something) may still move
554
+ // away: near the start the margin is what it has, less a few millimetres.
555
+ const startClear = fp.clearance(start[0], start[1], start[2], margin);
556
+ const nearStart = Math.min(margin, Math.max(0.002, startClear - 0.003));
557
+ const freeAt = (x, y, th, m = margin) => {
558
+ const c = chassisOf(x, y, th, d);
559
+ const mm = m > nearStart && Math.hypot(c[0] - start[0], c[1] - start[1]) < 0.35 ? nearStart : m;
560
+ return fp.free(c[0], c[1], c[2], mm);
561
+ };
562
+ const s0 = axleOf(start, d);
563
+ const g0 = axleOf(goal, d);
564
+ if (!fp.free(goal[0], goal[1], goal[2], goalMargin)) return { ok: false, message: "the goal pose touches furniture" };
565
+ const field = new DiscField(fp, [goal[0], goal[1]], { extra: [[start[0], start[1]]] });
566
+ const h0 = field.at(start[0], start[1]);
567
+ if (!Number.isFinite(h0)) return { ok: false, message: "no way through to the goal" };
568
+ const res = 0.05;
569
+ const { ox, oy, nx, ny } = field;
570
+ const keyOf = (x, y, th) => {
571
+ const i = Math.round((x - ox) / res);
572
+ const j = Math.round((y - oy) / res);
573
+ if (i < 0 || j < 0 || i >= nx || j >= ny) return -1;
574
+ const h = ((Math.round((th / TAU) * HEADINGS) % HEADINGS) + HEADINGS) % HEADINGS;
575
+ return (h * ny + j) * nx + i;
576
+ };
577
+ const best = new Map();
578
+ const nodes = [];
579
+ const heap = new Heap();
580
+ const heuristic = (x, y, th) => {
581
+ const c = chassisOf(x, y, th, d);
582
+ return field.at(c[0], c[1]);
583
+ };
584
+ const add = (x, y, th, g, parent, move) => {
585
+ const k = keyOf(x, y, th);
586
+ if (k < 0) return;
587
+ const prev = best.get(k);
588
+ if (prev !== undefined && prev <= g + 1e-9) return;
589
+ best.set(k, g);
590
+ const h = heuristic(x, y, th);
591
+ if (!Number.isFinite(h)) return;
592
+ nodes.push({ x, y, th, g, parent, move });
593
+ heap.push(nodes.length - 1, g + 1.3 * h);
594
+ };
595
+ // The free-space cost: driving close to furniture costs a little more, so paths keep to the middle.
596
+ const nearCost = (x, y, th) => {
597
+ const c = chassisOf(x, y, th, d);
598
+ const clear = fp.clearance(c[0], c[1], c[2], COST.clearance);
599
+ return COST.nearby * (COST.clearance - clear);
600
+ };
601
+ add(s0[0], s0[1], s0[2], 0, -1, -1);
602
+ let expanded = 0;
603
+ let lastYield = performance.now();
604
+ while (heap.size) {
605
+ const [n] = heap.pop();
606
+ const node = nodes[n];
607
+ if (best.get(keyOf(node.x, node.y, node.th)) < node.g - 1e-9) continue;
608
+ expanded++;
609
+ if (expanded > maxExpansions) return { ok: false, message: `no path found (searched ${expanded} poses)` };
610
+ // a few milliseconds of searching per control period, so the page keeps drawing
611
+ if (expanded % 32 === 0 && performance.now() - lastYield > slice) {
612
+ yield;
613
+ lastYield = performance.now();
614
+ }
615
+ // Try to finish with a few straight moves now and then, and always near the goal.
616
+ const near = Math.hypot(node.x - g0[0], node.y - g0[1]);
617
+ if (near < 1.6 && (expanded % 3 === 0 || near < 0.4)) {
618
+ const tail = finish(node, g0, freeAt, goalMargin, margin);
619
+ if (tail) return assemble(nodes, n, tail, expanded);
620
+ }
621
+ const lastKind = node.move >= 0 ? MOVES[node.move][0] : -1;
622
+ for (let m = 0; m < MOVES.length; m++) {
623
+ const [kind, ds, dth] = MOVES[m];
624
+ const [x, y, th] = moveEnd(node.x, node.y, node.th, ds, dth);
625
+ // check the move along its way: two points along a drive, every 5 degrees of a turn
626
+ const samples = kind === 2 ? Math.ceil(Math.abs(dth) / (Math.PI / 36)) : 2;
627
+ let ok = true;
628
+ for (let k = 1; k <= samples && ok; k++) {
629
+ const t = k / samples;
630
+ const [px, py, pth] = moveEnd(node.x, node.y, node.th, ds * t, dth * t);
631
+ ok = freeAt(px, py, pth);
632
+ }
633
+ if (!ok) continue;
634
+ let cost = kind === 0 ? STEP : kind === 1 ? STEP * COST.backward : COST.turn * Math.abs(dth);
635
+ if (kind !== 2 && dth !== 0) cost += COST.arc;
636
+ if (lastKind >= 0 && lastKind !== kind) cost += kind === 2 || lastKind === 2 ? COST.switchTurn : COST.switchGear;
637
+ if (kind !== 2) cost += nearCost(x, y, th);
638
+ add(x, y, wrap(th), node.g + cost, n, m);
639
+ }
640
+ }
641
+ return { ok: false, message: "no path found" };
642
+ }
643
+
644
+ /**
645
+ * Straight moves from a node to the goal (axle poses), if they are clear: line up on the goal's heading
646
+ * some way back from it and drive in straight, so the base meets furniture square; or go straight there.
647
+ * Returns a list of {kind, ...} moves or null.
648
+ */
649
+ function finish(node, g0, freeAt, goalMargin, margin) {
650
+ const [gx, gy, gth] = g0;
651
+ for (const back of [0.3, 0.15, 0]) {
652
+ const qx = gx - back * Math.cos(gth);
653
+ const qy = gy - back * Math.sin(gth);
654
+ const moves = [];
655
+ let x = node.x, y = node.y, th = node.th;
656
+ const dist = Math.hypot(qx - x, qy - y);
657
+ if (dist > 0.01) {
658
+ // face the pre-goal point (or back up to it if it is behind and close)
659
+ const bearing = Math.atan2(qy - y, qx - x);
660
+ const reverse = Math.abs(wrap(bearing - th)) > 2.2 && dist < 0.6;
661
+ const heading = reverse ? wrap(bearing + Math.PI) : bearing;
662
+ if (!turnClear(x, y, th, heading, freeAt)) continue;
663
+ if (Math.abs(wrap(heading - th)) > 1e-3) moves.push({ kind: "turn", heading, delta: wrap(heading - th) });
664
+ th = heading;
665
+ if (!lineClear(x, y, qx, qy, th, freeAt, back > 0 ? margin : goalMargin)) continue;
666
+ moves.push({ kind: "drive", dir: reverse ? -1 : 1, points: [[x, y, th], [qx, qy, th]] });
667
+ x = qx;
668
+ y = qy;
669
+ }
670
+ if (!turnClear(x, y, th, gth, freeAt)) continue;
671
+ if (Math.abs(wrap(gth - th)) > 1e-3) moves.push({ kind: "turn", heading: gth, delta: wrap(gth - th) });
672
+ th = gth;
673
+ if (back > 0) {
674
+ if (!lineClear(x, y, gx, gy, th, freeAt, goalMargin)) continue;
675
+ moves.push({ kind: "drive", dir: 1, points: [[x, y, th], [gx, gy, th]] });
676
+ }
677
+ return moves;
678
+ }
679
+ return null;
680
+ }
681
+
682
+ function turnClear(x, y, from, to, freeAt) {
683
+ const delta = wrap(to - from);
684
+ const n = Math.ceil(Math.abs(delta) / (Math.PI / 36));
685
+ for (let k = 1; k <= n; k++) if (!freeAt(x, y, from + (delta * k) / n)) return false;
686
+ return true;
687
+ }
688
+
689
+ function lineClear(x0, y0, x1, y1, th, freeAt, endMargin) {
690
+ const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / 0.03));
691
+ for (let k = 1; k <= n; k++) {
692
+ const t = k / n;
693
+ // The last stretch into a goal next to furniture may come closer than the travel margin.
694
+ if (!freeAt(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, th, t > 0.6 ? endMargin : undefined)) return false;
695
+ }
696
+ return true;
697
+ }
698
+
699
+ /** The planned moves, merged: consecutive turns into one, consecutive drives in one direction into one. */
700
+ function assemble(nodes, last, tail, expanded) {
701
+ const chain = [];
702
+ for (let n = last; n >= 0; n = nodes[n].parent) chain.push(nodes[n]);
703
+ chain.reverse();
704
+ const moves = [];
705
+ // Turns keep their signed angle: the way the planner checked, which is not always the shorter way.
706
+ const push = (m) => {
707
+ const prev = moves[moves.length - 1];
708
+ if (m.kind === "turn" && prev?.kind === "turn") {
709
+ prev.heading = m.heading;
710
+ prev.delta += m.delta;
711
+ } else if (m.kind === "drive" && prev?.kind === "drive" && prev.dir === m.dir) prev.points.push(...m.points.slice(1));
712
+ else moves.push(m);
713
+ };
714
+ for (let k = 1; k < chain.length; k++) {
715
+ const a = chain[k - 1];
716
+ const b = chain[k];
717
+ const [kind, ds, dth] = MOVES[b.move];
718
+ if (kind === 2) push({ kind: "turn", heading: wrap(b.th), delta: dth });
719
+ else {
720
+ // points along the arc every 2 cm
721
+ const n = Math.max(1, Math.round(Math.abs(ds) / 0.02));
722
+ const points = [[a.x, a.y, a.th]];
723
+ for (let i = 1; i <= n; i++) points.push(moveEnd(a.x, a.y, a.th, (ds * i) / n, (dth * i) / n));
724
+ push({ kind: "drive", dir: kind === 0 ? 1 : -1, points });
725
+ }
726
+ }
727
+ for (const m of tail) push(m);
728
+ let length = 0;
729
+ for (const m of moves) {
730
+ if (m.kind !== "drive") continue;
731
+ for (let i = 1; i < m.points.length; i++) length += Math.hypot(m.points[i][0] - m.points[i - 1][0], m.points[i][1] - m.points[i - 1][1]);
732
+ }
733
+ return { ok: true, moves, length, expanded, message: `planned ${length.toFixed(2)} m` };
734
+ }
735
+
736
+ // ---------------------------------------------------------------------------------------------
737
+ // Following a path
738
+
739
+ /** Robot geoms touching furniture (not free objects, not the floor), or null. */
740
+ export class ContactWatch {
741
+ constructor(sim, robotRoot) {
742
+ this.sim = sim;
743
+ this.inRobot = subtree(sim.model, robotRoot);
744
+ this.free = freeBodies(sim.model);
745
+ }
746
+
747
+ /** {robot, other, depth} for the deepest robot-furniture contact now, or null. */
748
+ check() {
749
+ const { model, data } = this.sim;
750
+ const vec = data.contact;
751
+ let found = null;
752
+ for (let i = 0; i < data.ncon; i++) {
753
+ const c = vec.get(i);
754
+ const g1 = c.geom1;
755
+ const g2 = c.geom2;
756
+ const dist = c.dist;
757
+ c.delete();
758
+ const b1 = model.geom_bodyid[g1];
759
+ const b2 = model.geom_bodyid[g2];
760
+ if (this.inRobot[b1] === this.inRobot[b2]) continue;
761
+ const other = this.inRobot[b1] ? g2 : g1;
762
+ const ob = model.geom_bodyid[other];
763
+ if (this.free[ob] || model.geom_type[other] === 0) continue;
764
+ if (!found || -dist > found.depth) found = { robot: this.sim.bodyNames[this.inRobot[b1] ? b1 : b2], other: this.sim.bodyNames[ob], depth: -dist };
765
+ }
766
+ return found;
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Drive the planned moves (a generator for the skill runner). Turns go to their heading; drives follow
772
+ * their axle points with pure pursuit. With the robot's Footprint `fp` it slows down near furniture and
773
+ * looks a quarter of a second ahead: it stops before a pose that would touch, rather than after.
774
+ * Stops with {ok: false} if the base strays from the path, stalls, would touch or touches furniture;
775
+ * {ok: true} at the end.
776
+ */
777
+ export function* followPath(robot, moves, { fp, watch, speed = 0.25, reverseSpeed = 0.18, turnRate = 0.9 } = {}) {
778
+ try {
779
+ for (const m of moves) {
780
+ // A turn ends on the planned heading, which takes out what the drive before it left over; it
781
+ // still goes the way the planner checked.
782
+ const delta = m.kind === "turn" ? m.delta + wrap(m.heading - (robot.pose()[2] + m.delta)) : 0;
783
+ const r = m.kind === "turn" ? yield* turnBy(robot, delta, { fp, watch, rate: turnRate }) : yield* track(robot, m.points, m.dir, { fp, watch, speed: m.dir > 0 ? speed : reverseSpeed });
784
+ if (!r.ok) return r;
785
+ // A drive that ran past its end backs up to it: the next turn happens where it was planned.
786
+ if (r.overshoot > 0.012) {
787
+ const [x, y, yaw] = robot.pose();
788
+ const d = fp?.fp.axle ?? 0;
789
+ const end = m.points[m.points.length - 1];
790
+ const back = yield* track(robot, [[x + d * Math.cos(yaw), y + d * Math.sin(yaw), yaw], [end[0], end[1], yaw]], -m.dir, { fp, watch, speed: 0.06 });
791
+ if (!back.ok) return back;
792
+ }
793
+ }
794
+ return { ok: true, message: "arrived" };
795
+ } finally {
796
+ robot.stopBase();
797
+ }
798
+ }
799
+
800
+ const LOOKAHEAD = 0.25; // s
801
+ const GUARD = 0.004; // m: closest the robot may come to furniture by its own motion
802
+
803
+ /** The chassis pose after driving at (v, w) for `t` seconds from `pose`, turning about the axle. */
804
+ function ahead(pose, v, w, t, axle) {
805
+ const [x, y, yaw] = pose;
806
+ const [ax, ay, th] = moveEnd(x + axle * Math.cos(yaw), y + axle * Math.sin(yaw), yaw, v * t, w * t);
807
+ return chassisOf(ax, ay, th, axle);
808
+ }
809
+
810
+ /** Top speeds near furniture: [m/s, rad/s] at a clearance (m). */
811
+ function nearLimits(clear) {
812
+ return [clamp(0.06 + 2 * (clear - 0.015), 0.06, 1), clamp(0.3 + 6 * (clear - 0.015), 0.3, 0.9)];
813
+ }
814
+
815
+ /** Turn in place by `delta` radians (positive left), the way given, however far. */
816
+ export function* turnBy(robot, delta, { fp, watch, rate = 0.9 } = {}) {
817
+ const dt = robot.sim.controlDt;
818
+ const axle = fp?.fp.axle ?? 0;
819
+ let last = robot.pose()[2];
820
+ let turned = 0;
821
+ const limit = 4 + (Math.abs(delta) / 0.25) * 2;
822
+ for (let t = 0; t < limit; t += dt) {
823
+ const pose = robot.pose();
824
+ turned += wrap(pose[2] - last);
825
+ last = pose[2];
826
+ const err = delta - turned;
827
+ const [, w] = robot.baseVelocity();
828
+ if (Math.abs(err) < 0.015 && Math.abs(w) < 0.12) {
829
+ robot.stopBase();
830
+ return { ok: true };
831
+ }
832
+ const touch = watch?.check();
833
+ if (touch) return { ok: false, touched: touch, message: `the ${touch.robot} touched the ${touch.other} while turning` };
834
+ let top = rate;
835
+ if (fp) top = Math.min(top, nearLimits(fp.clearance(...pose, 0.2))[1]);
836
+ const wCmd = Math.sign(err) * Math.min(top, Math.sqrt(2 * 1.2 * Math.abs(err)) + 0.04);
837
+ if (fp && !fp.free(...ahead(pose, 0, wCmd, Math.min(LOOKAHEAD, Math.abs(err / wCmd)), axle), GUARD)) {
838
+ robot.stopBase();
839
+ return { ok: false, blocked: true, message: "stopped turning: furniture in the way" };
840
+ }
841
+ robot.setBaseVelocity(0, wCmd);
842
+ yield;
843
+ }
844
+ return { ok: false, message: "the turn took too long" };
845
+ }
846
+
847
+ /** Follow axle points [[x, y, heading], ...] forward (dir 1) or backward (dir -1). */
848
+ export function* track(robot, points, dir, { fp, watch, speed = 0.25 }) {
849
+ const dt = robot.sim.controlDt;
850
+ const axle = fp?.fp.axle ?? 0;
851
+ // cumulative length along the points
852
+ const s = [0];
853
+ for (let i = 1; i < points.length; i++) s.push(s[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));
854
+ const total = s[s.length - 1];
855
+ if (total < 0.003) return { ok: true };
856
+ const end = points[points.length - 1];
857
+ const endDir = [Math.cos(end[2]), Math.sin(end[2])];
858
+ const pointAt = (u) => {
859
+ if (u >= total) return [end[0] + (u - total) * endDir[0] * dir, end[1] + (u - total) * endDir[1] * dir];
860
+ let i = 1;
861
+ while (i < s.length - 1 && s[i] < u) i++;
862
+ const t = (u - s[i - 1]) / Math.max(1e-9, s[i] - s[i - 1]);
863
+ return [points[i - 1][0] + t * (points[i][0] - points[i - 1][0]), points[i - 1][1] + t * (points[i][1] - points[i - 1][1])];
864
+ };
865
+ let at = 0; // index of the segment last matched
866
+ let stalled = 0;
867
+ const limit = 6 + (total / 0.05) * 2;
868
+ for (let t = 0; t < limit; t += dt) {
869
+ const pose = robot.pose();
870
+ const [cx, cy, yaw] = pose;
871
+ const ax = cx + axle * Math.cos(yaw);
872
+ const ay = cy + axle * Math.sin(yaw);
873
+ // where along the path the axle is: the nearest point on the next few segments
874
+ let bestD = Infinity;
875
+ let bestU = 0;
876
+ let bestI = at;
877
+ for (let i = Math.max(1, at); i < Math.min(s.length, at + 12); i++) {
878
+ const [x0, y0] = points[i - 1];
879
+ const [x1, y1] = points[i];
880
+ const L = s[i] - s[i - 1];
881
+ const u = L > 1e-9 ? clamp(((ax - x0) * (x1 - x0) + (ay - y0) * (y1 - y0)) / (L * L), 0, 1) : 0;
882
+ const d = Math.hypot(ax - (x0 + u * (x1 - x0)), ay - (y0 + u * (y1 - y0)));
883
+ if (d < bestD) {
884
+ bestD = d;
885
+ bestU = s[i - 1] + u * L;
886
+ bestI = i;
887
+ }
888
+ }
889
+ at = bestI;
890
+ // past the end: measure along the last heading
891
+ const along = (ax - end[0]) * endDir[0] + (ay - end[1]) * endDir[1];
892
+ const remaining = Math.max(total - bestU, 0) - (bestU >= total - 1e-6 ? along * dir : 0);
893
+ const [v] = robot.baseVelocity();
894
+ if (remaining < 0.006 && Math.abs(v) < 0.03) return { ok: true, overshoot: Math.max(0, -remaining) };
895
+ if (remaining < -0.03) return { ok: true, overshoot: -remaining };
896
+ if (bestD > 0.09) return { ok: false, strayed: bestD, message: `left the path by ${(bestD * 100).toFixed(0)} cm` };
897
+ const touch = watch?.check();
898
+ if (touch) return { ok: false, touched: touch, message: `the ${touch.robot} touched the ${touch.other}` };
899
+ // pure pursuit on the axle point, in the frame of the direction of travel
900
+ const look = clamp(0.06 + 0.4 * Math.abs(v), 0.08, 0.16);
901
+ const [tx, ty] = pointAt(bestU + look);
902
+ const heading = dir > 0 ? yaw : yaw + Math.PI;
903
+ const dx = tx - ax;
904
+ const dy = ty - ay;
905
+ const lx = Math.cos(heading) * dx + Math.sin(heading) * dy;
906
+ const ly = -Math.sin(heading) * dx + Math.cos(heading) * dy;
907
+ const curvature = (2 * ly) / Math.max(1e-4, lx * lx + ly * ly);
908
+ let [vTop, wTop] = [speed, 0.8];
909
+ if (fp) {
910
+ const [vn, wn] = nearLimits(fp.clearance(...pose, 0.2));
911
+ vTop = Math.min(vTop, vn);
912
+ wTop = Math.min(wTop, wn);
913
+ }
914
+ // braking early: the base's speed loop lags a little behind what it is told
915
+ let vCmd = Math.min(vTop, Math.sqrt(2 * 0.2 * Math.max(remaining - 0.004, 0)) + 0.012);
916
+ if (remaining < 0.004) vCmd = 0;
917
+ if (lx < 0.02) vCmd = 0.02; // target beside or behind: mostly turn
918
+ vCmd = Math.min(vCmd, wTop / Math.max(Math.abs(curvature), 1e-3));
919
+ const w = clamp(vCmd * curvature, -wTop, wTop);
920
+ if (fp && !fp.free(...ahead(pose, dir * vCmd, w, Math.min(LOOKAHEAD, (remaining + 0.01) / Math.max(vCmd, 1e-3)), axle), GUARD)) {
921
+ robot.stopBase();
922
+ return { ok: false, blocked: true, message: "stopped: furniture in the way" };
923
+ }
924
+ robot.setBaseVelocity(dir * vCmd, w);
925
+ stalled = vCmd > 0.04 && Math.abs(v) < 0.01 && t > 1.0 ? stalled + dt : 0;
926
+ if (stalled > 1.0) return { ok: false, blocked: true, message: "the base is stuck" };
927
+ yield;
928
+ }
929
+ return { ok: false, message: "the drive took too long" };
930
+ }
src/robots/skills.js CHANGED
@@ -4,6 +4,7 @@
4
  //
5
  // Positions are in the robot frame (x forward, y left, z up from the chassis origin) unless noted.
6
  import { CONTROL, inverseKinematics2Link } from "./xlerobot.js";
 
7
 
8
  const DOWN = Math.PI / 2; // gripper pitch pointing straight down
9
  // Gripper geometry (measured from the model's finger collision meshes) and grasp parameters.
@@ -16,6 +17,7 @@ export const GRASP = {
16
  sideGraspHeight: 0.09, // taller objects are grasped from the side
17
  clearance: 0.006, // finger tips above the surface the object stands on
18
  margin: 0.004, // gap between the fixed finger and the object before closing
 
19
  liftHeight: 0.1,
20
  maxWidth: 0.065,
21
  };
@@ -163,6 +165,53 @@ export function* drive(robot, distance, { speed = 0.22, accel = 0.35, timeout }
163
  }
164
  }
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  /** Turn in place by `angle` radians (positive turns left). */
167
  export function* turn(robot, angle, { rate = 0.9, timeout } = {}) {
168
  const [, , yaw0] = robot.pose();
@@ -193,14 +242,28 @@ export function* face(robot, point) {
193
  return yield* turn(robot, wrap(Math.atan2(point[1] - y, point[0] - x) - yaw));
194
  }
195
 
196
- /** Drive to a world point [x, y]: turn toward it, drive, stopping `stopShort` metres before it. */
197
- export function* goTo(robot, point, { stopShort = 0 } = {}) {
198
- const faced = yield* face(robot, point);
199
- if (!faced.ok) return faced;
200
- const [x, y] = robot.pose();
201
- const distance = Math.hypot(point[0] - x, point[1] - y) - stopShort;
202
- if (Math.abs(distance) < 0.01) return { ok: true, message: "already there" };
203
- return yield* drive(robot, distance);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  }
205
 
206
  /** Pan and tilt the head toward a world point. */
@@ -268,61 +331,89 @@ export function* homeArm(robot, side, { duration = 1.2 } = {}) {
268
  // ---------------------------------------------------------------------------------------------
269
  // Objects
270
 
271
- /** Geometry of a free body: centre (world), top height (world), horizontal yaw of its box, size. */
 
 
 
 
 
 
 
 
272
  export function objectInfo(sim, bodyId) {
273
  const { model, data } = sim;
274
  let top = -Infinity;
275
  let bottom = Infinity;
276
- let yaw = 0;
277
- let width = 0;
278
- let isBox = false;
279
- let aspect = 1;
280
  for (let g = model.body_geomadr[bodyId]; g < model.body_geomadr[bodyId] + model.body_geomnum[bodyId]; g++) {
281
  if (!model.geom_contype[g] && !model.geom_conaffinity[g]) continue;
282
- const type = model.geom_type[g];
283
- const size = model.geom_size.subarray(3 * g, 3 * g + 3);
284
- const R = data.geom_xmat.subarray(9 * g, 9 * g + 9);
285
- const z = data.geom_xpos[3 * g + 2];
286
- let half = 0;
287
- if (type === 2) half = size[0]; // sphere
288
- else if (type === 6) half = Math.abs(R[6]) * size[0] + Math.abs(R[7]) * size[1] + Math.abs(R[8]) * size[2]; // box
289
- else if (type === 5 || type === 3) {
290
- // cylinder or capsule along local z
291
- const c = Math.abs(R[8]);
292
- half = c * size[1] + Math.sqrt(Math.max(0, 1 - c * c)) * size[0] + (type === 3 ? size[0] * c : 0);
293
- } else half = model.geom_rbound[g];
294
- top = Math.max(top, z + half);
295
- bottom = Math.min(bottom, z - half);
296
- if (type === 6) {
297
- // the box's horizontal axis with the smaller extent: the jaws close across it
298
- const ax = [R[0], R[3]];
299
- const ay = [R[1], R[4]];
300
- const ex = Math.hypot(...ax) * size[0];
301
- const ey = Math.hypot(...ay) * size[1];
302
- const narrow = ex < ey ? ax : ay;
303
- yaw = Math.atan2(narrow[1], narrow[0]);
304
- width = 2 * Math.min(size[0], size[1]);
305
- aspect = Math.min(ex, ey) / Math.max(ex, ey);
306
- isBox = true;
307
- } else if (type === 2 || type === 5 || type === 3) {
308
- width = 2 * size[0];
309
  }
 
310
  }
311
- const center = sim.bodyPos(bodyId);
312
- if (model.body_geomnum[bodyId] > 1) {
313
- // Several geoms (a bowl, a mug): the narrower side of their joint footprint, as an approximation.
314
- let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
315
- for (let g = model.body_geomadr[bodyId]; g < model.body_geomadr[bodyId] + model.body_geomnum[bodyId]; g++) {
316
- const r = model.geom_rbound[g];
317
- const gx = data.geom_xpos[3 * g];
318
- const gy = data.geom_xpos[3 * g + 1];
319
- x0 = Math.min(x0, gx - r); x1 = Math.max(x1, gx + r);
320
- y0 = Math.min(y0, gy - r); y1 = Math.max(y1, gy + r);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  }
322
- width = Math.max(width, Math.min(x1 - x0, y1 - y0));
323
- isBox = false;
324
  }
325
- return { center, top, bottom, height: top - bottom, yaw, width, isBox, aspect };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  }
327
 
328
  /** Wrap an angle to (-pi/2, pi/2]: jaws closing along a line do not care about its direction. */
@@ -340,7 +431,7 @@ function wrapHalf(a) {
340
  * its finger tips stay above `support` (the height the object stands on). Returns null if no pitch
341
  * between vertical and 43 degrees works.
342
  */
343
- export function graspPose(robot, side, point, { width, narrowYaw = null, support, top = -Infinity, mode = "top" }) {
344
  const yaws = narrowYaw === null || mode === "side" ? [null] : [].concat(narrowYaw);
345
  const arm = robot.arms[side];
346
  const pitches = mode === "side" ? [0, 0.15, 0.3] : Array.from({ length: 17 }, (_, k) => Math.PI / 2 - 0.05 * k);
@@ -350,19 +441,40 @@ export function graspPose(robot, side, point, { width, narrowYaw = null, support
350
  let psi = Math.atan2(point[1] - arm.axis[1], point[0] - arm.axis[0]);
351
  let roll;
352
  let pad;
 
353
  for (let it = 0; it < 6; it++) {
354
- // a square-ish box can be grasped across either side: take the smaller wrist roll
 
355
  let delta = 0;
356
- if (yaws[0] !== null) delta = yaws.map((y) => wrapHalf(psi + Math.PI / 2 - y)).sort((a, b) => Math.abs(a) - Math.abs(b))[0];
 
 
 
 
 
 
 
 
 
 
 
 
357
  // stay inside the wrist roll range (-2.74..2.84): the same closing line, fingers swapped
358
  if (arm.rollHome + delta > 2.75) delta -= Math.PI;
359
  if (arm.rollHome + delta < -2.65) delta += Math.PI;
360
  roll = arm.rollHome + delta;
361
- const jawAngle = psi + Math.PI / 2 - delta; // from the moving finger to the fixed one
362
- const shift = width / 2 + GRASP.margin - GRASP.fingerInner;
 
 
 
 
 
 
363
  pad = [point[0] + shift * Math.cos(jawAngle), point[1] + shift * Math.sin(jawAngle), point[2]];
364
  psi = Math.atan2(pad[1] - arm.axis[1], pad[0] - arm.axis[0]);
365
  }
 
366
  const g = [Math.cos(pitch) * Math.cos(psi), Math.cos(pitch) * Math.sin(psi), -Math.sin(pitch)];
367
  const wrist = pad.map((v, k) => v - GRASP.padBelow * g[k]);
368
  if (mode === "top") {
@@ -378,40 +490,73 @@ export function graspPose(robot, side, point, { width, narrowYaw = null, support
378
  const [j2, j3] = inverseKinematics2Link(t.x, yIk);
379
  const wristPitch = j2 - j3 + pitch;
380
  if (Math.abs(wristPitch) > 1.64 || Math.abs(t.rotation) > 2.1) continue;
 
 
 
 
 
 
381
  // a side grasp needs the fingers (2.4 cm thick) clear of the support
382
  if (mode === "side" && wrist[2] - Math.sin(pitch) * GRASP.tipBelow - GRASP.fingerHalfThickness < support + GRASP.clearance) continue;
383
- return { wrist, pitch, roll, mode, along: g, target: { ...t, roll } };
384
  }
385
  return null;
386
  }
387
 
388
- /** Where and with which arm an object can be grasped, or why not. */
389
- export function graspPlan(robot, bodyId, side) {
390
- const info = objectInfo(robot.sim, bodyId);
391
- const center = robot.toRobot(info.center);
392
- const z0 = robot.toRobot([0, 0, 0])[2];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  // The pads close at the object's middle; graspPose raises them if the finger tips would touch the support.
394
  const point = [center[0], center[1], (info.top + info.bottom) / 2 + z0];
395
  const support = info.bottom + z0;
 
396
  let narrowYaw = null;
397
- if (info.isBox) {
398
- const yaw = wrap(info.yaw - robot.pose()[2]);
399
  narrowYaw = info.aspect > 0.8 ? [yaw, yaw + Math.PI / 2] : yaw;
400
  }
 
401
  if (center[0] < 0.1) return { info, center, reason: "behind or beside the robot" };
402
  if (info.width > GRASP.maxWidth) return { info, center, reason: `too wide for the gripper (${(info.width * 100).toFixed(0)} cm)` };
403
  const sides = side ? [side] : ["left", "right"].sort((a, b) => Math.abs(center[1] - robot.arms[a].axis[1]) - Math.abs(center[1] - robot.arms[b].axis[1]));
404
  // Tall objects are taken from the side at their middle; others from above.
405
  const modes = info.height > GRASP.sideGraspHeight ? ["side", "top"] : ["top"];
 
406
  for (const mode of modes) {
407
  for (const s of sides) {
408
- const pose = graspPose(robot, s, point, { width: info.width, narrowYaw, support, top: info.top + z0, mode });
409
  if (pose) return { info, center, point, side: s, pose, reason: null };
 
410
  }
411
  }
412
  const arm = robot.arms[sides[0]];
413
  const dist = Math.hypot(center[0] - arm.axis[0], center[1] - arm.axis[1]);
414
- return { info, center, reason: dist > 0.2 ? `out of reach (${dist.toFixed(2)} m from the ${sides[0]} shoulder)` : `no grasp pose for the ${sides[0]} arm` };
 
415
  }
416
 
417
  function fingerGeoms(robot, side) {
@@ -430,13 +575,28 @@ function fingerGeoms(robot, side) {
430
  return robot._fingers[side];
431
  }
432
 
433
- /** True when the object is between an arm's closed fingers. */
 
 
 
434
  export function holding(robot, side, bodyId) {
435
- const { data } = robot.sim;
 
436
  const [a, b] = fingerGeoms(robot, side);
437
  const mid = [0, 1, 2].map((k) => (data.geom_xpos[3 * a + k] + data.geom_xpos[3 * b + k]) / 2);
438
  const p = robot.sim.bodyPos(bodyId);
439
- return Math.hypot(p[0] - mid[0], p[1] - mid[1], p[2] - mid[2]) < 0.06 && robot.gripperOpening(side) < 0.6;
 
 
 
 
 
 
 
 
 
 
 
440
  }
441
 
442
  /**
@@ -554,13 +714,14 @@ export function heldOffset(robot, side, point) {
554
  * Put the object held by `side` down with its centre over a robot-frame point [x, y] and its bottom
555
  * at height `z` (the surface), then open and lift away. The gripper keeps its commanded pitch.
556
  */
557
- export function* place(robot, side, point, bodyId) {
558
  const sim = robot.sim;
559
  if (bodyId !== undefined) {
560
  // A held object no longer slips into place (the physics holds grasps firmly), so line the arm up.
561
  const world = robot.toWorld(point);
562
- yield* alignToPlace(robot, side, world);
563
- point = robot.toRobot(world);
 
564
  }
565
  const { pitch } = robot.arms[side].target;
566
  const z0 = robot.toRobot([0, 0, 0])[2];
@@ -588,10 +749,20 @@ export function* place(robot, side, point, bodyId) {
588
  yield* reach(robot, side, at(0.02), { pitch, duration: 0.6, settle: 0.15 });
589
  yield* reach(robot, side, at(0.008), { pitch, duration: 0.4, settle: 0.15 });
590
  yield* reach(robot, side, at(0.002), { pitch, duration: 0.3, settle: 0.15 });
 
 
 
591
  // Open part way: wide open, a jaw can catch the wall of the bowl or box it put something in, and lift it.
592
  yield* gripper(robot, side, true, { duration: 0.4, settle: 0.3, opening: 0.45 });
 
 
593
  const away = at(0.003);
594
- yield* reach(robot, side, [away[0], away[1], away[2] + 0.07], { pitch, duration: 0.7, settle: 0 });
 
 
 
 
 
595
  yield* homeArm(robot, side);
596
  if (bodyId === undefined) return { ok: true, message: `opened the ${side} gripper at the spot` };
597
  const now = robot.toRobot(sim.bodyPos(bodyId));
@@ -600,70 +771,265 @@ export function* place(robot, side, point, bodyId) {
600
  }
601
 
602
  /**
603
- * Before putting a held object down at a world point: unless the point is already about 0.27 m ahead and
604
- * in line with the arm, back away from the furniture (the base cannot turn against it), drive to where
605
- * it is, as approach does for picking, and creep forward until it is in reach or furniture stops the base.
606
  */
607
- function* alignToPlace(robot, side, world) {
608
- const ahead = 0.27;
609
- const lateral = robot.arms[side].axis[1];
610
- const rel = robot.toRobot(world);
611
- if (Math.abs(rel[1] - lateral) < 0.05 && rel[0] > 0.2 && rel[0] < 0.32) return;
612
- yield* drive(robot, -0.2, { speed: 0.15 });
613
- const [x, y] = robot.pose();
614
- const dist = Math.hypot(world[0] - x, world[1] - y);
615
- const bearing = Math.atan2(world[1] - y, world[0] - x);
616
- const heading = bearing - Math.asin(clamp(lateral / Math.max(dist, Math.abs(lateral) + 1e-3), -1, 1));
617
- const spot = [world[0] - ahead * Math.cos(heading) + lateral * Math.sin(heading), world[1] - ahead * Math.sin(heading) - lateral * Math.cos(heading)];
618
- yield* goTo(robot, spot);
619
- yield* turn(robot, wrap(heading - robot.pose()[2]));
620
- const now = robot.toRobot(world);
621
- if (now[0] > 0.3 && now[0] < 0.8) yield* drive(robot, Math.min(0.4, now[0] - ahead), { speed: 0.1 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  }
623
 
624
  /** Whether an object sits where the arms grasp it well: graspable, and no farther than 0.3 m ahead. */
625
- export function comfortable(robot, bodyId, side) {
626
- const plan = graspPlan(robot, bodyId, side);
627
  const ahead = plan.center ? plan.center[0] : Infinity;
628
  return { ok: !plan.reason && ahead <= 0.305, plan, ahead };
629
  }
630
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
  /**
632
- * Drive so an object comes within comfortable reach of one arm: aim at the spot from which it is about
633
- * 0.27 m ahead and in line with that arm, drive there (stopping if furniture blocks the way), turn
634
- * back toward it, then creep forward while it is still far. Repeats to correct.
635
  */
636
- export function* approach(robot, bodyId, { side } = {}) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
637
  const sim = robot.sim;
638
- let check = comfortable(robot, bodyId, side);
639
- if (check.ok) return { ok: true, message: `already in reach of the ${check.plan.side} arm`, side: check.plan.side };
640
  for (let attempt = 0; attempt < 3; attempt++) {
641
- const o = sim.bodyPos(bodyId);
642
- const [x, y] = robot.pose();
643
- const rel = robot.toRobot(o);
644
- const s = side ?? (rel[1] >= 0 ? "left" : "right");
645
- const lateral = robot.arms[s].axis[1];
646
- const ahead = 0.27;
647
- // Heading from which the object sits `ahead` forward and `lateral` to the side of the chassis.
648
- const dist = Math.hypot(o[0] - x, o[1] - y);
649
- const bearing = Math.atan2(o[1] - y, o[0] - x);
650
- const heading = bearing - Math.asin(Math.max(-1, Math.min(1, lateral / Math.max(dist, Math.abs(lateral) + 1e-3))));
651
- const spot = [o[0] - ahead * Math.cos(heading) + lateral * Math.sin(heading), o[1] - ahead * Math.sin(heading) - lateral * Math.cos(heading)];
652
- if (Math.hypot(spot[0] - x, spot[1] - y) > 0.03) {
653
- const moved = yield* goTo(robot, spot);
654
- if (!moved.ok && !moved.blocked) return { ok: false, message: `could not drive there: ${moved.message}` };
655
  }
656
- yield* turn(robot, wrap(heading - robot.pose()[2]));
657
- check = comfortable(robot, bodyId, side);
658
- if (check.ok) break;
659
- // Still far (furniture stopped the base early): creep forward until blocked or close enough.
660
- if (check.ahead > 0.29 && check.ahead < 0.8) {
661
- const crept = yield* drive(robot, Math.min(0.3, check.ahead - 0.26), { speed: 0.12 });
662
- check = comfortable(robot, bodyId, side);
663
- if (check.ok || crept.blocked) break;
664
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  }
666
- if (check.ok) return { ok: true, message: `in reach of the ${check.plan.side} arm`, side: check.plan.side };
667
- if (!check.plan.reason) return { ok: true, message: `in reach of the ${check.plan.side} arm, at the edge of its workspace`, side: check.plan.side };
668
- return { ok: false, message: `got as close as possible, but ${check.plan.reason}` };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
  }
 
4
  //
5
  // Positions are in the robot frame (x forward, y left, z up from the chassis origin) unless noted.
6
  import { CONTROL, inverseKinematics2Link } from "./xlerobot.js";
7
+ import { ContactWatch, DiscField, Footprint, ObstacleMap, chassisOf, followPath, geomShape, planPath, robotFootprint, track, turnBy } from "./nav.js";
8
 
9
  const DOWN = Math.PI / 2; // gripper pitch pointing straight down
10
  // Gripper geometry (measured from the model's finger collision meshes) and grasp parameters.
 
17
  sideGraspHeight: 0.09, // taller objects are grasped from the side
18
  clearance: 0.006, // finger tips above the surface the object stands on
19
  margin: 0.004, // gap between the fixed finger and the object before closing
20
+ tiltGap: 0.06, // more gap per unit of forward tilt for a fixed finger on the near side
21
  liftHeight: 0.1,
22
  maxWidth: 0.065,
23
  };
 
165
  }
166
  }
167
 
168
+ /** The robot's outline against the furniture and objects now; what the grippers hold goes with it. */
169
+ function footprintNow(robot) {
170
+ const held = heldBodies(robot);
171
+ return new Footprint(new ObstacleMap(robot.sim, robot.root, { objects: true, except: held }), robotFootprint(robot, held));
172
+ }
173
+
174
+ /** What to call a map shape in a message: its body's name, without underscores. */
175
+ const named = (shape) => (shape?.body ?? "furniture").replace(/_/g, " ");
176
+
177
+ /**
178
+ * How far the base can drive straight, up to `distance` metres (negative backward), keeping `margin`
179
+ * from furniture and objects (or, already closer, not getting closer); and what stops it, if anything.
180
+ */
181
+ export function clearDrive(robot, distance, margin = 0.015) {
182
+ const fp = footprintNow(robot);
183
+ const [x, y, yaw] = robot.pose();
184
+ const m = Math.min(margin, Math.max(0, fp.clearance(x, y, yaw, margin) - 0.003));
185
+ const n = Math.ceil(Math.abs(distance) / 0.01);
186
+ let ok = 0;
187
+ for (let k = 1; k <= n; k++) {
188
+ const d = (distance * k) / n;
189
+ const hit = fp.hit(x + d * Math.cos(yaw), y + d * Math.sin(yaw), yaw, m);
190
+ if (hit) return { distance: ok, blockedBy: named(hit) };
191
+ ok = d;
192
+ }
193
+ return { distance, blockedBy: null };
194
+ }
195
+
196
+ /** How far the base can turn in place, up to `angle` radians, as clearDrive; and what stops it. */
197
+ export function clearTurn(robot, angle, margin = 0.015) {
198
+ const fp = footprintNow(robot);
199
+ const [x, y, yaw] = robot.pose();
200
+ const d = fp.fp.axle;
201
+ const ax = x + d * Math.cos(yaw);
202
+ const ay = y + d * Math.sin(yaw);
203
+ const m = Math.min(margin, Math.max(0, fp.clearance(x, y, yaw, margin) - 0.003));
204
+ const n = Math.ceil(Math.abs(angle) / 0.035);
205
+ let ok = 0;
206
+ for (let k = 1; k <= n; k++) {
207
+ const a = (angle * k) / n;
208
+ const hit = fp.hit(...chassisOf(ax, ay, yaw + a, d), m);
209
+ if (hit) return { angle: ok, blockedBy: named(hit) };
210
+ ok = a;
211
+ }
212
+ return { angle, blockedBy: null };
213
+ }
214
+
215
  /** Turn in place by `angle` radians (positive turns left). */
216
  export function* turn(robot, angle, { rate = 0.9, timeout } = {}) {
217
  const [, , yaw0] = robot.pose();
 
242
  return yield* turn(robot, wrap(Math.atan2(point[1] - y, point[0] - x) - yaw));
243
  }
244
 
245
+ /**
246
+ * Drive the chassis to a world point [x, y] around the furniture, ending facing `heading` (radians) if
247
+ * given, otherwise the clear heading nearest the way there.
248
+ */
249
+ export function* goTo(robot, point, { heading } = {}) {
250
+ yield* stowArms(robot);
251
+ const held = heldBodies(robot);
252
+ const fp = new Footprint(new ObstacleMap(robot.sim, robot.root, { objects: true, except: held }), robotFootprint(robot, held));
253
+ const start = robot.pose();
254
+ const bearing = Math.atan2(point[1] - start[1], point[0] - start[0]);
255
+ const headings = heading !== undefined ? [heading] : Array.from({ length: 24 }, (_, k) => bearing + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * (Math.PI / 12));
256
+ let tried = 0;
257
+ for (const h of headings) {
258
+ if (!fp.free(point[0], point[1], h, 0.02)) continue;
259
+ const plan = yield* planPath(fp, start, [point[0], point[1], h], { margin: 0.025 });
260
+ if (plan.ok) {
261
+ const run = yield* followPath(robot, plan.moves, { fp, watch: new ContactWatch(robot.sim, robot.root) });
262
+ return run.ok ? { ok: true, message: `drove ${plan.length.toFixed(1)} m` } : run;
263
+ }
264
+ if (++tried >= 4) break;
265
+ }
266
+ return { ok: false, message: "found no clear way to that point" };
267
  }
268
 
269
  /** Pan and tilt the head toward a world point. */
 
331
  // ---------------------------------------------------------------------------------------------
332
  // Objects
333
 
334
+ /**
335
+ * Geometry of a free body, from the footprints of its geoms on the table: centre (world; the largest
336
+ * geom's, so a mug's body and not its handle), top and bottom heights (world), and how wide it is
337
+ * across each horizontal direction. The jaws close along `narrowYaw` (world yaw, null for round
338
+ * objects), where it is `width` wide; `length` is its extent the other way. That follows how it lies:
339
+ * a box on its side, a bottle or a banana lying down, a mug's handle (the jaws close across the mug,
340
+ * clear of it). `widthAlong(yaw)` gives the width along any world yaw.
341
+ * `isBox` and `yaw` (the narrow axis of a single box, 0 otherwise) are what the pick policy observes.
342
+ */
343
  export function objectInfo(sim, bodyId) {
344
  const { model, data } = sim;
345
  let top = -Infinity;
346
  let bottom = Infinity;
347
+ const shapes = [];
348
+ let main = -1;
349
+ let mainSize = -1;
350
+ let boxes = 0;
351
  for (let g = model.body_geomadr[bodyId]; g < model.body_geomadr[bodyId] + model.body_geomnum[bodyId]; g++) {
352
  if (!model.geom_contype[g] && !model.geom_conaffinity[g]) continue;
353
+ const s = geomShape(model, data, g);
354
+ shapes.push(s);
355
+ top = Math.max(top, s.z1);
356
+ bottom = Math.min(bottom, s.z0);
357
+ const size = (s.round ? 2 * s.r * 2 * s.r : 4 * s.hx * s.hy) * (s.z1 - s.z0);
358
+ if (size > mainSize) {
359
+ mainSize = size;
360
+ main = g;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  }
362
+ if (model.geom_type[g] === 6) boxes++;
363
  }
364
+ const widthAlong = (yaw) => {
365
+ const nx = Math.cos(yaw);
366
+ const ny = Math.sin(yaw);
367
+ let lo = Infinity;
368
+ let hi = -Infinity;
369
+ for (const s of shapes) {
370
+ const c = s.x * nx + s.y * ny;
371
+ const e = s.round ? s.r : s.hx * Math.abs(s.ux * nx + s.uy * ny) + s.hy * Math.abs(-s.uy * nx + s.ux * ny);
372
+ lo = Math.min(lo, c - e);
373
+ hi = Math.max(hi, c + e);
374
+ }
375
+ return hi - lo;
376
+ };
377
+ // The narrowest direction. Where a range of directions is about as narrow (a mug, all the way round
378
+ // but for its handle), the middle of that range: the jaws close across the mug, square to the handle.
379
+ const n = 90; // every 2 degrees over half a turn (a closing line has no direction)
380
+ const widths = Array.from({ length: n }, (_, k) => widthAlong((k * Math.PI) / n));
381
+ const width0 = Math.min(...widths);
382
+ const widest = Math.max(...widths);
383
+ // the run of directions around the narrowest one that are within 2 mm of it (a box has two runs, a
384
+ // face apart: only the one around the narrowest counts)
385
+ const k0 = widths.indexOf(width0);
386
+ let lo = 0;
387
+ let hi = 0;
388
+ while (lo > -n / 2 && widths[(k0 + lo - 1 + n) % n] <= width0 + 0.002) lo--;
389
+ while (hi < n / 2 && widths[(k0 + hi + 1) % n] <= width0 + 0.002) hi++;
390
+ let narrowYaw = ((k0 + (lo + hi) / 2) * Math.PI) / n;
391
+ let width = widthAlong(narrowYaw);
392
+ for (const d of [-0.02, -0.01, 0.01, 0.02]) {
393
+ const w = widthAlong(narrowYaw + d);
394
+ if (w < width - 0.0005) {
395
+ width = w;
396
+ narrowYaw += d;
397
  }
 
 
398
  }
399
+ const round = widest - width0 < 0.004;
400
+ const length = widthAlong(narrowYaw + Math.PI / 2);
401
+ const center = shapes.length > 1 && main >= 0 ? Array.from(data.geom_xpos.subarray(3 * main, 3 * main + 3)) : sim.bodyPos(bodyId);
402
+ const isBox = shapes.length === 1 && boxes === 1;
403
+ return {
404
+ center,
405
+ top,
406
+ bottom,
407
+ height: top - bottom,
408
+ width,
409
+ length,
410
+ narrowYaw: round ? null : wrap(narrowYaw),
411
+ round,
412
+ widthAlong,
413
+ yaw: isBox ? wrap(narrowYaw) : 0,
414
+ isBox,
415
+ aspect: width / Math.max(length, 1e-6),
416
+ };
417
  }
418
 
419
  /** Wrap an angle to (-pi/2, pi/2]: jaws closing along a line do not care about its direction. */
 
431
  * its finger tips stay above `support` (the height the object stands on). Returns null if no pitch
432
  * between vertical and 43 degrees works.
433
  */
434
+ export function graspPose(robot, side, point, { width, widthAlong = null, narrowYaw = null, support, top = -Infinity, mode = "top" }) {
435
  const yaws = narrowYaw === null || mode === "side" ? [null] : [].concat(narrowYaw);
436
  const arm = robot.arms[side];
437
  const pitches = mode === "side" ? [0, 0.15, 0.3] : Array.from({ length: 17 }, (_, k) => Math.PI / 2 - 0.05 * k);
 
441
  let psi = Math.atan2(point[1] - arm.axis[1], point[0] - arm.axis[0]);
442
  let roll;
443
  let pad;
444
+ let across = width;
445
  for (let it = 0; it < 6; it++) {
446
+ // a square-ish box can be grasped across either side: take the smaller wrist roll of the sides
447
+ // narrow enough (a mug is not grasped across its handle)
448
  let delta = 0;
449
+ if (yaws[0] !== null) {
450
+ const options = yaws.map((y) => wrapHalf(psi + Math.PI / 2 - y)).filter((d) => !widthAlong || widthAlong(psi + Math.PI / 2 - d) <= GRASP.maxWidth);
451
+ if (!options.length) {
452
+ across = Infinity;
453
+ break;
454
+ }
455
+ delta = options.sort((a, b) => Math.abs(a) - Math.abs(b))[0];
456
+ }
457
+ // `delta` turns the closing line in the horizontal plane. The wrist rolls about the gripper's own
458
+ // axis: pointing straight down that is the same angle, but with the gripper tilted the roll swings
459
+ // the line partly up and down, so it has to roll further for the same turn on the table.
460
+ const horizontal = delta;
461
+ delta = Math.atan2(Math.sin(horizontal), Math.cos(horizontal) * Math.max(Math.sin(pitch), 0.2));
462
  // stay inside the wrist roll range (-2.74..2.84): the same closing line, fingers swapped
463
  if (arm.rollHome + delta > 2.75) delta -= Math.PI;
464
  if (arm.rollHome + delta < -2.65) delta += Math.PI;
465
  roll = arm.rollHome + delta;
466
+ const jawAngle = psi + Math.PI / 2 - horizontal; // from the moving finger to the fixed one
467
+ // How wide the object is where the jaws close: from the side the closing line is fixed by the
468
+ // arm's direction, so a box has to be faced the right way.
469
+ if (widthAlong) across = widthAlong(jawAngle);
470
+ // A gripper tilted forward has its finger tips ahead of the pads: a fixed finger on the near side
471
+ // of the object (toward the robot) leans into it as it comes down, so it keeps further off.
472
+ const lean = mode === "top" ? GRASP.tiltGap * Math.cos(pitch) * Math.max(0, -Math.cos(jawAngle - psi)) : 0;
473
+ const shift = across / 2 + GRASP.margin + lean - GRASP.fingerInner;
474
  pad = [point[0] + shift * Math.cos(jawAngle), point[1] + shift * Math.sin(jawAngle), point[2]];
475
  psi = Math.atan2(pad[1] - arm.axis[1], pad[0] - arm.axis[0]);
476
  }
477
+ if (across > GRASP.maxWidth) continue;
478
  const g = [Math.cos(pitch) * Math.cos(psi), Math.cos(pitch) * Math.sin(psi), -Math.sin(pitch)];
479
  const wrist = pad.map((v, k) => v - GRASP.padBelow * g[k]);
480
  if (mode === "top") {
 
490
  const [j2, j3] = inverseKinematics2Link(t.x, yIk);
491
  const wristPitch = j2 - j3 + pitch;
492
  if (Math.abs(wristPitch) > 1.64 || Math.abs(t.rotation) > 2.1) continue;
493
+ // The pick comes down onto this pose from a few centimetres above: the wrist has to hold the pitch
494
+ // there too, or the gripper swings as it comes down and a finger catches the object.
495
+ if (mode === "top") {
496
+ const above = robot.wristTarget(side, [wrist[0], wrist[1], wrist[2] + 0.04], pitch);
497
+ if (Math.abs(effectivePitch(above) - pitch) > 0.03) continue;
498
+ }
499
  // a side grasp needs the fingers (2.4 cm thick) clear of the support
500
  if (mode === "side" && wrist[2] - Math.sin(pitch) * GRASP.tipBelow - GRASP.fingerHalfThickness < support + GRASP.clearance) continue;
501
+ return { wrist, pitch, roll, mode, width: across, along: g, target: { ...t, roll } };
502
  }
503
  return null;
504
  }
505
 
506
+ /**
507
+ * The robot frame at the robot's pose, or at a chassis pose `at` = {x, y, yaw} it is not at (level, at
508
+ * the chassis' current height): `toRobot(world point)` and the heading.
509
+ */
510
+ function robotFrame(robot, at) {
511
+ if (!at) return { toRobot: (p) => robot.toRobot(p), yaw: robot.pose()[2] };
512
+ const z = robot.sim.bodyPos(robot.root)[2];
513
+ const c = Math.cos(at.yaw);
514
+ const s = Math.sin(at.yaw);
515
+ return {
516
+ toRobot: (p) => {
517
+ const dx = p[0] - at.x;
518
+ const dy = p[1] - at.y;
519
+ return [c * dx + s * dy, -s * dx + c * dy, p[2] - z];
520
+ },
521
+ yaw: at.yaw,
522
+ };
523
+ }
524
+
525
+ /**
526
+ * Where and with which arm an object can be grasped, or why not. With `at` ({x, y, yaw}), as if the
527
+ * robot stood there: the go-to skill uses that to choose where to stand.
528
+ */
529
+ export function graspPlan(robot, bodyId, side, { at, info = objectInfo(robot.sim, bodyId) } = {}) {
530
+ const frame = robotFrame(robot, at);
531
+ const center = frame.toRobot(info.center);
532
+ const z0 = frame.toRobot([0, 0, 0])[2];
533
  // The pads close at the object's middle; graspPose raises them if the finger tips would touch the support.
534
  const point = [center[0], center[1], (info.top + info.bottom) / 2 + z0];
535
  const support = info.bottom + z0;
536
+ // The jaws close across the object's narrow side, however it lies; a square-ish one either way.
537
  let narrowYaw = null;
538
+ if (info.narrowYaw !== null) {
539
+ const yaw = wrap(info.narrowYaw - frame.yaw);
540
  narrowYaw = info.aspect > 0.8 ? [yaw, yaw + Math.PI / 2] : yaw;
541
  }
542
+ const widthAlong = (yaw) => info.widthAlong(yaw + frame.yaw);
543
  if (center[0] < 0.1) return { info, center, reason: "behind or beside the robot" };
544
  if (info.width > GRASP.maxWidth) return { info, center, reason: `too wide for the gripper (${(info.width * 100).toFixed(0)} cm)` };
545
  const sides = side ? [side] : ["left", "right"].sort((a, b) => Math.abs(center[1] - robot.arms[a].axis[1]) - Math.abs(center[1] - robot.arms[b].axis[1]));
546
  // Tall objects are taken from the side at their middle; others from above.
547
  const modes = info.height > GRASP.sideGraspHeight ? ["side", "top"] : ["top"];
548
+ let sideTooWide = false;
549
  for (const mode of modes) {
550
  for (const s of sides) {
551
+ const pose = graspPose(robot, s, point, { width: info.width, widthAlong, narrowYaw, support, top: info.top + z0, mode });
552
  if (pose) return { info, center, point, side: s, pose, reason: null };
553
+ if (mode === "side" && widthAlong(Math.atan2(center[1] - robot.arms[s].axis[1], center[0] - robot.arms[s].axis[0]) + Math.PI / 2) > GRASP.maxWidth) sideTooWide = true;
554
  }
555
  }
556
  const arm = robot.arms[sides[0]];
557
  const dist = Math.hypot(center[0] - arm.axis[0], center[1] - arm.axis[1]);
558
+ if (dist > 0.2) return { info, center, reason: `out of reach (${dist.toFixed(2)} m from the ${sides[0]} shoulder)` };
559
+ return { info, center, reason: sideTooWide ? `turned the wrong way to grasp from here (${(info.length * 100).toFixed(0)} cm across)` : `no grasp pose for the ${sides[0]} arm` };
560
  }
561
 
562
  function fingerGeoms(robot, side) {
 
575
  return robot._fingers[side];
576
  }
577
 
578
+ /**
579
+ * True when the object is between an arm's closed fingers: the point between the finger pads is within
580
+ * 2 cm of the object's geoms (anywhere along it: a tall bottle grasped near its top counts).
581
+ */
582
  export function holding(robot, side, bodyId) {
583
+ if (robot.gripperOpening(side) >= 0.6) return false;
584
+ const { model, data } = robot.sim;
585
  const [a, b] = fingerGeoms(robot, side);
586
  const mid = [0, 1, 2].map((k) => (data.geom_xpos[3 * a + k] + data.geom_xpos[3 * b + k]) / 2);
587
  const p = robot.sim.bodyPos(bodyId);
588
+ if (Math.hypot(p[0] - mid[0], p[1] - mid[1], p[2] - mid[2]) > 0.25) return false;
589
+ for (let g = model.body_geomadr[bodyId]; g < model.body_geomadr[bodyId] + model.body_geomnum[bodyId]; g++) {
590
+ if (!model.geom_contype[g] && !model.geom_conaffinity[g]) continue;
591
+ const s = geomShape(model, data, g);
592
+ if (mid[2] < s.z0 - 0.02 || mid[2] > s.z1 + 0.02) continue;
593
+ const dx = mid[0] - s.x;
594
+ const dy = mid[1] - s.y;
595
+ if (s.round) {
596
+ if (Math.hypot(dx, dy) < s.r + 0.02) return true;
597
+ } else if (Math.abs(dx * s.ux + dy * s.uy) < s.hx + 0.02 && Math.abs(-dx * s.uy + dy * s.ux) < s.hy + 0.02) return true;
598
+ }
599
+ return false;
600
  }
601
 
602
  /**
 
714
  * Put the object held by `side` down with its centre over a robot-frame point [x, y] and its bottom
715
  * at height `z` (the surface), then open and lift away. The gripper keeps its commanded pitch.
716
  */
717
+ export function* place(robot, side, point, bodyId, { slack = 0 } = {}) {
718
  const sim = robot.sim;
719
  if (bodyId !== undefined) {
720
  // A held object no longer slips into place (the physics holds grasps firmly), so line the arm up.
721
  const world = robot.toWorld(point);
722
+ const aligned = yield* alignToPlace(robot, side, world, slack, bodyId);
723
+ if (!aligned.ok) return { ok: false, message: `could not get to where it goes: ${aligned.message}` };
724
+ point = nearerSpot(robot, side, robot.toRobot(world), slack);
725
  }
726
  const { pitch } = robot.arms[side].target;
727
  const z0 = robot.toRobot([0, 0, 0])[2];
 
749
  yield* reach(robot, side, at(0.02), { pitch, duration: 0.6, settle: 0.15 });
750
  yield* reach(robot, side, at(0.008), { pitch, duration: 0.4, settle: 0.15 });
751
  yield* reach(robot, side, at(0.002), { pitch, duration: 0.3, settle: 0.15 });
752
+ // A tall object in a tilted grip comes down on one edge of its base: press a few millimetres further,
753
+ // so it turns flat between the fingers before they let go.
754
+ if (bodyId !== undefined && objectInfo(sim, bodyId).height > 0.07) yield* reach(robot, side, at(-0.008), { pitch, duration: 0.4, settle: 0.2 });
755
  // Open part way: wide open, a jaw can catch the wall of the bowl or box it put something in, and lift it.
756
  yield* gripper(robot, side, true, { duration: 0.4, settle: 0.3, opening: 0.45 });
757
+ // Out along the gripper first, then up: a tilted gripper lifted straight up drags its fingers over
758
+ // what it let go of, and a tall thing tips over.
759
  const away = at(0.003);
760
+ const arm = robot.arms[side];
761
+ const psi = Math.atan2(away[1] - arm.axis[1], away[0] - arm.axis[0]);
762
+ const along = [Math.cos(pitch) * Math.cos(psi), Math.cos(pitch) * Math.sin(psi), -Math.sin(pitch)];
763
+ const out = away.map((v, k) => v - 0.05 * along[k]);
764
+ yield* reach(robot, side, out, { pitch, duration: 0.5, settle: 0 });
765
+ yield* reach(robot, side, [out[0], out[1], out[2] + 0.05], { pitch, duration: 0.5, settle: 0 });
766
  yield* homeArm(robot, side);
767
  if (bodyId === undefined) return { ok: true, message: `opened the ${side} gripper at the spot` };
768
  const now = robot.toRobot(sim.bodyPos(bodyId));
 
771
  }
772
 
773
  /**
774
+ * Before putting a held object down at a world point: unless the point is already about 0.27 m ahead
775
+ * and in line with the arm, drive around the furniture to where it is.
 
776
  */
777
+ function* alignToPlace(robot, side, world, slack = 0, bodyId) {
778
+ const rel = nearerSpot(robot, side, robot.toRobot(world), slack);
779
+ if (Math.abs(rel[1] - robot.arms[side].axis[1]) < 0.05 && rel[0] > 0.2 && rel[0] < 0.32) return { ok: true, message: "in reach" };
780
+ yield* stowArms(robot);
781
+ // How the object sits in the gripper (its base), which does not change as the base drives.
782
+ let carry = null;
783
+ if (bodyId !== undefined) {
784
+ const info = objectInfo(robot.sim, bodyId);
785
+ const c = robot.toRobot(info.center);
786
+ carry = { held: heldOffset(robot, side, [c[0], c[1], info.bottom + robot.toRobot([0, 0, 0])[2]]), pitch: robot.arms[side].target.pitch };
787
+ }
788
+ return yield* driveToReach(robot, world, (at) => placeReach(robot, side, world, at, slack, carry), { side, what: "the spot" });
789
+ }
790
+
791
+ /**
792
+ * A robot-frame spot moved toward an arm by up to `slack` metres (but not nearer than 0.26 m ahead):
793
+ * on a plate, anywhere near its middle will do, and the nearer the easier to reach.
794
+ */
795
+ function nearerSpot(robot, side, p, slack) {
796
+ if (!(slack > 0)) return p;
797
+ const arm = robot.arms[side];
798
+ const dx = p[0] - arm.axis[0];
799
+ const dy = p[1] - arm.axis[1];
800
+ const d = Math.hypot(dx, dy) || 1;
801
+ const m = Math.min(slack, Math.max(0, p[0] - 0.26));
802
+ return [p[0] - (dx / d) * m, p[1] - (dy / d) * m, p[2]];
803
+ }
804
+
805
+ /**
806
+ * Extra cost of putting something down at a world point with an arm from chassis pose `at`, or null if
807
+ * the arm cannot: the point has to be 0.2-0.32 m ahead and in line with the arm, and the wrist able to
808
+ * hang above it.
809
+ */
810
+ function placeReach(robot, side, world, at, slack = 0, carry = null) {
811
+ const arm = robot.arms[side];
812
+ const p = nearerSpot(robot, side, robotFrame(robot, at).toRobot(world), slack);
813
+ if (p[0] < 0.2 || p[0] > 0.34 || Math.abs(p[1] - arm.axis[1]) > 0.05) return null;
814
+ // Where the wrist has to be: for an object in the gripper, as place() will put it down (the object's
815
+ // base 2 cm over the spot, held as it is held); otherwise the gripper pointing down over the spot.
816
+ const pitch = carry ? carry.pitch : DOWN;
817
+ const wrist = carry ? wristForHeld(robot, side, [p[0], p[1], p[2] + 0.02], carry.held, pitch) : [p[0], p[1], p[2] + GRASP.padBelow + 0.03];
818
+ const t = robot.wristTarget(side, wrist, pitch);
819
+ return Math.hypot(t.x, t.y + CONTROL.tipLength * Math.sin(pitch)) > 0.245 || t.x < 0.05 ? null : 2.5 * Math.max(0, p[0] - 0.27);
820
  }
821
 
822
  /** Whether an object sits where the arms grasp it well: graspable, and no farther than 0.3 m ahead. */
823
+ export function comfortable(robot, bodyId, side, { at, info } = {}) {
824
+ const plan = graspPlan(robot, bodyId, side, { at, info });
825
  const ahead = plan.center ? plan.center[0] : Infinity;
826
  return { ok: !plan.reason && ahead <= 0.305, plan, ahead };
827
  }
828
 
829
+ /** Free bodies the grippers hold now. */
830
+ function heldBodies(robot) {
831
+ return robot.sim.freeBodies([robot.root]).filter((o) => holding(robot, "left", o.id) || holding(robot, "right", o.id)).map((o) => o.id);
832
+ }
833
+
834
+ /** True when an arm is at the resting pose homeArm leaves it in. */
835
+ function atRest(robot, side) {
836
+ const arm = robot.arms[side];
837
+ const t = arm.target;
838
+ return Math.abs(t.x - CONTROL.initialEe[0]) < 0.01 && Math.abs(t.y - CONTROL.initialEe[1]) < 0.01 && Math.abs(t.pitch) < 0.05 && Math.abs(t.rotation - arm.rotationHome) < 0.05;
839
+ }
840
+
841
+ // Arms folded up for driving: nothing reaches out beyond the chassis (the grippers point up, 1.19 m
842
+ // high), so the base can come up to a counter whatever stands on it.
843
+ const TUCK = { x: 0.03, y: 0.24, pitch: -1.5 };
844
+
845
+ const tucked = (robot, side) => {
846
+ const t = robot.arms[side].target;
847
+ return Math.abs(t.x - TUCK.x) < 0.01 && Math.abs(t.y - TUCK.y) < 0.01 && Math.abs(t.pitch - TUCK.pitch) < 0.05 && Math.abs(t.rotation - robot.arms[side].rotationHome) < 0.05;
848
+ };
849
+
850
+ /** Run several arm moves at once, one control period at a time. */
851
+ function* together(moves) {
852
+ const running = moves.slice();
853
+ while (running.length) {
854
+ for (let k = running.length - 1; k >= 0; k--) if (running[k].next().done) running.splice(k, 1);
855
+ if (running.length) yield;
856
+ }
857
+ }
858
+
859
  /**
860
+ * Before the base drives: free arms fold up, both at once. An arm holding something stays as it is,
861
+ * the object lifted where it picked it up; the planner drives with that outline.
 
862
  */
863
+ function* stowArms(robot) {
864
+ const held = { left: false, right: false };
865
+ for (const o of robot.sim.freeBodies([robot.root])) for (const s of ["left", "right"]) if (holding(robot, s, o.id)) held[s] = true;
866
+ const moves = [];
867
+ for (const s of ["left", "right"]) {
868
+ if (held[s] || tucked(robot, s)) continue;
869
+ const arm = robot.arms[s];
870
+ moves.push(moveArm(robot, s, { ...TUCK, rotation: arm.rotationHome, roll: arm.rollHome }, { duration: 1.0, settle: 0.1 }));
871
+ }
872
+ yield* together(moves);
873
+ }
874
+
875
+ /** An arm to its resting pose unless it is there (the pick policy starts from it). */
876
+ export function* restArm(robot, side) {
877
+ if (!atRest(robot, side)) yield* homeArm(robot, side, { duration: 1.0 });
878
+ }
879
+
880
+ /**
881
+ * Chassis poses from which `reaches(at, side)` holds (it returns an extra cost, or null), best first
882
+ * (a generator: it spreads the work over control periods):
883
+ * around `target` (world) at every 5 degrees of heading, with the target 0.23-0.29 m ahead and in line
884
+ * with an arm, clear of furniture by `margin`. Scored by the length of the way there (a grid search
885
+ * for a disc inside the chassis), how well the target sits for the arm, and the extra cost.
886
+ */
887
+ function* standingPoses(robot, fp, target, reaches, { side, start, margin = 0.02 }) {
888
+ const field = new DiscField(fp, [start[0], start[1]], { extra: [target] });
889
+ yield;
890
+ const sides = side ? [side] : ["left", "right"];
891
+ const found = [];
892
+ let lastYield = performance.now();
893
+ for (let k = 0; k < 72; k++) {
894
+ // a few milliseconds per control period, so the page keeps drawing
895
+ if (performance.now() - lastYield > 8) {
896
+ yield;
897
+ lastYield = performance.now();
898
+ }
899
+ const yaw = -Math.PI + (k * Math.PI) / 36;
900
+ const c = Math.cos(yaw);
901
+ const s = Math.sin(yaw);
902
+ for (const sd of sides) {
903
+ const lateral = robot.arms[sd].axis[1];
904
+ for (let fwd = 0.23; fwd < 0.435; fwd += 0.01) {
905
+ for (const off of [-0.03, 0, 0.03]) {
906
+ const ty = lateral + off;
907
+ const x = target[0] - (c * fwd - s * ty);
908
+ const y = target[1] - (s * fwd + c * ty);
909
+ if (!fp.free(x, y, yaw, margin)) continue;
910
+ const way = field.at(x, y);
911
+ if (!Number.isFinite(way)) continue;
912
+ const extra = reaches({ x, y, yaw }, sd);
913
+ if (extra === null) continue;
914
+ // Not right up against the furniture when there is room: the pose is reached within a centimetre or two.
915
+ const clear = fp.clearance(x, y, yaw, 0.04);
916
+ const score = way + 0.1 * Math.abs(wrap(yaw - start[2])) + 2.5 * Math.abs(fwd - 0.26) + 1.5 * Math.abs(off) + 3 * (0.04 - clear) + extra;
917
+ found.push({ pose: [x, y, yaw], side: sd, score });
918
+ }
919
+ }
920
+ }
921
+ }
922
+ found.sort((a, b) => a.score - b.score);
923
+ // Keep poses that differ: 8 cm or 20 degrees from every better one.
924
+ const kept = [];
925
+ for (const f of found) {
926
+ if (kept.some((q) => Math.hypot(q.pose[0] - f.pose[0], q.pose[1] - f.pose[1]) < 0.08 && Math.abs(wrap(q.pose[2] - f.pose[2])) < 0.35)) continue;
927
+ kept.push(f);
928
+ if (kept.length >= 8) break;
929
+ }
930
+ return kept;
931
+ }
932
+
933
+ /**
934
+ * Drive around the furniture to a pose from which `reaches(at, side)` holds: plans to the best standing
935
+ * poses in turn until one has a path, follows it watching for contact, and plans again from where it
936
+ * is if the base strays, stalls or touches something. Returns {ok, message, side}.
937
+ */
938
+ function* driveToReach(robot, target, reaches, { side, what }) {
939
  const sim = robot.sim;
940
+ const watch = new ContactWatch(sim, robot.root);
941
+ let last = "";
942
  for (let attempt = 0; attempt < 3; attempt++) {
943
+ const held = heldBodies(robot);
944
+ const fp = new Footprint(new ObstacleMap(sim, robot.root, { objects: true, except: held }), robotFootprint(robot, held));
945
+ yield;
946
+ const start = robot.pose();
947
+ const poses = yield* standingPoses(robot, fp, target, reaches, { side, start });
948
+ if (!poses.length) return { ok: false, message: `there is no clear spot to stand from which an arm reaches ${what}` };
949
+ let plan = null;
950
+ let goal = null;
951
+ for (const p of poses.slice(0, 5)) {
952
+ plan = yield* planPath(fp, start, p.pose, { margin: 0.03, goalMargin: 0.02 });
953
+ if (plan.ok) {
954
+ goal = p;
955
+ break;
956
+ }
957
  }
958
+ if (!goal) return { ok: false, message: `found no way around the furniture to ${what}` };
959
+ // Gently with something in a gripper: a quick turn can swing it out.
960
+ const carrying = fp.fp.parts.length > 1 && heldBodies(robot).length > 0;
961
+ const run = yield* followPath(robot, plan.moves, { fp, watch, ...(carrying ? { speed: 0.15, reverseSpeed: 0.1, turnRate: 0.5 } : {}) });
962
+ if (run.ok) {
963
+ yield* settle(robot, fp, goal.pose);
964
+ return { ok: true, side: goal.side, message: `drove ${plan.length.toFixed(1)} m` };
 
965
  }
966
+ last = run.message;
967
+ if (run.touched) yield* backAway(robot, fp);
968
+ }
969
+ return { ok: false, message: `could not get there: ${last}` };
970
+ }
971
+
972
+ /**
973
+ * At the end of a path: square up to the goal's heading and close the distance along it. Both moves
974
+ * look ahead and stop short of furniture.
975
+ */
976
+ function* settle(robot, fp, goal) {
977
+ const dyaw = wrap(goal[2] - robot.pose()[2]);
978
+ if (Math.abs(dyaw) > 0.03) yield* turnBy(robot, dyaw, { fp });
979
+ const p = robot.pose();
980
+ const along = (goal[0] - p[0]) * Math.cos(p[2]) + (goal[1] - p[1]) * Math.sin(p[2]);
981
+ if (Math.abs(along) > 0.012) {
982
+ const d = fp.fp.axle;
983
+ const from = [p[0] + d * Math.cos(p[2]), p[1] + d * Math.sin(p[2]), p[2]];
984
+ const to = [from[0] + along * Math.cos(p[2]), from[1] + along * Math.sin(p[2]), p[2]];
985
+ yield* track(robot, [from, to], Math.sign(along), { fp, speed: 0.08 });
986
+ robot.stopBase();
987
  }
988
+ }
989
+
990
+ /** After touching furniture: back off 6 cm the way that is clear (behind first). */
991
+ function* backAway(robot, fp) {
992
+ const [x, y, yaw] = robot.pose();
993
+ for (const d of [-0.06, 0.06]) {
994
+ if (fp.free(x + d * Math.cos(yaw), y + d * Math.sin(yaw), yaw, 0)) {
995
+ yield* drive(robot, d, { speed: 0.08 });
996
+ return;
997
+ }
998
+ }
999
+ }
1000
+
1001
+ /**
1002
+ * Drive around the furniture so an object comes within comfortable reach of one arm: of all the places
1003
+ * to stand around it (every heading, either arm), the one with the shortest way there that also grasps
1004
+ * it well: from above where it can, across its narrow side, with the wrist turned little. An object too
1005
+ * wide to pick up (a bowl, a plate) is driven to so that an arm reaches it, to put something in or on it.
1006
+ */
1007
+ export function* approach(robot, bodyId, { side } = {}) {
1008
+ const sim = robot.sim;
1009
+ let check = comfortable(robot, bodyId, side);
1010
+ if (check.ok) return { ok: true, message: `already in reach of the ${check.plan.side} arm`, side: check.plan.side };
1011
+ const name = sim.bodyNames[bodyId];
1012
+ yield* stowArms(robot);
1013
+ const info = objectInfo(sim, bodyId);
1014
+ const graspable = info.width <= GRASP.maxWidth;
1015
+ // Standing where the arm grasps it comfortably is preferred; at the edge of its workspace it still can.
1016
+ const reaches = (at, s) => {
1017
+ if (!graspable) return placeReach(robot, s, [info.center[0], info.center[1], info.bottom + 0.012], at, Math.max(0, info.width / 2 - 0.045));
1018
+ const plan = graspPlan(robot, bodyId, s, { at, info });
1019
+ if (plan.reason) return null;
1020
+ const pose = plan.pose;
1021
+ // Also: the jaws square to the object (a tilted gripper rolled far closes at a slant), and across
1022
+ // its narrowest side (a carton grasped from the side has to be faced right).
1023
+ const slant = Math.abs(Math.sin(pose.roll - robot.arms[s].rollHome)) * Math.cos(pose.pitch) + 2 * Math.max(0, -Math.sin(pose.roll - robot.arms[s].rollHome)) * Math.cos(pose.pitch);
1024
+ // A tall object is held better by its middle, from the side, than by its top.
1025
+ const sideCost = info.height > 0.12 ? (pose.mode === "side" ? 0 : 0.4) : pose.mode === "side" ? 0.15 : 0;
1026
+ return (plan.center[0] > 0.305 ? 0.3 : 0) + sideCost + 0.25 * (Math.PI / 2 - pose.pitch) * (pose.mode === "side" ? 0 : 1) + 0.04 * Math.abs(pose.roll - robot.arms[s].rollHome) + 0.4 * slant + 6 * (pose.width - info.width);
1027
+ };
1028
+ const drove = yield* driveToReach(robot, info.center, reaches, { side, what: `the ${name}` });
1029
+ if (!drove.ok) return { ok: false, message: drove.message };
1030
+ check = comfortable(robot, bodyId, side);
1031
+ if (check.ok) return { ok: true, message: `in reach of the ${check.plan.side} arm (${drove.message})`, side: check.plan.side };
1032
+ if (!check.plan.reason) return { ok: true, message: `in reach of the ${check.plan.side} arm, at the edge of its workspace (${drove.message})`, side: check.plan.side };
1033
+ if (!graspable) return { ok: true, message: `next to the ${name}, in reach of the ${drove.side} arm (${drove.message}); it is ${check.plan.reason}`, side: drove.side };
1034
+ return { ok: false, message: `drove next to it, but ${check.plan.reason}` };
1035
  }
tools/build_public.mjs CHANGED
@@ -60,11 +60,12 @@ for (const { id } of JSON.parse(readFileSync(join(ASSETS, "robots", "index.json"
60
  report.push(`robot ${id}: ${p.count} meshes, ${(p.raw / 1e6).toFixed(1)} MB -> ${(p.packed / 1e6).toFixed(1)} MB`);
61
  }
62
 
63
- // Environments: registry, XML (with any files they list, and their decor) and splats.
64
  copy(join(ASSETS, "environments", "index.json"), join(PUBLIC, "environments", "index.json"));
65
  for (const env of JSON.parse(readFileSync(join(ASSETS, "environments", "index.json"), "utf8"))) {
66
  const src = join(ASSETS, "environments");
67
- const extra = [...(env.files ?? []), ...(env.decor ? [env.decor] : [])].map((f) => join(dirname(env.xml), f));
 
68
  for (const f of [env.xml, env.splat, ...extra].filter(Boolean)) copy(join(src, f), join(PUBLIC, "environments", f));
69
  report.push(`environment ${env.id}${env.splat ? ` (+ ${(statSync(join(src, env.splat)).size / 1e6).toFixed(1)} MB splat)` : ""}`);
70
  }
 
60
  report.push(`robot ${id}: ${p.count} meshes, ${(p.raw / 1e6).toFixed(1)} MB -> ${(p.packed / 1e6).toFixed(1)} MB`);
61
  }
62
 
63
+ // Environments: registry, XML (with any files they list, their decor and their objects) and splats.
64
  copy(join(ASSETS, "environments", "index.json"), join(PUBLIC, "environments", "index.json"));
65
  for (const env of JSON.parse(readFileSync(join(ASSETS, "environments", "index.json"), "utf8"))) {
66
  const src = join(ASSETS, "environments");
67
+ const own = env.objects?.endsWith(".xml") ? [env.objects] : [];
68
+ const extra = [...(env.files ?? []), ...(env.decor ? [env.decor] : []), ...own].map((f) => join(dirname(env.xml), f));
69
  for (const f of [env.xml, env.splat, ...extra].filter(Boolean)) copy(join(src, f), join(PUBLIC, "environments", f));
70
  report.push(`environment ${env.id}${env.splat ? ` (+ ${(statSync(join(src, env.splat)).size / 1e6).toFixed(1)} MB splat)` : ""}`);
71
  }
tools/check_sim.mjs CHANGED
@@ -1,86 +1,187 @@
1
- // Checks of the web app's logic in Node, with the page's own WebAssembly physics:
2
- // teleop keys and the base speed loop, scripted picks in the tabletop scene, and go-to / pick / place
3
- // in the kitchen. Exits non-zero if a check fails.
4
- //
5
- // usage: node tools/check_sim.mjs
6
- import { loadScene } from "./node_env.mjs";
7
- import { XLeRobotTeleop } from "../src/robots/xlerobot.js";
8
- import { approach, objectInfo, pick, place, runSkill } from "../src/robots/skills.js";
9
-
10
- let failed = 0;
11
- const check = (ok, what) => {
12
- console.log(`${ok ? "PASS" : "FAIL"}: ${what}`);
13
- if (!ok) failed++;
14
- };
15
-
16
- // Teleop and base, on the empty floor.
17
- {
18
- const { sim, robot } = await loadScene("basic");
19
- const control = () => robot.update();
20
- sim.reset(() => robot.home());
21
- sim.run(0.5, control);
22
- const teleop = new XLeRobotTeleop(robot);
23
- const p0 = robot.pose();
24
- teleop.down.add("KeyW");
25
- sim.run(2.0, (dt) => (teleop.tick(dt), robot.update()));
26
- teleop.down.clear();
27
- sim.run(0.5, (dt) => (teleop.tick(dt), robot.update()));
28
- const p1 = robot.pose();
29
- const moved = (p1[0] - p0[0]) * Math.cos(p0[2]) + (p1[1] - p0[1]) * Math.sin(p0[2]);
30
- check(moved > 0.3, `W drives forward (${moved.toFixed(2)} m in 2 s)`);
31
- const y0 = robot.armPositions("left")[1];
32
- teleop.down.add("Digit8");
33
- sim.run(0.5, (dt) => (teleop.tick(dt), robot.update()));
34
- teleop.down.clear();
35
- check(Math.abs(robot.armPositions("left")[1] - y0) > 0.05, "8 moves the left arm");
36
- robot.setBaseVelocity(0.2, 0);
37
- sim.run(3, control);
38
- const [v] = robot.baseVelocity();
39
- check(Math.abs(v - 0.2) < 0.04, `base speed loop holds 0.2 m/s (${v.toFixed(3)})`);
40
- robot.stopBase();
41
- }
42
-
43
- // Scripted picks in the tabletop scene, with the robot in front of the long table.
44
- {
45
- const { sim, robot } = await loadScene("tabletop");
46
- const control = () => robot.update();
47
- sim.reset(() => robot.home());
48
- sim.run(1.5, control);
49
- const settled = sim.snapshot();
50
- let ok = 0;
51
- const cases = [["box1", 0.25], ["sphere2", 0.05], ["cylinder1", 0.25], ["sphere1", 0.35], ["box1", 0.0], ["sphere2", 0.3], ["cylinder1", 0.5], ["sphere1", 0.55]];
52
- for (const [name, x] of cases) {
53
- sim.restore(settled);
54
- robot.home();
55
- robot.spawn(x, -0.09, -Math.PI / 2);
56
- robot.snapJoints();
57
- sim.forward();
58
- sim.run(0.5, control);
59
- if (runSkill(sim, robot, pick(robot, sim.id("body", name))).ok) ok++;
60
- }
61
- check(ok >= cases.length - 1, `tabletop scripted picks ${ok}/${cases.length}`);
62
- }
63
-
64
- // Kitchen: go to the orange, pick it, put it in the bowl.
65
- {
66
- const { sim, robot } = await loadScene("kitchen");
67
- const control = () => robot.update();
68
- sim.reset(() => robot.home());
69
- sim.run(1.0, control);
70
- const orange = sim.id("body", "orange");
71
- const bowl = sim.id("body", "bowl");
72
- const a = runSkill(sim, robot, approach(robot, orange), { maxSeconds: 40 });
73
- check(a.ok, `kitchen: go to the orange (${a.message})`);
74
- const p = runSkill(sim, robot, pick(robot, orange));
75
- check(p.ok, `kitchen: pick the orange (${p.message})`);
76
- const b = robot.toRobot(sim.bodyPos(bowl));
77
- const info = objectInfo(sim, bowl);
78
- runSkill(sim, robot, place(robot, p.side, [b[0], b[1], robot.toRobot([0, 0, info.bottom])[2] + 0.012], orange));
79
- sim.run(0.5, control);
80
- const o = sim.bodyPos(orange);
81
- const c = sim.bodyPos(bowl);
82
- check(Math.hypot(o[0] - c[0], o[1] - c[1]) < 0.055, "kitchen: the orange ends in the bowl");
83
- }
84
-
85
- console.log(failed ? `${failed} check(s) failed` : "all checks passed");
86
- process.exit(failed ? 1 : 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Checks of the web app's logic in Node, with the page's own WebAssembly physics:
2
+ // teleop keys and the base speed loop, scripted picks in the tabletop scene, grasps of objects turned
3
+ // every way, go-to and pick of every object in the tabletop scene without the base touching furniture,
4
+ // and go-to / pick / place in the kitchen. Exits non-zero if a check fails.
5
+ //
6
+ // usage: node tools/check_sim.mjs
7
+ import { loadScene } from "./node_env.mjs";
8
+ import { XLeRobotTeleop } from "../src/robots/xlerobot.js";
9
+ import { approach, objectInfo, pick, place, runSkill } from "../src/robots/skills.js";
10
+ import { ContactWatch } from "../src/robots/nav.js";
11
+
12
+ let failed = 0;
13
+ const check = (ok, what) => {
14
+ console.log(`${ok ? "PASS" : "FAIL"}: ${what}`);
15
+ if (!ok) failed++;
16
+ };
17
+
18
+ // Teleop and base, on the empty floor.
19
+ {
20
+ const { sim, robot } = await loadScene("basic");
21
+ const control = () => robot.update();
22
+ sim.reset(() => robot.home());
23
+ sim.run(0.5, control);
24
+ const teleop = new XLeRobotTeleop(robot);
25
+ const p0 = robot.pose();
26
+ teleop.down.add("KeyW");
27
+ sim.run(2.0, (dt) => (teleop.tick(dt), robot.update()));
28
+ teleop.down.clear();
29
+ sim.run(0.5, (dt) => (teleop.tick(dt), robot.update()));
30
+ const p1 = robot.pose();
31
+ const moved = (p1[0] - p0[0]) * Math.cos(p0[2]) + (p1[1] - p0[1]) * Math.sin(p0[2]);
32
+ check(moved > 0.3, `W drives forward (${moved.toFixed(2)} m in 2 s)`);
33
+ const y0 = robot.armPositions("left")[1];
34
+ teleop.down.add("Digit8");
35
+ sim.run(0.5, (dt) => (teleop.tick(dt), robot.update()));
36
+ teleop.down.clear();
37
+ check(Math.abs(robot.armPositions("left")[1] - y0) > 0.05, "8 moves the left arm");
38
+ robot.setBaseVelocity(0.2, 0);
39
+ sim.run(3, control);
40
+ const [v] = robot.baseVelocity();
41
+ check(Math.abs(v - 0.2) < 0.04, `base speed loop holds 0.2 m/s (${v.toFixed(3)})`);
42
+ robot.stopBase();
43
+ }
44
+
45
+ // Scripted picks in the tabletop scene, with the robot in front of the long table.
46
+ {
47
+ const { sim, robot } = await loadScene("tabletop", "xlerobot", { objects: "robot" });
48
+ const control = () => robot.update();
49
+ sim.reset(() => robot.home());
50
+ sim.run(1.5, control);
51
+ const settled = sim.snapshot();
52
+ let ok = 0;
53
+ const cases = [["box1", 0.25], ["sphere2", 0.05], ["cylinder1", 0.25], ["sphere1", 0.35], ["box1", 0.0], ["sphere2", 0.3], ["cylinder1", 0.5], ["sphere1", 0.55]];
54
+ for (const [name, x] of cases) {
55
+ sim.restore(settled);
56
+ robot.home();
57
+ robot.spawn(x, -0.09, -Math.PI / 2);
58
+ robot.snapJoints();
59
+ sim.forward();
60
+ sim.run(0.5, control);
61
+ if (runSkill(sim, robot, pick(robot, sim.id("body", name))).ok) ok++;
62
+ }
63
+ check(ok >= cases.length - 1, `tabletop scripted picks ${ok}/${cases.length}`);
64
+ }
65
+
66
+ // Grasps that follow how an object lies: a block, a banana and a mug turned to different yaws, in
67
+ // front of the robot at the tabletop's back counter (the other objects moved out of the way).
68
+ {
69
+ const { sim, robot } = await loadScene("tabletop");
70
+ const control = () => robot.update();
71
+ sim.reset(() => {
72
+ robot.home();
73
+ robot.snapJoints();
74
+ });
75
+ sim.run(1.0, control);
76
+ const settled = sim.snapshot();
77
+ const { model } = sim;
78
+ let ok = 0;
79
+ let n = 0;
80
+ for (const [name, yaws] of [["cube", [0, 30, 60]], ["banana", [0, 50, 100]], ["mug", [0, 150]]]) {
81
+ const id = sim.id("body", name);
82
+ const qa = model.jnt_qposadr[model.body_jntadr[id]];
83
+ const z = settled.qpos[qa + 2];
84
+ const q0 = Array.from(settled.qpos.subarray(qa + 3, qa + 7));
85
+ for (const deg of yaws) {
86
+ sim.restore(settled);
87
+ robot.home();
88
+ robot.spawn(0, -0.3 + 0.022 + 0.196, -Math.PI / 2);
89
+ robot.apply();
90
+ robot.snapJoints();
91
+ sim.forward();
92
+ sim.freeBodies([robot.root]).forEach((o, k) => {
93
+ if (o.id !== id) sim.data.qpos.set([3 + 0.3 * k, 3, 0.1, 1, 0, 0, 0], model.jnt_qposadr[model.body_jntadr[o.id]]);
94
+ });
95
+ const p = robot.toWorld([0.27, robot.arms.left.axis[1], 0]);
96
+ const a = (deg * Math.PI) / 180;
97
+ const [w, x, y, zq] = [Math.cos(a / 2), 0, 0, Math.sin(a / 2)];
98
+ // the yaw on top of how it rests
99
+ const q = [w * q0[0] - zq * q0[3], w * q0[1] - zq * q0[2], w * q0[2] + zq * q0[1], w * q0[3] + zq * q0[0]];
100
+ sim.data.qpos.set([p[0], p[1], z, ...q], qa);
101
+ sim.forward();
102
+ sim.run(0.5, control);
103
+ n++;
104
+ if (runSkill(sim, robot, pick(robot, id, { side: "left" })).ok) ok++;
105
+ }
106
+ }
107
+ check(ok >= n - 1, `grasps across objects' narrow sides, turned every way: ${ok}/${n}`);
108
+ }
109
+
110
+ // Tabletop: from the start, go to each object and pick it (the bowl and plate: go to them). The base
111
+ // must never touch the counters.
112
+ {
113
+ const { sim, robot } = await loadScene("tabletop");
114
+ const control = () => robot.update();
115
+ sim.reset(() => {
116
+ robot.home();
117
+ robot.snapJoints();
118
+ });
119
+ sim.run(1.0, control);
120
+ const settled = sim.snapshot();
121
+ const watch = new ContactWatch(sim, robot.root);
122
+ let reached = 0;
123
+ let picked = 0;
124
+ let touched = 0;
125
+ const names = sim.freeBodies([robot.root]).map((o) => o.name);
126
+ const containers = ["bowl", "plate"];
127
+ for (const name of names) {
128
+ sim.restore(settled);
129
+ robot.home();
130
+ robot.snapJoints();
131
+ sim.forward();
132
+ const id = sim.id("body", name);
133
+ let phase = "go";
134
+ const onTick = () => {
135
+ const c = watch.check();
136
+ // a finger on the worktop while grasping is picking; the base on furniture is not
137
+ if (c && (phase === "go" || /chassis|wheel/.test(c.robot))) touched++;
138
+ };
139
+ const a = runSkill(sim, robot, approach(robot, id), { maxSeconds: 60, onTick });
140
+ if (a.ok) reached++;
141
+ phase = "pick";
142
+ if (a.ok && !containers.includes(name) && runSkill(sim, robot, pick(robot, id), { maxSeconds: 30, onTick }).ok) picked++;
143
+ if (!a.ok) console.log(` ${name}: ${a.message}`);
144
+ }
145
+ check(reached === names.length, `tabletop: went to ${reached}/${names.length} objects`);
146
+ check(picked >= names.length - containers.length - 1, `tabletop: picked ${picked}/${names.length - containers.length}`);
147
+ check(touched === 0, `tabletop: the base never touched furniture (${(touched * sim.controlDt).toFixed(2)} s of contact)`);
148
+ }
149
+
150
+ // Kitchen: go to the orange, pick it, put it in the bowl.
151
+ {
152
+ const { sim, robot } = await loadScene("kitchen");
153
+ const control = () => robot.update();
154
+ sim.reset(() => {
155
+ robot.home();
156
+ robot.snapJoints();
157
+ });
158
+ sim.run(1.0, control);
159
+ const settled = sim.snapshot();
160
+ // The can is behind the island from the start: around it, without touching it.
161
+ const watch = new ContactWatch(sim, robot.root);
162
+ let touched = 0;
163
+ const can = sim.id("body", "can");
164
+ const toCan = runSkill(sim, robot, approach(robot, can), { maxSeconds: 60, onTick: () => (watch.check() ? touched++ : 0) });
165
+ const gotCan = toCan.ok && runSkill(sim, robot, pick(robot, can)).ok;
166
+ check(gotCan && touched === 0, `kitchen: around the island to the can and pick it (${toCan.message}; ${touched} ticks touching)`);
167
+ sim.restore(settled);
168
+ robot.home();
169
+ robot.snapJoints();
170
+ sim.forward();
171
+ const orange = sim.id("body", "orange");
172
+ const bowl = sim.id("body", "bowl");
173
+ const a = runSkill(sim, robot, approach(robot, orange), { maxSeconds: 40 });
174
+ check(a.ok, `kitchen: go to the orange (${a.message})`);
175
+ const p = runSkill(sim, robot, pick(robot, orange));
176
+ check(p.ok, `kitchen: pick the orange (${p.message})`);
177
+ const b = robot.toRobot(sim.bodyPos(bowl));
178
+ const info = objectInfo(sim, bowl);
179
+ runSkill(sim, robot, place(robot, p.side, [b[0], b[1], robot.toRobot([0, 0, info.bottom])[2] + 0.012], orange));
180
+ sim.run(0.5, control);
181
+ const o = sim.bodyPos(orange);
182
+ const c = sim.bodyPos(bowl);
183
+ check(Math.hypot(o[0] - c[0], o[1] - c[1]) < 0.055, "kitchen: the orange ends in the bowl");
184
+ }
185
+
186
+ console.log(failed ? `${failed} check(s) failed` : "all checks passed");
187
+ process.exit(failed ? 1 : 0);
tools/eval_kitchen.mjs CHANGED
@@ -1,31 +1,36 @@
1
- // The pick policy in the kitchen, where it was not trained: go to each object with the approach skill,
2
- // then let the policy pick it. Uses the page's code and ONNX Runtime Web, as tools/eval_policy.mjs.
3
- //
4
- // usage: node tools/eval_kitchen.mjs [assets/policies/xlerobot_pick]
5
- import { readFileSync } from "node:fs";
6
- import { join } from "node:path";
7
- import * as ort from "onnxruntime-web";
8
- import { loadScene, ROOT } from "./node_env.mjs";
9
- import { approach, runSkill, runSkillAsync } from "../src/robots/skills.js";
10
- import { PolicyRunner, policyPick } from "../src/policy/runner.js";
11
-
12
- const dir = process.argv[2] ?? join(ROOT, "assets", "policies", "xlerobot_pick");
13
- ort.env.wasm.numThreads = 1;
14
- const meta = JSON.parse(readFileSync(join(dir, "policy.json"), "utf8"));
15
- const runner = await PolicyRunner.load(ort, readFileSync(join(dir, meta.onnx)), meta);
16
- const { sim, robot } = await loadScene("kitchen");
17
- sim.reset(() => robot.home());
18
- sim.run(1.0, () => robot.update());
19
- const settled = sim.snapshot();
20
- let ok = 0;
21
- const names = ["orange", "apple", "cube"];
22
- for (const name of names) {
23
- sim.restore(settled);
24
- robot.home();
25
- const id = sim.id("body", name);
26
- const a = runSkill(sim, robot, approach(robot, id), { maxSeconds: 40 });
27
- const r = a.ok ? await runSkillAsync(sim, robot, policyPick(robot, runner, id, a.side), { maxSeconds: 14 }) : { ok: false, message: a.message };
28
- if (r.ok) ok++;
29
- console.log(`${name}: ${a.message} -> ${r.message}`);
30
- }
31
- console.log(`kitchen: the policy picked ${ok}/${names.length}`);
 
 
 
 
 
 
1
+ // The pick policy in the kitchen, where it was not trained: go to each object with the approach skill,
2
+ // then let the policy pick it. Uses the page's code and ONNX Runtime Web, as tools/eval_policy.mjs.
3
+ //
4
+ // usage: node tools/eval_kitchen.mjs [assets/policies/xlerobot_pick]
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import * as ort from "onnxruntime-web";
8
+ import { loadScene, ROOT } from "./node_env.mjs";
9
+ import { approach, restArm, runSkill, runSkillAsync } from "../src/robots/skills.js";
10
+ import { PolicyRunner, policyPick } from "../src/policy/runner.js";
11
+
12
+ const dir = process.argv[2] ?? join(ROOT, "assets", "policies", "xlerobot_pick");
13
+ ort.env.wasm.numThreads = 1;
14
+ const meta = JSON.parse(readFileSync(join(dir, "policy.json"), "utf8"));
15
+ const runner = await PolicyRunner.load(ort, readFileSync(join(dir, meta.onnx)), meta);
16
+ const { sim, robot } = await loadScene("kitchen");
17
+ sim.reset(() => {
18
+ robot.home();
19
+ robot.snapJoints();
20
+ });
21
+ sim.run(1.0, () => robot.update());
22
+ const settled = sim.snapshot();
23
+ let ok = 0;
24
+ const names = ["orange", "apple", "cube"];
25
+ for (const name of names) {
26
+ sim.restore(settled);
27
+ robot.home();
28
+ const id = sim.id("body", name);
29
+ const a = runSkill(sim, robot, approach(robot, id), { maxSeconds: 60 });
30
+ // The go-to skill drives with the arms folded; the policy learned to start with the arm at rest.
31
+ if (a.ok) runSkill(sim, robot, restArm(robot, a.side));
32
+ const r = a.ok ? await runSkillAsync(sim, robot, policyPick(robot, runner, id, a.side), { maxSeconds: 14 }) : { ok: false, message: a.message };
33
+ if (r.ok) ok++;
34
+ console.log(`${name}: ${a.message} -> ${r.message}`);
35
+ }
36
+ console.log(`kitchen: the policy picked ${ok}/${names.length}`);
tools/make_kitchen.py CHANGED
@@ -12,6 +12,8 @@ Material names are what the page's lit renderer gives textures to (src/render/ma
12
 
13
  from pathlib import Path
14
 
 
 
15
  OUT = Path(__file__).resolve().parents[1] / "assets" / "environments" / "kitchen" / "scene.xml"
16
 
17
  COUNTER_TOP = 0.90 # counter run
@@ -334,60 +336,35 @@ def room() -> None:
334
  ])
335
 
336
 
337
- def obj(name: str, pos, geoms: list[str], mass: float) -> None:
338
- lines.append(f' <body name="{name}" pos="{f(*pos)}">')
339
- lines.append(" <freejoint/>")
340
- for g in geoms:
341
- lines.append(f' {g.replace("/>", f" mass=\"{mass / len(geoms):.4g}\" contype=\"1\" conaffinity=\"1\"/>")}')
342
- lines.append(" </body>")
343
-
344
-
345
- # Round objects get rolling friction (condim 6): without it a sphere set rolling by the smallest
346
- # bounce keeps going.
347
- ROUND = 'condim="6" friction="1.2 0.02 0.002"'
348
-
349
-
350
  def objects() -> None:
 
351
  z = ISLAND_TOP
352
- obj("apple", (-0.91, -0.42, z + 0.025), [f'<geom type="sphere" size="0.025" material="apple" {ROUND}/>'], 0.08)
353
- obj("orange", (-0.91, -0.02, z + 0.024), [f'<geom type="sphere" size="0.024" material="orange" {ROUND}/>'], 0.07)
354
- obj("cube", (-0.9, 0.42, z + 0.02), ['<geom type="box" size="0.02 0.02 0.02" material="cube" condim="4" friction="1.2 0.05 0.01"/>'], 0.04)
355
- obj("can", (-1.38, -0.3, z + 0.045), [f'<geom type="cylinder" size="0.025 0.045" material="can" {ROUND}/>'], 0.06)
356
- obj("mug", (-1.35, 0.35, z + 0.04), [
357
- '<geom type="cylinder" size="0.03 0.04" material="mug" condim="4" friction="1.2 0.05 0.01"/>',
358
- '<geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" condim="4" friction="1.2 0.05 0.01"/>',
359
- ], 0.09)
360
- # A bowl and a plate to put things in or on: too wide to pick up.
361
- ring = []
362
- for k in range(10):
363
- import math
364
-
365
- a = 2 * math.pi * k / 10
366
- ring.append(f'<geom type="box" pos="{f(0.062 * math.cos(a), 0.062 * math.sin(a), 0.028)}" euler="0 0 {a:.4f}" size="0.006 0.021 0.022" material="bowl" condim="4"/>')
367
- # The bowl by the island's edge facing the room: placing reaches it (12 cm in, it was at the arm's limit).
368
- obj("bowl", (-0.94, 0.2, z + 0.003), ['<geom type="cylinder" pos="0 0 0.004" size="0.05 0.004" material="bowl" condim="4"/>', *ring], 0.3)
369
- obj("plate", (-0.99, -0.22, z + 0.01), ['<geom type="cylinder" size="0.1 0.006" material="plate" condim="4"/>'], 0.25)
370
- # On the dining table and the counter.
371
- obj("banana", (1.0, 1.35, 0.75 + 0.017), [f'<geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" {ROUND}/>'], 0.1)
372
- obj("cup", (1.5, 1.5, 0.75 + 0.045), [f'<geom type="cylinder" size="0.03 0.045" material="cup" {ROUND}/>'], 0.06)
373
- obj("bottle", (-2.55, -0.45, COUNTER_TOP + 0.085), [f'<geom type="cylinder" size="0.03 0.085" material="bottle" {ROUND}/>'], 0.2)
374
- obj("book", (1.15, -0.9, 0.44 + 0.012), ['<geom type="box" size="0.08 0.11 0.012" material="book" condim="4"/>'], 0.3)
375
- # In the fridge, on the lowest shelf near its front.
376
  fx = FRIDGE["x0"] + FRIDGE["depth"] - 0.18
377
  shelf = FRIDGE_SHELVES[0] + 0.006
378
- obj("yogurt", (fx, 1.62, shelf + 0.035), [f'<geom type="cylinder" size="0.03 0.035" material="yogurt" {ROUND}/>'], 0.12)
379
- obj("juice_box", (fx, 1.98, shelf + 0.06), ['<geom type="box" size="0.03 0.022 0.06" material="juice_box" condim="4" friction="1.2 0.05 0.01"/>'], 0.2)
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
 
382
  MATERIALS = {
 
383
  "floor": "0.62 0.47 0.33 1", "wall": "0.93 0.91 0.87 1", "tile": "0.9 0.92 0.93 1",
384
  "cabinet": "0.55 0.63 0.57 1", "cabinet_door": "0.58 0.66 0.6 1", "countertop": "0.9 0.89 0.86 1",
385
  "plinth": "0.25 0.25 0.25 1", "steel": "0.75 0.76 0.78 1", "glass": "0.1 0.1 0.12 1",
386
  "fridge": "0.92 0.92 0.93 1", "fridge_inside": "0.95 0.97 1 1", "wood": "0.55 0.38 0.24 1",
387
  "fabric": "0.33 0.38 0.47 1", "rug": "0.72 0.66 0.58 1",
388
- "apple": "0.75 0.1 0.08 1", "orange": "0.95 0.5 0.08 1", "cube": "0.95 0.78 0.1 1", "can": "0.8 0.1 0.15 1",
389
- "mug": "0.2 0.45 0.75 1", "bowl": "0.95 0.95 0.93 1", "plate": "0.97 0.97 0.95 1", "banana": "0.96 0.85 0.3 1",
390
- "cup": "0.3 0.7 0.5 1", "bottle": "0.15 0.45 0.3 1", "book": "0.6 0.15 0.2 1",
391
  # oven, cooktop, hood, glass doors
392
  "oven": "0.2 0.2 0.22 1", "oven_glass": "0.06 0.06 0.08 1", "oven_knob": "0.75 0.76 0.78 1", "burner": "0.3 0.3 0.32 1",
393
  "hood": "0.78 0.79 0.81 1", "cabinet_glass": "0.75 0.86 0.9 0.3",
@@ -398,7 +375,7 @@ MATERIALS = {
398
  "lemon": "0.98 0.9 0.3 1", "cake": "0.98 0.92 0.82 1", "cake_top": "0.85 0.2 0.3 1", "cheese": "0.98 0.82 0.35 1",
399
  "jar_red": "0.75 0.15 0.12 1", "jar_green": "0.35 0.55 0.2 1", "lid": "0.85 0.85 0.86 1", "leftovers": "0.9 0.6 0.35 1",
400
  "water": "0.75 0.88 0.95 0.6", "milk": "0.97 0.97 0.97 1", "milk_top": "0.2 0.45 0.85 1", "juice": "0.98 0.6 0.1 1",
401
- "sauce": "0.55 0.25 0.1 1", "egg": "0.96 0.9 0.8 1", "yogurt": "0.95 0.95 0.98 1", "juice_box": "0.95 0.55 0.1 1",
402
  }
403
 
404
 
 
12
 
13
  from pathlib import Path
14
 
15
+ import objects as objects_ # tools/objects.py
16
+
17
  OUT = Path(__file__).resolve().parents[1] / "assets" / "environments" / "kitchen" / "scene.xml"
18
 
19
  COUNTER_TOP = 0.90 # counter run
 
336
  ])
337
 
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  def objects() -> None:
340
+ """Small objects to pick (tools/objects.py), on the island, the dining table, the counter and in the fridge."""
341
  z = ISLAND_TOP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  fx = FRIDGE["x0"] + FRIDGE["depth"] - 0.18
343
  shelf = FRIDGE_SHELVES[0] + 0.006
344
+ for part in [
345
+ objects_.apple(-0.91, -0.42, z), objects_.orange(-0.91, -0.02, z), objects_.cube(-0.9, 0.42, z),
346
+ # The can and the mug near the island's back edge, where an arm reaches from the corridor behind it.
347
+ objects_.can(-1.43, -0.3, z), objects_.mug(-1.42, 0.35, z),
348
+ # A bowl and a plate to put things in or on. The bowl by the island's edge facing the room: placing
349
+ # reaches it (12 cm in, it was at the arm's limit).
350
+ objects_.bowl(-0.94, 0.2, z), objects_.plate(-0.99, -0.22, z),
351
+ # On the dining table, at the end without chairs where an arm reaches from the floor, and at the
352
+ # front of the counter (its door handles keep the base 6 cm off).
353
+ objects_.banana(0.52, 1.3, 0.75, yaw=1.3), objects_.cup(0.52, 1.62, 0.75), objects_.bottle(-2.41, -0.45, COUNTER_TOP),
354
+ objects_.book(1.15, -0.9, 0.44),
355
+ # In the fridge, on the lowest shelf near its front.
356
+ objects_.yogurt(fx, 1.62, shelf), objects_.juice_box(fx, 1.98, shelf),
357
+ ]:
358
+ lines.extend(part)
359
 
360
 
361
  MATERIALS = {
362
+ **objects_.MATERIALS,
363
  "floor": "0.62 0.47 0.33 1", "wall": "0.93 0.91 0.87 1", "tile": "0.9 0.92 0.93 1",
364
  "cabinet": "0.55 0.63 0.57 1", "cabinet_door": "0.58 0.66 0.6 1", "countertop": "0.9 0.89 0.86 1",
365
  "plinth": "0.25 0.25 0.25 1", "steel": "0.75 0.76 0.78 1", "glass": "0.1 0.1 0.12 1",
366
  "fridge": "0.92 0.92 0.93 1", "fridge_inside": "0.95 0.97 1 1", "wood": "0.55 0.38 0.24 1",
367
  "fabric": "0.33 0.38 0.47 1", "rug": "0.72 0.66 0.58 1",
 
 
 
368
  # oven, cooktop, hood, glass doors
369
  "oven": "0.2 0.2 0.22 1", "oven_glass": "0.06 0.06 0.08 1", "oven_knob": "0.75 0.76 0.78 1", "burner": "0.3 0.3 0.32 1",
370
  "hood": "0.78 0.79 0.81 1", "cabinet_glass": "0.75 0.86 0.9 0.3",
 
375
  "lemon": "0.98 0.9 0.3 1", "cake": "0.98 0.92 0.82 1", "cake_top": "0.85 0.2 0.3 1", "cheese": "0.98 0.82 0.35 1",
376
  "jar_red": "0.75 0.15 0.12 1", "jar_green": "0.35 0.55 0.2 1", "lid": "0.85 0.85 0.86 1", "leftovers": "0.9 0.6 0.35 1",
377
  "water": "0.75 0.88 0.95 0.6", "milk": "0.97 0.97 0.97 1", "milk_top": "0.2 0.45 0.85 1", "juice": "0.98 0.6 0.1 1",
378
+ "sauce": "0.55 0.25 0.1 1", "egg": "0.96 0.9 0.8 1",
379
  }
380
 
381
 
tools/make_tabletop.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write the tabletop environment's objects, assets/environments/tabletop/objects.xml.
2
+
3
+ usage: python tools/make_tabletop.py
4
+
5
+ MuJoCo-GS-Web's tabletop scene is a kitchen: a 3D Gaussian splat over three counters (collision boxes in
6
+ scene.xml, tops at 0.82 m). Its own objects are five coloured blocks and balls dropped in a row. These are
7
+ the kitchen environment's objects instead (tools/objects.py), set out where things stand in a kitchen and
8
+ where the splat shows free worktop (tools/make_decor.py has what stands where):
9
+ - back counter, right of the mini fridge: a bowl with fruit around it, a banana;
10
+ - back counter, in front of the mini fridge: a plate; in front of the tray of bottles: a mug and a glass;
11
+ - right counter, either side of the microwave: a can and a juice carton, a yogurt;
12
+ - left counter, in front of the jars: a bottle of oil and a block.
13
+ Each stands about 6 cm in from its counter's edge, where an arm grasps it comfortably from the floor in
14
+ front; the bowl and the plate a little further in, by their size.
15
+ """
16
+
17
+ from pathlib import Path
18
+
19
+ import objects as o # tools/objects.py
20
+
21
+ OUT = Path(__file__).resolve().parents[1] / "assets" / "environments" / "tabletop" / "objects.xml"
22
+ TOP = 0.82 # counter tops
23
+ BACK = -0.30 # the back counter's edge (y); it runs along x from -1 to 1
24
+ RIGHT = 1.0 # the right counter's edge (x), facing -x
25
+ LEFT = -1.0 # the left counter's edge (x), facing +x
26
+
27
+
28
+ def main() -> None:
29
+ parts = [
30
+ # Back counter. The robot faces -y here: its left arm is on the +x side.
31
+ o.apple(0.20, BACK - 0.06, TOP),
32
+ o.bowl(0.42, BACK - 0.09, TOP),
33
+ o.orange(0.64, BACK - 0.06, TOP),
34
+ o.banana(0.84, BACK - 0.065, TOP, yaw=0.35),
35
+ o.plate(-0.06, BACK - 0.115, TOP), # either arm reaches it, away from the corner
36
+ o.mug(-0.42, BACK - 0.065, TOP, yaw=1.57), # handle toward the room
37
+ o.cup(-0.58, BACK - 0.06, TOP),
38
+ # Right counter.
39
+ o.can(RIGHT + 0.06, -0.16, TOP),
40
+ o.juice_box(RIGHT + 0.06, 0.0, TOP, yaw=0.2),
41
+ o.yogurt(RIGHT + 0.06, 0.74, TOP),
42
+ # Left counter.
43
+ o.bottle(LEFT - 0.07, 0.20, TOP),
44
+ o.cube(LEFT - 0.06, -0.10, TOP, yaw=0.4),
45
+ ]
46
+ used = {line.split('material="')[1].split('"')[0] for part in parts for line in part if 'material="' in line}
47
+ mats = "\n".join(f' <material name="{k}" rgba="{v}"/>' for k, v in o.MATERIALS.items() if k in used)
48
+ body = "\n".join(line for part in parts for line in part)
49
+ xml = f"""<mujoco model="tabletop objects">
50
+ <!-- Written by tools/make_tabletop.py: the kitchen environment's objects on MuJoCo-GS-Web's tabletop counters. -->
51
+ <asset>
52
+ {mats}
53
+ </asset>
54
+
55
+ <worldbody>
56
+ {body}
57
+ </worldbody>
58
+ </mujoco>
59
+ """
60
+ OUT.write_text(xml, encoding="utf-8")
61
+ print(f"wrote {OUT} ({len(parts)} objects, {len(xml) / 1000:.1f} kB)")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
tools/node_env.mjs CHANGED
@@ -36,7 +36,12 @@ function filesUnder(dir, prefix = "") {
36
  return out;
37
  }
38
 
39
- /** Compose and compile `envId` with robot `robotId` (and the robot's objects when the scene asks). */
 
 
 
 
 
40
  export async function loadScene(envId = "tabletop", robotId = "xlerobot", { controlHz = 50, objects } = {}) {
41
  const mujoco = await mujocoModule();
42
  const env = environments().find((e) => e.id === envId);
@@ -44,16 +49,17 @@ export async function loadScene(envId = "tabletop", robotId = "xlerobot", { cont
44
  const meta = robotMeta(robotId);
45
  const robotDir = join(ASSETS, "robots", robotId);
46
  const meshDir = join(robotDir, "assets");
47
- const withObjects = objects ?? env.objects === "robot";
48
  const robot = {
49
  name: robotId,
50
  xml: readFileSync(join(robotDir, meta.xml), "utf8"),
51
  meshes: filesUnder(meshDir).map((f) => [f, readFileSync(join(meshDir, f))]),
52
- objectsXml: withObjects && meta.objects ? readFileSync(join(robotDir, meta.objects), "utf8") : null,
53
  };
54
  const envDir = join(ASSETS, "environments");
55
- const envFiles = [...(env.files ?? []), ...(env.decor ? [env.decor] : [])].map((f) => [f, readFileSync(join(envDir, dirname(env.xml), f))]);
56
- const includes = env.decor ? [env.decor] : [];
 
57
  const path = writeScene(mujoco, "/scene", { xml: readFileSync(join(envDir, env.xml), "utf8"), files: envFiles, includes }, robot, {
58
  modelName: `${envId}_${robotId}`,
59
  });
 
36
  return out;
37
  }
38
 
39
+ /**
40
+ * Compose and compile `envId` with robot `robotId`, with the objects the scene asks for: the robot's
41
+ * ("robot"), its own file, or those in its XML. `objects: "robot"` puts the robot's objects in any scene
42
+ * instead of the scene's own file (the pick policy's demonstrations use MuJoCo-GS-Web's tabletop
43
+ * objects); `objects: "none"` leaves both out.
44
+ */
45
  export async function loadScene(envId = "tabletop", robotId = "xlerobot", { controlHz = 50, objects } = {}) {
46
  const mujoco = await mujocoModule();
47
  const env = environments().find((e) => e.id === envId);
 
49
  const meta = robotMeta(robotId);
50
  const robotDir = join(ASSETS, "robots", robotId);
51
  const meshDir = join(robotDir, "assets");
52
+ const choice = objects ?? (env.objects === "robot" ? "robot" : "scene");
53
  const robot = {
54
  name: robotId,
55
  xml: readFileSync(join(robotDir, meta.xml), "utf8"),
56
  meshes: filesUnder(meshDir).map((f) => [f, readFileSync(join(meshDir, f))]),
57
+ objectsXml: choice === "robot" && meta.objects ? readFileSync(join(robotDir, meta.objects), "utf8") : null,
58
  };
59
  const envDir = join(ASSETS, "environments");
60
+ const ownObjects = choice === "scene" && env.objects?.endsWith(".xml") ? [env.objects] : [];
61
+ const includes = [...(env.decor ? [env.decor] : []), ...ownObjects];
62
+ const envFiles = [...(env.files ?? []), ...includes].map((f) => [f, readFileSync(join(envDir, dirname(env.xml), f))]);
63
  const path = writeScene(mujoco, "/scene", { xml: readFileSync(join(envDir, env.xml), "utf8"), files: envFiles, includes }, robot, {
64
  modelName: `${envId}_${robotId}`,
65
  });
tools/objects.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small objects to pick up, shared by the generated scenes (tools/make_kitchen.py, tools/make_tabletop.py).
2
+
3
+ The same shapes, masses and material names in every scene, so the page's renderers style them alike
4
+ (src/render/materials.js) and the skills grasp them alike. Each function returns the MJCF lines of one
5
+ free body standing (or lying) on a surface at height `z`, turned `yaw` radians about the vertical.
6
+ """
7
+
8
+ import math
9
+
10
+ # Round objects get rolling friction (condim 6): without it a sphere set rolling by the smallest
11
+ # bounce keeps going.
12
+ ROUND = 'condim="6" friction="1.2 0.02 0.002"'
13
+ FLAT = 'condim="4" friction="1.2 0.05 0.01"'
14
+
15
+ MATERIALS = {
16
+ "apple": "0.75 0.1 0.08 1", "orange": "0.95 0.5 0.08 1", "cube": "0.95 0.78 0.1 1", "can": "0.8 0.1 0.15 1",
17
+ "mug": "0.2 0.45 0.75 1", "bowl": "0.95 0.95 0.93 1", "plate": "0.97 0.97 0.95 1", "banana": "0.96 0.85 0.3 1",
18
+ "cup": "0.3 0.7 0.5 1", "bottle": "0.15 0.45 0.3 1", "book": "0.6 0.15 0.2 1",
19
+ "yogurt": "0.95 0.95 0.98 1", "juice_box": "0.95 0.55 0.1 1",
20
+ }
21
+
22
+
23
+ def f(*v: float) -> str:
24
+ return " ".join(f"{x:.4g}" for x in v)
25
+
26
+
27
+ def body(name: str, pos, geoms: list[str], mass: float, yaw: float = 0.0) -> list[str]:
28
+ turn = f' quat="{f(math.cos(yaw / 2), 0, 0, math.sin(yaw / 2))}"' if yaw else ""
29
+ lines = [f' <body name="{name}" pos="{f(*pos)}"{turn}>', " <freejoint/>"]
30
+ for g in geoms:
31
+ lines.append(f' {g.replace("/>", f" mass=\"{mass / len(geoms):.4g}\" contype=\"1\" conaffinity=\"1\"/>")}')
32
+ lines.append(" </body>")
33
+ return lines
34
+
35
+
36
+ def apple(x, y, z, yaw=0.0, name="apple"):
37
+ return body(name, (x, y, z + 0.025), [f'<geom type="sphere" size="0.025" material="apple" {ROUND}/>'], 0.08, yaw)
38
+
39
+
40
+ def orange(x, y, z, yaw=0.0, name="orange"):
41
+ return body(name, (x, y, z + 0.024), [f'<geom type="sphere" size="0.024" material="orange" {ROUND}/>'], 0.07, yaw)
42
+
43
+
44
+ def cube(x, y, z, yaw=0.0, name="cube"):
45
+ return body(name, (x, y, z + 0.02), [f'<geom type="box" size="0.02 0.02 0.02" material="cube" {FLAT}/>'], 0.04, yaw)
46
+
47
+
48
+ def can(x, y, z, yaw=0.0, name="can"):
49
+ return body(name, (x, y, z + 0.045), [f'<geom type="cylinder" size="0.025 0.045" material="can" {ROUND}/>'], 0.06, yaw)
50
+
51
+
52
+ def mug(x, y, z, yaw=0.0, name="mug"):
53
+ """A mug with its handle toward `yaw`."""
54
+ return body(name, (x, y, z + 0.04), [
55
+ f'<geom type="cylinder" size="0.03 0.04" material="mug" {FLAT}/>',
56
+ f'<geom type="box" pos="0.038 0 0" size="0.008 0.004 0.025" material="mug" {FLAT}/>',
57
+ ], 0.09, yaw)
58
+
59
+
60
+ def bowl(x, y, z, yaw=0.0, name="bowl"):
61
+ """A bowl to put things in: a base and a ring of ten wall segments; too wide to pick up."""
62
+ ring = []
63
+ for k in range(10):
64
+ a = 2 * math.pi * k / 10
65
+ ring.append(f'<geom type="box" pos="{f(0.062 * math.cos(a), 0.062 * math.sin(a), 0.028)}" euler="0 0 {a:.4f}" size="0.006 0.021 0.022" material="bowl" condim="4"/>')
66
+ return body(name, (x, y, z + 0.003), ['<geom type="cylinder" pos="0 0 0.004" size="0.05 0.004" material="bowl" condim="4"/>', *ring], 0.3, yaw)
67
+
68
+
69
+ def plate(x, y, z, yaw=0.0, name="plate"):
70
+ """A plate to put things on; too wide to pick up."""
71
+ return body(name, (x, y, z + 0.01), ['<geom type="cylinder" size="0.1 0.006" material="plate" condim="4"/>'], 0.25, yaw)
72
+
73
+
74
+ def banana(x, y, z, yaw=0.0, name="banana"):
75
+ """A banana lying along `yaw`."""
76
+ return body(name, (x, y, z + 0.017), [f'<geom type="capsule" fromto="-0.06 0 0 0.06 0.012 0" size="0.017" material="banana" {ROUND}/>'], 0.1, yaw)
77
+
78
+
79
+ def cup(x, y, z, yaw=0.0, name="cup"):
80
+ return body(name, (x, y, z + 0.045), [f'<geom type="cylinder" size="0.03 0.045" material="cup" {ROUND}/>'], 0.06, yaw)
81
+
82
+
83
+ def bottle(x, y, z, yaw=0.0, name="bottle"):
84
+ return body(name, (x, y, z + 0.085), [f'<geom type="cylinder" size="0.03 0.085" material="bottle" {ROUND}/>'], 0.2, yaw)
85
+
86
+
87
+ def book(x, y, z, yaw=0.0, name="book"):
88
+ return body(name, (x, y, z + 0.012), ['<geom type="box" size="0.08 0.11 0.012" material="book" condim="4"/>'], 0.3, yaw)
89
+
90
+
91
+ def yogurt(x, y, z, yaw=0.0, name="yogurt"):
92
+ return body(name, (x, y, z + 0.035), [f'<geom type="cylinder" size="0.03 0.035" material="yogurt" {ROUND}/>'], 0.12, yaw)
93
+
94
+
95
+ def juice_box(x, y, z, yaw=0.0, name="juice_box"):
96
+ """A juice carton, its wide side along `yaw`."""
97
+ return body(name, (x, y, z + 0.06), [f'<geom type="box" size="0.03 0.022 0.06" material="juice_box" {FLAT}/>'], 0.2, yaw)
tools/pick_layout.mjs CHANGED
@@ -7,9 +7,12 @@ export const TABLE = { edgeY: -0.3, topZ: 0.82 }; // tabletop scene, table2
7
  export const OBJECTS = ["sphere1", "sphere2", "box1", "cylinder1"]; // box2 is wider than the gripper opens
8
  const SPARE_SPOTS = [[-1.25, -0.5], [-1.25, -0.2], [-1.25, 0.1], [-1.25, 0.4], [-1.45, 0.0]]; // on the far table
9
 
10
- /** Load the tabletop scene, let its objects settle and return {sim, robot, layout(rng)}. */
 
 
 
11
  export async function pickScene() {
12
- const { sim, robot } = await loadScene("tabletop");
13
  const control = () => robot.update();
14
  sim.reset(() => robot.home());
15
  sim.run(1.5, control);
 
7
  export const OBJECTS = ["sphere1", "sphere2", "box1", "cylinder1"]; // box2 is wider than the gripper opens
8
  const SPARE_SPOTS = [[-1.25, -0.5], [-1.25, -0.2], [-1.25, 0.1], [-1.25, 0.4], [-1.45, 0.0]]; // on the far table
9
 
10
+ /**
11
+ * Load the tabletop scene with MuJoCo-GS-Web's objects (the blocks and balls the pick policy was trained
12
+ * on, not the scene's kitchen objects), let them settle and return {sim, robot, layout(rng)}.
13
+ */
14
  export async function pickScene() {
15
+ const { sim, robot } = await loadScene("tabletop", "xlerobot", { objects: "robot" });
16
  const control = () => robot.update();
17
  sim.reset(() => robot.home());
18
  sim.run(1.5, control);