File size: 29,497 Bytes
33c14d6
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
9ffd3e8
 
 
33c14d6
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
9ffd3e8
33c14d6
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
9ffd3e8
33c14d6
9ffd3e8
33c14d6
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110cee3
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
110cee3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
110cee3
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
9ffd3e8
33c14d6
 
9ffd3e8
33c14d6
9ffd3e8
33c14d6
9ffd3e8
 
 
 
 
 
 
 
 
 
 
110cee3
 
9ffd3e8
 
 
 
 
 
 
110cee3
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110cee3
9ffd3e8
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""Per-episode domain randomisation of a compiled model, from phase2_config.toml.

Every episode starts again from the nominal values stored at construction, so
ranges never compound. Only model arrays change; the scene file is untouched.

Layout: the board (turned half a turn when the robot plays white, at a random angle
and position) and the tray (either side, at a random angle) are redrawn until every
square centre and the tray's drop area are within the arm's reach and nothing
overlaps the deck or each other. The table then slides anywhere that still holds all
of them, so the board is sometimes near an edge or a corner with the floor in view.
Look: one to four of six lamps (kind, place, colour temperature, brightness, shadows),
table, floor, wall, board, piece, arm, deck and tray colours, and everyday clutter and
cables around the board. Cameras: the overhead camera anywhere a person could mount
it (place_overhead, called once the arm is at rest); the rover and wrist cameras only
move as much as remounting them would. Physics: piece mass and friction.
"""
from __future__ import annotations

import mujoco
import numpy as np

import scene_environment as env
from chess_world import SQUARES, ChessWorld, quat_yaw
from overlay import Camera, project

# (light, dark) square colours for vinyl boards, and piece colour pairs (white, black).
VINYL_BOARDS = [((0.93, 0.92, 0.84), (0.30, 0.52, 0.33)), ((0.94, 0.90, 0.80), (0.45, 0.30, 0.20)),
                ((0.95, 0.95, 0.93), (0.20, 0.35, 0.55)), ((0.90, 0.86, 0.74), (0.55, 0.40, 0.25)),
                ((0.96, 0.96, 0.96), (0.35, 0.35, 0.37))]
PIECE_COLOURS = [((0.93, 0.88, 0.76), (0.14, 0.11, 0.09)), ((0.95, 0.94, 0.92), (0.08, 0.08, 0.08)),
                 ((0.86, 0.72, 0.52), (0.30, 0.17, 0.10)), ((0.97, 0.93, 0.83), (0.45, 0.12, 0.10)),
                 ((0.90, 0.80, 0.62), (0.20, 0.14, 0.12))]
TABLE_FLAT = [(0.92, 0.92, 0.90), (0.55, 0.55, 0.57), (0.25, 0.25, 0.27), (0.80, 0.74, 0.64),
              (0.96, 0.95, 0.93), (0.35, 0.22, 0.14)]
# Printed-part colours of the arm (the owner's arm is white) and how often each is drawn.
ARM_COLOURS = {"white": (0.92, 0.92, 0.90), "ivory": (0.95, 0.92, 0.84), "yellow": (0.88, 0.67, 0.13),
               "orange": (0.95, 0.45, 0.10), "black": (0.10, 0.10, 0.11), "grey": (0.52, 0.53, 0.55),
               "red": (0.75, 0.12, 0.10), "blue": (0.15, 0.32, 0.72), "green": (0.20, 0.55, 0.28)}
ARM_WEIGHTS = np.array([0.30, 0.10, 0.12, 0.08, 0.12, 0.08, 0.07, 0.07, 0.06])
PRINTED_RGBA = (0.88, 0.67, 0.13)              # the printed-part colour in the scene file
FLOORS = ("oak_tex", "pale_wood_tex", "dark_wood_tex", "tile_tex", "carpet_tex", "concrete_tex", None)
LAMPS = ("window_key", "ceiling_fill", "ceiling_2", "desk_lamp", "sun", "fill_2")
# Clutter: footprint half extents in the body frame, footprint centre offset (y), tall?
CLUTTER = {"laptop": (0.155, 0.145, 0.036, True), "phone": (0.074, 0.036, 0.0, False),
           "mug": (0.07, 0.047, 0.0, True), "notebook": (0.105, 0.075, 0.0, False),
           "pen": (0.075, 0.006, 0.0, False)}
OLD_CABLES = ("arm_power_", "mains_cable_", "power_brick")   # fixed cables of the nominal scene


def _small_rotation(rng, deg):
    axis = rng.normal(size=3)
    axis /= np.linalg.norm(axis)
    angle = np.radians(rng.uniform(-deg, deg))
    return np.r_[np.cos(angle / 2), np.sin(angle / 2) * axis]


def _quat_mul(a, b):
    out = np.zeros(4)
    mujoco.mju_mulQuat(out, a, b)
    return out


def kelvin_rgb(k: float) -> np.ndarray:
    """Approximate sRGB colour of a black body at `k` kelvin, brightest channel 1."""
    t = k / 100
    r = 1.0 if t <= 66 else 1.292936 * (t - 60) ** -0.1332047
    g = 0.3900816 * np.log(t) - 0.6318414 if t <= 66 else 1.129891 * (t - 60) ** -0.0755148
    b = 1.0 if t >= 66 else (0.0 if t <= 19 else 0.5432068 * np.log(t - 10) - 1.1962541)
    rgb = np.clip([r, g, b], 0, 1)
    return rgb / rgb.max()


# ---------------------------------------------------------------------- 2D rectangles
def rect(cx, cy, hx, hy, yaw=0.0) -> np.ndarray:
    c, s = np.cos(yaw), np.sin(yaw)
    local = np.array([[-hx, -hy], [hx, -hy], [hx, hy], [-hx, hy]])
    return local @ np.array([[c, s], [-s, c]]) + [cx, cy]


def gap(a: np.ndarray, b: np.ndarray) -> float:
    """Separation of two convex polygons along their edge normals: a lower bound on
    their distance (negative when they overlap)."""
    best = -np.inf
    for poly in (a, b):
        for i in range(len(poly)):
            e = poly[(i + 1) % len(poly)] - poly[i]
            n = np.array([-e[1], e[0]]) / np.linalg.norm(e)
            pa, pb = a @ n, b @ n
            best = max(best, pb.min() - pa.max(), pa.min() - pb.max())
    return best


def inside(poly: np.ndarray, p, grow=0.0) -> bool:
    return gap(poly, np.array([p, p + [1e-6, 0], p + [0, 1e-6]])) < grow


class Randomizer:
    def __init__(self, m: mujoco.MjModel, world: ChessWorld, cfg: dict):
        self.m, self.world, self.cfg = m, world, cfg
        name = lambda i: m.geom(i).name
        # Hidden for good in phase 2: the overhead camera's mast (the camera moves anywhere)
        # and the nominal scene's fixed cables (replaced by randomised ones).
        mast = m.body("camera_mast").id
        for i in range(m.ngeom):
            if m.geom_bodyid[i] == mast or name(i).startswith(OLD_CABLES):
                m.geom_group[i] = 5
                m.geom_contype[i] = m.geom_conaffinity[i] = 0
        self.nominal = {k: getattr(m, k).copy() for k in (
            "mat_rgba", "mat_texid", "mat_specular", "mat_shininess", "geom_rgba", "geom_friction",
            "geom_group", "geom_pos", "geom_quat", "geom_size", "body_mass", "body_inertia", "body_pos",
            "body_quat", "light_pos", "light_dir", "light_diffuse", "light_specular", "light_ambient",
            "light_castshadow", "light_cutoff", "cam_pos", "cam_quat", "cam_fovy")}
        self.square_geoms = {"light": [], "dark": []}
        for i in range(m.ngeom):
            if name(i).startswith("sq_"):
                mat = m.material(m.geom_matid[i]).name
                self.square_geoms["dark" if mat == "dark_square_mat" else "light"].append(i)
        self.piece_visual = {c: [m.geom(f"{n}_visual").id for n in world.pieces if world.color[n] == c]
                             for c in "wb"}
        self.piece_collision = [i for i in range(m.ngeom)
                                if m.geom_bodyid[i] in world.body.values() and m.geom_group[i] == 3]
        hand = {m.body(b).id for b in ("gripper", "moving_jaw_so101_v1")}
        self.jaw_geoms = [i for i in range(m.ngeom) if m.geom_bodyid[i] in hand and m.geom_group[i] == 3]
        self.board_geoms = [i for i in range(m.ngeom) if m.geom_bodyid[i] == world.board and m.geom_contype[i]]
        self.textures = {m.texture(i).name: i for i in range(m.ntex)}
        self.mat = {m.material(i).name: i for i in range(m.nmat)}
        self.printed = [i for i in range(m.nmat) if np.allclose(m.mat_rgba[i, :3], PRINTED_RGBA)]
        self.cams = {n: m.camera(n).id for n in ("overhead", "rover", "wrist")}
        self.lights = {n: m.light(n).id for n in LAMPS}
        self.clutter = {k: m.body(f"clutter_{k}").id for k in CLUTTER}
        self.clutter_geoms = {k: [i for i in range(m.ngeom) if m.geom_bodyid[i] == b] for k, b in self.clutter.items()}
        self.cables = [[m.geom(f"cable_{k}_{i}").id for i in range(env.CABLE_SEGMENTS)] for k in range(env.CABLES)]
        root = m.body("base").id
        self.arm_bodies = set()
        for b in range(m.nbody):
            a = b
            while a > 0 and a != root:
                a = m.body_parentid[a]
            if a == root:
                self.arm_bodies.add(b)
        dk = mujoco.MjData(m)
        mujoco.mj_kinematics(m, dk)
        self.pan_xy = dk.xanchor[m.joint("shoulder_pan").id][:2].copy()
        self.board_half = float(m.geom_size[m.geom("board_border").id][0])     # playing area plus border
        self.deck = rect(env.DECK_CX, 0.0, env.DECK_HX, env.DECK_HALF_Y)

    # ------------------------------------------------------------------ per episode
    def apply(self, rng: np.random.Generator) -> dict:
        m = self.m
        for k, v in self.nominal.items():
            getattr(m, k)[:] = v
        info = {}
        self._layout(rng, info)
        self._table(rng, info)
        self._look(rng, info)
        self._lights(rng, info)
        self._clutter(rng, info)
        self._robot_cameras(rng, info)
        self._physics(rng, info)
        return info

    def _layout(self, rng, info):
        m, w, b, t = self.m, self.world, self.cfg["board"], self.cfg["tray"]
        white = bool(rng.random() < b["robot_plays_white_probability"])
        local = np.array([w.square_local[s][:2] for s in SQUARES])
        h = self.board_half
        # Each miss narrows the ranges, ending square and flush against the deck, which
        # sample_layout guarantees is in reach: large boards end up nearly square to the
        # robot (as they must be in reality), small ones use the full ranges.
        for attempt in range(500):
            k = max(0.0, 1 - attempt / 300)
            yaw = (np.pi if white else 0.0) + np.radians(k * rng.uniform(*b["yaw_deg"]))
            corners = rect(0, 0, h, h, yaw)
            cx = env.DECK_FRONT + b["deck_gap_m"] - corners[:, 0].min() + k * rng.uniform(*b["offset_x"])
            cy = k * rng.uniform(*b["offset_y"])
            c, s = np.cos(yaw), np.sin(yaw)
            centres = local @ np.array([[c, s], [-s, c]]) + [cx, cy]
            if np.linalg.norm(centres - self.pan_xy, axis=1).max() <= b["reach_m"]:
                break
        else:
            raise RuntimeError("no reachable board pose")
        m.body_pos[w.board] = [cx, cy, 0.0]
        m.body_quat[w.board] = quat_yaw(yaw)
        self.board_poly = rect(cx, cy, h, h, yaw)
        hx, hy = w.bin_half + 0.002
        drop = w.bin_half - 0.014                         # where the expert releases pieces
        first = 1.0 if rng.random() < t["left_probability"] else -1.0
        for attempt in range(600):
            side = first if attempt < 400 else -first      # the other side only if this one has no room
            az = side * np.radians(rng.uniform(*t["azimuth_deg"]))
            p = self.pan_xy + rng.uniform(*t["radius_m"]) * np.array([np.cos(az), np.sin(az)])
            tyaw = np.radians(rng.uniform(*t["yaw_deg"]))
            poly = rect(*p, hx, hy, tyaw)
            if gap(poly, self.board_poly) < t["board_gap_m"] or gap(poly, self.deck) < t["deck_gap_m"]:
                continue
            # The rover camera stalk and housing stand on the deck's front-right corner:
            # a tray tucked in beside them leaves the forearm no way past.
            if np.linalg.norm(p - env.ROVER_CAMERA_POS[:2]) < t["rover_camera_clearance_m"]:
                continue
            if np.linalg.norm(rect(*p, *drop, tyaw) - self.pan_xy, axis=1).max() <= t["reach_m"]:
                break
        else:
            raise RuntimeError("no reachable tray pose")
        m.body_pos[w.bin] = [p[0], p[1], 0.0]
        m.body_quat[w.bin] = quat_yaw(tyaw)
        self.tray_poly = poly
        info["board"] = dict(robot_plays="white" if white else "black", centre_m=[round(cx, 4), round(cy, 4)],
                             yaw_deg=round(float(np.degrees(yaw)), 2))
        info["tray"] = dict(side="left" if side > 0 else "right", centre_m=[round(float(p[0]), 4), round(float(p[1]), 4)],
                            yaw_deg=round(float(np.degrees(tyaw)), 2))

    def _table(self, rng, info):
        """Slide the table anywhere that keeps the deck, board and tray on it, U-shaped
        towards the limits so edges and corners (with the floor in view) come up often."""
        tb = self.cfg["table"]
        if "fixed_offset" in tb:
            dx, dy = tb["fixed_offset"]
            (cx, cy), (hx, hy) = env.TABLE_CENTER[:2], env.TABLE_HALF[:2]
            self.m.body_pos[self.world.table] = self.world.nominal_table_pos + [dx, dy, 0]
            self.table_poly = rect(cx + dx, cy + dy, hx, hy)
            info["table_offset_m"] = [dx, dy]
            return
        pts = np.vstack([self.deck, self.board_poly, self.tray_poly])
        lo, hi = pts.min(0) - tb["margin_m"], pts.max(0) + tb["margin_m"]
        (cx, cy), (hx, hy) = env.TABLE_CENTER[:2], env.TABLE_HALF[:2]
        dx_lo, dx_hi = max(hi[0] - (cx + hx), tb["back_edge_min_x"] - (cx - hx)), lo[0] - (cx - hx)
        dy_lo, dy_hi = hi[1] - (cy + hy), lo[1] - (cy - hy)
        dx = dx_lo + (dx_hi - dx_lo) * rng.beta(*tb["edge_bias"]) if dx_hi > dx_lo else 0.0
        dy = dy_lo + (dy_hi - dy_lo) * rng.beta(*tb["edge_bias"]) if dy_hi > dy_lo else 0.0
        self.m.body_pos[self.world.table] = self.world.nominal_table_pos + [dx, dy, 0]
        self.table_poly = rect(cx + dx, cy + dy, hx, hy)
        info["table_offset_m"] = [round(float(dx), 3), round(float(dy), 3)]

    def _pieces_and_arm(self, rng, info, a):
        m = self.m
        if a.get("piece_colours") == "black_white":
            white, black = PIECE_COLOURS[1]
        else:
            white, black = PIECE_COLOURS[rng.integers(len(PIECE_COLOURS))]
        for col, rgb in (("w", white), ("b", black)):
            m.geom_rgba[self.piece_visual[col], :3] = np.clip(np.array(rgb) * (1 + rng.uniform(-0.06, 0.06, 3)), 0, 1)
        names = a.get("arm_colours", list(ARM_COLOURS))
        weights = np.array([ARM_WEIGHTS[list(ARM_COLOURS).index(n)] for n in names])
        first = names[rng.choice(len(names), p=weights / weights.sum())]
        colours = {i: first for i in self.printed}
        if len(names) > 1 and rng.random() < a["two_tone_arm_probability"]:
            second = names[rng.integers(len(names))]
            for i in rng.choice(self.printed, size=len(self.printed) // 2, replace=False):
                colours[i] = second
        for i, c in colours.items():
            m.mat_rgba[i, :3] = np.clip(np.array(ARM_COLOURS[c]) * (1 + rng.uniform(-0.04, 0.04, 3)), 0, 1)
        info["arm_colour"] = first

    def _look(self, rng, info):
        m, a = self.m, self.cfg["appearance"]
        if a.get("fixed_look"):
            # Nominal board, table, floor, walls, deck and tray; only pieces and arm as configured.
            self._pieces_and_arm(rng, info, a)
            info.update(board_look="nominal", table_look="nominal", floor="nominal")
            return
        tex_rgb = mujoco.mjtTextureRole.mjTEXROLE_RGB
        wood = [self.textures[t] for t in ("oak_tex", "pale_wood_tex", "dark_wood_tex")]
        light_mat, dark_mat = self.mat["light_square_mat"], self.mat["dark_square_mat"]
        if rng.random() < a["flat_board_probability"]:
            light, dark = VINYL_BOARDS[rng.integers(len(VINYL_BOARDS))]
            m.mat_texid[light_mat, tex_rgb] = -1
            m.mat_texid[dark_mat, tex_rgb] = -1
            info["board_look"] = "vinyl"
        else:
            m.mat_texid[light_mat, tex_rgb] = self.textures["pale_wood_tex"] if rng.random() < 0.8 else wood[0]
            m.mat_texid[dark_mat, tex_rgb] = self.textures["dark_wood_tex"] if rng.random() < 0.8 else wood[0]
            light = np.array((0.98, 0.97, 0.94)) * (1 + rng.uniform(-a["tint"], a["tint"] / 3, 3))
            dark = np.array((0.95, 0.93, 0.90)) * (1 + rng.uniform(-a["tint"] * 2, a["tint"] / 3, 3))
            info["board_look"] = "wood"
        for kind, colour in (("light", light), ("dark", dark)):
            m.geom_rgba[self.square_geoms[kind], :3] = np.clip(colour, 0, 1)
        m.mat_rgba[self.mat["border_mat"], :3] *= 1 + rng.uniform(-a["tint"] * 2, a["tint"], 3)
        # Table: wood (pale laminate most often) or a flat colour, matte to glossy.
        table = self.mat["table_mat"]
        if rng.random() < 0.25:
            m.mat_texid[table, tex_rgb] = -1
            m.mat_rgba[table, :3] = TABLE_FLAT[rng.integers(len(TABLE_FLAT))]
            info["table_look"] = "flat"
        else:
            m.mat_texid[table, tex_rgb] = wood[rng.choice(3, p=[0.3, 0.5, 0.2])]
            m.mat_rgba[table, :3] = np.clip(1 + rng.uniform(-a["tint"] * 2, a["tint"], 3), 0, 1)
            info["table_look"] = "wood"
        m.mat_specular[table] = rng.uniform(*a["table_specular"])
        m.mat_shininess[table] = rng.uniform(*a["table_shininess"])
        # Floor and walls.
        floor = self.mat["floor_mat"]
        choice = FLOORS[rng.integers(len(FLOORS))]
        m.mat_texid[floor, tex_rgb] = -1 if choice is None else self.textures[choice]
        base = rng.uniform(0.25, 0.9, 3) if choice in (None, "carpet_tex", "tile_tex") else np.ones(3)
        m.mat_rgba[floor, :3] = np.clip(base * (1 + rng.uniform(-0.1, 0.1, 3)), 0, 1)
        info["floor"] = (choice or "flat").replace("_tex", "")
        m.mat_rgba[self.mat["wall_mat"], :3] = np.clip(rng.uniform(0.6, 0.97) * (1 + rng.uniform(-0.06, 0.06, 3)), 0, 1)
        # Pieces and arm (printed parts in one colour, sometimes two), then the deck and tray.
        self._pieces_and_arm(rng, info, a)
        m.mat_rgba[self.mat["case_mat"], :3] = rng.uniform(0.05, 0.85) * (1 + rng.uniform(-0.1, 0.1, 3))
        m.mat_rgba[self.mat["bin_mat"], :3] = rng.uniform(0.1, 0.85, 3)
        m.mat_rgba[self.mat["felt"], :3] = rng.uniform(0.05, 0.6, 3)
        m.mat_rgba[:] = np.clip(m.mat_rgba, 0, 1)

    def _lights(self, rng, info):
        m, L = self.m, self.cfg["lighting"]
        if L.get("fixed"):
            info["lights"] = dict(key="nominal", on=["window_key", "ceiling_fill"], ambient=0.55)
            return                                         # the scene's own window and ceiling lights
        for i in self.lights.values():
            m.light_diffuse[i] = m.light_specular[i] = 0
            m.light_castshadow[i] = 0
        centre = np.r_[m.body_pos[self.world.board][:2], self.world.board_top]
        kinds = list(L["key_weights"])
        key = kinds[rng.choice(len(kinds), p=np.array(list(L["key_weights"].values())) / sum(L["key_weights"].values()))]
        on = [key] + [n for n in LAMPS if n != key and rng.random() < L["extra_probability"]][:L["max_lights"] - 1]
        shadows = 0
        for n in on:
            i = self.lights[n]
            lo, hi = L["intensity"][n]
            colour = kelvin_rgb(rng.uniform(*(L["sun_k"] if n == "sun" else L["lamp_k"])))
            m.light_diffuse[i] = colour * rng.uniform(lo, hi)
            m.light_specular[i] = m.light_diffuse[i] * 0.3
            aim = centre + np.r_[rng.normal(0, 0.08, 2), 0]
            if n == "sun":
                el, az = np.radians(rng.uniform(*L["sun_elevation_deg"])), rng.uniform(0, 2 * np.pi)
                m.light_dir[i] = -np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])
            else:
                if n.startswith("ceiling"):
                    pos = centre + np.r_[rng.uniform(-0.8, 0.8, 2), rng.uniform(*L["ceiling_height_m"])]
                    aim = pos - [0, 0, 1] + np.r_[rng.normal(0, 0.25, 2), 0]
                else:
                    near = n == "desk_lamp"
                    dist = rng.uniform(*(L["desk_lamp_distance_m"] if near else L["window_distance_m"]))
                    az = rng.uniform(0, 2 * np.pi)
                    height = rng.uniform(*(L["desk_lamp_height_m"] if near else L["window_height_m"]))
                    pos = centre + np.r_[dist * np.cos(az), dist * np.sin(az), height]
                m.light_pos[i] = pos
                d = aim - pos
                m.light_dir[i] = d / np.linalg.norm(d)
                m.light_cutoff[i] = rng.uniform(*L["cutoff_deg"][n])
            if n != "fill_2" and (n == key or (shadows < L["max_shadows"] and rng.random() < 0.3)):
                m.light_castshadow[i] = 1
                shadows += 1
        amb = self.m.light("room_bounce").id
        m.light_ambient[amb] = kelvin_rgb(rng.uniform(*L["lamp_k"])) * rng.uniform(*L["ambient"])
        info["lights"] = dict(key=key, on=on, ambient=round(float(m.light_ambient[amb].max()), 3))

    def _clutter(self, rng, info):
        m, cl = self.m, self.cfg["clutter"]
        keep = [self.deck, self.board_poly, self.tray_poly]
        table = self.table_poly
        placed, present = [], []
        for k, (hx, hy, oy, tall) in CLUTTER.items():
            if rng.random() >= cl["probability"][k]:
                continue
            for _ in range(40):
                yaw = rng.uniform(0, 2 * np.pi)
                c, s = np.cos(yaw), np.sin(yaw)
                lo, hi = table.min(0) + 0.02, table.max(0) - 0.02
                pos = rng.uniform(lo, hi)
                centre = pos + [-s * oy, c * oy]
                poly = rect(*centre, hx, hy, yaw)
                if any(not inside(table, q, -0.005) for q in poly):
                    continue
                if min(gap(poly, p) for p in keep + placed) < cl["keep_out_m"]:
                    continue
                if tall and np.linalg.norm(centre - self.pan_xy) < cl["tall_min_reach_m"] and centre[0] > env.DECK_BACK - 0.03:
                    continue
                m.body_pos[self.clutter[k]] = [pos[0], pos[1], 0.0]
                m.body_quat[self.clutter[k]] = quat_yaw(yaw)
                m.geom_group[self.clutter_geoms[k]] = 1
                placed.append(poly)
                present.append(k)
                break
        for mat in ("device_mat", "device2_mat", "mug_mat", "notebook_mat", "pen_mat"):
            m.mat_rgba[self.mat[mat], :3] = rng.uniform(0.05, 0.9, 3) if mat != "device_mat" else rng.uniform(0.1, 0.8)
        cables = 0
        for k, segs in enumerate(self.cables):
            if rng.random() >= cl["cable_probability"][k]:
                continue
            pts = self._cable_path(rng, keep, from_deck=(k == 0 and rng.random() < 0.4))
            if len(pts) < 3:
                continue
            radius = rng.uniform(*cl["cable_radius_m"])
            m.mat_rgba[self.mat[f"cable_mat_{k}"], :3] = (0.03, 0.03, 0.035) if rng.random() < 0.7 else rng.uniform(0.3, 0.95)
            for g, (a, b) in zip(segs, zip(pts[:-1], pts[1:])):
                a3, b3 = np.r_[a, radius], np.r_[b, radius]
                v = b3 - a3
                length = np.linalg.norm(v)
                q = np.zeros(4)
                mujoco.mju_quatZ2Vec(q, v / length)
                m.geom_pos[g] = (a3 + b3) / 2
                m.geom_quat[g] = q
                m.geom_size[g, :2] = [radius, length / 2]
                m.geom_group[g] = 1
            cables += 1
        info["clutter"] = present + [f"cable x{cables}"] * bool(cables)

    def _cable_path(self, rng, keep, from_deck):
        """A cable lying on the table: a smooth random walk from a table edge (or from the
        deck's power socket) that stops at an edge and steps around the deck, board and tray."""
        cl, table = self.cfg["clutter"], self.table_poly
        n = env.CABLE_SEGMENTS
        step = rng.uniform(*cl["cable_length_m"]) / n
        lo, hi = table.min(0), table.max(0)
        if from_deck:
            start, heading = np.array([env.DECK_BACK - 0.005, rng.uniform(-0.06, 0.06)]), np.pi + rng.normal(0, 0.4)
        else:
            edge = rng.integers(4)
            u = rng.uniform(0.1, 0.9)
            along_x, along_y = lo[0] + u * (hi[0] - lo[0]), lo[1] + u * (hi[1] - lo[1])
            start = np.array([(along_x, lo[1] + 0.006), (along_x, hi[1] - 0.006),
                              (lo[0] + 0.006, along_y), (hi[0] - 0.006, along_y)][edge])
            heading = [np.pi / 2, -np.pi / 2, 0.0, np.pi][edge] + rng.uniform(-1.0, 1.0)
        pts = [start]
        for i in range(n):
            for attempt in range(8):
                h = heading + rng.normal(0, 0.3 + 0.25 * attempt)
                nxt = pts[-1] + step * np.array([np.cos(h), np.sin(h)])
                if not inside(table, nxt, -0.003):
                    return pts
                if any(inside(p, nxt, 0.012) for p in keep) and not (from_deck and i < 1):
                    continue
                pts.append(nxt)
                heading = h
                break
            else:
                break
        return pts

    def _robot_cameras(self, rng, info):
        """Rover and wrist cameras sit on the robot: only remounting errors."""
        m, c = self.m, self.cfg["cameras"]
        for name in ("rover", "wrist"):
            cid = self.cams[name]
            jitter = rng.uniform(-c[f"{name}_pos_jitter"], c[f"{name}_pos_jitter"], 3)
            # Each lens sits at the front face of its housing: 1 mm back puts the camera
            # inside it and the image goes black (38% of wrist views in the first pilot).
            # A backward component along the view direction is mirrored forward.
            view = np.zeros(3)
            mujoco.mju_rotVecQuat(view, np.array([0.0, 0.0, -1.0]), m.cam_quat[cid])
            back = jitter @ view
            if back < 0:
                jitter -= 2 * back * view
            m.cam_pos[cid] += jitter
            m.cam_quat[cid] = _quat_mul(m.cam_quat[cid], _small_rotation(rng, c[f"{name}_rot_jitter_deg"]))
            m.cam_fovy[cid] += rng.uniform(-c[f"{name}_fovy_jitter_deg"], c[f"{name}_fovy_jitter_deg"])

    def _physics(self, rng, info):
        m, p = self.m, self.cfg["physics"]
        for name in self.world.pieces:
            bid = self.world.body[name]
            f = rng.uniform(*p["mass_scale"])
            m.body_mass[bid] *= f
            m.body_inertia[bid] *= f
        mu = rng.uniform(*p["friction"])
        m.geom_friction[self.piece_collision, 0] = mu
        m.geom_friction[self.jaw_geoms, 0] = mu
        m.geom_friction[self.board_geoms, 0] = rng.uniform(*p["board_friction"])
        info["friction"] = round(float(mu), 3)

    # ------------------------------------------------------------------ overhead camera
    def place_overhead(self, d: mujoco.MjData, rng, info) -> None:
        """Put the overhead camera anywhere a person could mount it: 35-80 cm above the
        board, straight down to 45 degrees from vertical, from any side but behind the
        robot, with a common webcam lens. Redrawn until the whole board and the tray are
        in frame and the resting arm hides no square centre. `d` must hold the arm at rest
        with its kinematics computed."""
        m, w, c = self.m, self.world, self.cfg["cameras"]
        ds = self.cfg["dataset"]
        cid = self.cams["overhead"]
        W, H = ds["image_width"], ds["image_height"]
        centre = np.r_[m.body_pos[w.board][:2], w.board_top]
        board = np.c_[self.board_poly, np.full(4, w.board_top)]
        tray = w.bin_corners()
        squares = np.array([w.square_center(s) for s in SQUARES]) + [0, 0, 0.001]
        group = np.array([1, 1, 1, 0, 0, 0], np.uint8)
        hit = np.zeros(1, np.int32)
        margin = c["overhead_margin"]
        for _ in range(80):
            height = rng.uniform(*c["overhead_height_m"])
            tilt = np.radians(rng.uniform(*c["overhead_tilt_deg"]))
            az = np.radians(rng.uniform(*c["overhead_azimuth_deg"]))
            roll = np.radians(rng.uniform(*c["overhead_roll_deg"]))
            fovy = rng.uniform(*c["overhead_fovy_deg"])
            target = centre + np.r_[rng.normal(0, c["overhead_target_jitter_m"], 2), 0]
            away = np.array([np.sin(tilt) * np.cos(az), np.sin(tilt) * np.sin(az), np.cos(tilt)])
            pos = target + away * height / np.cos(tilt)
            if pos[0] < -0.7 or abs(pos[1]) > 1.1:
                continue
            f = (target - pos) / np.linalg.norm(target - pos)
            up_hint = -np.array([np.cos(az), np.sin(az), 0.0])      # image top toward the far side
            right = np.cross(f, up_hint)
            right /= np.linalg.norm(right)
            up = np.cross(right, f)
            right, up = np.cos(roll) * right + np.sin(roll) * up, -np.sin(roll) * right + np.cos(roll) * up
            R = np.column_stack([right, up, -f])
            cam = Camera(pos, R, fovy, W, H)
            ok = True
            for poly in (board, tray):
                if np.any((poly - pos) @ R[:, 2] >= 0):         # behind the camera
                    ok = False
                    break
                px = project(cam, poly)
                if px is None or len(px) != len(poly) or np.any(px[:, 0] < margin * W) or np.any(px[:, 0] > (1 - margin) * W) \
                        or np.any(px[:, 1] < margin * H) or np.any(px[:, 1] > (1 - margin) * H):
                    ok = False
                    break
            if not ok:
                continue
            hidden = 0
            for s in squares:
                dist = mujoco.mj_ray(m, d, pos, s - pos, group, 1, -1, hit)
                if 0 <= dist < 0.995 and m.geom_bodyid[hit[0]] in self.arm_bodies:
                    hidden += 1
                    break
            if hidden and not c.get("overhead_arm_may_hide"):
                continue
            q = np.zeros(4)
            mujoco.mju_mat2Quat(q, R.ravel())
            m.cam_pos[cid] = pos            # the camera's parent body sits at the world origin
            m.cam_quat[cid] = q
            m.cam_fovy[cid] = fovy
            info["overhead"] = dict(height_m=round(float(height), 3), tilt_deg=round(float(np.degrees(tilt)), 1),
                                    azimuth_deg=round(float(np.degrees(az)), 1), roll_deg=round(float(np.degrees(roll)), 1),
                                    fovy_deg=round(float(fovy), 1))
            return
        info["overhead"] = "nominal"