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 | class StealPantryAction(Action):
"""
Action used to steal crates from a pantry.
"""
def __init__(
self,
planner: "Planner",
strategy: Strategy,
pantry_id: PantryID,
weight: float = 2000000.0,
):
self.custom_weight = weight
super().__init__(f"StealPantry {pantry_id.name}", planner, strategy)
self.before_action_func = self.before_action
self.pantry_id = pantry_id
self.shift_inspect = 350
self.shift_align = 150
self.shift_capture = self.shift_align + 15
self.shift_approach = self.shift_align + 160
self.shift_step_back = 70
if Camp().color == Camp.Colors.blue:
self.good_crate_id = 36
self.bad_crate_id = 47
else:
self.good_crate_id = 47
self.bad_crate_id = 36
self.crate_group: CrateGroup | None = None
@property
def pantry(self) -> Pantry:
return self.planner.game_context.pantries[self.pantry_id]
async def recycle(self):
self.pantry.enabled = self.pantry_enabled_backup
self.recycled = True
async def before_action(self):
self.logger.info(f"{self.name}: before_action")
self.poses.clear()
self.crate_group: CrateGroup | None = None
self.pantry_enabled_backup = self.pantry.enabled
self.pantry.enabled = False
if self.planner.game_context.front_free:
self.side = "front"
self.crates_ids = self.planner.game_context.front_crates
self.arms_open = functools.partial(actuators.front_arms_open, self.planner)
self.arms_close = functools.partial(actuators.front_arms_close, self.planner)
self.lift_down = functools.partial(actuators.front_lift_down, self.planner)
self.lift_mid = functools.partial(actuators.front_lift_mid, self.planner)
else:
self.side = "back"
self.crates_ids = self.planner.game_context.back_crates
self.arms_open = functools.partial(actuators.back_arms_open, self.planner)
self.arms_close = functools.partial(actuators.back_arms_close, self.planner)
self.lift_down = functools.partial(actuators.back_lift_down, self.planner)
self.lift_mid = functools.partial(actuators.back_lift_mid, self.planner)
x, y = crates_utils.shift_pantry_center_from_border(self.pantry)
self.inspect_pose = Pose(
x=x,
y=y,
O=0,
max_speed_linear=100,
max_speed_angular=100,
motion_direction=MotionDirection.BIDIRECTIONAL,
bypass_final_orientation=False,
stop_before_distance=self.shift_inspect,
before_pose_func=self.before_inspect_pose,
after_pose_func=self.after_inspect_pose,
)
self.poses.append(self.inspect_pose)
async def before_inspect_pose(self):
self.logger.info(f"{self.name}: before_inspect_pose")
if self.planner.game_context.front_free:
await actuators.front_arms_close(self.planner)
await actuators.front_lift_mid(self.planner)
if self.planner.game_context.back_free:
await actuators.back_arms_close(self.planner)
await actuators.back_lift_mid(self.planner)
async def after_inspect_pose(self):
self.logger.info(f"{self.name}: after_inspect_pose")
await asyncio.sleep(0.5)
pose_current = self.planner.pose_current
# Check orientation to pantry
angle_to_pantry = math.degrees(math.atan2(self.pantry.y - pose_current.y, self.pantry.x - pose_current.x))
angle_diff = angle_to_pantry - pose_current.O
self.logger.info(
f"{self.name}: angle to pantry: "
f"{angle_to_pantry: 3.2f}°, current angle: {pose_current.O: 3.2f}°, diff: {angle_diff: 3.2f}°"
)
# Normalize to [-180, 180]
while angle_diff > 180:
angle_diff -= 360
while angle_diff < -180:
angle_diff += 360
if abs(angle_diff) > 10:
# Need to add an orientation adjustment pose
self.logger.info(f"{self.name}: adding orientation adjustment pose (diff={angle_diff: 3.2f}°)")
adjust_pose = Pose(
x=pose_current.x,
y=pose_current.y,
O=angle_to_pantry,
max_speed_linear=50,
max_speed_angular=50,
motion_direction=MotionDirection.BIDIRECTIONAL,
bypass_final_orientation=False,
before_pose_func=self.before_inspect_orientation,
after_pose_func=self.after_inspect_orientation,
)
self.poses.append(adjust_pose)
else:
self.logger.info(f"{self.name}: orientation to pantry is acceptable (diff={angle_diff: 3.2f}°)")
await self.after_inspect_orientation()
async def before_inspect_orientation(self):
self.logger.info(f"{self.name}: before_inspect_orientation")
async def after_inspect_orientation(self):
self.logger.info(f"{self.name}: after_inspect_orientation")
await asyncio.sleep(0.5)
pose_current = self.planner.pose_current
crates_found: list[tuple[int, models.Pose]] = await get_crates_position(self.planner)
self.logger.info(f"{self.name}: crates found:")
for crate_id, pose in crates_found:
self.logger.info(f"{self.name}: - {crate_id}: x={pose.x: 5.2f} y={pose.y: 5.2f} O={pose.O: 3.2f}°")
# 1. Analyze crates to find valid groups
analyzer = CrateAnalyzer(self.good_crate_id, self.bad_crate_id)
valid_groups = analyzer.find_groups(crates_found)
if not valid_groups:
self.logger.warning(f"{self.name}: No valid crate group found")
return
for i, group in enumerate(valid_groups):
self.logger.info(
f"{self.name}: Group {i}: x={group.pose.x: 5.2f} y={group.pose.y: 5.2f} O={group.pose.O: 3.2f}°"
f" IDs={group.crate_ids} BadCount={group.bad_crate_count}"
)
# 2. Select the best group that is reachable
best_approach_pose: models.Pose | None = None
for group in valid_groups:
# Convert group_pose to table frame
group_pose_table = transform_to_table_frame(group.pose, pose_current)
self.logger.info(
f"{self.name}: Testing group (table frame): "
f"x={group_pose_table.x: 5.2f} y={group_pose_table.y: 5.2f} O={group_pose_table.O: 3.2f}°"
)
# Exclude groups too far from pantry
dist_to_pantry = math.hypot(
group_pose_table.x - self.pantry.x,
group_pose_table.y - self.pantry.y,
)
if dist_to_pantry > 180:
self.logger.info(f"{self.name}: Group too far from pantry (dist={dist_to_pantry:.0f}mm), skipping")
continue
# Update pantry state using crate group pose
self.pantry.x = group_pose_table.x
self.pantry.y = group_pose_table.y
self.pantry.O = group_pose_table.O
self.pantry.enabled = True
# Compute possible approach positions
front_approach_pose = get_relative_pose(
group_pose_table,
front_offset=-self.shift_approach,
angular_offset=0,
)
back_approach_pose = get_relative_pose(
group_pose_table,
front_offset=self.shift_approach,
angular_offset=180,
)
# Identify obstacle crates (transform to table frame)
# A crate is part of the group if it is within 150mm of the group center (in robot frame)
obstacle_crates_table: list[models.Pose] = []
for _, crate_pose in crates_found:
if crate_pose in group.crates:
continue
obstacle_crates_table.append(transform_to_table_frame(crate_pose, pose_current))
# Check reachability
approach_pose = self.choose_approach_position(
pose_current,
front_approach_pose,
back_approach_pose,
group_pose_table,
obstacle_crates_table,
)
if approach_pose:
self.crate_group = group
best_approach_pose = approach_pose
self.logger.info(f"{self.name}: Found reachable group with approach: {approach_pose}")
break
else:
self.logger.info(f"{self.name}: Group not reachable")
if not self.crate_group:
self.logger.warning(f"{self.name}: No reachable group found")
return
if self.crate_group.bad_crate_count == 0:
self.logger.warning(f"{self.name}: Selected group has no bad crates, aborting steal")
return
self.crates_ids[:] = self.crate_group.crate_ids[:]
# Create approach pose
approach_pose = Pose(
**best_approach_pose.model_dump(),
max_speed_linear=10,
max_speed_angular=10,
motion_direction=MotionDirection.BIDIRECTIONAL,
bypass_final_orientation=True,
before_pose_func=self.before_approach,
after_pose_func=self.after_approach,
)
self.poses.append(approach_pose)
self.logger.info(
f"{self.name}: approach: x={approach_pose.x: 5.2f} y={approach_pose.y: 5.2f} O={approach_pose.O: 3.2f}°"
)
# Align
align_pose = Pose(
**get_relative_pose(
best_approach_pose,
front_offset=self.shift_approach - self.shift_align,
angular_offset=0,
).model_dump(),
max_speed_linear=10,
max_speed_angular=10,
motion_direction=(
MotionDirection.FORWARD_ONLY if self.planner.game_context.front_free else MotionDirection.BACKWARD_ONLY
),
before_pose_func=self.before_align,
after_pose_func=self.after_align,
)
self.poses.append(align_pose)
self.logger.info(f"{self.name}: align: x={align_pose.x: 5.2f} y={align_pose.y: 5.2f} O={align_pose.O: 3.2f}°")
# Capture
capture_pose = Pose(
**get_relative_pose(
best_approach_pose,
front_offset=self.shift_approach - self.shift_capture,
angular_offset=0,
).model_dump(),
max_speed_linear=10,
max_speed_angular=10,
motion_direction=(
MotionDirection.BACKWARD_ONLY if self.planner.game_context.front_free else MotionDirection.FORWARD_ONLY
),
bypass_final_orientation=True,
before_pose_func=self.before_capture,
after_pose_func=self.after_capture,
)
self.poses.append(capture_pose)
self.logger.info(
f"{self.name}: capture: x={capture_pose.x: 5.2f} y={capture_pose.y: 5.2f} O={capture_pose.O: 3.2f}°"
)
def choose_approach_position(
self,
pose_current: models.Pose,
front_pose: models.Pose,
back_pose: models.Pose,
group_pose: models.Pose,
obstacle_crates: list[models.Pose],
) -> models.Pose | None:
"""
Choose the best approach position (front or back) based on distance to current pose.
"""
valid_poses: list[models.Pose] = [front_pose, back_pose]
# check if approach positions are within table bounds
robot_width = self.planner.shared_properties.robot_width
limits = self.planner.shared_table_limits.copy()
limits[0] += robot_width / 2 # min x
limits[1] -= robot_width / 2 # max x
limits[2] += robot_width / 2 # min y
limits[3] -= robot_width / 2 # max y
for pose in valid_poses.copy():
if not (limits[0] <= pose.x <= limits[1] and limits[2] <= pose.y <= limits[3]):
self.logger.warning(
f"{self.name}: Approach position x={pose.x: 5.2f} y={pose.y: 5.2f}° out of table bounds"
)
valid_poses.remove(pose)
if not valid_poses:
self.logger.warning(f"{self.name}: No valid approach positions within table bounds")
return None
# Check if approach positions is not in an obstacle
# and if the path between approach and capture pose is clear
self.planner.shared_obstacles_lock.start_reading()
for pose in valid_poses.copy():
capture_pose = get_relative_pose(
pose,
front_offset=self.shift_approach - self.shift_capture,
angular_offset=0,
)
# Check dynamic and static obstacles from planner
is_valid = True
for obstacle_list in [self.planner.shared_circle_obstacles, self.planner.shared_rectangle_obstacles]:
obstacle_list: list[ObstacleCircle | ObstacleRectangle]
for obstacle in obstacle_list:
if obstacle.is_point_inside(pose.x, pose.y):
self.logger.warning(
f"{self.name}: Approach position x={pose.x: 5.2f} y={pose.y: 5.2f} in obstacle"
)
is_valid = False
break
if obstacle.is_segment_crossing(pose.x, pose.y, capture_pose.x, capture_pose.y):
self.logger.warning(
f"{self.name}: Path from approach x={pose.x: 5.2f} y={pose.y: 5.2f}° "
f"to capture x={capture_pose.x: 5.2f} y={capture_pose.y: 5.2f}° intersects obstacle"
)
is_valid = False
break
if not is_valid:
valid_poses.remove(pose)
break
if not is_valid:
continue
# Check against other crates
for crate_pose in obstacle_crates:
obstacle = ObstacleRectangle(crate_pose.x, crate_pose.y, crate_pose.O, 160, 60, 0)
if obstacle.is_point_inside(pose.x, pose.y):
self.logger.warning(
f"{self.name}: Approach position x={pose.x: 5.2f} y={pose.y: 5.2f}"
f" inside crate at x={crate_pose.x:.0f} y={crate_pose.y:.0f}"
)
is_valid = False
break
if obstacle.is_segment_crossing(pose.x, pose.y, group_pose.x, group_pose.y):
self.logger.warning(
f"{self.name}: Approach path from x={pose.x: 5.2f} y={pose.y: 5.2f}"
f" to x={group_pose.x: 5.2f} y={group_pose.y: 5.2f} intersects crate"
f" at x={crate_pose.x:.0f} y={crate_pose.y:.0f}"
)
is_valid = False
break
if not is_valid:
valid_poses.remove(pose)
self.planner.shared_obstacles_lock.finish_reading()
if not valid_poses:
self.logger.warning(f"{self.name}: No valid approach positions available")
return None
if len(valid_poses) == 1:
self.logger.info(f"{self.name}: Only one valid approach position available")
return valid_poses[0]
# Select closest approach position
dist_front = math.hypot(front_pose.x - pose_current.x, front_pose.y - pose_current.y)
dist_back = math.hypot(back_pose.x - pose_current.x, back_pose.y - pose_current.y)
if dist_front <= dist_back:
self.logger.info(f"{self.name}: Chose front approach position (distance: {dist_front: 5.2f} mm)")
return front_pose
else:
self.logger.info(f"{self.name}: Chose back approach position (distance: {dist_back: 5.2f} mm)")
return back_pose
async def before_approach(self):
self.logger.info(f"{self.name}: before_approach")
await self.arms_close()
await self.lift_mid()
async def after_approach(self):
self.logger.info(f"{self.name}: after_approach")
async def before_align(self):
self.logger.info(f"{self.name}: before_align")
self.pantry.enabled = False
await self.lift_down()
await self.arms_open()
self.logger.info(f"{self.name}: before_align: end")
async def after_align(self):
self.logger.info(f"{self.name}: after_align")
async def before_capture(self):
self.logger.info(f"{self.name}: before_capture: begin")
async def after_capture(self):
self.logger.info(f"{self.name}: after_capture")
await crates_utils.take_crates(self.planner, self.side)
drop_pose = await crates_utils.drop_crates(self.planner, self.side)
self.after_drop_org = drop_pose.after_pose_func
drop_pose.after_pose_func = self.after_drop
self.poses.append(drop_pose)
async def after_drop(self):
await self.after_drop_org()
# Step back
pose_current = self.pose_current
shift_step_back = self.shift_step_back if self.side == "front" else -self.shift_step_back
step_back_pose = Pose(
**get_relative_pose(pose_current, front_offset=-shift_step_back).model_dump(),
max_speed_linear=50,
max_speed_angular=50,
motion_direction=MotionDirection.BACKWARD_ONLY if self.side == "front" else MotionDirection.FORWARD_ONLY,
bypass_final_orientation=True,
before_pose_func=self.before_step_back,
after_pose_func=self.after_step_back,
)
self.poses.append(step_back_pose)
self.logger.info(
f"{self.name}: step back: x={step_back_pose.x: 5.2f} y={step_back_pose.y: 5.2f} O={step_back_pose.O: 3.2f}°"
)
async def before_step_back(self):
self.logger.info(f"{self.name}: before_step_back")
async def after_step_back(self):
self.logger.info(f"{self.name}: after_step_back")
self.pantry.enabled = True
def weight(self) -> float:
if not self.planner.game_context.front_free and not self.planner.game_context.back_free:
self.logger.info(f"{self.name}: Rejected: both front and back are full")
return 0
return self.custom_weight
|