Edgar Moreau commited on
Commit
49ef597
·
verified ·
1 Parent(s): 11c954b

Clear the playroom: cablepilot world model + MPPI in the browser

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ thumbnail.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,10 +1,64 @@
1
  ---
2
- title: Clear The Playroom
3
- emoji: 🏆
4
- colorFrom: red
5
- colorTo: pink
6
  sdk: static
7
- pinned: false
 
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Clear the Playroom
3
+ emoji: 🦢
4
+ colorFrom: yellow
5
+ colorTo: green
6
  sdk: static
7
+ pinned: true
8
+ license: apache-2.0
9
+ short_description: A cable robot plans with a 28k-param world model, live
10
+ thumbnail: https://huggingface.co/spaces/MacroSwan/clear-the-playroom/resolve/main/thumbnail.png
11
+ tags:
12
+ - robotics
13
+ - world-model
14
+ - model-predictive-control
15
+ - mppi
16
+ - cable-robot
17
+ - embodied-ai
18
  ---
19
 
20
+ # Clear the playroom
21
+
22
+ A cable robot hangs from four lines in a playroom. Every 0.2 s it imagines 128 futures with a small learned world model
23
+ and follows the cheapest. **Furniture is only a cost**: drag it around and watch the plans bend.
24
+
25
+ - **Click the floor** to drop a toy. The robot flies over it, reaches down, grabs it and drops it in the hamper.
26
+ - **Drag furniture**, resize it, or add more. Purple patches on the floor are **line shadows**: places a cable would
27
+ have to cut through furniture to reach, so the robot cannot pick there. Push a tall shelf around and watch them move.
28
+ - **Watch it think**: the ember line is the plan it chose, the green lines are the best futures it imagined, and the
29
+ panel shows what each decision costs (milliseconds, futures per CPU-second, CPU-seconds per toy) and which cost
30
+ terms shaped the plan.
31
+
32
+ Everything runs in your browser on one CPU thread. There is no server and no GPU.
33
+
34
+ ## What is real here
35
+
36
+ | | |
37
+ |---|---|
38
+ | **World model** | The released [MacroSwan/cablepilot](https://huggingface.co/MacroSwan/cablepilot) model: 28,401 parameters, trained on our own simulated motion ([MacroSwan/cablepilot-motion](https://huggingface.co/datasets/MacroSwan/cablepilot-motion)), ported to JavaScript. It matches PyTorch to 0.0005 mm (`tools/test.mjs`). |
39
+ | **Planner** | MPPI, ported from `cablepilot/planner/mppi.py` with the same settings. |
40
+ | **Furniture** | Reaches the planner only as costs: clearance of spheres down the robot's pole and of points along the four lines, as in `cablepilot/roommap/costs.py`. |
41
+ | **Robot** | Simulated by the same world model plus noise. Against the MuJoCo twin the model is off by about 2 cm over 2 s, and a real robot would differ more. |
42
+ | **Room** | Fictional: 4.6 × 4.0 m, line anchors in the corners at about 2.5 m. The floor is drawn in code. |
43
+
44
+ Grasping is a distance test, not contact physics.
45
+
46
+ ## Files
47
+
48
+ | file | what |
49
+ |---|---|
50
+ | `core/model.js` | the world model in plain JS |
51
+ | `core/mppi.js` | MPPI |
52
+ | `core/mission.js` | the room, furniture costs, the line-shadow map, the pick and carry phases, the simulated robot |
53
+ | `worker.js` | runs the robot's brain off the page's thread |
54
+ | `main.js`, `index.html`, `style.css` | the 3D page (three.js r170, vendored) |
55
+ | `tools/export_model.py` | the cablepilot weights → `core/model.json`, plus PyTorch test fixtures |
56
+ | `tools/test.mjs` | the JS model against PyTorch |
57
+ | `tools/run_headless.mjs` | the whole mission in node: 5/5 toys, 0 furniture contacts, about 210 s of robot time |
58
+
59
+ ```bash
60
+ node tools/test.mjs && node tools/run_headless.mjs 400
61
+ python3 -m http.server 8767 # then http://127.0.0.1:8767/?autorun&speed=4&follow
62
+ ```
63
+
64
+ Part of [MacroSwan](https://huggingface.co/MacroSwan): small world models and planning, with their compute bill.
core/mission.js ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The mission: a fictional MacroSwan playroom (4.6 x 4.0 m, line anchors in its corners at ~2.5 m, inside the range of
2
+ // random rooms the world model was trained on), furniture the visitor moves, toys the visitor drops, and a toy hamper. Furniture reaches the planner ONLY as costs, as in
3
+ // cablepilot/roommap/costs.py: clearance of spheres down the robot's pole and of points along the four lines, from
4
+ // boxes. The phases are a slim version of cablepilot/tasks/pick_place.py.
5
+
6
+ import { rollout as wmRollout } from "./model.js";
7
+ import { MPPI, PLANNER, rng } from "./mppi.js";
8
+
9
+ export const ROOM = {
10
+ name: "MacroSwan playroom (fictional)",
11
+ size: [4.6, 4.0], // walls: x in [-2.3, 2.3], y in [-2.0, 2.0]
12
+ mounts: [[2.22, 1.92, 2.52], [-2.22, 1.92, 2.48], [-2.22, -1.92, 2.55], [2.22, -1.92, 2.50]], // corners, CCW
13
+ hamper: [-1.2, -0.95], parking: [1.15, 0.85],
14
+ floor: { extent: 5.0 },
15
+ };
16
+ export const HAMPER = { half: 0.2, height: 0.40 }; // a laundry hamper's opening (clear_playroom.yaml)
17
+ export const DEFAULT_FURNITURE = [ // boxes {x, y, hx, hy, h}
18
+ { id: "shelf", label: "Toy shelf", x: 0.55, y: 1.72, hx: 0.6, hy: 0.18, h: 1.2 },
19
+ { id: "table", label: "Play table", x: 0.95, y: -0.85, hx: 0.35, hy: 0.35, h: 0.55 },
20
+ { id: "armchair", label: "Armchair", x: -1.55, y: 0.85, hx: 0.4, hy: 0.4, h: 0.9 },
21
+ ];
22
+ export const DEFAULT_TOYS = [[-0.4, 0.6], [0.3, 0.45], [-0.2, -0.3], [0.5, 0.0], [-0.6, -0.9]];
23
+
24
+ const DG = -0.5147; // grasp point below the gantry along the pole (stringman.yaml body numbers)
25
+ const SPHERES = [ // [d along the pole, radius] (roommap/costs.robot_spheres): gantry, pole, gripper, fingers
26
+ [-0.037, 0.085], [-0.09, 0.012], [-0.17, 0.012], [-0.25, 0.012], [-0.329, 0.012], [-0.3907, 0.075], [-0.4547, 0.045]];
27
+ const W = { goal: 4, swing: 0.05, swingCarry: 0.3, walls: 5, floor: 5, furniture: 5, lines: 5, height: 5 };
28
+ const P = { huber: 0.05, tw0: 0.3, terminal: 3, wallMargin: 0.25, robotClear: 0.03, lineClear: 0.07, lineN: 14,
29
+ lineSkip: 0.3, zMax: 2.2, lead: 0.45, toyZ: 0.02, aboveTop: 0.30, carryZ: HAMPER.height + 0.14, carryHighZ: HAMPER.height + 0.30 };
30
+
31
+ // ------------------------------------------------------------------------------------------- geometry
32
+ const poly = (() => { // the mount polygon, CCW, for "inside the room" distance
33
+ const c = ROOM.mounts.reduce((a, m) => [a[0] + m[0] / 4, a[1] + m[1] / 4], [0, 0]);
34
+ return ROOM.mounts.map(m => [m[0], m[1]]).sort((a, b) => Math.atan2(a[1] - c[1], a[0] - c[0]) - Math.atan2(b[1] - c[1], b[0] - c[0]));
35
+ })();
36
+ export function insideDistance(x, y) {
37
+ let best = Infinity;
38
+ for (let i = 0; i < poly.length; i++) {
39
+ const a = poly[i], b = poly[(i + 1) % poly.length], ex = b[0] - a[0], ey = b[1] - a[1], l = Math.hypot(ex, ey);
40
+ best = Math.min(best, ((x - a[0]) * -ey + (y - a[1]) * ex) / l);
41
+ }
42
+ return best;
43
+ }
44
+ export const REACH_MARGIN = 0.35;
45
+
46
+ function boxSdf(b, x, y, z) { // box from the floor to height h
47
+ const qx = Math.abs(x - b.x) - b.hx, qy = Math.abs(y - b.y) - b.hy, qz = Math.abs(z - b.h / 2) - b.h / 2;
48
+ const ox = Math.max(qx, 0), oy = Math.max(qy, 0), oz = Math.max(qz, 0);
49
+ return Math.hypot(ox, oy, oz) + Math.min(Math.max(qx, qy, qz), 0);
50
+ }
51
+ function sdf(boxes, x, y, z) { let d = 9; for (const b of boxes) d = Math.min(d, boxSdf(b, x, y, z)); return d; }
52
+
53
+ function hamperBoxes() { // the hamper's four walls (runner.obstacles does the same for the bin)
54
+ const [bx, by] = ROOM.hamper, i = HAMPER.half, t = 0.02, h = HAMPER.height;
55
+ return [{ x: bx + i + t / 2, y: by, hx: t / 2, hy: i + t, h }, { x: bx - i - t / 2, y: by, hx: t / 2, hy: i + t, h },
56
+ { x: bx, y: by + i + t / 2, hx: i, hy: t / 2, h }, { x: bx, y: by - i - t / 2, hx: i, hy: t / 2, h }];
57
+ }
58
+
59
+ export function axis(x, o = 0) { // pole axis (up) from the swing
60
+ const sx = x[o + 6], sy = x[o + 7], sz = Math.sqrt(Math.max(1e-6, 1 - sx * sx - sy * sy));
61
+ return [sx, sy, sz];
62
+ }
63
+ export function grasp(x, o = 0) { const a = axis(x, o); return [x[o] + DG * a[0], x[o + 1] + DG * a[1], x[o + 2] + DG * a[2]]; }
64
+ const huber = (d, k) => (d < k ? 0.5 * d * d / k : d - 0.5 * k);
65
+
66
+ // ------------------------------------------------------------------------------------------- where the hand can reach the floor
67
+ /** Why the hand cannot pick at (x, y) from the floor, or null. Checked with the gantry straight above the toy (grasp
68
+ * point at toy height): the hand must clear the furniture, and every line from its mount must clear it too. The
69
+ * last one is the cable robot's own constraint: furniture casts a "line shadow" on the floor. */
70
+ export function reachWhy(furniture, x, y) {
71
+ if (insideDistance(x, y) < REACH_MARGIN) return { code: "wall", text: "too close to a wall: the lines cannot pull the hand there" };
72
+ if (Math.hypot(x - ROOM.hamper[0], y - ROOM.hamper[1]) < HAMPER.half + 0.15) return { code: "hamper", text: "that is the hamper" };
73
+ if (sdf(furniture, x, y, 0.01) < 0.10) return { code: "furniture", text: "under or against furniture: the hand cannot get down there" };
74
+ const pz = P.toyZ - DG;
75
+ for (const M of ROOM.mounts) {
76
+ const dx = x - M[0], dy = y - M[1], dz = pz - M[2], L = Math.hypot(dx, dy, dz);
77
+ for (let i = 0; i <= 24; i++) {
78
+ const f = P.lineSkip / L + (1 - P.lineSkip / L - 0.08 / L) * i / 24;
79
+ if (sdf(furniture, M[0] + f * dx, M[1] + f * dy, M[2] + f * dz) < P.lineClear * 0.6)
80
+ return { code: "shadow", text: "in a line shadow: a cable to that spot would cut through furniture" };
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+ /** n x n grid over the 5 m floor image: 0 reachable, 1 wall, 2 furniture/hamper, 3 line shadow (row 0 = +y edge). */
86
+ export function reachMap(furniture, n = 100) {
87
+ const e = ROOM.floor.extent, out = new Uint8Array(n * n), code = { wall: 1, hamper: 2, furniture: 2, shadow: 3 };
88
+ for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
89
+ const x = ((c + 0.5) / n - 0.5) * e, y = (0.5 - (r + 0.5) / n) * e, w = reachWhy(furniture, x, y);
90
+ out[r * n + c] = w ? code[w.code] : 0;
91
+ }
92
+ return out;
93
+ }
94
+
95
+ // ------------------------------------------------------------------------------------------- the mission
96
+ export const PHASES = ["above", "descend", "close", "lift", "carry", "lower", "release", "park", "idle"];
97
+ const LABEL = { above: "flying over the toy", descend: "reaching down", close: "closing the fingers", lift: "lifting",
98
+ carry: "carrying to the hamper", lower: "lowering into the hamper", release: "dropping it in", park: "parking", idle: "waiting for toys" };
99
+
100
+ export class Mission {
101
+ constructor(model, seed = 0) {
102
+ this.m = model; this.seed = seed;
103
+ this.furniture = DEFAULT_FURNITURE.map(f => ({ ...f }));
104
+ this.toys = DEFAULT_TOYS.map(([x, y], i) => ({ id: i + 1, x, y, z: P.toyZ, state: "floor" }));
105
+ this.nextId = this.toys.length + 1;
106
+ this.reset();
107
+ }
108
+
109
+ reset() {
110
+ const x = new Float32Array(14);
111
+ x[0] = ROOM.parking[0]; x[1] = ROOM.parking[1]; x[2] = this.parkZ() - DG;
112
+ this.x = x; this.cmd = [0, 0, 0, 0, 0];
113
+ this.hist = Array.from({ length: this.m.H + 1 }, () => Float32Array.from(x));
114
+ this.chist = Array.from({ length: this.m.H }, () => this.cmd.slice());
115
+ this.mppi = new MPPI(PLANNER, this.seed);
116
+ this.t = 0; this.phase = "idle"; this.phaseT = 0; this.target = null; this.held = null;
117
+ this.stats = { plans: 0, planMs: 0, delivered: 0, contacts: 0, events: [] };
118
+ for (const t of this.toys) if (t.state !== "floor") { t.state = "floor"; t.z = P.toyZ; }
119
+ this.noise = rng(this.seed + 7);
120
+ }
121
+
122
+ // ---- edits from the page
123
+ setFurniture(list) { this.furniture = list.map(f => ({ ...f })); }
124
+ addToy(x, y) {
125
+ const why = this.placeable(x, y);
126
+ if (why) return { ok: false, why: why.text };
127
+ this.toys.push({ id: this.nextId++, x, y, z: P.toyZ, state: "floor" });
128
+ return { ok: true };
129
+ }
130
+ removeToy(id) { if (this.target && this.target.id === id) return; this.toys = this.toys.filter(t => t.id !== id); }
131
+ placeable(x, y) { return reachWhy(this.furniture, x, y); }
132
+ reachMap(n = 100) { return reachMap(this.furniture, n); }
133
+
134
+ // ---- what the planner should do now
135
+ /** On long moves the planner chases a carrot at most P.lead ahead of the hand, not the far target (pick_place's carry
136
+ * funnel does the same job): far goals make it sprint, and a sprinting cable robot swings. */
137
+ goal() {
138
+ const g = this.rawGoal();
139
+ if (!["above", "carry", "park"].includes(this.phase)) return g;
140
+ const G = grasp(this.x), dx = g[0] - G[0], dy = g[1] - G[1], d = Math.hypot(dx, dy);
141
+ if (d <= P.lead) return g;
142
+ return [G[0] + dx / d * P.lead, G[1] + dy / d * P.lead, g[2]];
143
+ }
144
+ rawGoal() {
145
+ const t = this.target, hz = this.maxTop() + P.aboveTop;
146
+ switch (this.phase) {
147
+ case "above": return [t.x, t.y, Math.max(0.35, Math.min(hz, 0.55))];
148
+ case "descend": case "close": return [t.x, t.y, P.toyZ];
149
+ case "lift": return [t.x, t.y, Math.max(0.45, Math.min(hz, 0.7))];
150
+ case "carry": return [ROOM.hamper[0], ROOM.hamper[1], P.carryHighZ];
151
+ case "lower": case "release": return [ROOM.hamper[0], ROOM.hamper[1], P.carryZ];
152
+ default: return [ROOM.parking[0], ROOM.parking[1], this.parkZ()];
153
+ }
154
+ }
155
+ parkZ() { return Math.max(0.8, this.maxTop() + 0.35); }
156
+ maxTop() { return this.furniture.reduce((a, f) => Math.max(a, f.h), HAMPER.height); }
157
+ fixed() {
158
+ const close = ["close", "lift", "carry", "lower"].includes(this.phase) ? 1 : 0;
159
+ return { 3: 0, 4: close };
160
+ }
161
+
162
+ // ---- the task's cost on imagined futures (S x T x 14)
163
+ cost(states, S) {
164
+ const T = PLANNER.horizon, goal = this.goal(), boxes = this.furniture.concat(hamperBoxes());
165
+ const zcap = this.maxTop() + P.lineClear, ws = ["carry", "lower", "release"].includes(this.phase) ? W.swingCarry : W.swing;
166
+ const J = new Float64Array(S), terms = { goal: 0, furniture: 0, lines: 0, walls: 0, swing: 0, floor: 0 };
167
+ const sw2 = (2 * Math.PI / 180) ** 2, nearFloor = this.phase === "descend" || this.phase === "close";
168
+ for (let s = 0; s < S; s++) {
169
+ let j = 0;
170
+ for (let k = 0; k < T; k++) {
171
+ const o = (s * T + k) * 14, a = axis(states, o), px = states[o], py = states[o + 1], pz = states[o + 2];
172
+ const gx = px + DG * a[0], gy = py + DG * a[1], gz = pz + DG * a[2];
173
+ let tw = P.tw0 + (1 - P.tw0) * k / (T - 1); if (k === T - 1) tw *= P.terminal;
174
+ const cg = W.goal * huber(Math.hypot(gx - goal[0], gy - goal[1], gz - goal[2]), P.huber) / P.huber * tw;
175
+ const csw = ws * (states[o + 8] ** 2 + states[o + 9] ** 2) / sw2;
176
+ const cw = W.walls * (Math.max(0, P.wallMargin - insideDistance(gx, gy)) / 0.02) ** 2;
177
+ const cf = W.floor * (Math.max(0, -0.005 - gz) / 0.01) ** 2 + W.height * (Math.max(0, pz - P.zMax) / 0.02) ** 2;
178
+ // furniture: spheres down the pole (the hand may touch the floor near a toy, not the furniture)
179
+ let cr = 0;
180
+ for (const [d, r] of SPHERES) {
181
+ const c = sdf(boxes, px + d * a[0], py + d * a[1], pz + d * a[2]);
182
+ const v = Math.max(0, P.robotClear + r - c) / 0.02; cr += v * v;
183
+ }
184
+ const cpad = sdf(boxes, gx, gy, gz); cr += (Math.max(0, (nearFloor ? 0.005 : 0.02) - cpad) / 0.02) ** 2;
185
+ // the four lines, below the tallest thing in the room only
186
+ let cl = 0;
187
+ for (const M of ROOM.mounts) {
188
+ const dx = px - M[0], dy = py - M[1], dz = pz - M[2], L = Math.hypot(dx, dy, dz);
189
+ let f0 = Math.min(0.9, P.lineSkip / L); const f1 = 1 - 0.08 / L;
190
+ f0 = Math.max(f0, Math.min(0.95, Math.max(0, (M[2] - zcap) / Math.max(1e-3, -dz))));
191
+ for (let i = 0; i < P.lineN; i++) {
192
+ const f = f0 + (f1 - f0) * i / (P.lineN - 1);
193
+ const c = sdf(boxes, M[0] + f * dx, M[1] + f * dy, M[2] + f * dz);
194
+ const v = Math.max(0, P.lineClear - c) / 0.02; cl += v * v;
195
+ }
196
+ }
197
+ cr *= W.furniture; cl *= W.lines;
198
+ j += cg + csw + cw + cf + cr + cl;
199
+ if (s === 0) { terms.goal += cg; terms.furniture += cr; terms.lines += cl; terms.walls += cw; terms.swing += csw; terms.floor += cf; }
200
+ }
201
+ J[s] = j;
202
+ }
203
+ return { J, terms };
204
+ }
205
+
206
+ // ---- one planner tick (0.2 s): plan, then the plant moves 2 model steps, then events
207
+ step() {
208
+ if (this.phase === "idle" || this.phase === "park") this.pickNext();
209
+ const M = ROOM.mounts, m = this.m;
210
+ const rollFn = (plans, S) => wmRollout(m, M, this.hist, this.chist, plans, S, PLANNER.horizon, 2);
211
+ const { action, info } = this.mppi.plan(rollFn, (st, _p, S) => this.cost(st, S), this.cmd, this.fixed());
212
+ this.stats.plans++; this.stats.planMs += info.ms.total;
213
+ // the robot: simulated by the same world model, one 0.1 s step at a time, plus noise on the swing and the gantry
214
+ // (in cablepilot the robot is the MuJoCo twin; the model tracks it to ~2 cm over 2 s, test 1)
215
+ const two = Float32Array.from([...action, ...action]);
216
+ const nxt = wmRollout(m, M, this.hist, this.chist, two, 1, 2, 1);
217
+ for (let k = 0; k < 2; k++) {
218
+ const xk = Float32Array.from(nxt.subarray(k * 14, (k + 1) * 14));
219
+ for (let i = 0; i < 2; i++) xk[8 + i] += 0.004 * this.noise.n();
220
+ for (let i = 0; i < 3; i++) xk[3 + i] += 0.002 * this.noise.n();
221
+ this.hist.push(xk); this.hist.shift();
222
+ this.chist.push(action.slice()); this.chist.shift();
223
+ }
224
+ this.x = Float32Array.from(this.hist[this.hist.length - 1]);
225
+ this.cmd = action; this.t += 0.2; this.phaseT += 0.2;
226
+ const G = grasp(this.x);
227
+ if (this.held) { this.held.x = G[0]; this.held.y = G[1]; this.held.z = G[2] - 0.02; }
228
+ // contact check on the TRUE state (the score; the planner never sees it)
229
+ const boxes = this.furniture.concat(hamperBoxes());
230
+ let touch = false;
231
+ for (const [d, r] of SPHERES) { const a = axis(this.x); if (sdf(boxes, this.x[0] + d * a[0], this.x[1] + d * a[1], this.x[2] + d * a[2]) < r) touch = true; }
232
+ if (touch) this.stats.contacts++;
233
+ this.events(G);
234
+ return this.frame(info);
235
+ }
236
+
237
+ pickNext() {
238
+ const floor = this.toys.filter(t => t.state === "floor" && !this.placeable(t.x, t.y));
239
+ if (!floor.length) { if (this.phase !== "park" && this.phase !== "idle") this.go("park"); else if (this.phase === "idle") this.phase = "park"; return; }
240
+ const G = grasp(this.x);
241
+ floor.sort((a, b) => Math.hypot(a.x - G[0], a.y - G[1]) - Math.hypot(b.x - G[0], b.y - G[1]));
242
+ this.target = floor[0]; this.target.state = "target"; this.go("above");
243
+ }
244
+
245
+ go(ph, why) {
246
+ this.phase = ph; this.phaseT = 0;
247
+ if (why) { this.stats.events.push({ t: +this.t.toFixed(1), what: why }); if (this.stats.events.length > 30) this.stats.events.shift(); }
248
+ }
249
+
250
+ events(G) {
251
+ const g = this.rawGoal(), v = Math.hypot(this.x[3], this.x[4], this.x[5]);
252
+ const dxy = Math.hypot(G[0] - g[0], G[1] - g[1]), dz = Math.abs(G[2] - g[2]);
253
+ const swing = Math.hypot(this.x[8], this.x[9]) * 180 / Math.PI;
254
+ const t = this.target;
255
+ if (t && this.placeable(t.x, t.y) && !this.held) { // the visitor moved furniture onto it
256
+ t.state = "floor"; this.target = null; this.go("idle", `toy ${t.id} skipped: ${this.placeable(t.x, t.y).text}`); return;
257
+ }
258
+ switch (this.phase) {
259
+ case "above": if (dxy < 0.05 && dz < 0.08) this.go("descend", `over toy ${t.id}`); break;
260
+ case "descend": if (dxy < 0.025 && dz < 0.02 && v < 0.06) this.go("close", `reached toy ${t.id}`); break;
261
+ case "close": if (this.x[12] > 0.85) {
262
+ if (Math.hypot(G[0] - t.x, G[1] - t.y) < 0.04) { this.held = t; t.state = "held"; this.go("lift", `grabbed toy ${t.id}`); }
263
+ else this.go("above", `missed toy ${t.id}, trying again`);
264
+ } break;
265
+ case "lift": if (dz < 0.05) this.go("carry", "lifted"); break;
266
+ case "carry": if (dxy < 0.06 && dz < 0.08 && swing < 6) this.go("lower", "over the hamper"); break;
267
+ case "lower": if (dxy < 0.04 && dz < 0.03 && swing < 5) this.go("release", "inside the rim"); break;
268
+ case "release": if (this.x[12] < 0.2) {
269
+ const h = this.held; h.state = "delivered"; h.x = ROOM.hamper[0] + (Math.random() - 0.5) * 0.2;
270
+ h.y = ROOM.hamper[1] + (Math.random() - 0.5) * 0.2; h.z = 0.05; this.held = null; this.target = null;
271
+ this.stats.delivered++; this.go("idle", `toy ${h.id} in the hamper (${this.t.toFixed(0)} s)`);
272
+ } break;
273
+ case "park": if (dxy < 0.08) this.go("idle"); break;
274
+ }
275
+ if (this.phase !== "park" && this.phase !== "idle" && this.phaseT > 45 && t) {
276
+ t.state = "floor"; if (this.held) { this.held = null; t.z = P.toyZ; }
277
+ this.target = null; this.go("idle", `gave up on toy ${t.id} after 45 s`);
278
+ }
279
+ }
280
+
281
+ frame(info) {
282
+ const T = PLANNER.horizon, gpath = st => { const out = []; for (let k = 0; k < T; k++) out.push(grasp(st, k * 14)); return out; };
283
+ return {
284
+ t: this.t, x: Array.from(this.x), cmd: this.cmd, phase: this.phase, label: LABEL[this.phase],
285
+ goal: this.goal(), target: this.target ? this.target.id : null,
286
+ nominal: info ? gpath(info.nominal) : [], rollouts: info ? info.rollouts.map(gpath) : [],
287
+ ess: info ? info.ess : 0, ms: info ? info.ms : null, terms: info ? info.terms : null,
288
+ toys: this.toys.map(t => ({ ...t })), furniture: this.furniture,
289
+ stats: { ...this.stats, events: this.stats.events.slice(-8), msPerPlan: this.stats.planMs / Math.max(1, this.stats.plans) },
290
+ };
291
+ }
292
+ }
core/model.js ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // cablepilot's world model (the released 28k-parameter model) in plain JS. A line-by-line port of
2
+ // cablepilot/model/learned.py: room-free features -> causal TCN encoders -> GRU latent unroll (the JEPA), then the
3
+ // prober reads each predicted latent and sets the coefficients of the hand-written physics, integrated 4 substeps per
4
+ // 0.1 s model step. Checked against PyTorch by tools/test.mjs.
5
+ //
6
+ // State x (14): p(3) v(3) swing s(2) s_dot(2) wrist wrist_dot close close_dot. Action (5): vx vy vz wrist_rate closure.
7
+
8
+ export const STATE_DIM = 14, ACTION_DIM = 5, FEAT_DIM = 28;
9
+ const G = 9.81;
10
+
11
+ // ---------------------------------------------------------------- small dense helpers (row-major nested arrays -> flat)
12
+ function flat(w) { return Float32Array.from(w.flat(Infinity)); }
13
+
14
+ function conv(w, b) { // Conv1d weight (out, in, k)
15
+ return { W: flat(w), b: Float32Array.from(b), out: w.length, cin: w[0].length, k: w[0][0].length };
16
+ }
17
+ function lin(w, b) { // Linear weight (out, in)
18
+ return { W: flat(w), b: b ? Float32Array.from(b) : new Float32Array(w.length), out: w.length, cin: w[0].length };
19
+ }
20
+ function linApply(L, x, xo, y) { // y = W x + b ; x read from offset xo
21
+ const { W, b, out, cin } = L;
22
+ for (let o = 0; o < out; o++) {
23
+ let s = b[o]; const r = o * cin;
24
+ for (let i = 0; i < cin; i++) s += W[r + i] * x[xo + i];
25
+ y[o] = s;
26
+ }
27
+ return y;
28
+ }
29
+
30
+ // causal TCN over a sequence: seq (len * cin) -> (len * out)
31
+ function tcnApply(T, seq, len) {
32
+ let cur = seq, c = T.layers[0].cin;
33
+ for (let li = 0; li < T.layers.length; li++) {
34
+ const L = T.layers[li];
35
+ const nxt = new Float32Array(len * L.out);
36
+ for (let t = 0; t < len; t++) {
37
+ for (let o = 0; o < L.out; o++) {
38
+ let s = L.b[o];
39
+ for (let j = 0; j < L.k; j++) {
40
+ const tt = t - (L.k - 1) + j; // left padding: causal
41
+ if (tt < 0) continue;
42
+ const wr = (o * L.cin) * L.k + j;
43
+ for (let i = 0; i < L.cin; i++) s += L.W[wr + i * L.k] * cur[tt * c + i];
44
+ }
45
+ nxt[t * L.out + o] = s > 0 ? s : 0; // ReLU after every hidden conv
46
+ }
47
+ }
48
+ cur = nxt; c = L.out;
49
+ }
50
+ const R = T.readout, out = new Float32Array(len * R.out);
51
+ for (let t = 0; t < len; t++)
52
+ for (let o = 0; o < R.out; o++) {
53
+ let s = R.b[o];
54
+ for (let i = 0; i < R.cin; i++) s += R.W[o * R.cin + i] * cur[t * c + i];
55
+ out[t * R.out + o] = s;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ function makeTCN(sd, prefix) {
61
+ const layers = [];
62
+ for (let i = 0; ; i += 2) {
63
+ const k = `${prefix}.tcn.${i}.conv.weight`;
64
+ if (!(k in sd)) break;
65
+ layers.push(conv(sd[k], sd[`${prefix}.tcn.${i}.conv.bias`]));
66
+ }
67
+ const rw = sd[`${prefix}.readout.weight`];
68
+ return { layers, readout: lin(rw.map(r => r.map(c => c[0])), sd[`${prefix}.readout.bias`]) };
69
+ }
70
+
71
+ const sig = x => 1 / (1 + Math.exp(-x));
72
+
73
+ // ---------------------------------------------------------------- the model
74
+ export function loadModel(json) {
75
+ const c = json.config, J = json.jepa, P = json.prober, N = json.norm;
76
+ const m = {
77
+ cfg: c, H: c.H, dtModel: c.dt, latent: c.latent, hidden: c.hidden,
78
+ stateEnc: makeTCN(J, "state_enc"), actionEnc: makeTCN(J, "action_enc"),
79
+ Wih: lin(J["cell.weight_ih"], J["cell.bias_ih"]), Whh: lin(J["cell.weight_hh"], J["cell.bias_hh"]),
80
+ readout: lin(J["readout.weight"], J["readout.bias"]),
81
+ net: [lin(P["net.0.weight"], P["net.0.bias"]), lin(P["net.2.weight"], P["net.2.bias"]), lin(P["net.4.weight"], P["net.4.bias"])],
82
+ logRateV: P.log_rate_v, aMax: P.log_a_max.map(Math.exp), logOmega: P.log_omega, zetaLogit: P.zeta_logit,
83
+ kappa0: P.kappa0, logRateW: P.log_rate_w, logRateC: P.log_rate_c,
84
+ omegaSpan: c.omega_span ?? 0.3,
85
+ sMean: Float32Array.from(N.s_mean), sStd: Float32Array.from(N.s_std),
86
+ aMean: Float32Array.from(N.a_mean), aStd: Float32Array.from(N.a_std),
87
+ };
88
+ m.kappaSpan = Math.max(0.5, 2 * m.omegaSpan);
89
+ return m;
90
+ }
91
+
92
+ // (14) state + mounts [[x,y,z] x4] -> normalised (28) features written into out
93
+ export function featuresNorm(m, x, xo, M, out) {
94
+ let j = 0;
95
+ out[j++] = x[xo + 2];
96
+ const ln = [0, 0, 0, 0];
97
+ for (let i = 0; i < 4; i++) {
98
+ const rx = M[i][0] - x[xo], ry = M[i][1] - x[xo + 1], rz = M[i][2] - x[xo + 2];
99
+ const l = Math.hypot(rx, ry, rz); ln[i] = l;
100
+ out[j++] = rx / l; out[j++] = ry / l; out[j++] = rz / l;
101
+ }
102
+ for (let i = 0; i < 4; i++) out[j++] = ln[i];
103
+ for (let i = 3; i < 14; i++) out[j++] = x[xo + i];
104
+ for (let i = 0; i < FEAT_DIM; i++) out[i] = (out[i] - m.sMean[i]) / m.sStd[i];
105
+ return out;
106
+ }
107
+
108
+ // GRUCell (PyTorch gate order r, z, n)
109
+ function gru(m, inp, h, gi, gh, hn) {
110
+ linApply(m.Wih, inp, 0, gi); linApply(m.Whh, h, 0, gh);
111
+ const H = m.hidden;
112
+ for (let i = 0; i < H; i++) {
113
+ const r = sig(gi[i] + gh[i]), z = sig(gi[H + i] + gh[H + i]);
114
+ const n = Math.tanh(gi[2 * H + i] + r * gh[2 * H + i]);
115
+ hn[i] = (1 - z) * n + z * h[i];
116
+ }
117
+ return hn;
118
+ }
119
+
120
+ /** The model's prediction, as LearnedCDPRModel.rollout: the shared history (H+1 states, H commands) and S candidate
121
+ * plans of T planner steps (each held for `stream` model steps) -> Float32Array (S * T * 14) at the planner steps. */
122
+ export function rollout(m, M, xHist, cHist, plans, S, T, stream = 2) {
123
+ const H = m.H, L = T * stream, D = m.latent, A = ACTION_DIM;
124
+ // 1. state encoder ONCE over the measured history (causal: its summary at H reads only the past)
125
+ const hf = new Float32Array((H + 1) * FEAT_DIM), tmp = new Float32Array(FEAT_DIM);
126
+ for (let t = 0; t <= H; t++) { featuresNorm(m, xHist[t], 0, M, tmp); hf.set(tmp, t * FEAT_DIM); }
127
+ const s0 = tcnApply(m.stateEnc, hf, H + 1).subarray(H * D, (H + 1) * D);
128
+ const out = new Float32Array(S * T * STATE_DIM);
129
+ const seq = new Float32Array((H + L) * A);
130
+ const inp = new Float32Array(D + m.actionEnc.readout.out);
131
+ const gi = new Float32Array(3 * m.hidden), gh = new Float32Array(3 * m.hidden);
132
+ let h = new Float32Array(m.hidden), hn = new Float32Array(m.hidden);
133
+ const lat = new Float32Array(L * D), s = new Float32Array(D);
134
+ const x = new Float32Array(STATE_DIM), cmds = new Float32Array(L * A);
135
+ for (let b = 0; b < S; b++) {
136
+ // 2. the action sequence: history commands then this plan, normalised
137
+ for (let t = 0; t < H; t++) for (let i = 0; i < A; i++) seq[t * A + i] = (cHist[t][i] - m.aMean[i]) / m.aStd[i];
138
+ for (let k = 0; k < L; k++) {
139
+ const pk = (b * T + Math.floor(k / stream)) * A;
140
+ for (let i = 0; i < A; i++) {
141
+ cmds[k * A + i] = plans[pk + i];
142
+ seq[(H + k) * A + i] = (plans[pk + i] - m.aMean[i]) / m.aStd[i];
143
+ }
144
+ }
145
+ const al = tcnApply(m.actionEnc, seq, H + L), AL = m.actionEnc.readout.out;
146
+ // 3. GRU unroll of the latent
147
+ h.fill(0); s.set(s0);
148
+ for (let k = 0; k < L; k++) {
149
+ inp.set(s, 0); inp.set(al.subarray((H + k) * AL, (H + k + 1) * AL), D);
150
+ gru(m, inp, h, gi, gh, hn); [h, hn] = [hn, h];
151
+ linApply(m.readout, h, 0, s); lat.set(s, k * D);
152
+ }
153
+ // 4. the prober sets the physics, integrated from the true current state
154
+ x.set(xHist[H]);
155
+ integrate(m, M, x, cmds, cHist[H - 1], lat, L, (k, xx) => {
156
+ if ((k + 1) % stream === 0) out.set(xx, (b * T + (k + 1) / stream - 1) * STATE_DIM);
157
+ });
158
+ }
159
+ return out;
160
+ }
161
+
162
+ const fbuf = new Float32Array(FEAT_DIM), pin = new Float32Array(24 + FEAT_DIM + 3);
163
+ const h1 = new Float32Array(64), h2 = new Float32Array(64), po = new Float32Array(18);
164
+
165
+ function integrate(m, M, x, cmds, cmdPrev, lat, L, emit, nSub = 4) {
166
+ const h = m.dtModel / nSub, D = m.latent;
167
+ let prev = cmdPrev;
168
+ const ce = new Float32Array(5);
169
+ for (let k = 0; k < L; k++) {
170
+ // prober(latent, normalised features, command error)
171
+ pin.set(lat.subarray(k * D, (k + 1) * D), 0);
172
+ pin.set(featuresNorm(m, x, 0, M, fbuf), D);
173
+ for (let i = 0; i < 3; i++) pin[D + FEAT_DIM + i] = cmds[k * 5 + i] - x[3 + i];
174
+ linApply(m.net[0], pin, 0, h1); for (let i = 0; i < 64; i++) h1[i] = h1[i] > 0 ? h1[i] : 0;
175
+ linApply(m.net[1], h1, 0, h2); for (let i = 0; i < 64; i++) h2[i] = h2[i] > 0 ? h2[i] : 0;
176
+ linApply(m.net[2], h2, 0, po);
177
+ const rateV = [0, 1, 2].map(i => Math.exp(m.logRateV[i] + Math.tanh(po[i])));
178
+ const rV = [po[3], po[4], po[5]];
179
+ const beta = sig(po[6]);
180
+ const omega = Math.exp(m.logOmega + m.omegaSpan * Math.tanh(po[7]));
181
+ const zeta = 0.5 * sig(m.zetaLogit + po[8]);
182
+ const kappa = m.kappa0 * Math.exp(m.kappaSpan * Math.tanh(po[9]));
183
+ const sEq = [0.15 * Math.tanh(po[10]), 0.15 * Math.tanh(po[11])];
184
+ const rS = [po[12], po[13]];
185
+ const rateW = Math.exp(m.logRateW + Math.tanh(po[14])), rW = po[15];
186
+ const rateC = Math.exp(m.logRateC + Math.tanh(po[16])), rC = 0.1 * po[17];
187
+ for (let i = 0; i < 5; i++) ce[i] = beta * cmds[k * 5 + i] + (1 - beta) * prev[i];
188
+ physicsSubsteps(x, ce, h, nSub, { rateV, rV, aMax: m.aMax, omega, zeta, kappa, sEq, rS, rateW, rW, rateC, rC });
189
+ prev = cmds.subarray(k * 5, k * 5 + 5);
190
+ emit(k, x);
191
+ }
192
+ }
193
+
194
+ /** The hand-written physics (slot 3): gantry behind acceleration-limited spools, a damped pendulum driven by the gantry's
195
+ * horizontal acceleration, the wrist and finger servos. Mutates x. */
196
+ export function physicsSubsteps(x, ce, h, nSub, c) {
197
+ const a = [0, 0, 0];
198
+ for (let n = 0; n < nSub; n++) {
199
+ for (let i = 0; i < 3; i++) {
200
+ a[i] = c.aMax[i] * Math.tanh(c.rateV[i] * (ce[i] - x[3 + i]) / c.aMax[i]) + c.rV[i];
201
+ x[3 + i] += a[i] * h; x[i] += x[3 + i] * h;
202
+ }
203
+ for (let i = 0; i < 2; i++) {
204
+ const sdd = -c.omega * c.omega * (x[6 + i] - c.sEq[i]) - 2 * c.zeta * c.omega * x[8 + i] + c.kappa * a[i] + c.rS[i];
205
+ x[8 + i] += sdd * h; x[6 + i] += x[8 + i] * h;
206
+ }
207
+ x[11] += (c.rateW * (ce[3] - x[11]) + c.rW) * h; x[10] += x[11] * h;
208
+ x[13] = Math.max(-1.2, Math.min(1.2, c.rateC * (ce[4] - x[12]))) + c.rC; x[12] += x[13] * h;
209
+ }
210
+ }
core/model.json ADDED
The diff for this file is too large to render. See raw diff
 
core/mppi.js ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // MPPI over the world model's imagined futures: a port of cablepilot/planner/mppi.py (same config keys, same steps).
2
+ // Per tick: perturb the nominal plan with temporally correlated noise (coarse + fine scales), roll every candidate out
3
+ // through the world model, score it (task costs + smoothness), softmax with the temperature solved so the effective
4
+ // sample size stays at ess_target * S, move the nominal a step towards the weighted average, execute its first action.
5
+
6
+ export function rng(seed) { // mulberry32 + Box-Muller
7
+ let a = seed >>> 0, spare = null;
8
+ const u = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1);
9
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
10
+ return { u, n() { if (spare !== null) { const s = spare; spare = null; return s; }
11
+ const r = Math.sqrt(-2 * Math.log(u() + 1e-12)), th = 2 * Math.PI * u(); spare = r * Math.sin(th); return r * Math.cos(th); } };
12
+ }
13
+
14
+ export const PLANNER = { // configs/planner_learned.yaml
15
+ dt: 0.2, horizon: 10, samples: 128, ess_target: 0.1,
16
+ sigma: [0.06, 0.06, 0.03, 0.4, 0.0], noise_corr: 0.9, r_weights: [90, 90, 90, 1, 0],
17
+ step_size: 0.3, sigma_scales: [1.0, 0.2], keep_rollouts: 12,
18
+ a_min: [-0.3, -0.3, -0.3, -1.5, 0.0], a_max: [0.3, 0.3, 0.3, 1.5, 1.0],
19
+ };
20
+
21
+ export class MPPI {
22
+ constructor(cfg, seed = 0) { this.cfg = cfg; this.r = rng(seed); this.nominal = null; }
23
+
24
+ reset(aNow) {
25
+ const { horizon: T } = this.cfg;
26
+ this.nominal = new Float32Array(T * 5);
27
+ for (let k = 0; k < T; k++) this.nominal.set(aNow, k * 5);
28
+ }
29
+
30
+ temperature(dJ) { // bisection on log-temperature: ESS = 1/sum(w^2) -> target
31
+ const S = dJ.length, target = Math.max(1, this.cfg.ess_target * S);
32
+ const sorted = Float64Array.from(dJ).sort(), scale = sorted[S >> 1] + 1e-9;
33
+ let lo = -12, hi = 12;
34
+ for (let it = 0; it < 30; it++) {
35
+ const mid = (lo + hi) / 2, tmp = scale * 10 ** mid;
36
+ let z = 0, z2 = 0;
37
+ for (let i = 0; i < S; i++) { const e = Math.exp(-dJ[i] / tmp); z += e; z2 += e * e; }
38
+ if (z * z / z2 < target) lo = mid; else hi = mid;
39
+ }
40
+ return scale * 10 ** hi;
41
+ }
42
+
43
+ /** rolloutFn(plans, S) -> Float32Array (S*T*14); costFn(states, plans, S) -> Float64Array (S); fixed {dim: value}.
44
+ * aPrev: the command being executed. Returns {action, info}. */
45
+ plan(rolloutFn, costFn, aPrev, fixed = {}) {
46
+ const c = this.cfg, S = c.samples, T = c.horizon, A = 5;
47
+ if (!this.nominal) this.reset(aPrev);
48
+ for (const [i, v] of Object.entries(fixed)) for (let k = 0; k < T; k++) this.nominal[k * A + +i] = v;
49
+ const t0 = performance.now();
50
+ // 1. candidates: nominal + AR(1) noise, scales cycled per sample, sample 0 = the nominal itself
51
+ const cands = new Float32Array(S * T * A), rho = c.noise_corr, q = Math.sqrt(1 - rho * rho);
52
+ const eps = new Float64Array(A);
53
+ for (let s = 0; s < S; s++) {
54
+ const sc = c.sigma_scales[s % c.sigma_scales.length];
55
+ for (let k = 0; k < T; k++)
56
+ for (let i = 0; i < A; i++) {
57
+ const w = this.r.n();
58
+ eps[i] = k === 0 ? w : rho * eps[i] + q * w;
59
+ let e = s === 0 || i in fixed ? 0 : eps[i] * c.sigma[i] * sc;
60
+ const v = this.nominal[k * A + i] + e;
61
+ cands[(s * T + k) * A + i] = Math.min(c.a_max[i], Math.max(c.a_min[i], v));
62
+ }
63
+ }
64
+ const t1 = performance.now();
65
+ const states = rolloutFn(cands, S);
66
+ const t2 = performance.now();
67
+ // 3. costs: the task's terms + smoothness sum_k R (a_k - a_{k-1})^2
68
+ const { J, terms } = costFn(states, cands, S);
69
+ for (let s = 0; s < S; s++) {
70
+ let sm = 0;
71
+ for (let k = 0; k < T; k++)
72
+ for (let i = 0; i < A; i++) {
73
+ const prev = k === 0 ? aPrev[i] : cands[(s * T + k - 1) * A + i];
74
+ const d = cands[(s * T + k) * A + i] - prev; sm += c.r_weights[i] * d * d;
75
+ }
76
+ J[s] += sm;
77
+ }
78
+ const t3 = performance.now();
79
+ // 4. softmax at the ESS temperature, move the nominal towards the weighted average
80
+ let Jmin = Infinity; for (let s = 0; s < S; s++) Jmin = Math.min(Jmin, J[s]);
81
+ const dJ = J.map(v => v - Jmin), temp = this.temperature(dJ);
82
+ const w = new Float64Array(S); let z = 0;
83
+ for (let s = 0; s < S; s++) { w[s] = Math.exp(-dJ[s] / temp); z += w[s]; }
84
+ let z2 = 0; for (let s = 0; s < S; s++) { w[s] /= z; z2 += w[s] * w[s]; }
85
+ for (let k = 0; k < T; k++)
86
+ for (let i = 0; i < A; i++) {
87
+ let avg = 0; for (let s = 0; s < S; s++) avg += w[s] * cands[(s * T + k) * A + i];
88
+ this.nominal[k * A + i] += c.step_size * (avg - this.nominal[k * A + i]);
89
+ }
90
+ const t3b = performance.now();
91
+ const nomStates = rolloutFn(this.nominal, 1);
92
+ const t4 = performance.now();
93
+ const action = Array.from(this.nominal.subarray(0, A));
94
+ const order = Array.from({ length: S }, (_, i) => i).sort((a, b) => J[a] - J[b]).slice(0, c.keep_rollouts);
95
+ const best = order.map(s => states.subarray(s * T * 14, (s + 1) * T * 14));
96
+ // receding horizon: shift, repeat the last
97
+ this.nominal.copyWithin(0, A); this.nominal.set(this.nominal.subarray((T - 2) * A, (T - 1) * A), (T - 1) * A);
98
+ return { action, info: { nominal: nomStates, rollouts: best, ess: 1 / z2, costMin: Jmin, terms,
99
+ ms: { noise: t1 - t0, rollout: t2 - t1 + (t4 - t3b), cost: t3 - t2, update: t3b - t3, total: t4 - t0 } } };
100
+ }
101
+ }
index.html CHANGED
@@ -1,19 +1,92 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <title>Clear the Playroom</title>
7
+ <meta name="description" content="A cable robot clears a playroom. A 28k-parameter world model imagines 128 futures every 0.2 s; furniture is only a cost.">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link href="https://fonts.googleapis.com/css2?family=Archivo:wght@500;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
10
+ <link rel="stylesheet" href="style.css">
11
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Cpath d=%22M4 4L16 18L28 4M4 28L16 18L28 28%22 stroke=%22%23e68e0d%22 stroke-width=%222.5%22 fill=%22none%22/%3E%3Ccircle cx=%2216%22 cy=%2218%22 r=%223.5%22 fill=%22%235fb68b%22/%3E%3C/svg%3E">
12
+ <script type="importmap">{ "imports": { "three": "./vendor/three.module.js", "three/addons/": "./vendor/addons/" } }</script>
13
+ </head>
14
+ <body>
15
+ <main class="app">
16
+ <section class="stage" aria-label="The playroom, in 3D">
17
+ <canvas id="view"></canvas>
18
+ <div class="hint" id="hint">Click the floor to drop a toy · drag furniture · click a toy to take it back · drag empty space to turn the view</div>
19
+ <div class="toast" id="toast" role="status" hidden></div>
20
+ <div class="legend">
21
+ <span><i class="sw ember"></i>the plan it chose</span>
22
+ <span><i class="sw future"></i>futures it imagined</span>
23
+ <span><i class="sw shadow"></i>line shadow</span>
24
+ </div>
25
+ </section>
26
+
27
+ <aside class="panel">
28
+ <header>
29
+ <p class="mark">MacroSwan <span>·</span> cablepilot mission</p>
30
+ <h1>Clear the playroom</h1>
31
+ <p class="lede">A cable robot hangs from four lines in a playroom. Every 0.2 s it imagines 128 futures with a small learned world model and follows the cheapest. Furniture is only a cost, so move it and watch the plans bend.</p>
32
+ </header>
33
+
34
+ <div class="controls">
35
+ <button id="run" class="primary">Start</button>
36
+ <div class="seg" role="group" aria-label="Speed">
37
+ <button data-speed="1" class="on">1×</button><button data-speed="2">2×</button><button data-speed="4">4×</button><button data-speed="0">max</button>
38
+ </div>
39
+ <button id="reset" class="ghost">Reset</button>
40
+ </div>
41
+
42
+ <section class="status">
43
+ <div class="phase"><span class="dot" id="phaseDot"></span><span id="phase">waiting for toys</span></div>
44
+ <div class="kpis">
45
+ <div><b id="toys">0/5</b><span>toys in the hamper</span></div>
46
+ <div><b id="clock">0 s</b><span>robot time</span></div>
47
+ <div><b id="contacts">0</b><span>furniture contacts</span></div>
48
+ </div>
49
+ </section>
50
+
51
+ <section class="card">
52
+ <h2>What one decision costs</h2>
53
+ <div class="kpis">
54
+ <div><b id="ms">–</b><span>ms per plan, this browser</span></div>
55
+ <div><b id="fps">–</b><span>futures imagined per CPU-second</span></div>
56
+ <div><b id="cpuToy">–</b><span>CPU-seconds per toy</span></div>
57
+ </div>
58
+ <div class="split" id="split" aria-label="Where the time goes"></div>
59
+ <p class="fine">28,401 parameters. 128 futures × 2 s ahead, 5 times a second, on one CPU thread. No GPU.</p>
60
+ </section>
61
+
62
+ <section class="card">
63
+ <h2>Why it chose this plan</h2>
64
+ <ul class="terms" id="terms"></ul>
65
+ <p class="fine">The chosen plan's cost terms over its 2 s horizon. Furniture and lines rise when you crowd the robot.</p>
66
+ </section>
67
+
68
+ <section class="card">
69
+ <h2>Furniture</h2>
70
+ <div class="add">
71
+ <button data-add="chair">+ Chair</button><button data-add="table">+ Table</button><button data-add="shelf">+ Shelf</button><button data-add="box">+ Box</button>
72
+ </div>
73
+ <div id="furn" class="furn"></div>
74
+ <label class="check"><input type="checkbox" id="showShadow" checked> Show line shadows on the floor</label>
75
+ <label class="check"><input type="checkbox" id="showFutures" checked> Show imagined futures</label>
76
+ <label class="check"><input type="checkbox" id="follow"> Follow the robot</label>
77
+ </section>
78
+
79
+ <section class="card">
80
+ <h2>Log</h2>
81
+ <ol class="log" id="log"></ol>
82
+ </section>
83
+
84
+ <footer class="fine">
85
+ <p><b>Planner:</b> the released <a href="https://huggingface.co/MacroSwan/cablepilot" target="_blank" rel="noopener">MacroSwan/cablepilot</a> world model, trained on our own simulated motion and ported to JavaScript. It matches PyTorch to 0.0005 mm.</p>
86
+ <p><b>Robot:</b> simulated by the same world model plus noise. Against the MuJoCo twin it is off by about 2 cm over 2 s, and a real robot would differ more. <b>Room:</b> a fictional 4.6 × 4.0 m playroom with the line anchors in its corners.</p>
87
+ </footer>
88
+ </aside>
89
+ </main>
90
+ <script type="module" src="main.js"></script>
91
+ </body>
92
  </html>
main.js ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The page: draws the room, the robot and what it imagines, and turns clicks into edits for the worker.
2
+ import * as THREE from "three";
3
+ import { OrbitControls } from "three/addons/controls/OrbitControls.js";
4
+ import { ROOM, HAMPER, DEFAULT_FURNITURE } from "./core/mission.js";
5
+
6
+ const $ = id => document.getElementById(id);
7
+ const C = { ember: 0xe68e0d, forest: 0x5fb68b, shadow: 0xa07ce0, bone: 0xe8e3da, furn: 0x50545c, bg: 0x121212 };
8
+ const TOY_COLORS = [0xf06aa7, 0xf2c230, 0x5fb68b, 0x5aa2f0, 0xf08a3c, 0xb07cf0];
9
+ const PRESETS = { chair: { label: "Chair", w: 0.44, d: 0.44, h: 0.85 }, table: { label: "Table", w: 0.8, d: 0.8, h: 0.72 },
10
+ shelf: { label: "Shelf", w: 1.0, d: 0.35, h: 1.6 }, box: { label: "Box", w: 0.5, d: 0.5, h: 0.4 } };
11
+
12
+ // ------------------------------------------------------------------------------------------- scene
13
+ const canvas = $("view"), stage = canvas.parentElement;
14
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
15
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
16
+ const scene = new THREE.Scene();
17
+ scene.background = new THREE.Color(C.bg);
18
+ const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 60);
19
+ camera.up.set(0, 0, 1);
20
+ camera.position.set(0.9, -5.6, 5.0);
21
+ const controls = new OrbitControls(camera, canvas);
22
+ controls.target.set(-0.3, 0.05, 0.35);
23
+ controls.enableDamping = true;
24
+ controls.maxPolarAngle = Math.PI / 2 - 0.08;
25
+ controls.minDistance = 1.5; controls.maxDistance = 14;
26
+
27
+ const hemi = new THREE.HemisphereLight(0xfff6e8, 0x1a1a1a, 1.6); hemi.position.set(0, 0, 10); scene.add(hemi);
28
+ const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(2.5, -3, 7); scene.add(sun);
29
+
30
+ const E = ROOM.floor.extent;
31
+ const floorTex = new THREE.CanvasTexture(drawFloor(1024));
32
+ floorTex.colorSpace = THREE.SRGBColorSpace;
33
+ floorTex.anisotropy = 4;
34
+
35
+ /** Our own floor, drawn in code: oak planks inside the walls, a rug and a play mat. 5 m across, room origin at the
36
+ * centre, +y up (the same convention as the reach map). */
37
+ function drawFloor(px) {
38
+ const cv = document.createElement("canvas"); cv.width = cv.height = px;
39
+ const g = cv.getContext("2d"), s = px / E, U = x => (x / E + 0.5) * px, V = y => (0.5 - y / E) * px;
40
+ let seed = 7; const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
41
+ g.fillStyle = "#151515"; g.fillRect(0, 0, px, px);
42
+ const [W, D] = ROOM.size, x0 = U(-W / 2), y0 = V(D / 2), w = W * s, h = D * s;
43
+ g.save(); g.beginPath(); g.rect(x0, y0, w, h); g.clip();
44
+ const plank = 0.16 * s; // 16 cm oak planks, staggered seams
45
+ for (let r = 0, y = y0; y < y0 + h; r++, y += plank) {
46
+ let x = x0 - rnd() * 1.4 * s;
47
+ while (x < x0 + w) {
48
+ const len = (0.9 + rnd() * 1.1) * s, tone = 150 + rnd() * 30;
49
+ g.fillStyle = `rgb(${tone + 22}, ${tone - 8}, ${tone - 52})`; g.fillRect(x, y, len, plank);
50
+ for (let k = 0; k < 3; k++) { // a little grain
51
+ g.strokeStyle = `rgba(90, 60, 30, ${0.08 + rnd() * 0.08})`; g.lineWidth = 1;
52
+ const gy = y + rnd() * plank; g.beginPath(); g.moveTo(x, gy); g.lineTo(x + len, gy + (rnd() - 0.5) * 3); g.stroke();
53
+ }
54
+ g.fillStyle = "rgba(60, 40, 20, 0.55)"; g.fillRect(x + len - 1, y, 1.2, plank);
55
+ x += len;
56
+ }
57
+ g.fillStyle = "rgba(60, 40, 20, 0.45)"; g.fillRect(x0, y, w, 1.2);
58
+ }
59
+ const round = (cx, cy, rw, rh, rad, fill, stroke) => { // rounded rectangle in metres
60
+ g.beginPath(); g.roundRect(U(cx - rw / 2), V(cy + rh / 2), rw * s, rh * s, rad * s);
61
+ g.fillStyle = fill; g.fill(); if (stroke) { g.lineWidth = 0.06 * s; g.strokeStyle = stroke; g.stroke(); }
62
+ };
63
+ round(-0.15, 0.15, 2.4, 1.7, 0.12, "#6f7f6a", "#55654f"); // the rug
64
+ g.globalAlpha = 0.18; for (let i = 0; i < 9; i++) round(-0.15, 0.15, 2.2 - i * 0.22, 1.5 - i * 0.15, 0.1, "transparent", "#e8e3da");
65
+ g.globalAlpha = 1;
66
+ const tiles = ["#c9a227", "#b8563a", "#3f7f9a", "#6c9a4a"]; // a play mat of foam tiles
67
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 2; j++) round(1.55 + i * 0.3 - 0.3, 0.55 + j * 0.3, 0.29, 0.29, 0.03, tiles[(i + j) % 4]);
68
+ g.restore();
69
+ g.strokeStyle = "#e8e3da"; g.lineWidth = 0.05 * s; g.strokeRect(x0, y0, w, h); // skirting
70
+ return cv;
71
+ }
72
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(E, E), new THREE.MeshStandardMaterial({ map: floorTex, roughness: 1 }));
73
+ scene.add(floor);
74
+
75
+ // the reach map: line shadows (purple) and the band too close to the walls (dimmed)
76
+ const RN = 100, reachData = new Uint8Array(RN * RN * 4);
77
+ const reachTex = new THREE.DataTexture(reachData, RN, RN, THREE.RGBAFormat);
78
+ reachTex.magFilter = THREE.LinearFilter;
79
+ const reach = new THREE.Mesh(new THREE.PlaneGeometry(E, E), new THREE.MeshBasicMaterial({ map: reachTex, transparent: true, depthWrite: false }));
80
+ reach.position.z = 0.003; scene.add(reach);
81
+ function setReach(map) {
82
+ for (let r = 0; r < RN; r++) for (let c = 0; c < RN; c++) {
83
+ const v = map[r * RN + c], o = ((RN - 1 - r) * RN + c) * 4; // map row 0 = +y edge, texture row 0 = -y
84
+ const [R, G, B, A] = v === 3 ? [160, 124, 224, 125] : v === 1 ? [10, 10, 12, 150] : [0, 0, 0, 0];
85
+ reachData[o] = R; reachData[o + 1] = G; reachData[o + 2] = B; reachData[o + 3] = A;
86
+ }
87
+ reachTex.needsUpdate = true;
88
+ }
89
+
90
+ // low walls (cut away, so the room stays readable from any angle)
91
+ { const [W, D] = ROOM.size, t = 0.06, hw = 0.35;
92
+ const wallMat = new THREE.MeshStandardMaterial({ color: 0x2a2826, roughness: 0.9 });
93
+ for (const [x, y, w, d] of [[0, D / 2 + t / 2, W + 2 * t, t], [0, -D / 2 - t / 2, W + 2 * t, t], [W / 2 + t / 2, 0, t, D], [-W / 2 - t / 2, 0, t, D]]) {
94
+ const m = new THREE.Mesh(new THREE.BoxGeometry(w, d, hw), wallMat); m.position.set(x, y, hw / 2); scene.add(m);
95
+ } }
96
+
97
+ // the four line anchors on posts
98
+ const postMat = new THREE.MeshStandardMaterial({ color: 0x3a3a3a, roughness: 0.8 });
99
+ for (const M of ROOM.mounts) {
100
+ const post = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, M[2], 10), postMat);
101
+ post.rotation.x = Math.PI / 2; post.position.set(M[0], M[1], M[2] / 2); scene.add(post);
102
+ const eye = new THREE.Mesh(new THREE.SphereGeometry(0.04, 16, 12), new THREE.MeshStandardMaterial({ color: C.ember }));
103
+ eye.position.set(...M); scene.add(eye);
104
+ }
105
+ const lineGeo = new THREE.BufferGeometry();
106
+ lineGeo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(8 * 3), 3));
107
+ const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({ color: 0xd8d2c6 }));
108
+ scene.add(lines);
109
+
110
+ // the robot: gantry, pole, gripper, two fingers (cablepilot stringman.yaml body numbers)
111
+ const robot = new THREE.Group(); scene.add(robot);
112
+ const dark = new THREE.MeshStandardMaterial({ color: 0x2b2b2b, roughness: 0.6 });
113
+ const bone = new THREE.MeshStandardMaterial({ color: C.bone, roughness: 0.5 });
114
+ const gantry = new THREE.Mesh(new THREE.BoxGeometry(0.09, 0.09, 0.08), dark); gantry.position.z = -0.02; robot.add(gantry);
115
+ const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.269, 8), bone);
116
+ pole.rotation.x = Math.PI / 2; pole.position.z = -0.1945; robot.add(pole);
117
+ const wrist = new THREE.Group(); robot.add(wrist);
118
+ const shell = new THREE.Mesh(new THREE.BoxGeometry(0.104, 0.07, 0.11), bone); shell.position.z = -0.3907; wrist.add(shell);
119
+ const fingers = [1, -1].map(side => {
120
+ const pivot = new THREE.Group(); pivot.position.set(0.025 * side, 0, -0.4047);
121
+ const f = new THREE.Mesh(new THREE.BoxGeometry(0.012, 0.044, 0.11), dark); f.position.z = -0.055;
122
+ pivot.add(f); wrist.add(pivot); return { pivot, side };
123
+ });
124
+
125
+ // the hamper (its four walls)
126
+ const hamper = new THREE.Group(); scene.add(hamper);
127
+ const wicker = new THREE.MeshStandardMaterial({ color: 0x8a6a45, roughness: 0.9 });
128
+ { const i = HAMPER.half, t = 0.02, h = HAMPER.height;
129
+ for (const [x, y, w, d] of [[i + t / 2, 0, t, 2 * i + 2 * t], [-i - t / 2, 0, t, 2 * i + 2 * t], [0, i + t / 2, 2 * i, t], [0, -i - t / 2, 2 * i, t]]) {
130
+ const m = new THREE.Mesh(new THREE.BoxGeometry(w, d, h), wicker); m.position.set(x, y, h / 2); hamper.add(m);
131
+ }
132
+ hamper.position.set(ROOM.hamper[0], ROOM.hamper[1], 0); }
133
+
134
+ // what it imagines: the chosen plan (ember tube) and the best futures (forest lines)
135
+ const FUT = 12, futMat = new THREE.LineBasicMaterial({ color: C.forest, transparent: true, opacity: 0.75 });
136
+ const futures = Array.from({ length: FUT }, () => {
137
+ const g = new THREE.BufferGeometry(); g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(11 * 3), 3));
138
+ const l = new THREE.Line(g, futMat); scene.add(l); return l;
139
+ });
140
+ let planTube = null;
141
+ const planMat = new THREE.MeshBasicMaterial({ color: C.ember });
142
+ const goalRing = new THREE.Mesh(new THREE.RingGeometry(0.035, 0.05, 32), new THREE.MeshBasicMaterial({ color: C.ember, transparent: true, opacity: 0.7, side: THREE.DoubleSide }));
143
+ scene.add(goalRing);
144
+
145
+ // ------------------------------------------------------------------------------------------- furniture (the page owns the list)
146
+ let furniture = DEFAULT_FURNITURE.map(f => ({ ...f })), selected = null, nextF = 1;
147
+ const furnMeshes = new Map();
148
+ const furnMat = () => new THREE.MeshStandardMaterial({ color: C.furn, roughness: 0.85, transparent: true, opacity: 0.88 });
149
+ function syncFurnMesh(f) {
150
+ let m = furnMeshes.get(f.id);
151
+ if (!m) {
152
+ m = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), furnMat());
153
+ m.add(new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)), new THREE.LineBasicMaterial({ color: 0x8c8f96 })));
154
+ m.userData.id = f.id; scene.add(m); furnMeshes.set(f.id, m);
155
+ }
156
+ m.scale.set(2 * f.hx, 2 * f.hy, f.h); m.position.set(f.x, f.y, f.h / 2);
157
+ m.material.emissive.setHex(f.id === selected ? 0x2a1f3d : 0x000000);
158
+ }
159
+ function syncAllFurniture() {
160
+ for (const [id, m] of furnMeshes) if (!furniture.find(f => f.id === id)) { scene.remove(m); furnMeshes.delete(id); }
161
+ furniture.forEach(syncFurnMesh);
162
+ }
163
+ let sendTimer = null;
164
+ function sendFurniture(now = false) {
165
+ clearTimeout(sendTimer);
166
+ const go = () => worker.postMessage({ type: "furniture", list: furniture });
167
+ if (now) go(); else sendTimer = setTimeout(go, 90);
168
+ }
169
+ function renderFurnList() {
170
+ const box = $("furn"); box.textContent = "";
171
+ for (const f of furniture) {
172
+ const el = document.createElement("div"); el.className = "fi" + (f.id === selected ? " sel" : "");
173
+ el.innerHTML = `<div class="row"><b></b><button type="button" aria-label="Remove">Remove</button></div>`;
174
+ el.querySelector("b").textContent = f.label;
175
+ el.querySelector("button").onclick = () => { furniture = furniture.filter(g => g !== f); if (selected === f.id) selected = null; syncAllFurniture(); renderFurnList(); sendFurniture(true); };
176
+ if (f.id === selected) {
177
+ const s = document.createElement("div"); s.className = "sliders";
178
+ for (const [key, name, lo, hi] of [["w", "Width", 0.2, 2.0], ["d", "Depth", 0.2, 2.0], ["h", "Height", 0.2, 1.9]]) {
179
+ const val = key === "w" ? 2 * f.hx : key === "d" ? 2 * f.hy : f.h, id = `fs-${f.id}-${key}`;
180
+ s.insertAdjacentHTML("beforeend", `<label for="${id}">${name}</label><input id="${id}" type="range" min="${lo}" max="${hi}" step="0.01" value="${val.toFixed(2)}"><output>${val.toFixed(2)} m</output>`);
181
+ }
182
+ s.querySelectorAll("input").forEach(inp => inp.oninput = () => {
183
+ const v = +inp.value, k = inp.id.split("-").pop();
184
+ if (k === "w") f.hx = v / 2; else if (k === "d") f.hy = v / 2; else f.h = v;
185
+ inp.nextElementSibling.textContent = v.toFixed(2) + " m"; syncFurnMesh(f); sendFurniture();
186
+ });
187
+ el.appendChild(s);
188
+ } else el.onclick = e => { if (e.target.tagName !== "BUTTON") { selected = f.id; syncAllFurniture(); renderFurnList(); } };
189
+ box.appendChild(el);
190
+ }
191
+ }
192
+ document.querySelectorAll("[data-add]").forEach(b => b.onclick = () => {
193
+ const p = PRESETS[b.dataset.add], f = { id: `${b.dataset.add}-${nextF++}`, label: p.label, x: 0.2 + 0.4 * (Math.random() - 0.5), y: 0.2 + 0.4 * (Math.random() - 0.5), hx: p.w / 2, hy: p.d / 2, h: p.h };
194
+ furniture.push(f); selected = f.id; syncAllFurniture(); renderFurnList(); sendFurniture(true);
195
+ });
196
+
197
+ // ------------------------------------------------------------------------------------------- toys
198
+ const toyMeshes = new Map();
199
+ const toyGeo = new THREE.BoxGeometry(0.05, 0.05, 0.05); // cablepilot's 4 cm toy blocks, drawn a touch larger
200
+ const targetRing = new THREE.Mesh(new THREE.RingGeometry(0.06, 0.075, 32), new THREE.MeshBasicMaterial({ color: C.ember, side: THREE.DoubleSide }));
201
+ targetRing.visible = false; scene.add(targetRing);
202
+ function syncToys(toys) {
203
+ for (const [id, m] of toyMeshes) if (!toys.find(t => t.id === id)) { scene.remove(m); toyMeshes.delete(id); }
204
+ for (const t of toys) {
205
+ let m = toyMeshes.get(t.id);
206
+ if (!m) {
207
+ const col = TOY_COLORS[t.id % TOY_COLORS.length];
208
+ m = new THREE.Mesh(toyGeo, new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 0.25, roughness: 0.4 }));
209
+ m.add(new THREE.LineSegments(new THREE.EdgesGeometry(toyGeo), new THREE.LineBasicMaterial({ color: 0xffffff })));
210
+ m.userData.id = t.id; scene.add(m); toyMeshes.set(t.id, m);
211
+ }
212
+ m.position.set(t.x, t.y, t.z + 0.005);
213
+ }
214
+ }
215
+
216
+ // ------------------------------------------------------------------------------------------- pointer: drag furniture, drop / take toys
217
+ const ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), ground = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
218
+ let down = null, drag = null;
219
+ function pick(e) {
220
+ const r = canvas.getBoundingClientRect();
221
+ ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
222
+ ray.setFromCamera(ndc, camera);
223
+ }
224
+ function groundPoint() { const p = new THREE.Vector3(); return ray.ray.intersectPlane(ground, p) ? p : null; }
225
+ stage.addEventListener("pointerdown", e => {
226
+ if (e.target !== canvas || e.button !== 0) return;
227
+ pick(e); down = { x: e.clientX, y: e.clientY };
228
+ const hit = ray.intersectObjects([...furnMeshes.values()], false)[0];
229
+ if (hit) {
230
+ const f = furniture.find(g => g.id === hit.object.userData.id), p = groundPoint();
231
+ drag = { f, dx: p ? f.x - p.x : 0, dy: p ? f.y - p.y : 0 };
232
+ selected = f.id; syncAllFurniture(); renderFurnList();
233
+ controls.enabled = false; canvas.classList.add("grab"); canvas.setPointerCapture(e.pointerId);
234
+ }
235
+ }, { capture: true });
236
+ canvas.addEventListener("pointermove", e => {
237
+ if (!drag) return;
238
+ pick(e); const p = groundPoint(); if (!p) return;
239
+ drag.f.x = Math.max(-E / 2, Math.min(E / 2, p.x + drag.dx)); drag.f.y = Math.max(-E / 2, Math.min(E / 2, p.y + drag.dy));
240
+ syncFurnMesh(drag.f); sendFurniture();
241
+ });
242
+ window.addEventListener("pointerup", e => {
243
+ if (drag) { drag = null; controls.enabled = true; canvas.classList.remove("grab"); sendFurniture(true); down = null; return; }
244
+ if (!down || e.target !== canvas) { down = null; return; }
245
+ const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y); down = null;
246
+ if (moved > 6) return; // that was a view turn
247
+ pick(e);
248
+ const toyHit = ray.intersectObjects([...toyMeshes.values()], false)[0];
249
+ if (toyHit) { worker.postMessage({ type: "removeToy", id: toyHit.object.userData.id }); return; }
250
+ const p = groundPoint();
251
+ if (p && Math.abs(p.x) < E / 2 && Math.abs(p.y) < E / 2) worker.postMessage({ type: "addToy", x: p.x, y: p.y, autostart: false });
252
+ });
253
+
254
+ // ------------------------------------------------------------------------------------------- controls
255
+ const worker = new Worker("./worker.js", { type: "module" });
256
+ let running = false;
257
+ function setRunning(on) { running = on; $("run").textContent = on ? "Pause" : "Start"; $("phaseDot").classList.toggle("live", on); }
258
+ $("run").onclick = () => { setRunning(!running); worker.postMessage({ type: "run", on: running }); };
259
+ $("reset").onclick = () => worker.postMessage({ type: "reset" });
260
+ document.querySelectorAll("[data-speed]").forEach(b => b.onclick = () => {
261
+ document.querySelectorAll("[data-speed]").forEach(o => o.classList.toggle("on", o === b));
262
+ worker.postMessage({ type: "speed", v: +b.dataset.speed });
263
+ });
264
+ $("showShadow").onchange = e => { reach.visible = e.target.checked; };
265
+ const home = { pos: camera.position.clone(), target: controls.target.clone() };
266
+ $("follow").onchange = e => { if (!e.target.checked) { camera.position.copy(home.pos); controls.target.copy(home.target); } };
267
+ $("showFutures").onchange = e => { futures.forEach(l => (l.visible = e.target.checked)); };
268
+ let toastTimer;
269
+ function toast(text) { const t = $("toast"); t.textContent = text; t.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => (t.hidden = true), 3200); }
270
+
271
+ // ------------------------------------------------------------------------------------------- frames from the worker
272
+ let prevX = null, curX = null, tRecv = 0, interval = 200;
273
+ const SPLIT = [["noise", "#6f6a62", "sampling"], ["rollout", "#5fb68b", "imagining"], ["cost", "#e68e0d", "scoring"], ["update", "#a07ce0", "choosing"]];
274
+ $("split").insertAdjacentHTML("afterend", `<div class="split-key">${SPLIT.map(([, c, n]) => `<span><i style="background:${c}"></i>${n}</span>`).join("")}</div>`);
275
+ const TERMS = [["goal", "goal"], ["furniture", "furniture"], ["lines", "lines"], ["walls", "walls"], ["swing", "swing"], ["floor", "floor"]];
276
+ $("terms").innerHTML = TERMS.map(([k, n]) => `<li data-k="${k}"><span>${n}</span><span class="bar"><i></i></span><span class="v">0</span></li>`).join("");
277
+
278
+ function onFrame(f) {
279
+ const now = performance.now();
280
+ if (curX) { interval = Math.min(1000, Math.max(30, now - tRecv)); prevX = curX; } else prevX = f.x;
281
+ curX = f.x; tRecv = now;
282
+ // lines, paths, goal
283
+ if (f.nominal.length) {
284
+ const pts = [gp(f.x), ...f.nominal].map(p => new THREE.Vector3(...p));
285
+ if (planTube) { planTube.geometry.dispose(); scene.remove(planTube); }
286
+ planTube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.014, 8), planMat); scene.add(planTube);
287
+ f.rollouts.forEach((r, i) => {
288
+ if (i >= FUT) return;
289
+ const a = futures[i].geometry.attributes.position; const all = [gp(f.x), ...r];
290
+ all.forEach((p, k) => a.setXYZ(k, p[0], p[1], p[2])); a.needsUpdate = true; futures[i].geometry.computeBoundingSphere();
291
+ });
292
+ }
293
+ goalRing.position.set(f.goal[0], f.goal[1], f.goal[2] + 0.002);
294
+ syncToys(f.toys);
295
+ const tgt = f.toys.find(t => t.id === f.target);
296
+ targetRing.visible = !!tgt && tgt.state === "target";
297
+ if (tgt) targetRing.position.set(tgt.x, tgt.y, 0.006);
298
+ // panel
299
+ const total = f.toys.length, done = f.toys.filter(t => t.state === "delivered").length;
300
+ $("phase").textContent = f.label; $("toys").textContent = `${done}/${total}`;
301
+ $("clock").textContent = `${f.t.toFixed(0)} s`;
302
+ $("contacts").textContent = f.stats.contacts; $("contacts").classList.toggle("bad", f.stats.contacts > 0);
303
+ if (f.stats.plans) {
304
+ $("ms").textContent = f.stats.msPerPlan.toFixed(0);
305
+ $("fps").textContent = Math.round(129 / (f.stats.msPerPlan / 1000)).toLocaleString();
306
+ $("cpuToy").textContent = done ? (f.stats.planMs / 1000 / done).toFixed(1) : "–";
307
+ }
308
+ if (f.ms) $("split").innerHTML = SPLIT.map(([k, c]) => `<i style="background:${c};flex:${Math.max(0.01, f.ms[k])}" title="${k} ${f.ms[k].toFixed(1)} ms"></i>`).join("");
309
+ if (f.terms) {
310
+ const scale = v => Math.min(100, 100 * Math.log10(1 + v) / 3);
311
+ for (const [k] of TERMS) {
312
+ const li = document.querySelector(`.terms li[data-k="${k}"]`), v = f.terms[k] || 0;
313
+ li.querySelector("i").style.width = scale(v) + "%"; li.querySelector(".v").textContent = v < 10 ? v.toFixed(1) : v.toFixed(0);
314
+ }
315
+ }
316
+ $("log").innerHTML = f.stats.events.slice().reverse().map(e => `<li><b>${e.t.toFixed(0)} s</b> ${e.what}</li>`).join("");
317
+ }
318
+ const DG = -0.5147;
319
+ function axisOf(x) { const sx = x[6], sy = x[7]; return [sx, sy, Math.sqrt(Math.max(1e-6, 1 - sx * sx - sy * sy))]; }
320
+ function gp(x) { const a = axisOf(x); return [x[0] + DG * a[0], x[1] + DG * a[1], x[2] + DG * a[2]]; }
321
+
322
+ worker.onmessage = ({ data: d }) => {
323
+ if (d.type === "frame") onFrame(d);
324
+ else if (d.type === "reach") setReach(d.map);
325
+ else if (d.type === "toast") toast(d.text);
326
+ else if (d.type === "running") setRunning(d.on);
327
+ else if (d.type === "done") { setRunning(false); toast(`Every reachable toy is in the hamper, in ${d.t.toFixed(0)} s of robot time.`); }
328
+ else if (d.type === "ready" && new URLSearchParams(location.search).has("autorun")) {
329
+ const sp = new URLSearchParams(location.search).get("speed");
330
+ if (sp) { worker.postMessage({ type: "speed", v: +sp }); document.querySelectorAll("[data-speed]").forEach(o => o.classList.toggle("on", o.dataset.speed === sp)); }
331
+ if (new URLSearchParams(location.search).has("follow")) { $("follow").checked = true; }
332
+ setRunning(true); worker.postMessage({ type: "run", on: true });
333
+ }
334
+ };
335
+ worker.postMessage({ type: "init" });
336
+ syncAllFurniture(); renderFurnList(); sendFurniture(true);
337
+
338
+ // ------------------------------------------------------------------------------------------- draw loop (robot pose interpolated between ticks)
339
+ const up = new THREE.Vector3(0, 0, 1), q = new THREE.Quaternion(), tmp = new THREE.Vector3();
340
+ function draw() {
341
+ requestAnimationFrame(draw);
342
+ controls.update();
343
+ if (curX) {
344
+ const a = Math.min(1, (performance.now() - tRecv) / interval), x = curX.map((v, i) => prevX[i] + (v - prevX[i]) * a);
345
+ robot.position.set(x[0], x[1], x[2]);
346
+ q.setFromUnitVectors(up, tmp.set(...axisOf(x))); robot.quaternion.copy(q);
347
+ wrist.rotation.z = x[10];
348
+ const open = (1 - Math.max(0, Math.min(1, x[12]))) * 59 * Math.PI / 180;
349
+ fingers.forEach(({ pivot, side }) => (pivot.rotation.y = -side * open));
350
+ const pos = lineGeo.attributes.position;
351
+ ROOM.mounts.forEach((M, i) => { pos.setXYZ(2 * i, ...M); pos.setXYZ(2 * i + 1, x[0], x[1], x[2]); });
352
+ pos.needsUpdate = true;
353
+ if ($("follow").checked) { // glide the view towards the hand, keep the visitor's angle
354
+ const g = gp(x), want = new THREE.Vector3(g[0], g[1], Math.max(0.2, g[2]));
355
+ const off = camera.position.clone().sub(controls.target);
356
+ if (off.length() > 2.4) off.setLength(off.length() * 0.97);
357
+ controls.target.lerp(want, 0.06); camera.position.copy(controls.target).add(off);
358
+ }
359
+ }
360
+ renderer.render(scene, camera);
361
+ }
362
+ new ResizeObserver(() => {
363
+ const w = stage.clientWidth, h = stage.clientHeight;
364
+ renderer.setSize(w, h, false); camera.aspect = w / Math.max(1, h); camera.updateProjectionMatrix();
365
+ }).observe(stage);
366
+ draw();
package.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"type":"module"}
style.css CHANGED
@@ -1,28 +1,96 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
 
 
 
 
 
4
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
 
 
 
 
 
 
10
 
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
 
 
 
 
17
 
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- .card p:last-child {
27
- margin-bottom: 0;
 
 
 
28
  }
 
 
1
+ /* MacroSwan mission. Dark by choice: the room is lit like a stage. Ember = the plan chosen, forest = imagined futures. */
2
+ :root {
3
+ --bg: #121212; --surface: #1a1a1a; --surface-2: #222220; --fg: #e8e3da; --muted: #a39d92; --line: #2c2b28;
4
+ --ember: #e68e0d; --forest: #5fb68b; --shadow: #a07ce0; --warn: #e5604a; --ok: #5fb68b;
5
+ --display: "Archivo", system-ui, sans-serif;
6
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
7
+ --mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
8
+ color-scheme: dark;
9
  }
10
+ * { box-sizing: border-box; }
11
+ html, body { height: 100%; }
12
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.5 var(--font); }
13
+ .app { display: grid; grid-template-columns: minmax(0, 1fr) 380px; height: 100%; }
14
+ .stage { position: relative; min-width: 0; min-height: 320px; }
15
+ #view { display: block; width: 100%; height: 100%; touch-action: none; cursor: crosshair; }
16
+ #view.grab { cursor: grabbing; }
17
+ .hint { position: absolute; left: 50%; bottom: 14px; transform: translateX(-50%); background: rgb(18 18 18 / 0.82);
18
+ border: 1px solid var(--line); border-radius: 999px; padding: 6px 14px; font-size: 12.5px; color: var(--muted);
19
+ white-space: nowrap; max-width: calc(100% - 24px); overflow: hidden; text-overflow: ellipsis; }
20
+ .toast { position: absolute; left: 50%; top: 16px; transform: translateX(-50%); background: var(--surface-2);
21
+ border: 1px solid var(--warn); color: var(--fg); padding: 8px 14px; border-radius: 8px; font-size: 13px; max-width: 90%; }
22
+ .legend { position: absolute; left: 14px; top: 14px; display: flex; flex-direction: column; gap: 4px; font-size: 12px;
23
+ color: var(--muted); background: rgb(18 18 18 / 0.75); padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line); }
24
+ .legend span { display: flex; align-items: center; gap: 8px; }
25
+ .sw { display: inline-block; width: 18px; height: 4px; border-radius: 2px; }
26
+ .sw.ember { background: var(--ember); } .sw.future { background: var(--forest); opacity: .7; }
27
+ .sw.shadow { background: var(--shadow); opacity: .6; height: 10px; }
28
 
29
+ .panel { border-left: 1px solid var(--line); overflow-y: auto; padding: 22px 20px 28px; display: flex; flex-direction: column; gap: 18px; }
30
+ .mark { font-family: var(--display); font-weight: 800; letter-spacing: .06em; text-transform: uppercase; font-size: 12px;
31
+ color: var(--ember); margin: 0 0 8px; }
32
+ .mark span { color: var(--forest); }
33
+ h1 { font-family: var(--display); font-weight: 800; font-size: 28px; line-height: 1.1; margin: 0 0 8px; text-wrap: balance; }
34
+ h2 { font-family: var(--display); font-weight: 700; font-size: 14px; margin: 0 0 10px; letter-spacing: .01em; }
35
+ .lede { color: var(--muted); margin: 0; }
36
+ .fine { color: var(--muted); font-size: 12px; margin: 8px 0 0; }
37
+ footer.fine p { margin: 0 0 6px; }
38
+ a { color: var(--ember); }
39
 
40
+ button { font: inherit; color: var(--fg); background: var(--surface-2); border: 1px solid var(--line); border-radius: 8px;
41
+ min-height: 36px; padding: 0 12px; cursor: pointer; }
42
+ button:hover { border-color: var(--muted); }
43
+ button:focus-visible, input:focus-visible { outline: 2px solid var(--ember); outline-offset: 2px; }
44
+ button.primary { background: var(--ember); color: #121212; border-color: var(--ember); font-weight: 600; min-width: 84px; }
45
+ button.ghost { background: transparent; }
46
+ .controls { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
47
+ .seg { display: inline-flex; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
48
+ .seg button { border: 0; border-radius: 0; background: transparent; min-width: 40px; color: var(--muted); }
49
+ .seg button.on { background: var(--surface-2); color: var(--fg); }
50
 
51
+ .status .phase { display: flex; align-items: center; gap: 8px; font-weight: 600; margin-bottom: 10px; }
52
+ .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex: none; }
53
+ .dot.live { background: var(--ember); box-shadow: 0 0 0 4px rgb(230 142 13 / .18); }
54
+ .kpis { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
55
+ .kpis div { display: flex; flex-direction: column; min-width: 0; }
56
+ .kpis b { font-family: var(--display); font-size: 20px; font-weight: 800; font-variant-numeric: tabular-nums; }
57
+ .kpis span { color: var(--muted); font-size: 11.5px; line-height: 1.3; }
58
+ #contacts.bad { color: var(--warn); }
59
+ .card { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 14px; }
60
+
61
+ .split { display: flex; height: 10px; border-radius: 3px; overflow: hidden; margin-top: 12px; gap: 2px; }
62
+ .split i { display: block; height: 100%; min-width: 2px; }
63
+ .split-key { display: flex; gap: 10px; flex-wrap: wrap; font-size: 11.5px; color: var(--muted); margin-top: 6px; }
64
+ .split-key span { display: inline-flex; align-items: center; gap: 5px; }
65
+ .split-key i { width: 8px; height: 8px; border-radius: 2px; display: inline-block; }
66
+
67
+ .terms { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 5px; }
68
+ .terms li { display: grid; grid-template-columns: 74px minmax(0, 1fr) 46px; gap: 8px; align-items: center; font-size: 12.5px; }
69
+ .terms .bar { height: 8px; background: var(--surface-2); border-radius: 0 4px 4px 0; position: relative; }
70
+ .terms .bar i { position: absolute; inset: 0 auto 0 0; background: var(--ember); border-radius: 0 4px 4px 0; min-width: 1px; }
71
+ .terms li[data-k="furniture"] .bar i, .terms li[data-k="lines"] .bar i { background: var(--shadow); }
72
+ .terms .v { font-family: var(--mono); font-size: 11.5px; text-align: right; color: var(--muted); font-variant-numeric: tabular-nums; }
73
+
74
+ .add { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
75
+ .add button { min-height: 32px; font-size: 13px; }
76
+ .furn { display: flex; flex-direction: column; gap: 6px; }
77
+ .fi { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; }
78
+ .fi.sel { border-color: var(--shadow); }
79
+ .fi .row { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
80
+ .fi .row b { font-weight: 600; font-size: 13px; }
81
+ .fi .row button { min-height: 26px; padding: 0 8px; font-size: 12px; }
82
+ .fi .sliders { display: grid; grid-template-columns: auto minmax(0, 1fr) 46px; gap: 2px 8px; align-items: center; margin-top: 6px; font-size: 12px; color: var(--muted); }
83
+ .fi .sliders output { font-family: var(--mono); font-size: 11.5px; text-align: right; }
84
+ input[type="range"] { width: 100%; accent-color: var(--shadow); }
85
+ .check { display: flex; gap: 8px; align-items: center; margin-top: 8px; font-size: 13px; color: var(--muted); }
86
+ .log { margin: 0; padding: 0 0 0 0; list-style: none; font-family: var(--mono); font-size: 11.5px; color: var(--muted);
87
+ display: flex; flex-direction: column; gap: 2px; min-height: 40px; }
88
+ .log li b { color: var(--fg); font-weight: 500; }
89
 
90
+ @media (max-width: 860px) {
91
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-rows: 58vh auto; height: auto; }
92
+ .panel { border-left: 0; border-top: 1px solid var(--line); overflow: visible;
93
+ padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); }
94
+ .hint { white-space: normal; text-align: center; border-radius: 10px; }
95
  }
96
+ @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
thumbnail.png ADDED

Git LFS Details

  • SHA256: fe47fb5bed94bc5bbe273fa3eb5108f810021ef29b63015266789f75abacedd7
  • Pointer size: 131 Bytes
  • Size of remote file: 173 kB
tools/export_model.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export cablepilot's released world model (weights/stringman_g1.pt) to JSON for the browser, plus test fixtures.
2
+
3
+ cd ~/Projects/pilothub/cablepilot && .venv/bin/python ../mission/tools/export_model.py
4
+
5
+ Writes mission/core/model.json (weights, normaliser, config) and mission/tools/fixtures.json (a rollout computed by
6
+ PyTorch on the mission room's mounts, that tools/test.mjs checks the JS port against).
7
+ """
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import torch
14
+ import yaml
15
+
16
+ CP = Path.cwd()
17
+ sys.path.insert(0, str(CP))
18
+ from cablepilot.model.learned import LearnedCDPRModel # noqa: E402
19
+
20
+ OUT = Path(__file__).resolve().parents[1]
21
+ ckpt = torch.load(CP / "weights/stringman_g1.pt", weights_only=True)
22
+
23
+
24
+ def t(v):
25
+ return np.asarray(v.detach().float().cpu()).round(7).tolist()
26
+
27
+
28
+ model = {
29
+ "config": ckpt["config"],
30
+ "jepa": {k: t(v) for k, v in ckpt["jepa"].items()},
31
+ "prober": {k: t(v) for k, v in ckpt["prober"].items()},
32
+ "norm": {k: t(v) for k, v in ckpt["norm"].items()},
33
+ "source": "MacroSwan/cablepilot, the released world model",
34
+ }
35
+ (OUT / "core/model.json").write_text(json.dumps(model))
36
+
37
+ # the mission's fictional room (core/mission.js ROOM.mounts)
38
+ M = np.asarray([[2.22, 1.92, 2.52], [-2.22, 1.92, 2.48], [-2.22, -1.92, 2.55], [2.22, -1.92, 2.50]], np.float32)
39
+ wm = LearnedCDPRModel(ckpt, dt=0.2, mounts=M)
40
+ rng = np.random.default_rng(0)
41
+ x = np.zeros(14, np.float32)
42
+ x[0:3] = [0.1, 0.2, 1.3]
43
+ x[3:6] = [0.05, -0.02, 0.0]
44
+ x[6:8] = [0.02, -0.01]
45
+ x[8:10] = [0.05, 0.03]
46
+ cmd = np.array([0.05, -0.02, 0.0, 0.0, 0.0], np.float32)
47
+ wm.reset_history(x, cmd)
48
+ xs, cs = [], []
49
+ for k in range(3): # a little real history, so the encoder sees motion
50
+ x2 = x.copy()
51
+ x2[0:3] += (k + 1) * 0.1 * x[3:6]
52
+ wm.observe(x2, cmd)
53
+ fut = (rng.normal(size=(3, 10, 5)) * [0.1, 0.1, 0.05, 0.3, 0.0]).astype(np.float32)
54
+ fut[..., 4] = [0.0, 0.5, 1.0][0]
55
+ out = wm.rollout(None, None, fut).numpy()
56
+ fx = {
57
+ "mounts": M.tolist(),
58
+ "states": np.stack(wm.states).tolist(),
59
+ "cmds": np.stack(wm.cmds).tolist(),
60
+ "future": fut.tolist(),
61
+ "rollout": out.tolist(),
62
+ }
63
+ (OUT / "tools/fixtures.json").write_text(json.dumps(fx))
64
+ print("model.json", (OUT / "core/model.json").stat().st_size // 1024, "KB; fixture rollout", out.shape,
65
+ "final p", out[0, -1, :3])
tools/fixtures.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"mounts": [[2.2200000286102295, 1.9199999570846558, 2.5199999809265137], [-2.2200000286102295, 1.9199999570846558, 2.4800000190734863], [-2.2200000286102295, -1.9199999570846558, 2.549999952316284], [2.2200000286102295, -1.9199999570846558, 2.5]], "states": [[0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10000000149011612, 0.20000000298023224, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10500000417232513, 0.1979999989271164, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.10999999940395355, 0.19600000977516174, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0], [0.11500000208616257, 0.1940000057220459, 1.2999999523162842, 0.05000000074505806, -0.019999999552965164, 0.0, 0.019999999552965164, -0.009999999776482582, 0.05000000074505806, 0.029999999329447746, 0.0, 0.0, 0.0, 0.0]], "cmds": [[0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0], [0.05000000074505806, -0.019999999552965164, 0.0, 0.0, 0.0]], "future": [[[0.01257302239537239, -0.013210486620664597, 0.03202113136649132, 0.03147003427147865, 0.0], [0.03615950420498848, 0.13040000200271606, 0.04735404998064041, -0.2111205756664276, 0.0], [-0.062327444553375244, 0.004132597707211971, -0.11625153571367264, -0.0656374990940094, 0.0], [-0.07322673499584198, -0.05442589893937111, -0.01581500843167305, 0.12348916381597519, 0.0], [-0.012853465974330902, 0.1366463452577591, -0.03325973451137543, 0.1054530218243599, 0.0], [0.0094012301415205, -0.07434992492198944, -0.04608627036213875, -0.1373177468776703, 0.0], [-0.10096181929111481, -0.020917557179927826, -0.007961250841617584, 0.16225367784500122, 0.0], [0.035537272691726685, -0.06538286060094833, -0.006480681709945202, 0.23519264161586761, 0.0], [-0.1259065568447113, 0.1513923704624176, 0.06729377061128616, 0.2343934178352356, 0.0], [-0.031392280012369156, 0.1458020657300949, 0.09801291674375534, 0.540490448474884, 0.0]], [[0.03573803976178169, -0.12083186209201813, -0.00022270665795076638, 0.19694247841835022, 0.0], [0.03951220586895943, 0.042986370623111725, 0.034802135080099106, -0.35523539781570435, 0.0], [-0.0436435230076313, -0.1169801875948906, 0.08696839213371277, -0.1487732231616974, 0.0], [-0.02585725486278534, 0.15834729373455048, 0.06601805239915848, 0.19000579416751862, 0.0], [0.005202897358685732, 0.06836862117052078, 0.05019807815551758, -0.18537211418151855, 0.0], [-0.13204309344291687, -0.06615280359983444, 0.04675249755382538, 0.014716384001076221, 0.0], [0.01885191909968853, -0.06331940740346909, -0.01887817494571209, -0.32734382152557373, 0.0], [0.06304115056991577, 0.05811658129096031, 0.06472793966531754, -0.22638173401355743, 0.0], [-0.02873877063393593, 0.15744082629680634, -0.021639293059706688, -0.2206449806690216, 0.0], [0.1031453087925911, 0.016100957989692688, -0.029276441782712936, -0.40236592292785645, 0.0]], [[0.05026828497648239, 0.09897129982709885, -0.008214729838073254, -0.3223094642162323, 0.0], [-0.1280393898487091, -0.07130680978298187, 0.031050892546772957, -0.6750423312187195, 0.0], [-0.058164082467556, 0.010927969589829445, -0.003785076318308711, 0.060634318739175797, 0.0], [-0.07583697140216827, 0.14209820330142975, 0.036304689943790436, 0.2531197965145111, 0.0], [0.07875882089138031, 0.08440786600112915, 0.0037796804681420326, -0.42803215980529785, 0.0], [-0.07695146650075912, -0.1422741711139679, 0.012922639958560467, -0.17056483030319214, 0.0], [-0.1043001115322113, 0.02684170752763748, 0.017933597788214684, 0.3967372477054596, 0.0], [0.10418397933244705, 0.14022648334503174, 0.057508282363414764, -0.7095911502838135, 0.0], [0.03396200016140938, 0.04237713664770126, 0.01856137067079544, 0.11482714861631393, 0.0], [-0.0358913317322731, -0.1901635229587555, -0.005445736460387707, -0.24111954867839813, 0.0]]], "rollout": [[[0.12402722239494324, 0.19023390114307404, 1.3006945848464966, 0.036565639078617096, -0.017109517008066177, 0.008963239379227161, 0.009135043248534203, -0.008510737679898739, -0.13547885417938232, -0.008057246915996075, 0.002010987838730216, 0.025188371539115906, 0.01066553220152855, 0.00972101092338562], [0.13010554015636444, 0.18884219229221344, 1.304046869277954, 0.03078395687043667, 0.007037260103970766, 0.023297837004065514, -0.022193724289536476, -0.009677872993052006, -0.13094834983348846, 0.01182114239782095, -0.008079640567302704, -0.16664794087409973, 0.011628241278231144, 0.0017136335372924805], [0.13490916788578033, 0.19276951253414154, 1.3086204528808594, 0.010668816044926643, 0.017929233610630035, 0.01524091325700283, -0.03378969803452492, -0.006431441754102707, -0.01182522065937519, -0.012054217047989368, -0.03868003934621811, -0.09107254445552826, 0.011813636869192123, -0.00038930773735046387], [0.13298210501670837, 0.1942315548658371, 1.3094736337661743, -0.02485404536128044, -0.0053301118314266205, -0.000676113530062139, -0.026241498067975044, -0.01826113648712635, 0.07064604014158249, -0.09518533200025558, -0.040709689259529114, 0.08651842921972275, 0.01069862861186266, -0.0017524510622024536], [0.12636534869670868, 0.19239862263202667, 1.30841064453125, -0.028873000293970108, 0.0016047884710133076, -0.010051155462861061, -0.0055481139570474625, -0.031255483627319336, 0.13698312640190125, 0.0055718086659908295, -0.019028550013899803, 0.1072227731347084, 0.010468488559126854, -0.0011655539274215698], [0.12258820980787277, 0.19455178081989288, 1.305155634880066, -0.00969030149281025, 0.001533815637230873, -0.02150237374007702, 0.019755259156227112, -0.016760606318712234, 0.09683062136173248, 0.0698971301317215, -0.013945470564067364, -0.09145210683345795, 0.00929915439337492, -0.001320183277130127], [0.12025725841522217, 0.19194377958774567, 1.3004412651062012, -0.023621121421456337, -0.01740693300962448, -0.020786209031939507, 0.017333852127194405, -0.011160564608871937, -0.11965328454971313, 0.007593768183141947, -0.019472768530249596, 0.1066577285528183, 0.00834305863827467, -0.0005019605159759521], [0.11392800509929657, 0.18717284500598907, 1.2971771955490112, -0.02232256531715393, -0.03369074687361717, -0.013293338008224964, -0.017290957272052765, -0.014605862088501453, -0.1421763002872467, -0.045358315110206604, 0.015053978189826012, 0.2190016806125641, 0.011400080285966396, 0.005173251032829285], [0.11056661605834961, 0.1807062029838562, 1.295971155166626, -0.027723632752895355, -0.019975554198026657, 0.003483012318611145, -0.02959423139691353, -0.020716873928904533, -0.02567393332719803, 0.015573905780911446, 0.061194539070129395, 0.23350317776203156, 0.010955480858683586, -0.0007605552673339844], [0.10233653336763382, 0.1810452938079834, 1.2995374202728271, -0.040857598185539246, 0.018562642857432365, 0.0292698722332716, -0.023559445515275, -0.005188561975955963, 0.095396026968956, 0.11093609780073166, 0.1282740831375122, 0.4831957519054413, 0.011142279952764511, 0.0004771202802658081]], [[0.12459491193294525, 0.18846511840820312, 1.3001495599746704, 0.044358983635902405, -0.040722355246543884, 0.001250139088369906, 0.010377105325460434, -0.01237791683524847, -0.11900854110717773, -0.058082666248083115, 0.012873848900198936, 0.15944331884384155, 0.010649549774825573, 0.009418517351150513], [0.13285546004772186, 0.17872413992881775, 1.3010824918746948, 0.04020673409104347, -0.03907402977347374, 0.010388972237706184, -0.018505869433283806, -0.025576617568731308, -0.13363467156887054, -0.020087411627173424, 0.014099063351750374, -0.2526845633983612, 0.011032906360924244, 0.0001967400312423706], [0.13913367688655853, 0.1725379377603531, 1.3051222562789917, 0.0178122129291296, -0.040413595736026764, 0.029825951904058456, -0.03397874906659126, -0.0190094243735075, -0.03785523772239685, 0.028380509465932846, -0.03827103227376938, -0.18363413214683533, 0.00997370295226574, -0.00018364191055297852], [0.13917942345142365, 0.1631641387939453, 1.3134022951126099, -0.00986326765269041, -0.03612584248185158, 0.04822481796145439, -0.030505752190947533, -0.013851012103259563, 0.06561807543039322, 0.05883663892745972, -0.0473688580095768, 0.12546980381011963, 0.010627222247421741, -0.00045008957386016846], [0.1368132382631302, 0.1602877527475357, 1.3238918781280518, -0.007347492501139641, 0.0020451867021620274, 0.05333616957068443, -0.0063299573957920074, 0.00426325760781765, 0.1576155424118042, 0.09741618484258652, -0.03719589486718178, -0.11910723149776459, 0.01064110454171896, -9.097158908843994e-05], [0.1344062089920044, 0.1622486710548401, 1.3344404697418213, -0.024802174419164658, 0.0007272558286786079, 0.051986295729875565, 0.015952197834849358, 0.01152019388973713, 0.03149593621492386, -0.05478512868285179, -0.05798301473259926, -0.020530441775918007, 0.008695986121892929, -0.0025387555360794067], [0.1275998055934906, 0.15876515209674835, 1.343903660774231, -0.025667710229754448, -0.030201133340597153, 0.03972320631146431, 0.003870674641802907, -0.018128300085663795, -0.08063997328281403, -0.1903982162475586, -0.07915571331977844, -0.265287309885025, 0.010737411677837372, 0.0032363086938858032], [0.12609213590621948, 0.15234783291816711, 1.3508323431015015, 0.0075562382116913795, -0.021453604102134705, 0.03872907534241676, -0.005740380845963955, -0.04280123859643936, -0.010799814015626907, -0.017355557531118393, -0.13500583171844482, -0.24328702688217163, 0.009441345930099487, -0.0020869970321655273], [0.12910985946655273, 0.15212324261665344, 1.3588392734527588, 0.0071917204186320305, 0.015178792178630829, 0.033736515790224075, -0.0030942519661039114, -0.017207246273756027, -0.005007131956517696, 0.21656285226345062, -0.18075230717658997, -0.2226334810256958, 0.009299122728407383, -0.00026385486125946045], [0.13015228509902954, 0.1578507125377655, 1.3634504079818726, 0.016812793910503387, 0.028144223615527153, 0.015055235475301743, -0.004836793523281813, 0.025329330936074257, 0.02155124768614769, 0.14490686357021332, -0.23700794577598572, -0.3693296015262604, 0.010855448432266712, 0.0024356842041015625]], [[0.12502136826515198, 0.1917276829481125, 1.2999902963638306, 0.050225697457790375, 0.002244428265839815, -0.0009684788528829813, 0.011364211328327656, -0.004732115659862757, -0.10584680736064911, 0.03686441108584404, -0.021308712661266327, -0.2622954845428467, 0.011424288153648376, 0.010567516088485718], [0.13294880092144012, 0.19401457905769348, 1.3002105951309204, 0.02508864551782608, 0.002400767058134079, 0.006568626035004854, -0.019352644681930542, -0.0031709838658571243, -0.17843401432037354, -0.05679422616958618, -0.10624898225069046, -0.6074880957603455, 0.009836286306381226, -0.0009057968854904175], [0.1335977464914322, 0.19229763746261597, 1.3023455142974854, -0.012702255509793758, -0.00582309253513813, 0.00945094134658575, -0.04693383723497391, -0.02291780896484852, -0.0788516029715538, -0.08208990097045898, -0.18973903357982635, -0.07545491307973862, 0.010495693422853947, 0.000901535153388977], [0.12760353088378906, 0.1938134729862213, 1.3044555187225342, -0.042969975620508194, 0.02207103930413723, 0.015744825825095177, -0.041178926825523376, -0.023670535534620285, 0.10882141441106796, 0.06812678277492523, -0.17146636545658112, 0.21141962707042694, 0.010496387258172035, -0.0006456822156906128], [0.11900433897972107, 0.202080637216568, 1.308334231376648, -0.030536022037267685, 0.05383891239762306, 0.018108190968632698, -0.0018200254999101162, 0.0016827627550810575, 0.260520339012146, 0.1415773332118988, -0.16798345744609833, -0.3029029369354248, 0.010993923991918564, -7.967650890350342e-05], [0.11497710645198822, 0.21256373822689056, 1.3115506172180176, -0.02784333936870098, 0.040466584265232086, 0.015864089131355286, 0.039286352694034576, 0.013081122189760208, 0.08366185426712036, -0.046159639954566956, -0.23049920797348022, -0.21405716240406036, 0.007726581301540136, -0.004399582743644714], [0.10594824701547623, 0.21772770583629608, 1.31488835811615, -0.059015221893787384, 0.023443007841706276, 0.017737355083227158, 0.01707940734922886, -0.0160574559122324, -0.23980064690113068, -0.1750672608613968, -0.22964070737361908, 0.28701627254486084, 0.008143247105181217, 0.0008707195520401001], [0.0936676487326622, 0.22410237789154053, 1.3192936182022095, -0.049568019807338715, 0.044679637998342514, 0.028638942167162895, -0.03208165615797043, -0.03708634525537491, -0.17038485407829285, -0.014931097626686096, -0.2285221964120865, -0.5067258477210999, 0.011696800589561462, 0.005549877882003784], [0.08789973706007004, 0.23531001806259155, 1.3259241580963135, -0.013728151097893715, 0.05410953611135483, 0.03187448903918266, -0.03058687597513199, -0.019889485090970993, 0.14018341898918152, 0.11999672651290894, -0.30553776025772095, -0.031404830515384674, 0.01012816559523344, -0.0019149929285049438], [0.08677390217781067, 0.24333456158638, 1.3313698768615723, -0.011078476905822754, 0.025164294987916946, 0.022025125101208687, 0.01130332238972187, -0.004618940409272909, 0.1948319971561432, 0.017213910818099976, -0.31292441487312317, -0.18019817769527435, 0.00938254315406084, -0.002829998731613159]]]}
tools/run_headless.mjs ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // node tools/run_headless.mjs [seconds] : run the mission without a page and print what happened (the smoke test).
2
+ import { readFileSync } from "node:fs";
3
+ import { loadModel } from "../core/model.js";
4
+ import { Mission } from "../core/mission.js";
5
+
6
+ const secs = +(process.argv[2] || 120);
7
+ const m = loadModel(JSON.parse(readFileSync(new URL("../core/model.json", import.meta.url))));
8
+ const mis = new Mission(m, 0);
9
+ let f, last = "";
10
+ const t0 = performance.now();
11
+ while (mis.t < secs) {
12
+ f = mis.step();
13
+ const ev = f.stats.events.at(-1);
14
+ if (ev && JSON.stringify(ev) !== last) { last = JSON.stringify(ev); console.log(`${ev.t.toFixed(1).padStart(6)} s ${ev.what}`); }
15
+ if (f.toys.every(t => t.state === "delivered")) break;
16
+ }
17
+ const wall = (performance.now() - t0) / 1000;
18
+ console.log(`\n${f.stats.delivered}/${f.toys.length} toys in ${f.t.toFixed(0)} s simulated, ${wall.toFixed(1)} s wall` +
19
+ ` | ${f.stats.msPerPlan.toFixed(0)} ms per plan | furniture contact ticks ${f.stats.contacts} | phase ${f.phase}`);
tools/shot.mjs ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // node tools/shot.mjs <url> <out.png> [wait_s] [WxH] : real-time headless check over the DevTools protocol (no
2
+ // Playwright): loads the page, waits, prints console messages and exceptions, saves a screenshot.
3
+ import { spawn } from "node:child_process";
4
+ import { mkdtempSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ const [url, out, waitS = "20", size = "1400x860"] = process.argv.slice(2);
9
+ const [W, H] = size.split("x").map(Number);
10
+ const port = 9300 + Math.floor(Math.random() * 500);
11
+ const prof = mkdtempSync(join(process.env.SHOT_DIR || tmpdir(), "shot-"));
12
+ const chr = spawn("chromium", ["--headless=new", "--no-sandbox", `--user-data-dir=${prof}`, "--enable-unsafe-swiftshader",
13
+ "--use-angle=swiftshader", `--remote-debugging-port=${port}`, `--window-size=${W},${H}`, "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
14
+ let errlog = ""; chr.stderr.on("data", d => (errlog += d));
15
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
16
+ let tab;
17
+ for (let i = 0; i < 150 && !tab; i++) {
18
+ await sleep(200);
19
+ try { tab = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).find(t => t.type === "page"); } catch {}
20
+ if (!tab && i > 20 && i % 10 === 0) try { tab = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json(); } catch {}
21
+ }
22
+ if (!tab) { console.error("no DevTools page", errlog.slice(0, 800)); chr.kill(); process.exit(1); }
23
+ const ws = new WebSocket(tab.webSocketDebuggerUrl);
24
+ await new Promise(r => (ws.onopen = r));
25
+ let id = 0; const pending = new Map();
26
+ const send = (method, params = {}) => new Promise(r => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); });
27
+ ws.onmessage = ({ data }) => {
28
+ const m = JSON.parse(data);
29
+ if (m.id && pending.has(m.id)) { pending.get(m.id)(m.result); pending.delete(m.id); }
30
+ if (m.method === "Runtime.consoleAPICalled") console.log("CONSOLE", m.params.type, m.params.args.map(a => a.value ?? a.description).join(" "));
31
+ if (m.method === "Runtime.exceptionThrown") console.log("EXCEPTION", m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text);
32
+ if (m.method === "Log.entryAdded" && m.params.entry.level === "error") console.log("LOG", m.params.entry.text, m.params.entry.url || "");
33
+ };
34
+ await send("Runtime.enable"); await send("Log.enable"); await send("Page.enable");
35
+ await send("Emulation.setDeviceMetricsOverride", { width: W, height: H, deviceScaleFactor: 1, mobile: W < 600 });
36
+ await send("Page.navigate", { url });
37
+ await sleep(+waitS * 1000);
38
+ const probe = await send("Runtime.evaluate", { expression: `JSON.stringify({phase: document.getElementById('phase')?.textContent, toys: document.getElementById('toys')?.textContent, clock: document.getElementById('clock')?.textContent, ms: document.getElementById('ms')?.textContent, contacts: document.getElementById('contacts')?.textContent, overflowX: document.documentElement.scrollWidth > innerWidth})`, returnByValue: true });
39
+ console.log("STATE", probe.result.value);
40
+ const shot = await send("Page.captureScreenshot", { format: "png" });
41
+ writeFileSync(out, Buffer.from(shot.data, "base64"));
42
+ ws.close(); chr.kill();
43
+ console.log("saved", out);
tools/test.mjs ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // node tools/test.mjs : the JS world model must reproduce PyTorch's rollout (tools/fixtures.json) to < 1e-4 m.
2
+ import { readFileSync } from "node:fs";
3
+ import { loadModel, rollout } from "../core/model.js";
4
+
5
+ const here = new URL(".", import.meta.url);
6
+ const m = loadModel(JSON.parse(readFileSync(new URL("../core/model.json", here))));
7
+ const fx = JSON.parse(readFileSync(new URL("fixtures.json", here)));
8
+ const S = fx.future.length, T = fx.future[0].length;
9
+ const plans = Float32Array.from(fx.future.flat(2));
10
+ const t0 = performance.now();
11
+ const out = rollout(m, fx.mounts, fx.states, fx.cmds, plans, S, T);
12
+ let maxErr = 0, worst = -1;
13
+ const ref = fx.rollout.flat(2);
14
+ for (let i = 0; i < ref.length; i++) { const e = Math.abs(out[i] - ref[i]); if (e > maxErr) { maxErr = e; worst = i; } }
15
+ console.log(`rollout ${S}x${T}: max |js - torch| = ${maxErr.toExponential(2)} (index ${worst % 14} of the state)`);
16
+ const big = new Float32Array(128 * T * 5).map((_, i) => plans[i % plans.length]);
17
+ const t1 = performance.now();
18
+ for (let r = 0; r < 5; r++) rollout(m, fx.mounts, fx.states, fx.cmds, big, 128, T);
19
+ console.log(`S=128, T=10: ${((performance.now() - t1) / 5).toFixed(1)} ms per rollout (node, one thread)`);
20
+ if (!(maxErr < 1e-4)) { console.error("FAIL"); process.exit(1); }
21
+ console.log("PASS");
vendor/addons/controls/OrbitControls.js ADDED
@@ -0,0 +1,1523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Controls,
3
+ MOUSE,
4
+ Quaternion,
5
+ Spherical,
6
+ TOUCH,
7
+ Vector2,
8
+ Vector3,
9
+ Plane,
10
+ Ray,
11
+ MathUtils
12
+ } from 'three';
13
+
14
+ // OrbitControls performs orbiting, dollying (zooming), and panning.
15
+ // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
16
+ //
17
+ // Orbit - left mouse / touch: one-finger move
18
+ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
19
+ // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
20
+
21
+ const _changeEvent = { type: 'change' };
22
+ const _startEvent = { type: 'start' };
23
+ const _endEvent = { type: 'end' };
24
+ const _ray = new Ray();
25
+ const _plane = new Plane();
26
+ const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
27
+
28
+ const _v = new Vector3();
29
+ const _twoPI = 2 * Math.PI;
30
+
31
+ const _STATE = {
32
+ NONE: - 1,
33
+ ROTATE: 0,
34
+ DOLLY: 1,
35
+ PAN: 2,
36
+ TOUCH_ROTATE: 3,
37
+ TOUCH_PAN: 4,
38
+ TOUCH_DOLLY_PAN: 5,
39
+ TOUCH_DOLLY_ROTATE: 6
40
+ };
41
+ const _EPS = 0.000001;
42
+
43
+ class OrbitControls extends Controls {
44
+
45
+ constructor( object, domElement = null ) {
46
+
47
+ super( object, domElement );
48
+
49
+ this.state = _STATE.NONE;
50
+
51
+ // Set to false to disable this control
52
+ this.enabled = true;
53
+
54
+ // "target" sets the location of focus, where the object orbits around
55
+ this.target = new Vector3();
56
+
57
+ // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect
58
+ this.cursor = new Vector3();
59
+
60
+ // How far you can dolly in and out ( PerspectiveCamera only )
61
+ this.minDistance = 0;
62
+ this.maxDistance = Infinity;
63
+
64
+ // How far you can zoom in and out ( OrthographicCamera only )
65
+ this.minZoom = 0;
66
+ this.maxZoom = Infinity;
67
+
68
+ // Limit camera target within a spherical area around the cursor
69
+ this.minTargetRadius = 0;
70
+ this.maxTargetRadius = Infinity;
71
+
72
+ // How far you can orbit vertically, upper and lower limits.
73
+ // Range is 0 to Math.PI radians.
74
+ this.minPolarAngle = 0; // radians
75
+ this.maxPolarAngle = Math.PI; // radians
76
+
77
+ // How far you can orbit horizontally, upper and lower limits.
78
+ // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
79
+ this.minAzimuthAngle = - Infinity; // radians
80
+ this.maxAzimuthAngle = Infinity; // radians
81
+
82
+ // Set to true to enable damping (inertia)
83
+ // If damping is enabled, you must call controls.update() in your animation loop
84
+ this.enableDamping = false;
85
+ this.dampingFactor = 0.05;
86
+
87
+ // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
88
+ // Set to false to disable zooming
89
+ this.enableZoom = true;
90
+ this.zoomSpeed = 1.0;
91
+
92
+ // Set to false to disable rotating
93
+ this.enableRotate = true;
94
+ this.rotateSpeed = 1.0;
95
+
96
+ // Set to false to disable panning
97
+ this.enablePan = true;
98
+ this.panSpeed = 1.0;
99
+ this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
100
+ this.keyPanSpeed = 7.0; // pixels moved per arrow key push
101
+ this.zoomToCursor = false;
102
+
103
+ // Set to true to automatically rotate around the target
104
+ // If auto-rotate is enabled, you must call controls.update() in your animation loop
105
+ this.autoRotate = false;
106
+ this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
107
+
108
+ // The four arrow keys
109
+ this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
110
+
111
+ // Mouse buttons
112
+ this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
113
+
114
+ // Touch fingers
115
+ this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
116
+
117
+ // for reset
118
+ this.target0 = this.target.clone();
119
+ this.position0 = this.object.position.clone();
120
+ this.zoom0 = this.object.zoom;
121
+
122
+ // the target DOM element for key events
123
+ this._domElementKeyEvents = null;
124
+
125
+ // internals
126
+
127
+ this._lastPosition = new Vector3();
128
+ this._lastQuaternion = new Quaternion();
129
+ this._lastTargetPosition = new Vector3();
130
+
131
+ // so camera.up is the orbit axis
132
+ this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
133
+ this._quatInverse = this._quat.clone().invert();
134
+
135
+ // current position in spherical coordinates
136
+ this._spherical = new Spherical();
137
+ this._sphericalDelta = new Spherical();
138
+
139
+ this._scale = 1;
140
+ this._panOffset = new Vector3();
141
+
142
+ this._rotateStart = new Vector2();
143
+ this._rotateEnd = new Vector2();
144
+ this._rotateDelta = new Vector2();
145
+
146
+ this._panStart = new Vector2();
147
+ this._panEnd = new Vector2();
148
+ this._panDelta = new Vector2();
149
+
150
+ this._dollyStart = new Vector2();
151
+ this._dollyEnd = new Vector2();
152
+ this._dollyDelta = new Vector2();
153
+
154
+ this._dollyDirection = new Vector3();
155
+ this._mouse = new Vector2();
156
+ this._performCursorZoom = false;
157
+
158
+ this._pointers = [];
159
+ this._pointerPositions = {};
160
+
161
+ this._controlActive = false;
162
+
163
+ // event listeners
164
+
165
+ this._onPointerMove = onPointerMove.bind( this );
166
+ this._onPointerDown = onPointerDown.bind( this );
167
+ this._onPointerUp = onPointerUp.bind( this );
168
+ this._onContextMenu = onContextMenu.bind( this );
169
+ this._onMouseWheel = onMouseWheel.bind( this );
170
+ this._onKeyDown = onKeyDown.bind( this );
171
+
172
+ this._onTouchStart = onTouchStart.bind( this );
173
+ this._onTouchMove = onTouchMove.bind( this );
174
+
175
+ this._onMouseDown = onMouseDown.bind( this );
176
+ this._onMouseMove = onMouseMove.bind( this );
177
+
178
+ this._interceptControlDown = interceptControlDown.bind( this );
179
+ this._interceptControlUp = interceptControlUp.bind( this );
180
+
181
+ //
182
+
183
+ if ( this.domElement !== null ) {
184
+
185
+ this.connect();
186
+
187
+ }
188
+
189
+ this.update();
190
+
191
+ }
192
+
193
+ connect() {
194
+
195
+ this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
196
+ this.domElement.addEventListener( 'pointercancel', this._onPointerUp );
197
+
198
+ this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
199
+ this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } );
200
+
201
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
202
+ document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } );
203
+
204
+ this.domElement.style.touchAction = 'none'; // disable touch scroll
205
+
206
+ }
207
+
208
+ disconnect() {
209
+
210
+ this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
211
+ this.domElement.removeEventListener( 'pointermove', this._onPointerMove );
212
+ this.domElement.removeEventListener( 'pointerup', this._onPointerUp );
213
+ this.domElement.removeEventListener( 'pointercancel', this._onPointerUp );
214
+
215
+ this.domElement.removeEventListener( 'wheel', this._onMouseWheel );
216
+ this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
217
+
218
+ this.stopListenToKeyEvents();
219
+
220
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
221
+ document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } );
222
+
223
+ this.domElement.style.touchAction = 'auto';
224
+
225
+ }
226
+
227
+ dispose() {
228
+
229
+ this.disconnect();
230
+
231
+ }
232
+
233
+ getPolarAngle() {
234
+
235
+ return this._spherical.phi;
236
+
237
+ }
238
+
239
+ getAzimuthalAngle() {
240
+
241
+ return this._spherical.theta;
242
+
243
+ }
244
+
245
+ getDistance() {
246
+
247
+ return this.object.position.distanceTo( this.target );
248
+
249
+ }
250
+
251
+ listenToKeyEvents( domElement ) {
252
+
253
+ domElement.addEventListener( 'keydown', this._onKeyDown );
254
+ this._domElementKeyEvents = domElement;
255
+
256
+ }
257
+
258
+ stopListenToKeyEvents() {
259
+
260
+ if ( this._domElementKeyEvents !== null ) {
261
+
262
+ this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown );
263
+ this._domElementKeyEvents = null;
264
+
265
+ }
266
+
267
+ }
268
+
269
+ saveState() {
270
+
271
+ this.target0.copy( this.target );
272
+ this.position0.copy( this.object.position );
273
+ this.zoom0 = this.object.zoom;
274
+
275
+ }
276
+
277
+ reset() {
278
+
279
+ this.target.copy( this.target0 );
280
+ this.object.position.copy( this.position0 );
281
+ this.object.zoom = this.zoom0;
282
+
283
+ this.object.updateProjectionMatrix();
284
+ this.dispatchEvent( _changeEvent );
285
+
286
+ this.update();
287
+
288
+ this.state = _STATE.NONE;
289
+
290
+ }
291
+
292
+ update( deltaTime = null ) {
293
+
294
+ const position = this.object.position;
295
+
296
+ _v.copy( position ).sub( this.target );
297
+
298
+ // rotate offset to "y-axis-is-up" space
299
+ _v.applyQuaternion( this._quat );
300
+
301
+ // angle from z-axis around y-axis
302
+ this._spherical.setFromVector3( _v );
303
+
304
+ if ( this.autoRotate && this.state === _STATE.NONE ) {
305
+
306
+ this._rotateLeft( this._getAutoRotationAngle( deltaTime ) );
307
+
308
+ }
309
+
310
+ if ( this.enableDamping ) {
311
+
312
+ this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;
313
+ this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;
314
+
315
+ } else {
316
+
317
+ this._spherical.theta += this._sphericalDelta.theta;
318
+ this._spherical.phi += this._sphericalDelta.phi;
319
+
320
+ }
321
+
322
+ // restrict theta to be between desired limits
323
+
324
+ let min = this.minAzimuthAngle;
325
+ let max = this.maxAzimuthAngle;
326
+
327
+ if ( isFinite( min ) && isFinite( max ) ) {
328
+
329
+ if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI;
330
+
331
+ if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI;
332
+
333
+ if ( min <= max ) {
334
+
335
+ this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) );
336
+
337
+ } else {
338
+
339
+ this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ?
340
+ Math.max( min, this._spherical.theta ) :
341
+ Math.min( max, this._spherical.theta );
342
+
343
+ }
344
+
345
+ }
346
+
347
+ // restrict phi to be between desired limits
348
+ this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) );
349
+
350
+ this._spherical.makeSafe();
351
+
352
+
353
+ // move target to panned location
354
+
355
+ if ( this.enableDamping === true ) {
356
+
357
+ this.target.addScaledVector( this._panOffset, this.dampingFactor );
358
+
359
+ } else {
360
+
361
+ this.target.add( this._panOffset );
362
+
363
+ }
364
+
365
+ // Limit the target distance from the cursor to create a sphere around the center of interest
366
+ this.target.sub( this.cursor );
367
+ this.target.clampLength( this.minTargetRadius, this.maxTargetRadius );
368
+ this.target.add( this.cursor );
369
+
370
+ let zoomChanged = false;
371
+ // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
372
+ // we adjust zoom later in these cases
373
+ if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) {
374
+
375
+ this._spherical.radius = this._clampDistance( this._spherical.radius );
376
+
377
+ } else {
378
+
379
+ const prevRadius = this._spherical.radius;
380
+ this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale );
381
+ zoomChanged = prevRadius != this._spherical.radius;
382
+
383
+ }
384
+
385
+ _v.setFromSpherical( this._spherical );
386
+
387
+ // rotate offset back to "camera-up-vector-is-up" space
388
+ _v.applyQuaternion( this._quatInverse );
389
+
390
+ position.copy( this.target ).add( _v );
391
+
392
+ this.object.lookAt( this.target );
393
+
394
+ if ( this.enableDamping === true ) {
395
+
396
+ this._sphericalDelta.theta *= ( 1 - this.dampingFactor );
397
+ this._sphericalDelta.phi *= ( 1 - this.dampingFactor );
398
+
399
+ this._panOffset.multiplyScalar( 1 - this.dampingFactor );
400
+
401
+ } else {
402
+
403
+ this._sphericalDelta.set( 0, 0, 0 );
404
+
405
+ this._panOffset.set( 0, 0, 0 );
406
+
407
+ }
408
+
409
+ // adjust camera position
410
+ if ( this.zoomToCursor && this._performCursorZoom ) {
411
+
412
+ let newRadius = null;
413
+ if ( this.object.isPerspectiveCamera ) {
414
+
415
+ // move the camera down the pointer ray
416
+ // this method avoids floating point error
417
+ const prevRadius = _v.length();
418
+ newRadius = this._clampDistance( prevRadius * this._scale );
419
+
420
+ const radiusDelta = prevRadius - newRadius;
421
+ this.object.position.addScaledVector( this._dollyDirection, radiusDelta );
422
+ this.object.updateMatrixWorld();
423
+
424
+ zoomChanged = !! radiusDelta;
425
+
426
+ } else if ( this.object.isOrthographicCamera ) {
427
+
428
+ // adjust the ortho camera position based on zoom changes
429
+ const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 );
430
+ mouseBefore.unproject( this.object );
431
+
432
+ const prevZoom = this.object.zoom;
433
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
434
+ this.object.updateProjectionMatrix();
435
+
436
+ zoomChanged = prevZoom !== this.object.zoom;
437
+
438
+ const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 );
439
+ mouseAfter.unproject( this.object );
440
+
441
+ this.object.position.sub( mouseAfter ).add( mouseBefore );
442
+ this.object.updateMatrixWorld();
443
+
444
+ newRadius = _v.length();
445
+
446
+ } else {
447
+
448
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
449
+ this.zoomToCursor = false;
450
+
451
+ }
452
+
453
+ // handle the placement of the target
454
+ if ( newRadius !== null ) {
455
+
456
+ if ( this.screenSpacePanning ) {
457
+
458
+ // position the orbit target in front of the new camera position
459
+ this.target.set( 0, 0, - 1 )
460
+ .transformDirection( this.object.matrix )
461
+ .multiplyScalar( newRadius )
462
+ .add( this.object.position );
463
+
464
+ } else {
465
+
466
+ // get the ray and translation plane to compute target
467
+ _ray.origin.copy( this.object.position );
468
+ _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix );
469
+
470
+ // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
471
+ // extremely large values
472
+ if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) {
473
+
474
+ this.object.lookAt( this.target );
475
+
476
+ } else {
477
+
478
+ _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target );
479
+ _ray.intersectPlane( _plane, this.target );
480
+
481
+ }
482
+
483
+ }
484
+
485
+ }
486
+
487
+ } else if ( this.object.isOrthographicCamera ) {
488
+
489
+ const prevZoom = this.object.zoom;
490
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
491
+
492
+ if ( prevZoom !== this.object.zoom ) {
493
+
494
+ this.object.updateProjectionMatrix();
495
+ zoomChanged = true;
496
+
497
+ }
498
+
499
+ }
500
+
501
+ this._scale = 1;
502
+ this._performCursorZoom = false;
503
+
504
+ // update condition is:
505
+ // min(camera displacement, camera rotation in radians)^2 > EPS
506
+ // using small-angle approximation cos(x/2) = 1 - x^2 / 8
507
+
508
+ if ( zoomChanged ||
509
+ this._lastPosition.distanceToSquared( this.object.position ) > _EPS ||
510
+ 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS ||
511
+ this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) {
512
+
513
+ this.dispatchEvent( _changeEvent );
514
+
515
+ this._lastPosition.copy( this.object.position );
516
+ this._lastQuaternion.copy( this.object.quaternion );
517
+ this._lastTargetPosition.copy( this.target );
518
+
519
+ return true;
520
+
521
+ }
522
+
523
+ return false;
524
+
525
+ }
526
+
527
+ _getAutoRotationAngle( deltaTime ) {
528
+
529
+ if ( deltaTime !== null ) {
530
+
531
+ return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime;
532
+
533
+ } else {
534
+
535
+ return _twoPI / 60 / 60 * this.autoRotateSpeed;
536
+
537
+ }
538
+
539
+ }
540
+
541
+ _getZoomScale( delta ) {
542
+
543
+ const normalizedDelta = Math.abs( delta * 0.01 );
544
+ return Math.pow( 0.95, this.zoomSpeed * normalizedDelta );
545
+
546
+ }
547
+
548
+ _rotateLeft( angle ) {
549
+
550
+ this._sphericalDelta.theta -= angle;
551
+
552
+ }
553
+
554
+ _rotateUp( angle ) {
555
+
556
+ this._sphericalDelta.phi -= angle;
557
+
558
+ }
559
+
560
+ _panLeft( distance, objectMatrix ) {
561
+
562
+ _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
563
+ _v.multiplyScalar( - distance );
564
+
565
+ this._panOffset.add( _v );
566
+
567
+ }
568
+
569
+ _panUp( distance, objectMatrix ) {
570
+
571
+ if ( this.screenSpacePanning === true ) {
572
+
573
+ _v.setFromMatrixColumn( objectMatrix, 1 );
574
+
575
+ } else {
576
+
577
+ _v.setFromMatrixColumn( objectMatrix, 0 );
578
+ _v.crossVectors( this.object.up, _v );
579
+
580
+ }
581
+
582
+ _v.multiplyScalar( distance );
583
+
584
+ this._panOffset.add( _v );
585
+
586
+ }
587
+
588
+ // deltaX and deltaY are in pixels; right and down are positive
589
+ _pan( deltaX, deltaY ) {
590
+
591
+ const element = this.domElement;
592
+
593
+ if ( this.object.isPerspectiveCamera ) {
594
+
595
+ // perspective
596
+ const position = this.object.position;
597
+ _v.copy( position ).sub( this.target );
598
+ let targetDistance = _v.length();
599
+
600
+ // half of the fov is center to top of screen
601
+ targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 );
602
+
603
+ // we use only clientHeight here so aspect ratio does not distort speed
604
+ this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix );
605
+ this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix );
606
+
607
+ } else if ( this.object.isOrthographicCamera ) {
608
+
609
+ // orthographic
610
+ this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix );
611
+ this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix );
612
+
613
+ } else {
614
+
615
+ // camera neither orthographic nor perspective
616
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
617
+ this.enablePan = false;
618
+
619
+ }
620
+
621
+ }
622
+
623
+ _dollyOut( dollyScale ) {
624
+
625
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
626
+
627
+ this._scale /= dollyScale;
628
+
629
+ } else {
630
+
631
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
632
+ this.enableZoom = false;
633
+
634
+ }
635
+
636
+ }
637
+
638
+ _dollyIn( dollyScale ) {
639
+
640
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
641
+
642
+ this._scale *= dollyScale;
643
+
644
+ } else {
645
+
646
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
647
+ this.enableZoom = false;
648
+
649
+ }
650
+
651
+ }
652
+
653
+ _updateZoomParameters( x, y ) {
654
+
655
+ if ( ! this.zoomToCursor ) {
656
+
657
+ return;
658
+
659
+ }
660
+
661
+ this._performCursorZoom = true;
662
+
663
+ const rect = this.domElement.getBoundingClientRect();
664
+ const dx = x - rect.left;
665
+ const dy = y - rect.top;
666
+ const w = rect.width;
667
+ const h = rect.height;
668
+
669
+ this._mouse.x = ( dx / w ) * 2 - 1;
670
+ this._mouse.y = - ( dy / h ) * 2 + 1;
671
+
672
+ this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize();
673
+
674
+ }
675
+
676
+ _clampDistance( dist ) {
677
+
678
+ return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) );
679
+
680
+ }
681
+
682
+ //
683
+ // event callbacks - update the object state
684
+ //
685
+
686
+ _handleMouseDownRotate( event ) {
687
+
688
+ this._rotateStart.set( event.clientX, event.clientY );
689
+
690
+ }
691
+
692
+ _handleMouseDownDolly( event ) {
693
+
694
+ this._updateZoomParameters( event.clientX, event.clientX );
695
+ this._dollyStart.set( event.clientX, event.clientY );
696
+
697
+ }
698
+
699
+ _handleMouseDownPan( event ) {
700
+
701
+ this._panStart.set( event.clientX, event.clientY );
702
+
703
+ }
704
+
705
+ _handleMouseMoveRotate( event ) {
706
+
707
+ this._rotateEnd.set( event.clientX, event.clientY );
708
+
709
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
710
+
711
+ const element = this.domElement;
712
+
713
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
714
+
715
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
716
+
717
+ this._rotateStart.copy( this._rotateEnd );
718
+
719
+ this.update();
720
+
721
+ }
722
+
723
+ _handleMouseMoveDolly( event ) {
724
+
725
+ this._dollyEnd.set( event.clientX, event.clientY );
726
+
727
+ this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart );
728
+
729
+ if ( this._dollyDelta.y > 0 ) {
730
+
731
+ this._dollyOut( this._getZoomScale( this._dollyDelta.y ) );
732
+
733
+ } else if ( this._dollyDelta.y < 0 ) {
734
+
735
+ this._dollyIn( this._getZoomScale( this._dollyDelta.y ) );
736
+
737
+ }
738
+
739
+ this._dollyStart.copy( this._dollyEnd );
740
+
741
+ this.update();
742
+
743
+ }
744
+
745
+ _handleMouseMovePan( event ) {
746
+
747
+ this._panEnd.set( event.clientX, event.clientY );
748
+
749
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
750
+
751
+ this._pan( this._panDelta.x, this._panDelta.y );
752
+
753
+ this._panStart.copy( this._panEnd );
754
+
755
+ this.update();
756
+
757
+ }
758
+
759
+ _handleMouseWheel( event ) {
760
+
761
+ this._updateZoomParameters( event.clientX, event.clientY );
762
+
763
+ if ( event.deltaY < 0 ) {
764
+
765
+ this._dollyIn( this._getZoomScale( event.deltaY ) );
766
+
767
+ } else if ( event.deltaY > 0 ) {
768
+
769
+ this._dollyOut( this._getZoomScale( event.deltaY ) );
770
+
771
+ }
772
+
773
+ this.update();
774
+
775
+ }
776
+
777
+ _handleKeyDown( event ) {
778
+
779
+ let needsUpdate = false;
780
+
781
+ switch ( event.code ) {
782
+
783
+ case this.keys.UP:
784
+
785
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
786
+
787
+ this._rotateUp( _twoPI * this.rotateSpeed / this.domElement.clientHeight );
788
+
789
+ } else {
790
+
791
+ this._pan( 0, this.keyPanSpeed );
792
+
793
+ }
794
+
795
+ needsUpdate = true;
796
+ break;
797
+
798
+ case this.keys.BOTTOM:
799
+
800
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
801
+
802
+ this._rotateUp( - _twoPI * this.rotateSpeed / this.domElement.clientHeight );
803
+
804
+ } else {
805
+
806
+ this._pan( 0, - this.keyPanSpeed );
807
+
808
+ }
809
+
810
+ needsUpdate = true;
811
+ break;
812
+
813
+ case this.keys.LEFT:
814
+
815
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
816
+
817
+ this._rotateLeft( _twoPI * this.rotateSpeed / this.domElement.clientHeight );
818
+
819
+ } else {
820
+
821
+ this._pan( this.keyPanSpeed, 0 );
822
+
823
+ }
824
+
825
+ needsUpdate = true;
826
+ break;
827
+
828
+ case this.keys.RIGHT:
829
+
830
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
831
+
832
+ this._rotateLeft( - _twoPI * this.rotateSpeed / this.domElement.clientHeight );
833
+
834
+ } else {
835
+
836
+ this._pan( - this.keyPanSpeed, 0 );
837
+
838
+ }
839
+
840
+ needsUpdate = true;
841
+ break;
842
+
843
+ }
844
+
845
+ if ( needsUpdate ) {
846
+
847
+ // prevent the browser from scrolling on cursor keys
848
+ event.preventDefault();
849
+
850
+ this.update();
851
+
852
+ }
853
+
854
+
855
+ }
856
+
857
+ _handleTouchStartRotate( event ) {
858
+
859
+ if ( this._pointers.length === 1 ) {
860
+
861
+ this._rotateStart.set( event.pageX, event.pageY );
862
+
863
+ } else {
864
+
865
+ const position = this._getSecondPointerPosition( event );
866
+
867
+ const x = 0.5 * ( event.pageX + position.x );
868
+ const y = 0.5 * ( event.pageY + position.y );
869
+
870
+ this._rotateStart.set( x, y );
871
+
872
+ }
873
+
874
+ }
875
+
876
+ _handleTouchStartPan( event ) {
877
+
878
+ if ( this._pointers.length === 1 ) {
879
+
880
+ this._panStart.set( event.pageX, event.pageY );
881
+
882
+ } else {
883
+
884
+ const position = this._getSecondPointerPosition( event );
885
+
886
+ const x = 0.5 * ( event.pageX + position.x );
887
+ const y = 0.5 * ( event.pageY + position.y );
888
+
889
+ this._panStart.set( x, y );
890
+
891
+ }
892
+
893
+ }
894
+
895
+ _handleTouchStartDolly( event ) {
896
+
897
+ const position = this._getSecondPointerPosition( event );
898
+
899
+ const dx = event.pageX - position.x;
900
+ const dy = event.pageY - position.y;
901
+
902
+ const distance = Math.sqrt( dx * dx + dy * dy );
903
+
904
+ this._dollyStart.set( 0, distance );
905
+
906
+ }
907
+
908
+ _handleTouchStartDollyPan( event ) {
909
+
910
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
911
+
912
+ if ( this.enablePan ) this._handleTouchStartPan( event );
913
+
914
+ }
915
+
916
+ _handleTouchStartDollyRotate( event ) {
917
+
918
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
919
+
920
+ if ( this.enableRotate ) this._handleTouchStartRotate( event );
921
+
922
+ }
923
+
924
+ _handleTouchMoveRotate( event ) {
925
+
926
+ if ( this._pointers.length == 1 ) {
927
+
928
+ this._rotateEnd.set( event.pageX, event.pageY );
929
+
930
+ } else {
931
+
932
+ const position = this._getSecondPointerPosition( event );
933
+
934
+ const x = 0.5 * ( event.pageX + position.x );
935
+ const y = 0.5 * ( event.pageY + position.y );
936
+
937
+ this._rotateEnd.set( x, y );
938
+
939
+ }
940
+
941
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
942
+
943
+ const element = this.domElement;
944
+
945
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
946
+
947
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
948
+
949
+ this._rotateStart.copy( this._rotateEnd );
950
+
951
+ }
952
+
953
+ _handleTouchMovePan( event ) {
954
+
955
+ if ( this._pointers.length === 1 ) {
956
+
957
+ this._panEnd.set( event.pageX, event.pageY );
958
+
959
+ } else {
960
+
961
+ const position = this._getSecondPointerPosition( event );
962
+
963
+ const x = 0.5 * ( event.pageX + position.x );
964
+ const y = 0.5 * ( event.pageY + position.y );
965
+
966
+ this._panEnd.set( x, y );
967
+
968
+ }
969
+
970
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
971
+
972
+ this._pan( this._panDelta.x, this._panDelta.y );
973
+
974
+ this._panStart.copy( this._panEnd );
975
+
976
+ }
977
+
978
+ _handleTouchMoveDolly( event ) {
979
+
980
+ const position = this._getSecondPointerPosition( event );
981
+
982
+ const dx = event.pageX - position.x;
983
+ const dy = event.pageY - position.y;
984
+
985
+ const distance = Math.sqrt( dx * dx + dy * dy );
986
+
987
+ this._dollyEnd.set( 0, distance );
988
+
989
+ this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) );
990
+
991
+ this._dollyOut( this._dollyDelta.y );
992
+
993
+ this._dollyStart.copy( this._dollyEnd );
994
+
995
+ const centerX = ( event.pageX + position.x ) * 0.5;
996
+ const centerY = ( event.pageY + position.y ) * 0.5;
997
+
998
+ this._updateZoomParameters( centerX, centerY );
999
+
1000
+ }
1001
+
1002
+ _handleTouchMoveDollyPan( event ) {
1003
+
1004
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
1005
+
1006
+ if ( this.enablePan ) this._handleTouchMovePan( event );
1007
+
1008
+ }
1009
+
1010
+ _handleTouchMoveDollyRotate( event ) {
1011
+
1012
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
1013
+
1014
+ if ( this.enableRotate ) this._handleTouchMoveRotate( event );
1015
+
1016
+ }
1017
+
1018
+ // pointers
1019
+
1020
+ _addPointer( event ) {
1021
+
1022
+ this._pointers.push( event.pointerId );
1023
+
1024
+ }
1025
+
1026
+ _removePointer( event ) {
1027
+
1028
+ delete this._pointerPositions[ event.pointerId ];
1029
+
1030
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
1031
+
1032
+ if ( this._pointers[ i ] == event.pointerId ) {
1033
+
1034
+ this._pointers.splice( i, 1 );
1035
+ return;
1036
+
1037
+ }
1038
+
1039
+ }
1040
+
1041
+ }
1042
+
1043
+ _isTrackingPointer( event ) {
1044
+
1045
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
1046
+
1047
+ if ( this._pointers[ i ] == event.pointerId ) return true;
1048
+
1049
+ }
1050
+
1051
+ return false;
1052
+
1053
+ }
1054
+
1055
+ _trackPointer( event ) {
1056
+
1057
+ let position = this._pointerPositions[ event.pointerId ];
1058
+
1059
+ if ( position === undefined ) {
1060
+
1061
+ position = new Vector2();
1062
+ this._pointerPositions[ event.pointerId ] = position;
1063
+
1064
+ }
1065
+
1066
+ position.set( event.pageX, event.pageY );
1067
+
1068
+ }
1069
+
1070
+ _getSecondPointerPosition( event ) {
1071
+
1072
+ const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ];
1073
+
1074
+ return this._pointerPositions[ pointerId ];
1075
+
1076
+ }
1077
+
1078
+ //
1079
+
1080
+ _customWheelEvent( event ) {
1081
+
1082
+ const mode = event.deltaMode;
1083
+
1084
+ // minimal wheel event altered to meet delta-zoom demand
1085
+ const newEvent = {
1086
+ clientX: event.clientX,
1087
+ clientY: event.clientY,
1088
+ deltaY: event.deltaY,
1089
+ };
1090
+
1091
+ switch ( mode ) {
1092
+
1093
+ case 1: // LINE_MODE
1094
+ newEvent.deltaY *= 16;
1095
+ break;
1096
+
1097
+ case 2: // PAGE_MODE
1098
+ newEvent.deltaY *= 100;
1099
+ break;
1100
+
1101
+ }
1102
+
1103
+ // detect if event was triggered by pinching
1104
+ if ( event.ctrlKey && ! this._controlActive ) {
1105
+
1106
+ newEvent.deltaY *= 10;
1107
+
1108
+ }
1109
+
1110
+ return newEvent;
1111
+
1112
+ }
1113
+
1114
+ }
1115
+
1116
+ function onPointerDown( event ) {
1117
+
1118
+ if ( this.enabled === false ) return;
1119
+
1120
+ if ( this._pointers.length === 0 ) {
1121
+
1122
+ this.domElement.setPointerCapture( event.pointerId );
1123
+
1124
+ this.domElement.addEventListener( 'pointermove', this._onPointerMove );
1125
+ this.domElement.addEventListener( 'pointerup', this._onPointerUp );
1126
+
1127
+ }
1128
+
1129
+ //
1130
+
1131
+ if ( this._isTrackingPointer( event ) ) return;
1132
+
1133
+ //
1134
+
1135
+ this._addPointer( event );
1136
+
1137
+ if ( event.pointerType === 'touch' ) {
1138
+
1139
+ this._onTouchStart( event );
1140
+
1141
+ } else {
1142
+
1143
+ this._onMouseDown( event );
1144
+
1145
+ }
1146
+
1147
+ }
1148
+
1149
+ function onPointerMove( event ) {
1150
+
1151
+ if ( this.enabled === false ) return;
1152
+
1153
+ if ( event.pointerType === 'touch' ) {
1154
+
1155
+ this._onTouchMove( event );
1156
+
1157
+ } else {
1158
+
1159
+ this._onMouseMove( event );
1160
+
1161
+ }
1162
+
1163
+ }
1164
+
1165
+ function onPointerUp( event ) {
1166
+
1167
+ this._removePointer( event );
1168
+
1169
+ switch ( this._pointers.length ) {
1170
+
1171
+ case 0:
1172
+
1173
+ this.domElement.releasePointerCapture( event.pointerId );
1174
+
1175
+ this.domElement.removeEventListener( 'pointermove', this._onPointerMove );
1176
+ this.domElement.removeEventListener( 'pointerup', this._onPointerUp );
1177
+
1178
+ this.dispatchEvent( _endEvent );
1179
+
1180
+ this.state = _STATE.NONE;
1181
+
1182
+ break;
1183
+
1184
+ case 1:
1185
+
1186
+ const pointerId = this._pointers[ 0 ];
1187
+ const position = this._pointerPositions[ pointerId ];
1188
+
1189
+ // minimal placeholder event - allows state correction on pointer-up
1190
+ this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
1191
+
1192
+ break;
1193
+
1194
+ }
1195
+
1196
+ }
1197
+
1198
+ function onMouseDown( event ) {
1199
+
1200
+ let mouseAction;
1201
+
1202
+ switch ( event.button ) {
1203
+
1204
+ case 0:
1205
+
1206
+ mouseAction = this.mouseButtons.LEFT;
1207
+ break;
1208
+
1209
+ case 1:
1210
+
1211
+ mouseAction = this.mouseButtons.MIDDLE;
1212
+ break;
1213
+
1214
+ case 2:
1215
+
1216
+ mouseAction = this.mouseButtons.RIGHT;
1217
+ break;
1218
+
1219
+ default:
1220
+
1221
+ mouseAction = - 1;
1222
+
1223
+ }
1224
+
1225
+ switch ( mouseAction ) {
1226
+
1227
+ case MOUSE.DOLLY:
1228
+
1229
+ if ( this.enableZoom === false ) return;
1230
+
1231
+ this._handleMouseDownDolly( event );
1232
+
1233
+ this.state = _STATE.DOLLY;
1234
+
1235
+ break;
1236
+
1237
+ case MOUSE.ROTATE:
1238
+
1239
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
1240
+
1241
+ if ( this.enablePan === false ) return;
1242
+
1243
+ this._handleMouseDownPan( event );
1244
+
1245
+ this.state = _STATE.PAN;
1246
+
1247
+ } else {
1248
+
1249
+ if ( this.enableRotate === false ) return;
1250
+
1251
+ this._handleMouseDownRotate( event );
1252
+
1253
+ this.state = _STATE.ROTATE;
1254
+
1255
+ }
1256
+
1257
+ break;
1258
+
1259
+ case MOUSE.PAN:
1260
+
1261
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
1262
+
1263
+ if ( this.enableRotate === false ) return;
1264
+
1265
+ this._handleMouseDownRotate( event );
1266
+
1267
+ this.state = _STATE.ROTATE;
1268
+
1269
+ } else {
1270
+
1271
+ if ( this.enablePan === false ) return;
1272
+
1273
+ this._handleMouseDownPan( event );
1274
+
1275
+ this.state = _STATE.PAN;
1276
+
1277
+ }
1278
+
1279
+ break;
1280
+
1281
+ default:
1282
+
1283
+ this.state = _STATE.NONE;
1284
+
1285
+ }
1286
+
1287
+ if ( this.state !== _STATE.NONE ) {
1288
+
1289
+ this.dispatchEvent( _startEvent );
1290
+
1291
+ }
1292
+
1293
+ }
1294
+
1295
+ function onMouseMove( event ) {
1296
+
1297
+ switch ( this.state ) {
1298
+
1299
+ case _STATE.ROTATE:
1300
+
1301
+ if ( this.enableRotate === false ) return;
1302
+
1303
+ this._handleMouseMoveRotate( event );
1304
+
1305
+ break;
1306
+
1307
+ case _STATE.DOLLY:
1308
+
1309
+ if ( this.enableZoom === false ) return;
1310
+
1311
+ this._handleMouseMoveDolly( event );
1312
+
1313
+ break;
1314
+
1315
+ case _STATE.PAN:
1316
+
1317
+ if ( this.enablePan === false ) return;
1318
+
1319
+ this._handleMouseMovePan( event );
1320
+
1321
+ break;
1322
+
1323
+ }
1324
+
1325
+ }
1326
+
1327
+ function onMouseWheel( event ) {
1328
+
1329
+ if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return;
1330
+
1331
+ event.preventDefault();
1332
+
1333
+ this.dispatchEvent( _startEvent );
1334
+
1335
+ this._handleMouseWheel( this._customWheelEvent( event ) );
1336
+
1337
+ this.dispatchEvent( _endEvent );
1338
+
1339
+ }
1340
+
1341
+ function onKeyDown( event ) {
1342
+
1343
+ if ( this.enabled === false || this.enablePan === false ) return;
1344
+
1345
+ this._handleKeyDown( event );
1346
+
1347
+ }
1348
+
1349
+ function onTouchStart( event ) {
1350
+
1351
+ this._trackPointer( event );
1352
+
1353
+ switch ( this._pointers.length ) {
1354
+
1355
+ case 1:
1356
+
1357
+ switch ( this.touches.ONE ) {
1358
+
1359
+ case TOUCH.ROTATE:
1360
+
1361
+ if ( this.enableRotate === false ) return;
1362
+
1363
+ this._handleTouchStartRotate( event );
1364
+
1365
+ this.state = _STATE.TOUCH_ROTATE;
1366
+
1367
+ break;
1368
+
1369
+ case TOUCH.PAN:
1370
+
1371
+ if ( this.enablePan === false ) return;
1372
+
1373
+ this._handleTouchStartPan( event );
1374
+
1375
+ this.state = _STATE.TOUCH_PAN;
1376
+
1377
+ break;
1378
+
1379
+ default:
1380
+
1381
+ this.state = _STATE.NONE;
1382
+
1383
+ }
1384
+
1385
+ break;
1386
+
1387
+ case 2:
1388
+
1389
+ switch ( this.touches.TWO ) {
1390
+
1391
+ case TOUCH.DOLLY_PAN:
1392
+
1393
+ if ( this.enableZoom === false && this.enablePan === false ) return;
1394
+
1395
+ this._handleTouchStartDollyPan( event );
1396
+
1397
+ this.state = _STATE.TOUCH_DOLLY_PAN;
1398
+
1399
+ break;
1400
+
1401
+ case TOUCH.DOLLY_ROTATE:
1402
+
1403
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
1404
+
1405
+ this._handleTouchStartDollyRotate( event );
1406
+
1407
+ this.state = _STATE.TOUCH_DOLLY_ROTATE;
1408
+
1409
+ break;
1410
+
1411
+ default:
1412
+
1413
+ this.state = _STATE.NONE;
1414
+
1415
+ }
1416
+
1417
+ break;
1418
+
1419
+ default:
1420
+
1421
+ this.state = _STATE.NONE;
1422
+
1423
+ }
1424
+
1425
+ if ( this.state !== _STATE.NONE ) {
1426
+
1427
+ this.dispatchEvent( _startEvent );
1428
+
1429
+ }
1430
+
1431
+ }
1432
+
1433
+ function onTouchMove( event ) {
1434
+
1435
+ this._trackPointer( event );
1436
+
1437
+ switch ( this.state ) {
1438
+
1439
+ case _STATE.TOUCH_ROTATE:
1440
+
1441
+ if ( this.enableRotate === false ) return;
1442
+
1443
+ this._handleTouchMoveRotate( event );
1444
+
1445
+ this.update();
1446
+
1447
+ break;
1448
+
1449
+ case _STATE.TOUCH_PAN:
1450
+
1451
+ if ( this.enablePan === false ) return;
1452
+
1453
+ this._handleTouchMovePan( event );
1454
+
1455
+ this.update();
1456
+
1457
+ break;
1458
+
1459
+ case _STATE.TOUCH_DOLLY_PAN:
1460
+
1461
+ if ( this.enableZoom === false && this.enablePan === false ) return;
1462
+
1463
+ this._handleTouchMoveDollyPan( event );
1464
+
1465
+ this.update();
1466
+
1467
+ break;
1468
+
1469
+ case _STATE.TOUCH_DOLLY_ROTATE:
1470
+
1471
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
1472
+
1473
+ this._handleTouchMoveDollyRotate( event );
1474
+
1475
+ this.update();
1476
+
1477
+ break;
1478
+
1479
+ default:
1480
+
1481
+ this.state = _STATE.NONE;
1482
+
1483
+ }
1484
+
1485
+ }
1486
+
1487
+ function onContextMenu( event ) {
1488
+
1489
+ if ( this.enabled === false ) return;
1490
+
1491
+ event.preventDefault();
1492
+
1493
+ }
1494
+
1495
+ function interceptControlDown( event ) {
1496
+
1497
+ if ( event.key === 'Control' ) {
1498
+
1499
+ this._controlActive = true;
1500
+
1501
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
1502
+
1503
+ document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
1504
+
1505
+ }
1506
+
1507
+ }
1508
+
1509
+ function interceptControlUp( event ) {
1510
+
1511
+ if ( event.key === 'Control' ) {
1512
+
1513
+ this._controlActive = false;
1514
+
1515
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
1516
+
1517
+ document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
1518
+
1519
+ }
1520
+
1521
+ }
1522
+
1523
+ export { OrbitControls };
vendor/three.module.js ADDED
The diff for this file is too large to render. See raw diff
 
worker.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The robot's brain runs here, off the page's thread: the world model, MPPI and the mission. The page only draws.
2
+ import { loadModel } from "./core/model.js";
3
+ import { Mission } from "./core/mission.js";
4
+
5
+ let mis = null, running = false, speed = 1, timer = null;
6
+
7
+ const post = (type, data = {}) => postMessage({ type, ...data });
8
+ const sendReach = () => post("reach", { n: 100, map: mis.reachMap(100) });
9
+
10
+ async function init() {
11
+ const json = await (await fetch("./core/model.json")).json();
12
+ mis = new Mission(loadModel(json), 0);
13
+ sendReach();
14
+ post("frame", mis.frame(null));
15
+ post("ready");
16
+ }
17
+
18
+ function loop() {
19
+ timer = null;
20
+ if (!running || !mis) return;
21
+ const t0 = performance.now();
22
+ const f = mis.step();
23
+ post("frame", f);
24
+ if (f.phase === "idle" && f.toys.every(t => t.state !== "floor" || mis.placeable(t.x, t.y))) {
25
+ running = false; post("done", { t: f.t, stats: f.stats }); return;
26
+ }
27
+ const wall = performance.now() - t0, budget = speed === 0 ? 0 : 200 / speed; // 0.2 s of robot time per tick
28
+ timer = setTimeout(loop, Math.max(0, budget - wall));
29
+ }
30
+
31
+ onmessage = ({ data: d }) => {
32
+ if (d.type === "init") return void init();
33
+ if (!mis) return;
34
+ switch (d.type) {
35
+ case "run": running = d.on; if (running && !timer) loop(); break;
36
+ case "speed": speed = d.v; break;
37
+ case "furniture": mis.setFurniture(d.list); sendReach(); if (!running) post("frame", mis.frame(null)); break;
38
+ case "addToy": { const r = mis.addToy(d.x, d.y); if (!r.ok) post("toast", { text: r.why }); post("frame", mis.frame(null)); if (r.ok && !running && d.autostart) { running = true; if (!timer) loop(); post("running", { on: true }); } break; }
39
+ case "removeToy": mis.removeToy(d.id); post("frame", mis.frame(null)); break;
40
+ case "reset": running = false; mis.reset(); post("running", { on: false }); post("frame", mis.frame(null)); break;
41
+ }
42
+ };