From 539fc5da162c533bad2860105521f55995d6f56a Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 12 Aug 2026 21:52:52 +0700 Subject: [PATCH] Refactor DockPlanner: typed config, dock anchor, validated dock footprint Split configuration out of the planner into DockPlannerConfig with explicit load/validate, so a missing or malformed key fails at initialize() with a message instead of silently defaulting to zero. - initialize() now scopes its NodeHandle to the plugin name. The previous "~/" form never resolved ("~" is not a key in the merged tree) and fell back to ROOT, so every parameter was read from the wrong place and cost_threshold silently dropped from 200 to 0. - Replace robot_nav_2d_utils::footprintFromParams(), whose declaration and definition disagreed on the argument type. The symbol was never defined, and because the plugin is dlopen'd lazily the failure only surfaced at the call site on the robot, long after a clean build. - Read footprint_dock, the dock object's polygon, with range and NaN checks. move_base2 copies it in per marker before the instance is built. - dock_anchor selects whether the marker goal sits at the dock centre or on its approach face; the face case ignores footprint_dock entirely. - makePlan() rejects start/goal outside the costmap global frame instead of planning across mismatched frames. - Add dock_planner_test covering config validation, footprint parsing and path generation. Co-Authored-By: Claude Opus 5 (1M context) --- CMakeLists.txt | 101 +- README.md | 374 ++---- config/dock_global_params.yaml | 58 +- include/dock_planner/dock_calc.h | 199 ++- include/dock_planner/dock_planner.h | 61 +- include/dock_planner/dock_planner_config.h | 63 + include/dock_planner/utils/conversion.h | 43 - include/dock_planner/utils/curve_common.h | 100 +- package.xml | 67 +- src/dock_calc.cpp | 1211 +++++++++---------- src/dock_planner.cpp | 291 +++-- src/dock_planner_config.cpp | 178 +++ src/utils/curve_common.cpp | 1267 ++------------------ test/dock_planner_test.cpp | 300 +++++ 14 files changed, 1760 insertions(+), 2553 deletions(-) create mode 100644 include/dock_planner/dock_planner_config.h delete mode 100644 include/dock_planner/utils/conversion.h create mode 100644 src/dock_planner_config.cpp create mode 100644 test/dock_planner_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 25fb921..9e32e56 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,7 +4,6 @@ project(dock_planner VERSION 1.0.0 LANGUAGES CXX) if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) set(BUILDING_WITH_CATKIN TRUE) message(STATUS "Building dock_planner with Catkin") - else() set(BUILDING_WITH_CATKIN FALSE) message(STATUS "Building dock_planner with Standalone CMake") @@ -15,11 +14,16 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -# Find dependencies +# Find dependencies. Boost is header-only here (boost/dll/alias.hpp exports the +# plugin symbol); no Boost component library is linked. find_package(Eigen3 REQUIRED) -find_package(Boost REQUIRED COMPONENTS system thread filesystem) +find_package(Boost REQUIRED) +find_package(yaml-cpp REQUIRED) +# librobot_time.so calls pthread_create but does not export the dependency; +# link it explicitly instead of inheriting it from an unrelated Boost component. +find_package(Threads REQUIRED) -if (NOT BUILDING_WITH_CATKIN) +if(NOT BUILDING_WITH_CATKIN) # Enable Position Independent Code set(CMAKE_POSITION_INDEPENDENT_CODE ON) @@ -29,14 +33,9 @@ if (NOT BUILDING_WITH_CATKIN) set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") - set(PACKAGES_DIR - robot_visualization_msgs - robot_nav_msgs - robot_nav_2d_msgs - robot_nav_2d_utils - robot_std_msgs + # Library targets provided by the standalone parent build. + set(STANDALONE_DEP_TARGETS robot_geometry_msgs - tf3 robot_time data_convert robot_costmap_2d @@ -44,19 +43,12 @@ if (NOT BUILDING_WITH_CATKIN) robot_cpp ) - find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) - else() # ======================================================== # Catkin specific configuration # ======================================================== find_package(catkin REQUIRED COMPONENTS - robot_visualization_msgs - robot_nav_msgs - robot_nav_2d_msgs - robot_nav_2d_utils - robot_std_msgs robot_geometry_msgs robot_time data_convert @@ -65,25 +57,12 @@ else() robot_cpp ) - find_package(Boost REQUIRED COMPONENTS system thread filesystem) - find_package(Eigen3 REQUIRED) - # Find tf3 library - find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) - catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} - CATKIN_DEPENDS robot_visualization_msgs robot_nav_msgs robot_nav_2d_msgs robot_nav_2d_utils robot_std_msgs robot_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_cpp + CATKIN_DEPENDS robot_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_cpp DEPENDS Eigen3 Boost ) - - include_directories( - include - ${catkin_INCLUDE_DIRS} - ${EIGEN3_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ${TF3_INCLUDE_DIR} - ) endif() # ======================================================== @@ -91,43 +70,40 @@ endif() # ======================================================== add_library(${PROJECT_NAME} SHARED src/dock_planner.cpp + src/dock_planner_config.cpp src/dock_calc.cpp src/utils/curve_common.cpp src/utils/pose.cpp src/utils/line_common.cpp ) +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + PRIVATE + ${Boost_INCLUDE_DIRS} +) + if(BUILDING_WITH_CATKIN) add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ${TF3_INCLUDE_DIR} - ) + target_include_directories(${PROJECT_NAME} PUBLIC ${catkin_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} - PUBLIC ${catkin_LIBRARIES} - PRIVATE Eigen3::Eigen Boost::system Boost::thread Boost::filesystem - ${TF3_LIBRARY} + PUBLIC ${catkin_LIBRARIES} Threads::Threads + PRIVATE Eigen3::Eigen yaml-cpp ) else() - target_include_directories(${PROJECT_NAME} - PUBLIC - $ - $ - ${TF3_INCLUDE_DIR} - ) - target_link_libraries(${PROJECT_NAME} PUBLIC - ${PACKAGES_DIR} + ${STANDALONE_DEP_TARGETS} + Threads::Threads PRIVATE - Eigen3::Eigen Boost::system Boost::thread Boost::filesystem - ${TF3_LIBRARY} + Eigen3::Eigen + yaml-cpp ) set_target_properties(${PROJECT_NAME} PROPERTIES @@ -138,12 +114,31 @@ else() endif() +if(COMMAND target_link_options) + target_link_options(${PROJECT_NAME} PRIVATE -Wl,--no-undefined) +endif() + +# Focused contract tests use a tiny self-contained runner so both catkin and +# standalone builds exercise the same code without adding a test dependency. +if(NOT BUILDING_WITH_CATKIN) + include(CTest) +endif() + +if((BUILDING_WITH_CATKIN AND CATKIN_ENABLE_TESTING) OR + (NOT BUILDING_WITH_CATKIN AND BUILD_TESTING)) + add_executable(${PROJECT_NAME}_test test/dock_planner_test.cpp) + target_link_libraries(${PROJECT_NAME}_test PRIVATE ${PROJECT_NAME}) + if(BUILDING_WITH_CATKIN) + add_dependencies(${PROJECT_NAME}_test ${catkin_EXPORTED_TARGETS}) + endif() + add_test(NAME ${PROJECT_NAME}_test COMMAND ${PROJECT_NAME}_test) +endif() + # ======================================================== # Install # ======================================================== if(BUILDING_WITH_CATKIN) ## Mark libraries for installation - ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html install(TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} @@ -185,6 +180,6 @@ else() message(STATUS "Project: ${PROJECT_NAME}") message(STATUS "Version: ${PROJECT_VERSION}") message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Dependencies: robot_visualization_msgs, robot_nav_msgs, robot_nav_2d_msgs, robot_nav_2d_utils, robot_std_msgs, robot_geometry_msgs, tf3, robot_time, data_convert, robot_costmap_2d, robot_nav_core, robot_cpp, Eigen3, Boost") + message(STATUS "Dependencies: robot_geometry_msgs, robot_time, data_convert, robot_costmap_2d, robot_nav_core, robot_cpp, Eigen3, Boost (headers), yaml-cpp") message(STATUS "=================================") endif() diff --git a/README.md b/README.md index 7e8b3b4..20121f7 100644 --- a/README.md +++ b/README.md @@ -1,312 +1,108 @@ # Dock Planner -Global planner tao duong di cho robot tiep can tram dock (tram sac, tram hang) bang duong cong NURBS. +Global planner tạo đường tiếp cận dock bằng hai đoạn NURBS bậc 2. Phiên bản hiện +tại chỉ tính hình học; chưa kiểm tra collision/free space trên costmap. -## Cau truc thu muc - -``` -dock_planner/ -├── include/dock_planner/ -│ ├── dock_planner.h # Lop DockPlanner - plugin interface -│ ├── dock_calc.h # Lop DockCalc - logic tinh toan duong di -│ └── utils/ -│ ├── curve_common.h # Thu vien NURBS curve -│ ├── pose.h # Chuyen doi pose/quaternion -│ └── common.h # Tien ich chung -├── src/ -│ ├── dock_planner.cpp # Khoi tao, load param, goi DockCalc -│ ├── dock_calc.cpp # Thuat toan chinh: NURBS path generation -│ └── utils/ -│ ├── curve_common.cpp -│ ├── line_common.cpp -│ └── pose.cpp -└── config/ - └── dock_global_params.yaml # Tham so cau hinh -``` - -## Pipeline tong quan - -```mermaid -flowchart TB - subgraph INIT["1. KHOI TAO - DockPlanner::initialize"] - I1["Lien ket costmap_robot"] --> I2["Load ROS params:
cost_threshold, calib_safety_distance"] - I2 --> I3["Load footprint_dock
tu param server"] - end - - subgraph PLAN["2. LAP KE HOACH - DockPlanner::makePlan"] - P1["Lay footprint_robot
tu costmap"] --> P2["Goi DockCalc::makePlanMoveToDock"] - P2 --> P3["Chuyen vector Pose
thanh vector PoseStamped"] - end - - subgraph CALC["3. TINH TOAN - DockCalc::makePlanMoveToDock"] - C1["Tinh RobotGeometry + safety_distance"] - C2["Xac dinh huong tiep can
forward / backward"] - C3["Tinh angle_threshold
heuristic"] - C4["Tao duong tam NURBS
findPathTMP"] - C5["Tim control points
segment 1"] - C6["Sinh NURBS segment 1"] - C7["Sinh NURBS segment 2"] - C8["Ghep path: start + seg1 + seg2 + goal"] - C1 --> C2 --> C3 --> C4 --> C5 --> C6 --> C7 --> C8 - end - - INIT --> PLAN --> CALC -``` - -## So do giai thuat chi tiet - -### 1. Khoi tao (initialize) - -```mermaid -flowchart LR - A["DockPlanner::initialize(name, costmap_robot)"] --> B{Da initialized?} - B -- Co --> Z["return true"] - B -- Chua --> C["Lien ket costmap_robot_
costmap_
frame_id_"] - C --> D["getParam:
check_free_space
cost_threshold
calib_safety_distance"] - D --> E["Copy params
sang DockCalc"] - E --> F["footprintFromParams
→ footprint_dock_"] - F --> G["initialized_ = true"] - G --> Z -``` - -### 2. Lap ke hoach (makePlan) +## Luồng xử lý ```mermaid flowchart TD - A["makePlan(start, goal, plan)"] --> B{initialized_?} - B -- false --> FAIL["return false"] - B -- true --> C["footprint_robot =
costmap_robot_->getRobotFootprint()"] - C --> D["makePlanMoveToDock
(start, goal, footprint_robot,
footprint_dock_, degree=2, step=0.02)"] - D --> E{Thanh cong?} - E -- false --> FAIL - E -- true --> F["Chuyen moi Pose thanh PoseStamped
(gan timestamp, frame_id)"] - F --> G["return true"] + A["DockPlanner::initialize"] --> B["Kiểm tra costmap và global frame"] + B --> C["Load và validate DockPlannerConfig"] + C --> D["Load footprint_dock nếu có"] + D --> E["DockPlanner::makePlan"] + E --> F["Kiểm tra start/goal cùng global frame"] + F --> G["Lấy robot footprint từ costmap"] + G --> H["DockCalc::makePlanMoveToDock"] + H --> I["Tính trục tiếp cận và angle threshold"] + I --> J["Sinh reference curve NURBS"] + J --> K["Chọn 3 control points cho segment 1"] + K --> L["Sinh segment 1 và segment 2"] + L --> M["Ghép path, bỏ điểm trùng và đóng dấu frame/time"] ``` -### 3. Thuat toan chinh (makePlanMoveToDock) +Mỗi đoạn NURBS dùng đúng 3 control points và bậc 2 với knot vector clamped +`[0, 0, 0, 1, 1, 1]`. Đây là bất biến của thuật toán, không phải tham số +tuning. -```mermaid -flowchart TD - START["makePlanMoveToDock(start, goal)"] --> GEOM +## Hợp đồng đầu vào - subgraph GEOM["BUOC 1: Tinh hinh hoc"] - G1["computeGeometry(footprint_robot)
→ robot.length, robot.radius"] - G2["computeGeometry(footprint_dock)
→ dock.length"] - G3["safety_distance =
(robot.radius + calib) * 2"] - G1 --> G3 - G2 --> G3 - end +- `start` và `goal` phải có pose hữu hạn, quaternion hợp lệ và cùng + `global_frame` của costmap. +- Robot footprint phải có ít nhất 3 điểm, có kích thước X/Y dương. Footprint + được phép lệch tâm so với base_link (ví dụ forklift có càng chìa một phía): + khoảng tiếp cận dùng extent của mép dẫn đầu theo chiều chạy segment cuối + (tiến → mép +x, lùi → mép −x), không dùng nửa bounding box. +- `dock_anchor` (`center` mặc định | `face`) khai goal nằm ở tâm footprint dock + hay ngay trên mặt tiếp cận. `face` thì dock không đóng góp vào khoảng tiếp + cận và `footprint_dock` bị bỏ qua. +- `footprint_dock` là tuỳ chọn, chỉ dùng khi `dock_anchor: center`, toạ độ + trong frame của goal. Nếu không có, planner cảnh báo và coi extent dock bằng + `0 m` khi tính khoảng tiếp cận. +- Pose đầu giữ đúng vị trí start, nhưng orientation lấy theo tangent và chiều + chuyển động của segment đầu; yaw hiện tại của robot không được chèn vào path. +- Mọi segment phải sinh thành công. Nếu có giá trị NaN/Inf, spline suy biến hoặc + segment rỗng, planner trả `false` và không trả partial path. - GEOM --> VALID{robot.length > 0
AND safety > 0?} - VALID -- false --> ERR["return false"] - VALID -- true --> POSE_C +`footprint_dock` và `dock_anchor` được runtime cập nhật từ +`docking_marker_profiles//` vào namespace `DockPlanner` trước khi tạo +plugin; vì vậy file config không khai báo footprint hay anchor cố định. - subgraph POSE_C["BUOC 2: Tinh diem trung gian C"] - PC1["distance_min_C =
(robot.length + dock.length) / 2"] - PC2["yaw_goal = normalizeAngle(goal.yaw)"] - PC3["Pose_C = offsetPoint(goal, yaw_goal, distance_min_C)"] - PC1 --> PC3 - PC2 --> PC3 - end +## Tham số cấu hình - POSE_C --> DIR +File mặc định: `config/dock_global_params.yaml`. - subgraph DIR["BUOC 3: Xac dinh huong di"] - D1["t = compute_t(start, goal, Pose_C)"] - D2{t < 0 ?} - D3["Lat yaw_goal 180 do
Tinh lai Pose_C va t
dir = backward"] - D4["dir = forward"] - D1 --> D2 - D2 -- Co --> D3 - D2 -- Khong --> D4 - end +| Tham số | Mặc định | Đơn vị | Mô tả | +|---|---:|---|---| +| `approach/alignment_distance_padding` | `0.0` | m | Khoảng căn thẳng thêm sau nửa tổng chiều dài robot và dock | +| `approach/lateral_distance_near` | `0.10` | m | Cận dưới của miền nội suy angle threshold | +| `approach/lateral_distance_far` | `1.00` | m | Cận trên của miền nội suy angle threshold | +| `approach/angle_threshold_near` | `2.35619449019` | rad | Ngưỡng góc tại lateral distance gần | +| `approach/angle_threshold_far` | `1.09955742876` | rad | Ngưỡng góc tại lateral distance xa | +| `approach/direction_angle_hysteresis` | `0.05` | rad | Biên trễ khi phân loại hướng nối vào reference path | +| `approach/direction_distance_tolerance` | `0.10` | m | Biên khoảng cách khi loại điểm nối gần cuối reference path | +| `sampling/path_point_spacing` | `0.05` | m | Khoảng cách mục tiêu giữa các pose được lấy mẫu | - DIR --> T_CHECK{t > 1 ?} - T_CHECK -- false --> ERR - T_CHECK -- true --> ANGLE +Quan hệ bắt buộc: - subgraph ANGLE["BUOC 4: Tinh angle threshold"] - A1["Pose_D = compute_D(goal, Pose_C, t)"] - A2["distance_AD =
pointToSegmentDistance(start, goal, Pose_C)"] - A3["scale = f(distance_AD)
angle_threshold =
min((alpha+|scale|)*beta*pi, gamma*pi)"] - A1 --> A3 - A2 --> A3 - end +- `0 <= lateral_distance_near < lateral_distance_far` +- `0 < angle_threshold_far < angle_threshold_near < pi` +- `0 <= direction_angle_hysteresis < angle_threshold_far` +- `0 < path_point_spacing <= 1.0` +- Các khoảng cách còn lại phải không âm; tất cả giá trị phải hữu hạn. - ANGLE --> TMP_PATH +Angle threshold được nội suy từ giá trị `near` đến `far` theo lateral distance +và clamp ngoài miền cấu hình. Mật độ path được tính theo chiều dài ước lượng của +đường cong, đồng thời luôn giữ hai endpoint. - subgraph TMP_PATH["BUOC 5: Tao duong tam"] - T1["Tinh Pose_F = offsetPoint(goal, yaw, dist_F)"] - T2["mid = trung diem(C, F)"] - T3["findPathTMP({C, mid, F})
→ saved_poses_tmp"] - T1 --> T2 --> T3 - end +## Tham số cố ý không tồn tại - TMP_PATH --> TMP_OK{Path tmp ok?} - TMP_OK -- false --> ERR - TMP_OK -- true --> SEG1 +`check_free_space`, `cost_threshold`, `allow_unknown` và +`calib_safety_distance` không được đọc và không nên khai báo. Collision checker +chưa được implement; giữ các key này sẽ tạo cảm giác an toàn sai. Khi bổ sung +collision checking, cần định nghĩa lại hợp đồng costmap và test riêng trước khi +đưa các tham số này vào config. - subgraph SEG1["BUOC 6: Sinh segment 1"] - S1["findNURBSControlPoints
(start, saved_poses_tmp, angle_threshold)
→ control_points_1, dir"] - S2["Xac dinh chieu reverse
cua segment 1"] - S3["generateNURBSPath(control_points_1)
→ first_segment"] - S1 --> S2 --> S3 - end +## Cấu trúc chính - SEG1 --> SEG1_OK{first_segment
khong rong?} - SEG1_OK -- false --> ERR - SEG1_OK -- true --> SEG2 - - subgraph SEG2["BUOC 7: Sinh segment 2"] - S4["mid_ctrl = trung diem
(first_segment.back, goal)"] - S5["generateNURBSPath
({last_of_seg1, mid_ctrl, goal})
→ second_segment"] - S4 --> S5 - end - - SEG2 --> ASSEMBLE["BUOC 8: Ghep duong di
start + seg1 + seg2 + goal"] - ASSEMBLE --> OK["return true"] +```text +include/dock_planner/ + dock_planner.h Plugin interface + dock_planner_config.h Load, validate và nội suy config + dock_calc.h Core hình học độc lập với plugin + utils/curve_common.h Đánh giá NURBS tối thiểu (setup + CalculateCurvePoint) +src/ + dock_planner.cpp + dock_planner_config.cpp + dock_calc.cpp + utils/curve_common.cpp +test/ + dock_planner_test.cpp +config/ + dock_global_params.yaml ``` -### 4. Sinh duong NURBS (generateNURBSPath) - -```mermaid -flowchart TD - A["generateNURBSPath
(control_points, check_free,
edge_end, reverse)"] --> B["setupSpline(control_points, degree)
Tao knot vector + weights
Nap vao Spline_Inf"] - B --> C["Tinh chieu dai NURBS
calculateNURBSLength"] - C --> D["step_new = resolution / length
(adaptive step)"] - D --> E["Duyet t = 0 → 1
(buoc step_new)"] - - E --> F["point = CalculateCurvePoint(t)"] - F --> G{point hop le?
khong NaN?} - G -- false --> E - G -- true --> H{Kiem tra
isFreeSpace?} - H -- Bi chan --> I["obstacle_flag = true
BREAK"] - H -- Thong --> J["Luu pose
Cap nhat orientation"] - J --> E - - I --> K["result.clear()"] - E -- t > 1.0 --> L["Gan orientation
cho diem cuoi"] - L --> M["return result"] - K --> M -``` - -### 5. Tim control points (findNURBSControlPoints) - -```mermaid -flowchart TD - A["findNURBSControlPoints
(start, saved_poses, angle_threshold)"] --> B["findNearestPointOnPath
→ idx, dir"] - B --> C{idx != -1 ?} - - C -- idx hop le --> D["control_points = {start, saved[idx]}"] - D --> E{dir == 1?} - E -- Co --> F["Tim diem lui ve
sao cho dist >= target
→ end_idx"] - F --> G["Them saved[end_idx]"] - E -- Khong, dir == -1 --> H["Them saved.back()"] - - C -- idx == -1 --> I["mid = trung diem
(start, nearest)"] - I --> J["control_points =
{start, mid, nearest}"] - - G --> K["return true"] - H --> K - J --> K -``` - -### 6. Tim diem gan nhat tren duong (findNearestPointOnPath) - -```mermaid -flowchart TD - A["findNearestPointOnPath
(pose, saved_poses, angle_threshold)"] --> B["Tim nearest_idx
(khoang cach nho nhat)"] - B --> C["Duyet nguoc tu nearest_idx → 1"] - C --> D{signedAngle >= threshold?} - D -- Co --> E["nearest_idx = i
found_flag_1 = true"] - D -- Khong --> C - - E --> F{Kiem tra khoang cach
distance_2 >= distance_1?} - F -- Co --> G["dir = 1
return nearest_idx"] - F -- Khong --> H["Duyet xuoi tu nearest_idx → cuoi"] - C -- Het vong --> H - - H --> I{signedAngle >= threshold - 0.05?} - I -- Co --> J["dir = -1
return nearest_idx"] - I -- Khong, i == cuoi --> K["dir = 0
return -1"] - - J --> L{dist hop ly?} - L -- false --> K - L -- true --> J -``` - -## Mo ta cac diem hinh hoc - -``` - F ──────── mid ──────── C ──────── Goal - | (duong tam) | | - | | | - | Pose_D | | - | ╲ | | - | ╲ distance_AD | | - | ╲ | | - Start ╲ | | - | | - ◄── distance_min_F ────►| | - ◄── dist_C ──►| -``` - -- **Goal**: Vi tri dock dich -- **Pose_C**: Diem offset tu Goal theo huong yaw_goal, cach `(robot.length + dock.length) / 2` -- **Pose_F**: Diem xa hon tren cung huong, cach Goal = `dist_C + dist_CD + dist_DF` -- **Pose_D**: Hinh chieu vuong goc tu Start len duong Goal→C keo dai -- **distance_AD**: Khoang cach vuong goc tu Start den duong Goal→C -- **Duong tam (C → mid → F)**: Duong NURBS tam de tim diem noi segment 1 - -## Luong du lieu giua cac lop - -```mermaid -flowchart LR - subgraph Plugin["DockPlanner (Plugin Interface)"] - init["initialize()"] - make["makePlan()"] - end - - subgraph Core["DockCalc (Core Algorithm)"] - calc["makePlanMoveToDock()"] - nurbs["generateNURBSPath()"] - tmp["findPathTMP()"] - ctrl["findNURBSControlPoints()"] - near["findNearestPointOnPath()"] - setup["setupSpline()"] - end - - subgraph Lib["Utils"] - curve["CurveCommon
(NURBS engine)"] - spline["Spline_Inf
(knot/ctrl/weight)"] - end - - init -->|"config params"| calc - make -->|"start, goal,
footprints"| calc - calc --> tmp - calc --> ctrl - calc --> nurbs - ctrl --> near - tmp --> setup - nurbs --> setup - setup --> curve - setup --> spline - curve -->|"CalculateCurvePoint"| nurbs - curve -->|"CalculateCurvePoint"| tmp -``` - -## Tham so cau hinh - -| Tham so | Kieu | Mac dinh | Mo ta | -|---------|------|----------|-------| -| `cost_threshold` | int | 200 | Nguong chi phi vat can (0-255) | -| `calib_safety_distance` | double | 0.0 | Khoang cach an toan bo sung (met) | -| `check_free_space` | bool | false | Bat/tat kiem tra vung tu do | -| `degree` (hardcode) | int | 2 | Bac cua duong cong NURBS | -| `step` (hardcode) | double | 0.02 | Buoc lay mau tham so t | - -## Ghi chu - -- **NURBS (Non-Uniform Rational B-Spline)**: Duong cong bac 2 voi 3 control points, knot vector dang clamped `[0,0,0,1,1,1]`. -- **Adaptive step**: Buoc lay mau duoc tinh tu `resolution / curve_length` de dam bao mat do diem dong deu theo do phan giai costmap. -- **2-segment path**: Duong di gom 2 doan NURBS noi tiep — segment 1 dua robot tu vi tri hien tai vao duong tiep can, segment 2 dua robot tu diem noi den dock. +`utils/curve_common` chỉ giữ phần đánh giá điểm trên spline mà `DockCalc` dùng +(`curveIsValid`, `ReadSplineInf`, `CalculateCurvePoint`). Các hàm derivative, +curvature và visualization của bản gốc đã bị loại bỏ cùng với code không còn +được gọi. diff --git a/config/dock_global_params.yaml b/config/dock_global_params.yaml index 1c5332d..e31fc4e 100644 --- a/config/dock_global_params.yaml +++ b/config/dock_global_params.yaml @@ -1,12 +1,48 @@ -base_global_planner: "DockPlanner" +# DockPlanner plugin and approach-curve parameters. +# +# Collision/free-space checking is intentionally not configured here yet: +# DockPlanner currently generates geometry only. Do not add cost_threshold, +# allow_unknown, or check_free_space until the collision checker is implemented. DockPlanner: - # File: config/planner_params.yaml - MyGlobalPlanner: - cost_threshold: 200 # Ngưỡng chi phí vật cản (0-255) - safety_distance: 2 # Khoảng cách an toàn (cells) - use_dijkstra: false # Sử dụng Dijkstra thay vì A* - - # File: config/costmap_params.yaml - global_costmap: - inflation_radius: 0.3 # Bán kính phình vật cản - cost_scaling_factor: 10.0 # Hệ số tỷ lệ chi phí \ No newline at end of file + # Boost.DLL library containing the exported symbol "DockPlanner". + library_path: libdock_planner + + approach: + # [m] Extra straight alignment distance beyond half the combined robot/dock + # X extents. Increase if the robot must align earlier before entering a dock. + alignment_distance_padding: 0.0 + + # [m] Lateral-distance range used to interpolate angle_threshold_*. + # Values outside this range are clamped, so behavior remains bounded. + lateral_distance_near: 0.10 + lateral_distance_far: 1.00 + + # [rad] Permitted joining angle at the near/far lateral-distance limits. + # Required relation: 0 < far < near < pi. + angle_threshold_near: 2.35619449019 # 0.75*pi + angle_threshold_far: 1.09955742876 # 0.35*pi + + # [rad] Relaxes the forward direction test relative to the reverse test. + # Required: 0 <= value < angle_threshold_far. + direction_angle_hysteresis: 0.05 + + # [m] Distance margin used when rejecting a reference-path joining point + # that is already too close to the end of the approach curve. + direction_distance_tolerance: 0.10 + + sampling: + # [m] Target spacing between generated path poses. The curve is sampled by + # arc-length estimate and always includes both endpoints. + path_point_spacing: 0.05 + + # footprint_dock and dock_anchor are intentionally not declared here. They + # describe the physical dock, not the robot, and move_base2 copies the values + # selected from docking_marker_profiles// into this namespace before + # constructing the planner. + # + # dock_anchor: 'center' (default) — goal is the dock footprint center; the + # near-face extent of footprint_dock is added to the approach distance. + # 'face' — goal already sits on the approach face; footprint_dock is + # ignored entirely. + # With anchor 'center' and footprint_dock absent, dock size contributes 0 m + # and DockPlanner emits a warning. diff --git a/include/dock_planner/dock_calc.h b/include/dock_planner/dock_calc.h index c873ad4..d615e43 100644 --- a/include/dock_planner/dock_calc.h +++ b/include/dock_planner/dock_calc.h @@ -1,139 +1,96 @@ -#ifndef DOCK_CALC_H -#define DOCK_CALC_H - -#include -#include - -#include - -#include -#include - -#include - -#include "dock_planner/utils/curve_common.h" -#include "dock_planner/utils/pose.h" -#include "dock_planner/utils/common.h" -#include +#ifndef DOCK_PLANNER_DOCK_CALC_H_ +#define DOCK_PLANNER_DOCK_CALC_H_ #include +#include #include +#include + +#include "dock_planner/dock_planner_config.h" +#include "dock_planner/utils/curve_common.h" + namespace dock_planner { - struct RobotGeometry - { - double length; // dọc trục X - double width; // dọc trục Y - double radius; // circle around base_link - }; - class DockCalc - { - private: - std::unique_ptr input_spline_inf; - std::unique_ptr CurveDesign; +struct RobotGeometry +{ + double length = 0.0; // [m], bounding-box extent along footprint X + double width = 0.0; // [m], bounding-box extent along footprint Y + // Signed extents measured from the frame origin (base_link for the robot, + // goal pose for the dock). They differ when the origin is not the + // 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 +}; - std::vector footprint_robot_; - robot_geometry_msgs::PoseStamped save_goal_; +/** Pure docking-path geometry. Collision checking is intentionally out of scope. */ +class DockCalc +{ +public: + DockCalc(); + explicit DockCalc(const DockPlannerConfig& config); + ~DockCalc(); - bool check_goal_; - int store_start_nearest_idx_; - int start_target_idx_; - double min_distance_to_goal_; + void setConfig(const DockPlannerConfig& config); - // Tính khoảng cách giữa 2 điểm - inline double calc_distance(const robot_geometry_msgs::Pose& p1, const robot_geometry_msgs::Pose& p2) - { - return std::hypot(p1.position.x - p2.position.x, p1.position.y - p2.position.y); - } + bool makePlanMoveToDock( + const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + const std::vector& footprint_robot, + const std::vector& footprint_dock, + std::vector& plan); - inline double calculateAdaptiveStep(double segment_length, double desired_point_spacing = 0.02) - { - if (segment_length <= 1e-9) return 1.0; - return desired_point_spacing / segment_length; - } +private: + static constexpr int kNurbsDegree = 2; - inline double calculateAngle(double x1, double y1, double x2, double y2) - { - double angle = atan2(y2 - y1, x2 - x1); - return angle; - } + std::unique_ptr input_spline_inf_; + std::unique_ptr curve_design_; + DockPlannerConfig config_; + std::mutex calculation_mutex_; - inline double normalizeAngle(double angle) - { - return std::remainder(angle, 2.0 * M_PI); - } + static double distance(const robot_geometry_msgs::Pose& first, + const robot_geometry_msgs::Pose& second); + static double angleBetweenPoints(double x1, double y1, double x2, double y2); + static double normalizeAngle(double angle); + static bool isFinitePose(const robot_geometry_msgs::Pose& pose); + static RobotGeometry computeGeometry(const std::vector& footprint); - double calculateNURBSLength(CurveCommon* curve_design, - Spline_Inf* spline_inf, - int degree, - double initial_step = 0.02); + static robot_geometry_msgs::Pose offsetPoint(const robot_geometry_msgs::Pose& pose, + double yaw, double distance); + static double pointToLineDistance(const robot_geometry_msgs::Pose& point, + const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end); + static double signedAngle(const robot_geometry_msgs::Pose& first, + const robot_geometry_msgs::Pose& vertex, + const robot_geometry_msgs::Pose& second); + static bool projectionRatio(const robot_geometry_msgs::Pose& point, + const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end, + double& ratio); + static robot_geometry_msgs::Pose extrapolate(const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end, + double ratio); - robot_geometry_msgs::Pose offsetPoint(const robot_geometry_msgs::Pose& A,const double& theta, const double& d); + bool setupSpline(const std::vector& control_points); + double calculateNurbsLength(double sample_step = 0.02); + bool sampleCurve(const std::vector& control_points, + std::vector& path, + bool reverse_orientation); + bool sampleTemporaryCurve(const std::vector& control_points, + std::vector& path); - double pointToSegmentDistance(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C); + bool findNurbsControlPoints(int& direction, + std::vector& control_points, + const robot_geometry_msgs::Pose& start_pose, + const std::vector& reference_path, + double angle_threshold); + int findNearestPointOnPath(int& direction, std::size_t& nearest_index, + const robot_geometry_msgs::Pose& pose, + const std::vector& path, + double angle_threshold) const; +}; - double signedAngle(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C); +} // namespace dock_planner - double compute_t(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C); - - robot_geometry_msgs::Pose compute_D(const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C,const double& t); - - void setupSpline(const std::vector& control_points, int degree); - - void updatePoseOrientation(std::vector& saved_poses, - std::vector& nurbs_path, - bool reverse = true); - - bool findPathTMP(const std::vector& control_points, - std::vector& saved_poses, - const int& degree, double step = 0.02); - - bool findNURBSControlPoints(int& dir, std::vector& control_points, - const robot_geometry_msgs::Pose& start_pose, - const std::vector& posesOnPathWay, - const double& angle_threshol, const int& degree); - - int findNearestPointOnPath(int& dir, const robot_geometry_msgs::Pose& pose, - const std::vector& posesOnPathWay, - const double& angle_threshol); - - bool isFreeSpace(const robot_geometry_msgs::Pose& pose, const std::vector& footprint); - - std::vector calcFreeZone(const robot_geometry_msgs::Pose& pose, - const std::vector& footprint); - - std::vector interpolateFootprint(const robot_geometry_msgs::Pose& pose, - const std::vector& footprint, const double& resolution); - - RobotGeometry computeGeometry(const std::vector& fp); - - - public: - //Params - robot_costmap_2d::Costmap2D* costmap_; - - int cost_threshold_; // Threshold for obstacle detection - double safety_distance_; // Derived = (robot.radius + calib_safety_distance_) * 2.0, recomputed each plan - double calib_safety_distance_; // Configured via ROS param "calib_safety_distance" - - DockCalc(); - - ~DockCalc(); - - bool makePlanMoveToDock(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - const std::vector& footprint_robot, - const std::vector& footprint_dock, - const int& degree, const double& step, - std::vector& planMoveToDock, - bool reverse = false); - - - }; - -}//namespace dock_planner - - -#endif \ No newline at end of file +#endif // DOCK_PLANNER_DOCK_CALC_H_ diff --git a/include/dock_planner/dock_planner.h b/include/dock_planner/dock_planner.h index d0ed37d..5f044d2 100644 --- a/include/dock_planner/dock_planner.h +++ b/include/dock_planner/dock_planner.h @@ -1,40 +1,39 @@ -#ifndef DOCK_PLANNER_H -#define DOCK_PLANNER_H +#ifndef DOCK_PLANNER_DOCK_PLANNER_H_ +#define DOCK_PLANNER_DOCK_PLANNER_H_ +#include +#include - -#include "dock_planner/dock_calc.h" #include -namespace dock_planner { - class DockPlanner : public robot_nav_core::BaseGlobalPlanner - { - public: - DockPlanner(); - DockPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot); - - bool initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot); - - bool makePlan(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - std::vector& plan); +#include "dock_planner/dock_calc.h" +#include "dock_planner/dock_planner_config.h" - static robot_nav_core::BaseGlobalPlanner::Ptr create(); +namespace dock_planner +{ - private: - // Core components - robot_costmap_2d::Costmap2DROBOT* costmap_robot_; - robot_costmap_2d::Costmap2D* costmap_; - bool initialized_; - std::string frame_id_; - std::vector footprint_dock_; +class DockPlanner : public robot_nav_core::BaseGlobalPlanner +{ +public: + DockPlanner(); - int cost_threshold_; - double calib_safety_distance_; - bool check_free_space_; + bool initialize(std::string name, + robot_costmap_2d::Costmap2DROBOT* costmap_robot) override; - DockCalc calc_plan_to_dock_; - }; -} // namespace dock_planner + bool makePlan(const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) override; -#endif \ No newline at end of file + static robot_nav_core::BaseGlobalPlanner::Ptr create(); + +private: + robot_costmap_2d::Costmap2DROBOT* costmap_robot_ = nullptr; // non-owning + bool initialized_ = false; + std::string global_frame_; + std::vector footprint_dock_; + DockCalc dock_calc_; +}; + +} // namespace dock_planner + +#endif // DOCK_PLANNER_DOCK_PLANNER_H_ diff --git a/include/dock_planner/dock_planner_config.h b/include/dock_planner/dock_planner_config.h new file mode 100644 index 0000000..48892b0 --- /dev/null +++ b/include/dock_planner/dock_planner_config.h @@ -0,0 +1,63 @@ +#ifndef DOCK_PLANNER_DOCK_PLANNER_CONFIG_H_ +#define DOCK_PLANNER_DOCK_PLANNER_CONFIG_H_ + +#include + +#include + +namespace dock_planner +{ + +/** Shared by config validation and path geometry; single definition on purpose. */ +inline constexpr double kPi = 3.14159265358979323846; + +/** + * @brief Where the docking goal pose is anchored on the dock object. + * + * kCenter: goal is the dock footprint center; the near-face extent of + * footprint_dock is added to the approach distance. + * kFace: goal is already on the approach face; footprint_dock does not + * contribute to the approach distance and is ignored entirely. + */ +enum class DockAnchor +{ + kCenter, + kFace, +}; + +/** + * @brief Runtime parameters that materially affect the docking path geometry. + * + * Collision checking is intentionally not part of this contract yet. Adding a + * parameter for an unimplemented safety feature would make the YAML misleading. + */ +struct DockPlannerConfig +{ + double alignment_distance_padding = 0.0; // [m] + double lateral_distance_near = 0.10; // [m] + double lateral_distance_far = 1.00; // [m] + double angle_threshold_near = 2.35619449019; // [rad], 0.75*pi + double angle_threshold_far = 1.09955742876; // [rad], 0.35*pi + double direction_angle_hysteresis = 0.05; // [rad] + double direction_distance_tolerance = 0.10; // [m] + double path_point_spacing = 0.05; // [m] + + /** + * Per-marker key copied down by move_base2 (like footprint_dock). + * Default kCenter keeps the legacy formula for existing profiles. + */ + DockAnchor dock_anchor = DockAnchor::kCenter; + + /** Load optional overrides from the planner namespace and validate the result. */ + static bool load(const robot::NodeHandle& nh, DockPlannerConfig& config, std::string& error); + + /** Validate values supplied directly by tests or another non-YAML adapter. */ + bool validate(std::string& error) const; + + /** Interpolate and clamp the approach-angle threshold by lateral distance. */ + double angleThreshold(double lateral_distance) const; +}; + +} // namespace dock_planner + +#endif // DOCK_PLANNER_DOCK_PLANNER_CONFIG_H_ diff --git a/include/dock_planner/utils/conversion.h b/include/dock_planner/utils/conversion.h deleted file mode 100644 index 216b999..0000000 --- a/include/dock_planner/utils/conversion.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef CONVERSION_H_ -#define CONVERSION_H_ -#include "curve_common.h" - -#include -#include -#include - -inline Eigen::Vector3d EigenVecter3dFromPointMsg(const robot_geometry_msgs::Point& msg) { - return Eigen::Vector3d(msg.x, msg.y, msg.z); -} - -inline EigenTrajectoryPoint::Vector EigenTrajectoryVectorFromVector(const std::vector &plan) -{ - EigenTrajectoryPoint::Vector eigen_trajectory_point_vec; - EigenTrajectoryPoint eigen_trajectory_point; - - for(int i = 0; i < plan.size(); i++) - { - eigen_trajectory_point.position(0) = plan.at(i).pose.position.x; - eigen_trajectory_point.position(1) = plan.at(i).pose.position.y; - eigen_trajectory_point_vec.push_back(eigen_trajectory_point); - } - - return eigen_trajectory_point_vec; -} - -inline EigenTrajectoryPoint::Vector EigenTrajectoryVectorFromVector(const std::vector &discreate_point_vec) -{ - EigenTrajectoryPoint::Vector eigen_trajectory_point_vec; - EigenTrajectoryPoint eigen_trajectory_point; - - for(int i = 0; i < discreate_point_vec.size(); i++) - { - eigen_trajectory_point.position(0) = discreate_point_vec.at(i).x; - eigen_trajectory_point.position(1) = discreate_point_vec.at(i).y; - eigen_trajectory_point_vec.push_back(eigen_trajectory_point); - } - - return eigen_trajectory_point_vec; -} - -#endif //CONVERSION_H_ \ No newline at end of file diff --git a/include/dock_planner/utils/curve_common.h b/include/dock_planner/utils/curve_common.h index 28bef34..377784b 100644 --- a/include/dock_planner/utils/curve_common.h +++ b/include/dock_planner/utils/curve_common.h @@ -1,82 +1,62 @@ -#ifndef CURVE_COMMON_H_ -#define CURVE_COMMON_H_ +#ifndef DOCK_PLANNER_UTILS_CURVE_COMMON_H_ +#define DOCK_PLANNER_UTILS_CURVE_COMMON_H_ + +#include #include -#include #include -#include -#include "color.h" -#include +namespace dock_planner +{ + +/** + * @brief State for evaluating one clamped B-spline/NURBS curve. + * + * N_double_vec is scratch space reused by CalculateCurvePoint; it is not part + * of the curve definition and holds the basis values of the last evaluation. + */ struct Spline_Inf { - int order; + int order = 0; std::vector knot_vector; std::vector weight; - //std::vector N; - - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - std::vector > control_point; - std::vector > N; - std::vector > dN; - std::vector > ddN; + std::vector> control_point; std::vector N_double_vec; - std::vector R_double_vec; - std::vector dR_double_vec; - std::vector ddR_double_vec; - // std::vector ddN_double_vec; - //Eigen::Matrix N; //bsaic function - Eigen::MatrixXd curvefit_N; - -}; - -struct EigenTrajectoryPoint -{ - typedef std::vector > Vector; - double u_data; - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - Eigen::Vector3d position; - //Eigen::VectorXd u_data; }; +/** + * @brief Minimal NURBS evaluation used by DockCalc. + * + * Only curve setup, validity checking, and point evaluation are provided. + * Derivatives, curvature, and visualization helpers were removed together + * with the code paths that used them. + */ class CurveCommon { public: CurveCommon(); - robot_nav_msgs::Path Generate_Line(robot_geometry_msgs::Point start_point, robot_geometry_msgs::Point end_point, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_BezierCurve(EigenTrajectoryPoint::Vector control_point, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_BsplineCurve(Spline_Inf bspline_inf, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_NURBSCurve(Spline_Inf spline_inf, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_DerivativeBsplineCurve(Spline_Inf bspline_inf, int differential_times, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_DerivativeBasisFuncCurve(Spline_Inf bspline_inf, int differential_times, int index, double t_intervel, std::string frame_id); - void CalculateDerivativeBasisFunc(Spline_Inf* spline_inf, double u_data, int differential_times); - robot_geometry_msgs::Point CalculateDerivativeCurvePoint(Spline_Inf* spline_inf, double u_data, int differential_times, bool UsingNURBS); - robot_geometry_msgs::Point CalculateCurvePoint(Spline_Inf* spline_inf, double u_data, bool UsingNURBS); - double CalculateCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateSignedCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - Eigen::Vector3d CalculateCurvatureDirectionVector(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateCurvatureRadius(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateCurveLength(Spline_Inf spline_inf, double start_u, double end_u, int sub_intervals, bool UsingNURBS); + /** Check degree and the knot/control-point count relation. */ bool curveIsValid(int degree, const std::vector& knot_vector, - std::vector>& control_points); + const std::vector>& control_points); - void ReadSplineInf(Spline_Inf* bspline_inf, int order, std::vector > control_point, std::vector knot_vector); - void ReadSplineInf(Spline_Inf* bspline_inf, std::vector weight_vector, bool use_limit_derivative_fitting); - void ReadDiscreate2DPointFromLaunch(EigenTrajectoryPoint::Vector* input_point, std::vector file_discreate_point); - void ReadDiscreate2DPointFromLaunch(std::vector >* input_point, std::vector file_discreate_point); - void ShowDiscreatePoint(robot_visualization_msgs::Marker* points, EigenTrajectoryPoint::Vector discreate_point); - void ShowDiscreatePoint(robot_visualization_msgs::Marker* points, std::vector > discreate_point); - - //TODO: move relate visualize function to new vislization.h - int print(); - robot_visualization_msgs::Marker ShowDiscreatePoint(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint2(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint(std::vector > discreate_point, const std::string& frame_id, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint2(std::vector > discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale); -private: + /** Store order, knot vector, and control points into spline_inf. */ + void ReadSplineInf(Spline_Inf* spline_inf, int order, + const std::vector>& control_point, + const std::vector& knot_vector); + /** Store the NURBS weights; must be called after the control points. */ + void ReadSplineInf(Spline_Inf* spline_inf, const std::vector& weight_vector, + bool use_limit_derivative_fitting); + /** + * Evaluate the curve at parameter u_data in [0, 1]. Returns a NaN point on + * invalid input (null/empty spline, non-finite u, degenerate denominator). + */ + robot_geometry_msgs::Point CalculateCurvePoint(Spline_Inf* spline_inf, double u_data, + bool UsingNURBS); }; -#endif //CURVE_COMMON_H_ \ No newline at end of file +} // namespace dock_planner + +#endif // DOCK_PLANNER_UTILS_CURVE_COMMON_H_ diff --git a/package.xml b/package.xml index c9f0c9c..cacfce9 100644 --- a/package.xml +++ b/package.xml @@ -1,58 +1,19 @@ - + + dock_planner - 0.7.10 - - dock_planner is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. dock_planner - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote + 0.7.11 + Global planner that generates a quadratic NURBS approach path for docking. + duongtd BSD - http://www.ros.org/wiki/dock_planner - - catkin + catkin - robot_costmap_2d - robot_costmap_2d + robot_costmap_2d + robot_nav_core + robot_geometry_msgs + robot_cpp + robot_time + data_convert + yaml-cpp - robot_nav_core - robot_nav_core - - robot_geometry_msgs - robot_geometry_msgs - - robot_nav_msgs - robot_nav_msgs - - robot_std_msgs - robot_std_msgs - - - - - robot_cpp - robot_cpp - - robot_time - robot_time - - robot_visualization_msgs - robot_visualization_msgs - - data_convert - data_convert - - robot_nav_2d_msgs - robot_nav_2d_msgs - - robot_nav_2d_utils - robot_nav_2d_utils - - \ No newline at end of file + diff --git a/src/dock_calc.cpp b/src/dock_calc.cpp index 8e197d0..61f6384 100644 --- a/src/dock_calc.cpp +++ b/src/dock_calc.cpp @@ -1,683 +1,668 @@ #include "dock_planner/dock_calc.h" +#include +#include +#include +#include + +#include +#include + namespace dock_planner { - DockCalc::DockCalc() - : input_spline_inf(std::make_unique()), - CurveDesign(std::make_unique()), - check_goal_(false), - store_start_nearest_idx_(0), - start_target_idx_(0), - min_distance_to_goal_(0.0), - costmap_(nullptr), - cost_threshold_(200), - safety_distance_(0.0), - calib_safety_distance_(0.0) +namespace +{ + +constexpr double kEpsilon = 1e-9; + +bool finitePoint(const robot_geometry_msgs::Point& point) +{ + return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z); +} + +void appendUnique(std::vector& output, + const robot_geometry_msgs::Pose& pose) +{ + if (output.empty() || + std::hypot(output.back().position.x - pose.position.x, + output.back().position.y - pose.position.y) > kEpsilon) { + output.push_back(pose); + } +} + +} // namespace + +DockCalc::DockCalc() + : input_spline_inf_(std::make_unique()), + curve_design_(std::make_unique()) +{ +} + +DockCalc::DockCalc(const DockPlannerConfig& config) + : input_spline_inf_(std::make_unique()), + curve_design_(std::make_unique()), + config_(config) +{ +} + +DockCalc::~DockCalc() = default; + +void DockCalc::setConfig(const DockPlannerConfig& config) +{ + std::lock_guard lock(calculation_mutex_); + config_ = config; +} + +double DockCalc::distance(const robot_geometry_msgs::Pose& first, + const robot_geometry_msgs::Pose& second) +{ + return std::hypot(first.position.x - second.position.x, + first.position.y - second.position.y); +} + +double DockCalc::angleBetweenPoints(double x1, double y1, double x2, double y2) +{ + return std::atan2(y2 - y1, x2 - x1); +} + +double DockCalc::normalizeAngle(double angle) +{ + return std::remainder(angle, 2.0 * kPi); +} + +bool DockCalc::isFinitePose(const robot_geometry_msgs::Pose& pose) +{ + const auto& q = pose.orientation; + const double quaternion_norm = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; + return finitePoint(pose.position) && std::isfinite(q.x) && std::isfinite(q.y) && + std::isfinite(q.z) && std::isfinite(q.w) && quaternion_norm > kEpsilon; +} + +RobotGeometry DockCalc::computeGeometry( + const std::vector& footprint) +{ + if (footprint.size() < 3) + { + return {}; } - DockCalc::~DockCalc() = default; + double min_x = std::numeric_limits::max(); + double max_x = std::numeric_limits::lowest(); + double min_y = std::numeric_limits::max(); + double max_y = std::numeric_limits::lowest(); - robot_geometry_msgs::Pose DockCalc::offsetPoint(const robot_geometry_msgs::Pose& A, const double& theta, const double& d) + for (const auto& point : footprint) { - robot_geometry_msgs::Pose B; - B.position.x = A.position.x + d * std::cos(theta); - B.position.y = A.position.y + d * std::sin(theta); - return B; - } - - double DockCalc::pointToSegmentDistance(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C) - { - double theta = signedAngle(A,B,C); - double sin_theta = sin(fabs(theta)); - double h = calc_distance(A,B); - double distance = sin_theta * h; - return distance; - } - - double DockCalc::signedAngle(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C) - { - double ABx = B.position.x - A.position.x; - double ABy = B.position.y - A.position.y; - - double CBx = B.position.x - C.position.x; - double CBy = B.position.y - C.position.y; - - double cross = ABx*CBy - ABy*CBx; - double dot = ABx*CBx + ABy*CBy; - - double angle = atan2(cross,dot); - return angle; - } - - double DockCalc::compute_t(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C) - { - constexpr double epsilon = 1e-6; - double dx = C.position.x - B.position.x; - double dy = C.position.y - B.position.y; - double bx = B.position.x - A.position.x; - double by = B.position.y - A.position.y; - - double numerator = dx * bx + dy * by; - double denominator = dx * dx + dy * dy; - - if (denominator <= epsilon) + if (!finitePoint(point)) { - throw std::runtime_error("B and C are the same!"); + return {}; } - - return -numerator / denominator; + min_x = std::min(min_x, point.x); + max_x = std::max(max_x, point.x); + min_y = std::min(min_y, point.y); + max_y = std::max(max_y, point.y); } - robot_geometry_msgs::Pose DockCalc::compute_D(const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C, const double& t) + RobotGeometry geometry; + geometry.length = max_x - min_x; + geometry.width = max_y - min_y; + geometry.front_extent = max_x; + geometry.rear_extent = -min_x; + return geometry; +} + +robot_geometry_msgs::Pose DockCalc::offsetPoint(const robot_geometry_msgs::Pose& pose, + double yaw, double offset) +{ + robot_geometry_msgs::Pose result = pose; + result.position.x += offset * std::cos(yaw); + result.position.y += offset * std::sin(yaw); + return result; +} + +double DockCalc::pointToLineDistance(const robot_geometry_msgs::Pose& point, + const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end) +{ + const double line_x = line_end.position.x - line_start.position.x; + const double line_y = line_end.position.y - line_start.position.y; + const double line_length = std::hypot(line_x, line_y); + if (line_length <= kEpsilon) { - robot_geometry_msgs::Pose D; - D.position.x = B.position.x + t * (C.position.x - B.position.x); - D.position.y = B.position.y + t * (C.position.y - B.position.y); - return D; + return std::numeric_limits::quiet_NaN(); } - void DockCalc::setupSpline(const std::vector& control_points, int degree) + const double point_x = point.position.x - line_start.position.x; + const double point_y = point.position.y - line_start.position.y; + return std::fabs(line_x * point_y - line_y * point_x) / line_length; +} + +double DockCalc::signedAngle(const robot_geometry_msgs::Pose& first, + const robot_geometry_msgs::Pose& vertex, + const robot_geometry_msgs::Pose& second) +{ + const double first_x = vertex.position.x - first.position.x; + const double first_y = vertex.position.y - first.position.y; + const double second_x = vertex.position.x - second.position.x; + const double second_y = vertex.position.y - second.position.y; + return std::atan2(first_x * second_y - first_y * second_x, + first_x * second_x + first_y * second_y); +} + +bool DockCalc::projectionRatio(const robot_geometry_msgs::Pose& point, + const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end, + double& ratio) +{ + const double line_x = line_end.position.x - line_start.position.x; + const double line_y = line_end.position.y - line_start.position.y; + const double denominator = line_x * line_x + line_y * line_y; + if (denominator <= kEpsilon) { - std::vector> eigen_points; - eigen_points.reserve(control_points.size()); - for (const auto& cp : control_points) - { - eigen_points.emplace_back(cp.position.x, cp.position.y, 0); - } - - const int n = static_cast(control_points.size()) - 1; - const int m = n + degree + 1; - std::vector knot_vector; - knot_vector.reserve(m + 1); - for (int i = 0; i <= m; i++) - { - knot_vector.push_back(i <= degree ? 0.0 : 1.0); - } - - std::vector weights(control_points.size(), 1.0); - - input_spline_inf->knot_vector.clear(); - input_spline_inf->control_point.clear(); - input_spline_inf->weight.clear(); - - CurveDesign->ReadSplineInf(input_spline_inf.get(), degree + 1, eigen_points, knot_vector); - CurveDesign->ReadSplineInf(input_spline_inf.get(), weights, false); + return false; } - RobotGeometry DockCalc::computeGeometry(const std::vector& fp) + ratio = ((point.position.x - line_start.position.x) * line_x + + (point.position.y - line_start.position.y) * line_y) / + denominator; + return std::isfinite(ratio); +} + +robot_geometry_msgs::Pose DockCalc::extrapolate( + const robot_geometry_msgs::Pose& line_start, + const robot_geometry_msgs::Pose& line_end, + double ratio) +{ + robot_geometry_msgs::Pose result = line_start; + result.position.x += ratio * (line_end.position.x - line_start.position.x); + result.position.y += ratio * (line_end.position.y - line_start.position.y); + return result; +} + +bool DockCalc::setupSpline(const std::vector& control_points) +{ + if (control_points.size() != static_cast(kNurbsDegree + 1)) { - if (fp.size() < 4) return {0, 0, 0}; - - double min_x = std::numeric_limits::max(); - double max_x = std::numeric_limits::lowest(); - double min_y = std::numeric_limits::max(); - double max_y = std::numeric_limits::lowest(); - double radius = 0.0; - - for (const auto& p : fp) - { - min_x = std::min(min_x, p.x); - max_x = std::max(max_x, p.x); - min_y = std::min(min_y, p.y); - max_y = std::max(max_y, p.y); - radius = std::max(radius, std::hypot(p.x, p.y)); - } - return {max_x - min_x, max_y - min_y, radius}; + robot::log_error("[dock_calc] A quadratic docking curve requires exactly three control points.\n"); + return false; } - bool DockCalc::makePlanMoveToDock(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - const std::vector& footprint_robot, - const std::vector& footprint_dock, - const int& degree, const double& step, - std::vector& planMoveToDock, - bool reverse) + std::vector> eigen_points; + eigen_points.reserve(control_points.size()); + for (const auto& control_point : control_points) { - constexpr double epsilon = 1e-6; - robot::log_info("[dock_calc] makePlanMoveToDock start: (%f, %f), goal: (%f, %f), goal frame id: %s", start.pose.position.x, start.pose.position.y, goal.pose.position.x, goal.pose.position.y, goal.header.frame_id.c_str()); - planMoveToDock.clear(); - - if(save_goal_.pose.position.x != goal.pose.position.x || - save_goal_.pose.position.y != goal.pose.position.y || - data_convert::getYaw(save_goal_.pose.orientation) != data_convert::getYaw(goal.pose.orientation)) + if (!finitePoint(control_point.position)) { - check_goal_ = true; - save_goal_ = goal; + robot::log_error("[dock_calc] NURBS control point contains NaN/Inf.\n"); + return false; } + eigen_points.emplace_back(control_point.position.x, control_point.position.y, 0.0); + } - footprint_robot_ = footprint_robot; - // Calculate footprint distances - RobotGeometry robot = computeGeometry(footprint_robot); - RobotGeometry dock = computeGeometry(footprint_dock); - double distance_robot = robot.length; - double distance_dock = dock.length; - if (distance_robot <= epsilon) + const std::vector knot_vector = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0}; + if (!curve_design_->curveIsValid(kNurbsDegree, knot_vector, eigen_points)) + { + return false; + } + + input_spline_inf_->knot_vector.clear(); + input_spline_inf_->control_point.clear(); + input_spline_inf_->weight.clear(); + curve_design_->ReadSplineInf(input_spline_inf_.get(), kNurbsDegree + 1, + eigen_points, knot_vector); + curve_design_->ReadSplineInf(input_spline_inf_.get(), + std::vector(control_points.size(), 1.0), false); + return input_spline_inf_->weight.size() == control_points.size(); +} + +double DockCalc::calculateNurbsLength(double sample_step) +{ + const int sample_count = std::max(2, static_cast(std::ceil(1.0 / sample_step))); + double length = 0.0; + robot_geometry_msgs::Point previous; + bool have_previous = false; + + for (int index = 0; index <= sample_count; ++index) + { + const double parameter = static_cast(index) / sample_count; + const auto current = curve_design_->CalculateCurvePoint(input_spline_inf_.get(), + parameter, true); + if (!finitePoint(current)) { - robot::log_error("[dock_calc] Robot geometry is invalid, cannot calculate plan to dock."); + robot::log_error( + "[dock_calc][diag] NURBS length sampling produced a non-finite point " + "at u=%.12g: point=(%.12g, %.12g, %.12g).\n", + parameter, current.x, current.y, current.z); + return std::numeric_limits::quiet_NaN(); + } + if (have_previous) + { + length += std::hypot(current.x - previous.x, current.y - previous.y); + } + previous = current; + have_previous = true; + } + return length; +} + +bool DockCalc::sampleCurve(const std::vector& control_points, + std::vector& path, + bool reverse_orientation) +{ + path.clear(); + if (!setupSpline(control_points)) + { + return false; + } + + const double curve_length = calculateNurbsLength(); + if (!std::isfinite(curve_length) || curve_length <= kEpsilon) + { + robot::log_error( + "[dock_calc][diag] NURBS curve has invalid or zero length: " + "length=%.12g m, epsilon=%.12g m, spacing=%.6f m, " + "cp0=(%.9f, %.9f), cp1=(%.9f, %.9f), cp2=(%.9f, %.9f).\n", + curve_length, kEpsilon, config_.path_point_spacing, + control_points[0].position.x, control_points[0].position.y, + control_points[1].position.x, control_points[1].position.y, + control_points[2].position.x, control_points[2].position.y); + return false; + } + + const int sample_count = std::max( + 2, static_cast(std::ceil(curve_length / config_.path_point_spacing))); + path.reserve(static_cast(sample_count + 1)); + for (int index = 0; index <= sample_count; ++index) + { + const double parameter = static_cast(index) / sample_count; + const auto point = curve_design_->CalculateCurvePoint(input_spline_inf_.get(), parameter, true); + if (!finitePoint(point)) + { + robot::log_error("[dock_calc] NURBS produced NaN/Inf at u=%f.\n", parameter); + path.clear(); return false; } - safety_distance_ = (robot.radius + calib_safety_distance_) * 2.0; - if (safety_distance_ <= epsilon) + robot_geometry_msgs::Pose pose; + pose.position = point; + pose.orientation = data_convert::createQuaternionMsgFromYaw(0.0); + appendUnique(path, pose); + } + + if (path.size() < 2) + { + path.clear(); + return false; + } + + for (std::size_t index = 0; index + 1 < path.size(); ++index) + { + const auto& current = path[index]; + const auto& next = path[index + 1]; + const double yaw = reverse_orientation + ? angleBetweenPoints(next.position.x, next.position.y, + current.position.x, current.position.y) + : angleBetweenPoints(current.position.x, current.position.y, + next.position.x, next.position.y); + path[index].orientation = data_convert::createQuaternionMsgFromYaw(yaw); + } + path.back().orientation = path[path.size() - 2].orientation; + return true; +} + +bool DockCalc::sampleTemporaryCurve( + const std::vector& control_points, + std::vector& path) +{ + return sampleCurve(control_points, path, false); +} + +bool DockCalc::findNurbsControlPoints( + int& direction, std::vector& control_points, + const robot_geometry_msgs::Pose& start_pose, + const std::vector& reference_path, + double angle_threshold) +{ + if (reference_path.empty()) + { + return false; + } + + std::size_t nearest_index = 0; + const int index = findNearestPointOnPath(direction, nearest_index, start_pose, + reference_path, angle_threshold); + auto poseAt = [](double x, double y) + { + robot_geometry_msgs::Pose pose; + pose.position.x = x; + pose.position.y = y; + pose.orientation = data_convert::createQuaternionMsgFromYaw(0.0); + return pose; + }; + + control_points.clear(); + if (index >= 0) + { + const std::size_t middle_index = static_cast(index); + control_points.push_back(start_pose); + control_points.push_back(poseAt(reference_path[middle_index].position.x, + reference_path[middle_index].position.y)); + const double target_distance = distance(start_pose, reference_path[middle_index]); + + if (direction == 1) { - robot::log_error("[dock_calc] Safety distance is zero, cannot calculate plan to dock."); - return false; - } - - // Lambda: Generate NURBS path - auto generateNURBSPath = [&](const std::vector& control_points, bool check_isFreeSpace, - bool edge_end_plag, bool path_reverse) -> std::vector - { - std::vector result; - bool obstacle_flag = false; - - setupSpline(control_points, degree); - - // Calculate adaptive step - double edge_length = calculateNURBSLength(CurveDesign.get(), input_spline_inf.get(), degree, step); - double resolution = costmap_->getResolution(); - double step_new = calculateAdaptiveStep(edge_length, resolution); - - std::vector saved_poses; - for (double t = 0.0; t <= 1.0; t += step_new) + std::size_t end_index = middle_index; + for (std::size_t candidate = middle_index;; --candidate) { - robot_geometry_msgs::Point point = CurveDesign->CalculateCurvePoint(input_spline_inf.get(), t, true); - - if (!std::isnan(point.x) && !std::isnan(point.y)) + if (distance(reference_path[middle_index], reference_path[candidate]) >= target_distance || + candidate == 0) { - robot_geometry_msgs::Pose pose; - pose.position = point; - pose.orientation = data_convert::createQuaternionMsgFromYaw(0.0); - - bool status_isFreeSpace = true; - if(edge_end_plag) - { - double distance_to_goal = calc_distance(pose, goal.pose); - if(distance_to_goal >= min_distance_to_goal_) - { - if(check_isFreeSpace) status_isFreeSpace = isFreeSpace(pose, footprint_robot_); - } - } - else - { - if(check_isFreeSpace) status_isFreeSpace = isFreeSpace(pose, footprint_robot_); - } - - if (status_isFreeSpace && t < 1.0) - { - saved_poses.push_back(pose); - if (saved_poses.size() > 1) - { - updatePoseOrientation(saved_poses, result, path_reverse); - } - } - if(!status_isFreeSpace) - { - obstacle_flag = true; - break; - } - } - } - - // Set final orientation - if (!saved_poses.empty()) - { - double end_yaw = path_reverse ? - calculateAngle(control_points.back().position.x, control_points.back().position.y, - saved_poses.back().position.x, saved_poses.back().position.y) : - calculateAngle(saved_poses.back().position.x, saved_poses.back().position.y, - control_points.back().position.x, control_points.back().position.y); - - tf3::Quaternion q; - q.setRPY(0, 0, end_yaw); - saved_poses.back().orientation.x = q.x(); - saved_poses.back().orientation.y = q.y(); - saved_poses.back().orientation.z = q.z(); - saved_poses.back().orientation.w = q.w(); - - result.push_back(saved_poses.back()); - } - if(obstacle_flag) - { - robot::log_error("[dock_calc] Obstacle detected, path generation interrupted."); - result.clear(); - } - if (result.empty()) - { - robot::log_error("[dock_calc] No valid path generated."); - } - else - { - robot::log_info("[dock_calc] Path generated with %zu points.", result.size()); - } - return result; - }; - - // Calculate minimum distance for pose C - double distance_min_for_pose_C = (distance_robot + distance_dock) / 2.0; - min_distance_to_goal_ = (safety_distance_ + distance_dock / 2.0); - - // Calculate pose C (offset from goal) - robot_geometry_msgs::Pose Goal_Pose = goal.pose; - double yaw_goal = normalizeAngle(data_convert::getYaw(goal.pose.orientation)); - robot_geometry_msgs::Pose Pose_C = offsetPoint(Goal_Pose, yaw_goal, distance_min_for_pose_C); - - // Compute t parameter and determine direction - double t = compute_t(start.pose, goal.pose, Pose_C); - /** - * dir_robot_move_to_goal = false robot move backward - * dir_robot_move_to_goal = true robot move forward - */ - bool dir_robot_move_to_goal = true; - - if (t < 0) - { - yaw_goal = (yaw_goal > 0) ? yaw_goal - M_PI : yaw_goal + M_PI; - Pose_C = offsetPoint(Goal_Pose, yaw_goal, distance_min_for_pose_C); - t = compute_t(start.pose, goal.pose, Pose_C); - dir_robot_move_to_goal = false; - } - - if (t <= 1) - { - robot::log_error("[dock_calc] t(%f) <= 1, cannot calculate plan to dock.", t); - return false; - } - - // Calculate pose D and distance AD - robot_geometry_msgs::Pose Pose_D = compute_D(goal.pose, Pose_C, t); - double distance_AD = pointToSegmentDistance(start.pose, goal.pose, Pose_C); - - // Angle threshold heuristic: linearly scale [MIN_DISTANCE..MAX_DISTANCE] of - // perpendicular distance AD into an angle in [alpha*beta*pi .. gamma*pi]. - // Closer to the line → larger angle threshold (more permissive turn). - constexpr double MAX_DISTANCE = 1.0; // distance at which scale = MIN_SCALE - constexpr double MIN_DISTANCE = 0.1; // distance at which scale = MAX_SCALE - constexpr double MIN_SCALE = 0.2; - constexpr double MAX_SCALE = 1.0; - constexpr double CALIB_FACTOR_ALPHA = 0.5; // base offset added to |scale| - constexpr double CALIB_FACTOR_BETA = 0.5; // multiplier applied to (alpha + |scale|) - constexpr double CALIB_FACTOR_GAMMA = 0.77; // upper clamp expressed as fraction of pi - - const double scale = MIN_SCALE + (MAX_SCALE - MIN_SCALE) * - (MAX_DISTANCE - distance_AD) / (MAX_DISTANCE - MIN_DISTANCE); - const double angle_threshold = std::min( - (CALIB_FACTOR_ALPHA + std::fabs(scale)) * CALIB_FACTOR_BETA * M_PI, - CALIB_FACTOR_GAMMA * M_PI); - - // Generate temporary path - double distance_CD = calc_distance(Pose_C, Pose_D); - double angle_alpha = (M_PI - angle_threshold) / 2.0; - double distance_DF = distance_AD / tan(angle_alpha); - double distance_min_for_pose_F = distance_min_for_pose_C + distance_CD + distance_DF; - - robot_geometry_msgs::Pose Pose_F = offsetPoint(Goal_Pose, yaw_goal, distance_min_for_pose_F); - robot_geometry_msgs::Pose mid_pose; - mid_pose.position.x = (Pose_C.position.x + Pose_F.position.x) / 2.0; - mid_pose.position.y = (Pose_C.position.y + Pose_F.position.y) / 2.0; - - std::vector control_points_tmp = {Pose_C, mid_pose, Pose_F}; - std::vector saved_poses_tmp; - - - if (!findPathTMP(control_points_tmp, saved_poses_tmp, degree, step)) - { - robot::log_error("[dock_calc] Failed to find path with temporary control points."); - return false; - } - - // Find first segment control points - int dir; - std::vector control_points_1; - if (!findNURBSControlPoints(dir, control_points_1, start.pose, saved_poses_tmp, angle_threshold, degree)) - { - robot::log_error("[dock_calc] Failed to find NURBS control points for first segment."); - return false; - } - - // Determine reverse direction for first segment - bool first_segment_reverse = (dir == -1 && !dir_robot_move_to_goal) || - ((dir == 1 || dir == 0) && dir_robot_move_to_goal); - - // Generate first segment - std::vector first_segment = generateNURBSPath(control_points_1, true, false, first_segment_reverse); - if (first_segment.empty()) return false; - - // Generate second segment (to goal) - robot_geometry_msgs::Pose mid_control_point; - mid_control_point.position.x = (first_segment.back().position.x + goal.pose.position.x) / 2.0; - mid_control_point.position.y = (first_segment.back().position.y + goal.pose.position.y) / 2.0; - - std::vector control_points_2 = {first_segment.back(), - mid_control_point, - goal.pose}; - - std::vector second_segment = generateNURBSPath(control_points_2, true, true, dir_robot_move_to_goal); - - // Assemble final path: start + first_segment + second_segment + goal - planMoveToDock.reserve(1 + first_segment.size() + second_segment.size() + 1); - planMoveToDock.push_back(start.pose); - planMoveToDock.insert(planMoveToDock.end(), first_segment.begin(), first_segment.end()); - planMoveToDock.insert(planMoveToDock.end(), second_segment.begin(), second_segment.end()); - planMoveToDock.push_back(goal.pose); - - return true; - } - - bool DockCalc::findPathTMP(const std::vector& control_points, - std::vector& saved_poses, - const int& degree, double step) - { - setupSpline(control_points, degree); - - for(double t = 0.0; t <= 1.0; t += step) - { - robot_geometry_msgs::Point point = CurveDesign->CalculateCurvePoint(input_spline_inf.get(), t, true); - if(!std::isnan(point.x) && !std::isnan(point.y)) - { - robot_geometry_msgs::Pose pose; - pose.position = point; - pose.orientation.x = 0.0; - pose.orientation.y = 0.0; - pose.orientation.z = 0.0; - pose.orientation.w = 1.0; - - bool status_isFreeSpace = isFreeSpace(pose, footprint_robot_); - if(status_isFreeSpace) - { - saved_poses.push_back(pose); - } - else - { - robot::log_error("[dock_calc][findPathTMP] Obstacle detected at t(%f)", t); + end_index = candidate; break; } } - else - { - robot::log_error("[dock_calc][findPathTMP] NaN point at t(%f)", t); - } + control_points.push_back(poseAt(reference_path[end_index].position.x, + reference_path[end_index].position.y)); } - if(saved_poses.empty()) + else if (direction == -1) { - robot::log_error("[dock_calc][findPathTMP] No valid poses generated."); - return false; + control_points.push_back(poseAt(reference_path.back().position.x, + reference_path.back().position.y)); } - return true; } - void DockCalc::updatePoseOrientation(std::vector& saved_poses, - std::vector& nurbs_path, - bool reverse) + if (control_points.size() != 3) { - auto& prev = saved_poses[saved_poses.size() - 2]; - const auto& curr = saved_poses.back(); - - const double yaw = reverse - ? calculateAngle(curr.position.x, curr.position.y, prev.position.x, prev.position.y) - : calculateAngle(prev.position.x, prev.position.y, curr.position.x, curr.position.y); - - tf3::Quaternion q; - q.setRPY(0, 0, yaw); - prev.orientation.x = q.x(); - prev.orientation.y = q.y(); - prev.orientation.z = q.z(); - prev.orientation.w = q.w(); - - nurbs_path.push_back(prev); - } - - double DockCalc::calculateNURBSLength(CurveCommon* curve_design, - Spline_Inf* spline_inf, - int degree, - double initial_step) - { - double length = 0.0; - robot_geometry_msgs::Point prev_point, curr_point; - - const double step = (degree == 1) ? 0.1 : initial_step; - - for(double u = 0; u <= 1; u += step) - { - curr_point = curve_design->CalculateCurvePoint(spline_inf, u, true); - - if(u > 0 && !std::isnan(curr_point.x) && !std::isnan(curr_point.y)) - { - length += std::hypot(curr_point.x - prev_point.x, - curr_point.y - prev_point.y); - } - prev_point = curr_point; - } - return length; - } - - bool DockCalc::findNURBSControlPoints(int& dir, std::vector& control_points, - const robot_geometry_msgs::Pose& start_pose, - const std::vector& saved_poses, - const double& angle_threshold, const int& degree) - { - if (saved_poses.empty()) - { - robot::log_error("[dock_calc] No saved poses available to find NURBS control points."); - return false; - } - + const auto& nearest = reference_path[nearest_index]; control_points.clear(); - int idx = findNearestPointOnPath(dir, start_pose, saved_poses, angle_threshold); - - auto createPose = [](double x, double y) -> robot_geometry_msgs::Pose - { - robot_geometry_msgs::Pose pose; - pose.position.x = x; - pose.position.y = y; - pose.orientation = data_convert::createQuaternionMsgFromYaw(0); - return pose; - }; - - if (idx != -1) - { - start_target_idx_ = idx; - - // Add start and middle poses - control_points.push_back(start_pose); - control_points.push_back(createPose(saved_poses[idx].position.x, saved_poses[idx].position.y)); - - // Calculate distance from start to middle point - double dx = start_pose.position.x - saved_poses[idx].position.x; - double dy = start_pose.position.y - saved_poses[idx].position.y; - double target_distance = std::hypot(dx, dy); - - if (dir == 1) - { - // Find appropriate end point going backwards - int end_idx = idx; - const auto& mid_pose = control_points[1]; - - for (int i = idx; i >= 0; i--) - { - double dx_me = mid_pose.position.x - saved_poses[i].position.x; - double dy_me = mid_pose.position.y - saved_poses[i].position.y; - double dist_me = std::hypot(dx_me, dy_me); - - if (dist_me >= target_distance || i == 0) - { - end_idx = i; - break; - } - } - - control_points.push_back(createPose(saved_poses[end_idx].position.x, saved_poses[end_idx].position.y)); - start_target_idx_ = end_idx; - } - else if (dir == -1) - { - const auto& last_pose = saved_poses.back(); - control_points.push_back(createPose(last_pose.position.x, last_pose.position.y)); - start_target_idx_ = saved_poses.size() - 1; - } - - } - else - { - const auto& nearest_pose = saved_poses[store_start_nearest_idx_]; - auto mid_pose = createPose( - (start_pose.position.x + nearest_pose.position.x) / 2.0, - (start_pose.position.y + nearest_pose.position.y) / 2.0 - ); - - control_points.push_back(start_pose); - control_points.push_back(mid_pose); - control_points.push_back(nearest_pose); - start_target_idx_ = store_start_nearest_idx_; - } - - return true; + control_points.push_back(start_pose); + control_points.push_back(poseAt((start_pose.position.x + nearest.position.x) / 2.0, + (start_pose.position.y + nearest.position.y) / 2.0)); + control_points.push_back(nearest); + direction = 0; } - int DockCalc::findNearestPointOnPath(int& dir, const robot_geometry_msgs::Pose& pose, - const std::vector& saved_poses, - const double& angle_threshol) + return distance(control_points[0], control_points[1]) > kEpsilon && + distance(control_points[1], control_points[2]) > kEpsilon; +} + +int DockCalc::findNearestPointOnPath( + int& direction, std::size_t& nearest_index, + const robot_geometry_msgs::Pose& pose, + const std::vector& path, + double angle_threshold) const +{ + direction = 0; + nearest_index = 0; + if (path.size() < 2) { - // Tìm điểm gần nhất - int nearest_idx = 0; - double min_dist = std::numeric_limits::max(); - for (int i = 0; i < (int)saved_poses.size(); ++i) - { - double distance = std::hypot(saved_poses[i].position.x - pose.position.x, saved_poses[i].position.y - pose.position.y); + return -1; + } - if (distance < min_dist) - { - min_dist = distance; - nearest_idx = i; - } + double min_distance = std::numeric_limits::max(); + for (std::size_t index = 0; index < path.size(); ++index) + { + const double candidate = distance(path[index], pose); + if (candidate < min_distance) + { + min_distance = candidate; + nearest_index = index; } + } - // Lưu chỉ mục của điểm gần nhất - store_start_nearest_idx_ = nearest_idx; - bool found_pose_flag_1 = false; - bool found_pose_flag_2 = false; - - for(int i = store_start_nearest_idx_; i >= 1; i--) + for (std::size_t index = nearest_index; index >= 1; --index) + { + if (std::fabs(signedAngle(pose, path[index], path[index - 1])) >= + std::fabs(angle_threshold)) { - double angle = signedAngle(pose, saved_poses[i], saved_poses[i - 1]); - - if(fabs(angle) >= fabs(angle_threshol)) + const double pose_distance = distance(pose, path[index]); + const double prefix_distance = distance(path.front(), path[index]); + if (prefix_distance >= pose_distance) { - nearest_idx = i; - found_pose_flag_1 = true; - break; + direction = 1; + return static_cast(index); } + break; } + } - double distance_1 = calc_distance(pose,saved_poses[nearest_idx]); - double distance_2 = calc_distance(saved_poses[0],saved_poses[nearest_idx]); - if(found_pose_flag_1 && (distance_2 >= distance_1)) + const double forward_threshold = std::max( + 0.0, std::fabs(angle_threshold) - config_.direction_angle_hysteresis); + for (std::size_t index = nearest_index; index + 1 < path.size(); ++index) + { + if (std::fabs(signedAngle(pose, path[index], path[index + 1])) >= forward_threshold) { - found_pose_flag_2 = true; - dir = 1; - } - - if(!found_pose_flag_2) - { - const int last_idx = (int)saved_poses.size() - 1; - for(int i = store_start_nearest_idx_; i < last_idx; i++) + const double pose_distance = distance(pose, path[index]); + const double suffix_distance = distance(path[index], path.back()); + if (suffix_distance + config_.direction_distance_tolerance < pose_distance) { - double angle = signedAngle(pose, saved_poses[i], saved_poses[i + 1]); - - if(fabs(angle) >= (fabs(angle_threshol) - 0.05)) - { - nearest_idx = i; - dir = -1; - break; - } - if(i == last_idx - 1) - { - dir = 0; - return -1; - } - } - double distance_1 = calc_distance(pose,saved_poses[nearest_idx]); - double distance_2 = calc_distance(saved_poses[nearest_idx],saved_poses.back()); - if(distance_2 + 0.1 < distance_1) - { - dir = 0; return -1; } + direction = -1; + return static_cast(index); } - - return nearest_idx; + } + return -1; +} + +bool DockCalc::makePlanMoveToDock( + const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + const std::vector& footprint_robot, + const std::vector& footprint_dock, + std::vector& plan) +{ + std::lock_guard lock(calculation_mutex_); + plan.clear(); + std::string config_error; + if (!config_.validate(config_error)) + { + robot::log_error("[dock_calc] Invalid planner configuration: %s.\n", + config_error.c_str()); + return false; + } + if (!isFinitePose(start.pose) || !isFinitePose(goal.pose)) + { + robot::log_error("[dock_calc] Start or goal pose contains NaN/Inf or an invalid quaternion.\n"); + return false; } - bool DockCalc::isFreeSpace(const robot_geometry_msgs::Pose& pose, - const std::vector& footprint) + const RobotGeometry robot = computeGeometry(footprint_robot); + if (robot.length <= kEpsilon || robot.width <= kEpsilon) { - // TODO: implement obstacle checking using costmap_ - return true; + robot::log_error("[dock_calc] Robot footprint is missing or geometrically invalid.\n"); + return false; } - std::vector DockCalc::calcFreeZone(const robot_geometry_msgs::Pose& pose, - const std::vector& footprint) + // With dock_anchor == kFace the goal already sits on the approach face, so + // the dock never contributes to the approach distance and footprint_dock + // is ignored entirely. + RobotGeometry dock; + if (config_.dock_anchor == DockAnchor::kCenter && !footprint_dock.empty()) { - // Dịch sang tọa độ tuyệt đối - std::vector free_zone; - double cos_th = std::cos(data_convert::getYaw(pose.orientation)); - double sin_th = std::sin(data_convert::getYaw(pose.orientation)); - for (auto pt : footprint) + dock = computeGeometry(footprint_dock); + if (dock.length <= kEpsilon || dock.width <= kEpsilon) { - pt.x *= 1.2; - pt.y *= 1.2; - - robot_geometry_msgs::Point abs_pt; - abs_pt.x = pose.position.x + pt.x * cos_th - pt.y * sin_th; - abs_pt.y = pose.position.y + pt.x * sin_th + pt.y * cos_th; - free_zone.push_back(abs_pt); - } - return free_zone; - } - - std::vector DockCalc::interpolateFootprint(const robot_geometry_msgs::Pose& pose, - const std::vector& footprint, const double& resolution) - { - - // Dịch sang tọa độ tuyệt đối - std::vector abs_footprint; - double cos_th = std::cos(data_convert::getYaw(pose.orientation)); - double sin_th = std::sin(data_convert::getYaw(pose.orientation)); - for (auto pt : footprint) - { - pt.x *= 1.1; - pt.y *= 1.1; - robot_geometry_msgs::Point abs_pt; - abs_pt.x = pose.position.x + pt.x * cos_th - pt.y * sin_th; - abs_pt.y = pose.position.y + pt.x * sin_th + pt.y * cos_th; - abs_footprint.push_back(abs_pt); - } - - std::vector points; - const size_t fp_size = abs_footprint.size(); - for (size_t i = 0; i < fp_size; ++i) - { - const robot_geometry_msgs::Point &start = abs_footprint[i]; - const robot_geometry_msgs::Point &end = abs_footprint[(i + 1) % fp_size]; - - double dx = end.x - start.x; - double dy = end.y - start.y; - double distance = std::hypot(dx, dy); - int steps = std::max(1, static_cast(std::floor(distance / resolution))); - - for (int j = 0; j <= steps; ++j) - { - if (j == steps && i != fp_size - 1) - continue; // tránh lặp điểm chung giữa 2 cạnh liên tiếp - double t = static_cast(j) / steps; - robot_geometry_msgs::Point pt; - pt.x = start.x + t * dx; - pt.y = start.y + t * dy; - points.push_back(pt); + robot::log_error("[dock_calc] Dock footprint is geometrically invalid.\n"); + return false; } } - return points; + + // Select the approach side from the goal orientation first: which side the + // start lies on decides the driving direction of the final segment, and + // therefore which robot/dock extents lead. The sign of the projection does + // not depend on the probe length. + double goal_yaw = normalizeAngle(data_convert::getYaw(goal.pose.orientation)); + double side_ratio = 0.0; + if (!projectionRatio(start.pose, goal.pose, offsetPoint(goal.pose, goal_yaw, 1.0), + side_ratio)) + { + robot::log_error("[dock_calc] Goal orientation is degenerate.\n"); + return false; + } + bool goal_side_forward = true; + if (side_ratio < 0.0) + { + goal_yaw = normalizeAngle(goal_yaw + kPi); + goal_side_forward = false; } -} \ No newline at end of file + // goal_side_forward == true means the final segment is driven backward + // (path orientations reversed in sampleCurve), so the robot's rear edge + // leads; forward approaches lead with the front edge. The dock's near face + // is the one on the approach side of the goal frame. + const double robot_extent = goal_side_forward ? robot.rear_extent : robot.front_extent; + const double dock_extent = goal_side_forward ? dock.front_extent : dock.rear_extent; + const double alignment_distance = + robot_extent + dock_extent + config_.alignment_distance_padding; + if (!std::isfinite(alignment_distance) || alignment_distance <= kEpsilon) + { + robot::log_error( + "[dock_calc] Alignment distance is not positive (robot_extent=%.3f m, " + "dock_extent=%.3f m, padding=%.3f m); check footprints and dock_anchor.\n", + robot_extent, dock_extent, config_.alignment_distance_padding); + return false; + } + + const robot_geometry_msgs::Pose alignment_pose = + offsetPoint(goal.pose, goal_yaw, alignment_distance); + double projection_ratio = 0.0; + if (!projectionRatio(start.pose, goal.pose, alignment_pose, projection_ratio)) + { + robot::log_error("[dock_calc] Goal and alignment pose are degenerate.\n"); + return false; + } + + if (projection_ratio <= 1.0) + { + robot::log_error("[dock_calc] Start is too close to the dock axis (projection=%f).\n", + projection_ratio); + return false; + } + + const auto projected_pose = extrapolate(goal.pose, alignment_pose, projection_ratio); + const double lateral_distance = pointToLineDistance(start.pose, goal.pose, alignment_pose); + const double angle_threshold = config_.angleThreshold(lateral_distance); + if (!std::isfinite(lateral_distance) || !std::isfinite(angle_threshold)) + { + return false; + } + + const double half_complement = (kPi - angle_threshold) / 2.0; + const double tangent = std::tan(half_complement); + if (!std::isfinite(tangent) || std::fabs(tangent) <= kEpsilon) + { + return false; + } + + const double projected_distance = distance(alignment_pose, projected_pose); + const double lateral_extension = lateral_distance / tangent; + const double reference_distance = alignment_distance + projected_distance + lateral_extension; + if (!std::isfinite(reference_distance)) + { + return false; + } + + const auto reference_end = offsetPoint(goal.pose, goal_yaw, reference_distance); + robot_geometry_msgs::Pose reference_mid = alignment_pose; + reference_mid.position.x = (alignment_pose.position.x + reference_end.position.x) / 2.0; + reference_mid.position.y = (alignment_pose.position.y + reference_end.position.y) / 2.0; + + std::vector reference_path; + if (!sampleTemporaryCurve({alignment_pose, reference_mid, reference_end}, reference_path)) + { + robot::log_error( + "[dock_calc][diag] Failed to generate approach reference curve: " + "start=(%.9f, %.9f, yaw=%.9f), goal=(%.9f, %.9f, yaw=%.9f), " + "robot=(front=%.3f m, rear=%.3f m, width=%.3f m), " + "dock=(front=%.3f m, rear=%.3f m, anchor=%s), padding=%.6f m, " + "alignment_distance=%.9f m, alignment=(%.9f, %.9f), " + "projection_ratio=%.12g, goal_side=%s, projected=(%.9f, %.9f), " + "projected_distance=%.12g m, lateral_distance=%.12g m, " + "angle_threshold=%.12g rad, lateral_extension=%.12g m, " + "reference_distance=%.12g m, reference_end=(%.9f, %.9f).\n", + start.pose.position.x, start.pose.position.y, + data_convert::getYaw(start.pose.orientation), + goal.pose.position.x, goal.pose.position.y, + data_convert::getYaw(goal.pose.orientation), + robot.front_extent, robot.rear_extent, robot.width, + dock.front_extent, dock.rear_extent, + config_.dock_anchor == DockAnchor::kFace ? "face" : "center", + config_.alignment_distance_padding, alignment_distance, + alignment_pose.position.x, alignment_pose.position.y, + projection_ratio, goal_side_forward ? "forward" : "backward", + projected_pose.position.x, projected_pose.position.y, + projected_distance, lateral_distance, angle_threshold, + lateral_extension, reference_distance, + reference_end.position.x, reference_end.position.y); + return false; + } + + int direction = 0; + std::vector first_control_points; + if (!findNurbsControlPoints(direction, first_control_points, start.pose, + reference_path, angle_threshold)) + { + robot::log_error("[dock_calc] Failed to select first-segment control points.\n"); + return false; + } + + const bool first_reverse_orientation = + (direction == -1 && !goal_side_forward) || + ((direction == 1 || direction == 0) && goal_side_forward); + std::vector first_segment; + if (!sampleCurve(first_control_points, first_segment, first_reverse_orientation)) + { + return false; + } + + robot_geometry_msgs::Pose second_mid = first_segment.back(); + second_mid.position.x = (first_segment.back().position.x + goal.pose.position.x) / 2.0; + second_mid.position.y = (first_segment.back().position.y + goal.pose.position.y) / 2.0; + + std::vector second_segment; + if (!sampleCurve({first_segment.back(), second_mid, goal.pose}, second_segment, + goal_side_forward)) + { + robot::log_error("[dock_calc] Failed to generate the final docking segment.\n"); + return false; + } + + plan.reserve(1 + first_segment.size() + second_segment.size()); + appendUnique(plan, start.pose); + for (const auto& pose : first_segment) + { + appendUnique(plan, pose); + } + for (const auto& pose : second_segment) + { + appendUnique(plan, pose); + } + + if (distance(plan.back(), goal.pose) <= kEpsilon) + { + plan.back() = goal.pose; + } + else + { + plan.push_back(goal.pose); + } + + if (plan.size() < 2) + { + plan.clear(); + return false; + } + + // Preserve the exact requested start position, but use the generated + // segment orientation. Keeping start.pose.orientation here would inject + // the robot's current yaw into the path and could make the controller + // classify the first segment with the wrong driving direction. + plan.front().orientation = first_segment.front().orientation; + + robot::log_info("[dock_calc] Generated docking path with %zu unique poses.\n", plan.size()); + return true; +} + +} // namespace dock_planner diff --git a/src/dock_planner.cpp b/src/dock_planner.cpp index b1db3f0..ebc6107 100644 --- a/src/dock_planner.cpp +++ b/src/dock_planner.cpp @@ -1,124 +1,217 @@ #include "dock_planner/dock_planner.h" -#include + #include +#include +#include + #include +#include -namespace dock_planner +namespace dock_planner +{ +namespace { - /** - * @brief Constructor mặc định - * Khởi tạo tất cả các pointer về nullptr và trạng thái chưa initialized - */ - DockPlanner::DockPlanner() : costmap_robot_(nullptr), - costmap_(nullptr), - initialized_(false), - cost_threshold_(200), - calib_safety_distance_(0.0), - check_free_space_(false) {} - /** - * @brief Constructor với parameters - * @param name Tên của planner - * @param costmap_robot Pointer tới costmap ROS wrapper - * Tự động gọi initialize() nếu được cung cấp costmap - */ - DockPlanner::DockPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) - : costmap_robot_(nullptr), - costmap_(nullptr), - initialized_(false), - cost_threshold_(200), - calib_safety_distance_(0.0), - check_free_space_(false) +enum class FootprintLoadStatus +{ + kMissing, + kValid, + kInvalid, +}; + +FootprintLoadStatus loadDockFootprint( + const robot::NodeHandle& nh, const std::string& planner_name, + std::vector& footprint) +{ + footprint.clear(); + YAML::Node node; + if (!nh.getParam("footprint_dock", node) || !node.IsDefined()) { - initialize(name, costmap_robot); + return FootprintLoadStatus::kMissing; + } + if (!node.IsSequence() || node.size() < 3) + { + robot::log_error("[dock_planner] '%s/footprint_dock' must contain at least three [x, y] points.\n", + planner_name.c_str()); + return FootprintLoadStatus::kInvalid; } - /** - * @brief Khởi tạo global planner - * @param name Tên của planner instance - * @param costmap_robot Pointer tới costmap ROS wrapper - * - * Thiết lập: - * - Liên kết với costmap - * - Tạo publisher cho visualization - * - Load parameters từ ROS parameter server - * - Đánh dấu trạng thái initialized - */ - bool DockPlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) + footprint.reserve(node.size()); + for (std::size_t index = 0; index < node.size(); ++index) { - if (!initialized_) + const YAML::Node& point_node = node[index]; + if (!point_node.IsSequence() || point_node.size() != 2) { - costmap_robot_ = costmap_robot; - costmap_ = costmap_robot_->getCostmap(); - frame_id_ = costmap_robot_->getGlobalFrameID(); - calc_plan_to_dock_.costmap_ = costmap_robot_->getCostmap(); - - robot::NodeHandle private_nh("~/" + name); - - // Load parameters from the private namespace - private_nh.getParam("check_free_space", check_free_space_); - private_nh.getParam("cost_threshold", cost_threshold_); - private_nh.getParam("calib_safety_distance", calib_safety_distance_); - - calc_plan_to_dock_.cost_threshold_ = cost_threshold_; - calc_plan_to_dock_.calib_safety_distance_ = calib_safety_distance_; - - - robot_nav_2d_msgs::Polygon2D footprint_dock = robot_nav_2d_utils::footprintFromParams(private_nh, false); - - for(auto pt : footprint_dock.points) - { - robot_geometry_msgs::Point footprint_point; - footprint_point.x = pt.x; - footprint_point.y = pt.y; - footprint_point.z = 0.0; - footprint_dock_.push_back(footprint_point); - } - - initialized_ = true; + robot::log_error("[dock_planner] '%s/footprint_dock[%zu]' must be exactly [x, y].\n", + planner_name.c_str(), index); + footprint.clear(); + return FootprintLoadStatus::kInvalid; } + + robot_geometry_msgs::Point point; + try + { + point.x = point_node[0].as(); + point.y = point_node[1].as(); + } + catch (const YAML::Exception& exception) + { + robot::log_error("[dock_planner] '%s/footprint_dock[%zu]' is not numeric: %s\n", + planner_name.c_str(), index, exception.what()); + footprint.clear(); + return FootprintLoadStatus::kInvalid; + } + + if (!std::isfinite(point.x) || !std::isfinite(point.y)) + { + robot::log_error("[dock_planner] '%s/footprint_dock[%zu]' contains NaN/Inf.\n", + planner_name.c_str(), index); + footprint.clear(); + return FootprintLoadStatus::kInvalid; + } + point.z = 0.0; + footprint.push_back(point); + } + + const auto minmax_x = std::minmax_element( + footprint.begin(), footprint.end(), + [](const auto& first, const auto& second) { return first.x < second.x; }); + const auto minmax_y = std::minmax_element( + footprint.begin(), footprint.end(), + [](const auto& first, const auto& second) { return first.y < second.y; }); + if (minmax_x.second->x - minmax_x.first->x <= 1e-9 || + minmax_y.second->y - minmax_y.first->y <= 1e-9) + { + robot::log_error("[dock_planner] '%s/footprint_dock' has zero X or Y extent.\n", + planner_name.c_str()); + footprint.clear(); + return FootprintLoadStatus::kInvalid; + } + return FootprintLoadStatus::kValid; +} + +} // namespace + +DockPlanner::DockPlanner() = default; + +bool DockPlanner::initialize(std::string name, + robot_costmap_2d::Costmap2DROBOT* costmap_robot) +{ + if (initialized_) + { return true; } - - bool DockPlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - std::vector& plan) + if (name.empty()) { - if(!initialized_) return false; - plan.clear(); + robot::log_error("[dock_planner] Cannot initialize with an empty plugin name.\n"); + return false; + } + if (costmap_robot == nullptr || costmap_robot->getCostmap() == nullptr) + { + robot::log_error("[dock_planner] Cannot initialize without a valid costmap.\n"); + return false; + } + if (costmap_robot->getGlobalFrameID().empty()) + { + robot::log_error("[dock_planner] Costmap global frame is empty.\n"); + return false; + } - std::vector planMoveToDock; - std::vector footprint_robot = costmap_robot_->getRobotFootprint(); + robot::NodeHandle planner_nh(name); + if (planner_nh.getNamespace() == "/") + { + robot::log_error("[dock_planner] Parameter namespace '%s' does not exist.\n", name.c_str()); + return false; + } - constexpr int degree = 2; - constexpr double step = 0.02; - if (!calc_plan_to_dock_.makePlanMoveToDock(start, goal, footprint_robot, footprint_dock_, degree, step, planMoveToDock, true)) + DockPlannerConfig loaded_config; + std::string config_error; + if (!DockPlannerConfig::load(planner_nh, loaded_config, config_error)) + { + robot::log_error("[dock_planner] Invalid configuration for '%s': %s.\n", + name.c_str(), config_error.c_str()); + return false; + } + + std::vector loaded_footprint; + if (loaded_config.dock_anchor == DockAnchor::kFace) + { + // Goal sits on the approach face: dock size never enters the approach + // formula, so a declared footprint_dock is deliberately ignored. + if (planner_nh.hasParam("footprint_dock")) + { + robot::log_info("[dock_planner] '%s' uses dock_anchor=face; footprint_dock is ignored.\n", + name.c_str()); + } + } + else + { + const FootprintLoadStatus footprint_status = + loadDockFootprint(planner_nh, name, loaded_footprint); + if (footprint_status == FootprintLoadStatus::kInvalid) + { return false; - - const robot::Time plan_time = robot::Time::now(); - const std::string& global_frame = costmap_robot_->getGlobalFrameID(); - plan.reserve(planMoveToDock.size()); - for (const auto& p : planMoveToDock) - { - robot_geometry_msgs::PoseStamped pose; - pose.header.stamp = plan_time; - pose.header.frame_id = global_frame; - pose.pose.position.x = p.position.x; - pose.pose.position.y = p.position.y; - pose.pose.position.z = 0; - pose.pose.orientation = p.orientation; - plan.push_back(pose); } - return true; + if (footprint_status == FootprintLoadStatus::kMissing) + { + robot::log_warning("[dock_planner] '%s/footprint_dock' is not set; dock size will not contribute to approach geometry.\n", + name.c_str()); + } } - // Export factory function - robot_nav_core::BaseGlobalPlanner::Ptr DockPlanner::create() { - return std::make_shared(); + costmap_robot_ = costmap_robot; + global_frame_ = costmap_robot->getGlobalFrameID(); + footprint_dock_ = std::move(loaded_footprint); + dock_calc_.setConfig(loaded_config); + initialized_ = true; + return true; +} + +bool DockPlanner::makePlan( + const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) +{ + plan.clear(); + if (!initialized_ || costmap_robot_ == nullptr) + { + robot::log_error("[dock_planner] makePlan() called before successful initialize().\n"); + return false; + } + if (start.header.frame_id.empty() || goal.header.frame_id.empty() || + start.header.frame_id != global_frame_ || goal.header.frame_id != global_frame_) + { + robot::log_error("[dock_planner] Start and goal must both be in global frame '%s' (got '%s' and '%s').\n", + global_frame_.c_str(), start.header.frame_id.c_str(), + goal.header.frame_id.c_str()); + return false; } + std::vector path; + if (!dock_calc_.makePlanMoveToDock(start, goal, costmap_robot_->getRobotFootprint(), + footprint_dock_, path) || path.empty()) + { + return false; + } -} // namespace dock_planner + const robot::Time plan_time = robot::Time::now(); + plan.reserve(path.size()); + for (const auto& path_pose : path) + { + robot_geometry_msgs::PoseStamped stamped_pose; + stamped_pose.header.stamp = plan_time; + stamped_pose.header.frame_id = global_frame_; + stamped_pose.pose = path_pose; + plan.push_back(stamped_pose); + } + return true; +} -// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias) -BOOST_DLL_ALIAS(dock_planner::DockPlanner::create, DockPlanner) +robot_nav_core::BaseGlobalPlanner::Ptr DockPlanner::create() +{ + return std::make_shared(); +} + +} // namespace dock_planner + +BOOST_DLL_ALIAS(dock_planner::DockPlanner::create, DockPlanner) diff --git a/src/dock_planner_config.cpp b/src/dock_planner_config.cpp new file mode 100644 index 0000000..23006e3 --- /dev/null +++ b/src/dock_planner_config.cpp @@ -0,0 +1,178 @@ +#include "dock_planner/dock_planner_config.h" + +#include +#include + +namespace dock_planner +{ +namespace +{ + +bool readOptionalDouble(const robot::NodeHandle& nh, const std::string& key, + double& value, std::string& error) +{ + if (!nh.hasParam(key)) + { + return true; + } + + double parsed = value; + if (!nh.getParam(key, parsed, value)) + { + error = "parameter '" + key + "' must be numeric"; + return false; + } + value = parsed; + return true; +} + +bool readDockAnchor(const robot::NodeHandle& nh, DockAnchor& anchor, std::string& error) +{ + if (!nh.hasParam("dock_anchor")) + { + return true; + } + + std::string parsed; + if (!nh.getParam("dock_anchor", parsed, std::string())) + { + error = "parameter 'dock_anchor' must be a string"; + return false; + } + if (parsed == "center") + { + anchor = DockAnchor::kCenter; + return true; + } + if (parsed == "face") + { + anchor = DockAnchor::kFace; + return true; + } + error = "parameter 'dock_anchor' must be 'center' or 'face' (got '" + parsed + "')"; + return false; +} + +bool requireFinite(const char* name, double value, std::string& error) +{ + if (std::isfinite(value)) + { + return true; + } + error = std::string("parameter '") + name + "' must be finite"; + return false; +} + +} // namespace + +bool DockPlannerConfig::load(const robot::NodeHandle& nh, DockPlannerConfig& config, + std::string& error) +{ + DockPlannerConfig loaded; + if (!readOptionalDouble(nh, "approach/alignment_distance_padding", + loaded.alignment_distance_padding, error) || + !readOptionalDouble(nh, "approach/lateral_distance_near", + loaded.lateral_distance_near, error) || + !readOptionalDouble(nh, "approach/lateral_distance_far", + loaded.lateral_distance_far, error) || + !readOptionalDouble(nh, "approach/angle_threshold_near", + loaded.angle_threshold_near, error) || + !readOptionalDouble(nh, "approach/angle_threshold_far", + loaded.angle_threshold_far, error) || + !readOptionalDouble(nh, "approach/direction_angle_hysteresis", + loaded.direction_angle_hysteresis, error) || + !readOptionalDouble(nh, "approach/direction_distance_tolerance", + loaded.direction_distance_tolerance, error) || + !readOptionalDouble(nh, "sampling/path_point_spacing", + loaded.path_point_spacing, error)) + { + return false; + } + + if (!readDockAnchor(nh, loaded.dock_anchor, error)) + { + return false; + } + + if (!loaded.validate(error)) + { + return false; + } + + config = loaded; + error.clear(); + return true; +} + +bool DockPlannerConfig::validate(std::string& error) const +{ + const struct + { + const char* name; + double value; + } values[] = { + {"approach/alignment_distance_padding", alignment_distance_padding}, + {"approach/lateral_distance_near", lateral_distance_near}, + {"approach/lateral_distance_far", lateral_distance_far}, + {"approach/angle_threshold_near", angle_threshold_near}, + {"approach/angle_threshold_far", angle_threshold_far}, + {"approach/direction_angle_hysteresis", direction_angle_hysteresis}, + {"approach/direction_distance_tolerance", direction_distance_tolerance}, + {"sampling/path_point_spacing", path_point_spacing}, + }; + + for (const auto& entry : values) + { + if (!requireFinite(entry.name, entry.value, error)) + { + return false; + } + } + + if (alignment_distance_padding < 0.0) + { + error = "parameter 'approach/alignment_distance_padding' must be >= 0 m"; + return false; + } + if (lateral_distance_near < 0.0 || lateral_distance_far <= lateral_distance_near) + { + error = "approach lateral distances must satisfy 0 <= near < far"; + return false; + } + if (angle_threshold_far <= 0.0 || angle_threshold_near >= kPi || + angle_threshold_near <= angle_threshold_far) + { + error = "approach angle thresholds must satisfy 0 < far < near < pi"; + return false; + } + if (direction_angle_hysteresis < 0.0 || + direction_angle_hysteresis >= angle_threshold_far) + { + error = "parameter 'approach/direction_angle_hysteresis' must be >= 0 and smaller than angle_threshold_far"; + return false; + } + if (direction_distance_tolerance < 0.0) + { + error = "parameter 'approach/direction_distance_tolerance' 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"; + return false; + } + + error.clear(); + return true; +} + +double DockPlannerConfig::angleThreshold(double lateral_distance) const +{ + const double clamped = std::clamp(lateral_distance, lateral_distance_near, + lateral_distance_far); + const double ratio = (clamped - lateral_distance_near) / + (lateral_distance_far - lateral_distance_near); + return angle_threshold_near + ratio * (angle_threshold_far - angle_threshold_near); +} + +} // namespace dock_planner diff --git a/src/utils/curve_common.cpp b/src/utils/curve_common.cpp index cfd439a..7c594e5 100644 --- a/src/utils/curve_common.cpp +++ b/src/utils/curve_common.cpp @@ -1,1157 +1,19 @@ #include "dock_planner/utils/curve_common.h" -#include "dock_planner/utils/conversion.h" -#include -#include + +#include +#include + +#include + +namespace dock_planner +{ CurveCommon::CurveCommon() { } -robot_nav_msgs::Path CurveCommon::Generate_Line(robot_geometry_msgs::Point start_point, robot_geometry_msgs::Point end_point, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path line_result; - robot_geometry_msgs::PoseStamped current_pose; - - line_result.header.frame_id = frame_id; - line_result.header.stamp = robot::Time::now(); - - current_pose.header.frame_id = frame_id; - - int segment = 1 / t_intervel; - double line_parameter = 0; - - for (int i = 0; i < segment; i++) - { - current_pose.header.seq = i; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = start_point.x * (1 - line_parameter) + end_point.x * (line_parameter); - current_pose.pose.position.y = start_point.y * (1 - line_parameter) + end_point.y * (line_parameter); - - line_result.poses.push_back(current_pose); - line_parameter += t_intervel; - } - - std::cout << "End cacluation" << "\n"; - return line_result; -} - -robot_nav_msgs::Path CurveCommon::Generate_BezierCurve(EigenTrajectoryPoint::Vector control_point, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path bezier_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - EigenTrajectoryPoint::Vector temp_control_point_vec; - - bezier_curve_result.header.frame_id = frame_id; - bezier_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int segment = 1 / t_intervel; - int control_point_length = control_point.size(); - double curve_parameter = 0; - temp_control_point_vec.reserve(control_point_length); - - for (int i = 0; i <= segment; i++) - { - temp_control_point_vec.assign(control_point.begin(), control_point.end()); - - for (int j = 1; j <= control_point_length - 1; j++) - { - for (int k = 1; k <= control_point_length - j; k++) - { - temp_control_point_vec.at(k - 1).position(0) = temp_control_point_vec.at(k - 1).position(0) * (1 - curve_parameter) + temp_control_point_vec.at(k).position(0) * curve_parameter; - temp_control_point_vec.at(k - 1).position(1) = temp_control_point_vec.at(k - 1).position(1) * (1 - curve_parameter) + temp_control_point_vec.at(k).position(1) * curve_parameter; - } - } - current_pose.header.seq = i; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = temp_control_point_vec.at(0).position(0); - current_pose.pose.position.y = temp_control_point_vec.at(0).position(1); - bezier_curve_result.poses.push_back(current_pose); - curve_parameter += t_intervel; - } - - std::cout << "End calculate Bezier Curve" << "\n"; - return bezier_curve_result; -} - -void CurveCommon::ReadDiscreate2DPointFromLaunch(EigenTrajectoryPoint::Vector *input_point, std::vector file_discreate_point) -{ - int index = 0; - Eigen::Vector3d read_point; - EigenTrajectoryPoint eigen_discreate_point; - input_point->reserve(file_discreate_point.size() / 2); - - for (int i = 0; i < file_discreate_point.size(); i++) - { - if (i % 2 == 0) - { - read_point(0) = file_discreate_point[i]; - } - else - { - read_point(1) = file_discreate_point[i]; - eigen_discreate_point.position = read_point; - // input_point->emplace_back(dis_control_point); //I don't know why have error - input_point->push_back(eigen_discreate_point); - index++; - } - } - - // Debug use - // std::cout << "input control point size : " << input_control_point->size() << "\n"; - // for(int i = 0; i < input_control_point->size(); i++) - // { - // std::cout << "control point x : " << input_control_point->at(i).position(0) << "\n"; - // std::cout << "control point y : " << input_control_point->at(i).position(1) << "\n"; - // } -} - -void CurveCommon::ReadDiscreate2DPointFromLaunch(std::vector> *input_point, std::vector file_discreate_point) -{ - Eigen::Vector3d read_point; - input_point->reserve(file_discreate_point.size() / 2); - - for (int i = 0; i < file_discreate_point.size(); i++) - { - if (i % 2 == 0) - { - read_point(0) = file_discreate_point[i]; - } - else - { - read_point(1) = file_discreate_point[i]; - input_point->push_back(read_point); - } - } - - // Debug use - // std::cout << "input control point size : " << input_point->size() << "\n"; - // for(int i = 0; i < input_point->size(); i++) - // { - // std::cout << "control point x : " << input_point->at(i)(0) << "\n"; - // std::cout << "control point y : " << input_point->at(i)(1) << "\n"; - // } -} - -robot_visualization_msgs::Marker CurveCommon::ShowDiscreatePoint(std::vector> discreate_point, const std::string &frame_id, const std::string &name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - // waypoints_marker.color = color; - waypoints_marker.color.r = 1; - waypoints_marker.color.g = 1; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(discreate_point.size()); - - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker CurveCommon::ShowDiscreatePoint2(std::vector> discreate_point, const std::string &frame_id, robot_std_msgs::ColorRGBA point_color, const std::string &name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - waypoints_marker.color = point_color; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(discreate_point.size()); - - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker CurveCommon::ShowDiscreatePoint(EigenTrajectoryPoint::Vector &discreate_point, const std::string &frame_id, const std::string &name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - // waypoints_marker.color = color; - waypoints_marker.color.r = 1; - waypoints_marker.color.g = 1; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(discreate_point.size()); - - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker CurveCommon::ShowDiscreatePoint2(EigenTrajectoryPoint::Vector &discreate_point, const std::string &frame_id, robot_std_msgs::ColorRGBA point_color, const std::string &name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - waypoints_marker.color = point_color; - // waypoints_marker.color.r = r; - // waypoints_marker.color.g = g; - // waypoints_marker.color.b = b; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(discreate_point.size()); - - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -void CurveCommon::ShowDiscreatePoint(robot_visualization_msgs::Marker *points, EigenTrajectoryPoint::Vector discreate_point) -{ - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - points->points.push_back(view_point); - } -} - -void CurveCommon::ShowDiscreatePoint(robot_visualization_msgs::Marker *points, std::vector> discreate_point) -{ - robot_geometry_msgs::Point view_point; - for (int i = 0; i < discreate_point.size(); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - points->points.push_back(view_point); - } -} - -void CurveCommon::ReadSplineInf(Spline_Inf *bspline_inf, int order, std::vector> control_point, std::vector knot_vector) -{ - bspline_inf->order = order; - bspline_inf->knot_vector.assign(knot_vector.begin(), knot_vector.end()); - bspline_inf->control_point.assign(control_point.begin(), control_point.end()); - - // Debug use - // std::cout << "knot vector size : " << bspline_inf->knot_vector.size() << "\n"; - // for(int i = 0; i < bspline_inf->knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf->knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf->control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf->control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf->control_point.at(i)(0) << ", y = " << bspline_inf->control_point.at(i)(1) << "\n"; - // } -} - -void CurveCommon::ReadSplineInf(Spline_Inf *spline_inf, std::vector weight_vector, bool use_limit_derivative_fitting) -{ - if (!use_limit_derivative_fitting) - { - if (spline_inf->control_point.size() != weight_vector.size()) - { - std::cout << "weight vector size is wrong" << "\n"; - return; - } - } - else - { - for (int i = 0; i < 2; i++) - weight_vector.push_back(1); - } - - spline_inf->weight.assign(weight_vector.begin(), weight_vector.end()); - - // Debug use - // std::cout << "knot vector size : " << spline_inf->knot_vector.size() << "\n"; - // for(int i = 0; i < spline_inf->knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << spline_inf->knot_vector.at(i) << "\n"; - // } - - // std::cout << "control point size : " << spline_inf->control_point.size() << "\n"; - // for(int i = 0; i < spline_inf->control_point.size(); i++) - // { - // std::cout << "control point x : " << spline_inf->control_point.at(i)(0) << ", y = " << spline_inf->control_point.at(i)(1) << "\n"; - // } -} - -robot_nav_msgs::Path CurveCommon::Generate_BsplineCurve(Spline_Inf bspline_inf, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path bspline_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - - bspline_curve_result.header.frame_id = frame_id; - bspline_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; // The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 100; - double curve_parameter = 0; - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double sum_x = 0, sum_y = 0; - std::vector curve_parameter_vec; - Eigen::VectorXd temp_basic_function; - std::vector> temp_basic_function_eigen; - - // Debug use - // for(int i = 0; i < bspline_inf.knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf.knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf.control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf.control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf.control_point.at(i)(0) << ", y = " << bspline_inf.control_point.at(i)(1) << "\n"; - // } - - // TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for (int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - bspline_inf.N.clear(); - temp_basic_function.resize(segment); - - // TODO: Check basic function boundary is correct - // Calculate degree = 0's basic function - for (int i = 0; i < m; i++) - { - if (bspline_inf.knot_vector.at(i) != bspline_inf.knot_vector.at(n)) - { - for (int u = 0; u < segment; u++) - { - if (bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < bspline_inf.knot_vector.at(i + 1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - // std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - // std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - else - { - for (int u = 0; u < segment; u++) - { - if (bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i + 1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - // std::cout << "temp basic function index : " << u << "temp basic function value : " << temp_basic_function(u) << "\n"; - // std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - - // if(bspline_inf.knot_vector.at(i) < bspline_inf.knot_vector.at(i+1)) - // { - // if(bspline_inf.knot_vector.at(i) != bspline_inf.knot_vector.at(n)) - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - // else - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "n basic function index : " << u << " n basic function value : " << temp_basic_function(u) << "\n"; - // //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - // } - // else - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "temp basic function index : " << u << " temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - bspline_inf.N.push_back(temp_basic_function); - // std::cout << i << "'s bspline_inf Ni,0 size " << temp_basic_function.size() << "\n"; - } - - // Calculate the rest of basic function - for (int p = 1; p <= p_degree; p++) - { - temp_basic_function_eigen.clear(); - for (int i = 0; i < (m - p); i++) - { - for (int u = 0; u < segment; u++) - { - left_denom = bspline_inf.knot_vector.at(p + i) - bspline_inf.knot_vector.at(i); - right_denom = bspline_inf.knot_vector.at(i + p + 1) - bspline_inf.knot_vector.at(i + 1); - - if (left_denom == 0) - left_term = 0; - else - left_term = (curve_parameter_vec[u] - bspline_inf.knot_vector.at(i)) * bspline_inf.N.at(i)(u) / left_denom; - - if (right_denom == 0) - right_term = 0; - else - right_term = (bspline_inf.knot_vector.at(i + p + 1) - curve_parameter_vec[u]) * bspline_inf.N.at(i + 1)(u) / right_denom; - - temp_basic_function(u) = left_term + right_term; - } - temp_basic_function_eigen.push_back(temp_basic_function); - } - bspline_inf.N = temp_basic_function_eigen; - } - - for (int u = 0; u < segment; u++) - { - sum_x = 0; - sum_y = 0; - for (int i = 0; i < bspline_inf.N.size(); i++) - { - sum_x += bspline_inf.control_point.at(i)(0) * bspline_inf.N.at(i)(u); - sum_y += bspline_inf.control_point.at(i)(1) * bspline_inf.N.at(i)(u); - // std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; - } - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = sum_x; - current_pose.pose.position.y = sum_y; - bspline_curve_result.poses.push_back(current_pose); - } - - std::cout << "End Calculate" << "\n"; - return bspline_curve_result; -} - -robot_nav_msgs::Path CurveCommon::Generate_NURBSCurve(Spline_Inf spline_inf, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path nurbs_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - - nurbs_curve_result.header.frame_id = frame_id; - nurbs_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = spline_inf.order - 1; - int n = spline_inf.control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect - int m = spline_inf.knot_vector.size() - 1; // The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 100; - double curve_parameter = 0; - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double sum_nurbs_denom = 0; - double sum_x = 0, sum_y = 0; - std::vector curve_parameter_vec; - Eigen::VectorXd temp_basic_function; - std::vector> temp_basic_function_eigen; - - // Debug use - // for(int i = 0; i < bspline_inf.knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf.knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf.control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf.control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf.control_point.at(i)(0) << ", y = " << bspline_inf.control_point.at(i)(1) << "\n"; - // } - - if (spline_inf.weight.size() == 0) - { - std::cout << "weight vector size is zero, please call read ReadSplineInf function" << "\n"; - return nurbs_curve_result; - } - - // TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for (int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - spline_inf.N.clear(); - temp_basic_function.resize(segment); - - // TODO: Check basic function boundary is correct - // Calculate degree = 0's basic function - for (int i = 0; i < m; i++) - { - // if(spline_inf.knot_vector.at(i) != spline_inf.knot_vector.at(n)) - if (spline_inf.knot_vector.at(i) != spline_inf.knot_vector.at(i + 1)) - { - for (int u = 0; u < segment; u++) - { - if (spline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < spline_inf.knot_vector.at(i + 1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - // std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - // std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - else - { - for (int u = 0; u < segment; u++) - { - if (spline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= spline_inf.knot_vector.at(i + 1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - // std::cout << "temp basic function index : " << u << "temp basic function value : " << temp_basic_function(u) << "\n"; - // std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - - spline_inf.N.push_back(temp_basic_function); - // std::cout << i << "'s bspline_inf Ni,0 size " << temp_basic_function.size() << "\n"; - } - - // Calculate the rest of basic function - for (int p = 1; p <= p_degree; p++) - { - temp_basic_function_eigen.clear(); - for (int i = 0; i < (m - p); i++) // m-p is calculate how many region between basis function - { - for (int u = 0; u < segment; u++) - { - left_denom = spline_inf.knot_vector.at(p + i) - spline_inf.knot_vector.at(i); - right_denom = spline_inf.knot_vector.at(i + p + 1) - spline_inf.knot_vector.at(i + 1); - - if (left_denom == 0) - left_term = 0; - else - left_term = (curve_parameter_vec[u] - spline_inf.knot_vector.at(i)) * spline_inf.N.at(i)(u) / left_denom; - - if (right_denom == 0) - right_term = 0; - else - right_term = (spline_inf.knot_vector.at(i + p + 1) - curve_parameter_vec[u]) * spline_inf.N.at(i + 1)(u) / right_denom; - - temp_basic_function(u) = left_term + right_term; - } - temp_basic_function_eigen.push_back(temp_basic_function); - } - spline_inf.N = temp_basic_function_eigen; - } - - for (int u = 0; u < segment; u++) - { - sum_nurbs_denom = 0; - sum_x = 0; - sum_y = 0; - for (int i = 0; i < spline_inf.N.size(); i++) - { - sum_nurbs_denom += spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - sum_x += spline_inf.control_point.at(i)(0) * spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - sum_y += spline_inf.control_point.at(i)(1) * spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - // std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; - } - sum_x /= sum_nurbs_denom; - sum_y /= sum_nurbs_denom; - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = sum_x; - current_pose.pose.position.y = sum_y; - nurbs_curve_result.poses.push_back(current_pose); - } - - std::cout << "End calculate NURBS function" << "\n"; - return nurbs_curve_result; -} - -void CurveCommon::CalculateDerivativeBasisFunc(Spline_Inf *spline_inf, double u_data, int differential_times) -{ - int p_degree = spline_inf->order - 1; - int n = spline_inf->control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect - int m = spline_inf->knot_vector.size() - 1; // The last knot vector index number - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double derivative_left_term = 0, derivative_right_term = 0; - double derivative_value = 0; - std::vector temp_basic_function; - Eigen::VectorXd derivative_temp_basic_function; - double degree_basis_value; - std::vector> derivative_basic_function_eigen; - - // Calculate degree = 0's basic function - spline_inf->N_double_vec.clear(); - spline_inf->N_double_vec.resize(m); - for (int i = 0; i < m; i++) - { - // if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(n)) - if (spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(i + 1)) - { - if (spline_inf->knot_vector.at(i) <= u_data && u_data < spline_inf->knot_vector.at(i + 1)) - degree_basis_value = 1; - else - degree_basis_value = 0; - } - else - { - if (spline_inf->knot_vector.at(i) <= u_data && u_data <= spline_inf->knot_vector.at(i + 1)) - degree_basis_value = 1; - else - degree_basis_value = 0; - } - - spline_inf->N_double_vec.at(i) = degree_basis_value; - } - - // Calculate the rest of basic function - spline_inf->dN.clear(); - for (int p = 1; p <= p_degree; p++) - { - temp_basic_function.clear(); - derivative_temp_basic_function.resize(m - p); - for (int i = 0; i < (m - p); i++) - { - left_denom = spline_inf->knot_vector.at(p + i) - spline_inf->knot_vector.at(i); - right_denom = spline_inf->knot_vector.at(i + p + 1) - spline_inf->knot_vector.at(i + 1); - - if (left_denom == 0) - { - left_term = 0; - derivative_left_term = 0; - } - else - { - left_term = (u_data - spline_inf->knot_vector.at(i)) * spline_inf->N_double_vec.at(i) / left_denom; - derivative_left_term = spline_inf->N_double_vec.at(i) / left_denom; - } - - if (right_denom == 0) - { - right_term = 0; - derivative_right_term = 0; - } - else - { - right_term = (spline_inf->knot_vector.at(i + p + 1) - u_data) * spline_inf->N_double_vec.at(i + 1) / right_denom; - derivative_right_term = spline_inf->N_double_vec.at(i + 1) / right_denom; - } - - derivative_value = p * (derivative_left_term - derivative_right_term); - temp_basic_function.push_back(left_term + right_term); // Calculate Ni,p - derivative_temp_basic_function(i) = derivative_value; // Calculate dNi,p - } - spline_inf->N_double_vec.assign(temp_basic_function.begin(), temp_basic_function.end()); - spline_inf->dN.push_back(derivative_temp_basic_function); - } - - if (differential_times > 1) - { - spline_inf->ddN.clear(); - for (int p = 2; p <= p_degree; p++) - { - derivative_temp_basic_function.resize(m - p); - for (int i = 0; i < (m - p); i++) - { - left_denom = spline_inf->knot_vector.at(p + i) - spline_inf->knot_vector.at(i); - right_denom = spline_inf->knot_vector.at(i + p + 1) - spline_inf->knot_vector.at(i + 1); - - if (left_denom == 0) - derivative_left_term = 0; - else - derivative_left_term = spline_inf->dN.at(p - 2)(i) / left_denom; - - if (right_denom == 0) - derivative_right_term = 0; - else - derivative_right_term = spline_inf->dN.at(p - 2)(i + 1) / right_denom; - - derivative_value = p * (derivative_left_term - derivative_right_term); - derivative_temp_basic_function(i) = derivative_value; // Calculate ddNi,p - } - spline_inf->ddN.push_back(derivative_temp_basic_function); - } - } -} - -robot_geometry_msgs::Point CurveCommon::CalculateDerivativeCurvePoint(Spline_Inf *spline_inf, double u_data, int differential_times, bool UsingNURBS) -{ - robot_geometry_msgs::Point derivative_curve_point; - int p_degree = spline_inf->order - 1; - double sum_x = 0, sum_y = 0; - double sum_denom = 0; - double sum_derivative_once_denom = 0; - double sum_derivative_twice_denom = 0; - double R_fraction = 0; - double dR_left_term_fraction = 0; - double dR_right_term = 0; - double ddR_left_term_fraction = 0; - double ddR_median_term_fraction = 0; - double ddR_right_term_fraction = 0; - - spline_inf->R_double_vec.clear(); - spline_inf->dR_double_vec.clear(); - spline_inf->ddR_double_vec.clear(); - - // Debug use - // std::cout << "N_double_vec :" << "\n"; - // for(int i = 0; i < spline_inf->N_double_vec.size(); i++) - // { - // std::cout << spline_inf->N_double_vec.at(i) << " "; - // } - // std::cout << "\n"; - - // std::cout << "dN :" << "\n"; - // for(int i = 0; i < spline_inf->dN.back().size(); i++) - // { - // std::cout << spline_inf->dN.back()(i) << " "; - // } - // std::cout << "\n"; - - // TODO: Safety check - if (UsingNURBS == false) - { - if (differential_times == 1) - { - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->dN.back()(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->dN.back()(i); - // std::cout << i << "'s spline_inf.dN : " << spline_inf->dN.back()(i) << "\n"; - } - } - if (differential_times == 2) - { - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->ddN.back()(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->ddN.back()(i); - // std::cout << i << "'s spline_inf.ddN : " << spline_inf->ddN.back()(i) << "\n"; - } - } - } - else - { - // TODO: Safety check differential_times - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - sum_denom += spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - sum_derivative_once_denom += spline_inf->dN.back()(i) * spline_inf->weight.at(i); - if (differential_times == 2) - sum_derivative_twice_denom += spline_inf->ddN.back()(i) * spline_inf->weight.at(i); - } - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - if (sum_denom != 0) - { - R_fraction = spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - - dR_left_term_fraction = spline_inf->dN.back()(i) * spline_inf->weight.at(i); - dR_right_term = R_fraction * sum_derivative_once_denom / std::pow(sum_denom, 2); - - if (differential_times == 2) - { - ddR_left_term_fraction = spline_inf->ddN.back()(i) * spline_inf->weight.at(i); - ddR_median_term_fraction = 2 * dR_left_term_fraction * sum_derivative_once_denom + R_fraction * sum_derivative_twice_denom; - ddR_right_term_fraction = 2 * R_fraction * std::pow(sum_derivative_once_denom, 2); - spline_inf->ddR_double_vec.push_back((ddR_left_term_fraction / sum_denom) - (ddR_median_term_fraction / std::pow(sum_denom, 2)) + (ddR_right_term_fraction / std::pow(sum_denom, 3))); - } - - spline_inf->R_double_vec.push_back(R_fraction / sum_denom); - spline_inf->dR_double_vec.push_back((dR_left_term_fraction / sum_denom) - dR_right_term); - } - else - { - spline_inf->R_double_vec.push_back(0); - spline_inf->dR_double_vec.push_back(0); - spline_inf->ddR_double_vec.push_back(0); - } - } - - if (differential_times == 1) - { - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->dR_double_vec.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->dR_double_vec.at(i); - // std::cout << i << "'s spline_inf.dN : " << spline_inf->dN.back()(i) << "\n"; - } - } - if (differential_times == 2) - { - for (int i = 0; i < spline_inf->control_point.size(); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->ddR_double_vec.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->ddR_double_vec.at(i); - } - } - } - - derivative_curve_point.x = sum_x; - derivative_curve_point.y = sum_y; - derivative_curve_point.z = 0; - - // Debug use - // std::cout << u_data << "'s derivative current_pose x : " << derivative_curve_point.x << "\n"; - // std::cout << u_data << "'s derivative current_pose y : " << derivative_curve_point.y << "\n"; - - return derivative_curve_point; -} - -robot_nav_msgs::Path CurveCommon::Generate_DerivativeBsplineCurve(Spline_Inf bspline_inf, int differential_times, double t_intervel, std::string frame_id) -{ - robot_geometry_msgs::Point derivative_point_result; - robot_nav_msgs::Path bspline_derivative_result; - robot_geometry_msgs::PoseStamped current_pose; - - bspline_derivative_result.header.frame_id = frame_id; - bspline_derivative_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; // The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 0; - double curve_parameter = 0; - std::vector curve_parameter_vec; - - // TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for (int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - // TODO: Can support high order derivative in loop - for (int u = 0; u < segment; u++) - { - CalculateDerivativeBasisFunc(&bspline_inf, curve_parameter_vec[u], differential_times); - derivative_point_result = CalculateDerivativeCurvePoint(&bspline_inf, curve_parameter_vec[u], differential_times, false); - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = derivative_point_result.x; - current_pose.pose.position.y = derivative_point_result.y; - bspline_derivative_result.poses.push_back(current_pose); - } - - return bspline_derivative_result; -} - -robot_nav_msgs::Path CurveCommon::Generate_DerivativeBasisFuncCurve(Spline_Inf bspline_inf, int differential_times, int index, double t_intervel, std::string frame_id) -{ - robot_geometry_msgs::Point derivative_point_result; - robot_nav_msgs::Path derivative_basis_result; - robot_geometry_msgs::PoseStamped current_pose; - - derivative_basis_result.header.frame_id = frame_id; - derivative_basis_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - // TODO: Add error ckeck function(below code with error) - // if(differential_times == 0 && index < bspline_inf.N_double_vec.size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.N_double_vec.size() << "\n"; - // return derivative_basis_result; - // } - // if(differential_times == 1 && index < bspline_inf.dN.back().size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.dN.back().size() << "\n"; - // return derivative_basis_result; - // } - // if(differential_times == 2 && index < bspline_inf.ddN.back().size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.ddN.back().size() << "\n"; - // return derivative_basis_result; - // } - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; // The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 0; - double curve_parameter = 0; - std::vector curve_parameter_vec; - - // TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for (int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - // TODO: Can support high order derivative in loop - for (int u = 0; u < segment; u++) - { - CalculateDerivativeBasisFunc(&bspline_inf, curve_parameter_vec[u], differential_times); - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = curve_parameter_vec[u]; - if (differential_times == 0) - current_pose.pose.position.y = bspline_inf.N_double_vec.at(index); - else if (differential_times == 1) - current_pose.pose.position.y = bspline_inf.dN.back()(index); - else - current_pose.pose.position.y = bspline_inf.ddN.back()(index); - derivative_basis_result.poses.push_back(current_pose); - } - - return derivative_basis_result; -} - -double CurveCommon::CalculateCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - if (u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return 0; - } - - if (u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - double curvature = 0; - double fraction = 0; - double denominator = 0; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - fraction = derivative_once_point.cross(derivative_twice_point).lpNorm<2>(); - denominator = std::pow(derivative_once_point.lpNorm<2>(), 3); - - if (denominator == 0) - curvature = 0; - else - curvature = fraction / denominator; - - // TODO: Check curvature direction (but in nurbs planner not useful) - // Eigen::Vector3d direction_vector; //curvature direction - // direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - // if(direction_vector(0) < 0 && direction_vector(1) < 0 || direction_vector(0) > 0 && direction_vector(1) < 0) - // curvature *= -1; - - return curvature; -} - -double CurveCommon::CalculateSignedCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - if (u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return 0; - } - - if (u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - double curvature = 0; - double fraction = 0; - double denominator = 0; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - fraction = derivative_once_point.cross(derivative_twice_point).lpNorm<2>(); - denominator = std::pow(derivative_once_point.lpNorm<2>(), 3); - - if (denominator == 0) - curvature = 0; - else - curvature = fraction / denominator; - - // TODO: Check curvature direction (but in nurbs planner not useful) - Eigen::Vector3d direction_vector; // curvature direction - direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - if (direction_vector(0) < 0 && direction_vector(1) < 0 || direction_vector(0) > 0 && direction_vector(1) < 0) - curvature *= -1; - - return curvature; -} - -Eigen::Vector3d CurveCommon::CalculateCurvatureDirectionVector(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - Eigen::Vector3d direction_vector; - if (u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return direction_vector; - } - - if (u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - - return direction_vector; -} - -double CurveCommon::CalculateCurvatureRadius(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - double curvature_radius = 0; - double curvature = 0; - - curvature = CalculateCurvature(spline_inf, u_data, UsingNURBS); - - if (curvature == 0) - return curvature_radius = 0; - else - return curvature_radius = 1 / curvature; -} - -double CurveCommon::CalculateCurveLength(Spline_Inf spline_inf, double start_u, double end_u, int sub_intervals, bool UsingNURBS) -{ - if (sub_intervals % 2 != 0) - { - std::cout << "Error! sub_intervals value is a even number" << "\n"; - return 0; - } - - Eigen::Vector3d eigen_derivative_point; - double sum_length = 0; - double interval = 0; - double u_index = 0; - - interval = (end_u - start_u) / (double)sub_intervals; - - for (int i = 0; i <= sub_intervals; i++) - { - u_index = start_u + interval * i; - CalculateDerivativeBasisFunc(&spline_inf, u_index, 1); - eigen_derivative_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_index, 1, UsingNURBS)); - - if (i == 0 || i == sub_intervals) - sum_length += eigen_derivative_point.lpNorm<2>(); - else if ((i % 2) == 1) - sum_length += 4 * eigen_derivative_point.lpNorm<2>(); - else if ((i % 2) == 0) - sum_length += 2 * eigen_derivative_point.lpNorm<2>(); - } - - sum_length *= interval / 3; - - return sum_length; -} - -bool CurveCommon::curveIsValid(int degree, const std::vector &knot_vector, - std::vector> &control_points) +bool CurveCommon::curveIsValid(int degree, const std::vector& knot_vector, + const std::vector>& control_points) { if (degree < 1 || degree > 9) { @@ -1166,14 +28,62 @@ bool CurveCommon::curveIsValid(int degree, const std::vector &knot_vecto return true; } -robot_geometry_msgs::Point CurveCommon::CalculateCurvePoint(Spline_Inf *spline_inf, double u_data, bool UsingNURBS) +void CurveCommon::ReadSplineInf(Spline_Inf* spline_inf, int order, + const std::vector>& control_point, + const std::vector& knot_vector) { - // TODO: Check u = 1 bug, why x=nan and y=nan? + spline_inf->order = order; + spline_inf->knot_vector.assign(knot_vector.begin(), knot_vector.end()); + spline_inf->control_point.assign(control_point.begin(), control_point.end()); +} +void CurveCommon::ReadSplineInf(Spline_Inf* spline_inf, const std::vector& weight_vector, + bool use_limit_derivative_fitting) +{ + if (!use_limit_derivative_fitting) + { + if (spline_inf->control_point.size() != weight_vector.size()) + { + robot::log_error("[curve_common] weight vector size (%zu) does not match control point count (%zu).\n", + weight_vector.size(), spline_inf->control_point.size()); + return; + } + spline_inf->weight.assign(weight_vector.begin(), weight_vector.end()); + return; + } + + std::vector padded_weight(weight_vector); + padded_weight.push_back(1.0); + padded_weight.push_back(1.0); + spline_inf->weight.assign(padded_weight.begin(), padded_weight.end()); +} + +robot_geometry_msgs::Point CurveCommon::CalculateCurvePoint(Spline_Inf* spline_inf, double u_data, bool UsingNURBS) +{ robot_geometry_msgs::Point curve_point; + if (spline_inf == nullptr || spline_inf->control_point.empty() || !std::isfinite(u_data)) + { + curve_point.x = std::numeric_limits::quiet_NaN(); + curve_point.y = std::numeric_limits::quiet_NaN(); + return curve_point; + } + + // A clamped spline evaluates exactly to its boundary control points. Handling + // the boundaries explicitly also avoids the zero NURBS denominator at u=1. + if (u_data <= 0.0) + { + curve_point.x = spline_inf->control_point.front()(0); + curve_point.y = spline_inf->control_point.front()(1); + return curve_point; + } + if (u_data >= 1.0) + { + curve_point.x = spline_inf->control_point.back()(0); + curve_point.y = spline_inf->control_point.back()(1); + return curve_point; + } + int p_degree = spline_inf->order - 1; - int n = spline_inf->control_point.size() - 1; - // TODO: Check knot vector size and sequence is correect int m = spline_inf->knot_vector.size() - 1; // The last knot vector index number double left_denom = 0, right_denom = 0; double left_term = 0, right_term = 0; @@ -1187,7 +97,6 @@ robot_geometry_msgs::Point CurveCommon::CalculateCurvePoint(Spline_Inf *spline_i spline_inf->N_double_vec.resize(m); for (int i = 0; i < m; i++) { - // if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(n)) if (spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(i + 1)) { if (spline_inf->knot_vector.at(i) <= u_data && u_data < spline_inf->knot_vector.at(i + 1)) @@ -1239,41 +148,39 @@ robot_geometry_msgs::Point CurveCommon::CalculateCurvePoint(Spline_Inf *spline_i if (!UsingNURBS) { - for (int i = 0; i < spline_inf->N_double_vec.size(); i++) + for (std::size_t i = 0; i < spline_inf->N_double_vec.size(); i++) { sum_x += spline_inf->control_point.at(i)(0) * spline_inf->N_double_vec.at(i); sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i); - // std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; } - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; curve_point.x = sum_x; curve_point.y = sum_y; + return curve_point; } - else + + if (spline_inf->weight.empty()) { - if (spline_inf->weight.size() == 0) - { - std::cout << "weight vector size is zero, please call read ReadSplineInf function" << "\n"; - curve_point.x = 0; - curve_point.y = 0; - return curve_point; - } - - for (int i = 0; i < spline_inf->N_double_vec.size(); i++) - { - sum_nurbs_denom += spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - // std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; - } - sum_x /= sum_nurbs_denom; - sum_y /= sum_nurbs_denom; - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; - curve_point.x = sum_x; - curve_point.y = sum_y; + robot::log_error("[curve_common] weight vector is empty; call ReadSplineInf with weights first.\n"); + curve_point.x = std::numeric_limits::quiet_NaN(); + curve_point.y = std::numeric_limits::quiet_NaN(); + return curve_point; } + for (std::size_t i = 0; i < spline_inf->N_double_vec.size(); i++) + { + sum_nurbs_denom += spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); + sum_x += spline_inf->control_point.at(i)(0) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); + sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); + } + if (!std::isfinite(sum_nurbs_denom) || std::fabs(sum_nurbs_denom) <= 1e-12) + { + curve_point.x = std::numeric_limits::quiet_NaN(); + curve_point.y = std::numeric_limits::quiet_NaN(); + return curve_point; + } + curve_point.x = sum_x / sum_nurbs_denom; + curve_point.y = sum_y / sum_nurbs_denom; return curve_point; -} \ No newline at end of file +} + +} // namespace dock_planner diff --git a/test/dock_planner_test.cpp b/test/dock_planner_test.cpp new file mode 100644 index 0000000..9c87a97 --- /dev/null +++ b/test/dock_planner_test.cpp @@ -0,0 +1,300 @@ +#include +#include +#include +#include +#include + +#include + +#include "dock_planner/dock_calc.h" +#include "dock_planner/dock_planner_config.h" + +namespace +{ + +int failures = 0; + +void check(bool condition, const char* expression, int line) +{ + if (!condition) + { + std::cerr << "FAIL line " << line << ": " << expression << '\n'; + ++failures; + } +} + +#define CHECK(expression) check((expression), #expression, __LINE__) + +robot_geometry_msgs::Point point(double x, double y) +{ + robot_geometry_msgs::Point result; + result.x = x; + result.y = y; + result.z = 0.0; + return result; +} + +robot_geometry_msgs::PoseStamped pose(double x, double y, double yaw) +{ + robot_geometry_msgs::PoseStamped result; + result.pose.position.x = x; + result.pose.position.y = y; + result.pose.orientation = data_convert::createQuaternionMsgFromYaw(yaw); + return result; +} + +bool near(double first, double second, double tolerance = 1e-9) +{ + return std::fabs(first - second) <= tolerance; +} + +double normalizeAngle(double angle) +{ + return std::remainder(angle, 2.0 * 3.14159265358979323846); +} + +void checkGeneratedPath(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) +{ + std::vector path; + CHECK(calculator.makePlanMoveToDock(start, goal, robot_footprint, + dock_footprint, path)); + CHECK(path.size() > 2); + CHECK(near(path.front().position.x, start.pose.position.x)); + CHECK(near(path.front().position.y, start.pose.position.y)); + CHECK(near(path.back().position.x, goal.pose.position.x)); + CHECK(near(path.back().position.y, goal.pose.position.y)); + + for (std::size_t index = 0; index < path.size(); ++index) + { + const auto& current = path[index]; + CHECK(std::isfinite(current.position.x)); + CHECK(std::isfinite(current.position.y)); + CHECK(std::isfinite(current.orientation.z)); + CHECK(std::isfinite(current.orientation.w)); + if (index > 0) + { + CHECK(std::hypot(current.position.x - path[index - 1].position.x, + current.position.y - path[index - 1].position.y) > 1e-9); + } + } +} + +void testConfig() +{ + dock_planner::DockPlannerConfig config; + std::string error; + CHECK(config.validate(error)); + CHECK(error.empty()); + CHECK(near(config.angleThreshold(0.0), config.angle_threshold_near)); + CHECK(near(config.angleThreshold(10.0), config.angle_threshold_far)); + CHECK(near(config.angleThreshold(0.55), + (config.angle_threshold_near + config.angle_threshold_far) / 2.0)); + + config.path_point_spacing = 0.0; + CHECK(!config.validate(error)); + CHECK(!error.empty()); + + config = dock_planner::DockPlannerConfig{}; + config.angle_threshold_far = config.angle_threshold_near; + CHECK(!config.validate(error)); + + config = dock_planner::DockPlannerConfig{}; + config.lateral_distance_far = std::numeric_limits::quiet_NaN(); + CHECK(!config.validate(error)); +} + +void testPathGeneration() +{ + dock_planner::DockPlannerConfig config; + config.path_point_spacing = 0.05; + dock_planner::DockCalc calculator(config); + + const std::vector robot_footprint = { + point(0.50, -0.35), point(0.50, 0.35), + point(-0.50, 0.35), point(-0.50, -0.35)}; + const std::vector dock_footprint = { + point(0.50, -0.40), point(0.50, 0.40), + point(-0.50, 0.40), point(-0.50, -0.40)}; + + const auto start = pose(2.8, 0.6, 0.0); + const auto goal = pose(0.0, 0.0, 0.0); + checkGeneratedPath(calculator, start, goal, robot_footprint, dock_footprint); + checkGeneratedPath(calculator, pose(2.8, 0.0, 0.0), goal, + robot_footprint, dock_footprint); + checkGeneratedPath(calculator, pose(2.8, -0.6, 0.0), goal, + robot_footprint, dock_footprint); + checkGeneratedPath(calculator, pose(-2.8, 0.6, 0.0), goal, + robot_footprint, dock_footprint); + checkGeneratedPath(calculator, pose(0.6, 2.8, 1.5707963267948966), + pose(0.0, 0.0, 1.5707963267948966), + robot_footprint, dock_footprint); + + const auto prealigned_start = pose(2.8, 0.6, -1.2); + std::vector orientation_path; + CHECK(calculator.makePlanMoveToDock(prealigned_start, goal, robot_footprint, + dock_footprint, orientation_path)); + CHECK(orientation_path.size() > 2); + const double first_path_yaw = data_convert::getYaw( + orientation_path.front().orientation); + const double expected_reverse_path_yaw = std::atan2( + orientation_path.front().position.y - orientation_path[1].position.y, + orientation_path.front().position.x - orientation_path[1].position.x); + CHECK(near(normalizeAngle(first_path_yaw - expected_reverse_path_yaw), 0.0)); + CHECK(std::fabs(normalizeAngle( + first_path_yaw - data_convert::getYaw(prealigned_start.pose.orientation))) > 0.1); + + // Regression for the integrated run where libamr_comunication_utils was + // loaded before DockPlanner and its global CurveCommon symbol was selected. + const std::vector runtime_footprint = { + point(0.583, -0.48), point(0.583, 0.48), + point(-0.583, 0.48), point(-0.583, -0.48)}; + checkGeneratedPath(calculator, + pose(9.914814184, 9.939527902, 0.015737065), + pose(8.411853097, 10.115902417, 0.015734468), + runtime_footprint, runtime_footprint); + + std::vector path; + auto invalid_start = start; + invalid_start.pose.position.x = std::numeric_limits::infinity(); + CHECK(!calculator.makePlanMoveToDock(invalid_start, goal, robot_footprint, + dock_footprint, path)); + CHECK(path.empty()); + + CHECK(!calculator.makePlanMoveToDock(start, goal, {}, dock_footprint, path)); + CHECK(path.empty()); + + CHECK(!calculator.makePlanMoveToDock(pose(0.8, 0.2, 0.0), goal, + robot_footprint, dock_footprint, path)); + CHECK(path.empty()); + + // Slightly beyond the nominal 1.0 m alignment distance: projection_ratio + // passes the strict > 1 check, but the reference NURBS is still too short. + CHECK(!calculator.makePlanMoveToDock(pose(1.0 + 5e-10, 0.0, 0.0), goal, + robot_footprint, dock_footprint, path)); + CHECK(path.empty()); + + config.path_point_spacing = 0.0; + calculator.setConfig(config); + CHECK(!calculator.makePlanMoveToDock(start, goal, robot_footprint, + dock_footprint, path)); + CHECK(path.empty()); +} + +bool pathsEqual(const std::vector& first, + const std::vector& second) +{ + if (first.size() != second.size()) + { + return false; + } + for (std::size_t index = 0; index < first.size(); ++index) + { + if (!near(first[index].position.x, second[index].position.x) || + !near(first[index].position.y, second[index].position.y) || + !near(first[index].orientation.z, second[index].orientation.z) || + !near(first[index].orientation.w, second[index].orientation.w)) + { + return false; + } + } + return true; +} + +// A stacker-style robot: base_link at the drive cluster, forks extending +// 1.2 m behind it (-x), body 0.8 m ahead (+x). The approach distance must use +// the extent of the leading edge, not half the bounding box. +void testAsymmetricFootprint() +{ + dock_planner::DockPlannerConfig config; + dock_planner::DockCalc calculator(config); + + const std::vector stacker_footprint = { + point(0.8, -0.5), point(0.8, 0.5), point(-1.2, 0.5), point(-1.2, -0.5)}; + const std::vector rear_matched_footprint = { + point(1.2, -0.5), point(1.2, 0.5), point(-1.2, 0.5), point(-1.2, -0.5)}; + const std::vector front_matched_footprint = { + point(0.8, -0.5), point(0.8, 0.5), point(-0.8, 0.5), point(-0.8, -0.5)}; + const std::vector dock_footprint = { + point(0.5, -0.4), point(0.5, 0.4), point(-0.5, 0.4), point(-0.5, -0.4)}; + + // Goal yaw points toward the start: backward approach, the rear edge + // (forks, 1.2 m) leads. The path must match a symmetric robot with the + // same rear extent, regardless of the front extent. + const auto backing_start = pose(4.0, 0.5, 0.0); + const auto goal = pose(0.0, 0.0, 0.0); + std::vector asymmetric_path; + std::vector reference_path; + CHECK(calculator.makePlanMoveToDock(backing_start, goal, stacker_footprint, + dock_footprint, asymmetric_path)); + CHECK(calculator.makePlanMoveToDock(backing_start, goal, rear_matched_footprint, + dock_footprint, reference_path)); + CHECK(pathsEqual(asymmetric_path, reference_path)); + CHECK(calculator.makePlanMoveToDock(backing_start, goal, front_matched_footprint, + dock_footprint, reference_path)); + CHECK(!pathsEqual(asymmetric_path, reference_path)); + + // Goal yaw points away from the start: the axis flips, the approach is + // forward and the front edge (0.8 m) leads. + const auto forward_goal = pose(0.0, 0.0, 3.14159265358979323846); + CHECK(calculator.makePlanMoveToDock(backing_start, forward_goal, stacker_footprint, + dock_footprint, asymmetric_path)); + CHECK(calculator.makePlanMoveToDock(backing_start, forward_goal, front_matched_footprint, + dock_footprint, reference_path)); + CHECK(pathsEqual(asymmetric_path, reference_path)); +} + +void testDockAnchor() +{ + dock_planner::DockPlannerConfig config; + const std::vector robot_footprint = { + point(0.50, -0.35), point(0.50, 0.35), + point(-0.50, 0.35), point(-0.50, -0.35)}; + const std::vector dock_footprint = { + point(0.9, -0.8), point(0.9, 0.8), point(-0.9, 0.8), point(-0.9, -0.8)}; + + const auto start = pose(4.0, 0.6, 0.0); + const auto goal = pose(0.0, 0.0, 0.0); + + // face: the goal already sits on the approach face, so the dock footprint + // must not contribute — identical to center with no dock footprint at all. + config.dock_anchor = dock_planner::DockAnchor::kFace; + dock_planner::DockCalc face_calculator(config); + std::vector face_path; + CHECK(face_calculator.makePlanMoveToDock(start, goal, robot_footprint, + dock_footprint, face_path)); + + config.dock_anchor = dock_planner::DockAnchor::kCenter; + dock_planner::DockCalc center_calculator(config); + std::vector no_dock_path; + CHECK(center_calculator.makePlanMoveToDock(start, goal, robot_footprint, + {}, no_dock_path)); + CHECK(pathsEqual(face_path, no_dock_path)); + + // center with a real dock footprint must differ from face: the near-face + // extent (0.9 m) pushes the alignment pose further out. + std::vector center_path; + CHECK(center_calculator.makePlanMoveToDock(start, goal, robot_footprint, + dock_footprint, center_path)); + CHECK(!pathsEqual(face_path, center_path)); +} + +} // namespace + +int main() +{ + testConfig(); + testPathGeneration(); + testAsymmetricFootprint(); + testDockAnchor(); + if (failures != 0) + { + std::cerr << failures << " DockPlanner test assertion(s) failed.\n"; + return 1; + } + std::cout << "DockPlanner tests passed.\n"; + return 0; +}