From 1f04a95e1bf40ee0bd65b0d99ff4b663181e6756 Mon Sep 17 00:00:00 2001 From: duongtd Date: Tue, 25 Aug 2026 12:14:58 +0700 Subject: [PATCH] =?UTF-8?q?feat:=20th=C3=AAm=20m=C3=B4=20h=C3=ACnh=20?= =?UTF-8?q?=C4=91=E1=BB=99ng=20h=E1=BB=8Dc=20differential=20v=C3=A0=20mane?= =?UTF-8?q?uver=20straight-pivot-straight?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hai thay đổi đi cùng một commit vì maneuver mới là hình dạng chính của base differential, đồng thời là fallback của base Ackermann; tách ra sẽ tạo commit trung gian không build được. Mô hình động học (kinematics/kinematic_model): - kAckermann là mặc định và giữ nguyên hành vi cũ, nên YAML chưa khai báo khoá này không đổi gì. - kDifferential bỏ qua lookup axle TF. Base differential không publish frame trục lái, tra cứu sẽ ném exception và làm chết plugin ngay lúc initialize; bán kính quay nhỏ nhất do đó lấy thẳng từ kinematics/minimum_turning_radius. - Bán kính 0 giờ là giá trị hợp lệ, nghĩa là robot xoay tại chỗ được. Chỉ giá trị âm hoặc không hữu hạn mới là lỗi cấu hình. Maneuver straight-pivot-straight: - Đỉnh xoay nằm giữa robot và dock nên không tốn thêm chiều sâu lối đi như cusp, vốn đẩy robot ra xa dock hơn chỗ đang đứng. - Vòng xoay tại chỗ được ghi thẳng vào path thành một khối pose cùng vị trí, khác yaw. Base Ackermann không đổi hướng ở một góc gấp của polyline, nên trạng thái dừng-đánh-lái phải nằm trong plan chứ không để controller tự suy. - maneuver/pivot_fallback_extension mở khoá hình dạng này cho Ackermann, đo bằng phần cusp đẩy robot RA XA dock hơn chỗ nó đang đứng. Ngưỡng tương đối là có chủ đích: bản trước đo chiều sâu lối đi tuyệt đối, cộng cả khoảng robot đang chiếm, nên loại bỏ mọi maneuver xuất phát từ khoảng cách tiếp cận bình thường. Mặc định 0 = tắt hoàn toàn. - maneuver/pivot_safety_margin giữ khoảng hở giữa đường tròn thân xe quét khi xoay tại chỗ và mặt gần của dock. Xoay tại chỗ quay mọi điểm footprint quanh base_link nên kích thước liên quan là circumscribed radius, luôn lớn hơn mating extent dùng cho đoạn thẳng cuối. Kiểm chứng: catkin_make --pkg dock_planner build sạch, ./devel/lib/dock_planner/dock_planner_test PASS. --- README.md | 234 +++++++++--- config/dock_global_params.yaml | 126 +++++-- include/dock_planner/dock_calc.h | 52 ++- include/dock_planner/dock_planner_config.h | 69 +++- src/dock_calc.cpp | 419 +++++++++++++++++---- src/dock_planner.cpp | 89 +++-- src/dock_planner_config.cpp | 104 ++++- test/dock_planner_test.cpp | 261 ++++++++++++- 8 files changed, 1132 insertions(+), 222 deletions(-) diff --git a/README.md b/README.md index e8eb35f..6de9e76 100644 --- a/README.md +++ b/README.md @@ -1,85 +1,199 @@ # Dock Planner -Global planner cho docking Ackermann theo một maneuver xác định: +Global planner sinh đường vào dock, implement `robot_nav_core::BaseGlobalPlanner` +và export bằng `BOOST_DLL_ALIAS` với symbol `DockPlanner`. + +Planner chỉ sinh **hình học**. Collision / free-space checking chưa được +implement — xem "Phạm vi an toàn hiện tại". + +## Ba kiểu đường + +Planner thử theo thứ tự và lấy kiểu **đầu tiên dựng được**. Kiểu nào không dựng +được thì **rơi xuống kiểu kế tiếp**, không bao giờ trở thành lỗi. Chỉ khi mọi +kiểu đều trượt mới trả `false` kèm một dòng log liệt kê đủ số đo. ```text -start -- tiến theo cung tròn --> cusp -- lùi thẳng --> goal +1. direct_entry start ──── cung ────╮ + ╰─ thẳng ─► goal + +2. single_cusp goal ◄─ thẳng ─ ✖cusp + ╰─ cung ─── start + lấn thêm `cusp_extension` mét về phía XA dock + +3. straight_pivot_straight goal ◄─ thẳng ─ V ⟳xoay⟳ ─ thẳng ─ start + điểm xoay nằm GIỮA robot và dock: lấn thêm 0 mét ``` -Planner chỉ sinh hình học. Collision/free-space checking chưa được implement. +Đoạn cuối của cả ba kiểu luôn **thẳng** và trùng hướng yaw của goal: robot phải +đạt đúng hướng trước khi chui vào dock. -## Luồng xử lý +### Kiểu nào được chọn -1. `DockPlanner::initialize()` load và validate config. -2. Lấy `wheel_base` từ TF `front_axle_frame -> rear_axle_frame`, giống - `StanleyControl`. -3. Tính giới hạn động học bicycle: +```text +turns_in_place = (model == differential) && (minimum_turning_radius == 0) +pivot_enabled = turns_in_place || (pivot_fallback_extension > 0) +prefer_pivot = pivot_enabled && ( turns_in_place + || cusp không đặt được + || cusp_extension > pivot_fallback_extension ) +``` - ```text - minimum_turning_radius = wheel_base / tan(max_steering_angle) - ``` +| tình huống | thứ tự thử | +|---|---| +| `turns_in_place` | direct_entry → **pivot** → cusp | +| ackermann, `cusp_extension` vượt ngưỡng | direct_entry → **pivot** → cusp | +| ackermann, cusp rẻ | direct_entry → **cusp** → pivot | +| `pivot_fallback_extension = 0`, không turns_in_place | direct_entry → **cusp** | -4. `DockCalc` đổi start sang hệ tọa độ goal: longitudinal dọc trục dock và - lateral vuông góc trục dock. -5. Chọn cusp ở phía trước start, đủ xa dock và đủ xa để cung tiếp cận có bán - kính không nhỏ hơn `minimum_turning_radius`. -6. Lấy mẫu cung tiến. Pose yaw luôn cùng chiều tangent của cung, không dùng yaw - hiện tại của robot. -7. Lấy mẫu đoạn thẳng từ cusp về goal. Pose yaw giữ bằng goal yaw nên controller - phân loại đoạn này là chạy lùi. -8. Ghép hai đoạn, bỏ điểm cusp trùng và đóng dấu frame/time. +`cusp_extension = cusp_distance − start_longitudinal`, tức cusp bắt robot chạy ra +xa dock thêm bao nhiêu **so với chỗ nó đang đứng**. Đại lượng này cố ý là **tương +đối**: một số tuyệt đối kiểu "chiều sâu lối đi" sẽ tính cả chỗ robot đang đứng +vào phần "cần thêm", và loại sạch mọi manơ xuất phát từ khoảng cách bình thường. -## Hợp đồng hình học +`direct_entry` chỉ vào danh sách khi `direct_entry_min_curve_room > 0` và khoảng +chỗ còn lại cho cung vượt ngưỡng đó. -- Goal yaw phải chỉ từ dock ra phía robot tiếp cận. Start phải có longitudinal - dương trong frame goal; planner từ chối start nằm phía sau dock thay vì âm - thầm đảo goal yaw. -- Robot footprint phải có ít nhất ba điểm, hữu hạn, có X/Y extent dương. Đoạn - cuối luôn lùi nên khoảng cách cusp tối thiểu dùng `rear_extent` của robot. -- `dock_anchor: center` cộng near-face `front_extent` của `footprint_dock` vào - khoảng cách cusp. `dock_anchor: face` bỏ qua dock footprint. -- Cung đầu luôn chạy tiến và có `radius >= minimum_turning_radius`. -- Đoạn cuối nằm đúng trên trục dock, chạy lùi và có yaw bằng goal yaw. -- Path có đúng một lần đổi chiều tại cusp. -- Mọi lỗi TF, NaN/Inf, footprint sai, bán kính sai hoặc maneuver vượt giới hạn - đều trả `false`; planner không trả partial path. +## Hai mô hình động học -`footprint_dock` và `dock_anchor` được move_base2 copy từ -`docking_marker_profiles//` vào namespace `DockPlanner` trước khi tạo -plugin. +| | `ackermann` | `differential` | +|---|---|---| +| `R_min` | **đo**: `wheel_base / tan(max_steering_angle)` | **đọc**: `minimum_turning_radius` | +| `wheel_base` | lấy từ TF `rear_axle_frame → front_axle_frame` | không dùng, đặt 0 | +| TF trục bánh | bắt buộc phải tra được, không thì `initialize()` fail | **không tra** | +| `max_steering_angle` | bắt buộc, phải ∈ (0, π/2) | không đọc, không validate | +| axle frames | phải khác nhau, không rỗng | không đọc, không validate | +| xoay tại chỗ | chỉ khi `pivot_fallback_extension > 0` | khi `minimum_turning_radius == 0` | + +`R_min == 0` là **giá trị hợp lệ**, không phải lỗi: đó là thứ cho phép planner +đặt một cú xoay tại chỗ vào path. Chỉ số âm hoặc không hữu hạn mới là lỗi. + +Khai nhầm `ackermann` cho robot vi sai thì plugin **không nạp được** — nó đi tra +frame `steer_link` mà robot vi sai không có. + +## Điểm xoay đặt ở đâu + +```text +Xv = max( độ dài đoạn thẳng cuối, + circumscribed_radius + nửa thân dock phía tiếp cận + pivot_safety_margin ) +``` + +Xoay tại chỗ quay **mọi** điểm footprint quanh `base_link`, nên kích thước phải +dùng là **bán kính ngoại tiếp**, không phải `front_extent`/`rear_extent`. Với +footprint 1.65 / −0.35 × ±0.40: ngoại tiếp `hypot(1.65, 0.40) = 1.698 m` trong +khi mép sau chỉ 0.35 m. Đặt điểm xoay theo mép sau là góc robot cắt vào dock. + +`circumscribed_radius` là max `hypot(x, y)` trên các đỉnh footprint. Chính xác +tuyệt đối, kể cả footprint lõm: khoảng cách là hàm lồi nên cực đại trên đa giác +luôn rơi vào một đỉnh. + +Chiều chạy đoạn 1 chọn theo **|góc xoay| nhỏ nhất**. Trên cả hai phía dock, lựa +chọn đó trùng chiều đoạn cuối, nên path có **một chiều chạy duy nhất** từ đầu tới +cuối — không có điểm đổi chiều nào, tốt hơn `single_cusp` về mặt điều khiển. + +## Khối xoay được mã hoá thế nào — hợp đồng với local planner + +Cú xoay ghi vào path thành một **khối pose cùng vị trí, yaw tăng dần**, chứ không +phải một đỉnh gãy trần: robot Ackermann lẫn vi sai đều không đổi hướng tức thời +tại vertex được. + +Ba ràng buộc bắt buộc, sai một cái là khối bị nuốt mất: + +1. Khối ghi bằng `push_back`, **không** qua `appendUnique()` — hàm đó tồn tại + đúng để xoá pose không di chuyển, tức xoá sạch khối xoay. +2. Khối tối thiểu **4 pose cùng vị trí**. `StanleyControl::planDivision` chỉ tách + segment xoay sau `++rot_count > 2`, mà `rot_count` chỉ tăng ở pose có + `same_xy_prev`. Planner phát 7 pose (vertex + `kPivotBlockSteps`). +3. Bước yaw mỗi pose phải `> kPlanEpsilon` (`1e-6`), nếu không `same_yaw` đúng và + Case 1 không đếm. + +Đổi local planner docking sang plugin khác thì phải kiểm lại ba điều trên — +planner mới có nhận dạng khối pose cùng vị trí không. + +## Mép nào của robot áp vào dock + +**Suy ra** theo từng lần lập plan, không cấu hình được: + +| robot đứng phía | mép áp dock | đoạn dẫn | đoạn cuối | +|---|---|---|---| +| `+X` của goal | sau (`rear_extent`) | tiến | lùi | +| `−X` của goal | trước (`front_extent`) | lùi | tiến | + +Suy được vì goal đã offset sẵn từ tầng trên sao cho `base_link` dừng đúng tại +goal khi manơ hoàn tất. Start nằm đúng trên trục ngang của goal thì không suy +được phía nào và plan bị từ chối. ## Tham số cấu hình -File mặc định: `config/dock_global_params.yaml`. +File mặc định đi kèm gói: `config/dock_global_params.yaml`. Cây đang chạy nằm ở +`move_base2/config/runtime/` và `pnkx_nav_core/config/`. -| Tham số | Mặc định | Đơn vị | Mô tả | -|---|---:|---|---| -| `kinematics/front_axle_frame` | `steer_link` | frame | Frame tâm trục lái | -| `kinematics/rear_axle_frame` | `base_link` | frame | Frame tâm trục sau/reference | -| `kinematics/max_steering_angle` | `0.50` | rad | Góc lái bicycle lớn nhất khi robot đang chạy | -| `maneuver/minimum_forward_distance` | `0.25` | m | Đoạn tiến tối thiểu trước cusp | -| `maneuver/maximum_forward_extension` | `3.0` | m | Độ mở rộng cusp tối đa tính từ start | -| `terminal/reverse_distance_padding` | `0.0` | m | Khoảng lùi thẳng cộng thêm ngoài robot/dock extent | -| `sampling/path_point_spacing` | `0.05` | m | Khoảng cách lấy mẫu mục tiêu | +| Tham số | Mặc định | Đơn vị | Model | Mô tả | +|---|---:|---|---|---| +| `kinematics/model` | `ackermann` | — | cả hai | `ackermann` \| `differential` | +| `kinematics/front_axle_frame` | `steer_link` | frame | ackermann | Frame tâm trục lái | +| `kinematics/rear_axle_frame` | `base_link` | frame | ackermann | Frame tâm trục sau | +| `kinematics/max_steering_angle` | `0.50` | rad | ackermann | Góc lái bicycle lớn nhất | +| `kinematics/minimum_turning_radius` | `0.0` | m | differential | 0 = xoay tại chỗ được | +| `maneuver/minimum_forward_distance` | `0.25` | m | cả hai | Đoạn dẫn tối thiểu trước cusp | +| `maneuver/maximum_forward_extension` | `3.0` | m | cả hai | Trần `cusp_extension`; vượt thì LOẠI kiểu 2 | +| `maneuver/direct_entry_min_curve_room` | `0.0` | m | cả hai | 0 = tắt kiểu 1 | +| `maneuver/pivot_fallback_extension` | `0.0` | m | cả hai | 0 = tắt kiểu 3 (bỏ qua khi `turns_in_place`) | +| `maneuver/pivot_safety_margin` | `0.15` | m | cả hai | Khe hở vòng quét khi xoay ↔ mặt dock | +| `terminal/reverse_distance_padding` | `0.0` | m | cả hai | Khoảng hở cộng thêm cho đoạn cuối | +| `terminal/straight_length` | `0.0` | m | cả hai | Độ dài đoạn thẳng cuối mong muốn | +| `sampling/path_point_spacing` | `0.05` | m | cả hai | Khoảng cách lấy mẫu | -`wheel_base` và `minimum_turning_radius` là giá trị dẫn xuất, không khai trong -YAML để tránh cấu hình mâu thuẫn. +`wheel_base` không khai trong YAML: nó là giá trị đo, để tránh cấu hình mâu thuẫn. -Điều kiện bắt buộc: +`footprint_dock` và `dock_anchor` cũng không khai ở đây — `move_base2` chọn theo +từng marker rồi rót vào namespace `DockPlanner` trước khi dựng plugin. +`dock_anchor: center` cộng nửa thân dock phía tiếp cận vào khoảng hở; +`dock_anchor: face` bỏ qua `footprint_dock` hoàn toàn. -- Hai axle frame khác nhau và không rỗng. -- `0 < max_steering_angle < pi/2`. -- `0 < minimum_forward_distance <= maximum_forward_extension`. -- `reverse_distance_padding >= 0`. -- `0 < path_point_spacing <= 1.0`. +Điều kiện validate: + +- `ackermann`: hai axle frame khác nhau và không rỗng, `0 < max_steering_angle < π/2`, + `wheel_base >= 0`. +- `differential`: `minimum_turning_radius >= 0`. +- Chung: `0 < minimum_forward_distance <= maximum_forward_extension`, + `direct_entry_min_curve_room >= 0`, `pivot_fallback_extension >= 0`, + `pivot_safety_margin >= 0`, `reverse_distance_padding >= 0`, + `straight_length >= 0`, `0 < path_point_spacing <= 1.0`. `max_steering_angle` phải là góc lái tương đương theo bicycle model, không phải -servo tick hay góc pivot đặc biệt tại vận tốc bằng không. Giá trị mặc định chỉ -là điểm bắt đầu cho APM; phải thay bằng số đo trên robot thật. +servo tick hay góc pivot tại vận tốc bằng không. Giá trị mặc định chỉ là điểm +bắt đầu; phải thay bằng số đo trên robot thật. + +## Log + +Mỗi lần lập plan in một dòng đủ để biết vì sao kiểu đó được chọn: + +```text +[dock_calc] Generated rear-edge dock path: selected_maneuver=straight_pivot_straight, +model=ackermann, poses=70 (approach=23, terminal=48), terminal straight 2.348 m driven +reverse, min_radius=2.4287 m, start=(long=2.800 m, lateral=0.600 m in approach frame), +curve_room=1.950 m, cusp_extension=1.598 m (pivot threshold=1.000 m), arc_radius=inf, +pivot_vertex=2.348 m, pivot_angle=-0.9263 rad, circumscribed_radius=1.698 m. +``` + +Kiểu bị loại in ở mức info, không phải error — bị loại là chuyện bình thường vì +còn kiểu khác. Chỉ khi hết kiểu mới có một dòng error liệt kê đủ số đo. + +Dòng log footprint in mỗi lần lập plan là cố ý: footprint robot do host đẩy vào +lúc chạy và âm thầm rơi về bản trong costmap YAML nếu host không đẩy. Hai bản +chênh nhau hơn một mét ở đầu xe là chuyện có thật, và chênh đó dịch điểm xoay +đúng bằng ngần ấy. ## Phạm vi an toàn hiện tại -`check_free_space`, `cost_threshold`, `allow_unknown` và -`calib_safety_distance` không được đọc. Cung tiến có thể quét một vùng lớn phía -trước và bên hông robot; chưa được phép coi path hợp lệ về collision chỉ vì core -hình học trả thành công. +`check_free_space`, `cost_threshold`, `allow_unknown` và `calib_safety_distance` +**không được đọc**. Path hợp lệ về hình học **không** đồng nghĩa với không va +chạm: + +- `pivot_safety_margin` chỉ chặn phía **gần dock** — bảo đảm vòng quét khi xoay + không chạm mặt dock. Nó không biết gì về tường, kệ hay người bên cạnh. +- Không có ràng buộc nào về phía **xa dock**. Kiểu 3 không lấn thêm chỗ theo + thiết kế, nhưng kiểu 1 và 2 thì có, và không ai kiểm. +- Cung của kiểu 1 và 2 quét một vùng rộng ở hai bên hông robot. + +Đừng thêm khoá cấu hình cho những tính năng an toàn chưa hiện thực — YAML khai +một khoá không ai đọc thì nguy hiểm hơn là không khai. diff --git a/config/dock_global_params.yaml b/config/dock_global_params.yaml index 5c35968..e1d5e2d 100644 --- a/config/dock_global_params.yaml +++ b/config/dock_global_params.yaml @@ -6,9 +6,20 @@ # Cây config đang chạy nằm ở move_base2/config/runtime/ và pnkx_nav_core/config/. # Sửa tham số ở hai cây đó thì phải đồng bộ khoá (và tài liệu) về đây. # -# Hình dạng đường: một đoạn cua rời xa dock (lead-in), một điểm đổi chiều (cusp), -# rồi một đoạn THẲNG cuối trùng hướng yaw của goal. Đoạn cuối luôn thẳng để robot -# đã đạt đúng hướng trước khi chui vào dock — đi cong vào gầm trolley rất dễ va. +# Ba kiểu đường. Planner thử theo thứ tự và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào +# không dựng được thì rơi xuống kiểu kế tiếp, KHÔNG bao giờ biến thành lỗi: +# 1. direct_entry — một cung hội tụ vào trục goal rồi đi thẳng vào. Một chiều +# chạy, không dừng, không xoay. Rẻ nhất khi chạy. +# 2. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào. +# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra. +# 3. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường +# minh vào path (một khối pose cùng vị trí, yaw tăng dần), rồi một đoạn +# thẳng vào goal. Điểm xoay nằm GIỮA robot và dock nên KHÔNG lấn thêm một +# mét nào, đổi lại có thêm một lần dừng để xoay. +# Thứ tự ưu tiên giữa 2 và 3 do `kinematics/model` và `maneuver/*` quyết định — +# xem comment của từng khoá. +# Đoạn cuối của cả ba kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt +# đúng hướng trước khi chui vào dock — đi cong vào gầm trolley rất dễ va. # # Mép nào của robot áp vào dock được SUY RA theo từng lần lập plan, dựa vào phía # robot đang đứng so với goal. Không khai báo bằng tham số: @@ -26,42 +37,101 @@ DockPlanner: # Thư viện Boost.DLL chứa symbol export tên "DockPlanner". library_path: libdock_planner + # ══════════════════════════════════════════════════════════════════════════════ + # ĐỘNG HỌC — khoá nào có tác dụng phụ thuộc `model`. Khoá của model KIA được + # đọc vào nhưng KHÔNG dùng và KHÔNG kiểm tra, nên để lại giá trị cũ vô hại. + # + # khoá ackermann differential + # ───────────────────────────── ─────────── ──────────── + # front_axle_frame DÙNG bỏ qua + # rear_axle_frame DÙNG bỏ qua + # max_steering_angle DÙNG bỏ qua + # minimum_turning_radius bỏ qua DÙNG + # ══════════════════════════════════════════════════════════════════════════════ kinematics: - # Hai frame trục bánh, dùng để ĐO wheel_base từ TF. Phải trùng với cặp frame - # StanleyControl đang dùng, nếu lệch thì bán kính cua tính ra sai. + # Mô hình dẫn động. Quyết định planner ĐO hay ĐỌC bán kính cua nhỏ nhất, và + # robot có được xoay tại chỗ hay không. + # ackermann — có trục lái. R_min được ĐO: wheel_base lấy từ TF hai frame + # trục bánh, chia cho tan(max_steering_angle). Robot không + # đổi được hướng nếu không di chuyển. + # differential — hai bánh chủ động độc lập. KHÔNG có trục lái nên KHÔNG tra + # TF trục bánh. R_min ĐỌC thẳng từ minimum_turning_radius. + # ► Chỉnh: để nhầm `ackermann` cho robot vi sai thì plugin KHÔNG NẠP ĐƯỢC — + # nó đi tra frame `steer_link` mà robot vi sai không hề có. + model: ackermann + + # ── chỉ có tác dụng khi model: ackermann ───────────────────────────────────── + + # Hai frame trục bánh, dùng để ĐO wheel_base từ TF. Phải trùng cặp frame + # StanleyControl đang dùng, lệch là bán kính cua tính ra sai. front_axle_frame: "steer_link" rear_axle_frame: "base_link" - # [rad] Góc lái lớn nhất của mô hình xe đạp tương đương khi chạy đoạn cua. - # PHẢI đo trên robot thật rồi ghi đè giá trị mặc định này. Đây KHÔNG phải - # tick servo, KHÔNG phải góc vô lăng, cũng KHÔNG phải góc pivot tại chỗ. - # Quyết định bán kính cua nhỏ nhất: R_min = wheel_base / tan(góc này). - # Khai lớn hơn thực tế -> planner sinh cung robot bám không nổi, robot lệch - # path. Khai nhỏ hơn thực tế -> đường vòng rộng, tốn không gian. - max_steering_angle: 0.50 + # [rad] Góc lái lớn nhất của mô hình xe đạp tương đương khi đang chạy. + # PHẢI đo trên robot thật. KHÔNG phải tick servo, KHÔNG phải góc vô lăng, + # cũng KHÔNG phải góc pivot tại chỗ. + # R_min = wheel_base / tan(góc này). + # Khai lớn hơn thực tế -> sinh cung robot bám không nổi, robot lệch path. + # Khai nhỏ hơn thực tế -> đường vòng rộng, tốn không gian. + max_steering_angle: 0.5 + + # ── chỉ có tác dụng khi model: differential ────────────────────────────────── + + # [m] Bán kính cua nhỏ nhất, khai trực tiếp vì robot vi sai không có góc lái. + # 0 — CHO PHÉP xoay tại chỗ. Đây là giá trị bình thường của robot vi sai, + # và nó bật kiểu đường 3 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu + # này không lấn thêm một mét nào về phía xa dock. + # > 0 — CẤM xoay tại chỗ (ví dụ đang chở tải cao, xoay tại chỗ dễ đổ). + # Planner quay về dùng cung y như ackermann, bán kính tối thiểu đúng + # bằng số này, và kiểu 3 chỉ còn bật qua pivot_fallback_extension. + minimum_turning_radius: 0.0 maneuver: - # [m] Cusp được đặt cách điểm xuất phát ít nhất khoảng này, đo theo hướng RỜI - # XA dock. Bảo đảm luôn có một đoạn lead-in thật trước khi đổi chiều, thay vì - # cusp trùng ngay vị trí robot. + # [m] Cusp đặt cách điểm xuất phát ít nhất khoảng này, đo theo hướng RỜI XA + # dock. Bảo đảm luôn có đoạn lead-in thật trước khi đổi chiều, thay vì cusp + # trùng ngay vị trí robot. minimum_forward_distance: 0.25 - # [m] Từ chối lập plan nếu cusp phải nằm xa hơn khoảng này so với điểm xuất - # phát để thoả ràng buộc bán kính cua và khoảng hở với dock. - # Tăng lên nếu robot đứng lệch nhiều mà vẫn muốn ra được plan; giảm xuống nếu - # muốn chặn sớm những manơ chiếm quá nhiều không gian. + # [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 2 bị + # LOẠI (không phải fail): planner chuyển sang kiểu khác, chỉ khi không kiểu + # nào dựng được mới trả lỗi. + # Tăng lên nếu robot đứng lệch nhiều mà vẫn muốn giữ đường có cusp; giảm + # xuống để đẩy sớm sang kiểu 3. maximum_forward_extension: 3.0 - # [m] Bật kiểu vào dock KHÔNG CÓ CUSP (một cung hội tụ vào trục goal rồi đi - # thẳng vào, giữ nguyên một chiều chạy) khi khoảng chỗ còn lại cho cung — - # tức khoảng cách dọc trục từ robot tới goal trừ đi độ dài đoạn thẳng cuối — - # vượt ngưỡng này. - # Bán kính cung VẪN được kiểm với giới hạn Ackermann. Trượt bất kỳ phép kiểm - # nào thì quay về đường có cusp, nên tham số này chỉ có thể BỚT một lần đổi - # chiều, không bao giờ thêm. - # Mặc định 0 = tắt hẳn, luôn lập đường có cusp. Bật khi đã chạy thử. + # [m] Bật kiểu 1 (direct_entry — một cung hội tụ vào trục goal rồi đi thẳng + # vào, giữ nguyên một chiều chạy) khi khoảng chỗ còn lại cho cung — khoảng + # cách dọc trục từ robot tới goal trừ độ dài đoạn thẳng cuối — vượt số này. + # Bán kính cung VẪN bị kiểm với R_min. Trượt phép kiểm nào thì rơi xuống + # kiểu sau, nên khoá này chỉ có thể BỚT một lần đổi chiều, không bao giờ thêm. + # 0 = tắt hẳn kiểu 1. direct_entry_min_curve_room: 0.0 + # [m] Chuyển từ kiểu 2 (cusp) sang kiểu 3 (thẳng + xoay + thẳng) khi cusp bắt + # robot chạy RA XA dock thêm quá số này, đo từ chỗ robot ĐANG ĐỨNG. + # So sánh cố ý là TƯƠNG ĐỐI. Lấy một con số tuyệt đối kiểu "chiều sâu lối đi" + # rồi so với vị trí robot là tính cả chỗ robot đang đứng vào phần "cần thêm", + # và mọi manơ xuất phát từ khoảng cách bình thường đều bị loại sạch. + # 0 — TẮT hẳn kiểu 3 (hành vi cũ, luôn lập đường có cusp). + # nhỏ hơn — chuyển sang xoay tại chỗ sớm hơn: tiết kiệm lối đi, thêm 1 lần dừng. + # lớn hơn — ưu tiên cusp: chạy mượt hơn, chiếm nhiều lối đi hơn. + # ⚠ Chỉ khai > 0 khi CHẮC robot xoay tại chỗ được quanh base_link. + # KHÔNG có tác dụng khi model=differential VÀ minimum_turning_radius=0 — lúc + # đó kiểu 3 đã là kiểu chính rồi, không cần ngưỡng nào bật nó. + pivot_fallback_extension: 0.0 + + # [m] Khoảng hở giữa vòng tròn thân robot quét khi xoay tại chỗ và mặt gần + # của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 3 được dùng. + # Xoay tại chỗ quay MỌI điểm footprint quanh base_link, nên kích thước phải + # tính là BÁN KÍNH NGOẠI TIẾP, luôn lớn hơn phần nhô mép dùng cho đoạn thẳng + # cuối. Ví dụ footprint 1.65/0.35 x ±0.40: ngoại tiếp 1.698 m trong khi mép + # sau chỉ 0.35 m — chênh 1.35 m. + # Điểm xoay đặt tại: max(độ dài đoạn thẳng cuối, ngoại tiếp + nửa thân dock + # phía tiếp cận + số này). + # Tăng lên: điểm xoay lùi ra xa dock hơn, an toàn hơn. Tăng quá thì điểm xoay + # vượt qua chỗ robot đứng, kiểu 3 bị loại và planner quay về cusp. + pivot_safety_margin: 0.15 + terminal: # [m] Khoảng hở CỘNG THÊM cho đoạn thẳng cuối, ngoài phần thân robot nhô ra ở # mép áp dock (rear_extent khi đoạn cuối đi lùi, front_extent khi đi tiến) và, @@ -74,7 +144,7 @@ DockPlanner: # là chỉ dùng khoảng hở tối thiểu. # Tăng lên thì robot có quãng thẳng dài hơn để chỉnh hết sai số hướng trước # khi vào dock, ĐỔI LẠI ăn vào chỗ dành cho cung, nên đặt lớn quá sẽ đẩy plan - # quay về kiểu có cusp. + # sang kiểu có cusp hoặc kiểu xoay tại chỗ. straight_length: 0.0 sampling: diff --git a/include/dock_planner/dock_calc.h b/include/dock_planner/dock_calc.h index cb7c313..247ea6b 100644 --- a/include/dock_planner/dock_calc.h +++ b/include/dock_planner/dock_calc.h @@ -20,6 +20,11 @@ struct RobotGeometry // bounding-box center — e.g. a forklift whose forks extend past base_link. double front_extent = 0.0; // [m], origin to the +X edge double rear_extent = 0.0; // [m], origin to the -X edge + // Farthest footprint vertex from the frame origin. This is the radius the + // body sweeps when it turns on the spot, so it -- not front_extent or + // rear_extent -- is what has to clear the dock at a pivot vertex. It is + // always the larger of the two for any footprint that has width. + double circumscribed_radius = 0.0; // [m] }; /** Pure docking-path geometry. Collision checking is intentionally out of scope. */ @@ -64,10 +69,53 @@ private: const robot_geometry_msgs::Pose& goal, double approach_yaw, double heading_offset, double start_longitudinal, - double start_lateral, double minimum_cusp_distance, + double start_lateral, double cusp_distance, double minimum_turning_radius, std::vector& path, - double& cusp_distance, double& curve_radius) const; + double& curve_radius) const; + + /** + * @brief Where the cusp has to sit, without sampling anything. + * + * Split out of sampleLeadIn so the caller can compare the cost of the + * single-cusp shape against the other shapes BEFORE committing to it. + * @p extension is how much further away from the dock the cusp pushes the + * robot, measured from where it already stands, and is the quantity the + * pivot fallback threshold is compared against. + * + * Returns false when that extension leaves (0, maximum_forward_extension], + * which is a normal outcome: the caller then plans another shape. + */ + bool cuspPlacement(double start_longitudinal, double start_lateral, + double minimum_cusp_distance, + double minimum_turning_radius, + double& cusp_distance, double& extension) const; + + /** + * @brief Straight leg to a vertex on the goal axis, then an explicit + * on-the-spot rotation onto the terminal heading. + * + * The vertex sits BETWEEN the robot and the dock, so this shape never + * claims space further from the dock than the robot already occupies -- + * that is the whole reason it exists. @p vertex_distance must already + * include the clearance the swept circle needs; see makePlanMoveToDock. + * + * The rotation is written into the path as a block of poses that share a + * position and step in yaw, because an Ackermann or differential base + * cannot change heading instantly at a bare polyline vertex. The block is + * emitted with push_back rather than appendUnique, which would drop every + * pose in it for not moving. + * + * Returns false when the vertex is not ahead of the robot or the leg is too + * short to sample; the caller then plans another shape. + */ + bool samplePivotPolyline(const robot_geometry_msgs::Pose& start, + const robot_geometry_msgs::Pose& goal, + double approach_yaw, double heading_offset, + double start_longitudinal, double start_lateral, + double vertex_distance, + std::vector& path, + double& pivot_angle) const; /** * @brief No-cusp entry: one arc that converges onto the goal axis, then the diff --git a/include/dock_planner/dock_planner_config.h b/include/dock_planner/dock_planner_config.h index 26610b6..db627b0 100644 --- a/include/dock_planner/dock_planner_config.h +++ b/include/dock_planner/dock_planner_config.h @@ -25,6 +25,22 @@ enum class DockAnchor kFace, }; +/** + * @brief Drive kinematics the path geometry has to respect. + * + * kAckermann: steered front axle. The minimum turning radius is measured, not + * declared -- wheel_base comes from the axle TF and is combined with + * max_steering_angle. The robot cannot change heading without moving. + * kDifferential: independently driven wheels. There is no steered axle and no + * axle TF to look up, so the minimum turning radius is declared directly and is + * normally 0, meaning the robot can turn on the spot. + */ +enum class KinematicModel +{ + kAckermann, + kDifferential, +}; + /** * @brief Runtime parameters that materially affect the docking path geometry. * @@ -33,11 +49,28 @@ enum class DockAnchor */ struct DockPlannerConfig { + /** + * Default kAckermann so an existing YAML that never heard of this key keeps + * behaving exactly as before. + */ + KinematicModel kinematic_model = KinematicModel::kAckermann; + + // Ackermann only. A differential base has no steered axle, so these are + // neither read nor validated when kinematic_model is kDifferential. std::string front_axle_frame = "steer_link"; std::string rear_axle_frame = "base_link"; double max_steering_angle = 0.50; // [rad], equivalent bicycle steering angle double wheel_base = 0.0; // [m], resolved from axle TF by DockPlanner + /** + * [m] Differential only. 0 means the base may turn on the spot, which is the + * normal case and unlocks the straight-pivot-straight shape as the primary + * maneuver. Set it above 0 to forbid on-the-spot turns -- for instance while + * carrying a tall load -- and the planner falls back to the same arc-based + * shapes an Ackermann base uses. + */ + double minimum_turning_radius = 0.0; + double reverse_distance_padding = 0.0; // [m], additional cusp clearance from dock double minimum_forward_distance = 0.25; // [m], guarantees a forward leg before reversing double maximum_forward_extension = 3.0; // [m], rejects unexpectedly large maneuvers @@ -59,6 +92,29 @@ struct DockPlannerConfig */ double direct_entry_min_curve_room = 0.0; + /** + * [m] Ackermann only. Switch from the single-cusp shape to + * straight-pivot-straight once the cusp forces the robot this much further + * AWAY from the dock than where it already stands. The comparison is + * deliberately relative to the robot's current standoff: an absolute aisle + * measurement counts space the robot already occupies and rejects every + * maneuver planned from a normal approach distance. + * 0 disables the shape entirely and always plans a cusp. + * Ignored when kinematic_model is kDifferential, where the pivot shape is + * the primary maneuver rather than a fallback. + */ + double pivot_fallback_extension = 0.0; + + /** + * [m] Clearance kept between the circle the body sweeps while it turns on + * the spot and the near face of the dock. Turning on the spot rotates every + * footprint point about base_link, so the relevant robot dimension is the + * circumscribed radius, which is always larger than the mating extent the + * straight terminal is sized from. This margin pushes the pivot vertex that + * much further away from the dock. + */ + double pivot_safety_margin = 0.15; + /** * Per-marker key copied down by move_base2 (like footprint_dock). * Default kCenter keeps the legacy formula for existing profiles. @@ -71,8 +127,19 @@ struct DockPlannerConfig /** Validate values supplied directly by tests or another non-YAML adapter. */ bool validate(std::string& error) const; - /** Radius at the rear-axle reference point for the bicycle model. */ + /** + * Smallest radius the path geometry may use, in metres. + * Ackermann: derived from the measured wheel base and the steering limit. + * Differential: the declared value, 0 when turning on the spot is allowed. + * NaN when the model's inputs are unusable. + */ double minimumTurningRadius() const; + + /** True when the model needs the axle TF resolved before planning. */ + bool requiresAxleTf() const + { + return kinematic_model == KinematicModel::kAckermann; + } }; } // namespace dock_planner diff --git a/src/dock_calc.cpp b/src/dock_calc.cpp index bafed4c..346366c 100644 --- a/src/dock_calc.cpp +++ b/src/dock_calc.cpp @@ -15,6 +15,42 @@ namespace constexpr double kEpsilon = 1e-9; +/** + * Poses appended after the vertex to describe the on-the-spot rotation. + * StanleyControl::planDivision only splits a rotation out of the plan after + * three consecutive samples that share a position, so the block needs at least + * four poses counting the vertex itself; six keeps margin for any consumer that + * counts differently. + */ +constexpr int kPivotBlockSteps = 6; + +/** Below this the robot is already on the terminal heading. [rad] */ +constexpr double kNegligiblePivot = 1e-6; + +/** Path shapes the planner can produce, in no particular order. */ +enum class Shape +{ + kNone, + kDirectEntry, + kPivot, + kCusp, +}; + +const char* shapeName(Shape shape) +{ + switch (shape) + { + case Shape::kDirectEntry: + return "direct_entry"; + case Shape::kPivot: + return "straight_pivot_straight"; + case Shape::kCusp: + return "single_cusp"; + default: + return "none"; + } +} + bool finitePoint(const robot_geometry_msgs::Point& point) { return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z); @@ -105,6 +141,7 @@ RobotGeometry DockCalc::computeGeometry( double max_x = std::numeric_limits::lowest(); double min_y = std::numeric_limits::max(); double max_y = std::numeric_limits::lowest(); + double max_radius = 0.0; for (const auto& point : footprint) { @@ -116,6 +153,10 @@ RobotGeometry DockCalc::computeGeometry( max_x = std::max(max_x, point.x); min_y = std::min(min_y, point.y); max_y = std::max(max_y, point.y); + // Distance is convex, so its maximum over a polygon is always attained + // at a vertex -- true even for a concave footprint. Scanning the + // vertices is therefore exact, not an approximation. + max_radius = std::max(max_radius, std::hypot(point.x, point.y)); } RobotGeometry geometry; @@ -123,6 +164,7 @@ RobotGeometry DockCalc::computeGeometry( geometry.width = max_y - min_y; geometry.front_extent = max_x; geometry.rear_extent = -min_x; + geometry.circumscribed_radius = max_radius; return geometry; } @@ -142,44 +184,20 @@ bool DockCalc::sampleLeadIn( double heading_offset, double start_longitudinal, double start_lateral, - double minimum_cusp_distance, + double cusp_distance, double minimum_turning_radius, std::vector& path, - double& cusp_distance, double& curve_radius) const { path.clear(); - cusp_distance = std::numeric_limits::quiet_NaN(); curve_radius = std::numeric_limits::infinity(); const double lateral = std::fabs(start_lateral); - double forward_extension = config_.minimum_forward_distance; - - // A circle tangent to the dock axis at the cusp and passing through the - // start has R = (dx^2 + lateral^2) / (2*lateral). Select the smallest dx - // that guarantees R >= the Ackermann limit. If lateral >= 2*R_min, the - // lateral offset alone already makes the circle conservative enough. - if (lateral > kEpsilon) - { - const double radicand = 2.0 * minimum_turning_radius * lateral - - lateral * lateral; - if (radicand > 0.0) - { - forward_extension = std::max(forward_extension, std::sqrt(radicand)); - } - } - - cusp_distance = std::max(minimum_cusp_distance, - start_longitudinal + forward_extension); + // Where the cusp goes is decided by cuspPlacement() before any shape is + // sampled, so this function only has to honour it. const double actual_extension = cusp_distance - start_longitudinal; - if (!std::isfinite(actual_extension) || actual_extension <= kEpsilon || - actual_extension > config_.maximum_forward_extension + kEpsilon) + if (!std::isfinite(actual_extension) || actual_extension <= kEpsilon) { - robot::log_error( - "[dock_calc] Lead-in cusp extension %.3f m is outside (0, %.3f] m " - "(start_longitudinal=%.3f m, minimum_cusp=%.3f m).\n", - actual_extension, config_.maximum_forward_extension, - start_longitudinal, minimum_cusp_distance); return false; } @@ -267,6 +285,153 @@ bool DockCalc::sampleLeadIn( return true; } +bool DockCalc::cuspPlacement(double start_longitudinal, double start_lateral, + double minimum_cusp_distance, + double minimum_turning_radius, + double& cusp_distance, double& extension) const +{ + cusp_distance = std::numeric_limits::quiet_NaN(); + extension = std::numeric_limits::quiet_NaN(); + + const double lateral = std::fabs(start_lateral); + double forward_extension = config_.minimum_forward_distance; + + // A circle tangent to the dock axis at the cusp and passing through the + // start has R = (dx^2 + lateral^2) / (2*lateral). Select the smallest dx + // that guarantees R >= the steering limit. If lateral >= 2*R_min, the + // lateral offset alone already makes the circle conservative enough, and a + // differential base with R_min = 0 never needs any extra dx at all. + if (lateral > kEpsilon) + { + const double radicand = 2.0 * minimum_turning_radius * lateral - + lateral * lateral; + if (radicand > 0.0) + { + forward_extension = std::max(forward_extension, std::sqrt(radicand)); + } + } + + const double placed = std::max(minimum_cusp_distance, + start_longitudinal + forward_extension); + const double actual_extension = placed - start_longitudinal; + if (!std::isfinite(actual_extension) || actual_extension <= kEpsilon || + actual_extension > config_.maximum_forward_extension + kEpsilon) + { + // Informational, not an error: another shape may still be planned. The + // caller logs an error only if every shape is exhausted. + robot::log_info( + "[dock_calc] Single-cusp extension %.3f m is outside (0, %.3f] m " + "(start_longitudinal=%.3f m, minimum_cusp=%.3f m); trying another shape.\n", + actual_extension, config_.maximum_forward_extension, + start_longitudinal, minimum_cusp_distance); + return false; + } + + cusp_distance = placed; + extension = actual_extension; + return true; +} + +bool DockCalc::samplePivotPolyline( + const robot_geometry_msgs::Pose& start, + const robot_geometry_msgs::Pose& goal, + double approach_yaw, + double heading_offset, + double start_longitudinal, + double start_lateral, + double vertex_distance, + std::vector& path, + double& pivot_angle) const +{ + path.clear(); + pivot_angle = 0.0; + + // The vertex must lie between the robot and the dock. That is the property + // this shape is chosen for: it never reaches further from the dock than the + // robot already stands, so it costs no extra aisle depth at all. + if (!std::isfinite(vertex_distance) || + vertex_distance + kEpsilon >= start_longitudinal) + { + return false; + } + + const double leg_length = std::hypot(start_longitudinal - vertex_distance, + start_lateral); + if (!std::isfinite(leg_length) || + leg_length <= 2.0 * config_.path_point_spacing) + { + // Too short to sample into a usable leg; another shape fits better. + return false; + } + + // Body yaw the terminal is driven at, and therefore the yaw the rotation + // has to finish on. It equals goal_yaw on both docking sides, because a + // front dock offsets approach_yaw and heading_offset by pi each. + const double terminal_yaw = normalizeAngle(approach_yaw + heading_offset); + + // Two ways to drive the first leg: nose-first along it, or in reverse. + // Taking the smaller pivot also selects the travel direction the terminal + // already uses, on either docking side, so the finished path keeps one + // travel direction from end to end and contains no cusp. + const double leg_course = std::atan2(-start_lateral, + vertex_distance - start_longitudinal); + const double forward_yaw = normalizeAngle(approach_yaw + leg_course); + const double reverse_yaw = normalizeAngle(forward_yaw + kPi); + const double forward_turn = normalizeAngle(terminal_yaw - forward_yaw); + const double reverse_turn = normalizeAngle(terminal_yaw - reverse_yaw); + const bool drive_forward = std::fabs(forward_turn) <= std::fabs(reverse_turn); + const double leg_yaw = drive_forward ? forward_yaw : reverse_yaw; + pivot_angle = drive_forward ? forward_turn : reverse_turn; + + const robot_geometry_msgs::Pose vertex = poseFromDockCoordinates( + goal, approach_yaw, vertex_distance, 0.0, leg_yaw); + + const int sample_count = std::max( + 1, static_cast(std::ceil(leg_length / config_.path_point_spacing))); + path.reserve(static_cast(sample_count + 1 + kPivotBlockSteps)); + for (int index = 0; index <= sample_count; ++index) + { + const double ratio = static_cast(index) / sample_count; + robot_geometry_msgs::Pose pose; + pose.position.x = start.position.x + ratio * (vertex.position.x - start.position.x); + pose.position.y = start.position.y + ratio * (vertex.position.y - start.position.y); + pose.position.z = start.position.z + ratio * (vertex.position.z - start.position.z); + pose.orientation = data_convert::createQuaternionMsgFromYaw(leg_yaw); + appendUnique(path, pose); + } + + if (path.size() < 2) + { + path.clear(); + return false; + } + path.front().position = start.position; + path.back() = vertex; + + if (std::fabs(pivot_angle) <= kNegligiblePivot) + { + // Already on the terminal heading: a block of identical poses would + // only make the controller stop for nothing. + pivot_angle = 0.0; + return true; + } + + // push_back, NOT appendUnique: these poses share a position by design and + // appendUnique exists to delete exactly that. Losing them would leave a + // bare polyline vertex, which no wheeled base can drive through -- heading + // cannot change instantaneously at a corner. + for (int index = 1; index <= kPivotBlockSteps; ++index) + { + const double ratio = static_cast(index) / + static_cast(kPivotBlockSteps); + robot_geometry_msgs::Pose pose = vertex; + pose.orientation = data_convert::createQuaternionMsgFromYaw( + normalizeAngle(leg_yaw + ratio * pivot_angle)); + path.push_back(pose); + } + return true; +} + bool DockCalc::sampleDirectEntry( const robot_geometry_msgs::Pose& start, const robot_geometry_msgs::Pose& goal, @@ -427,13 +592,17 @@ bool DockCalc::makePlanMoveToDock( return false; } + // 0 is legal for a differential base: it is what allows an on-the-spot + // rotation to appear in the path. Only negative or non-finite is an error. const double minimum_turning_radius = config_.minimumTurningRadius(); - if (!std::isfinite(minimum_turning_radius) || minimum_turning_radius <= kEpsilon) + if (!std::isfinite(minimum_turning_radius) || minimum_turning_radius < 0.0) { robot::log_error( - "[dock_calc] Kinematics are unresolved: wheel_base=%.6f m, " - "max_steering_angle=%.6f rad.\n", - config_.wheel_base, config_.max_steering_angle); + "[dock_calc] Kinematics are unresolved: model=%s, wheel_base=%.6f m, " + "max_steering_angle=%.6f rad, minimum_turning_radius=%.6f m.\n", + config_.requiresAxleTf() ? "ackermann" : "differential", + config_.wheel_base, config_.max_steering_angle, + config_.minimum_turning_radius); return false; } if (!isFinitePose(start.pose) || !isFinitePose(goal.pose)) @@ -568,44 +737,129 @@ bool DockCalc::makePlanMoveToDock( std::max(minimum_cusp_distance, config_.straight_length); const double curve_room = start_longitudinal - straight_distance; - std::vector approach_segment; - double cusp_distance = straight_distance; - double curve_radius = 0.0; - bool direct_entry = false; + const bool differential = + config_.kinematic_model == KinematicModel::kDifferential; - // Preferred shape when there is room for it: no direction change at all, so - // the controller never has to detect a cusp, and the robot converges onto the - // dock axis while still far from the dock. + // Vertex of the straight-pivot-straight shape. Turning on the spot rotates + // every footprint point about base_link, so the body sweeps its + // circumscribed radius here, which is always more than the mating extent + // the straight terminal is sized from. Sizing the vertex from the terminal + // instead would drive a corner of the robot into the dock. + const double pivot_vertex_distance = std::max( + straight_distance, + robot.circumscribed_radius + dock_extent + config_.pivot_safety_margin); + + // The pivot shape needs a base that can change heading without moving. A + // differential base can exactly when its declared turning radius is 0; a + // non-zero radius there means on-the-spot turns were forbidden on purpose, + // for instance while carrying a tall load. Any other base pivots only if the + // integrator says so, which is what a non-zero threshold means. + const bool turns_in_place = differential && minimum_turning_radius <= kEpsilon; + const bool pivot_enabled = + turns_in_place || config_.pivot_fallback_extension > 0.0; + + double cusp_distance = straight_distance; + double cusp_extension = std::numeric_limits::quiet_NaN(); + const bool cusp_reachable = + cuspPlacement(start_longitudinal, start_lateral, minimum_cusp_distance, + minimum_turning_radius, cusp_distance, cusp_extension); + + // On a differential base the pivot shape is the primary maneuver rather + // than a fallback: it costs no extra aisle and needs no arc. On an + // Ackermann base it is preferred once the cusp would push the robot further + // away from the dock than the threshold, or when no cusp can be placed at + // all -- returning no path there would be strictly worse than returning one + // with an extra stop. + const bool prefer_pivot = + pivot_enabled && + (turns_in_place || !cusp_reachable || + cusp_extension > config_.pivot_fallback_extension); + + Shape order[3]; + int order_size = 0; if (config_.direct_entry_min_curve_room > 0.0 && curve_room > config_.direct_entry_min_curve_room) { - direct_entry = sampleDirectEntry(start.pose, goal.pose, approach_yaw, - heading_offset, start_longitudinal, - start_lateral, straight_distance, - minimum_turning_radius, approach_segment, - curve_radius); - if (!direct_entry) + order[order_size++] = Shape::kDirectEntry; + } + if (prefer_pivot) + { + order[order_size++] = Shape::kPivot; + order[order_size++] = Shape::kCusp; + } + else + { + order[order_size++] = Shape::kCusp; + if (pivot_enabled) { - approach_segment.clear(); - const double lateral = std::fabs(start_lateral); - const double radicand = 2.0 * minimum_turning_radius * lateral - - lateral * lateral; - robot::log_info( - "[dock_calc] Direct entry does not fit (curve room=%.3f m, lateral=%.3f m " - "needs >= %.3f m at min_radius=%.3f m); planning the single-cusp " - "maneuver instead.\n", - curve_room, start_lateral, - radicand > 0.0 ? std::sqrt(radicand) : 0.0, minimum_turning_radius); + order[order_size++] = Shape::kPivot; } } - if (!direct_entry && - !sampleLeadIn(start.pose, goal.pose, approach_yaw, heading_offset, - start_longitudinal, start_lateral, - straight_distance, minimum_turning_radius, - approach_segment, cusp_distance, curve_radius)) + std::vector approach_segment; + Shape selected = Shape::kNone; + double curve_radius = std::numeric_limits::infinity(); + double pivot_angle = 0.0; + + // Each candidate falls through to the next when it cannot be built, so + // adding a shape can never introduce a new way to fail. That was the defect + // in the aisle-depth gate this ladder replaced: it rejected shapes without + // ever offering a cheaper one. + for (int index = 0; index < order_size && selected == Shape::kNone; ++index) { - robot::log_error("[dock_calc] Failed to generate the lead-in segment.\n"); + approach_segment.clear(); + switch (order[index]) + { + case Shape::kDirectEntry: + if (sampleDirectEntry(start.pose, goal.pose, approach_yaw, + heading_offset, start_longitudinal, + start_lateral, straight_distance, + minimum_turning_radius, approach_segment, + curve_radius)) + { + selected = Shape::kDirectEntry; + } + break; + + case Shape::kPivot: + if (samplePivotPolyline(start.pose, goal.pose, approach_yaw, + heading_offset, start_longitudinal, + start_lateral, pivot_vertex_distance, + approach_segment, pivot_angle)) + { + selected = Shape::kPivot; + } + break; + + case Shape::kCusp: + if (cusp_reachable && + sampleLeadIn(start.pose, goal.pose, approach_yaw, heading_offset, + start_longitudinal, start_lateral, cusp_distance, + minimum_turning_radius, approach_segment, + curve_radius)) + { + selected = Shape::kCusp; + } + break; + + default: + break; + } + } + + if (selected == Shape::kNone || approach_segment.empty()) + { + robot::log_error( + "[dock_calc] No docking maneuver could be planned: model=%s, " + "start=(long=%.3f m, lateral=%.3f m in approach frame), " + "min_radius=%.3f m, straight_distance=%.3f m, " + "cusp_reachable=%s (extension=%.3f m, max=%.3f m), " + "pivot_enabled=%s (vertex=%.3f m, circumscribed=%.3f m).\n", + differential ? "differential" : "ackermann", + start_longitudinal, start_lateral, minimum_turning_radius, + straight_distance, cusp_reachable ? "yes" : "no", cusp_extension, + config_.maximum_forward_extension, pivot_enabled ? "yes" : "no", + pivot_vertex_distance, robot.circumscribed_radius); return false; } @@ -617,14 +871,22 @@ bool DockCalc::makePlanMoveToDock( return false; } + // The approach segment is copied verbatim instead of through appendUnique: + // the rotation block is a run of poses that deliberately share a position, + // and appendUnique exists to delete exactly that. Only the junction between + // the two segments is deduplicated, which is all appendUnique ever removed + // here for the arc-based shapes. plan.reserve(approach_segment.size() + terminal_segment.size()); - for (const auto& pose : approach_segment) - { - appendUnique(plan, pose); - } + plan.insert(plan.end(), approach_segment.begin(), approach_segment.end()); for (const auto& pose : terminal_segment) { - appendUnique(plan, pose); + if (!plan.empty() && + std::hypot(plan.back().position.x - pose.position.x, + plan.back().position.y - pose.position.y) <= kEpsilon) + { + continue; + } + plan.push_back(pose); } if (plan.size() < 3) @@ -635,20 +897,21 @@ bool DockCalc::makePlanMoveToDock( plan.front().position = start.pose.position; plan.back() = goal.pose; + const double terminal_length = distance(approach_segment.back(), goal.pose); robot::log_info( - "[dock_calc] Generated %s-edge %s dock path: poses=%zu, approach=%zu (%s), " - "terminal=%zu (%s straight %.3f m), wheel_base=%.4f m, max_steer=%.4f rad, " + "[dock_calc] Generated %s-edge dock path: selected_maneuver=%s, model=%s, " + "poses=%zu (approach=%zu, terminal=%zu), terminal straight %.3f m driven %s, " "min_radius=%.4f m, start=(long=%.3f m, lateral=%.3f m in approach frame), " - "curve room=%.3f m, arc_radius=%.4f m.\n", - dock_with_front ? "front" : "rear", - direct_entry ? "direct (no cusp)" : "single-cusp", - plan.size(), approach_segment.size(), - direct_entry ? (dock_with_front ? "forward" : "reverse") - : (dock_with_front ? "reverse" : "forward"), - terminal_segment.size(), dock_with_front ? "forward" : "reverse", - cusp_distance, config_.wheel_base, config_.max_steering_angle, - minimum_turning_radius, start_longitudinal, start_lateral, - curve_room, curve_radius); + "curve_room=%.3f m, cusp_extension=%.3f m (pivot threshold=%.3f m), " + "arc_radius=%.4f m, pivot_vertex=%.3f m, pivot_angle=%.4f rad, " + "circumscribed_radius=%.3f m.\n", + dock_with_front ? "front" : "rear", shapeName(selected), + differential ? "differential" : "ackermann", + plan.size(), approach_segment.size(), terminal_segment.size(), + terminal_length, dock_with_front ? "forward" : "reverse", + minimum_turning_radius, start_longitudinal, start_lateral, curve_room, + cusp_extension, config_.pivot_fallback_extension, curve_radius, + pivot_vertex_distance, pivot_angle, robot.circumscribed_radius); return true; } diff --git a/src/dock_planner.cpp b/src/dock_planner.cpp index 235db09..b47af18 100644 --- a/src/dock_planner.cpp +++ b/src/dock_planner.cpp @@ -133,44 +133,59 @@ bool DockPlanner::initialize(std::string name, return false; } - try + if (loaded_config.requiresAxleTf()) { - // Match StanleyControl's axle-TF contract: lookup the front axle in - // the rear-axle frame, then use the planar translation norm. - const tf3::TransformStampedMsg axle_transform = - costmap_robot->getTfBuffer().lookupTransform( - loaded_config.rear_axle_frame, - loaded_config.front_axle_frame, - tf3::Time()); - loaded_config.wheel_base = std::hypot( - axle_transform.transform.translation.x, - axle_transform.transform.translation.y); - } - catch (const tf3::TransformException& exception) - { - robot::log_error( - "[dock_planner] Cannot resolve wheel base from TF %s -> %s: %s.\n", - loaded_config.front_axle_frame.c_str(), - loaded_config.rear_axle_frame.c_str(), exception.what()); - return false; - } + try + { + // Match StanleyControl's axle-TF contract: lookup the front axle in + // the rear-axle frame, then use the planar translation norm. + const tf3::TransformStampedMsg axle_transform = + costmap_robot->getTfBuffer().lookupTransform( + loaded_config.rear_axle_frame, + loaded_config.front_axle_frame, + tf3::Time()); + loaded_config.wheel_base = std::hypot( + axle_transform.transform.translation.x, + axle_transform.transform.translation.y); + } + catch (const tf3::TransformException& exception) + { + robot::log_error( + "[dock_planner] Cannot resolve wheel base from TF %s -> %s: %s.\n", + loaded_config.front_axle_frame.c_str(), + loaded_config.rear_axle_frame.c_str(), exception.what()); + return false; + } - if (!std::isfinite(loaded_config.wheel_base) || loaded_config.wheel_base <= 0.0) + if (!std::isfinite(loaded_config.wheel_base) || loaded_config.wheel_base <= 0.0) + { + robot::log_error( + "[dock_planner] Wheel base resolved to %.6f m from TF %s -> %s.\n", + loaded_config.wheel_base, loaded_config.front_axle_frame.c_str(), + loaded_config.rear_axle_frame.c_str()); + return false; + } + } + else { - robot::log_error( - "[dock_planner] Wheel base resolved to %.6f m from TF %s -> %s.\n", - loaded_config.wheel_base, loaded_config.front_axle_frame.c_str(), - loaded_config.rear_axle_frame.c_str()); - return false; + // A differential base publishes no steered-axle frame. Looking one up + // would throw and take the whole plugin down, so the turning radius + // comes from configuration instead and wheel_base stays meaningless. + loaded_config.wheel_base = 0.0; } const double minimum_turning_radius = loaded_config.minimumTurningRadius(); - if (!std::isfinite(minimum_turning_radius) || minimum_turning_radius <= 0.0) + // 0 is valid for a differential base: it means the robot may turn on the + // spot. Only a negative or non-finite radius is a configuration error. + if (!std::isfinite(minimum_turning_radius) || minimum_turning_radius < 0.0) { robot::log_error( - "[dock_planner] Cannot derive minimum turning radius from wheel_base=%.6f m " - "and max_steering_angle=%.6f rad.\n", - loaded_config.wheel_base, loaded_config.max_steering_angle); + "[dock_planner] Cannot derive minimum turning radius (model=%s, " + "wheel_base=%.6f m, max_steering_angle=%.6f rad, " + "minimum_turning_radius=%.6f m).\n", + loaded_config.requiresAxleTf() ? "ackermann" : "differential", + loaded_config.wheel_base, loaded_config.max_steering_angle, + loaded_config.minimum_turning_radius); return false; } @@ -207,12 +222,16 @@ bool DockPlanner::initialize(std::string name, initialized_ = true; robot::log_info( - "[dock_planner] Initialized single-cusp dock maneuver (docking edge is " - "derived per plan from the side the robot stands on): TF %s -> %s, " - "wheel_base=%.4f m, max_steering_angle=%.4f rad, minimum_turning_radius=%.4f m.\n", - loaded_config.front_axle_frame.c_str(), loaded_config.rear_axle_frame.c_str(), + "[dock_planner] Initialized dock maneuver (docking edge is derived per plan " + "from the side the robot stands on): model=%s, TF %s -> %s, wheel_base=%.4f m, " + "max_steering_angle=%.4f rad, minimum_turning_radius=%.4f m, " + "pivot_fallback_extension=%.3f m, pivot_safety_margin=%.3f m.\n", + loaded_config.requiresAxleTf() ? "ackermann" : "differential", + loaded_config.requiresAxleTf() ? loaded_config.front_axle_frame.c_str() : "-", + loaded_config.requiresAxleTf() ? loaded_config.rear_axle_frame.c_str() : "-", loaded_config.wheel_base, loaded_config.max_steering_angle, - minimum_turning_radius); + minimum_turning_radius, loaded_config.pivot_fallback_extension, + loaded_config.pivot_safety_margin); return true; } diff --git a/src/dock_planner_config.cpp b/src/dock_planner_config.cpp index f551d61..62b9725 100644 --- a/src/dock_planner_config.cpp +++ b/src/dock_planner_config.cpp @@ -71,6 +71,35 @@ bool readDockAnchor(const robot::NodeHandle& nh, DockAnchor& anchor, std::string return false; } +bool readKinematicModel(const robot::NodeHandle& nh, KinematicModel& model, + std::string& error) +{ + if (!nh.hasParam("kinematics/model")) + { + return true; + } + + std::string parsed; + if (!nh.getParam("kinematics/model", parsed, std::string())) + { + error = "parameter 'kinematics/model' must be a string"; + return false; + } + if (parsed == "ackermann") + { + model = KinematicModel::kAckermann; + return true; + } + if (parsed == "differential") + { + model = KinematicModel::kDifferential; + return true; + } + error = "parameter 'kinematics/model' must be 'ackermann' or 'differential' (got '" + + parsed + "')"; + return false; +} + bool requireFinite(const char* name, double value, std::string& error) { if (std::isfinite(value)) @@ -87,7 +116,14 @@ bool DockPlannerConfig::load(const robot::NodeHandle& nh, DockPlannerConfig& con std::string& error) { DockPlannerConfig loaded; - if (!readOptionalString(nh, "kinematics/front_axle_frame", + if (!readKinematicModel(nh, loaded.kinematic_model, error) || + !readOptionalDouble(nh, "kinematics/minimum_turning_radius", + loaded.minimum_turning_radius, error) || + !readOptionalDouble(nh, "maneuver/pivot_fallback_extension", + loaded.pivot_fallback_extension, error) || + !readOptionalDouble(nh, "maneuver/pivot_safety_margin", + loaded.pivot_safety_margin, error) || + !readOptionalString(nh, "kinematics/front_axle_frame", loaded.front_axle_frame, error) || !readOptionalString(nh, "kinematics/rear_axle_frame", loaded.rear_axle_frame, error) || @@ -133,6 +169,9 @@ bool DockPlannerConfig::validate(std::string& error) const } values[] = { {"kinematics/max_steering_angle", max_steering_angle}, {"kinematics/wheel_base", wheel_base}, + {"kinematics/minimum_turning_radius", minimum_turning_radius}, + {"maneuver/pivot_fallback_extension", pivot_fallback_extension}, + {"maneuver/pivot_safety_margin", pivot_safety_margin}, {"terminal/reverse_distance_padding", reverse_distance_padding}, {"terminal/straight_length", straight_length}, {"maneuver/minimum_forward_distance", minimum_forward_distance}, @@ -149,24 +188,36 @@ bool DockPlannerConfig::validate(std::string& error) const } } - if (front_axle_frame.empty() || rear_axle_frame.empty()) + // A differential base has no steered axle: validating axle frames or a + // steering limit there would reject a perfectly valid configuration and + // stop the plugin from loading at all. + if (kinematic_model == KinematicModel::kAckermann) { - error = "kinematics axle frame names must not be empty"; - return false; + if (front_axle_frame.empty() || rear_axle_frame.empty()) + { + error = "kinematics axle frame names must not be empty"; + return false; + } + if (front_axle_frame == rear_axle_frame) + { + error = "kinematics front_axle_frame and rear_axle_frame must be different"; + return false; + } + if (max_steering_angle <= 0.0 || max_steering_angle >= kPi / 2.0) + { + error = "parameter 'kinematics/max_steering_angle' must be in (0, pi/2) rad"; + return false; + } + if (wheel_base < 0.0) + { + error = "resolved kinematics wheel_base must be >= 0 m"; + return false; + } } - if (front_axle_frame == rear_axle_frame) + else if (minimum_turning_radius < 0.0) { - error = "kinematics front_axle_frame and rear_axle_frame must be different"; - return false; - } - if (max_steering_angle <= 0.0 || max_steering_angle >= kPi / 2.0) - { - error = "parameter 'kinematics/max_steering_angle' must be in (0, pi/2) rad"; - return false; - } - if (wheel_base < 0.0) - { - error = "resolved kinematics wheel_base must be >= 0 m"; + error = "parameter 'kinematics/minimum_turning_radius' must be >= 0 m " + "(0 allows turning on the spot)"; return false; } if (reverse_distance_padding < 0.0) @@ -195,6 +246,17 @@ bool DockPlannerConfig::validate(std::string& error) const error = "maneuver maximum_forward_extension must be >= minimum_forward_distance"; return false; } + if (pivot_fallback_extension < 0.0) + { + error = "parameter 'maneuver/pivot_fallback_extension' must be >= 0 m " + "(0 disables the straight-pivot-straight shape)"; + return false; + } + if (pivot_safety_margin < 0.0) + { + error = "parameter 'maneuver/pivot_safety_margin' must be >= 0 m"; + return false; + } if (path_point_spacing <= 0.0 || path_point_spacing > 1.0) { error = "parameter 'sampling/path_point_spacing' must be in (0, 1] m"; @@ -207,6 +269,16 @@ bool DockPlannerConfig::validate(std::string& error) const double DockPlannerConfig::minimumTurningRadius() const { + if (kinematic_model == KinematicModel::kDifferential) + { + // 0 is a legal answer here, not a failure: it is what lets the planner + // place an explicit on-the-spot rotation in the path. + if (!std::isfinite(minimum_turning_radius) || minimum_turning_radius < 0.0) + { + return std::numeric_limits::quiet_NaN(); + } + return minimum_turning_radius; + } if (!(wheel_base > 0.0) || !(max_steering_angle > 0.0) || !(max_steering_angle < kPi / 2.0)) { diff --git a/test/dock_planner_test.cpp b/test/dock_planner_test.cpp index cc7f641..5ae0915 100644 --- a/test/dock_planner_test.cpp +++ b/test/dock_planner_test.cpp @@ -202,12 +202,104 @@ void checkDirectEntry(const std::vector& path, CHECK(std::fabs(longitudinal(path[entry_index], goal)) >= straight_distance - 1e-6); } +/** + * @brief Assert the straight-pivot-straight contract: one straight leg, one + * explicit on-the-spot rotation, one straight terminal, one travel + * direction throughout. + * + * @param expected_vertex_distance where the rotation must happen, measured + * along the goal axis. It has to clear the swept circle, not just the + * mating extent, or a corner of the body hits the dock while it turns. + */ +void checkPivotPath(const std::vector& path, + const robot_geometry_msgs::Pose& goal, + bool terminal_forward, + double expected_vertex_distance) +{ + CHECK(path.size() > 3); + const double goal_yaw = data_convert::getYaw(goal.orientation); + + // Locate the run of poses that share a position: that is the rotation. + std::size_t block_start = path.size(); + std::size_t block_end = 0; + for (std::size_t index = 1; index < path.size(); ++index) + { + if (std::hypot(path[index].position.x - path[index - 1].position.x, + path[index].position.y - path[index - 1].position.y) <= 1e-9) + { + if (block_start == path.size()) + { + block_start = index - 1; + } + block_end = index; + } + } + CHECK(block_start < path.size()); + // StanleyControl::planDivision only splits a rotation out of the plan after + // three consecutive same-position samples, so four poses is the hard floor. + // Fewer and the controller drives through the corner instead of turning. + CHECK(block_end >= block_start + 3); + + for (std::size_t index = block_start; index <= block_end; ++index) + { + CHECK(std::fabs(lateral(path[index], goal)) < 1e-7); + CHECK(near(std::fabs(longitudinal(path[index], goal)), + expected_vertex_distance, 1e-6)); + } + + // Yaw steps one way only, never by less than the epsilon planDivision uses + // to decide two samples share a heading, and lands on the goal heading. + const double first_step = normalizeAngle( + data_convert::getYaw(path[block_start + 1].orientation) - + data_convert::getYaw(path[block_start].orientation)); + CHECK(std::fabs(first_step) > 1e-6); + for (std::size_t index = block_start + 1; index <= block_end; ++index) + { + const double step = normalizeAngle( + data_convert::getYaw(path[index].orientation) - + data_convert::getYaw(path[index - 1].orientation)); + CHECK(std::fabs(step) > 1e-6); + CHECK(step * first_step > 0.0); + } + CHECK(std::fabs(normalizeAngle( + data_convert::getYaw(path[block_end].orientation) - goal_yaw)) < 1e-7); + + // One travel direction end to end: no cusp anywhere, which is the whole + // reason this shape is preferred over the single-cusp one. + for (std::size_t index = 0; index + 1 < path.size(); ++index) + { + if (std::hypot(path[index + 1].position.x - path[index].position.x, + path[index + 1].position.y - path[index].position.y) <= 1e-9) + { + continue; + } + CHECK(edgeIsForward(path[index], path[index + 1]) == terminal_forward); + } + + // Terminal leg: on the axis and already at the goal heading. + for (std::size_t index = block_end; index < path.size(); ++index) + { + CHECK(std::fabs(lateral(path[index], goal)) < 1e-7); + CHECK(std::fabs(normalizeAngle( + data_convert::getYaw(path[index].orientation) - goal_yaw)) < 1e-7); + } + + // The defining property: the path never reaches further away from the dock + // than the robot already stood, so it costs no extra aisle depth. + for (const auto& sample : path) + { + CHECK(std::fabs(longitudinal(sample, goal)) <= + std::fabs(longitudinal(path.front(), goal)) + 1e-9); + } +} + std::vector generatePath( dock_planner::DockCalc& calculator, const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, const std::vector& robot_footprint, - const std::vector& dock_footprint) + const std::vector& dock_footprint, + bool allow_stationary_block = false) { std::vector path; CHECK(calculator.makePlanMoveToDock(start, goal, robot_footprint, @@ -225,7 +317,9 @@ std::vector generatePath( CHECK(std::isfinite(current.position.y)); CHECK(std::isfinite(current.orientation.z)); CHECK(std::isfinite(current.orientation.w)); - if (index > 0) + // The pivot shape deliberately repeats a position while the body turns, + // so that check only applies to the shapes made of motion alone. + if (index > 0 && !allow_stationary_block) { CHECK(std::hypot(current.position.x - path[index - 1].position.x, current.position.y - path[index - 1].position.y) > 1e-9); @@ -269,6 +363,167 @@ void testConfig() config = dock_planner::DockPlannerConfig{}; config.path_point_spacing = std::numeric_limits::quiet_NaN(); CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_fallback_extension = -0.01; + CHECK(!config.validate(error)); + config = dock_planner::DockPlannerConfig{}; + config.pivot_safety_margin = -0.01; + CHECK(!config.validate(error)); + + // A differential base has no steered axle, so empty axle frames and a zero + // steering angle must NOT stop it loading -- validating them there would + // reject a perfectly valid robot. + config = dock_planner::DockPlannerConfig{}; + config.kinematic_model = dock_planner::KinematicModel::kDifferential; + config.max_steering_angle = 0.0; + config.front_axle_frame.clear(); + config.rear_axle_frame.clear(); + CHECK(config.validate(error)); + CHECK(!config.requiresAxleTf()); + // 0 is the answer, not a failure: it is what allows turning on the spot. + CHECK(near(config.minimumTurningRadius(), 0.0)); + + config.minimum_turning_radius = -0.1; + CHECK(!config.validate(error)); + config.minimum_turning_radius = 1.5; + CHECK(config.validate(error)); + CHECK(near(config.minimumTurningRadius(), 1.5)); + + // Ackermann still needs its axle TF resolved before it can plan. + config = dock_planner::DockPlannerConfig{}; + CHECK(config.requiresAxleTf()); +} + +/** Footprint of the APM reference robot: 1.65 m of nose, 0.35 m of tail. */ +std::vector apmFootprint() +{ + return {point(1.65, -0.40), point(1.65, 0.40), + point(-0.35, 0.40), point(-0.35, -0.40)}; +} + +std::vector apmDockFootprint() +{ + return {point(0.50, -0.40), point(0.50, 0.40), + point(-0.50, 0.40), point(-0.50, -0.40)}; +} + +/** + * Where the rotation has to happen for the footprints above. The swept circle + * is the binding constraint, not the mating extent: hypot(1.65, 0.40) is + * 1.6978 m, so the vertex ends up 1.50 m further out than the 0.85 m the rear + * mating extent plus dock face would have suggested. + */ +double apmPivotVertex(double pivot_safety_margin) +{ + return std::max(0.85, std::hypot(1.65, 0.40) + 0.50 + pivot_safety_margin); +} + +void testPivotFallback() +{ + dock_planner::DockPlannerConfig config = apmConfig(); + config.pivot_fallback_extension = 1.0; + dock_planner::DockCalc calculator(config); + + const auto robot_footprint = apmFootprint(); + const auto dock_footprint = apmDockFootprint(); + const auto goal = pose(0.0, 0.0, 0.0); + const double maximum_curvature = 1.0 / config.minimumTurningRadius(); + const double vertex = apmPivotVertex(config.pivot_safety_margin); + + // 0.60 m of lateral offset needs a 1.598 m cusp extension at min_radius + // 2.4287 m, past the 1.0 m threshold, so the pivot shape takes over. + const auto pivot_path = generatePath(calculator, pose(2.8, 0.6, -1.2), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(pivot_path, goal.pose, false, vertex); + + // Same start, mirrored to the far side of the goal: the docking edge flips, + // so the whole path drives FORWARD instead, and the vertex is unchanged + // because the swept circle, not the mating extent, decides where it sits. + const auto front_pivot = generatePath(calculator, pose(-2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(front_pivot, goal.pose, true, vertex); + + // Only 0.05 m of lateral offset: the cusp costs 0.490 m, under the + // threshold, so nothing changes and the cusp is still planned. + const auto cusp_path = generatePath(calculator, pose(2.8, 0.05, 0.0), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(cusp_path, goal.pose, maximum_curvature, false); + + // Vertex behind the robot (start 1.5 m out, vertex 2.348 m): the pivot + // shape cannot be built and the planner must fall back to the cusp rather + // than refuse a path. + const auto behind_path = generatePath(calculator, pose(1.5, 0.3, 0.0), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(behind_path, goal.pose, maximum_curvature, false); + + // The safety margin really does move the vertex: pushing it 0.50 m further + // out puts it past the 2.8 m start, so the same case falls back to a cusp. + config.pivot_safety_margin = 0.65; + calculator.setConfig(config); + const auto margin_path = generatePath(calculator, pose(2.8, 0.6, -1.2), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(margin_path, goal.pose, maximum_curvature, false); + + // A cusp that cannot be placed at all used to be a hard failure. With the + // pivot shape available it is a path instead: refusing to dock is strictly + // worse than docking with one extra stop. + config = apmConfig(); + config.maximum_forward_extension = 0.30; + std::vector refused; + dock_planner::DockCalc no_pivot(config); + CHECK(!no_pivot.makePlanMoveToDock(pose(2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint, refused)); + CHECK(refused.empty()); + + config.pivot_fallback_extension = 1.0; + dock_planner::DockCalc rescued(config); + const auto rescue_path = generatePath(rescued, pose(2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(rescue_path, goal.pose, false, + apmPivotVertex(config.pivot_safety_margin)); +} + +void testDifferentialModel() +{ + dock_planner::DockPlannerConfig config; + config.kinematic_model = dock_planner::KinematicModel::kDifferential; + config.minimum_turning_radius = 0.0; + config.path_point_spacing = 0.05; + config.direct_entry_min_curve_room = 0.0; + // Deliberately left at 0: a differential base pivots because it can, not + // because a threshold turned the shape on. + config.pivot_fallback_extension = 0.0; + dock_planner::DockCalc calculator(config); + + const auto robot_footprint = apmFootprint(); + const auto dock_footprint = apmDockFootprint(); + const auto goal = pose(0.0, 0.0, 0.0); + const double vertex = apmPivotVertex(config.pivot_safety_margin); + + CHECK(near(config.minimumTurningRadius(), 0.0)); + + const auto rear_path = generatePath(calculator, pose(2.8, 0.6, -1.2), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(rear_path, goal.pose, false, vertex); + + // Barely off the axis: an Ackermann base would have taken the cheap cusp + // here, but a base that turns on the spot always prefers the shape that + // claims no extra aisle. + const auto aligned_path = generatePath(calculator, pose(2.8, 0.05, 0.0), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(aligned_path, goal.pose, false, vertex); + + const auto front_path = generatePath(calculator, pose(-2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint, true); + checkPivotPath(front_path, goal.pose, true, vertex); + + // Turning on the spot forbidden -- a tall load, say. The base is still + // differential, but the planner must go back to arc-based shapes. + config.minimum_turning_radius = 1.5; + dock_planner::DockCalc loaded(config); + const auto loaded_path = generatePath(loaded, pose(2.8, 0.6, -1.2), goal, + robot_footprint, dock_footprint); + checkSingleCuspPath(loaded_path, goal.pose, 1.0 / 1.5, false); } void testPathGeneration() @@ -506,6 +761,8 @@ int main() testConfig(); testPathGeneration(); testDirectEntry(); + testPivotFallback(); + testDifferentialModel(); testAsymmetricFootprint(); testDockAnchor(); if (failures != 0)