commit 72435b76fd8c2485d5f1854ad9b29d6f3eb4c0a4 Author: duongtd Date: Sun Aug 9 18:48:16 2026 +0700 first commit diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..eacbe95 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,152 @@ +cmake_minimum_required(VERSION 3.10) +project(sbpl_recovery) + +# C++17 theo quy ước workspace cho code mới. +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(catkin REQUIRED COMPONENTS + recovery_core + robot_cpp + robot_costmap_2d + robot_nav_core + robot_geometry_msgs + robot_nav_msgs + robot_tf3_geometry_msgs +) + +find_package(Boost REQUIRED COMPONENTS + system + filesystem + thread +) + +find_package(Threads REQUIRED) + +# tf3 cài sẵn ngoài workspace (xem CLAUDE.md) — không phải package catkin. +find_library(TF3_LIBRARY + NAMES tf3 + + PATHS + /usr/lib + /usr/local/lib + /usr/lib/x86_64-linux-gnu +) + +if(NOT TF3_LIBRARY) + message(FATAL_ERROR + "sbpl_recovery: libtf3 not found. Install tf3 (see the auto_setup.sh scripts under " + "Controllers/, Devices/, Localizations/) or add its location to CMAKE_PREFIX_PATH.") +endif() + +catkin_package( + INCLUDE_DIRS + include + + LIBRARIES + sbpl_recovery + + CATKIN_DEPENDS + recovery_core + robot_cpp + robot_costmap_2d + robot_nav_core + robot_geometry_msgs + robot_nav_msgs + robot_tf3_geometry_msgs + + DEPENDS + Boost +) + +# ================================================================================================== +# Plugin: libsbpl_recovery.so — export symbol `DetourPathRecovery` (Boost.DLL) +# ================================================================================================== + +add_library(sbpl_recovery SHARED + plugins/detour_path_recovery.cpp +) + +target_compile_options(sbpl_recovery PRIVATE -Wall -Wextra) + +# Header dependency vào dạng SYSTEM để -Wall -Wextra của chính gói không bị warning của +# robot_cpp/costmap_2d nhấn chìm — cùng lý do với recovery_core. +target_include_directories(sbpl_recovery SYSTEM + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} +) + +target_link_libraries(sbpl_recovery + PRIVATE + ${catkin_LIBRARIES} + Boost::system + Boost::filesystem + Boost::thread + Threads::Threads + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} +) + +add_dependencies(sbpl_recovery ${catkin_EXPORTED_TARGETS}) + +install(TARGETS sbpl_recovery + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} +) + +# ================================================================================================== +# Test +# ================================================================================================== + +if(CATKIN_ENABLE_TESTING) + # Planner giả cho unit test — nạp qua đúng đường Boost.DLL mà runtime đi. + add_library(sbpl_recovery_test_line_planner SHARED + test/plugins/test_line_planner.cpp + ) + target_compile_options(sbpl_recovery_test_line_planner PRIVATE -Wall -Wextra) + target_include_directories(sbpl_recovery_test_line_planner SYSTEM + PRIVATE + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + target_link_libraries(sbpl_recovery_test_line_planner + PRIVATE + ${catkin_LIBRARIES} + Boost::system + Boost::filesystem + Threads::Threads + ${CMAKE_DL_LIBS} + ) + + catkin_add_gtest(detour_path_recovery_test test/detour_path_recovery_test.cpp) + if(TARGET detour_path_recovery_test) + target_compile_options(detour_path_recovery_test PRIVATE -Wall -Wextra) + target_compile_definitions(detour_path_recovery_test PRIVATE + SBPL_RECOVERY_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config" + SBPL_RECOVERY_TEST_LIBRARY_DIR="${CATKIN_DEVEL_PREFIX}/lib" + ) + target_include_directories(detour_path_recovery_test SYSTEM + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + # catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain. + target_link_libraries(detour_path_recovery_test + ${catkin_LIBRARIES} + ${Boost_LIBRARIES} + pthread + ${CMAKE_DL_LIBS} + ${TF3_LIBRARY} + ) + # Plugin KHÔNG link thẳng vào test: chúng được nạp qua RecoveryRegistry lúc chạy, đúng đường + # runtime — nhưng phải build xong trước khi test chạy. + add_dependencies(detour_path_recovery_test + sbpl_recovery + sbpl_recovery_test_line_planner + ) + endif() +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..af00aa7 --- /dev/null +++ b/README.md @@ -0,0 +1,84 @@ +# sbpl_recovery + +Recovery behavior **họ path** cho `recovery_core`: khi local planner bế tắc (vật cản chắn tuyến), +behavior lập một **đường vòng** bằng một global planner plugin — mặc định `SBPLLatticePlanner` — +rồi **nối đường vòng vào phần còn lại của global plan hiện hành** và trả về cho runtime bám tiếp. + +Port từ [`navigation_experimental/sbpl_recovery`](https://github.com/ros-planning/navigation_experimental) +(BSD, Eitan Marder-Eppstein) sang hệ sinh thái `robot_*` (không roscpp). + +## Khác bản gốc ở đâu + +| Bản gốc (ROS) | Bản này | +|---|---| +| Tự lái: chạy `pose_follower` bên trong, publish thẳng `cmd_vel` | **Không lái.** Trả `RecoveryOutputType::kPath`; runtime áp path và local planner đang active bám theo — một nguồn vận tốc duy nhất | +| Plan nhận qua topic `NavfnROS/plan` | Plan đến từ `RecoveryContext::plan` — chính plan control loop đang bám | +| Sau recovery move_base replan nên chỉ cần lập tới điểm nối | **Splice**: path trả về = đường vòng + phần plan cũ sau điểm nối, vì runtime không replan sau recovery (contract 2026-08-04b) | +| `pluginlib` | `boost::dll` + `BOOST_DLL_ALIAS(…, DetourPathRecovery)` + `library_path` trong YAML | + +## Local costmap hay global costmap? + +Mặc định **local costmap** (`use_global_costmap: false`): + +- vật cản buộc phải vòng là thứ sensor vừa thấy — nằm tươi nhất trong local costmap; +- cửa sổ lăn nhỏ nên một lượt SBPL bounded (~vài chục ms), chạy được trong một tick recovery. + +Đổi lại hai ràng buộc: + +- **điểm nối phải nằm trong cửa sổ local** — vật cản chắn dài hơn nửa cửa sổ thì behavior trả + `kFailed` và nhường behavior kế tiếp trong route; +- local costmap chạy ở frame `odom`, plan ở frame `map` → cần `RecoveryContext::tf` (runtime đã + nối sẵn). Thiếu TF thì lượt chạy bị từ chối kèm lý do. + +`use_global_costmap: true` khi cần vòng xa hơn cửa sổ (đổi lại phụ thuộc độ tươi của obstacle +layer trên global costmap). + +## Cấu hình + +```yaml +recovery: + behaviors: + - {name: detour_path, type: DetourPathRecovery} + routes: + # Thêm detour_path vào route nào cần đường vòng, ví dụ: + # controlling_failed: [wait, detour_path] + detour_path: + planner_name: SBPLLatticePlanner # global planner gen-1, nạp qua library_path ở root config + use_global_costmap: false + planning_distance: 2.0 # [m] điểm nối cách robot tối thiểu chừng này dọc plan + sample_step: 0.5 # [m] khoảng cách dọc plan giữa hai ứng viên điểm nối + rejoin_clearance: 0.5 # [m] điểm nối cách POSE BẨN GẦN NHẤT tối thiểu chừng này + attempts_per_run: 3 # số ứng viên thử tối đa một lượt (mỗi tick thử một ứng viên) + timeout: 10.0 # [s] trần lượt, recovery_core cưỡng chế + +DetourPathRecovery: + library_path: libsbpl_recovery +``` + +Planner đọc tham số từ namespace mang tên chính nó (`SBPLLatticePlanner/…`) — trùng tên với +`backup_global_planner` thì dùng chung tuning, gồm cả `primitive_filename` (độ phân giải mprim +phải khớp resolution của costmap được chọn). + +Hai khoá `lock_costmap: false` và `costmap_frame_override` **chỉ dành cho unit test** với costmap +placeholder — production không đặt. + +## Chọn điểm nối + +Ứng viên điểm nối phải **đặt được robot vào** (`RecoveryContext::collision`, footprint thật) và cách +**pose bẩn gần nhất** dọc plan ít nhất `rejoin_clearance`. Chọn thuần theo khoảng cách — như bản gốc +— cho ra ứng viên nằm ngay trên vật cản đang chắn tuyến: planner không bao giờ tới được, mà mỗi lượt +thử hỏng vẫn giữ mutex costmap trọn `allocated_time` và làm đói thread cập nhật costmap. + +Không có ứng viên nào đặt được → `start()` trả `false` **ngay**, không chạy lượt SBPL nào. Context +không có collision checker → quay về luật thuần-khoảng-cách (không biết thì không loại). + +## Verify + +```bash +catkin_make --pkg sbpl_recovery +./devel/lib/sbpl_recovery/detour_path_recovery_test +``` + +Test dùng planner giả (`TestLinePlanner`, nạp qua đúng đường Boost.DLL) — kiểm chọn điểm nối, +splice, thử-lại theo ứng viên, quy đổi frame map↔odom qua tf3, mất pose giữa lượt, và từ chối khi +thiếu TF. Đường chạy với SBPL thật thuộc test tích hợp trên sim. diff --git a/include/sbpl_recovery/merge_grids.h b/include/sbpl_recovery/merge_grids.h new file mode 100644 index 0000000..8c8af19 --- /dev/null +++ b/include/sbpl_recovery/merge_grids.h @@ -0,0 +1,118 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * sbpl_recovery — gộp lưới costmap: global làm nền, cửa sổ local đè lên. + * + * Author: DuongTD + *********************************************************************/ +#ifndef SBPL_RECOVERY_MERGE_GRIDS_H_ +#define SBPL_RECOVERY_MERGE_GRIDS_H_ + +#include + +#include +#include + +namespace sbpl_recovery +{ + +/** + * @struct PlanarTransform2D + * @brief Phép biến đổi cứng 2D (frame local -> frame lưới đích), tra TF MỘT lần rồi áp hàng chục + * nghìn cell — không tra TF trong vòng lặp. + */ +struct PlanarTransform2D +{ + double x = 0.0; ///< [m] tịnh tiến + double y = 0.0; ///< [m] + double cos_yaw = 1.0; + double sin_yaw = 0.0; + + void apply(double in_x, double in_y, double& out_x, double& out_y) const + { + out_x = x + cos_yaw * in_x - sin_yaw * in_y; + out_y = y + sin_yaw * in_x + cos_yaw * in_y; + } + + /// @brief Chiều ngược của @ref apply (frame đích -> frame nguồn). Phép quay là trực giao nên + /// nghịch đảo chỉ là chuyển vị — không cần dựng transform thứ hai. + void applyInverse(double in_x, double in_y, double& out_x, double& out_y) const + { + const double dx = in_x - x; + const double dy = in_y - y; + out_x = cos_yaw * dx + sin_yaw * dy; + out_y = -sin_yaw * dx + cos_yaw * dy; + } +}; + +/** + * @brief Cost một cell sau khi gộp hai nguồn: một bên báo chắn là chắn. + * + * Quy tắc (chốt 2026-08-05, xem DETOUR_MERGED_GRID_PLAN.md): + * - local `NO_INFORMATION` -> giữ giá trị global (local chưa quét thì tin mắt rộng); + * - global `NO_INFORMATION` nhưng local ĐÃ biết -> lấy local (255 là giá trị lớn nhất, `max` mù + * sẽ biến "chưa biết" thành "chắn"); + * - cả hai đều biết -> `max`: local FREE (60) KHÔNG xoá tường global — global của hệ này chỉ chứa + * tĩnh, tường không tự đi. + */ +inline unsigned char mergeCellCost(unsigned char global_cost, unsigned char local_cost) +{ + if (local_cost == robot_costmap_2d::NO_INFORMATION) + { + return global_cost; + } + if (global_cost == robot_costmap_2d::NO_INFORMATION) + { + return local_cost; + } + return std::max(global_cost, local_cost); +} + +/** + * @brief Đè cửa sổ @p local lên @p out (đã là bản copy của lưới global, CÙNG frame với đích). + * + * Duyệt theo cell của local (nhỏ hơn nhiều lần lưới đích); tâm cell local được quy sang frame đích + * bằng @p local_to_out rồi ghi theo @ref mergeCellCost. Cell local rơi ngoài lưới đích bị bỏ qua. + * Cả hai lưới đều là BẢN CHỤP của bên gọi — hàm này không đụng costmap sống, không cần mutex. + */ +inline void overlayLocalGrid(const robot_costmap_2d::Costmap2D& local, + const PlanarTransform2D& local_to_out, + robot_costmap_2d::Costmap2D& out) +{ + const unsigned int size_x = local.getSizeInCellsX(); + const unsigned int size_y = local.getSizeInCellsY(); + + for (unsigned int ly = 0; ly < size_y; ++ly) + { + for (unsigned int lx = 0; lx < size_x; ++lx) + { + const unsigned char local_cost = local.getCost(lx, ly); + if (local_cost == robot_costmap_2d::NO_INFORMATION) + { + continue; // Không đóng góp gì — giữ nền global, khỏi tính transform. + } + + double wx = 0.0; + double wy = 0.0; + local.mapToWorld(lx, ly, wx, wy); + + double ox = 0.0; + double oy = 0.0; + local_to_out.apply(wx, wy, ox, oy); + + unsigned int mx = 0; + unsigned int my = 0; + if (!out.worldToMap(ox, oy, mx, my)) + { + continue; + } + + out.setCost(mx, my, mergeCellCost(out.getCost(mx, my), local_cost)); + } + } +} + +} // namespace sbpl_recovery + +#endif // SBPL_RECOVERY_MERGE_GRIDS_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..2634e32 --- /dev/null +++ b/package.xml @@ -0,0 +1,47 @@ + + + sbpl_recovery + 0.1.0 + + Recovery behavior họ path cho recovery_core: lập đường vòng quanh vật cản bằng một global + planner plugin (mặc định SBPLLatticePlanner) rồi nối lại global plan hiện hành. + + Port từ navigation_experimental/sbpl_recovery. Khác bản gốc: behavior KHÔNG tự lái — nó trả + path (RecoveryOutputType::kPath) và runtime bám path đó bằng local planner đang active, giữ + bất biến một nguồn vận tốc duy nhất. Mặc định lập đường vòng trên LOCAL costmap (vật cản tươi + nhất, cửa sổ nhỏ nên một lượt SBPL bounded); dữ liệu plan ở frame map được quy đổi hai chiều + qua tf3. + + Planner nạp qua Boost.DLL theo khoá library_path — thay planner khác chỉ là đổi một dòng YAML. + + DuongTD + DuongTD + BSD + + catkin + + recovery_core + recovery_core + + robot_cpp + robot_cpp + + robot_costmap_2d + robot_costmap_2d + + robot_nav_core + robot_nav_core + + robot_geometry_msgs + robot_geometry_msgs + + robot_nav_msgs + robot_nav_msgs + + robot_tf3_geometry_msgs + robot_tf3_geometry_msgs + + + sbpl_lattice_planner + diff --git a/plugins/detour_path_recovery.cpp b/plugins/detour_path_recovery.cpp new file mode 100644 index 0000000..b6f225c --- /dev/null +++ b/plugins/detour_path_recovery.cpp @@ -0,0 +1,1277 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * sbpl_recovery — recovery họ path: lập đường vòng quanh vật cản rồi NỐI LẠI global plan hiện hành. + * + * Port từ `navigation_experimental/sbpl_recovery` (Eitan Marder-Eppstein, BSD) sang khuôn + * `recovery_core`. Hai khác biệt có chủ đích so với bản gốc: + * + * 1. Bản gốc TỰ LÁI: chạy pose_follower bên trong và publish thẳng cmd_vel — hai nguồn vận tốc + * song song với move_base. Ở đây behavior thuộc họ `kPath`: nó chỉ TRẢ VỀ đường vòng; runtime + * áp path đó và local planner đang active bám theo (một nguồn vận tốc duy nhất, đúng D8). + * 2. Bản gốc nhận plan qua topic; ở đây plan đến từ `RecoveryContext::plan` — chính plan mà + * control loop đang bám, không lệch phiên bản. + * + * Đường vòng được NỐI với phần còn lại của plan cũ (splice): contract 2026-08-04b không replan sau + * recovery, nên path trả về phải đi tới đích của CHẶNG, không phải chỉ tới điểm nối — nếu không + * robot sẽ báo "tới đích" ngay tại điểm nối giữa tuyến. + * + * Author: DuongTD + *********************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +namespace sbpl_recovery +{ +namespace +{ +constexpr double kDefaultPlanningDistance = 2.0; // [m] +constexpr double kDefaultSampleStep = 0.5; // [m] +constexpr double kDefaultRejoinClearance = 0.5; // [m] +constexpr double kDefaultMaxRejoinDistance = 0.0; // [m] 0 = quét tới cuối plan / rìa lưới +constexpr int kDefaultAttemptsPerRun = 3; +constexpr double kSpacingEpsilon = 1e-6; // [m] +constexpr double kReferencePlanLogThrottle = 10.0; // [s] + +double sqDistance(const robot_geometry_msgs::PoseStamped& a, + const robot_geometry_msgs::PoseStamped& b) +{ + const double dx = a.pose.position.x - b.pose.position.x; + const double dy = a.pose.position.y - b.pose.position.y; + return dx * dx + dy * dy; +} + +/// [m] Khoảng cách từ điểm tới đoạn thẳng. +double pointToSegment(double px, double py, double ax, double ay, double bx, double by) +{ + const double dx = bx - ax; + const double dy = by - ay; + const double len_sq = dx * dx + dy * dy; + + if (len_sq <= 1e-12) + { + return std::hypot(px - ax, py - ay); + } + + double t = ((px - ax) * dx + (py - ay) * dy) / len_sq; + t = std::max(0.0, std::min(1.0, t)); + return std::hypot(px - (ax + t * dx), py - (ay + t * dy)); +} + +/** + * @brief [m] Độ lệch lớn nhất của @p detour so với đoạn plan gốc `plan[0..rejoin]`. + * + * Đây là guard cho ràng buộc lệch tuyến của fleet: order chỉ định tuyến, robot chỉ được rời khỏi nó + * trong một hành lang cho phép. Đo so với **plan gốc** chứ không so với đường thẳng nối hai đầu — + * plan gốc mới là thứ fleet đã duyệt. + */ +double maxDeviation(const std::vector& plan, std::size_t rejoin, + const std::vector& detour) +{ + if (plan.size() < 2 || detour.empty()) + { + return 0.0; + } + + const std::size_t last = std::min(rejoin, plan.size() - 1); + double worst = 0.0; + + for (const robot_geometry_msgs::PoseStamped& pose : detour) + { + double best = std::numeric_limits::max(); + for (std::size_t i = 0; i < last; ++i) + { + best = std::min(best, pointToSegment(pose.pose.position.x, pose.pose.position.y, + plan[i].pose.position.x, plan[i].pose.position.y, + plan[i + 1].pose.position.x, + plan[i + 1].pose.position.y)); + } + worst = std::max(worst, best); + } + + return worst; +} +} // namespace + +/** + * @class DetourPathRecovery + * @brief Lập đường vòng bằng một global planner plugin (mặc định SBPL) và nối lại plan hiện hành. + * + * Thuật toán (giữ nguyên khung của bản gốc): + * 1. `onStart`: chụp plan hiện hành; đi dọc plan tới đoạn GẦN robot (tránh chọn điểm nối sau lưng + * trên tuyến vòng), rồi chọn tối đa `attempts_per_run` ứng viên điểm nối cách robot ít nhất + * `planning_distance` và cách nhau `sample_step` dọc plan. + * 2. Mỗi `update()` thử ĐÚNG MỘT ứng viên: makePlan(pose hiện tại → ứng viên) trên costmap đã + * chọn. Thành công → trả path = đường vòng + phần plan cũ sau điểm nối, `kSucceeded`. + * Hết ứng viên → `kFailed`, state machine chuyển behavior kế tiếp của route. + * + * ## Ba chế độ costmap (`costmap_source`) + * + * - `combined` (khuyến nghị, xem `DETOUR_MERGED_GRID_PLAN.md`): LƯỚI GỘP — snapshot global làm + * nền (tường/kệ tĩnh, phủ toàn bản đồ) rồi đè cửa sổ local lên (vật cản sensor tươi). Mutex hai + * costmap chỉ bị giữ trong lúc copy (~vài ms); SBPL search trên bản chụp KHÔNG giữ mutex nào — + * map update không bao giờ bị planner bỏ đói. Một frame (map), một nguồn sự thật: quét ứng viên, + * SBPL và splice cùng nhìn một lưới. Cần planner export capability `ExternalGrid` + * (sbpl_lattice_planner có sẵn). Điểm nối được quét tới CUỐI plan. + * - `local`: chỉ cửa sổ lăn — cho hệ không có global costmap; điểm nối kẹt trong cửa sổ. + * - `global`: chỉ lưới tĩnh — cho hệ mà global có nạp obstacle. Đã đo trên sim 2026-08-05: global + * KHÔNG nạp sensor thì goal nào SBPL cũng vẽ xuyên đúng chỗ vật cản tươi — đừng dùng khi đó. + * + * ## Timing + * + * `onUpdate` chạy trên control thread. Một lượt makePlan trên cửa sổ local là lời gọi "nặng" so + * với khuyến cáo của hook, nhưng CHỦ ĐÍCH chấp nhận: trong RECOVERING họ path robot đứng yên + * (velocity source = kNone), một cycle giãn ra không làm sai lệnh nào — cùng ngân sách thời gian + * mà recovery blocking của move_base gen-1 vẫn dùng. Mỗi tick chỉ thử một ứng viên để chặn trên + * từng cycle là một lượt planner duy nhất. + * + * Param (namespace của instance): + * - `planner_name` [string, "SBPLLatticePlanner"] tên instance planner: vừa là namespace đọc + * param, vừa là tên truyền vào `initialize()`. Đổi nó = có một instance tuning + * riêng (vd `allocated_time` ngắn cho detour) mà không đụng bản dùng chung. + * - `planner_symbol` [string, = planner_name] alias Boost.DLL **có thật** trong `.so`, và cũng là + * khoá tra `/library_path`. Chỉ cần khai khi `planner_name` + * không phải một alias có thật — đúng trường hợp `SBPLLatticePlanner`, vốn chỉ + * export một symbol duy nhất (khác bộ local planner, nơi mỗi biến thể là một + * class riêng có alias riêng). + * - `use_global_costmap` [bool, false] legacy; `costmap_source` khai thì thắng. + * - `planning_distance` [m, 2.0] điểm nối cách robot tối thiểu chừng này. + * - `sample_step` [m, 0.5] khoảng cách dọc plan giữa hai ứng viên liên tiếp. + * - `rejoin_clearance` [m, 0.5] điểm nối phải cách pose bẩn gần nhất (CẢ HAI PHÍA dọc + * plan) ít nhất chừng này. Sát mép vật cản thì đường vòng + * gần như luôn đâm vào vùng đệm của chính nó. + * - `max_rejoin_distance` [m, 0 = không giới hạn] TRẦN quét dọc plan, thuần tuỳ chọn: quét luôn + * tự dừng ở rìa lưới (`kOutside`) hoặc cuối plan. Đừng đặt + * nhỏ: sim 2026-08-05 hai lần liền cap cắt quét ngay sau + * pose bẩn cuối và báo "không có chỗ sạch" dù chưa nhìn tiếp. + * - `attempts_per_run` [int, 3] số ứng viên tối đa một lượt. + * - `rejoin_on` [string, "reference"] tuyến để nối lại: `reference` = tuyến GỐC của chặng (plan + * do planner sinh — detour tự kéo robot về tuyến order, và + * `max_deviation` đo đúng hành lang fleet đã duyệt); + * `current` = plan đang bám (hành vi cũ, tuyến trôi dần qua + * từng lượt detour). Runtime không cấp tuyến tham chiếu thì + * tự quay về `current` kèm cảnh báo. + * - `timeout` [s] trần lượt, base cưỡng chế (0 = không giới hạn). + * - `lock_costmap` [bool, true] giữ mutex costmap quanh makePlan (giao thức với + * map-update thread). CHỈ unit test với costmap placeholder được tắt. + * - `costmap_frame_override` [string, ""] frame của costmap khi không dereference được costmap. + * CHỈ dành cho unit test với costmap placeholder. + */ +class DetourPathRecovery final : public recovery_core::RecoveryBehavior +{ +public: + DetourPathRecovery() = default; + + static recovery_core::RecoveryBehavior::RecoveryBehaviorPtr create() + { + return std::make_shared(); + } + + recovery_core::RecoveryOutputType outputKind() const override + { + return recovery_core::RecoveryOutputType::kPath; + } + +protected: + bool onConfigure(robot::NodeHandle& nh) override + { + nh.param("planner_name", planner_name_, std::string("SBPLLatticePlanner")); + // Symbol Boost.DLL mặc định TRÙNG tên instance. Tách ra vì hai thứ này chỉ trùng nhau khi mỗi + // biến thể planner là một class riêng có alias riêng (như bộ local planner). `SBPLLatticePlanner` + // chỉ export ĐÚNG MỘT symbol, nên muốn một instance SBPL riêng cho detour (allocated_time ngắn + // để không treo control thread) thì phải nạp cùng symbol đó nhưng đọc param từ namespace khác. + nh.param("planner_symbol", planner_symbol_, planner_name_); + // "local" | "global" | "combined". Khai thì thắng `use_global_costmap` (giữ để tương thích). + nh.param("costmap_source", costmap_source_, std::string()); + nh.param("use_global_costmap", use_global_costmap_, false); + nh.param("planning_distance", planning_distance_, kDefaultPlanningDistance); + nh.param("sample_step", sample_step_, kDefaultSampleStep); + nh.param("rejoin_clearance", rejoin_clearance_, kDefaultRejoinClearance); + nh.param("max_rejoin_distance", max_rejoin_distance_, kDefaultMaxRejoinDistance); + nh.param("attempts_per_run", attempts_per_run_, kDefaultAttemptsPerRun); + nh.param("max_deviation", max_deviation_, 0.0); + // "reference" | "current". Xem @ref rejoin_on_ và RecoveryContext::reference_plan. + nh.param("rejoin_on", rejoin_on_, std::string("reference")); + nh.param("lock_costmap", lock_costmap_, true); + nh.param("costmap_frame_override", costmap_frame_override_, std::string()); + + if (rejoin_on_ != "reference" && rejoin_on_ != "current") + { + robot::log_error("[sbpl_recovery] '%s': rejoin_on='%s' must be reference | current.", + name().c_str(), rejoin_on_.c_str()); + return false; + } + + if (planner_name_.empty() || planner_symbol_.empty()) + { + robot::log_error("[sbpl_recovery] '%s': planner_name/planner_symbol must not be empty.", + name().c_str()); + return false; + } + + if (costmap_source_.empty()) + { + costmap_source_ = use_global_costmap_ ? "global" : "local"; + } + if (costmap_source_ != "local" && costmap_source_ != "global" && costmap_source_ != "combined") + { + robot::log_error("[sbpl_recovery] '%s': costmap_source='%s' must be local | global | " + "combined.", name().c_str(), costmap_source_.c_str()); + return false; + } + // combined = LƯỚI GỘP (2026-08-05, vòng 3): global nền + local đè, SBPL initialize trên GLOBAL + // (env theo kích thước lưới gộp) và nhận bản chụp gộp qua capability ExternalGrid mỗi attempt. + // Nguyên lý không đổi: người LẬP đường phải nhìn thấy vật cản tươi — giờ nhìn qua lưới gộp. + use_global_costmap_ = costmap_source_ != "local"; + if (!std::isfinite(planning_distance_) || planning_distance_ <= 0.0) + { + robot::log_error("[sbpl_recovery] '%s': planning_distance=%.3f m must be > 0.", + name().c_str(), planning_distance_); + return false; + } + if (!std::isfinite(sample_step_) || sample_step_ <= 0.0) + { + robot::log_error("[sbpl_recovery] '%s': sample_step=%.3f m must be > 0.", name().c_str(), + sample_step_); + return false; + } + if (!std::isfinite(rejoin_clearance_) || rejoin_clearance_ < 0.0) + { + robot::log_error("[sbpl_recovery] '%s': rejoin_clearance=%.3f m must be >= 0.", + name().c_str(), rejoin_clearance_); + return false; + } + if (!std::isfinite(max_rejoin_distance_) || max_rejoin_distance_ < 0.0) + { + robot::log_error("[sbpl_recovery] '%s': max_rejoin_distance=%.3f m must be >= 0 " + "(0 = scan to the end of the plan).", + name().c_str(), max_rejoin_distance_); + return false; + } + if (max_rejoin_distance_ > 0.0 && max_rejoin_distance_ < planning_distance_) + { + // Tầm quét ngắn hơn khoảng cách tối thiểu tới điểm nối thì không ứng viên nào lọt qua được cả + // hai điều kiện — lượt detour nào cũng từ chối, im lặng. + robot::log_error("[sbpl_recovery] '%s': max_rejoin_distance=%.3f m < planning_distance=%.3f " + "m — no candidate could ever satisfy both.", + name().c_str(), max_rejoin_distance_, planning_distance_); + return false; + } + if (attempts_per_run_ < 1) + { + robot::log_error("[sbpl_recovery] '%s': attempts_per_run=%d must be >= 1.", name().c_str(), + attempts_per_run_); + return false; + } + if (!std::isfinite(max_deviation_) || max_deviation_ < 0.0) + { + robot::log_error("[sbpl_recovery] '%s': max_deviation=%.3f m must be >= 0 (0 = no limit).", + name().c_str(), max_deviation_); + return false; + } + + // Họ path không bị base bắt buộc có pose, nhưng behavior NÀY cần: điểm nối chọn theo khoảng + // cách tới robot. Chặn ở boot thay vì lượt chạy đầu tiên. + if (ctx().pose == nullptr) + { + robot::log_error("[sbpl_recovery] '%s': needs a PoseProvider to pick a rejoin point.", + name().c_str()); + return false; + } + + robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); + if (costmap == nullptr) + { + robot::log_error("[sbpl_recovery] '%s': the %s costmap is missing from the context.", + name().c_str(), use_global_costmap_ ? "global" : "local"); + return false; + } + if (costmap_source_ == "combined" && costmap_frame_override_.empty() && + ctx().local_costmap == nullptr) + { + // Lưới gộp cần CẢ HAI nguồn — thiếu mắt tươi thì đây chỉ còn là mode "global", và mode đó + // đã được đo là mù vật cản sensor. Bắt lỗi cấu hình ở boot thay vì chạy sai âm thầm. + robot::log_error("[sbpl_recovery] '%s': costmap_source=combined needs BOTH costmaps but the " + "local costmap is missing from the context.", name().c_str()); + return false; + } + + return loadPlanner(costmap); + } + + bool onStart(const recovery_core::RecoveryGoal& /*goal*/) override + { + robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); + if (costmap == nullptr) + { + robot::log_error("[sbpl_recovery] '%s': costmap disappeared from the context.", + name().c_str()); + return false; + } + + // Con trỏ costmap là non-owning và CÓ THỂ bị thay giữa hai lượt (contract của RecoveryContext). + // Planner đã initialize() với con trỏ cũ thì phải dựng lại — dùng tiếp là đọc một costmap chết. + if (costmap != initialized_costmap_ && !loadPlanner(costmap)) + { + return false; + } + + // Costmap quá hạn = lưới đang mô tả một thế giới của quá khứ. Lập đường vòng trên nó là sinh + // ra một plan trông hợp lệ nhưng vô nghĩa (sim 2026-08-05: detour 22-31 pose trên map cũ ngay + // sau khi chính attempt SBPL trước đó bỏ đói map update). Từ chối kèm lý do; gate qua test seam + // vì costmap placeholder của unit test không dereference được. + if (costmap_frame_override_.empty()) + { + const bool chosen_current = costmap->isCurrent(); + const bool local_current = costmap_source_ != "combined" || + ctx().local_costmap == nullptr || + ctx().local_costmap->isCurrent(); + if (!chosen_current || !local_current) + { + robot::log_warning("[sbpl_recovery] '%s': refusing to start — the %s costmap is stale " + "(planning on a past world produces junk detours).", + name().c_str(), !chosen_current + ? (use_global_costmap_ ? "global" : "local") + : "local"); + return false; + } + } + + // Tuyến để NỐI LẠI. Mặc định là tuyến THAM CHIẾU của chặng (plan do planner sinh), không phải + // plan đang bám (2026-08-05e): nối vào plan đang bám nghĩa là mỗi lượt detour lấy kết quả của + // lượt trước làm mốc — sim đo được tuyến bị ăn mòn dần (rejoin 106/305 -> 130/289 -> 132/273), + // robot không bao giờ quay về tuyến order, và `max_deviation` đo với một mốc đã trôi nên hành + // lang fleet mất ý nghĩa. Nối vào tuyến tham chiếu thì chính SBPL kéo robot trở lại tuyến đã + // duyệt, và đuôi splice cũng là đuôi tuyến gốc nên chặng luôn kết thúc đúng chỗ. + plan_.clear(); + const bool want_reference = rejoin_on_ == "reference" && ctx().reference_plan != nullptr; + bool have_plan = want_reference && ctx().reference_plan->getGlobalPlan(plan_) && !plan_.empty(); + if (!have_plan) + { + // Runtime không cấp tuyến tham chiếu (hoặc chưa có plan nào của planner): quay về plan đang + // bám. Mất khả năng tự về tuyến, nhưng vẫn vòng được — im lặng thì tệ hơn. + if (want_reference) + { + robot::log_warning_throttle( + kReferencePlanLogThrottle, + "[sbpl_recovery] '%s': no reference route available — rejoining the CURRENT plan " + "instead; detours will not pull the robot back to the order route.", name().c_str()); + } + plan_.clear(); + have_plan = ctx().plan != nullptr && ctx().plan->getGlobalPlan(plan_) && !plan_.empty(); + } + if (!have_plan) + { + robot::log_warning("[sbpl_recovery] '%s': no plan to rejoin — refusing to start.", + name().c_str()); + return false; + } + + plan_frame_ = plan_.front().header.frame_id; + costmap_frame_ = costmapFrame(costmap); + + if (plan_frame_ != costmap_frame_ && ctx().tf == nullptr) + { + // Local costmap (odom) + plan (map) là ca mặc định — thiếu TF thì không quy đổi được. + robot::log_error("[sbpl_recovery] '%s': plan frame '%s' != costmap frame '%s' and the " + "context has no TF buffer.", + name().c_str(), plan_frame_.c_str(), costmap_frame_.c_str()); + return false; + } + + robot_geometry_msgs::PoseStamped robot_in_plan; + if (!robotPoseIn(plan_frame_, robot_in_plan)) + { + robot::log_warning("[sbpl_recovery] '%s': robot pose unavailable — cannot pick a rejoin " + "point.", name().c_str()); + return false; + } + + // Lưới gộp cho lượt quét ứng viên; mỗi attempt trong onUpdate sẽ chụp lại bản tươi hơn. + if (merged_active_ && !buildMergedGrid()) + { + robot::log_warning("[sbpl_recovery] '%s': could not build the merged grid — refusing to " + "start.", name().c_str()); + return false; + } + + buildCandidates(robot_in_plan); + if (candidates_.empty()) + { + // Không có điểm nối nào đặt được robot vào: từ chối NGAY thay vì chạy `attempts_per_run` lượt + // SBPL chắc chắn hỏng — mỗi lượt hỏng vẫn giữ mutex costmap trọn `allocated_time` và làm đói + // thread cập nhật costmap. + // + // Log kèm SỐ LIỆU của lượt quét: "không có ứng viên" có ít nhất ba nguyên nhân khác hẳn nhau + // (tầm quét quá ngắn, vật cản trải dài qua rìa tầm, hoặc ngưỡng khoảng cách quá chặt) và + // không phân biệt được chúng nếu chỉ báo kết quả. + robot::log_warning("[sbpl_recovery] '%s': no placeable rejoin point — refusing to start. " + "plan=%zu pose(s), scanned=%zu, scan ended at %.2f m (cap %.2f m, 0 = " + "none), blocked=%zu, first blocked at %.2f m, last blocked at %.2f m, " + "last blocked IN VIEW at %.2f m (that is the one the rejoin point must " + "clear), first joinable spot at %.2f m (need >= %.2f m from any block " + "and >= %.2f m from the robot).", + name().c_str(), plan_.size(), scan_.scanned, scan_.reach_distance, + max_rejoin_distance_, scan_.blocked, scan_.first_blocked_distance, + scan_.last_blocked_distance, scan_.last_blocked_in_view_distance, + scan_.first_clear_distance, rejoin_clearance_, planning_distance_); + return false; + } + + attempt_ = 0; + return true; + } + + recovery_core::RecoveryResult onUpdate(const robot::Time& now, double /*dt*/) override + { + if (attempt_ >= candidates_.size()) + { + return recovery_core::RecoveryResult::Failed() + .withProgress(1.0, 0.0) + .withMessage("no reachable rejoin point on the plan after " + + std::to_string(candidates_.size()) + " attempt(s)"); + } + + const std::size_t rejoin_index = candidates_[attempt_]; + + // Pose lấy TƯƠI mỗi lượt thử: behavior trước đó trong route (rotate/back_up) có thể đã dời + // robot; và mất pose giữa chừng phải kết thúc lượt, không dùng pose cũ. + robot_geometry_msgs::PoseStamped start; + if (!robotPoseIn(costmap_frame_, start)) + { + return recovery_core::RecoveryResult::Failed().withMessage("robot pose became unavailable"); + } + + robot_geometry_msgs::PoseStamped rejoin_goal; + std::vector detour; + bool planned = false; + + try + { + rejoin_goal = toFrame(plan_[rejoin_index], costmap_frame_); + + if (merged_active_) + { + // Lưới gộp: chụp lại bản TƯƠI trước từng attempt (mutex chỉ bị giữ trong lúc copy), rồi + // SBPL search trên bản chụp — KHÔNG giữ mutex costmap nào, map update không bị bỏ đói dù + // attempt thua đốt trọn allocated_time. + if (!buildMergedGrid()) + { + return recovery_core::RecoveryResult::Failed() + .withMessage("could not rebuild the merged grid (TF/costmap unavailable)"); + } + set_external_grid_(planner_.get(), &merged_grid_); + planned = planner_->makePlan(start, rejoin_goal, detour); + } + // Cùng giao thức khoá với PlannerRunner/gen-1: map-update thread ghi lưới dưới mutex này, + // planner đọc lưới sống thì phải giữ nó. Chỉ unit test với costmap placeholder được tắt. + else if (lock_costmap_) + { + robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); + boost::unique_lock lock( + *(costmap->getCostmap()->getMutex())); + planned = planner_->makePlan(start, rejoin_goal, detour); + } + else + { + planned = planner_->makePlan(start, rejoin_goal, detour); + } + } + catch (const std::exception& ex) + { + robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%zu threw: %s", name().c_str(), + attempt_ + 1, candidates_.size(), ex.what()); + planned = false; + } + + if (planned && !detour.empty() && max_deviation_ > 0.0) + { + // Guard lệch tuyến: đường vòng phải nằm trong hành lang fleet cho phép quanh tuyến gốc. + // `plan_` ở frame plan còn `detour` vừa được planner sinh ra ở frame costmap, nên phải quy + // về cùng frame trước khi đo. TF đứt giữa chừng thì bỏ qua guard — nhánh splice bên dưới sẽ + // gặp lại đúng lỗi đó và xử lý một lần. + std::vector detour_in_plan_frame; + detour_in_plan_frame.reserve(detour.size()); + bool converted = true; + try + { + for (const robot_geometry_msgs::PoseStamped& pose : detour) + { + detour_in_plan_frame.push_back(toFrame(pose, plan_frame_)); + } + } + catch (const std::exception&) + { + converted = false; + } + + if (converted) + { + const double deviation = maxDeviation(plan_, rejoin_index, detour_in_plan_frame); // [m] + if (deviation > max_deviation_) + { + robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%zu strays %.2f m from the route " + "(limit %.2f m) — rejected.", + name().c_str(), attempt_ + 1, candidates_.size(), deviation, + max_deviation_); + ++attempt_; + return recovery_core::RecoveryResult::Running() + .withProgress(progressNow(), remainingNow()) + .withMessage("detour rejected: deviates too far from the route"); + } + } + } + + if (planned && !detour.empty()) + { + robot_nav_msgs::Path out; + out.header.frame_id = plan_frame_; + out.header.stamp = now; + out.poses.reserve(detour.size() + (plan_.size() - rejoin_index)); + + try + { + for (const robot_geometry_msgs::PoseStamped& pose : detour) + { + out.poses.push_back(toFrame(pose, plan_frame_)); + } + } + catch (const std::exception& ex) + { + // TF đứt đúng giữa lúc quy đổi kết quả: đường vòng không dùng được, coi như lượt thử hỏng. + robot::log_warning("[sbpl_recovery] '%s': could not express the detour in '%s': %s", + name().c_str(), plan_frame_.c_str(), ex.what()); + ++attempt_; + return recovery_core::RecoveryResult::Running() + .withProgress(progressNow(), remainingNow()) + .withMessage("detour found but its frame conversion failed"); + } + + // Nối phần còn lại của plan cũ SAU điểm nối: contract 2026-08-04b không replan sau recovery, + // path này phải tự đi tới đích của chặng. Bỏ chính pose điểm nối — detour đã kết thúc ở đó. + for (std::size_t i = rejoin_index + 1; i < plan_.size(); ++i) + { + out.poses.push_back(plan_[i]); + } + + robot::log_info("[sbpl_recovery] '%s': detour with %zu pose(s) rejoins the plan at index " + "%zu/%zu (attempt %zu/%zu).", + name().c_str(), detour.size(), rejoin_index, plan_.size(), attempt_ + 1, + candidates_.size()); + + return recovery_core::RecoveryResult::PathOut(out, recovery_core::RecoveryStatus::kSucceeded) + .withProgress(1.0, 0.0) + .withMessage("detour rejoins the current plan"); + } + + ++attempt_; + return recovery_core::RecoveryResult::Running() + .withProgress(progressNow(), remainingNow()) + .withMessage("detour attempt " + std::to_string(attempt_) + "/" + + std::to_string(candidates_.size()) + " failed"); + } + +private: + robot_costmap_2d::Costmap2DROBOT* chosenCostmap() const + { + return use_global_costmap_ ? ctx().global_costmap : ctx().local_costmap; + } + + /// Frame của costmap đã chọn. Override chỉ dành cho unit test với costmap placeholder — + /// production để rỗng và đọc thẳng từ costmap. + std::string costmapFrame(robot_costmap_2d::Costmap2DROBOT* costmap) const + { + return costmap_frame_override_.empty() ? costmap->getGlobalFrameID() : costmap_frame_override_; + } + + bool loadPlanner(robot_costmap_2d::Costmap2DROBOT* costmap) + { + // Tra library_path và đọc param của planner từ ROOT config (không phải namespace của instance + // recovery) — cùng chỗ với mọi planner khác, nên `SBPLLatticePlanner` dùng chung tuning với + // backup planner nếu trùng tên. + robot::NodeHandle root_nh; + robot::PluginLoaderHelper loader(root_nh); + const std::string library_path = loader.findLibraryPath(planner_symbol_); + if (library_path.empty()) + { + robot::log_error("[sbpl_recovery] '%s': no library found for planner symbol '%s' — check the " + "key '%s/library_path' in the YAML.", + name().c_str(), planner_symbol_.c_str(), planner_symbol_.c_str()); + return false; + } + + try + { + // factory_ giữ .so còn nạp — phải sống lâu hơn planner_ (factory_ khai TRƯỚC planner_ nên bị + // huỷ SAU). + planner_factory_ = boost::dll::import_alias( + library_path, planner_symbol_, boost::dll::load_mode::append_decorations); + planner_ = planner_factory_(); + } + catch (const boost::system::system_error& ex) + { + robot::log_error("[sbpl_recovery] '%s': could not load symbol '%s' from '%s': %s. Lưu ý: " + "`planner_symbol` phải là alias Boost.DLL CÓ THẬT trong .so; muốn một " + "instance tuning riêng thì đổi `planner_name` (namespace param), không phải " + "symbol.", + name().c_str(), planner_symbol_.c_str(), library_path.c_str(), ex.what()); + return false; + } + catch (const std::exception& ex) + { + robot::log_error("[sbpl_recovery] '%s': error while loading planner '%s': %s", name().c_str(), + planner_symbol_.c_str(), ex.what()); + return false; + } + + if (!planner_) + { + robot::log_error("[sbpl_recovery] '%s': factory of '%s' returned null.", name().c_str(), + planner_symbol_.c_str()); + return false; + } + + try + { + // Boot-time là chỗ đúng cho initialize: SBPL dựng environment theo kích thước costmap và + // CHẶN tới khi costmap khác 0 — không được làm điều đó trong control loop. + if (!planner_->initialize(planner_name_, costmap)) + { + robot::log_error("[sbpl_recovery] '%s': planner '%s' reported an initialize() failure.", + name().c_str(), planner_name_.c_str()); + planner_.reset(); + return false; + } + } + catch (const std::exception& ex) + { + robot::log_error("[sbpl_recovery] '%s': initialize() of '%s' threw: %s", name().c_str(), + planner_name_.c_str(), ex.what()); + planner_.reset(); + return false; + } + + initialized_costmap_ = costmap; + + // `costmap_frame_override` là test seam với costmap placeholder — lúc đó không được dựng + // checker thật (nó sẽ dereference placeholder) và cũng không nạp capability lưới ngoài. + merged_active_ = false; + if (costmap_frame_override_.empty()) + { + if (costmap_source_ == "global") + { + // Checker phải nhìn cùng lưới với planner (ctx().collision của runtime trỏ local). + own_checker_ = std::make_unique(costmap); + } + else if (costmap_source_ == "combined") + { + // Lưới gộp cần planner nhận lưới NGOÀI (bản chụp global+local). Capability nằm ngoài + // interface BaseGlobalPlanner nên tra qua một alias Boost.DLL thứ hai trong CÙNG .so: + // "ExternalGrid". Thiếu nó = planner này không chạy được mode combined — + // báo lỗi cấu hình ở boot, không âm thầm rơi về hành vi khác. + try + { + // std::function giữ luôn tham chiếu .so bên trong callable của boost::dll — cùng cơ chế + // giữ-sống với planner_factory_. + set_external_grid_ = + boost::dll::import_alias( + library_path, planner_symbol_ + "ExternalGrid", + boost::dll::load_mode::append_decorations); + } + catch (const std::exception& ex) + { + robot::log_error("[sbpl_recovery] '%s': costmap_source=combined but '%s' does not " + "export the '%sExternalGrid' capability: %s. Use a planner that " + "supports external grids, or switch costmap_source to local/global.", + name().c_str(), library_path.c_str(), planner_symbol_.c_str(), + ex.what()); + planner_.reset(); + return false; + } + merged_active_ = true; + } + } + + robot::log_info("[sbpl_recovery] '%s': detour planner '%s' ready on the %s costmap.", + name().c_str(), planner_name_.c_str(), + costmap_source_ == "combined" ? "merged (global+local)" + : (use_global_costmap_ ? "global" : "local")); + return true; + } + + /** + * @brief Chụp lưới gộp: global làm nền, cửa sổ local đè lên (xem merge_grids.h). + * + * Mutex mỗi costmap chỉ bị giữ trong lúc copy nguyên khối lưới của nó; phần overlay chạy trên + * hai BẢN CHỤP nên không đụng costmap sống. TF local->map tra MỘT lần cho cả lượt. + */ + bool buildMergedGrid() + { + robot_costmap_2d::Costmap2DROBOT* global = ctx().global_costmap; + robot_costmap_2d::Costmap2DROBOT* local = ctx().local_costmap; + if (global == nullptr || local == nullptr) + { + return false; + } + + PlanarTransform2D local_to_map; // Ghi lại làm member: pha quét ứng viên cần chiều ngược. + const std::string local_frame = local->getGlobalFrameID(); + const std::string map_frame = global->getGlobalFrameID(); + if (local_frame != map_frame) + { + if (ctx().tf == nullptr) + { + robot::log_warning("[sbpl_recovery] '%s': merged grid needs TF '%s' -> '%s' but the " + "context has no TF buffer.", + name().c_str(), local_frame.c_str(), map_frame.c_str()); + return false; + } + try + { + const tf3::TransformStampedMsg transform = + ctx().tf->lookupTransform(map_frame, local_frame, tf3::Time()); + local_to_map.x = transform.transform.translation.x; + local_to_map.y = transform.transform.translation.y; + // Quaternion phẳng (robot 2D): yaw = 2*atan2(z, w) — cùng phép rút gọn với port SBPL. + const double yaw = 2.0 * std::atan2(transform.transform.rotation.z, + transform.transform.rotation.w); + local_to_map.cos_yaw = std::cos(yaw); + local_to_map.sin_yaw = std::sin(yaw); + } + catch (const std::exception& ex) + { + robot::log_warning("[sbpl_recovery] '%s': TF '%s' -> '%s' unavailable for the merged " + "grid: %s", + name().c_str(), local_frame.c_str(), map_frame.c_str(), ex.what()); + return false; + } + } + + { + boost::unique_lock lock( + *(global->getCostmap()->getMutex())); + merged_grid_ = *global->getCostmap(); + } + { + boost::unique_lock lock( + *(local->getCostmap()->getMutex())); + local_snapshot_ = *local->getCostmap(); + } + overlayLocalGrid(local_snapshot_, local_to_map, merged_grid_); + local_to_map_ = local_to_map; + return true; + } + + /// Pose robot trong @p frame. Trả false khi mất pose hoặc TF không quy đổi được. + bool robotPoseIn(const std::string& frame, robot_geometry_msgs::PoseStamped& out) const + { + robot_geometry_msgs::PoseStamped raw; + if (!ctx().pose->getRobotPose(raw)) + { + return false; + } + + try + { + out = toFrame(raw, frame); + } + catch (const std::exception& ex) + { + robot::log_warning("[sbpl_recovery] '%s': cannot express the robot pose in '%s': %s", + name().c_str(), frame.c_str(), ex.what()); + return false; + } + return true; + } + + /// Quy @p in về @p target qua TF của context. Ném tf3 exception khi không quy đổi được. + robot_geometry_msgs::PoseStamped toFrame(const robot_geometry_msgs::PoseStamped& in, + const std::string& target) const + { + if (in.header.frame_id == target || in.header.frame_id.empty()) + { + return in; + } + if (ctx().tf == nullptr) + { + throw std::runtime_error("frame '" + in.header.frame_id + "' != '" + target + + "' and no TF buffer is available"); + } + + const tf3::TransformStampedMsg transform = + ctx().tf->lookupTransform(target, in.header.frame_id, tf3::Time()); + robot_geometry_msgs::PoseStamped out; + tf3::doTransform(in, out, transform); + out.header.frame_id = target; + return out; + } + + /** + * @brief Đặt được robot tại pose này không (footprint thật, trên costmap đang dùng). + * + * Không có collision checker, hoặc không quy đổi được frame → coi là **đặt được**. "Không biết" + * không được biến thành "loại": loại nhầm hết ứng viên thì detour mất sạch đường ra, trong khi + * planner mới là bên phán quyết cuối cùng. + */ + /** + * @brief Collision checker khớp với costmap mà DETOUR đang lập plan trên đó. + * + * `ctx().collision` của runtime trỏ vào costmap LOCAL. Khi `use_global_costmap: true`, kiểm ứng + * viên bằng checker local là tự mâu thuẫn: pose ngoài cửa sổ lăn 8x8 m bị đọc thành "chắn" trong + * khi SBPL trên global costmap tới đó bình thường — đúng lỗi sim 2026-08-05 (footprint của pose ở + * ~3.5 m vươn quá rìa 4.0 m, `kOutsideMap`, cả đuôi tầm quét thành "vật cản"). Người quyết định + * và người kiểm phải nhìn cùng một lưới. + */ + const recovery_core::CollisionChecker* checker() const + { + if (use_global_costmap_ && own_checker_ != nullptr) + { + return own_checker_.get(); + } + return ctx().collision; + } + + /** + * @brief Phân loại một vị trí ứng viên trên costmap đã chọn. + * + * Kiểm **một điểm** (tâm robot), KHÔNG quét footprint — hai lý do, cả hai đo được trên sim + * 2026-08-05: + * 1. Footprint dài ~1 m làm dải "chắn" quanh vật cản phình thêm cả mét mỗi phía; cộng với việc + * footprint của pose ở ~3.5 m ló khỏi rìa cửa sổ lăn 4.0 m (bị đọc thành chắn), cả đuôi tầm + * quét thành "vật cản" và không bao giờ còn điểm nối. + * 2. SBPL — người phán quyết cuối — đằng nào cũng tự kiểm footprint khi lập đường; ở đây chỉ cần + * lọc thô. Cùng phép đo với `move_base2::checkPlan` (thứ khai hoả lượt detour này), nên hai + * bên nhìn thấy cùng một dải bẩn. + * + * `kUnknown` được coi là ĐẶT ĐƯỢC — khớp cả ba bên trong cùng đường chạy: `checkPlan` bỏ qua ô + * NO_INFORMATION, SBPL chạy `allow_unknown: true`. Lệch một bên là monitor báo chắn còn detour + * thấy sạch (hoặc ngược lại) — vòng lặp vô nghĩa. + * + * `kOutside` phải được bên gọi xử lý là **hết tầm quét**, không phải vật cản. + */ + /// @brief Phân loại một điểm bằng @p collision trong @p frame. Lỗi TF -> kFree (không loại mù). + recovery_core::CollisionChecker::Placement classifyOn( + const recovery_core::CollisionChecker* collision, const std::string& frame, + const robot_geometry_msgs::PoseStamped& pose_in_plan) const + { + using Placement = recovery_core::CollisionChecker::Placement; + + if (collision == nullptr) + { + return Placement::kOutside; + } + + robot_geometry_msgs::PoseStamped in_grid; + try + { + in_grid = toFrame(pose_in_plan, frame); + } + catch (const std::exception&) + { + return Placement::kFree; + } + + return collision->classifyPoint(in_grid.pose.position.x, in_grid.pose.position.y); + } + + /// @brief Phân loại một CELL trên lưới gộp (đã ở frame của lưới — map). + recovery_core::CollisionChecker::Placement classifyMergedPoint(double wx, double wy) const + { + using Placement = recovery_core::CollisionChecker::Placement; + + unsigned int mx = 0; + unsigned int my = 0; + if (!merged_grid_.worldToMap(wx, wy, mx, my)) + { + return Placement::kOutside; + } + + const unsigned char cost = merged_grid_.getCost(mx, my); + if (cost == robot_costmap_2d::NO_INFORMATION) + { + // Cùng quy ước với checkPlan và SBPL allow_unknown: chưa biết KHÔNG phải vật cản. + return Placement::kUnknown; + } + if (cost == robot_costmap_2d::LETHAL_OBSTACLE || + cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) + { + return Placement::kBlocked; + } + return Placement::kFree; + } + + /** + * @brief Pose này có nằm trong TẦM NHÌN LOCAL (cửa sổ costmap lăn) không? + * + * Chỉ dùng để chọn `last_blocked_in_view` — pose bẩn ngoài tầm là dữ liệu cũ (đuôi plan không bao + * giờ được replan, và lưới gộp ngoài cửa sổ chỉ còn dữ liệu tĩnh của global) nên không được quyền + * quyết định điểm nối phải nằm đâu. **Không** dùng làm bộ lọc ứng viên: điểm nối ngoài cửa sổ vẫn + * hợp lệ, vì planner chạy trên lưới gộp cỡ global. + * + * Dùng thẳng membership của lưới local thay vì một tham số "tầm nhìn" riêng: đúng hình học thật + * của cửa sổ lăn, và tự đúng khi ai đó đổi kích thước costmap. + * + * Mode `local`/`global` không có bản chụp local → trả true cho mọi pose, tức luật suy biến về + * "sau pose bẩn cuối cùng trong tầm quét", đúng hành vi của hai mode đó. + */ + bool inLocalView(const robot_geometry_msgs::PoseStamped& pose_in_plan) const + { + if (!merged_active_ || local_snapshot_.getSizeInCellsX() == 0) + { + return true; + } + + robot_geometry_msgs::PoseStamped in_map; + try + { + in_map = toFrame(pose_in_plan, costmap_frame_); + } + catch (const std::exception&) + { + return true; // Không quy đổi được thì không loại — luật suy biến về tầm quét, an toàn hơn. + } + + double lx = 0.0; + double ly = 0.0; + local_to_map_.applyInverse(in_map.pose.position.x, in_map.pose.position.y, lx, ly); + + unsigned int mx = 0; + unsigned int my = 0; + return local_snapshot_.worldToMap(lx, ly, mx, my); + } + + recovery_core::CollisionChecker::Placement classifyPose( + const robot_geometry_msgs::PoseStamped& pose_in_plan) const + { + using Placement = recovery_core::CollisionChecker::Placement; + + // Mode "combined": MỘT lưới gộp (global nền + local đè) là nguồn sự thật duy nhất — cùng lưới + // mà SBPL sẽ lập đường trên đó, nên người quét và người lập nhìn thấy cùng một thế giới. + if (merged_active_) + { + robot_geometry_msgs::PoseStamped in_grid; + try + { + in_grid = toFrame(pose_in_plan, costmap_frame_); + } + catch (const std::exception&) + { + return Placement::kFree; // Lỗi TF -> không loại mù; planner là người phán quyết cuối. + } + return classifyMergedPoint(in_grid.pose.position.x, in_grid.pose.position.y); + } + + const recovery_core::CollisionChecker* collision = checker(); + if (collision == nullptr) + { + return Placement::kFree; // Không biết thì không loại — planner là người phán quyết cuối. + } + return classifyOn(collision, costmap_frame_, pose_in_plan); + } + + /** + * @brief Chọn ứng viên điểm nối trên plan. + * + * Ba pha: + * 1. Tiến dọc plan tới đoạn **gần robot** — không có pha này, một tuyến vòng lại gần chỗ robot sẽ + * cho điểm nối phía sau lưng và robot quay đầu chạy ngược tuyến. + * 2. Tìm **pose bẩn cuối cùng trong tầm với**: đó là chỗ chắn phải vòng qua. + * 3. Nhận ứng viên **đặt được robot vào**, nằm **sau** chỗ chắn ít nhất `rejoin_clearance`, cách + * robot ít nhất `planning_distance`, cách nhau `sample_step`. + * + * Pha 2 và điều kiện "sạch" ở pha 3 là thứ bản gốc (và bản đầu của gói này) **không có**: chọn + * điểm nối thuần theo khoảng cách nghĩa là các ứng viên nằm ngay trên vật cản đang chắn tuyến — + * planner không bao giờ tới được, và mỗi lượt thử hỏng vẫn tốn trọn `allocated_time` trong lúc + * đang giữ mutex costmap. Đây đúng là lỗi đã quan sát trên sim 2026-08-05: ba ứng viên ở 2.03, + * 2.55, 3.06 m đều nằm trên tuyến bị chắn và cả ba đều "Solution not found". + */ + void buildCandidates(const robot_geometry_msgs::PoseStamped& robot_in_plan) + { + candidates_.clear(); + const double sq_planning_distance = planning_distance_ * planning_distance_; + + // --- Pha 1 --------------------------------------------------------------------------------- + std::size_t near_index = 0; + while (near_index < plan_.size() && + sqDistance(robot_in_plan, plan_[near_index]) >= sq_planning_distance) + { + ++near_index; + } + if (near_index == plan_.size()) + { + near_index = 0; // Plan không bao giờ lại gần robot — xét từ đầu thay vì bỏ cuộc. + } + + // --- Pha 2: quét & phân loại MỘT lượt ------------------------------------------------------- + // + // Ranh giới quét: rìa lưới costmap (`kOutside` — phần plan ngoài lưới không đánh giá được, + // không phải "chắn"), cuối plan, hoặc trần tuỳ chọn `max_rejoin_distance` (> 0). Với lưới gộp + // phủ toàn bản đồ, quét đi tới CUỐI plan. + using Placement = recovery_core::CollisionChecker::Placement; + + struct ScannedPose + { + std::size_t index; + double travelled; // [m] dọc plan, tính từ đoạn gần robot. + Placement placement; + }; + std::vector scanned; // Cấp phát mỗi lượt recovery — sự kiện hiếm, ngoài control path. + scanned.reserve(plan_.size() - near_index); + + scan_ = ScanStats(); + std::size_t last_blocked_in_view = plan_.size(); + { + double travelled = 0.0; // [m] + for (std::size_t i = near_index; i < plan_.size(); ++i) + { + if (i > near_index) + { + travelled += std::sqrt(sqDistance(plan_[i - 1], plan_[i])); + } + scan_.reach_distance = travelled; // [m] chỗ quét thật sự dừng, dù dừng vì lý do nào. + if (max_rejoin_distance_ > 0.0 && travelled > max_rejoin_distance_) + { + break; + } + + const Placement placement = classifyPose(plan_[i]); + if (placement == Placement::kOutside) + { + break; + } + ++scan_.scanned; + scanned.push_back({i, travelled, placement}); + + if (placement == Placement::kBlocked) + { + ++scan_.blocked; + scan_.last_blocked_distance = travelled; // [m] + if (scan_.first_blocked_distance < 0.0) + { + scan_.first_blocked_distance = travelled; // [m] + } + // Chỉ chỗ chắn NHÌN THẤY ĐƯỢC mới quyết định điểm nối phải nằm ở đâu — xem chú thích + // của pha 4. + if (inLocalView(plan_[i])) + { + last_blocked_in_view = i; + scan_.last_blocked_in_view_distance = travelled; // [m] + } + } + } + } + const bool have_block = last_blocked_in_view < plan_.size(); + + // --- Pha 3: khoảng cách tới pose bẩn gần nhất, HAI PHÍA dọc plan ---------------------------- + // + // Hành lang này tính với MỌI pose bẩn, kể cả ngoài tầm nhìn: nó là kiểm hình học tại chỗ (đừng + // đặt goal sát một bức tường mà global đã biết), rẻ, và không thể giết ứng viên ở xa nó. + const double kInfinity = std::numeric_limits::infinity(); + std::vector to_prev_block(scanned.size(), kInfinity); + std::vector to_next_block(scanned.size(), kInfinity); + { + double prev_block_at = -kInfinity; // [m] travelled của pose bẩn gần nhất phía trước. + for (std::size_t k = 0; k < scanned.size(); ++k) + { + if (scanned[k].placement == Placement::kBlocked) + { + to_prev_block[k] = 0.0; + prev_block_at = scanned[k].travelled; + } + else if (prev_block_at > -kInfinity) + { + to_prev_block[k] = scanned[k].travelled - prev_block_at; + } + } + double next_block_at = kInfinity; // [m] travelled của pose bẩn gần nhất phía sau. + for (std::size_t k = scanned.size(); k-- > 0;) + { + if (scanned[k].placement == Placement::kBlocked) + { + to_next_block[k] = 0.0; + next_block_at = scanned[k].travelled; + } + else if (next_block_at < kInfinity) + { + to_next_block[k] = next_block_at - scanned[k].travelled; + } + } + } + + // --- Pha 4: ứng viên ------------------------------------------------------------------------ + // + // Luật "sau pose bẩn CUỐI CÙNG TRONG TẦM NHÌN LOCAL" (2026-08-05f). Hai luật trước đều sai, và + // sai ở PHẠM VI chứ không sai ở ý: + // - "sau pose bẩn cuối toàn tầm quét": đuôi plan không bao giờ được replan nên nó cắt qua vật + // cản ở xa; một vết bẩn ở 7.96 m thành "chỗ chắn cuối" và giết sạch ứng viên hợp lệ ngay sau + // vật cản ĐANG chắn ở 2.5 m -> refuse -> ABORT (log sim 11:00); + // - "sau CỤM CHẮN ĐẦU TIÊN": chữa được ca trên nhưng nối vào khe giữa hai vật cản CÙNG NHÌN + // THẤY, robot chạy ~0.5 m rồi bị chắn lại -> detour lặp quanh đúng vật cản thứ nhất. + // Đúng: chỗ chắn nào robot ĐANG NHÌN THẤY (nằm trong cửa sổ costmap local) thì phải vòng qua + // hết; chỗ chắn ngoài tầm là dữ liệu cũ, không được quyền phủ quyết. + // + // Điểm nối ĐƯỢC PHÉP nằm ngoài cửa sổ local: từ 2026-08-05e planner chạy trên lưới GỘP cỡ + // global, nên biên thật của nó là bản đồ global chứ không phải cửa sổ lăn. Vật cản kéo dài quá + // tầm nhìn thì đường vòng tới một chỗ ta chưa thấy — monitor sẽ bắn lại và detour lượt nữa; + // đoán một lần rồi sửa rẻ hơn nhích từng đoạn để lấy đúng thông tin đó. + // + // Đường lùi cho plan ngắn hơn `planning_distance`. CHỈ dùng khi không có chỗ chắn nào: nếu có, + // một điểm nối "gần nhất có thể" gần như luôn nằm trước vật cản, tức vô nghĩa. + std::size_t fallback = plan_.size(); + double last_accepted_at = -kInfinity; // [m] travelled của ứng viên vừa nhận (giãn sample_step). + + for (std::size_t k = 0; k < scanned.size(); ++k) + { + const std::size_t i = scanned[k].index; + + if (scanned[k].placement == Placement::kBlocked) + { + continue; + } + + if (have_block) + { + if (i <= last_blocked_in_view) + { + continue; // Phải qua HẾT phần chắn NHÌN THẤY ĐƯỢC, không chỉ cụm đầu tiên. + } + if (to_prev_block[k] + kSpacingEpsilon < rejoin_clearance_ || + to_next_block[k] + kSpacingEpsilon < rejoin_clearance_) + { + continue; // Sát mép vật cản (phía nào cũng vậy) thì đường vòng đâm vào vùng đệm của nó. + } + if (scan_.first_clear_distance < 0.0) + { + scan_.first_clear_distance = scanned[k].travelled; // [m] chỗ nối được sớm nhất (chẩn đoán). + } + } + else if (i > near_index) + { + fallback = i; + } + + if (sqDistance(robot_in_plan, plan_[i]) < sq_planning_distance) + { + continue; + } + if (scanned[k].travelled - last_accepted_at + kSpacingEpsilon < sample_step_) + { + continue; + } + + candidates_.push_back(i); + last_accepted_at = scanned[k].travelled; + if (candidates_.size() >= static_cast(attempts_per_run_)) + { + break; + } + } + + if (candidates_.empty() && fallback < plan_.size()) + { + candidates_.push_back(fallback); + } + } + + double progressNow() const + { + return candidates_.empty() + ? 1.0 + : static_cast(attempt_) / static_cast(candidates_.size()); + } + + double remainingNow() const + { + return static_cast(candidates_.size() - std::min(attempt_, candidates_.size())); + } + + // --- Param --------------------------------------------------------------- + std::string planner_name_ = "SBPLLatticePlanner"; ///< Namespace param + tên truyền vào initialize(). + std::string planner_symbol_ = "SBPLLatticePlanner"; ///< Alias Boost.DLL thật trong .so. + bool use_global_costmap_ = false; + double planning_distance_ = kDefaultPlanningDistance; ///< [m] + double sample_step_ = kDefaultSampleStep; ///< [m] + double rejoin_clearance_ = kDefaultRejoinClearance; ///< [m] cách chỗ chắn tối thiểu. + double max_rejoin_distance_ = kDefaultMaxRejoinDistance; ///< [m] tầm quét, <= nửa cửa sổ costmap. + int attempts_per_run_ = kDefaultAttemptsPerRun; + double max_deviation_ = 0.0; ///< [m] 0 = không giới hạn. + /// "reference" = nối vào tuyến gốc của chặng (mặc định, tự về tuyến order); "current" = nối vào + /// plan đang bám (hành vi trước 2026-08-05e). + std::string rejoin_on_ = "reference"; + bool lock_costmap_ = true; + std::string costmap_frame_override_; ///< Test seam — production để rỗng. + + // --- Planner plugin (factory_ khai trước planner_: .so phải sống lâu hơn instance) ----------- + std::function planner_factory_; + robot_nav_core::BaseGlobalPlanner::Ptr planner_; + robot_costmap_2d::Costmap2DROBOT* initialized_costmap_ = nullptr; ///< non-owning. + + /// Checker trên costmap ĐÃ CHỌN, chỉ dựng cho mode "global" (ctx().collision là local). + std::unique_ptr own_checker_; + + std::string costmap_source_; ///< "local" | "global" | "combined". + + // --- Lưới gộp (mode combined) --------------------------------------------------------------- + /// Capability lưới ngoài của planner (alias "ExternalGrid"); std::function giữ .so sống. + std::function + set_external_grid_; + robot_costmap_2d::Costmap2D merged_grid_; ///< Bản chụp gộp; buffer tái dùng giữa các lượt. + robot_costmap_2d::Costmap2D local_snapshot_; ///< Bản chụp cửa sổ local; tái dùng như trên. + /// Frame local -> frame lưới gộp, chụp cùng lúc với hai lưới. Chiều ngược dùng cho @ref inLocalView. + PlanarTransform2D local_to_map_; + bool merged_active_ = false; ///< combined + đủ hai costmap + planner có capability. + + // --- Trạng thái một lượt -------------------------------------------------- + std::vector plan_; ///< Bản chụp plan, frame plan_frame_. + std::string plan_frame_; + std::string costmap_frame_; + std::vector candidates_; ///< Index điểm nối trong plan_, thử tuần tự. + std::size_t attempt_ = 0; + + /// Số liệu lượt quét gần nhất — chỉ để log khi từ chối, không tham gia quyết định nào. + struct ScanStats + { + std::size_t scanned = 0; + std::size_t blocked = 0; + double first_blocked_distance = -1.0; ///< [m] pose bẩn ĐẦU TIÊN; -1 = không có chỗ chắn nào. + /// [m] pose bẩn cuối cùng còn NHÌN THẤY ĐƯỢC — mốc quyết định điểm nối. -1 = không có. + double last_blocked_in_view_distance = -1.0; + double last_blocked_distance = -1.0; ///< [m] pose bẩn cuối cùng trong tầm quét. + double first_clear_distance = -1.0; ///< [m] chỗ nối được sớm nhất (đủ clearance); -1 = không. + double reach_distance = 0.0; ///< [m] chỗ quét kết thúc thật: rìa lưới, cap, hoặc hết plan. + }; + ScanStats scan_; +}; + +} // namespace sbpl_recovery + +BOOST_DLL_ALIAS(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery) diff --git a/test/config/recovery_behaviors_params.yaml b/test/config/recovery_behaviors_params.yaml new file mode 100644 index 0000000..6af9aae --- /dev/null +++ b/test/config/recovery_behaviors_params.yaml @@ -0,0 +1,94 @@ +# Config CHỈ dành cho unit test của sbpl_recovery — được nạp qua PNKX_NAV_CORE_CONFIG_DIR do chính +# binary test đặt. KHÔNG phải config runtime. +# +# `lock_costmap: false` và `costmap_frame_override` là test seam: costmap trong test là placeholder +# không dereference được (không dựng nổi Costmap2DROBOT trong unit test — cần tf3 + cây config đầy +# đủ). Production không bao giờ đặt hai khoá này. + +recovery: + behaviors: + - {name: detour, type: DetourPathRecovery} + - {name: detour_flaky, type: DetourPathRecovery} + - {name: detour_dead, type: DetourPathRecovery} + - {name: detour_map, type: DetourPathRecovery} + - {name: detour_narrow, type: DetourPathRecovery} + - {name: detour_alias, type: DetourPathRecovery} + + detour: + planner_name: TestLinePlanner + planning_distance: 1.0 # [m] + sample_step: 0.5 # [m] + attempts_per_run: 3 + lock_costmap: false + costmap_frame_override: odom + + detour_flaky: + planner_name: TestFlakyPlanner # hai ứng viên đầu bị "chắn", ứng viên ba mới thông + planning_distance: 1.0 + sample_step: 0.5 + attempts_per_run: 3 + lock_costmap: false + costmap_frame_override: odom + + detour_dead: + planner_name: TestDeadPlanner # không ứng viên nào thông -> behavior phải kFailed + planning_distance: 1.0 + sample_step: 0.5 + attempts_per_run: 3 + lock_costmap: false + costmap_frame_override: odom + + detour_map: + planner_name: TestLinePlanner # plan ở frame map, costmap ở odom -> ép đường quy đổi TF + planning_distance: 1.0 + sample_step: 0.5 + attempts_per_run: 3 + lock_costmap: false + costmap_frame_override: odom + + # Tên instance KHÁC symbol: đọc param từ `DetourOnlyTuning`, nạp .so theo alias `TestLinePlanner`. + # Đây là đường mà cấu hình runtime dùng để cho detour một instance SBPL riêng (allocated_time + # ngắn) trong khi `libsbpl_lattice_planner` chỉ export đúng một symbol. + detour_alias: + planner_name: DetourOnlyTuning + planner_symbol: TestLinePlanner + planning_distance: 1.0 + sample_step: 0.5 + attempts_per_run: 3 + lock_costmap: false + costmap_frame_override: odom + + detour_narrow: + planner_name: TestOffsetPlanner # planner giả luôn vẽ đường vòng lệch 1.0 m khỏi tuyến + planning_distance: 1.0 + sample_step: 0.5 + attempts_per_run: 3 + max_deviation: 0.2 # [m] chặt hơn độ lệch của planner -> mọi ứng viên bị loại + lock_costmap: false + costmap_frame_override: odom + +# Bảng symbol -> thư viện cho Boost.DLL. Ba symbol planner cùng một .so; param của planner đọc theo +# namespace mang tên symbol. +TestLinePlanner: + library_path: libsbpl_recovery_test_line_planner + +TestFlakyPlanner: + library_path: libsbpl_recovery_test_line_planner + fail_first_attempts: 2 + +TestDeadPlanner: + library_path: libsbpl_recovery_test_line_planner + fail_first_attempts: 1000 + +# Luôn vẽ đường vòng lệch 1.0 m khỏi đoạn thẳng start->goal: dùng để kiểm guard max_deviation. +TestOffsetPlanner: + library_path: libsbpl_recovery_test_line_planner + lateral_offset: 1.0 + +# Namespace param THUẦN — cố ý KHÔNG có library_path: nó không phải symbol, việc nạp .so đi theo +# `planner_symbol`. Tham số khác hẳn bản mặc định để test chứng minh param được đọc từ đây. +DetourOnlyTuning: + points: 9 + +DetourPathRecovery: + library_path: libsbpl_recovery diff --git a/test/detour_path_recovery_test.cpp b/test/detour_path_recovery_test.cpp new file mode 100644 index 0000000..5fbb0c5 --- /dev/null +++ b/test/detour_path_recovery_test.cpp @@ -0,0 +1,801 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm DetourPathRecovery: chọn điểm nối, splice với plan cũ, thử-lại theo ứng viên, quy đổi frame + * qua TF, và các đường từ chối. Planner là plugin giả (TestLinePlanner) nạp qua đúng đường + * Boost.DLL mà runtime đi; costmap là placeholder — hai test seam `lock_costmap` và + * `costmap_frame_override` giữ cho không có dereference nào chạm vào nó. + * + * Author: DuongTD + *********************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include + +namespace +{ + +using recovery_core::RecoveryBehavior; +using recovery_core::RecoveryContext; +using recovery_core::RecoveryGoal; +using recovery_core::RecoveryRegistry; +using recovery_core::RecoveryResult; +using recovery_core::RecoveryStatus; +using recovery_core::RecoveryTrigger; + +/// Costmap placeholder: địa chỉ hợp lệ nhưng KHÔNG phải costmap — mọi đường dereference đã bị tắt +/// qua test seam. Cùng khuôn với planner_runner_test của move_base2. +robot_costmap_2d::Costmap2DROBOT* dummyCostmap() +{ + static std::uintptr_t placeholder = 0; + return reinterpret_cast(&placeholder); +} + +class FakePoseProvider final : public recovery_core::PoseProvider +{ +public: + bool ok = true; + robot_geometry_msgs::PoseStamped pose; + + bool getRobotPose(robot_geometry_msgs::PoseStamped& out) const override + { + if (!ok) + { + return false; + } + out = pose; + return true; + } +}; + +/** + * @class BandCollisionChecker + * @brief Chặn một dải theo trục x: [from, to] không đặt được robot vào. + * + * Mô phỏng đúng tình huống sim: một vật cản nằm CHÍNH TRÊN tuyến, kéo dài vài mét — thứ khiến các + * ứng viên điểm nối chọn thuần theo khoảng cách đều rơi vào vùng cấm. + */ +class BandCollisionChecker final : public recovery_core::CollisionChecker +{ +public: + void blockBand(double from_x, double to_x) + { + from_x_ = from_x; + to_x_ = to_x; + } + + /// Vật cản THỨ HAI xa hơn trên tuyến — plan cũ không replan nên đuôi nó xuyên vật cản này mãi. + void blockSecondBand(double from_x, double to_x) + { + second_from_x_ = from_x; + second_to_x_ = to_x; + } + + /// Dải "chưa quan sát": costmap local lăn theo robot nên đây là phần lớn tuyến phía trước. + void unknownBand(double from_x, double to_x) + { + unknown_from_x_ = from_x; + unknown_to_x_ = to_x; + } + + /// Rìa lưới costmap: từ x này trở đi pose nằm NGOÀI lưới — quét phải dừng, không phải "chắn". + void outsideFrom(double from_x) + { + outside_from_x_ = from_x; + } + + double footprintCost(double x, double y, double theta) const override + { + (void)y; + (void)theta; + ++query_count_; + if ((x >= from_x_ && x <= to_x_) || (x >= second_from_x_ && x <= second_to_x_)) + { + return -1.0; + } + return (x >= unknown_from_x_ && x <= unknown_to_x_) ? -3.0 : 0.0; + } + + Placement classify(double x, double y, double theta) const override + { + if (x >= outside_from_x_) + { + return Placement::kOutside; + } + const double cost = footprintCost(x, y, theta); + if (cost >= 0.0) + { + return Placement::kFree; + } + return cost == -3.0 ? Placement::kUnknown : Placement::kBlocked; + } + + std::size_t queryCount() const + { + return query_count_; + } + +private: + double from_x_ = 1.0; + double to_x_ = 0.0; // dải rỗng: mặc định không chặn gì + double second_from_x_ = 1.0; + double second_to_x_ = 0.0; // dải thứ hai, mặc định rỗng + double unknown_from_x_ = 1.0; + double unknown_to_x_ = 0.0; + double outside_from_x_ = 1e9; // mặc định: lưới phủ hết + mutable std::size_t query_count_ = 0; +}; + +class FakePlanProvider final : public recovery_core::PlanProvider +{ +public: + std::vector plan; + + bool getGlobalPlan(std::vector& out) const override + { + if (plan.empty()) + { + return false; + } + out = plan; + return true; + } +}; + +robot_geometry_msgs::PoseStamped makePose(const std::string& frame, double x, double y) +{ + robot_geometry_msgs::PoseStamped pose; + pose.header.frame_id = frame; + pose.pose.position.x = x; + pose.pose.position.y = y; + pose.pose.orientation.w = 1.0; + return pose; +} + +/// Plan thẳng dọc trục x: [from_x, to_x] bước @p step, y cố định. +std::vector makeLinePlan(const std::string& frame, double from_x, + double to_x, double step, double y) +{ + std::vector plan; + for (double x = from_x; x <= to_x + 1e-9; x += step) + { + plan.push_back(makePose(frame, x, y)); + } + return plan; +} + +RecoveryBehavior* findBehavior(RecoveryRegistry& registry, const std::string& name) +{ + for (std::size_t i = 0; i < registry.size(); ++i) + { + if (registry.nameAt(i) == name) + { + return registry.at(i); + } + } + return nullptr; +} + +RecoveryGoal controllingGoal() +{ + RecoveryGoal goal; + goal.trigger = RecoveryTrigger::kControllingFailed; + return goal; +} + +/** + * Fixture: registry thật + plugin thật (nạp qua Boost.DLL) trên cổng giả. TF có sẵn một transform + * tĩnh map->odom (odom gốc tại (2, 1) trong map) cho các ca đổi frame. + */ +class DetourPathRecoveryTest : public ::testing::Test +{ +protected: + void SetUp() override + { + tf3::TransformStampedMsg map_to_odom; + map_to_odom.header.frame_id = "map"; + map_to_odom.child_frame_id = "odom"; + map_to_odom.transform.translation.x = 2.0; // [m] p_map = p_odom + (2, 1) + map_to_odom.transform.translation.y = 1.0; // [m] + map_to_odom.transform.rotation.w = 1.0; + ASSERT_TRUE(tf_.setTransform(map_to_odom, "test", /*is_static=*/true)); + + ctx_.pose = &pose_; + ctx_.plan = &plan_; + // Tuyến tham chiếu để RỖNG mặc định: phần lớn test kiểm hình học trên plan hiện hành, và + // behavior phải tự quay về `plan` khi tham chiếu chưa có. Test nào cần thì tự nạp. + ctx_.reference_plan = &reference_plan_; + ctx_.collision = &collision_; + ctx_.local_costmap = dummyCostmap(); + ctx_.tf = &tf_; + + robot::NodeHandle nh; + ASSERT_TRUE(registry_.loadFromConfig(nh, "recovery", ctx_)); + ASSERT_EQ(registry_.size(), 6u); + } + + FakePoseProvider pose_; + FakePlanProvider plan_; + FakePlanProvider reference_plan_; + BandCollisionChecker collision_; + tf3::BufferCore tf_; + RecoveryContext ctx_; + RecoveryRegistry registry_; + robot::Time t0_{100, 0}; +}; + +TEST_F(DetourPathRecoveryTest, StartRefusesWithoutAPlan) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan.clear(); // Không có plan thì không có gì để nối lại. + + EXPECT_FALSE(detour->start(controllingGoal(), t0_)); +} + +TEST_F(DetourPathRecoveryTest, SplicesTheDetourOntoTheRemainder) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + // Plan cùng frame với costmap (odom): không cần quy đổi. Robot ở gốc, plan 0..5 m bước 0.5. + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + EXPECT_EQ(path->header.frame_id, "odom"); + + // Ứng viên đầu tiên: pose đầu cách robot >= planning_distance (1.0 m) => x = 1.0 (index 2). + // Đường vòng 5 điểm (0,0)->(1,0) + phần còn lại của plan x = 1.5..5.0 (8 pose) = 13 pose. + ASSERT_EQ(path->poses.size(), 13u); + EXPECT_NEAR(path->poses.front().pose.position.x, 0.0, 1e-9); + EXPECT_NEAR(path->poses[4].pose.position.x, 1.0, 1e-9); // cuối đường vòng = điểm nối + EXPECT_NEAR(path->poses[5].pose.position.x, 1.5, 1e-9); // pose đầu của phần plan cũ + EXPECT_NEAR(path->poses.back().pose.position.x, 5.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, FlakyPlannerRetriesUntilACandidateWorks) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour_flaky"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + + // Hai ứng viên đầu (x = 1.0, 1.5) bị planner giả từ chối; ứng viên ba (x = 2.0) thành công. + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + + const RecoveryResult result = detour->update(t0_); + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Cuối đường vòng phải là điểm nối thứ BA — bằng chứng cursor ứng viên có tiến. + EXPECT_NEAR(path->poses[4].pose.position.x, 2.0, 1e-9); + EXPECT_NEAR(path->poses[5].pose.position.x, 2.5, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, FailsAfterAllCandidates) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour_dead"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + + // Hết attempts_per_run (3) ứng viên: kFailed để state machine chuyển behavior kế tiếp. + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed); +} + +TEST_F(DetourPathRecoveryTest, ConvertsFramesThroughTf) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour_map"); + ASSERT_NE(detour, nullptr); + + // Plan ở MAP, costmap ở ODOM (odom gốc tại map (2,1)). Robot đứng ở odom (0,0) = map (2,1). + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("map", 2.0, 7.0, 0.5, 1.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Kết quả phải nằm TRỌN trong frame của plan: đường vòng (planner trả ở odom) đã được quy về map. + EXPECT_EQ(path->header.frame_id, "map"); + EXPECT_NEAR(path->poses.front().pose.position.x, 2.0, 1e-9); // robot tại map (2,1) + EXPECT_NEAR(path->poses.front().pose.position.y, 1.0, 1e-9); + EXPECT_NEAR(path->poses[4].pose.position.x, 3.0, 1e-9); // điểm nối map x=3.0 + EXPECT_NEAR(path->poses[5].pose.position.x, 3.5, 1e-9); // plan cũ tiếp tục + EXPECT_NEAR(path->poses.back().pose.position.x, 7.0, 1e-9); + EXPECT_NEAR(path->poses.back().pose.position.y, 1.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, RejoinPointsSkipPastTheBlockedStretch) +{ + // Lỗi sim 2026-08-05: ứng viên chọn thuần theo khoảng cách đều rơi vào chính vật cản đang chắn + // tuyến, nên cả ba lượt SBPL đều "Solution not found" — mà mỗi lượt hỏng vẫn giữ mutex costmap. + // Đúng: bỏ qua cả dải bẩn, điểm nối đầu tiên phải nằm sau nó + rejoin_clearance. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 0.0); + collision_.blockBand(1.0, 2.4); // [m] vật cản trải dài trên tuyến + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Đường vòng 5 điểm; điểm cuối của nó là điểm nối. Pose bẩn cuối cùng trên plan là x = 2.0 + // (2.5 đã ra ngoài dải), cộng `rejoin_clearance` 0.5 -> ứng viên đầu tiên đạt là x = 2.5. + // KHÔNG phải x = 1.0 như luật chọn thuần-khoảng-cách cũ, vốn rơi thẳng vào vật cản. + EXPECT_NEAR(path->poses[4].pose.position.x, 2.5, 1e-9); + EXPECT_NEAR(path->poses[5].pose.position.x, 3.0, 1e-9); + EXPECT_NEAR(path->poses.back().pose.position.x, 6.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, PosesBeyondReachStopTheScanInsteadOfCountingAsBlocked) +{ + // Lỗi sim 2026-08-05 (lượt 2): pose ngoài cửa sổ costmap bị đọc thành "bẩn" — plan dài vài chục + // mét trên cửa sổ 8x8 m nên phần xa làm mọi ứng viên bị loại. Ngữ nghĩa đúng: `kOutside` là HẾT + // TẦM QUÉT — dừng lại, không phải vật cản. + // + // Mô phỏng: rìa lưới ở 3.5 m, plan dài 20 m, KHÔNG có vật cản thật trong lưới. Ứng viên phải + // chọn bình thường trong tầm, không bị phần ngoài lưới làm hỏng. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 20.0, 0.5, 0.0); + collision_.outsideFrom(3.5); // rìa lưới: quét dừng ở đây, không phải "chắn" + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Ứng viên đầu tiên vẫn là x = 1.0 (planning_distance của instance `detour`), không phải một pose + // nào đó bị phần ngoài lưới đẩy đi. + EXPECT_NEAR(path->poses[4].pose.position.x, 1.0, 1e-9); + EXPECT_NEAR(path->poses.back().pose.position.x, 20.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, RejoinsOntoTheReferenceRouteNotTheDriftedPlan) +{ + // Contract 2026-08-05e: điểm nối nằm trên TUYẾN GỐC của chặng, không phải plan đang bám. Nối vào + // plan đang bám thì mỗi lượt detour lấy kết quả lượt trước làm mốc — sim đo tuyến bị ăn mòn dần + // (rejoin 106/305 -> 130/289 -> 132/273) và robot không bao giờ quay về tuyến order. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + // Plan ĐANG BÁM đã trôi sang y = 3.0 sau vài lượt detour trước đó. + plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 3.0); + // Tuyến GỐC vẫn là tuyến order ở y = 0.0. + reference_plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Đuôi splice phải là đuôi TUYẾN GỐC (y = 0), không phải plan đã trôi (y = 3): đó chính là thứ + // kéo robot trở lại tuyến fleet đã duyệt. + EXPECT_NEAR(path->poses.back().pose.position.y, 0.0, 1e-9); + EXPECT_NEAR(path->poses.back().pose.position.x, 6.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, FallsBackToTheCurrentPlanWhenNoReferenceRouteExists) +{ + // Runtime chưa lập được plan nào (hoặc không cấp tuyến tham chiếu): vẫn phải vòng được, chỉ mất + // khả năng tự về tuyến. Im lặng bỏ cuộc thì tệ hơn nhiều. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 6.0, 0.5, 3.0); + reference_plan_.plan.clear(); // chưa có tuyến gốc + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + EXPECT_NEAR(path->poses.back().pose.position.y, 3.0, 1e-9); // đuôi của plan đang bám +} + +TEST_F(DetourPathRecoveryTest, RejoinsPastEveryVisibleObstacleNotJustTheFirst) +{ + // Luật chốt 2026-08-05f: điểm nối phải qua HẾT phần chắn còn NHÌN THẤY ĐƯỢC. Hai luật trước đều + // sai ở PHẠM VI: + // - "sau pose bẩn cuối toàn tầm quét": đuôi plan không bao giờ được replan nên nó cắt qua vật + // cản ở xa; vết bẩn ở 7.96 m giết sạch ứng viên hợp lệ ngay sau vật cản đang chắn ở 2.5 m -> + // refuse -> ABORT (log sim 11:00); + // - "sau cụm chắn ĐẦU TIÊN": nối vào khe giữa hai vật cản cùng nhìn thấy, robot chạy ~0.5 m rồi + // bị chắn lại -> detour lặp vô ích quanh đúng vật cản thứ nhất. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 10.0, 0.5, 0.0); + collision_.blockBand(1.0, 2.0); // vật cản đang chắn tuyến + collision_.blockSecondBand(4.0, 4.5); // vật cản thứ hai, CÙNG nhìn thấy -> phải vòng qua luôn + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Pose bẩn cuối nhìn thấy được là x = 4.5; + rejoin_clearance 0.5 -> ứng viên đầu tiên x = 5.0. + // KHÔNG phải x = 2.5 trong khe giữa hai vật cản như luật "cụm đầu tiên". + EXPECT_NEAR(path->poses[4].pose.position.x, 5.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, NarrowGapBetweenObstaclesIsSkipped) +{ + // Clearance tính CẢ HAI PHÍA: khoảng sạch giữa hai vật cản mà hẹp hơn 2*rejoin_clearance thì + // điểm nối trong đó đặt robot sát mép vật cản kế tiếp — monitor sẽ bắn lại ngay sau một nhịp. + // Đúng: nhảy qua, nối sau cụm thứ hai. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 10.0, 0.5, 0.0); + collision_.blockBand(1.0, 2.0); + collision_.blockSecondBand(2.5, 3.0); // khoảng giữa không còn pose sạch đủ clearance hai phía + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Sau cụm thứ hai (x = 3.0) + clearance 0.5 -> ứng viên đầu tiên x = 3.5. + EXPECT_NEAR(path->poses[4].pose.position.x, 3.5, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, UnobservedSpaceIsNotAnObstacle) +{ + // Lỗi sim 2026-08-05 (lượt 3): costmap local lăn theo robot nên mọi ô ngoài tầm sensor là + // NO_INFORMATION, và `footprintCost` trả âm cho cả ca đó. Detour đọc gần hết tuyến phía trước + // thành vật cản -> "no placeable rejoin point" -> từ chối mọi lượt. + // + // Phải khớp hai bên còn lại: `checkPlan` bỏ qua ô unknown, SBPL chạy `allow_unknown: true`. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 20.0, 0.5, 0.0); + collision_.unknownBand(0.6, 100.0); // gần như toàn bộ tuyến phía trước là "chưa quan sát" + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + ASSERT_NE(result.pathOut(), nullptr); + EXPECT_NEAR(result.pathOut()->poses[4].pose.position.x, 1.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, RealObstacleStillBlocksEvenAmidUnobservedSpace) +{ + // Nới unknown KHÔNG được nới luôn vật cản thật: vật cản nằm giữa vùng chưa quan sát vẫn phải đẩy + // điểm nối ra sau nó. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 20.0, 0.5, 0.0); + collision_.unknownBand(0.6, 100.0); + collision_.blockBand(1.0, 1.6); // vật cản THẬT nằm trong vùng unknown + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + ASSERT_NE(result.pathOut(), nullptr); + // Pose bẩn cuối là x = 1.5; cộng rejoin_clearance 0.5 -> điểm nối đầu tiên là x = 2.0. + EXPECT_NEAR(result.pathOut()->poses[4].pose.position.x, 2.0, 1e-9); +} + +TEST_F(DetourPathRecoveryTest, RefusesWhenTheOnlyCleanPosesAreBeforeTheObstacle) +{ + // Đường lùi ghi TRƯỚC chỗ chắn phải bị vứt: nối lại vào pose nằm trước vật cản là đưa robot về + // đúng chỗ vừa bị chặn, rồi monitor bắn lại ngay lượt sau và cạn route. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 20.0, 0.5, 0.0); + // Sạch tới 1.4 m rồi chắn hết phần còn lại TRONG TẦM QUÉT (3.0 m). + collision_.blockBand(1.5, 100.0); + + EXPECT_FALSE(detour->start(controllingGoal(), t0_)); +} + +TEST_F(DetourPathRecoveryTest, RefusesToStartWhenNoRejoinPointIsPlaceable) +{ + // Toàn bộ phần còn lại của tuyến bị chắn: từ chối NGAY. Chạy đủ attempts_per_run lượt SBPL chắc + // chắn hỏng chỉ để tới cùng kết luận, trong khi mỗi lượt giữ mutex costmap trọn allocated_time — + // đó chính là thứ làm đói thread cập nhật costmap trên sim. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + collision_.blockBand(0.5, 100.0); + + EXPECT_FALSE(detour->start(controllingGoal(), t0_)); +} + +TEST_F(DetourPathRecoveryTest, NoCollisionCheckerFallsBackToDistanceOnlyCandidates) +{ + // Context không có collision checker: "không biết" không được biến thành "loại hết" — hành vi + // phải y như trước, planner là bên phán quyết cuối. + FakePoseProvider pose; + FakePlanProvider plan; + RecoveryContext ctx; + ctx.pose = &pose; + ctx.plan = &plan; + ctx.collision = nullptr; + ctx.local_costmap = dummyCostmap(); + ctx.tf = &tf_; + + robot::NodeHandle nh; + RecoveryRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "recovery", ctx)); + + RecoveryBehavior* detour = findBehavior(registry, "detour"); + ASSERT_NE(detour, nullptr); + + pose.pose = makePose("odom", 0.0, 0.0); + plan.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + ASSERT_NE(result.pathOut(), nullptr); + EXPECT_NEAR(result.pathOut()->poses[4].pose.position.x, 1.0, 1e-9); // ứng viên đầu như cũ +} + +TEST_F(DetourPathRecoveryTest, PlannerSymbolMayDifferFromTheInstanceName) +{ + // Đường mà runtime dùng để cho detour một instance SBPL riêng: `planner_name` là namespace param + // (`DetourOnlyTuning`, khai `points: 9`), `planner_symbol` là alias có thật trong .so. + // `libsbpl_lattice_planner` chỉ export một symbol, nên nếu hai thứ này bị buộc phải trùng nhau + // thì không thể có instance tuning riêng — đúng lỗi làm route path_blocked rỗng trên sim. + RecoveryBehavior* detour = findBehavior(registry_, "detour_alias"); + ASSERT_NE(detour, nullptr) << "behavior bị loại lúc nạp: planner_symbol không resolve được"; + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + const RecoveryResult result = detour->update(t0_); + + ASSERT_EQ(result.status, RecoveryStatus::kSucceeded); + const robot_nav_msgs::Path* path = result.pathOut(); + ASSERT_NE(path, nullptr); + + // Param đọc từ `DetourOnlyTuning`: đường vòng 9 điểm (mặc định là 5) + 8 pose còn lại của plan. + EXPECT_EQ(path->poses.size(), 17u); + EXPECT_NEAR(path->poses[8].pose.position.x, 1.0, 1e-9); // điểm nối +} + +TEST_F(DetourPathRecoveryTest, RejectsDetoursThatStrayTooFarFromTheRoute) +{ + // Guard lệch tuyến: order chỉ định tuyến, robot chỉ được rời khỏi nó trong hành lang fleet cho + // phép. Planner giả luôn phình 1.0 m, ngưỡng đặt 0.2 m -> mọi ứng viên bị loại, behavior kFailed + // để route chuyển sang cách xử lý khác. + RecoveryBehavior* detour = findBehavior(registry_, "detour_narrow"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + + // Ba ứng viên, ứng viên nào cũng lập được đường nhưng đều vượt ngưỡng lệch. + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kRunning); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed); +} + +TEST_F(DetourPathRecoveryTest, AcceptsDetoursInsideTheDeviationLimit) +{ + // Cùng ngưỡng 0.2 m nhưng planner mặc định (`detour`) không phình: đường vòng nằm trên tuyến nên + // guard không được chặn nhầm. + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kSucceeded); +} + +TEST_F(DetourPathRecoveryTest, FailsWhenPoseIsLostMidRun) +{ + RecoveryBehavior* detour = findBehavior(registry_, "detour"); + ASSERT_NE(detour, nullptr); + + pose_.pose = makePose("odom", 0.0, 0.0); + plan_.plan = makeLinePlan("odom", 0.0, 5.0, 0.5, 0.0); + + ASSERT_TRUE(detour->start(controllingGoal(), t0_)); + + // Mất pose giữa lượt: không được lập đường vòng bằng pose cũ. + pose_.ok = false; + EXPECT_EQ(detour->update(t0_).status, RecoveryStatus::kFailed); +} + +TEST(DetourPathRecoveryNoTfTest, RefusesWhenFramesDifferWithoutTf) +{ + // Registry riêng với context KHÔNG có TF: plan (map) khác frame costmap (odom) phải bị từ chối + // ngay tại start, kèm lý do — không đoán, không trộn frame. + FakePoseProvider pose; + FakePlanProvider plan; + RecoveryContext ctx; + ctx.pose = &pose; + ctx.plan = &plan; + ctx.local_costmap = dummyCostmap(); + ctx.tf = nullptr; + + robot::NodeHandle nh; + RecoveryRegistry registry; + ASSERT_TRUE(registry.loadFromConfig(nh, "recovery", ctx)); + + RecoveryBehavior* detour = findBehavior(registry, "detour_map"); + ASSERT_NE(detour, nullptr); + + pose.pose = makePose("odom", 0.0, 0.0); + plan.plan = makeLinePlan("map", 2.0, 7.0, 0.5, 1.0); + + EXPECT_FALSE(detour->start(controllingGoal(), robot::Time{100, 0})); +} + +} // namespace + +// ================================================================================================ +// merge_grids.h — ngữ nghĩa gộp lưới (thuần, lưới tay, không cần costmap sống) +// ================================================================================================ + +TEST(MergeGrids, CellMergeSemantics) +{ + using robot_costmap_2d::FREE_SPACE; + using robot_costmap_2d::LETHAL_OBSTACLE; + using robot_costmap_2d::NO_INFORMATION; + + // local chưa quét -> tin mắt rộng. + EXPECT_EQ(sbpl_recovery::mergeCellCost(LETHAL_OBSTACLE, NO_INFORMATION), LETHAL_OBSTACLE); + EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, NO_INFORMATION), FREE_SPACE); + // global chưa biết nhưng local ĐÃ biết -> lấy local (max mù sẽ biến 255 thành "chắn"). + EXPECT_EQ(sbpl_recovery::mergeCellCost(NO_INFORMATION, FREE_SPACE), FREE_SPACE); + EXPECT_EQ(sbpl_recovery::mergeCellCost(NO_INFORMATION, LETHAL_OBSTACLE), LETHAL_OBSTACLE); + // Cả hai đều biết -> một bên chắn là chắn; local FREE không xoá tường global. + EXPECT_EQ(sbpl_recovery::mergeCellCost(LETHAL_OBSTACLE, FREE_SPACE), LETHAL_OBSTACLE); + EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, LETHAL_OBSTACLE), LETHAL_OBSTACLE); + EXPECT_EQ(sbpl_recovery::mergeCellCost(FREE_SPACE, FREE_SPACE), FREE_SPACE); +} + +TEST(MergeGrids, OverlayWritesLocalWindowOntoGlobalBase) +{ + using robot_costmap_2d::Costmap2D; + using robot_costmap_2d::FREE_SPACE; + using robot_costmap_2d::LETHAL_OBSTACLE; + using robot_costmap_2d::NO_INFORMATION; + + // Nền global 10x10 @ 0.1 m, gốc (0,0): FREE, một bức tường tĩnh tại (0.55, 0.55). + Costmap2D merged(10, 10, 0.1, 0.0, 0.0, FREE_SPACE); + merged.setCost(5, 5, LETHAL_OBSTACLE); + + // Cửa sổ local 4x4 @ 0.1 m, gốc (0.2, 0.2): một vật cản tươi, một cell FREE trùng tường global, + // phần còn lại chưa quét (NO_INFORMATION). + Costmap2D local(4, 4, 0.1, 0.2, 0.2, NO_INFORMATION); + local.setCost(1, 1, LETHAL_OBSTACLE); // (0.35, 0.35): vật cản sensor + local.setCost(3, 3, FREE_SPACE); // (0.55, 0.55): local nói sạch NGAY TRÊN tường global + + sbpl_recovery::PlanarTransform2D identity; + sbpl_recovery::overlayLocalGrid(local, identity, merged); + + unsigned int mx = 0; + unsigned int my = 0; + ASSERT_TRUE(merged.worldToMap(0.35, 0.35, mx, my)); + EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE); // vật cản tươi được đè vào nền + ASSERT_TRUE(merged.worldToMap(0.55, 0.55, mx, my)); + EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE); // tường global KHÔNG bị local FREE xoá + ASSERT_TRUE(merged.worldToMap(0.25, 0.25, mx, my)); + EXPECT_EQ(merged.getCost(mx, my), FREE_SPACE); // local chưa quét -> giữ nền global + ASSERT_TRUE(merged.worldToMap(0.95, 0.95, mx, my)); + EXPECT_EQ(merged.getCost(mx, my), FREE_SPACE); // ngoài cửa sổ local -> nền global nguyên vẹn +} + +TEST(MergeGrids, OverlayTransformsLocalFrameIntoGridFrame) +{ + using robot_costmap_2d::Costmap2D; + using robot_costmap_2d::FREE_SPACE; + using robot_costmap_2d::LETHAL_OBSTACLE; + using robot_costmap_2d::NO_INFORMATION; + + Costmap2D merged(20, 20, 0.1, 0.0, 0.0, FREE_SPACE); + + // Local frame (odom) lệch map: tịnh tiến (1.0, 0.5), quay 90 độ. + Costmap2D local(4, 4, 0.1, 0.0, 0.0, NO_INFORMATION); + local.setCost(2, 0, LETHAL_OBSTACLE); // tâm cell tại odom (0.25, 0.05) + + sbpl_recovery::PlanarTransform2D odom_to_map; + odom_to_map.x = 1.0; + odom_to_map.y = 0.5; + odom_to_map.cos_yaw = 0.0; + odom_to_map.sin_yaw = 1.0; // yaw = +90 độ: (x, y) -> (-y, x) + + sbpl_recovery::overlayLocalGrid(local, odom_to_map, merged); + + // odom (0.25, 0.05) -> map (1.0 - 0.05, 0.5 + 0.25) = (0.95, 0.75). + unsigned int mx = 0; + unsigned int my = 0; + ASSERT_TRUE(merged.worldToMap(0.95, 0.75, mx, my)); + EXPECT_EQ(merged.getCost(mx, my), LETHAL_OBSTACLE); +} + +int main(int argc, char** argv) +{ +#ifdef SBPL_RECOVERY_TEST_CONFIG_DIR + // Trỏ cây config vào bản test TRƯỚC khi bất kỳ NodeHandle nào được dựng. + setenv("PNKX_NAV_CORE_CONFIG_DIR", SBPL_RECOVERY_TEST_CONFIG_DIR, 1); +#endif +#ifdef SBPL_RECOVERY_TEST_LIBRARY_DIR + // PluginLoaderHelper chỉ ghép ".so" trong nhánh PNKX_NAV_CORE_LIBRARY_PATH — không đặt biến này + // thì `library_path: libsbpl_recovery` không resolve được khi LD_LIBRARY_PATH thiếu devel/lib. + // Cùng khuôn với bộ test của recovery_core. + setenv("PNKX_NAV_CORE_LIBRARY_PATH", SBPL_RECOVERY_TEST_LIBRARY_DIR, 0); +#endif + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/plugins/test_line_planner.cpp b/test/plugins/test_line_planner.cpp new file mode 100644 index 0000000..58f92f9 --- /dev/null +++ b/test/plugins/test_line_planner.cpp @@ -0,0 +1,94 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * sbpl_recovery — global planner GIẢ cho unit test: nối thẳng start->goal. + * + * Không đụng costmap (test truyền placeholder không dereference được). Kịch bản lỗi điều khiển + * bằng param `fail_first_attempts`: N lời gọi makePlan đầu tiên trả false — mô phỏng "ứng viên + * điểm nối gần bị chắn, ứng viên xa hơn mới thông". + * + * Export hai alias từ cùng một factory: `TestLinePlanner` (luôn thành công) và `TestFlakyPlanner` + * (đọc param theo tên riêng của nó) — mỗi symbol đọc param từ namespace mang tên chính nó. + * + * Author: DuongTD + *********************************************************************/ + +#include +#include +#include +#include + +#include + +#include +#include + +namespace sbpl_recovery_test +{ + +class TestLinePlanner final : public robot_nav_core::BaseGlobalPlanner +{ +public: + static robot_nav_core::BaseGlobalPlanner::Ptr create() + { + return std::make_shared(); + } + + bool initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* /*costmap*/) override + { + // Costmap là placeholder trong test — TUYỆT ĐỐI không dereference. + robot::NodeHandle root; + robot::NodeHandle nh(root, name); + nh.param("fail_first_attempts", fail_first_attempts_, 0); + nh.param("points", points_, 5); + nh.param("lateral_offset", lateral_offset_, 0.0); + return true; + } + + bool makePlan(const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) override + { + plan.clear(); + if (calls_made_++ < fail_first_attempts_) + { + return false; + } + + // `lateral_offset` đẩy các điểm GIỮA sang bên theo pháp tuyến của đoạn start->goal, giữ nguyên + // hai đầu. Đây là hình dạng của một đường vòng thật, và là thứ guard `max_deviation` phải đo. + const double dx = goal.pose.position.x - start.pose.position.x; + const double dy = goal.pose.position.y - start.pose.position.y; + const double length = std::hypot(dx, dy); + const double nx = length > 1e-9 ? -dy / length : 0.0; + const double ny = length > 1e-9 ? dx / length : 0.0; + + for (int i = 0; i < points_; ++i) + { + const double ratio = points_ > 1 ? static_cast(i) / (points_ - 1) : 1.0; + // Hình chuông: 0 ở hai đầu, lớn nhất ở giữa. + const double bulge = lateral_offset_ * std::sin(ratio * M_PI); + + robot_geometry_msgs::PoseStamped pose = start; + pose.pose.position.x = start.pose.position.x + ratio * dx + bulge * nx; + pose.pose.position.y = start.pose.position.y + ratio * dy + bulge * ny; + pose.pose.orientation = goal.pose.orientation; + plan.push_back(pose); + } + return true; + } + +private: + int fail_first_attempts_ = 0; + int points_ = 5; + double lateral_offset_ = 0.0; ///< [m] độ phình ngang lớn nhất so với đoạn start->goal. + int calls_made_ = 0; +}; + +} // namespace sbpl_recovery_test + +BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestLinePlanner) +BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestFlakyPlanner) +BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestDeadPlanner) +BOOST_DLL_ALIAS(sbpl_recovery_test::TestLinePlanner::create, TestOffsetPlanner)