File size: 32,858 Bytes
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7a278
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ae6b40
8c7a278
6686473
 
 
 
 
 
8c7a278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6686473
 
 
 
 
 
 
 
ae96451
 
 
 
 
 
 
 
 
6686473
ae96451
 
6686473
 
 
 
 
 
 
ae96451
 
 
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
 
 
 
 
 
 
 
6686473
 
 
 
ae96451
6686473
 
ae96451
6686473
 
 
ae96451
6686473
 
 
ae96451
6686473
 
ae96451
6686473
 
 
 
 
 
 
 
 
 
 
 
ae96451
6686473
 
 
ae96451
 
6686473
 
 
 
 
 
 
 
 
 
8c7a278
 
 
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
 
6686473
 
00b6c5e
6686473
 
00b6c5e
 
 
6686473
 
 
 
 
 
 
 
00b6c5e
6686473
 
 
 
 
 
 
00b6c5e
 
 
 
 
 
 
 
6686473
 
 
00b6c5e
6686473
 
 
00b6c5e
 
 
6686473
 
 
 
 
 
8c7a278
 
6686473
00b6c5e
6686473
ae96451
 
 
 
 
 
6686473
ae96451
 
 
 
 
 
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
6686473
 
 
00b6c5e
6686473
 
 
 
 
 
 
 
 
8c7a278
 
 
6686473
 
 
 
 
 
 
 
00b6c5e
 
 
8c7a278
 
 
00b6c5e
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
6686473
ae96451
 
8c7a278
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
8c7a278
6686473
8c7a278
ae96451
8c7a278
6686473
ae96451
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7a278
 
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
 
 
 
 
 
 
 
 
 
 
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
6686473
ae96451
6686473
 
 
 
 
 
 
 
 
ae96451
6686473
ae96451
6686473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
6686473
 
 
ae96451
6686473
 
 
 
 
 
 
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
"""Module 3 - Motion & Kinematics Controller.



Solves IK for the Panda and executes collision-aware pick/place trajectories.



Pick is a safe 3-phase motion:

  1. move to a pre-grasp pose 10 cm above the grasp point (gripper open),

  2. descend straight down to the grasp pose and clamp,

  3. lift the object.



During a pick we isolate collisions so that *only the finger pads* may touch the

target object; every other arm link is filtered out. This prevents the approach

motion from nudging the object before the fingers close - a failure mode that

previously produced spurious "no two-finger contact" grasps.

"""

import logging

import pybullet as pb

from . import config
from .gripper_controller import GripperController

logger = logging.getLogger(__name__)


class RobotController:
    """High-level motion controller for the Franka Panda."""

    def __init__(self, robot_id, gripper=None,

                 arm_indices=None, end_effector_index=config.END_EFFECTOR_INDEX):
        self.robot_id = robot_id
        self.arm_indices = arm_indices or config.ARM_JOINT_INDICES
        self.ee_index = end_effector_index
        self.gripper = gripper or GripperController(robot_id)
        self._down_ori = pb.getQuaternionFromEuler(config.TOP_DOWN_EULER)
        self.table_id = None
        self.tray_id = None

        # Query joint limits, ranges, and rest poses for the IK solver
        self._lower_limits = []
        self._upper_limits = []
        self._joint_ranges = []
        self._rest_poses = []
        num_joints = pb.getNumJoints(self.robot_id)
        for i in range(num_joints):
            info = pb.getJointInfo(self.robot_id, i)
            joint_type = info[2]
            if joint_type in [pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC]:
                self._lower_limits.append(info[8])
                self._upper_limits.append(info[9])
                self._joint_ranges.append(info[9] - info[8])
                if len(self._rest_poses) < len(config.ARM_REST_POSE):
                    self._rest_poses.append(config.ARM_REST_POSE[len(self._rest_poses)])
                else:
                    self._rest_poses.append(0.0)

        # Time scale for slowing down/speeding up execution speed.
        # < 1.0 increases speed. 0.1 = 10x speed.
        self.time_scale = 0.1

        # Sticky "joint got stuck" flag. Set by move_to_pose whenever a waypoint
        # is unreachable (IK saturation / singularity). The closed-loop executor
        # resets it before each high-level action and reads it afterwards to
        # decide whether to abort, recover and re-plan. Sticky (not cleared on a
        # later successful sub-move) so a mid-trajectory stall is never masked.
        self._stuck = False
        self._cancellation_token = None

    def set_cancellation_token(self, token):
        """Attach the active task token; ``None`` restores non-interruptible use."""
        self._cancellation_token = token

    def _checkpoint(self):
        token = self._cancellation_token
        if token is not None:
            token.checkpoint()

    def hold_current_pose(self):
        """Stop trajectory progress while preserving grasp and physical state."""
        current_q = self._current_joint_positions()
        for index, joint in enumerate(self.arm_indices):
            pb.setJointMotorControl2(
                self.robot_id,
                joint,
                pb.POSITION_CONTROL,
                targetPosition=current_q[index],
                force=config.ARM_MAX_FORCE,
            )

    # ------------------------------------------------------------------ #
    # Kinematics helpers
    # ------------------------------------------------------------------ #
    def _current_joint_positions(self):
        """Read the current position of every arm joint."""
        return [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]

    def _current_active_joint_positions(self):
        """Query all active (revolute/prismatic) joints of the robot."""
        positions = []
        num_joints = pb.getNumJoints(self.robot_id)
        for i in range(num_joints):
            info = pb.getJointInfo(self.robot_id, i)
            if info[2] in [pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC]:
                positions.append(pb.getJointState(self.robot_id, i)[0])
        return positions

    def _ik(self, position, orientation, seed_positions=None):
        """Solve IK for the Panda and return arm joints target positions.



        Parameters

        ----------

        seed_positions : list[float] | None

            Explicit seed; when *None* the live joint state is used.

        """
        if seed_positions is None:
            seed_positions = self._current_active_joint_positions()
        elif len(seed_positions) == len(self.arm_indices):
            # Pad with current finger joints to match active joint count
            active_q = self._current_active_joint_positions()
            seed_positions = list(seed_positions) + active_q[len(self.arm_indices):]

        solution = pb.calculateInverseKinematics(
            self.robot_id, self.ee_index, position, orientation,
            lowerLimits=self._lower_limits,
            upperLimits=self._upper_limits,
            jointRanges=self._joint_ranges,
            restPoses=seed_positions,
            maxNumIterations=300, residualThreshold=1e-5,
        )
        return list(solution[:len(self.arm_indices)])

    def tcp_position(self):
        return list(pb.getLinkState(self.robot_id, self.ee_index)[0])

    def _get_corridor_max_z(self, start_pos, target_pos, exclude_ids: list, corridor_width=0.20) -> float:
        """Find the maximum Z height of other objects within a corridor along the travel path."""
        import math
        max_z = config.TABLE_TOP_Z
        
        ax, ay = start_pos[0], start_pos[1]
        bx, by = target_pos[0], target_pos[1]
        dx, dy = bx - ax, by - ay
        ab_lensq = dx*dx + dy*dy
        
        num_bodies = pb.getNumBodies()
        for i in range(num_bodies):
            if i in exclude_ids:
                continue
            try:
                aabb_min, aabb_max = pb.getAABB(i)
                if aabb_max[2] > 1.0:  # Ignore sky/extreme geometry
                    continue
                
                # Check distance from object XY to segment AB
                px, py = 0.5 * (aabb_min[0] + aabb_max[0]), 0.5 * (aabb_min[1] + aabb_max[1])
                
                if ab_lensq < 1e-6:
                    dist = math.dist([px, py], [ax, ay])
                else:
                    t = ((px - ax) * dx + (py - ay) * dy) / ab_lensq
                    t = max(0.0, min(1.0, t))
                    cx = ax + t * dx
                    cy = ay + t * dy
                    dist = math.dist([px, py], [cx, cy])
                    
                if dist < corridor_width:
                    max_z = max(max_z, aabb_max[2])
            except Exception:
                pass
        return max_z

    def is_reachable(self, position, orientation=None, tol=0.02):
        """Check if a target pose is reachable by the robot arm.



        ``tol`` is the max EE position error (m) the IK solution may leave and

        still count as reachable. The default (0.02 m) is the tight approach

        gate; grasp pre-descend checks pass the looser descend tolerance

        (:attr:`GRASP_DESCEND_TOL`) so this pre-check stays consistent with the

        actual descend abort threshold β€” otherwise a low grasp the descend

        would reach gets vetoed here.

        """
        import math
        orientation = orientation or self._down_ori
        # Save current joint states
        old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]

        # Calculate IK
        target_joints = self._ik(position, orientation)

        # Temporarily set joint positions to solution to check EE position
        for j, q in zip(self.arm_indices, target_joints):
            pb.resetJointState(self.robot_id, j, q)

        # Get EE position
        ee_pos = self.tcp_position()
        dist = math.dist(ee_pos, position)

        # Check for physical collisions of links -1 to 8 with table or tray
        has_collision = False
        if dist < tol:
            pb.performCollisionDetection()
            for link in range(-1, 9):
                if self.table_id is not None:
                    contacts = pb.getContactPoints(self.robot_id, self.table_id, linkIndexA=link)
                    if contacts:
                        has_collision = True
                        break
                if self.tray_id is not None:
                    contacts = pb.getContactPoints(self.robot_id, self.tray_id, linkIndexA=link)
                    if contacts:
                        has_collision = True
                        break

        # Restore old joint states
        for j, q in zip(self.arm_indices, old_states):
            pb.resetJointState(self.robot_id, j, q)

        return (dist < tol) and not has_collision

    def get_max_reachable_z(self, x, y, orientation=None, start_z=0.75, step=-0.02, min_z=0.35):
        """Find the maximum Z height at a given XY coordinate that is physically reachable."""
        z = start_z
        while z >= min_z:
            if self.is_reachable([x, y, z], orientation):
                return z
            z += step
        return min_z

    def _settle(self, steps=60):
        scaled_steps = int(steps * self.time_scale)
        for _ in range(scaled_steps):
            self._checkpoint()
            pb.stepSimulation()

    # ------------------------------------------------------------------ #
    # Stuck-state signalling (for the closed-loop monitor)
    # ------------------------------------------------------------------ #
    def reset_stuck(self):
        """Clear the stuck flag β€” call right before a monitored action."""
        self._stuck = False

    def is_stuck(self):
        """True if any sub-move since the last :meth:`reset_stuck` got stuck."""
        return self._stuck

    # ------------------------------------------------------------------ #
    # Homing
    # ------------------------------------------------------------------ #
    def recover_to_rest(self, open_gripper=False):
        """Last-resort recovery: teleport the arm joints to the rest pose.



        Used by the monitor when *controlled* homing is itself stuck. Unlike

        :meth:`reset_to_home` the gripper is left as-is by default, so a carried

        object is NOT dropped β€” the arm simply jumps back to a known-good

        configuration the next plan can start from. Clears the stuck flag.

        """
        for j, q in zip(self.arm_indices, config.ARM_REST_POSE):
            pb.resetJointState(self.robot_id, j, q)
        if open_gripper:
            self.gripper.open()
        self._settle(30)
        self._stuck = False
        return self.tcp_position()

    def reset_to_home(self):
        """Teleport the arm to the rest pose and open the gripper (setup only)."""
        for j, q in zip(self.arm_indices, config.ARM_REST_POSE):
            pb.resetJointState(self.robot_id, j, q)
        for j in self.gripper.finger_indices:
            pb.resetJointState(self.robot_id, j, config.FINGER_OPEN)
        self.gripper.open()

    # ------------------------------------------------------------------ #
    # Cartesian motion (waypoint-interpolated for anti-stuck behaviour)
    # ------------------------------------------------------------------ #
    # Maximum Cartesian distance (metres) between consecutive waypoints.
    _WAYPOINT_MAX_STEP = 0.03   # 3 cm
    # If the IK solution's EE deviates more than this from the planned
    # Cartesian waypoint, we consider the waypoint unreachable and stop.
    _WAYPOINT_STUCK_TOL = 0.04  # 4 cm
    # Max TCP-to-grasp error accepted after descend before we attach the grasp
    # constraint. The pre-descend is_reachable() gate uses the SAME value so it
    # never vetoes a grasp the descend itself would have reached.
    GRASP_DESCEND_TOL = 0.05  # 5 cm

    def move_to_pose(self, position, orientation=None, steps=240, settle=30):
        """Move the TCP to *position* and *orientation* via Cartesian-space 6D interpolation.



        The straight-line path from the current TCP to *position* is split

        into segments. Orientation is interpolated using SLERP.

        At every waypoint the IK solver is re-invoked with the *current* joint

        state as seed (DLS-style) so that the solution stays near the present

        configuration and does not jump across singularities.



        If a waypoint is detected as unreachable (EE error > tolerance)

        the motion stops early and a warning is logged.

        """
        import math as _m
        orientation = orientation or self._down_ori
        start_pos = self.tcp_position()
        start_ori = pb.getLinkState(self.robot_id, self.ee_index)[1]

        # ── build Cartesian waypoints ────────────────────────────────────
        dx = position[0] - start_pos[0]
        dy = position[1] - start_pos[1]
        dz = position[2] - start_pos[2]
        dist = _m.sqrt(dx*dx + dy*dy + dz*dz)

        # compute rotation angle for segment count
        diff_q = pb.getDifferenceQuaternion(start_ori, orientation)
        angle = 2 * _m.acos(max(-1.0, min(1.0, diff_q[3])))
        
        pos_segments = int(_m.ceil(dist / self._WAYPOINT_MAX_STEP))
        rot_segments = int(_m.ceil(angle / 0.1)) # ~5.7 degrees per waypoint max
        n_segments = max(1, pos_segments, rot_segments)

        waypoints = []
        for i in range(1, n_segments + 1):
            t = i / n_segments
            wp_pos = [
                start_pos[0] + t * dx,
                start_pos[1] + t * dy,
                start_pos[2] + t * dz,
            ]
            wp_ori = pb.getQuaternionSlerp(start_ori, orientation, t)
            waypoints.append((wp_pos, wp_ori))

        # Distribute the total sim steps evenly across waypoints.
        steps_per_wp = max(4, int(steps / n_segments))
        scaled_steps_per_wp = int(steps_per_wp * self.time_scale)

        # ── traverse waypoints ───────────────────────────────────────────
        for wp_idx, (wp_pos, wp_ori) in enumerate(waypoints):
            self._checkpoint()
            current_q = self._current_joint_positions()
            target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q)

            # Stuck-detection + iterative refinement: temporarily set the
            # solved joints and check where the EE actually ends up. A single
            # DLS solve seeded from an awkward config (e.g. after a long idle
            # hold) can leave several cm of lateral error β€” enough to land a
            # finger ON a can instead of straddling it β€” so re-seed the solver
            # from its own solution until the error is millimetric.
            old_q = current_q  # already read above
            for attempt in range(4):
                for j_idx, j in enumerate(self.arm_indices):
                    pb.resetJointState(self.robot_id, j, target_q[j_idx])
                ee_check = self.tcp_position()
                ee_err = _m.dist(ee_check, wp_pos)
                if ee_err <= 0.005 or attempt == 3:
                    break
                target_q = self._ik(wp_pos, wp_ori, seed_positions=target_q)
            # Restore joints so the smooth interpolation starts from the
            # real current state (not the teleported one).
            for j_idx, j in enumerate(self.arm_indices):
                pb.resetJointState(self.robot_id, j, old_q[j_idx])

            if ee_err > self._WAYPOINT_STUCK_TOL:
                self._stuck = True   # surface the stall to the closed-loop monitor
                curr_q = self._current_joint_positions()
                logger.warning(
                    f"[IK-STUCK] Waypoint {wp_idx+1}/{len(waypoints)} "
                    f"unreachable (err={ee_err:.4f} m > tol={self._WAYPOINT_STUCK_TOL}). "
                    f"Stopping early at {[round(c,3) for c in self.tcp_position()]}. "
                    f"Joint angles: {[round(q, 4) for q in curr_q]}"
                )
                import json
                import time
                import os
                os.makedirs("test_log", exist_ok=True)
                ts = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
                dump_file = f"test_log/ik_stuck_state_{ts}.json"
                with open(dump_file, "w") as f:
                    json.dump({
                        "tcp_position": self.tcp_position(),
                        "target_waypoint": wp_pos,
                        "ee_err": ee_err,
                        "joint_angles": curr_q,
                        "ik_target_angles": list(target_q)
                    }, f, indent=2)
                logger.warning(f"Saved IK-STUCK state to {dump_file}")
                break

            # Smooth joint-space interpolation toward this waypoint.
            start_q = self._current_joint_positions()
            for s in range(1, scaled_steps_per_wp + 1):
                self._checkpoint()
                alpha = s / scaled_steps_per_wp
                for k, j in enumerate(self.arm_indices):
                    q = start_q[k] + alpha * (target_q[k] - start_q[k])
                    pb.setJointMotorControl2(
                        self.robot_id, j, pb.POSITION_CONTROL,
                        targetPosition=q, force=config.ARM_MAX_FORCE,
                    )
                pb.stepSimulation()

        # Catch-up phase: if the arm lagged behind due to velocity limits (e.g. near max reach),
        # give it some extra simulation steps to physically catch up to the final target_q.
        max_catch_up = int(400 * self.time_scale)
        for _ in range(max_catch_up):
            self._checkpoint()
            if _m.dist(self.tcp_position(), position) < 0.03:
                break
            pb.stepSimulation()

        self._settle(settle)
        return self.tcp_position()

    # ------------------------------------------------------------------ #
    # U-shaped (Lift-and-Place) trajectory
    # ------------------------------------------------------------------ #
    def _travel_ceiling(self, verts_xy, orientation, carried_height, exclude, z_safe):
        """Safe horizontal-fly height for a polyline of XY vertices.



        Clears the tallest obstacle along every segment (plus the carried

        object's height), aims for ``z_safe`` only as an upper bound, and is

        capped a margin below the lowest reachable height sampled densely along

        the whole route β€” so IK never saturates into a singularity mid-fly.

        """
        corridor_max_z = config.TABLE_TOP_Z
        for a, b in zip(verts_xy[:-1], verts_xy[1:]):
            corridor_max_z = max(
                corridor_max_z,
                self._get_corridor_max_z([a[0], a[1]], [b[0], b[1]], exclude),
            )
        z_ceiling = max(
            config.TABLE_TOP_Z + config.LIFT_HEIGHT,
            corridor_max_z + carried_height + config.TRAVEL_CLEARANCE,
        )
        if z_safe is not None:
            z_ceiling = max(z_ceiling, z_safe)            # explicit caller aim
        else:
            z_ceiling = min(z_ceiling, config.Z_SAFE_TRAVEL)   # default cap

        return z_ceiling

    def plan_u_path(self, start, xy_path, goal_z, orientation=None,

                    carried_height=0.0, exclude_ids=None, z_safe=None):
        """U-shaped trajectory that follows an XY *polyline* (e.g. an A* route).



        Rises straight to a safe ceiling, traverses every ``(x, y)`` waypoint in

        ``xy_path`` at that height (bending around obstacles), then descends onto

        the last waypoint at ``goal_z``. The ceiling is computed by

        :meth:`_travel_ceiling`, so the whole fly stays reachable and clears

        obstacle heights.

        """
        orientation = orientation or self._down_ori
        exclude = list(exclude_ids) if exclude_ids else [self.robot_id]
        verts = [(start[0], start[1])] + [(p[0], p[1]) for p in xy_path]

        z_target = self._travel_ceiling(verts, orientation, carried_height, exclude, z_safe)

        waypoints = []

        # The whole horizontal traverse is held at the safe travel ceiling
        # ``z_target`` (which already clears obstacle heights + the carried
        # object's height, and is globally bounded by ``Z_SAFE_TRAVEL``). We do
        # NOT cap traverse waypoints by a per-XY ``get_max_reachable_z`` probe:
        # that probe does a single DLS IK solve seeded from the current pose, and
        # while CARRYING an object that seed yields false "unreachable" verdicts,
        # which used to collapse the ceiling down to ``goal_z`` and drag a tall
        # object (e.g. the pear) across the table, knocking neighbours over. The
        # real motion (:meth:`move_to_pose`) walks there incrementally with good
        # seeds, so the ceiling is reachable in practice.

        # 1. Start point lift straight up to the travel ceiling.
        z_start = max(z_target, start[2], goal_z)
        waypoints.append([start[0], start[1], z_start])

        # 2. Traverse every XY waypoint AT the ceiling (stay high, don't descend).
        for (px, py) in [(p[0], p[1]) for p in xy_path]:
            waypoints.append([px, py, max(z_target, goal_z)])

        # 3. Descend vertically onto the last waypoint only.
        last = xy_path[-1]
        waypoints.append([last[0], last[1], goal_z])
        return waypoints

    def plan_u_trajectory(self, start, goal, orientation=None,

                          carried_height=0.0, exclude_ids=None, z_safe=None):
        """Straight-line U path from *start* to *goal* (single XY segment).



        Thin wrapper over :meth:`plan_u_path` for callers that don't need A*

        routing (pick approach, place). Returns ``[[sx,sy,Zc],[gx,gy,Zc],[gx,gy,gz]]``.

        """
        return self.plan_u_path(
            start, [(goal[0], goal[1])], goal[2], orientation=orientation,
            carried_height=carried_height, exclude_ids=exclude_ids, z_safe=z_safe,
        )

    def execute_trajectory(self, waypoints, orientation=None, steps=240, settle=30):
        """Drive the TCP through each waypoint in turn.



        Reuses :meth:`move_to_pose` so every segment keeps the DLS-seeded,

        Cartesian-interpolated, ``stepSimulation``-paced motion (and its

        ``[IK-STUCK]`` guard). Returns the final TCP position.

        """
        orientation = orientation or self._down_ori
        for wp in waypoints:
            self._checkpoint()
            self.move_to_pose(wp, orientation, steps=steps, settle=settle)
        return self.tcp_position()

    # ------------------------------------------------------------------ #
    # Collision isolation (only finger pads may touch the target object)
    # ------------------------------------------------------------------ #
    def isolate_object_collisions(self, object_id):
        n_links = pb.getNumJoints(self.robot_id)
        for link in range(-1, n_links):
            pb.setCollisionFilterPair(self.robot_id, object_id, link, -1, 0)
        for finger in self.gripper.finger_indices:
            pb.setCollisionFilterPair(self.robot_id, object_id, finger, -1, 1)

    def isolate_gripper_collisions(self, object_id):
        """Disable collisions for gripper fingers with the object to avoid physics jitter."""
        for finger in self.gripper.finger_indices:
            pb.setCollisionFilterPair(self.robot_id, object_id, finger, -1, 0)

    def restore_object_collisions(self, object_id):
        n_links = pb.getNumJoints(self.robot_id)
        for link in range(-1, n_links):
            pb.setCollisionFilterPair(self.robot_id, object_id, link, -1, 1)

    # ------------------------------------------------------------------ #
    # Pick / place primitives
    # ------------------------------------------------------------------ #
    def _abort_grasp_retract(self, object_id, orientation=None):
        """Back the gripper straight up BEFORE restoring arm-object collisions.



        Restoring collisions while a finger is still wedged against (or

        overlapping) the object makes the solver eject it violently β€” that is

        how a failed grasp knocks the object off the table. Retreating first

        leaves the object standing where it is.

        """
        tcp = self.tcp_position()
        safe_z = max(config.TABLE_TOP_Z + config.LIFT_HEIGHT, tcp[2] + 0.10)
        self.move_to_pose([tcp[0], tcp[1], safe_z], orientation or self._down_ori, steps=180)
        self.restore_object_collisions(object_id)

    def pick(self, object_id, grasp_pos, grasp_ori=None):
        """Execute the 3-phase pick. Returns (grip_force_N, is_holding).



        Collision isolation stays active after the lift so the object doesn't

        collide with arm links during transport. Caller must ensure place() is

        called (which restores collisions after release).

        """
        import math
        grasp_ori = grasp_ori or self._down_ori
        self.isolate_object_collisions(object_id)
        logger.debug(f"pick phase-1: pre-grasp hover object_id={object_id}")

        # Phase 1: hover above with the gripper open, reaching the pre-grasp via
        # a U-shaped path so the arm never sweeps diagonally through tall objects.
        # The gripper is empty here, so carried_height=0; the target itself is
        # excluded from the corridor scan (pre-grasp already sits above it).
        self.gripper.open()
        pre_grasp = [grasp_pos[0], grasp_pos[1], grasp_pos[2] + config.PRE_GRASP_HEIGHT]
        tcp_pos = self.tcp_position()
        waypoints = self.plan_u_trajectory(
            tcp_pos, pre_grasp, orientation=grasp_ori,
            carried_height=0.0, exclude_ids=[self.robot_id, object_id],
        )
        self.execute_trajectory(waypoints, grasp_ori)

        # Check reachability before descend β€” use the same tolerance the descend
        # abort uses, so this gate never rejects a grasp the descend would reach.
        if not self.is_reachable(grasp_pos, grasp_ori, tol=self.GRASP_DESCEND_TOL):
            logger.warning(f"[WARN ] Target grasp position {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting grasp.")
            self._abort_grasp_retract(object_id, grasp_ori)
            return 0.0, False

        # Phase 2: descend straight down, then attach via constraint.
        logger.debug(f"pick phase-2: descend to grasp pos={[round(c,3) for c in grasp_pos]}")
        self.move_to_pose(grasp_pos, grasp_ori, steps=160)
        
        # Check actual EE distance to grasp target (prevent "magic" constraint grasping)
        tcp_pos = self.tcp_position()
        dist_to_grasp = math.dist(tcp_pos, grasp_pos)
        if dist_to_grasp > self.GRASP_DESCEND_TOL:
            logger.warning(f"[WARN ] TCP is too far from grasp position! Distance: {dist_to_grasp:.3f} m. Grasp aborted.")
            self._abort_grasp_retract(object_id, grasp_ori)
            return 0.0, False

        force = self.gripper.grasp(object_id)
        self._settle(60)

        # Phase 3: lift β€” TCP must be high enough that the object's bottom clears the table and other objects.
        # TCP is at the object's top (AABB grasp); object bottom = TCP_z - obj_height.
        aabb_min, aabb_max = pb.getAABB(object_id)
        obj_height = aabb_max[2] - aabb_min[2]
        
        # Calculate max_other_z in the corridor at grasp_pos (start and target have same XY)
        max_other_z = self._get_corridor_max_z(grasp_pos, grasp_pos, [self.robot_id, object_id])
        
        min_lift_z = max_other_z + obj_height + 0.05   # 5 cm margin above the tallest other object
        lift_z = max(config.TABLE_TOP_Z + config.LIFT_HEIGHT, min_lift_z)
        lift = [grasp_pos[0], grasp_pos[1], lift_z]
        logger.debug(f"pick phase-3: lift to z={lift_z:.3f} (obj_height={obj_height:.3f}, max_other_z={max_other_z:.3f})")
        self.move_to_pose(lift, grasp_ori)

        # Isolation kept active during transport β€” place() restores on release.
        held = self.gripper.is_holding(object_id)
        return force, held

    def place(self, target_pos, orientation=None, clearance=0.02):
        """Move above the target, lower to correct height, release, and retract.



        TCP is lowered so the object's bottom arrives at target_pos[2] + clearance.

        Collision isolation (set by pick) is restored after the gripper opens so

        the arm can retract without nudging the freshly-placed object.

        """
        import math
        orientation = orientation or self._down_ori
        # Compute held object height to calculate dynamic safe above_z
        held_id = self.gripper._constrained_id
        if held_id is not None:
            aabb_min, aabb_max = pb.getAABB(held_id)
            obj_height = aabb_max[2] - aabb_min[2]
            exclude = [self.robot_id, held_id]
        else:
            obj_height = 0.0
            exclude = [self.robot_id]
            
        # Lower the TCP so the carried object's bottom lands at target_z + clearance,
        # reaching it via a U-shaped path that clears obstacles in the corridor
        # (carried object's height is added to the clearance).
        tcp_pos = self.tcp_position()
        tcp_z = target_pos[2] + clearance + obj_height
        lower = [target_pos[0], target_pos[1], tcp_z]
        waypoints = self.plan_u_trajectory(
            tcp_pos, lower, orientation=orientation,
            carried_height=obj_height, exclude_ids=exclude,
        )
        logger.debug(
            f"place: U-path to {[round(c,3) for c in target_pos]}, "
            f"ceiling={waypoints[0][2]:.3f}, lower tcp_z={tcp_z:.3f} (obj_height={obj_height:.3f})"
        )
        self.execute_trajectory(waypoints, orientation)

        # Release constraint: snap ONLY Z so object bottom lands exactly on the target surface.
        # XY is already correct (arm is positioned at target XY). Restoring arm-object collisions
        # AFTER retract prevents the arm from nudging the freshly-placed object.
        logger.debug("place: releasing gripper")
        if held_id is not None:
            obj_pos, obj_ori = pb.getBasePositionAndOrientation(held_id)
            aabb_min_now, aabb_max_now = pb.getAABB(held_id)
            half_h = (aabb_max_now[2] - aabb_min_now[2]) / 2
        self.gripper.open()  # removes constraint
        if held_id is not None:
            cur_pos, _ = pb.getBasePositionAndOrientation(held_id)
            snap_z = target_pos[2] + half_h
            # If the arm deviated significantly from the target XY (IK couldn't fully
            # reach the target), snap XY too so the object doesn't land in the wrong slot.
            xy_err = math.dist([cur_pos[0], cur_pos[1]], [target_pos[0], target_pos[1]])
            if xy_err > 0.05:
                logger.warning(
                    f"place: arm deviated {xy_err:.3f} m from target XY "
                    f"({[round(c,3) for c in target_pos[:2]]}); snapping XY as well"
                )
                snap_x, snap_y = target_pos[0], target_pos[1]
            else:
                snap_x, snap_y = cur_pos[0], cur_pos[1]
            # Force zero roll and pitch so the object lands perfectly upright/flat (stable)
            yaw = pb.getEulerFromQuaternion(obj_ori)[2]
            upright_ori = pb.getQuaternionFromEuler([0.0, 0.0, yaw])
            pb.resetBasePositionAndOrientation(
                held_id,
                [snap_x, snap_y, snap_z],
                upright_ori,
            )
        self._settle(120)
        # Retract UPWARD from tcp_z, then restore collisions (arm is clear of placed object).
        retract = [target_pos[0], target_pos[1], tcp_z + config.PRE_GRASP_HEIGHT]
        self.move_to_pose(retract, orientation)
        if held_id is not None:
            self.restore_object_collisions(held_id)