File size: 47,641 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa4121e
33c14d6
 
 
 
 
 
 
 
 
 
fa4121e
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa4121e
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
9ffd3e8
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa4121e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
9ffd3e8
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
9ffd3e8
 
33c14d6
9ffd3e8
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
"""Scripted pick-and-place expert with ground-truth piece poses.

One primitive moves one piece: home, above source, descend, close on the head,
lift clear, traverse, above destination, descend, open, retreat, home. It is
planned in three parts (pick, lift, carry-and-place), each from the actual state. The
gripper points straight down with the jaws along a board diagonal where
possible, else along a rank or file. Grasps and releases are straight down; while
carrying over the far ranks, where straight-down reach runs out, the fingertips
lean outward by the least tilt that clears. The expert tries the directions in order of
finger clearance and keeps the first whose whole trajectory passes a collision
check in a planning copy of the model. After the grasp it
reads where the piece actually sits in the hand and plans the placement from that.

When all of those fail, three fallbacks follow, in this order: in-between jaw yaws
(22.5 degrees off the diagonals and axes); near the arm base (ranks 7-8), a carry that
leans the fingertips inward where it passes the shoulder; and near the base, a grasp
with the fingertips leaning inward, which keeps the wrist camera off the shoulder. A
piece grasped at a lean hangs at that lean, so it is set down with the wrist roll and
lean that stand it upright again. Moves that succeed without a fallback are planned
exactly as before.

Trajectories are joint targets at the recording rate, with minimum-jerk timing.
"""
from __future__ import annotations

import copy
import time
from dataclasses import dataclass, field

import mujoco
import numpy as np

from chess_world import ChessWorld
from grasp_geometry import measure_jaws, piece_profile, piece_triangles, plan_grasp
from kinematics import Kinematics

ARM, PIECE, STATIC, CARRIED, WRIST = 1, 2, 4, 8, 16   # collision classes in the planning model
WRIST_BODIES = ("gripper", "moving_jaw_so101_v1", "wrist_camera_mount", "wrist_camera")
PROXIMAL_BODIES = ("shoulder", "upper_arm", "lower_arm")   # can meet the hand when it rolls
DIAGONALS = np.radians([45, -45, 135, -135])
# Along a rank or file. Needed on rank 8, where a diagonal finger would reach over the
# rover deck; ranked after the diagonals, which keep the fingers furthest from neighbours.
AXES = np.radians([90, -90, 0, 180])
AXIS_PENALTY = 0.004
# In-between jaw yaws, tried only after every diagonal and axis option has failed. Near
# the arm base (ranks 7-8) the yaws that clear the neighbours can put the wrist camera
# or the jaw into the shoulder; an in-between yaw often clears both.
BETWEEN = np.radians([22.5, -22.5, 67.5, -67.5, 112.5, -112.5, 157.5, -157.5])
# Carrying close to the arm base, the folded arm can bring the wrist camera or the hand
# into the shoulder. As a last resort the carry leans the fingertips inward (toward the
# base) where the path runs within NEAR_BASE of the pan axis, which moves the hand's top
# away from the shoulder; the lean is gone again before the piece is set down.
INWARD_TILTS = np.radians([10, 20])
NEAR_BASE = (0.13, 0.17)      # m from the pan axis: full lean inside (ranks 7-8), none outside
IK_POS_TOL = 5e-4
TILTS = np.radians([0, 5, 10, 15, 20])
TILT_RATE = 0.25         # rad/s of tilt change allowed while carrying   # outward fingertip tilts tried when reach runs out
REACH_STEP = 0.003       # height search step; the result stays one step inside the edge
CORRIDOR = 0.021         # two feet radii and a margin: pieces closer than this to the carry path
VERTICAL_PHASES = ("descend", "close", "lift", "place", "open", "retreat", "check")
IK_ROT_TOL = 0.02


def min_jerk(n: int) -> np.ndarray:
    s = np.arange(1, n + 1) / n
    return 10 * s**3 - 15 * s**4 + 6 * s**5


def wrap(a):
    return (a + np.pi) % (2 * np.pi) - np.pi


@dataclass
class Destination:
    kind: str                  # "square" or "bin"
    pos: np.ndarray            # world point where the piece base should come to rest
    square: str | None = None


@dataclass
class Trajectory:
    q: list = field(default_factory=list)       # 5 arm joint targets per frame
    g: list = field(default_factory=list)       # gripper target per frame
    phase: list = field(default_factory=list)
    label: list | None = None                   # arm targets to record as the action, if not q (perturb_pick)

    def add(self, q, g, phase):
        self.q.append(np.asarray(q, float).copy())
        self.g.append(float(g))
        self.phase.append(phase)

    def __len__(self):
        return len(self.q)

    def extend(self, other: "Trajectory"):
        if self.label is not None or other.label is not None:
            self.label = (list(self.q) if self.label is None else self.label) + \
                         (list(other.q) if other.label is None else other.label)
        self.q += other.q
        self.g += other.g
        self.phase += other.phase


@dataclass
class PickPlan:
    traj: Trajectory
    yaw: float
    grasp: object
    offset: np.ndarray       # pinch point in the gripper frame
    grasp_point: np.ndarray  # world pinch point at the grasp
    q_grasp: np.ndarray
    carry_tilt: float = 0.0  # outward tilt at the top of the lift
    grasp_tilt: float = 0.0  # lean at the grasp (negative: fingertips toward the base)
    dart_offset_mm: list | None = None   # executed sideways offset (x, y) if perturbed (perturb_pick)


class PlanningFailed(Exception):
    pass


class Expert:
    def __init__(self, m: mujoco.MjModel, world: ChessWorld, cfg: dict):
        self.m, self.w, self.cfg = m, world, cfg
        self.kin = Kinematics(m)
        self.jaws = measure_jaws(m)
        self.fps = cfg["dataset"]["fps"]
        self.e, self.gcfg = cfg["expert"], cfg["grasp"]
        self.close_q = self.gcfg["close_q"]
        self.gripper_body = m.body("gripper").id
        self.grip_qadr = m.jnt_qposadr[m.joint("gripper").id]
        # Pan axis position on the table; the pan joint does not move it.
        dk = mujoco.MjData(m)
        mujoco.mj_kinematics(m, dk)
        self.pan_xy = dk.xanchor[m.joint("shoulder_pan").id][:2].copy()
        self.tris = {k: piece_triangles(m, next(n for n in world.pieces if world.kind[n] == k))
                     for k in world.height}
        self.profiles = {}
        self._planning_model()

    # ------------------------------------------------------------------ planning model
    def _planning_model(self):
        m = self.m
        pm = copy.deepcopy(m)
        pm.geom_contype[:] = 0
        pm.geom_conaffinity[:] = 0
        pm.geom_margin[:] = 0
        pm.geom_gap[:] = 0
        margin = self.e["plan_margin_mm"] / 1000
        root = m.body("shoulder").id
        arm_bodies = {b for b in range(m.nbody) if self._in_subtree(b, root)}
        self.arm_geoms = [g for g in range(m.ngeom) if m.geom_bodyid[g] in arm_bodies and m.geom_group[g] == 3]
        self.piece_geoms = {n: [g for g in range(m.ngeom) if m.geom_bodyid[g] == self.w.body[n] and m.geom_group[g] == 3]
                            for n in self.w.pieces}
        # Everything else that collides: board, tray, table, deck, both camera mounts, walls.
        piece_bodies = set(self.w.body.values())
        static = [g for g in range(m.ngeom) if m.geom_contype[g] and m.geom_bodyid[g] not in arm_bodies
                  and m.geom_bodyid[g] not in piece_bodies]
        # MuJoCo uses the larger margin of the two geoms, so a small arm margin sets the
        # arm-to-arm clearance while pieces and fixed obstacles bring their own.
        pm.geom_contype[self.arm_geoms] = ARM
        # Self-collision: the hand and wrist camera against the upper links.
        for g in self.arm_geoms:
            body = m.body(m.geom_bodyid[g]).name
            if body in WRIST_BODIES:
                pm.geom_contype[g] = ARM | WRIST
            elif body in PROXIMAL_BODIES:
                pm.geom_conaffinity[g] = WRIST
        for gs in self.piece_geoms.values():
            pm.geom_contype[gs] = PIECE
            pm.geom_conaffinity[gs] = ARM | CARRIED
            pm.geom_margin[gs] = margin
        pm.geom_contype[static] = STATIC
        pm.geom_conaffinity[static] = ARM
        self.static_geoms = static
        # The per-body bounding-volume tree is built at compile time and ignores these
        # runtime margins, so multi-hull bodies would only report actual overlap.
        pm.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
        self.pm, self.pd = pm, mujoco.MjData(pm)

    def _in_subtree(self, b, root):
        while b > 0:
            if b == root:
                return True
            b = self.m.body_parentid[b]
        return False

    def _sync_planning(self, d, carried=None, ignored=()):
        """Copy the episode's board/tray pose and set per-plan roles of pieces."""
        pm = self.pm
        for b in (self.w.board, self.w.bin, self.w.table):
            pm.body_pos[b] = self.m.body_pos[b]
            pm.body_quat[b] = self.m.body_quat[b]
        for n, gs in self.piece_geoms.items():
            if n == carried:
                pm.geom_contype[gs], pm.geom_conaffinity[gs] = CARRIED, 0
            elif n in ignored:
                pm.geom_contype[gs], pm.geom_conaffinity[gs] = 0, 0
            else:
                pm.geom_contype[gs], pm.geom_conaffinity[gs] = PIECE, ARM | CARRIED
        # Margin sets for sideways and vertical motion (see phase2_config.toml).
        e = self.e
        self.margins = {}
        for mode, piece, carry in (("lateral", e["plan_margin_mm"], e["carry_margin_mm"]),
                                   ("vertical", e["vertical_margin_mm"], e["vertical_carry_margin_mm"]),
                                   ("lift", e["vertical_margin_mm"], e["lift_carry_margin_mm"])):
            mg = np.zeros(pm.ngeom)
            mg[self.arm_geoms] = e["self_margin_mm"] / 1000
            mg[self.static_geoms] = e["static_margin_mm"] / 1000
            for n, gs in self.piece_geoms.items():
                mg[gs] = (carry if n == carried else piece) / 1000
            self.margins[mode] = mg
        self.pd.qpos[:] = d.qpos

    def _collision_free(self, traj: Trajectory, start: int = 0, carried=None, rel=None, stride=2):
        """True if no checked frame puts the arm or the carried piece within the margin."""
        pd = self.pd
        idx = list(range(start, len(traj), stride))
        if len(traj) and idx[-1] != len(traj) - 1:
            idx.append(len(traj) - 1)
        for i in idx:
            pd.qpos[self.kin.qadr] = traj.q[i]
            pd.qpos[self.grip_qadr] = max(traj.g[i], self._grip_floor)
            if carried is not None and traj.phase[i] in ("lift", "traverse", "place"):
                mujoco.mj_kinematics(self.pm, pd)
                R = pd.xmat[self.gripper_body].reshape(3, 3)
                pos = pd.xpos[self.gripper_body] + R @ rel[0]
                quat = np.zeros(4)
                mujoco.mju_mat2Quat(quat, (R @ rel[1]).ravel())
                a = self.w.qadr[carried]
                pd.qpos[a:a + 3], pd.qpos[a + 3:a + 7] = pos, quat
            ph = traj.phase[i]
            self.pm.geom_margin[:] = self.margins["lift" if ph == "lift" else
                                                  "vertical" if ph in VERTICAL_PHASES else "lateral"]
            mujoco.mj_kinematics(self.pm, pd)
            mujoco.mj_collision(self.pm, pd)
            if pd.ncon:
                c = pd.contact[0]
                self.last_collision = (traj.phase[i], self.pm.body(self.pm.geom_bodyid[c.geom1]).name,
                                       self.pm.body(self.pm.geom_bodyid[c.geom2]).name)
                return False
        return True

    def _config_free(self, q, g):
        t = Trajectory()
        t.add(q, g, "check")
        return self._collision_free(t)

    # ------------------------------------------------------------------ geometry helpers
    def profile(self, name: str, closing_world: float, d):
        """Grasp profile of a piece for jaws closing along world yaw `closing_world`."""
        kind = self.w.kind[name]
        R = d.xmat[self.w.body[name]].reshape(3, 3)
        u = R.T @ np.array([np.cos(closing_world), np.sin(closing_world), 0])
        ang = np.arctan2(u[1], u[0])
        step = np.radians(5 if kind == "knight" else 10)
        key = (kind, int(round(ang / step)))
        if key not in self.profiles:
            a = key[1] * step
            self.profiles[key] = piece_profile(self.tris[kind], np.array([np.cos(a), np.sin(a)]))
        return self.profiles[key]

    def grasp_for(self, name, yaw, d, open_margin=None):
        prof = self.profile(name, yaw, d)
        tip = self.gcfg["tip_fraction"][self.w.kind[name]] * prof.height
        margin = self.gcfg["open_margins_mm"][0] / 1000 if open_margin is None else open_margin
        g = plan_grasp(self.jaws, prof, tip, self.gcfg["fixed_gap_mm"] / 1000, margin)
        return g, np.array([g.center_x, 0.0, self.jaws.tip_z])

    def _neighbour_tops(self, d, xy, radius, exclude=()):
        """Highest point of pieces whose axis is within `radius` of `xy` (world z)."""
        top = self.w.board_top
        for n in self.w.pieces:
            if n in exclude:
                continue
            p = d.xpos[self.w.body[n]]
            if np.linalg.norm(p[:2] - xy[:2]) < radius and p[2] > -0.1:
                top = max(top, p[2] + self.w.height[self.w.kind[n]])
        return top

    def _corridor_top(self, d, a, b, width, exclude=()):
        top = self.w.board_top
        ab = b[:2] - a[:2]
        L2 = max(ab @ ab, 1e-12)
        for n in self.w.pieces:
            if n in exclude:
                continue
            p = d.xpos[self.w.body[n]]
            if p[2] < -0.1:
                continue
            t = np.clip((p[:2] - a[:2]) @ ab / L2, 0, 1)
            if np.linalg.norm(p[:2] - (a[:2] + t * ab)) < width:
                top = max(top, p[2] + self.w.height[self.w.kind[n]])
        return top

    def _solve(self, point, yaw, offset, q_seed, global_search=False, tilt=0.0):
        if global_search:
            q, ep, er = self.kin.solve_global(point, yaw, offset, q_seed, tilt=tilt)
        else:
            q, ep, er = self.kin.solve(point, yaw, offset, q_seed, iters=60, tilt=tilt)
            if ep > IK_POS_TOL or er > IK_ROT_TOL:
                q, ep, er = self.kin.solve_global(point, yaw, offset, q_seed, tilt=tilt)
        if ep > IK_POS_TOL or er > IK_ROT_TOL:
            raise PlanningFailed(f"unreachable {np.round(point, 3)}")
        return q

    def _local(self, point, yaw, offset, q_seed, tilt=0.0):
        q, ep, er = self.kin.solve(point, yaw, offset, q_seed, iters=100, tilt=tilt)
        if ep > IK_POS_TOL or er > IK_ROT_TOL:
            raise PlanningFailed(f"unreachable {np.round(point, 3)}")
        return q

    def _reachable_height(self, xy, yaw, offset, q_seed, z_lo, z_hi, z_floor=None, tilt=0.0):
        """Highest z in [z_lo, z_hi] reachable at `xy` with the gripper vertical, found by
        walking up from z_lo on the same IK branch a trajectory would follow, then
        stepping back one step from the workspace edge. If z_lo itself is out of reach,
        the highest reachable z down to `z_floor`.
        """
        xy = np.asarray(xy)[:2]
        try:
            q = self._solve(np.r_[xy, z_lo], yaw, offset, q_seed, tilt=tilt)
        except PlanningFailed:
            if z_floor is None or z_floor >= z_lo:
                raise
            for z in np.r_[np.arange(z_lo - REACH_STEP, z_floor, -REACH_STEP), z_floor]:
                try:
                    return z, self._solve(np.r_[xy, z], yaw, offset, q_seed, tilt=tilt)
                except PlanningFailed:
                    continue
            raise
        try:
            return z_hi, self._local(np.r_[xy, z_hi], yaw, offset, q, tilt)
        except PlanningFailed:
            pass
        reached = [(z_lo, q)]
        for z in np.arange(z_lo + REACH_STEP, z_hi, REACH_STEP):
            try:
                q = self._local(np.r_[xy, z], yaw, offset, q, tilt)
            except PlanningFailed:
                break
            reached.append((z, q))
        return reached[-2] if len(reached) > 1 else reached[-1]

    # ------------------------------------------------------------------ trajectory pieces
    def _duration(self, value, rate, lo, hi):
        return float(np.clip(value / rate, lo, hi)) / self.speed

    def _joint_move(self, traj, q0, q1, g0, g1, phase):
        T = self._duration(np.max(np.abs(q1 - q0)), self.e["joint_speed"], 1.0, 3.0)
        for s in min_jerk(max(2, round(T * self.fps))):
            traj.add(q0 + (q1 - q0) * s, g0 + (g1 - g0) * s, phase)
        return q1

    def _cart_move(self, traj, q, p0, p1, yaw0, yaw1, offset, g0, g1, phase, speed, tmin, tmax,
                   tilt0=0.0, tilt1=0.0):
        dist = max(np.linalg.norm(p1 - p0), abs(wrap(yaw1 - yaw0)) * 0.03, abs(tilt1 - tilt0) * 0.08)
        T = self._duration(dist, speed, tmin, tmax)
        for s in min_jerk(max(2, round(T * self.fps))):
            q = self._solve(p0 + (p1 - p0) * s, yaw0 + wrap(yaw1 - yaw0) * s, offset, q,
                            tilt=tilt0 + (tilt1 - tilt0) * s)
            traj.add(q, g0 + (g1 - g0) * s, phase)
        return q

    def _hold(self, traj, q, g0, g1, secs, phase):
        n = max(1, round(secs / self.speed * self.fps))
        for s in min_jerk(n):
            traj.add(q, g0 + (g1 - g0) * s, phase)

    # ------------------------------------------------------------------ pick
    def plan_pick(self, d, name: str, rng) -> PickPlan:
        self.speed = rng.uniform(*self.e["speed_scale"])
        base = self.w.base_pos(d, name)
        q_now = d.qpos[self.kin.qadr].copy()
        g_now = float(d.qpos[self.grip_qadr])
        self._sync_planning(d, ignored=(name,))
        clearance = self.e["travel_clearance_mm"] / 1000
        errors = []
        margins = [m / 1000 for m in self.gcfg["open_margins_mm"]]
        primary = self._yaw_order(d, name, base)
        options = [(yaw, m, 0.0) for m in margins for yaw in primary]
        options += [(yaw, m, 0.0) for m in margins for yaw in self._yaw_order(d, name, base, BETWEEN)]
        # Last resort close to the base: grasp with the fingertips leaning inward, which
        # keeps the wrist camera and the hand's top off the shoulder. The piece then hangs
        # at that lean in the hand, and plan_place sets it down with a matching lean.
        if np.linalg.norm(base[:2] - self.pan_xy) < NEAR_BASE[1]:
            options += [(yaw, m, -lean) for lean in INWARD_TILTS for m in margins for yaw in primary]
        deadline = time.time() + self.e["plan_budget_s"]
        for yaw, margin, tilt in options:
            if time.time() > deadline:
                errors.append("time budget")
                break
            try:
                grasp, offset = self.grasp_for(name, yaw, d, margin)
                self._grip_floor = grasp.contact_q
                point = base + [0, 0, grasp.tip_height]
                top = self._neighbour_tops(d, base, 0.045, exclude=(name,))
                z_above = max(top + clearance + 0.004, point[2] + 0.025)
                q_grasp = self._solve(point, yaw, offset, q_now, global_search=True, tilt=tilt)
                if not self._config_free(q_grasp, grasp.open_q):
                    raise PlanningFailed(f"grasp pose collides {self.last_collision}")
                z_above, q_above = self._reachable_height(point, yaw, offset, q_grasp, point[2], z_above, tilt=tilt)
                if z_above < point[2] + 0.015:
                    raise PlanningFailed("no room above the source")
                above = np.r_[point[:2], z_above]
                traj = Trajectory()
                self._joint_move(traj, q_now, q_above, g_now, grasp.open_q, "approach")
                q = self._cart_move(traj, q_above, above, point, yaw, yaw, offset, grasp.open_q, grasp.open_q,
                                    "descend", self.e["vertical_speed"], 0.7, 1.8, tilt, tilt)
                self._hold(traj, q, grasp.open_q, grasp.open_q, 0.1, "descend")
                if not self._collision_free(traj):
                    raise PlanningFailed(f"collision {self.last_collision}")
                self._hold(traj, q, grasp.open_q, self.close_q, 0.45, "close")
                self._hold(traj, q, self.close_q, self.close_q, 0.25, "close")
                return PickPlan(traj, yaw, grasp, offset, point, q, grasp_tilt=tilt)
            except PlanningFailed as exc:
                errors.append(str(exc))
        raise PlanningFailed("pick: " + "; ".join(errors))

    def perturb_pick(self, d, name: str, pick: PickPlan, rng) -> PickPlan:
        """DART-style perturbation: execute the approach off-centre, record the clean plan.

        The executed hand drifts sideways by a random offset (`dart_radius_mm`, any direction)
        during the approach, holds it into the descent and returns to the planned path over a
        random `dart_return_s`, ending before the fingertips come within `dart_clear_mm` of the
        piece's top.
        From there on it follows the plan exactly. The recorded actions (`traj.label`) are the
        clean plan throughout, so an episode shows "from off-centre, command the centred path"
        and never an off-centre aim. The executed part is collision-checked with the target
        included; an offset that collides is redrawn, up to `dart_tries` times, else the plan
        runs unperturbed.
        """
        e, t = self.e, pick.traj
        desc = [i for i, ph in enumerate(t.phase) if ph == "descend"]
        if not desc or desc[0] < 2:
            return pick
        k0 = desc[0]
        top = self.w.base_pos(d, name)[2] + self.w.height[self.w.kind[name]]
        z_clear = top + e["dart_clear_mm"] / 1000
        pts = [self.kin.pose(q, pick.offset)[0] for q in t.q[k0:desc[-1] + 1]]
        k_clear = k0 + next((j for j, p in enumerate(pts) if p[2] <= z_clear), len(pts) - 1)
        n_down = min(round(rng.uniform(*e["dart_return_s"]) * self.fps), k_clear - 2)
        k_peak = k_clear - n_down
        k_up = min(k0, k_peak)
        w = np.zeros(len(t))
        w[:k_up] = np.r_[0.0, min_jerk(k_up - 1)]             # 0 at the start, full by the end of the approach
        w[k_up:k_peak] = 1.0                                   # held into the descent
        w[k_peak:k_clear] = 1 - min_jerk(n_down)               # back to 0 at k_clear - 1
        q_above = t.q[k0 - 1]
        p_above = self.kin.pose(q_above, pick.offset)[0]
        lo, hi = e["dart_radius_mm"]
        for _ in range(e["dart_tries"]):
            r, a = rng.uniform(lo, hi) / 1000, rng.uniform(0, 2 * np.pi)
            delta = np.array([r * np.cos(a), r * np.sin(a), 0.0])
            try:
                dq = self._solve(p_above + delta, pick.yaw, pick.offset, q_above, tilt=pick.grasp_tilt) - q_above
                ex = Trajectory()
                q = q_above
                for i in range(k_clear):
                    if i < k0:
                        q = t.q[i] + w[i] * dq
                    else:
                        q = self._solve(pts[i - k0] + w[i] * delta, pick.yaw, pick.offset, q, tilt=pick.grasp_tilt)
                    ex.add(q, t.g[i], t.phase[i])
            except PlanningFailed:
                continue
            self._sync_planning(d)                  # the target counts while the hand is off the plan
            free = self._collision_free(ex)
            self._sync_planning(d, ignored=(name,))
            if not free:
                continue
            ex.q += [q.copy() for q in t.q[k_clear:]]
            ex.g += t.g[k_clear:]
            ex.phase += t.phase[k_clear:]
            ex.label = [q.copy() for q in t.q]
            return PickPlan(ex, pick.yaw, pick.grasp, pick.offset, pick.grasp_point, pick.q_grasp,
                            pick.carry_tilt, pick.grasp_tilt, dart_offset_mm=[round(float(x), 2) for x in delta[:2] * 1000])
        return pick

    def _yaw_order(self, d, name, base, offsets=None):
        """Diagonals, best finger clearance to neighbouring pieces first (or the given
        board-relative `offsets`, ordered the same way)."""
        byaw = self.w.board_yaw()
        scored = []
        between = offsets is not None
        for off in (offsets if between else np.r_[DIAGONALS, AXES]):
            yaw = byaw + off
            u = np.array([np.cos(yaw), np.sin(yaw)])
            v = np.array([-u[1], u[0]])
            worst = 1.0
            for n in self.w.pieces:
                if n == name:
                    continue
                p = d.xpos[self.w.body[n]]
                rel = p[:2] - base[:2]
                if p[2] < -0.1 or np.linalg.norm(rel) > 0.06:
                    continue
                a, c = rel @ u, rel @ v
                r = self.w.foot_radius[self.w.kind[n]]
                # finger boxes: moving side +u 6..30 mm, fixed side -u 6..24 mm, across +-9 mm
                for lo, hi in ((0.006, 0.030), (-0.024, -0.006)):
                    du = max(lo - a, 0, a - hi)
                    dv = max(abs(c) - 0.009, 0)
                    worst = min(worst, np.hypot(du, dv) - r)
            penalty = 0.0 if off in DIAGONALS else AXIS_PENALTY
            scored.append((-worst + penalty, abs(wrap(off)) > np.pi / 2, yaw))
        order = [y for *_, y in sorted(scored)]
        if self.w.kind[name] == "knight" and not between:
            # Across the head: the normalised knight faces its local +y.
            R = d.xmat[self.w.body[name]].reshape(3, 3)
            facing = np.arctan2(R[1, 1], R[0, 1])
            order = [facing + np.pi / 2, facing - np.pi / 2] + order
        return order

    # ------------------------------------------------------------------ carry and place
    def _in_hand(self, d, name):
        """Piece base position and orientation in the gripper frame, as it actually sits."""
        gb = self.gripper_body
        Rg = d.xmat[gb].reshape(3, 3)
        Rp = d.xmat[self.w.body[name]].reshape(3, 3)
        return Rg.T @ (d.xpos[self.w.body[name]] - d.xpos[gb]), Rg.T @ Rp

    def _need_profile(self, d, name, start, target, careful=False, n=33):
        """Base height the carried piece needs at points along the straight carry path.

        At each point: the top of every piece whose axis is within the corridor, plus
        the clearance. Careful mode widens the corridor and adds all pieces within
        40 mm of the destination. Returns (path fraction s, needed base z, length).
        """
        clearance = self.e["travel_clearance_mm"] / 1000
        width = 0.028 if careful else CORRIDOR
        s = np.linspace(0, 1, n)
        xy = start[None, :2] + (target[:2] - start[:2])[None] * s[:, None]
        need = np.full(n, target[2] + 0.004)
        for other in self.w.pieces:
            if other == name:
                continue
            p = d.xpos[self.w.body[other]]
            if p[2] < -0.1:
                continue
            top = p[2] + self.w.height[self.w.kind[other]] + clearance
            near = np.linalg.norm(xy - p[:2], axis=1) < width
            need[near] = np.maximum(need[near], top)
            if careful and np.linalg.norm(p[:2] - target[:2]) < 0.04:
                need[-1] = max(need[-1], top)
        return s, need, float(np.linalg.norm(target[:2] - start[:2]))

    def _need_near(self, s, need, length, end, reach=0.03):
        """Largest need within `reach` metres of one end of the path (0 = start, 1 = end)."""
        dist = np.abs(s - end) * length
        return float(need[dist <= reach].max())

    def _travel_height(self, d, name, start, dest: Destination, careful=False):
        """Highest base height the carry needs anywhere on its way (kept for the tray)."""
        target = self._release_point(dest)
        _, need, _ = self._need_profile(d, name, start, target, careful)
        top = need.max()
        if dest.kind == "bin":
            top = max(top, self.w.bin_rim + self.m.body_pos[self.w.bin][2] + self.e["travel_clearance_mm"] / 1000)
        return max(top, target[2] + 0.02)

    def _release_point(self, dest: Destination):
        if dest.kind == "bin":
            return dest.pos + [0, 0, self.e["bin_release_mm"] / 1000]
        return dest.pos + [0, 0, self.e["place_drop_mm"] / 1000]

    def plan_lift(self, d, name: str, pick: PickPlan, dest: Destination) -> Trajectory:
        """Straight up from the planned grasp pose, as high as the carry needs and the arm reaches.

        Planned from the commanded grasp pose, not the slightly sagging measured one:
        at the edge of reach the measured pose can lie just outside the workspace.
        """
        rel = self._in_hand(d, name)
        base = self.w.base_pos(d, name)
        pinch_above_base = pick.grasp_point[2] - base[2]
        self._sync_planning(d, carried=name)
        self._grip_floor = pick.grasp.contact_q
        target = self._release_point(dest)
        prof = self._need_profile(d, name, base, target)
        z_base = max(self._need_near(*prof, end=0.0), base[2] + 0.012)
        if dest.kind == "bin":
            z_base = max(z_base, self._travel_height(d, name, base, dest))
        z_travel = z_base + pinch_above_base
        start = pick.grasp_point
        if pick.grasp_tilt:          # a leaned grasp lifts at the same lean
            tilt = pick.grasp_tilt
            z_lift, _ = self._reachable_height(start, pick.yaw, pick.offset, pick.q_grasp, start[2] + 0.005,
                                               max(z_travel, start[2] + 0.005), tilt=tilt)
        else:
            tilt, z_lift, _ = self._best_tilt(start, pick.yaw, pick.offset, pick.q_grasp,
                                              start[2] + 0.005, max(z_travel, start[2] + 0.005))
        pick.carry_tilt = tilt
        traj = Trajectory()
        self._cart_move(traj, pick.q_grasp, start, np.r_[start[:2], z_lift], pick.yaw, pick.yaw, pick.offset,
                        self.close_q, self.close_q, "lift", self.e["vertical_speed"], 0.6, 1.6, pick.grasp_tilt, tilt)
        # Neighbours already within the clearance where the lift starts (pieces up to 3 mm
        # off-centre on 22-25 mm squares can stand a fraction of a millimetre apart) are
        # left out of its check: the piece slides straight up past them, and the physics
        # judges whether they were disturbed. The arm and fixed obstacles stay checked.
        ignored = []
        start_frame = Trajectory()
        start_frame.add(traj.q[0], traj.g[0], "lift")
        while not self._collision_free(start_frame, carried=name, rel=rel) and len(ignored) < 4:
            _, a, b = self.last_collision
            other = b if a == name else a if b == name else None
            if other is None or other not in self.w.body:
                break
            ignored.append(other)
            self._sync_planning(d, carried=name, ignored=tuple(ignored))
        if not self._collision_free(traj, carried=name, rel=rel):
            raise PlanningFailed(f"lift: collision {self.last_collision}")
        return traj

    def plan_place(self, d, name: str, pick: PickPlan, dest: Destination, rng, home) -> Trajectory:
        """Traverse, place, open, retreat and return home, from where the piece hangs now."""
        rel = self._in_hand(d, name)
        q0 = d.qpos[self.kin.qadr].copy()
        start = self.w.base_pos(d, name)
        self._last_d = d
        errors = []
        lean_yaws = (self._upright_yaws(rel, pick.yaw, name, q0, self._release_point(dest))
                     if pick.grasp_tilt else None)
        deadline = time.time() + self.e["plan_budget_s"]
        for careful, target, yaw_dst, inward, lean in self._place_options(dest, pick.yaw, name, rng, start, lean_yaws):
            if time.time() > deadline:
                errors.append("time budget")
                break
            self._sync_planning(d, carried=name)
            self._grip_floor = pick.grasp.contact_q
            try:
                prof = self._need_profile(d, name, start, target, careful)
                if dest.kind == "bin":
                    rim = self._travel_height(d, name, start, dest, careful)
                    prof = (prof[0], np.maximum(prof[1], np.where(prof[0] > 0.6, rim, prof[1])), prof[2])
                z_end = max(self._need_near(*prof, end=1.0), target[2] + 0.012)
                if lean is None:
                    tilt_dst, z_dst, _ = self._best_tilt(target, yaw_dst, rel[0], q0, target[2], z_end)
                    end_tilt = 0.0
                else:                # a piece held at a lean goes down at the lean that stands it upright
                    z_dst, _ = self._reachable_height(target, yaw_dst, rel[0], q0, target[2], z_end, tilt=lean)
                    tilt_dst = end_tilt = lean
                traj = Trajectory()
                above_dst = np.r_[target[:2], z_dst]
                q = self._traverse(traj, q0, start, above_dst, pick.yaw, yaw_dst, rel[0], prof,
                                   pick.carry_tilt, tilt_dst, inward)
                q = self._cart_move(traj, q, above_dst, target, yaw_dst, yaw_dst, rel[0],
                                    self.close_q, self.close_q, "place", self.e["vertical_speed"], 0.7, 1.8,
                                    tilt_dst, end_tilt)
                if not self._collision_free(traj, carried=name, rel=rel):
                    raise PlanningFailed(f"collision {self.last_collision}")
                traj.extend(self._release_and_home(d, name, pick, q, yaw_dst, rng, home, end_tilt))
                self._last_place = dict(target=target, yaw=yaw_dst, tilt_dst=tilt_dst, end_tilt=end_tilt,
                                        pick=pick, home=home)
                return traj
            except PlanningFailed as exc:
                errors.append(str(exc))
        raise PlanningFailed("place: " + "; ".join(errors))

    def refine_descent(self, d, name: str, rng) -> Trajectory | None:
        """Re-plan the descent, release and return home from where the piece hangs now.

        The piece can slip a few millimetres in the hand while it is carried, and the
        placement was planned with the grip read after the lift. Called with the arm
        above the destination; aims the piece's actual base at the target. None if the
        new descent collides (the original plan then runs on)."""
        lp = getattr(self, "_last_place", None)
        if lp is None:
            return None
        rel = self._in_hand(d, name)
        q0 = d.qpos[self.kin.qadr].copy()
        self._sync_planning(d, carried=name)
        self._grip_floor = lp["pick"].grasp.contact_q
        traj = Trajectory()
        q = self._cart_move(traj, q0, self.w.base_pos(d, name), lp["target"], lp["yaw"], lp["yaw"], rel[0],
                            self.close_q, self.close_q, "place", self.e["vertical_speed"], 0.7, 1.8,
                            lp["tilt_dst"], lp["end_tilt"])
        if not self._collision_free(traj, carried=name, rel=rel):
            return None
        traj.extend(self._release_and_home(d, name, lp["pick"], q, lp["yaw"], rng, lp["home"], lp["end_tilt"]))
        return traj

    def _release_and_home(self, d, name, pick, q, yaw, rng, home, tilt=0.0) -> Trajectory:
        """Open, step the fixed finger off the piece it was pressed against (-x in the
        gripper frame), rise until the fingertips clear the piece, and go to rest.

        Tries a wide then a narrow opening, and a short then a full retreat. The placed
        piece stands between the jaws, so only the other pieces are checked.
        """
        self._sync_planning(d, ignored=(name,))
        prof = self.profile(name, pick.yaw, d)
        clear_top = prof.height - pick.grasp.tip_height + 0.008
        rises = sorted({min(clear_top, self.e["retreat_mm"] / 1000), self.e["retreat_mm"] / 1000})
        g_home = rng.uniform(*self.e["home_gripper"])
        errors = []
        for margin in self.gcfg["release_margins_mm"]:
            open_q = self.grasp_for(name, pick.yaw, d, margin / 1000)[0].open_q
            for rise in rises:
                try:
                    t = Trajectory()
                    self._hold(t, q, self.close_q, open_q, 0.3, "open")
                    self._hold(t, q, open_q, open_q, 0.15, "open")
                    p_tip, R = self.kin.pose(q, pick.offset)
                    shifted = p_tip - R[:, 0] * 0.001
                    qr = self._cart_move(t, q, p_tip, shifted, yaw, yaw, pick.offset, open_q, open_q,
                                         "retreat", 0.02, 0.15, 0.3, tilt, tilt)
                    z_up, _ = self._reachable_height(shifted, yaw, pick.offset, qr, shifted[2], shifted[2] + rise,
                                                     tilt=tilt)
                    qr = self._cart_move(t, qr, shifted, np.r_[shifted[:2], z_up], yaw, yaw, pick.offset,
                                         open_q, open_q, "retreat", 0.08, 0.4, 1.0, tilt, tilt)
                    for via in (None, np.r_[qr[:4], home[4]]):
                        t_home = Trajectory()
                        t_home.extend(t)
                        if via is not None:      # turn the wrist first, then fold
                            self._joint_move(t_home, qr, via, open_q, open_q, "home")
                        self._joint_move(t_home, qr if via is None else via, home, open_q, g_home, "home")
                        self._hold(t_home, home, g_home, g_home, 0.5, "home")
                        if self._collision_free(t_home):
                            return t_home
                        errors.append(f"collision {self.last_collision}")
                except PlanningFailed as exc:
                    errors.append(str(exc))
        raise PlanningFailed("release: " + "; ".join(errors))

    def _place_options(self, dest, yaw_src, name, rng, start, lean_yaws=None):
        """(careful, release point, jaw yaw, inward carry lean, placing lean) to try. The
        whole tray is highlighted, so a drop anywhere in it is correct; a few spots are
        tried. A piece held at a lean (`lean_yaws`: yaw and lean pairs from _upright_yaws)
        can only be set down with those; otherwise the placing lean is None (upright hand)."""
        points = [self._release_point(dest)]
        if dest.kind == "square":
            nudge = self._nudge(d_state=self._last_d, name=name, target=points[0])
            if nudge is not None:
                points.append(points[0] + nudge)
        if dest.kind == "bin":
            half = self.w.bin_half - 0.014
            points += [self.w.bin_point(*rng.uniform(-half, half), self.e["bin_release_mm"] / 1000) for _ in range(3)]
        if lean_yaws is not None:
            return [(c, p, y, 0.0, t) for c in (False, True) for p in points for y, t in lean_yaws]
        main = [(c, p, y) for c in (False, True) for p in points for y in self._dest_yaws(yaw_src, name)]
        out = [(*o, 0.0, None) for o in main]
        out += [(c, p, y, 0.0, None) for c in (False, True) for p in points
                for y in self._dest_yaws(yaw_src, name, BETWEEN)]
        near = min(np.linalg.norm(start[:2] - self.pan_xy), np.linalg.norm(points[0][:2] - self.pan_xy)) < NEAR_BASE[1]
        if near:
            out += [(c, p, y, lean, None) for lean in INWARD_TILTS for c, p, y in main if not c]
        if self.w.kind[name] == "knight":
            # Last resort: let the knight end up facing another way (it does not matter
            # in chess), which doubles the jaw yaws available near the base.
            free = [y for y in self._dest_yaws(yaw_src, name, any_facing=True)
                    if all(abs(wrap(y - o[2])) > 1e-6 for o in main)]
            out += [(c, p, y, 0.0, None) for c in (False, True) for p in points for y in free]
            if near:
                out += [(False, p, y, lean, None) for lean in INWARD_TILTS for p in points for y in free]
        return out

    def _upright_yaws(self, rel, yaw_src, name, q_seed, target):
        """Jaw yaws and leans at which a piece held at a lean stands upright at `target`.

        The arm can lean the hand only within its own vertical plane, so the wrist roll
        must turn the piece's axis (fixed in the hand) into that plane, and the lean then
        stands it up. Two yaws half a turn apart do this; each is kept if the piece ends
        within 2 degrees of upright. The plane barely changes across a square or the tray,
        so the nominal release point stands for the nudged ones."""
        u = rel[1][:, 2]                                   # piece axis in the gripper frame
        theta = float(np.arccos(np.clip(u[2], -1.0, 1.0)))
        beta = float(np.arctan2(u[1], u[0]))
        out = []
        for flip in (0.0, np.pi):
            psi, tp = yaw_src, 0.0
            try:
                for _ in range(3):                         # the arm's plane depends a little on yaw and lean
                    q = self._solve(target, psi, rel[0], q_seed, global_search=True, tilt=tp)
                    self.kin._set(q)
                    a = self.kin.d.xaxis[self.kin.lift_joint]
                    radial = np.cross(a, [0.0, 0.0, 1.0])[:2]
                    psi = yaw_src + wrap(np.arctan2(radial[1], radial[0]) + flip - beta - yaw_src)
                    errs = []
                    for t in (theta, -theta):
                        R = self.kin.target_rotation(target, psi, t)
                        errs.append((float(np.arccos(np.clip((R @ u)[2], -1.0, 1.0))), t))
                    err, tp = min(errs)
            except PlanningFailed:
                continue
            if err > np.radians(2):
                continue
            out.append((psi, tp))
        if self.w.kind[name] == "knight":                  # keep the knight facing where it faced if possible
            kept = [(psi, tp) for psi, tp in out if abs(wrap(psi - yaw_src)) <= np.pi / 2 + 0.2]
            out = kept + [o for o in out if o not in kept]
        return out

    def _nudge(self, d_state, name, target):
        """Small offset of the drop point away from neighbours crowding the square, the
        way a person sets a piece down a little off-centre. None if nothing crowds it."""
        push = np.zeros(2)
        for other in self.w.pieces:
            if other == name:
                continue
            p = d_state.xpos[self.w.body[other]]
            rel = target[:2] - p[:2]
            dist = np.linalg.norm(rel)
            if p[2] > -0.1 and 1e-6 < dist < 0.03:
                push += rel / dist**3
        if not push.any():
            return None
        return np.r_[push / np.linalg.norm(push) * self.e["place_nudge_mm"] / 1000, 0.0]

    def _dest_yaws(self, yaw_src, name, offsets=None, any_facing=False):
        byaw = self.w.board_yaw()
        if offsets is None:
            options = [yaw_src] + [byaw + o for o in np.r_[DIAGONALS, AXES]]
        else:
            options = [byaw + o for o in offsets]
        if self.w.kind[name] == "knight" and not any_facing:
            # Keep the knight facing where it faced; a half turn would reverse it.
            options = [o for o in options if abs(wrap(o - yaw_src)) < np.pi / 2 + 0.2]
        # Unwrapped targets: the short way round first, then the long way, which
        # moves the wrist camera to the other side of the arm.
        out = []
        for o in sorted(options, key=lambda o: abs(wrap(o - yaw_src))):
            short = wrap(o - yaw_src)
            out.append(yaw_src + short)
            if abs(short) > np.pi / 4:
                out.append(yaw_src + short - np.sign(short) * 2 * np.pi)
        return out

    def _best_tilt(self, xy, yaw, offset, q, z_lo, z_want):
        """Least outward tilt at which `z_want` is reachable at `xy`; else the tilt
        that reaches highest. Returns (tilt, z, q)."""
        best = None
        for tilt in TILTS:
            try:
                z, qz = self._reachable_height(xy, yaw, offset, q, z_lo, z_want, tilt=tilt)
            except PlanningFailed:
                continue
            if z >= z_want - 1e-6:
                return tilt, z, qz
            if best is None or z > best[1] + 1e-6:
                best = (tilt, z, qz)
        if best is None:
            raise PlanningFailed(f"unreachable {np.round(np.r_[np.asarray(xy)[:2], z_lo], 3)}")
        return best

    def _traverse(self, traj, q, a, b, yaw0, yaw1, offset, prof, tilt_a=0.0, tilt_b=0.0, inward=0.0):
        """Carry from a to b over the needed-height profile, lowered where the arm cannot
        reach that high. The profile is made tent-shaped (it rises over obstacles and never
        dips between them) and then followed with one minimum-jerk timing over its length.
        With `inward`, the fingertips lean that far toward the base where the path runs
        close to it (NEAR_BASE)."""
        s_prof, need, _ = prof
        rise = np.maximum.accumulate(np.maximum(need, a[2]))
        fall = np.maximum.accumulate(np.maximum(need, b[2])[::-1])[::-1]
        tent = np.minimum(rise, fall)
        n_check = 10
        pts, tilts = [], []
        qs = q
        floor = min(a[2], b[2])
        for s in np.linspace(0, 1, n_check + 2)[1:-1]:
            xy = a[:2] + (b[:2] - a[:2]) * s
            want = float(np.interp(s, s_prof, tent))
            z_lo = max(floor, min(want, max(a[2], b[2])))
            yaw = yaw0 + (yaw1 - yaw0) * self._turn(s)
            try:
                tilt, z, qs = self._best_tilt(np.r_[xy, 0], yaw, offset, qs, z_lo, want)
            except PlanningFailed:
                tilt = max(tilt_a, tilt_b)
                z, qs = self._reachable_height(np.r_[xy, 0], yaw, offset, qs, z_lo, want, z_floor=floor, tilt=tilt)
            pts.append(np.r_[xy, z])
            tilts.append(tilt)
        path = [a] + pts + [b]
        # Tilt changes gradually: hold the largest value within two samples, then average.
        tilts = np.r_[tilt_a, tilts, tilt_b]
        padded = np.r_[tilt_a, tilt_a, tilts, tilt_b, tilt_b]
        held = np.max([padded[i:i + len(tilts)] for i in range(5)], axis=0)
        tilts = np.convolve(np.r_[held[0], held, held[-1]], np.ones(3) / 3, mode="valid")
        if inward:
            r = np.array([np.linalg.norm(p[:2] - self.pan_xy) for p in path])
            near = np.clip((NEAR_BASE[1] - r) / (NEAR_BASE[1] - NEAR_BASE[0]), 0, 1)
            near = near * near * (3 - 2 * near)
            tilts = tilts - inward * near
        tilts[0], tilts[-1] = tilt_a, tilt_b
        # Arc-length parametrised polyline with one minimum-jerk profile over its length.
        seg = np.array([np.linalg.norm(p1 - p0) for p0, p1 in zip(path[:-1], path[1:])])
        total = seg.sum()
        T = self._duration(total, self.e["carry_speed"], 1.0, 3.5)
        T = max(T, np.abs(np.diff(tilts)).sum() / TILT_RATE / self.speed)
        cum = np.r_[0, np.cumsum(seg)] / max(total, 1e-9)
        for s in min_jerk(max(2, round(T * self.fps))):
            k = min(np.searchsorted(cum, s, side="right") - 1, len(seg) - 1)
            t = (s - cum[k]) / max(cum[k + 1] - cum[k], 1e-9)
            p = path[k] + (path[k + 1] - path[k]) * t
            tilt = tilts[k] + (tilts[k + 1] - tilts[k]) * t
            q = self._solve(p, yaw0 + (yaw1 - yaw0) * self._turn(s), offset, q, tilt=tilt)
            traj.add(q, self.close_q, "traverse")
        return q

    @staticmethod
    def _turn(s):
        """Wrist turn progress along the carry: all of it in the middle 60%, where
        the arm is closer in and reaches higher than over the far ranks."""
        t = np.clip((s - 0.2) / 0.6, 0, 1)
        return t * t * (3 - 2 * t)