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
  "~/<name>" 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) <noreply@anthropic.com>
This commit is contained in:
2026-08-12 21:52:52 +07:00
parent 91ba7b1569
commit 539fc5da16
14 changed files with 1760 additions and 2553 deletions

View File

@@ -4,7 +4,6 @@ project(dock_planner VERSION 1.0.0 LANGUAGES CXX)
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
set(BUILDING_WITH_CATKIN TRUE) set(BUILDING_WITH_CATKIN TRUE)
message(STATUS "Building dock_planner with Catkin") message(STATUS "Building dock_planner with Catkin")
else() else()
set(BUILDING_WITH_CATKIN FALSE) set(BUILDING_WITH_CATKIN FALSE)
message(STATUS "Building dock_planner with Standalone CMake") message(STATUS "Building dock_planner with Standalone CMake")
@@ -15,9 +14,14 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) 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(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)
@@ -29,14 +33,9 @@ if (NOT BUILDING_WITH_CATKIN)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
set(PACKAGES_DIR # Library targets provided by the standalone parent build.
robot_visualization_msgs set(STANDALONE_DEP_TARGETS
robot_nav_msgs
robot_nav_2d_msgs
robot_nav_2d_utils
robot_std_msgs
robot_geometry_msgs robot_geometry_msgs
tf3
robot_time robot_time
data_convert data_convert
robot_costmap_2d robot_costmap_2d
@@ -44,19 +43,12 @@ if (NOT BUILDING_WITH_CATKIN)
robot_cpp robot_cpp
) )
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
else() else()
# ======================================================== # ========================================================
# Catkin specific configuration # Catkin specific configuration
# ======================================================== # ========================================================
find_package(catkin REQUIRED COMPONENTS 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_geometry_msgs
robot_time robot_time
data_convert data_convert
@@ -65,25 +57,12 @@ else()
robot_cpp 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( catkin_package(
INCLUDE_DIRS include INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME} 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 DEPENDS Eigen3 Boost
) )
include_directories(
include
${catkin_INCLUDE_DIRS}
${EIGEN3_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS}
${TF3_INCLUDE_DIR}
)
endif() endif()
# ======================================================== # ========================================================
@@ -91,43 +70,40 @@ endif()
# ======================================================== # ========================================================
add_library(${PROJECT_NAME} SHARED add_library(${PROJECT_NAME} SHARED
src/dock_planner.cpp src/dock_planner.cpp
src/dock_planner_config.cpp
src/dock_calc.cpp src/dock_calc.cpp
src/utils/curve_common.cpp src/utils/curve_common.cpp
src/utils/pose.cpp src/utils/pose.cpp
src/utils/line_common.cpp src/utils/line_common.cpp
) )
if(BUILDING_WITH_CATKIN)
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_include_directories(${PROJECT_NAME} target_include_directories(${PROJECT_NAME}
PUBLIC PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include> $<INSTALL_INTERFACE:include>
${TF3_INCLUDE_DIR} 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 ${catkin_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} target_link_libraries(${PROJECT_NAME}
PUBLIC ${catkin_LIBRARIES} PUBLIC ${catkin_LIBRARIES} Threads::Threads
PRIVATE Eigen3::Eigen Boost::system Boost::thread Boost::filesystem PRIVATE Eigen3::Eigen yaml-cpp
${TF3_LIBRARY}
) )
else() else()
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
${TF3_INCLUDE_DIR}
)
target_link_libraries(${PROJECT_NAME} target_link_libraries(${PROJECT_NAME}
PUBLIC PUBLIC
${PACKAGES_DIR} ${STANDALONE_DEP_TARGETS}
Threads::Threads
PRIVATE PRIVATE
Eigen3::Eigen Boost::system Boost::thread Boost::filesystem Eigen3::Eigen
${TF3_LIBRARY} yaml-cpp
) )
set_target_properties(${PROJECT_NAME} PROPERTIES set_target_properties(${PROJECT_NAME} PROPERTIES
@@ -138,12 +114,31 @@ else()
endif() 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 # Install
# ======================================================== # ========================================================
if(BUILDING_WITH_CATKIN) if(BUILDING_WITH_CATKIN)
## Mark libraries for installation ## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
install(TARGETS ${PROJECT_NAME} install(TARGETS ${PROJECT_NAME}
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
@@ -185,6 +180,6 @@ else()
message(STATUS "Project: ${PROJECT_NAME}") message(STATUS "Project: ${PROJECT_NAME}")
message(STATUS "Version: ${PROJECT_VERSION}") message(STATUS "Version: ${PROJECT_VERSION}")
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") 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 "=================================") message(STATUS "=================================")
endif() endif()

374
README.md
View File

@@ -1,312 +1,108 @@
# Dock Planner # 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 ## Luồng xử lý
```
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:<br/>cost_threshold, calib_safety_distance"]
I2 --> I3["Load footprint_dock<br/>tu param server"]
end
subgraph PLAN["2. LAP KE HOACH - DockPlanner::makePlan"]
P1["Lay footprint_robot<br/>tu costmap"] --> P2["Goi DockCalc::makePlanMoveToDock"]
P2 --> P3["Chuyen vector Pose<br/>thanh vector PoseStamped"]
end
subgraph CALC["3. TINH TOAN - DockCalc::makePlanMoveToDock"]
C1["Tinh RobotGeometry + safety_distance"]
C2["Xac dinh huong tiep can<br/>forward / backward"]
C3["Tinh angle_threshold<br/>heuristic"]
C4["Tao duong tam NURBS<br/>findPathTMP"]
C5["Tim control points<br/>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_<br/>costmap_<br/>frame_id_"]
C --> D["getParam:<br/>check_free_space<br/>cost_threshold<br/>calib_safety_distance"]
D --> E["Copy params<br/>sang DockCalc"]
E --> F["footprintFromParams<br/>→ footprint_dock_"]
F --> G["initialized_ = true"]
G --> Z
```
### 2. Lap ke hoach (makePlan)
```mermaid ```mermaid
flowchart TD flowchart TD
A["makePlan(start, goal, plan)"] --> B{initialized_?} A["DockPlanner::initialize"] --> B["Kiểm tra costmap và global frame"]
B -- false --> FAIL["return false"] B --> C["Load và validate DockPlannerConfig"]
B -- true --> C["footprint_robot =<br/>costmap_robot_->getRobotFootprint()"] C --> D["Load footprint_dock nếu có"]
C --> D["makePlanMoveToDock<br/>(start, goal, footprint_robot,<br/>footprint_dock_, degree=2, step=0.02)"] D --> E["DockPlanner::makePlan"]
D --> E{Thanh cong?} E --> F["Kiểm tra start/goal cùng global frame"]
E -- false --> FAIL F --> G["Lấy robot footprint từ costmap"]
E -- true --> F["Chuyen moi Pose thanh PoseStamped<br/>(gan timestamp, frame_id)"] G --> H["DockCalc::makePlanMoveToDock"]
F --> G["return true"] 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 ## Hợp đồng đầu vào
flowchart TD
START["makePlanMoveToDock(start, goal)"] --> GEOM
subgraph GEOM["BUOC 1: Tinh hinh hoc"] - `start` và `goal` phải có pose hữu hạn, quaternion hợp lệ và cùng
G1["computeGeometry(footprint_robot)<br/>→ robot.length, robot.radius"] `global_frame` của costmap.
G2["computeGeometry(footprint_dock)<br/>→ dock.length"] - Robot footprint phải có ít nhất 3 điểm, có kích thước X/Y dương. Footprint
G3["safety_distance =<br/>(robot.radius + calib) * 2"] được phép lệch tâm so với base_link (ví dụ forklift có càng chìa một phía):
G1 --> G3 khoảng tiếp cận dùng extent của mép dẫn đầu theo chiều chạy segment cuối
G2 --> G3 (tiến → mép +x, lùi → mép −x), không dùng nửa bounding box.
end - `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<br/>AND safety > 0?} `footprint_dock` và `dock_anchor` được runtime cập nhật từ
VALID -- false --> ERR["return false"] `docking_marker_profiles/<marker>/` vào namespace `DockPlanner` trước khi tạo
VALID -- true --> POSE_C 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"] ## Tham số cấu hình
PC1["distance_min_C =<br/>(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
POSE_C --> DIR File mặc định: `config/dock_global_params.yaml`.
subgraph DIR["BUOC 3: Xac dinh huong di"] | Tham số | Mặc định | Đơn vị | Mô tả |
D1["t = compute_t(start, goal, Pose_C)"] |---|---:|---|---|
D2{t < 0 ?} | `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 |
D3["Lat yaw_goal 180 do<br/>Tinh lai Pose_C va t<br/>dir = backward"] | `approach/lateral_distance_near` | `0.10` | m | Cận dưới của miền nội suy angle threshold |
D4["dir = forward"] | `approach/lateral_distance_far` | `1.00` | m | Cận trên của miền nội suy angle threshold |
D1 --> D2 | `approach/angle_threshold_near` | `2.35619449019` | rad | Ngưỡng góc tại lateral distance gần |
D2 -- Co --> D3 | `approach/angle_threshold_far` | `1.09955742876` | rad | Ngưỡng góc tại lateral distance xa |
D2 -- Khong --> D4 | `approach/direction_angle_hysteresis` | `0.05` | rad | Biên trễ khi phân loại hướng nối vào reference path |
end | `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 ?} Quan hệ bắt buộc:
T_CHECK -- false --> ERR
T_CHECK -- true --> ANGLE
subgraph ANGLE["BUOC 4: Tinh angle threshold"] - `0 <= lateral_distance_near < lateral_distance_far`
A1["Pose_D = compute_D(goal, Pose_C, t)"] - `0 < angle_threshold_far < angle_threshold_near < pi`
A2["distance_AD =<br/>pointToSegmentDistance(start, goal, Pose_C)"] - `0 <= direction_angle_hysteresis < angle_threshold_far`
A3["scale = f(distance_AD)<br/>angle_threshold =<br/>min((alpha+|scale|)*beta*pi, gamma*pi)"] - `0 < path_point_spacing <= 1.0`
A1 --> A3 - 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.
A2 --> A3
end
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"] ## Tham số cố ý không tồn tại
T1["Tinh Pose_F = offsetPoint(goal, yaw, dist_F)"]
T2["mid = trung diem(C, F)"]
T3["findPathTMP({C, mid, F})<br/>→ saved_poses_tmp"]
T1 --> T2 --> T3
end
TMP_PATH --> TMP_OK{Path tmp ok?} `check_free_space`, `cost_threshold`, `allow_unknown` và
TMP_OK -- false --> ERR `calib_safety_distance` không được đọc và không nên khai báo. Collision checker
TMP_OK -- true --> SEG1 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"] ## Cấu trúc chính
S1["findNURBSControlPoints<br/>(start, saved_poses_tmp, angle_threshold)<br/>→ control_points_1, dir"]
S2["Xac dinh chieu reverse<br/>cua segment 1"]
S3["generateNURBSPath(control_points_1)<br/>→ first_segment"]
S1 --> S2 --> S3
end
SEG1 --> SEG1_OK{first_segment<br/>khong rong?} ```text
SEG1_OK -- false --> ERR include/dock_planner/
SEG1_OK -- true --> SEG2 dock_planner.h Plugin interface
dock_planner_config.h Load, validate và nội suy config
subgraph SEG2["BUOC 7: Sinh segment 2"] dock_calc.h Core hình học độc lập với plugin
S4["mid_ctrl = trung diem<br/>(first_segment.back, goal)"] utils/curve_common.h Đánh giá NURBS tối thiểu (setup + CalculateCurvePoint)
S5["generateNURBSPath<br/>({last_of_seg1, mid_ctrl, goal})<br/>→ second_segment"] src/
S4 --> S5 dock_planner.cpp
end dock_planner_config.cpp
dock_calc.cpp
SEG2 --> ASSEMBLE["BUOC 8: Ghep duong di<br/>start + seg1 + seg2 + goal"] utils/curve_common.cpp
ASSEMBLE --> OK["return true"] test/
dock_planner_test.cpp
config/
dock_global_params.yaml
``` ```
### 4. Sinh duong NURBS (generateNURBSPath) `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,
```mermaid curvature và visualization của bản gốc đã bị loại bỏ cùng với code không còn
flowchart TD được gọi.
A["generateNURBSPath<br/>(control_points, check_free,<br/>edge_end, reverse)"] --> B["setupSpline(control_points, degree)<br/>Tao knot vector + weights<br/>Nap vao Spline_Inf"]
B --> C["Tinh chieu dai NURBS<br/>calculateNURBSLength"]
C --> D["step_new = resolution / length<br/>(adaptive step)"]
D --> E["Duyet t = 0 → 1<br/>(buoc step_new)"]
E --> F["point = CalculateCurvePoint(t)"]
F --> G{point hop le?<br/>khong NaN?}
G -- false --> E
G -- true --> H{Kiem tra<br/>isFreeSpace?}
H -- Bi chan --> I["obstacle_flag = true<br/>BREAK"]
H -- Thong --> J["Luu pose<br/>Cap nhat orientation"]
J --> E
I --> K["result.clear()"]
E -- t > 1.0 --> L["Gan orientation<br/>cho diem cuoi"]
L --> M["return result"]
K --> M
```
### 5. Tim control points (findNURBSControlPoints)
```mermaid
flowchart TD
A["findNURBSControlPoints<br/>(start, saved_poses, angle_threshold)"] --> B["findNearestPointOnPath<br/>→ 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<br/>sao cho dist >= target<br/>→ end_idx"]
F --> G["Them saved[end_idx]"]
E -- Khong, dir == -1 --> H["Them saved.back()"]
C -- idx == -1 --> I["mid = trung diem<br/>(start, nearest)"]
I --> J["control_points =<br/>{start, mid, nearest}"]
G --> K["return true"]
H --> K
J --> K
```
### 6. Tim diem gan nhat tren duong (findNearestPointOnPath)
```mermaid
flowchart TD
A["findNearestPointOnPath<br/>(pose, saved_poses, angle_threshold)"] --> B["Tim nearest_idx<br/>(khoang cach nho nhat)"]
B --> C["Duyet nguoc tu nearest_idx → 1"]
C --> D{signedAngle >= threshold?}
D -- Co --> E["nearest_idx = i<br/>found_flag_1 = true"]
D -- Khong --> C
E --> F{Kiem tra khoang cach<br/>distance_2 >= distance_1?}
F -- Co --> G["dir = 1<br/>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<br/>return nearest_idx"]
I -- Khong, i == cuoi --> K["dir = 0<br/>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<br/>(NURBS engine)"]
spline["Spline_Inf<br/>(knot/ctrl/weight)"]
end
init -->|"config params"| calc
make -->|"start, goal,<br/>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.

View File

@@ -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: DockPlanner:
# File: config/planner_params.yaml # Boost.DLL library containing the exported symbol "DockPlanner".
MyGlobalPlanner: library_path: libdock_planner
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 approach:
global_costmap: # [m] Extra straight alignment distance beyond half the combined robot/dock
inflation_radius: 0.3 # Bán kính phình vật cản # X extents. Increase if the robot must align earlier before entering a dock.
cost_scaling_factor: 10.0 # Hệ số tỷ lệ chi phí 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/<marker>/ 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.

View File

@@ -1,139 +1,96 @@
#ifndef DOCK_CALC_H #ifndef DOCK_PLANNER_DOCK_CALC_H_
#define DOCK_CALC_H #define DOCK_PLANNER_DOCK_CALC_H_
#include <robot_nav_2d_utils/footprint.h>
#include <robot_geometry_msgs/PoseStamped.h>
#include <robot_nav_msgs/Path.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/costmap_2d.h>
#include <tf3/LinearMath/Quaternion.h>
#include "dock_planner/utils/curve_common.h"
#include "dock_planner/utils/pose.h"
#include "dock_planner/utils/common.h"
#include <robot/robot.h>
#include <memory> #include <memory>
#include <mutex>
#include <vector> #include <vector>
#include <robot_geometry_msgs/PoseStamped.h>
#include "dock_planner/dock_planner_config.h"
#include "dock_planner/utils/curve_common.h"
namespace dock_planner namespace dock_planner
{ {
struct RobotGeometry struct RobotGeometry
{ {
double length; // dọc trục X double length = 0.0; // [m], bounding-box extent along footprint X
double width; // dọc trục Y double width = 0.0; // [m], bounding-box extent along footprint Y
double radius; // circle around base_link // 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
}; };
/** Pure docking-path geometry. Collision checking is intentionally out of scope. */
class DockCalc class DockCalc
{ {
private:
std::unique_ptr<Spline_Inf> input_spline_inf;
std::unique_ptr<CurveCommon> CurveDesign;
std::vector<robot_geometry_msgs::Point> footprint_robot_;
robot_geometry_msgs::PoseStamped save_goal_;
bool check_goal_;
int store_start_nearest_idx_;
int start_target_idx_;
double min_distance_to_goal_;
// 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);
}
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;
}
inline double calculateAngle(double x1, double y1, double x2, double y2)
{
double angle = atan2(y2 - y1, x2 - x1);
return angle;
}
inline double normalizeAngle(double angle)
{
return std::remainder(angle, 2.0 * M_PI);
}
double calculateNURBSLength(CurveCommon* curve_design,
Spline_Inf* spline_inf,
int degree,
double initial_step = 0.02);
robot_geometry_msgs::Pose offsetPoint(const robot_geometry_msgs::Pose& A,const double& theta, const double& d);
double pointToSegmentDistance(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C);
double signedAngle(const robot_geometry_msgs::Pose& A, const robot_geometry_msgs::Pose& B, const robot_geometry_msgs::Pose& C);
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<robot_geometry_msgs::Pose>& control_points, int degree);
void updatePoseOrientation(std::vector<robot_geometry_msgs::Pose>& saved_poses,
std::vector<robot_geometry_msgs::Pose>& nurbs_path,
bool reverse = true);
bool findPathTMP(const std::vector<robot_geometry_msgs::Pose>& control_points,
std::vector<robot_geometry_msgs::Pose>& saved_poses,
const int& degree, double step = 0.02);
bool findNURBSControlPoints(int& dir, std::vector<robot_geometry_msgs::Pose>& control_points,
const robot_geometry_msgs::Pose& start_pose,
const std::vector<robot_geometry_msgs::Pose>& posesOnPathWay,
const double& angle_threshol, const int& degree);
int findNearestPointOnPath(int& dir, const robot_geometry_msgs::Pose& pose,
const std::vector<robot_geometry_msgs::Pose>& posesOnPathWay,
const double& angle_threshol);
bool isFreeSpace(const robot_geometry_msgs::Pose& pose, const std::vector<robot_geometry_msgs::Point>& footprint);
std::vector<robot_geometry_msgs::Point> calcFreeZone(const robot_geometry_msgs::Pose& pose,
const std::vector<robot_geometry_msgs::Point>& footprint);
std::vector<robot_geometry_msgs::Point> interpolateFootprint(const robot_geometry_msgs::Pose& pose,
const std::vector<robot_geometry_msgs::Point>& footprint, const double& resolution);
RobotGeometry computeGeometry(const std::vector<robot_geometry_msgs::Point>& fp);
public: 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();
explicit DockCalc(const DockPlannerConfig& config);
~DockCalc(); ~DockCalc();
bool makePlanMoveToDock(const robot_geometry_msgs::PoseStamped& start, void setConfig(const DockPlannerConfig& config);
bool makePlanMoveToDock(
const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal, const robot_geometry_msgs::PoseStamped& goal,
const std::vector<robot_geometry_msgs::Point>& footprint_robot, const std::vector<robot_geometry_msgs::Point>& footprint_robot,
const std::vector<robot_geometry_msgs::Point>& footprint_dock, const std::vector<robot_geometry_msgs::Point>& footprint_dock,
const int& degree, const double& step, std::vector<robot_geometry_msgs::Pose>& plan);
std::vector<robot_geometry_msgs::Pose>& planMoveToDock,
bool reverse = false);
private:
static constexpr int kNurbsDegree = 2;
std::unique_ptr<Spline_Inf> input_spline_inf_;
std::unique_ptr<CurveCommon> curve_design_;
DockPlannerConfig config_;
std::mutex calculation_mutex_;
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<robot_geometry_msgs::Point>& footprint);
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);
bool setupSpline(const std::vector<robot_geometry_msgs::Pose>& control_points);
double calculateNurbsLength(double sample_step = 0.02);
bool sampleCurve(const std::vector<robot_geometry_msgs::Pose>& control_points,
std::vector<robot_geometry_msgs::Pose>& path,
bool reverse_orientation);
bool sampleTemporaryCurve(const std::vector<robot_geometry_msgs::Pose>& control_points,
std::vector<robot_geometry_msgs::Pose>& path);
bool findNurbsControlPoints(int& direction,
std::vector<robot_geometry_msgs::Pose>& control_points,
const robot_geometry_msgs::Pose& start_pose,
const std::vector<robot_geometry_msgs::Pose>& reference_path,
double angle_threshold);
int findNearestPointOnPath(int& direction, std::size_t& nearest_index,
const robot_geometry_msgs::Pose& pose,
const std::vector<robot_geometry_msgs::Pose>& path,
double angle_threshold) const;
}; };
} // namespace dock_planner } // namespace dock_planner
#endif // DOCK_PLANNER_DOCK_CALC_H_
#endif

View File

@@ -1,40 +1,39 @@
#ifndef DOCK_PLANNER_H #ifndef DOCK_PLANNER_DOCK_PLANNER_H_
#define DOCK_PLANNER_H #define DOCK_PLANNER_DOCK_PLANNER_H_
#include <string>
#include <vector>
#include "dock_planner/dock_calc.h"
#include <robot_nav_core/base_global_planner.h> #include <robot_nav_core/base_global_planner.h>
namespace dock_planner { #include "dock_planner/dock_calc.h"
#include "dock_planner/dock_planner_config.h"
namespace dock_planner
{
class DockPlanner : public robot_nav_core::BaseGlobalPlanner class DockPlanner : public robot_nav_core::BaseGlobalPlanner
{ {
public: public:
DockPlanner(); DockPlanner();
DockPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot);
bool initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot); bool initialize(std::string name,
robot_costmap_2d::Costmap2DROBOT* costmap_robot) override;
bool makePlan(const robot_geometry_msgs::PoseStamped& start, bool makePlan(const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal, const robot_geometry_msgs::PoseStamped& goal,
std::vector<robot_geometry_msgs::PoseStamped>& plan); std::vector<robot_geometry_msgs::PoseStamped>& plan) override;
static robot_nav_core::BaseGlobalPlanner::Ptr create(); static robot_nav_core::BaseGlobalPlanner::Ptr create();
private: private:
// Core components robot_costmap_2d::Costmap2DROBOT* costmap_robot_ = nullptr; // non-owning
robot_costmap_2d::Costmap2DROBOT* costmap_robot_; bool initialized_ = false;
robot_costmap_2d::Costmap2D* costmap_; std::string global_frame_;
bool initialized_;
std::string frame_id_;
std::vector<robot_geometry_msgs::Point> footprint_dock_; std::vector<robot_geometry_msgs::Point> footprint_dock_;
DockCalc dock_calc_;
int cost_threshold_;
double calib_safety_distance_;
bool check_free_space_;
DockCalc calc_plan_to_dock_;
}; };
} // namespace dock_planner } // namespace dock_planner
#endif #endif // DOCK_PLANNER_DOCK_PLANNER_H_

View File

@@ -0,0 +1,63 @@
#ifndef DOCK_PLANNER_DOCK_PLANNER_CONFIG_H_
#define DOCK_PLANNER_DOCK_PLANNER_CONFIG_H_
#include <string>
#include <robot/node_handle.h>
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_

View File

@@ -1,43 +0,0 @@
#ifndef CONVERSION_H_
#define CONVERSION_H_
#include "curve_common.h"
#include <Eigen/Geometry>
#include <robot_geometry_msgs/Point.h>
#include <robot_geometry_msgs/Quaternion.h>
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<robot_geometry_msgs::PoseStamped> &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<robot_geometry_msgs::Point> &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_

View File

@@ -1,82 +1,62 @@
#ifndef CURVE_COMMON_H_ #ifndef DOCK_PLANNER_UTILS_CURVE_COMMON_H_
#define CURVE_COMMON_H_ #define DOCK_PLANNER_UTILS_CURVE_COMMON_H_
#include <vector>
#include <Eigen/Eigen> #include <Eigen/Eigen>
#include <robot_nav_msgs/Path.h>
#include <robot_geometry_msgs/Point.h> #include <robot_geometry_msgs/Point.h>
#include <robot_visualization_msgs/Marker.h>
#include "color.h"
#include <robot/robot.h>
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 struct Spline_Inf
{ {
int order; int order = 0;
std::vector<double> knot_vector; std::vector<double> knot_vector;
std::vector<double> weight; std::vector<double> weight;
//std::vector<double> N;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> control_point; std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> control_point;
std::vector<Eigen::VectorXd, Eigen::aligned_allocator<Eigen::VectorXd> > N;
std::vector<Eigen::VectorXd, Eigen::aligned_allocator<Eigen::VectorXd> > dN;
std::vector<Eigen::VectorXd, Eigen::aligned_allocator<Eigen::VectorXd> > ddN;
std::vector<double> N_double_vec; std::vector<double> N_double_vec;
std::vector<double> R_double_vec;
std::vector<double> dR_double_vec;
std::vector<double> ddR_double_vec;
// std::vector<double> ddN_double_vec;
//Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, Eigen::Dynamic> N; //bsaic function
Eigen::MatrixXd curvefit_N;
};
struct EigenTrajectoryPoint
{
typedef std::vector<EigenTrajectoryPoint, Eigen::aligned_allocator<EigenTrajectoryPoint> > 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 class CurveCommon
{ {
public: public:
CurveCommon(); 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); /** Check degree and the knot/control-point count relation. */
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);
bool curveIsValid(int degree, const std::vector<double>& knot_vector, bool curveIsValid(int degree, const std::vector<double>& knot_vector,
std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>& control_points); const std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>& control_points);
void ReadSplineInf(Spline_Inf* bspline_inf, int order, std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > control_point, std::vector<double> knot_vector); /** Store order, knot vector, and control points into spline_inf. */
void ReadSplineInf(Spline_Inf* bspline_inf, std::vector<double> weight_vector, bool use_limit_derivative_fitting); void ReadSplineInf(Spline_Inf* spline_inf, int order,
void ReadDiscreate2DPointFromLaunch(EigenTrajectoryPoint::Vector* input_point, std::vector<double> file_discreate_point); const std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>& control_point,
void ReadDiscreate2DPointFromLaunch(std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> >* input_point, std::vector<double> file_discreate_point); const std::vector<double>& knot_vector);
void ShowDiscreatePoint(robot_visualization_msgs::Marker* points, EigenTrajectoryPoint::Vector discreate_point);
void ShowDiscreatePoint(robot_visualization_msgs::Marker* points, std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > 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<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > discreate_point, const std::string& frame_id, const std::string& name, double scale);
robot_visualization_msgs::Marker ShowDiscreatePoint2(std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale);
private:
/** Store the NURBS weights; must be called after the control points. */
void ReadSplineInf(Spline_Inf* spline_inf, const std::vector<double>& 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_ } // namespace dock_planner
#endif // DOCK_PLANNER_UTILS_CURVE_COMMON_H_

View File

@@ -1,58 +1,19 @@
<package> <?xml version="1.0"?>
<package format="2">
<name>dock_planner</name> <name>dock_planner</name>
<version>0.7.10</version> <version>0.7.11</version>
<description> <description>Global planner that generates a quadratic NURBS approach path for docking.</description>
dock_planner is the second generation of the transform library, which lets <maintainer email="xroboticdevs@gmail.com">duongtd</maintainer>
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.
</description>
<author>Tully Foote</author>
<author>Eitan Marder-Eppstein</author>
<author>Wim Meeussen</author>
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
<license>BSD</license> <license>BSD</license>
<url type="website">http://www.ros.org/wiki/dock_planner</url> <buildtool_depend>catkin</buildtool_depend>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <depend>robot_costmap_2d</depend>
<depend>robot_nav_core</depend>
<build_depend>robot_costmap_2d</build_depend> <depend>robot_geometry_msgs</depend>
<run_depend>robot_costmap_2d</run_depend> <depend>robot_cpp</depend>
<depend>robot_time</depend>
<build_depend>robot_nav_core</build_depend> <depend>data_convert</depend>
<run_depend>robot_nav_core</run_depend> <depend>yaml-cpp</depend>
<build_depend>robot_geometry_msgs</build_depend>
<run_depend>robot_geometry_msgs</run_depend>
<build_depend>robot_nav_msgs</build_depend>
<run_depend>robot_nav_msgs</run_depend>
<build_depend>robot_std_msgs</build_depend>
<run_depend>robot_std_msgs</run_depend>
<build_depend>robot_cpp</build_depend>
<run_depend>robot_cpp</run_depend>
<build_depend>robot_time</build_depend>
<run_depend>robot_time</run_depend>
<build_depend>robot_visualization_msgs</build_depend>
<run_depend>robot_visualization_msgs</run_depend>
<build_depend>data_convert</build_depend>
<run_depend>data_convert</run_depend>
<build_depend>robot_nav_2d_msgs</build_depend>
<run_depend>robot_nav_2d_msgs</run_depend>
<build_depend>robot_nav_2d_utils</build_depend>
<run_depend>robot_nav_2d_utils</run_depend>
</package> </package>

File diff suppressed because it is too large Load Diff

View File

@@ -1,124 +1,217 @@
#include "dock_planner/dock_planner.h" #include "dock_planner/dock_planner.h"
#include <cmath>
#include <algorithm> #include <algorithm>
#include <cmath>
#include <utility>
#include <boost/dll/alias.hpp> #include <boost/dll/alias.hpp>
#include <robot/robot.h>
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)
{ {
initialize(name, costmap_robot);
enum class FootprintLoadStatus
{
kMissing,
kValid,
kInvalid,
};
FootprintLoadStatus loadDockFootprint(
const robot::NodeHandle& nh, const std::string& planner_name,
std::vector<robot_geometry_msgs::Point>& footprint)
{
footprint.clear();
YAML::Node node;
if (!nh.getParam("footprint_dock", node) || !node.IsDefined())
{
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;
} }
/** footprint.reserve(node.size());
* @brief Khởi tạo global planner for (std::size_t index = 0; index < node.size(); ++index)
* @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)
{ {
if (!initialized_) const YAML::Node& point_node = node[index];
if (!point_node.IsSequence() || point_node.size() != 2)
{ {
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<double>();
point.y = point_node[1].as<double>();
}
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;
}
if (name.empty())
{
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;
}
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;
}
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<robot_geometry_msgs::Point> 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;
}
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());
}
}
costmap_robot_ = costmap_robot; costmap_robot_ = costmap_robot;
costmap_ = costmap_robot_->getCostmap(); global_frame_ = costmap_robot->getGlobalFrameID();
frame_id_ = costmap_robot_->getGlobalFrameID(); footprint_dock_ = std::move(loaded_footprint);
calc_plan_to_dock_.costmap_ = costmap_robot_->getCostmap(); dock_calc_.setConfig(loaded_config);
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; initialized_ = true;
}
return true; return true;
} }
bool DockPlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, bool DockPlanner::makePlan(
const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal, const robot_geometry_msgs::PoseStamped& goal,
std::vector<robot_geometry_msgs::PoseStamped>& plan) std::vector<robot_geometry_msgs::PoseStamped>& plan)
{ {
if(!initialized_) return false;
plan.clear(); plan.clear();
if (!initialized_ || costmap_robot_ == nullptr)
std::vector<robot_geometry_msgs::Pose> planMoveToDock; {
std::vector<robot_geometry_msgs::Point> footprint_robot = costmap_robot_->getRobotFootprint(); robot::log_error("[dock_planner] makePlan() called before successful initialize().\n");
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))
return false; 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<robot_geometry_msgs::Pose> path;
if (!dock_calc_.makePlanMoveToDock(start, goal, costmap_robot_->getRobotFootprint(),
footprint_dock_, path) || path.empty())
{
return false;
}
const robot::Time plan_time = robot::Time::now(); const robot::Time plan_time = robot::Time::now();
const std::string& global_frame = costmap_robot_->getGlobalFrameID(); plan.reserve(path.size());
plan.reserve(planMoveToDock.size()); for (const auto& path_pose : path)
for (const auto& p : planMoveToDock)
{ {
robot_geometry_msgs::PoseStamped pose; robot_geometry_msgs::PoseStamped stamped_pose;
pose.header.stamp = plan_time; stamped_pose.header.stamp = plan_time;
pose.header.frame_id = global_frame; stamped_pose.header.frame_id = global_frame_;
pose.pose.position.x = p.position.x; stamped_pose.pose = path_pose;
pose.pose.position.y = p.position.y; plan.push_back(stamped_pose);
pose.pose.position.z = 0;
pose.pose.orientation = p.orientation;
plan.push_back(pose);
} }
return true; return true;
} }
// Export factory function robot_nav_core::BaseGlobalPlanner::Ptr DockPlanner::create()
robot_nav_core::BaseGlobalPlanner::Ptr DockPlanner::create() { {
return std::make_shared<dock_planner::DockPlanner>(); return std::make_shared<DockPlanner>();
} }
} // namespace dock_planner } // namespace dock_planner
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)
BOOST_DLL_ALIAS(dock_planner::DockPlanner::create, DockPlanner) BOOST_DLL_ALIAS(dock_planner::DockPlanner::create, DockPlanner)

178
src/dock_planner_config.cpp Normal file
View File

@@ -0,0 +1,178 @@
#include "dock_planner/dock_planner_config.h"
#include <algorithm>
#include <cmath>
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

File diff suppressed because it is too large Load Diff

300
test/dock_planner_test.cpp Normal file
View File

@@ -0,0 +1,300 @@
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include <data_convert/data_convert.h>
#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_geometry_msgs::Point>& robot_footprint,
const std::vector<robot_geometry_msgs::Point>& dock_footprint)
{
std::vector<robot_geometry_msgs::Pose> 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<double>::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_geometry_msgs::Point> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Pose> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Pose> path;
auto invalid_start = start;
invalid_start.pose.position.x = std::numeric_limits<double>::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<robot_geometry_msgs::Pose>& first,
const std::vector<robot_geometry_msgs::Pose>& 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Pose> asymmetric_path;
std::vector<robot_geometry_msgs::Pose> 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_geometry_msgs::Point> 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<robot_geometry_msgs::Point> 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<robot_geometry_msgs::Pose> 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<robot_geometry_msgs::Pose> 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<robot_geometry_msgs::Pose> 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;
}