From 6fbc29f6d8be815cfcfc4f0c8ec476bc72acd135 Mon Sep 17 00:00:00 2001 From: duongtd Date: Sun, 9 Aug 2026 19:21:50 +0700 Subject: [PATCH] update --- README.md | 277 +++++++----------- .../sbpl_lattice_planner.h | 25 +- src/sbpl_lattice_planner.cpp | 88 ++++-- 3 files changed, 193 insertions(+), 197 deletions(-) diff --git a/README.md b/README.md index b40abb2..f03c7dc 100644 --- a/README.md +++ b/README.md @@ -1,184 +1,121 @@ -sbpl_lattice_planner -==================== +# sbpl_lattice_planner -The `sbpl_lattice_planner` is a global planner plugin for -[move_base](https://wiki.ros.org/move_base) and wraps the -[SBPL search-based planning library](https://wiki.ros.org/sbpl). +Global planner tìm đường trên **lattice (x, y, theta)** bằng thư viện +[SBPL](https://github.com/sbpl/sbpl) (ARA\* / AD\*), port sang hệ sinh thái +navigation phi-ROS: implement `robot_nav_core::BaseGlobalPlanner`, dùng +`robot_costmap_2d`, export plugin bằng **boost::dll** (không phải pluginlib). -Paths are generated by combining a series of "motion primitives" which are -short, kinematically feasible motions. Planning is therefore done in x, y, and -theta dimensions, resulting in smooth paths that take robot orientation into -account, which is especially important if the robot is not assumed to be -circular or has nonholonomic constraints (e.g., the robot cannot move -sideways). Plans can be found using the `ARA*` planner or `AD*` planner from the -SBPL library. +Path được ghép từ các **motion primitive** — những đoạn chuyển động ngắn khả thi +về động học đọc từ file `.mprim` — nên kết quả có tính đến hướng (heading) của +robot, phù hợp robot nonholonomic và footprint không tròn. -## Video +Nguồn gốc: port từ `sbpl_lattice_planner` của +[navigation_experimental](https://github.com/ros-planning/navigation_experimental) +(manifest ROS cũ vẫn còn dạng comment trong `package.xml`). -[![SBPL lattice planner on PR2 robot](https://img.youtube.com/vi/WeXdCmEpRW0/0.jpg)](https://www.youtube.com/watch?v=WeXdCmEpRW0) +## Khác biệt so với bản ROS gốc -## How to use +| | Bản ROS gốc | Bản này | +|---|---|---| +| Interface | `nav_core::BaseGlobalPlanner` (pluginlib) | `robot_nav_core::BaseGlobalPlanner`, export qua `BOOST_DLL_ALIAS(SBPLLatticePlanner::create, SBPLLatticePlanner)` | +| Params | ROS param server | `robot::NodeHandle` đọc YAML trực tiếp từ disk (`PNKX_NAV_CORE_CONFIG_DIR`) | +| Costmap | `costmap_2d` | `robot_costmap_2d::Costmap2DROBOT` | +| Topics | publish `plan`, `sbpl_lattice_planner_stats`, `footprint_markers` | **Không publish gì** — mọi publisher đã tắt; path chỉ trả về qua `makePlan()`, phía host (move_base → AmrPublisher) lo việc đưa lên ROS | +| Start heading | luôn là heading hiện tại của robot | có thêm chế độ `free_start_heading` (xem dưới) | -This global planner can be used with `move_base` simply by setting the -`base_global_planner` parameter to `SBPLLatticePlanner`. Additionally, at the -very least the path to a motion primitive file must be specified shown below in -the list of parameters. +Di sản còn lại trong package (không dùng ở runtime): `msg/SBPLLatticePlannerStats.msg` +(publishStats đã comment), params `publish_footprint_path` / `visualizer_skip_poses` +(publisher tắt nên không có tác dụng), các script `matlab/mprim/genmprim*.m`. -### Example in Stage +## Runtime: được load như thế nào -The package contains a launch file for testing the `sbpl_lattice_planner` as -the global planner for `move_base` using stage for 2D simulation: +1. `move_base` (pnkx_nav_core) chọn planner theo + `base_global_planner: SBPLLatticePlanner` trong `move_base_common_params.yaml`. +2. Symbol `SBPLLatticePlanner` được resolve qua key `library_path: libsbpl_lattice_planner` + trong `sbpl_global_params.yaml` (tìm theo `PNKX_NAV_CORE_LIBRARY_PATH`, `devel/lib`, + `LD_LIBRARY_PATH`). +3. Mỗi lần `makePlan(start, goal, plan)`: + - Nếu kích thước costmap / footprint / cost tại bán kính ngoại tiếp thay đổi → + hủy và khởi tạo lại environment SBPL (đọc lại file mprim). + - Đồng bộ cost từ `robot_costmap_2d` sang SBPL: LETHAL/INSCRIBED giữ mức + `lethal_obstacle`, các giá trị khác scale tuyến tính theo + `sbpl_cost_multiplier`; quá `force_scratch_limit` cell thay đổi thì plan từ đầu. + - `SetStart`/`SetGoal` → `replan(allocated_time)` → convert chuỗi state thành + path (nối intermediate poses của từng primitive — **khoảng cách pose trên + path chính là khoảng cách sample trong file mprim**). + +### Chế độ `free_start_heading` + +Dùng khi local planner tự quay tại chỗ về hướng path trước khi bám +(vd `turn_around_priority` của hybrid planner). Khi đó heading xuất phát không +phải ràng buộc thật; giữ nó chỉ ép SBPL vẽ cung quay đầu (U-turn) ở đầu path +lúc goal nằm phía sau — chuỗi primitive quay tại chỗ đắt hơn cung tiến nhiều +lần theo costmult nên không bao giờ được chọn. + +Cơ chế 3 tầng, đảm bảo **path mở đầu bằng đoạn thẳng theo hướng đi thật của +route** (không nhất thiết hướng tới goal): + +1. Plan lần 1 với heading giả định hướng thẳng tới goal (goal quá gần ~2 cell + thì dùng heading của goal). Đây chỉ là seed — SBPL bắt buộc cần một state + `(x, y, theta)` cụ thể. +2. Nếu 0.5m đầu path vẫn cong (lệch heading > 0.2 rad): quét tìm đoạn thẳng + đầu tiên trên path (heading không đổi liên tục ≥ 0.3m, quét tối đa 3m — + đủ vượt U-turn 180°), căn heading xuất phát theo hướng đó và **plan lại + đúng một lần**. Replan lỗi thì giữ path đầu, không trả thất bại. +3. Heading giả định không ra nghiệm → tự retry với heading thật của robot. + +## Cấu hình + +File: `pnkx_nav_core/config/sbpl_global_params.yaml`, khối `SBPLLatticePlanner:`. +**Lưu ý hai cây config của workspace**: bản trùng tên bên +`Controllers/Packages/amr_startup/config` là di sản ROS, nav core không đọc — +sửa nhầm bên đó sẽ không có tác dụng. + +| Param | Kiểu | Default trong code | Ý nghĩa | +|---|---|---|---| +| `library_path` | string | — (bắt buộc) | tên library để boost::dll resolve symbol | +| `primitive_filename` | string | `""` (bắt buộc) | đường dẫn file `.mprim`; `resolution_m` trong file PHẢI khớp resolution costmap, lệch là SBPL từ chối nạp | +| `planner_type` | string | `ARAPlanner` | `ARAPlanner` (ARA\*) hoặc `ADPlanner` (AD\*) | +| `allocated_time` | double | 10.0 | [s] quỹ thời gian mỗi lần plan; còn dư thì ARA\* tiếp tục hạ epsilon | +| `initial_epsilon` | double | 3.0 | hệ số nới heuristic lần search đầu (>= 1); 1.0 = A\* tối ưu ngay, không có nghiệm sớm | +| `forward_search` | bool | false | search xuôi start→goal hay ngược; AD\* nên dùng backward để replan nhanh | +| `force_scratch_limit` | int | 500 | số cell costmap thay đổi vượt ngưỡng này thì bỏ search cũ, plan từ đầu | +| `nominalvel_mpersecs` | double | 0.4 | [m/s] vận tốc danh định — dùng tính cost thời gian của primitive | +| `timetoturn45degsinplace_secs` | double | 0.6 | [s] thời gian quay tại chỗ 45° — dùng tính cost góc quay | +| `free_start_heading` | bool | false | bỏ ràng buộc heading xuất phát, path mở đầu bằng đoạn thẳng (xem trên); chỉ bật khi local planner có bước quay tại chỗ đầu path | +| `allow_unknown` | bool | true | cho phép plan xuyên vùng unknown | +| `lethal_obstacle` | uchar | 20 | mức cost obstacle trong bản đồ nội bộ của SBPL; các giá trị khác scale theo | +| `environment_type` | string | `XYThetaLattice` | chỉ hỗ trợ giá trị này | +| `publish_footprint_path` | bool | true | (không tác dụng — publisher đã tắt) | +| `visualizer_skip_poses` | int | 5 | (không tác dụng — publisher đã tắt) | + +Cost mỗi primitive = `max(thời_gian_tịnh_tiến, thời_gian_quay) * costmult` của +primitive trong file mprim — nên `nominalvel` / `timetoturn45` và bộ costmult +trong file mprim phải được tune **cùng nhau**. + +## Motion primitives + +- `matlab/mprim/` chứa các bộ `.mprim` có sẵn (5cm là chính: `unicycle_highcost_5cm.mprim` + — bộ tham chiếu tuned backward=40/turninplace=20, `unicycle_5cm_noreverse_trolley.mprim` + — cấm lùi, `diff.mprim` — bộ đang được `sbpl_global_params.yaml` trỏ tới, v.v.). +- Sinh bộ mới: dùng **`Test/mprim_gen`** (Python, xem README của nó) — generator + theo config robot, tự kiểm các ràng buộc SBPL (costmult nguyên, heading cuối + khớp góc rời rạc, spacing pose đều ≤ 1 cell). Các script `genmprim*.m` MATLAB + chỉ giữ làm tham khảo lịch sử. + +## Build ```bash -roslaunch sbpl_lattice_planner move_base_sbpl_fake_localization_2.5cm.launch +catkin_make --pkg sbpl_lattice_planner # từ root workspace ``` -## ROS API +CMakeLists dual catkin/standalone (giống `hybrid_local_planner`). Cần thư viện +SBPL cài sẵn ở mức hệ thống (`find_package(SBPL REQUIRED)` — bản ROS Noetic +`/opt/ros/noetic` dùng được). Output: `devel/lib/libsbpl_lattice_planner.so`. -### Published Topics +## Tuning costmap (giữ nguyên từ bản gốc, vẫn đúng) -`~/SBPLLatticePlanner/plan` ([nav\_msgs/Path](http://docs.ros.org/api/nav_msgs/html/msg/Path.html)) - -- The last plan computed by SBPL, published every time the planner computes a - new path, and used primarily for visualization purposes. - -`~/SBPLLatticePlanner/sbpl_lattice_planner_stats` ([sbpl\_lattice\_planner/SBPLLatticePlannerStats](http://docs.ros.org/api/sbpl_lattice_planner/html/msg/SBPLLatticePlannerStats.html)) - -- Statistics from the last planning request. Stats include: time taken to get - to the first and final solutions, number of state expansions taken to get the - first and final solutions, the epsilon (bound on the sub-optimality of the - solution) of the first and final solutions, and the size of the final - solution. - -`~/SBPLLatticePlanner/footprint_markers` ([visualization\_msgs/Marker](http://docs.ros.org/api/visualization_msgs/html/msg/Marker.html)) - -- The footprint markers along the planned path (for visualization in RViz). - -### Subscribed Topics - -None - -### Services - -None - -### Parameters - -`~/SBPLLatticePlanner/planner_type` (`string`, default: "ARAPlanner") - -- Specifies which planner to use. It can either be "ARAPlanner" for `ARA*` or - "ADPlanner" for `AD*`. - -`~/SBPLLatticePlanner/allocated_time` (`double`, default: 10.0) - -- The amount of time given to the planner to find a solution. If there is still - time remaining after the planner finds its sub-optimal initial solution - (specified by "initial_epsilon"), the planner will use up remaining time - improving the solution until it is optimal or until time runs out (whichever - comes first). - -`~/SBPLLatticePlanner/initial_epsilon` (`double`, default: 3.0) - -- The value the heuristic is scaled by for the first search. This value must - be greater or equal to 1. The larger this value is, the faster the search - tends to find a solution (likely sub-optimal if epsilon is larger than 1). - After the first search, the planner will continue to reduce the epsilon value - until it is 1 (optimal search). - -`~/SBPLLatticePlanner/environment_type` (`string`, default: "XYThetaLattice")) - -- The type of environment being searched. Currently, XYThetaLattice is the only - supported environment. - -`~/SBPLLatticePlanner/forward_search` (`bool`, default: false) - -- The direction the search is done in. If you are using `AD*`, you should use - backward search for fast replanning times. For `ARA*` it doesn't matter too - much which direction you use. - -`~/SBPLLatticePlanner/primitive_filename` (`string`, default: "") - -- The path to a motion primitive file. This MUST be specified by the user for - the planner to work. There is an example motion primitive file that can be - used in `matlab/mprim/pr2.mprim` in the SBPL package. If you want to generate - your own motion primitive file to match the kinematics of your robot or your - map resolution, there is are several `genmprim*.m` scripts in `matlab/mprim/` - in the SBPL package to help you. - -`~/SBPLLatticePlanner/force_scratch_limit` (`int`, default: 500) - -- The parameter only matters if you are using `AD*`. If at least this many map - cells have changed since the last plan was generated, the planner will not - reuse previous search information and instead plan from scratch. - -`~/SBPLLatticePlanner/nominalvel_mpersecs` (`double`, default: 0.4) - -- The linear velocity of the robot in meters/sec. - -`~/SBPLLatticePlanner/timetoturn45degsinplace_secs` (`double`, 0.6) - -- The time it takes the robot to turn 45 degrees in place in seconds. - -`~/SBPLLatticePlanner/lethal_obstacle` (`unsigned char`, default: 20) - -- The cost of an obstacle in the planner's version of the costmap. All other - values in the costmap are scaled accordingly. The obstacle cost is the - largest in the costmap_2d so by setting this parameter to something below its - obstacle thresh, we can get obstacle padding that is less harsh and more - reasonable. This will make the planner more likely to choose to go through - more narrow areas such as doorways. - -`~/SBPLLatticePlanner/publish_footprint_path` (`bool`, default: true) - -- Whether or not to publish the `footprint_markers` topic. - -`~/SBPLLatticePlanner/visualizer_skip_poses` (`int`, default: 5) - -- Only publish every nth pose on the `footprint_markers` topic. - -`~/SBPLLatticePlanner/allow_unknown` (`bool`, default: true) - -- Whether or not to allow planning through unknown space. - - -## Customizing your Motion Primitives - -Please refer to the [SBPL documentation](https://wiki.ros.org/sbpl) for -pre-made motion primitives for the PR2 (and other robots) as well as -instructions on how to generate your own custom motions. - - -## Choosing good costmap_2d parameters - -If the costmap_2d parameters are set incorrectly, sbpl_lattice_planner will -ignore the robot's footprint and incorrectly plan paths that lead into -obstacles. For this reason, the following two parameters of the global -costmap_2d have to be fine-tuned to your robot's footprint: - -* **inflation_radius:** Maximum distance from an obstacle at which costs are - incurred for planning paths. Must be greater or equal to the robot's - circumscribed radius. -* **cost_scaling_factor:** Exponential rate at which the obstacle cost drops - off (default: 10). Must be chosen so that the cost value is greater than 0 at - the robot's circumscribed radius. - -The most important of these two parameters is inflation_radius. If this -parameter is less than the robot's circumscribed radius, SBPL will skip the -detailed footprint check and plan into obstacles. If cost_scaling_factor is too -large for the robot footprint (i.e., the inflation around the obstacles is too -small), SBPL will always perform a detailed footprint check, even for poses -that are far away from obstacles. This will incur a performance penalty, but no -infeasible paths. - -The best way to fine-tune these parameters is by using `rqt_reconfigure` and -observing the resulting costmap with inflated obstacles in RViz. First you -should set inflation_radius to something bigger than the circumscribed radius. -This parameter is a cutoff, so if the costmap value has not yet reached 0 at -this distance, it is clamped to 0. This parameter isn't that important as long -as it is greater than the robot's circumscribed radius. The parameter -cost_scaling_factor is an exponential dropoff, so lowering it increases the -inflation radius. Lower it until the inflation radius is at least the robot's -circumscribed radius. Once you have found good parameters, put them into your -move_base launch file. Also see: https://wiki.ros.org/costmap_2d#Inflation . - -For more details, see [issue #33](https://github.com/ros-planning/navigation_experimental/issues/33). +`inflation_radius` của global costmap phải ≥ bán kính ngoại tiếp của robot, +nếu không SBPL bỏ qua footprint check chi tiết và plan đâm vào vật cản. +`cost_scaling_factor` phải đủ nhỏ để cost tại bán kính ngoại tiếp > 0 — quá +lớn thì mọi pose đều phải footprint check chi tiết, chậm nhưng không sai. diff --git a/include/sbpl_lattice_planner/sbpl_lattice_planner.h b/include/sbpl_lattice_planner/sbpl_lattice_planner.h index 5c76124..82e5dd7 100644 --- a/include/sbpl_lattice_planner/sbpl_lattice_planner.h +++ b/include/sbpl_lattice_planner/sbpl_lattice_planner.h @@ -54,12 +54,27 @@ public: * @param plan The plan... filled by the planner * @return True if a valid plan was found, false otherwise */ - virtual bool makePlan(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, + virtual bool makePlan(const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, std::vector& plan); + /** + * @brief Nạp lưới NGOÀI thay cho lưới sống của costmap trong các lần makePlan kế tiếp. + * + * Dùng cho detour trên lưới gộp (global nền + local đè): bên gọi snapshot hai costmap dưới mutex + * rồi đưa bản chụp vào đây — makePlan đọc bản chụp, KHÔNG giữ mutex costmap nào trong lúc search. + * + * Ràng buộc: lưới ngoài phải CÙNG kích thước/resolution với costmap đã initialize() (bản chụp + * gộp lấy global làm nền nên tự thoả). Footprint/inflation/frame vẫn đọc từ costmap sống. + * Con trỏ non-owning, bên gọi giữ buffer sống qua lời gọi makePlan. `nullptr` = quay lại lưới sống. + * + * Không thuộc interface `BaseGlobalPlanner` — bên ngoài .so gọi qua alias Boost.DLL + * `SBPLLatticePlannerExternalGrid` (xem cuối sbpl_lattice_planner.cpp). + */ + void setExternalGrid(const robot_costmap_2d::Costmap2D* grid); + virtual ~SBPLLatticePlanner(){}; - + static robot_nav_core::BaseGlobalPlanner::Ptr create(); private: @@ -110,8 +125,12 @@ private: * plan lại một lần. Không ra nghiệm thì retry với heading thật. */ bool free_start_heading_; + /// @return lưới đang có hiệu lực: lưới ngoài nếu được nạp, không thì lưới sống của costmap. + const robot_costmap_2d::Costmap2D* activeGrid() const; + std::string name_; robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< manages the cost map for us */ + const robot_costmap_2d::Costmap2D* external_grid_; /**< non-owning; NULL = dùng lưới sống */ std::vector footprint_; std::vector footprint_prev_; unsigned int current_env_width_; diff --git a/src/sbpl_lattice_planner.cpp b/src/sbpl_lattice_planner.cpp index 9dc11d8..1b908d7 100644 --- a/src/sbpl_lattice_planner.cpp +++ b/src/sbpl_lattice_planner.cpp @@ -82,14 +82,22 @@ class LatticeSCQ : public StateChangeQuery{ }; SBPLLatticePlanner::SBPLLatticePlanner() - : initialized_(false), costmap_robot_(NULL){ + : initialized_(false), costmap_robot_(NULL), external_grid_(NULL){ } -SBPLLatticePlanner::SBPLLatticePlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) - : initialized_(false), costmap_robot_(NULL) +SBPLLatticePlanner::SBPLLatticePlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) + : initialized_(false), costmap_robot_(NULL), external_grid_(NULL) { initialize(name, costmap_robot); } + +void SBPLLatticePlanner::setExternalGrid(const robot_costmap_2d::Costmap2D* grid){ + external_grid_ = grid; +} + +const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{ + return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap(); +} bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot){ if(!initialized_){ @@ -194,7 +202,7 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 bool ret; try{ - robot::log_warning("DEBUG 2000"); + // robot::log_warning("DEBUG 2000"); ret = env_->InitializeEnv(costmap_robot_->getCostmap()->getSizeInCellsX(), // width costmap_robot_->getCostmap()->getSizeInCellsY(), // height 0, // mapdata @@ -207,7 +215,7 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 ret = true; current_env_width_ = costmap_robot_->getCostmap()->getSizeInCellsX(); current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY(); - robot::log_warning("DEBUG 3000"); + // robot::log_warning("DEBUG 3000"); } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception: %s", e->what()); @@ -291,12 +299,16 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, return false; } + // Lưới cell đang có hiệu lực: bản chụp ngoài (detour trên lưới gộp) hoặc lưới sống. Footprint, + // inflation và frame vẫn thuộc costmap sống — lưới ngoài bắt buộc cùng kích thước với nó. + const robot_costmap_2d::Costmap2D* grid = activeGrid(); + bool do_init = false; - if (current_env_width_ != costmap_robot_->getCostmap()->getSizeInCellsX() || - current_env_height_ != costmap_robot_->getCostmap()->getSizeInCellsY()) { + if (current_env_width_ != grid->getSizeInCellsX() || + current_env_height_ != grid->getSizeInCellsY()) { robot::log_info("Costmap dimensions have changed from (%d x %d) to (%d x %d), reinitializing sbpl_lattice_planner.", current_env_width_, current_env_height_, - costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY()); + grid->getSizeInCellsX(), grid->getSizeInCellsY()); do_init = true; } else if (footprint_ != costmap_robot_->getRobotFootprint()) { @@ -314,6 +326,19 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, planner_ = NULL; delete env_; env_ = NULL; + // initialize() dựng env theo LƯỚI SỐNG — lưới ngoài lệch kích thước với nó sẽ churn re-init + // mỗi lượt. Contract của setExternalGrid cấm lệch, nhưng phát hiện được thì nói thẳng. + if (external_grid_ != NULL && + (external_grid_->getSizeInCellsX() != grid->getSizeInCellsX() || + external_grid_->getSizeInCellsY() != grid->getSizeInCellsY())) { + robot::log_error("[sbpl_lattice_planner] external grid (%d x %d) does not match the live " + "costmap (%d x %d); dropping the external grid.", + external_grid_->getSizeInCellsX(), external_grid_->getSizeInCellsY(), + grid->getSizeInCellsX(), + grid->getSizeInCellsY()); + external_grid_ = NULL; + grid = activeGrid(); + } initialize(name_, costmap_robot_); } @@ -336,14 +361,14 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, const double dx = goal.pose.position.x - start.pose.position.x; const double dy = goal.pose.position.y - start.pose.position.y; // Goal quá gần (< ~2 cell): hướng tới goal hết ý nghĩa, dùng luôn heading của goal. - theta_start = (std::hypot(dx, dy) > 2.0 * costmap_robot_->getCostmap()->getResolution()) + theta_start = (std::hypot(dx, dy) > 2.0 * grid->getResolution()) ? atan2(dy, dx) : theta_goal; start_heading_overridden = true; } try{ - int ret = env_->SetStart(start.pose.position.x - costmap_robot_->getCostmap()->getOriginX(), start.pose.position.y - costmap_robot_->getCostmap()->getOriginY(), theta_start); + int ret = env_->SetStart(start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->getOriginY(), theta_start); if(ret < 0 || planner_->set_start(ret) == 0){ robot::log_error("ERROR: failed to set start state\n"); return false; @@ -355,7 +380,7 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, } try{ - int ret = env_->SetGoal(goal.pose.position.x - costmap_robot_->getCostmap()->getOriginX(), goal.pose.position.y - costmap_robot_->getCostmap()->getOriginY(), theta_goal); + int ret = env_->SetGoal(goal.pose.position.x - grid->getOriginX(), goal.pose.position.y - grid->getOriginY(), theta_goal); if(ret < 0 || planner_->set_goal(ret) == 0){ robot::log_error("ERROR: failed to set goal state\n"); return false; @@ -371,11 +396,11 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, int allCount = 0; vector changedcellsV; - for(unsigned int ix = 0; ix < costmap_robot_->getCostmap()->getSizeInCellsX(); ix++) { - for(unsigned int iy = 0; iy < costmap_robot_->getCostmap()->getSizeInCellsY(); iy++) { + for(unsigned int ix = 0; ix < grid->getSizeInCellsX(); ix++) { + for(unsigned int iy = 0; iy < grid->getSizeInCellsY(); iy++) { unsigned char oldCost = env_->GetMapCost(ix,iy); - unsigned char newCost = costMapCostToSBPLCost(costmap_robot_->getCostmap()->getCost(ix,iy)); + unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy)); if(oldCost == newCost) continue; @@ -392,7 +417,7 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, (newCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && newCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { onOffCount++; } - env_->UpdateCost(ix, iy, costMapCostToSBPLCost(costmap_robot_->getCostmap()->getCost(ix,iy))); + env_->UpdateCost(ix, iy, costMapCostToSBPLCost(grid->getCost(ix,iy))); nav2dcell_t nav2dcell; nav2dcell.x = ix; @@ -431,8 +456,8 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, // ngay tại cell xuất phát) — thử lại MỘT lần với heading thật trước khi bỏ cuộc. robot::log_warning("[sbpl_lattice_planner] no solution with free start heading, " "retrying with actual robot heading"); - int sid = env_->SetStart(start.pose.position.x - costmap_robot_->getCostmap()->getOriginX(), - start.pose.position.y - costmap_robot_->getCostmap()->getOriginY(), + int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), + start.pose.position.y - grid->getOriginY(), theta_start_actual); if(sid >= 0 && planner_->set_start(sid) != 0){ ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost); @@ -510,8 +535,8 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, robot::log_debug("[sbpl_lattice_planner] initial segment curved (dev %.2f rad), " "replanning with start heading realigned to %.2f", max_dev, theta_realign); try{ - int sid = env_->SetStart(start.pose.position.x - costmap_robot_->getCostmap()->getOriginX(), - start.pose.position.y - costmap_robot_->getCostmap()->getOriginY(), + int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), + start.pose.position.y - grid->getOriginY(), theta_realign); vector realigned_ids; int realigned_cost; @@ -534,8 +559,8 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, // if the plan has zero points, add a single point to make move_base happy if( sbpl_path.size() == 0 ) { EnvNAVXYTHETALAT3Dpt_t s( - start.pose.position.x - costmap_robot_->getCostmap()->getOriginX(), - start.pose.position.y - costmap_robot_->getCostmap()->getOriginY(), + start.pose.position.x - grid->getOriginX(), + start.pose.position.y - grid->getOriginY(), theta_start); // sbpl_path.push_back(s); } @@ -560,8 +585,8 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, pose.header.stamp = plan_time; pose.header.frame_id = costmap_robot_->getGlobalFrameID(); - pose.pose.position.x = sbpl_path[i].x + costmap_robot_->getCostmap()->getOriginX(); - pose.pose.position.y = sbpl_path[i].y + costmap_robot_->getCostmap()->getOriginY(); + pose.pose.position.x = sbpl_path[i].x + grid->getOriginX(); + pose.pose.position.y = sbpl_path[i].y + grid->getOriginY(); pose.pose.position.z = start.pose.position.z; // tf2::Quaternion temp; @@ -641,8 +666,23 @@ robot_nav_core::BaseGlobalPlanner::Ptr SBPLLatticePlanner::create() { return std::make_shared(); } +// Cầu capability cho bên NGOÀI .so: caller chỉ giữ BaseGlobalPlanner* (nạp qua alias factory), +// còn dynamic_cast xuống lớp cụ thể chạy Ở TRONG .so này — typeinfo nhất quán, không phụ thuộc +// RTLD_LOCAL/GLOBAL của boost::dll. Planner không phải instance của lớp này thì bỏ qua kèm log. +void setExternalGridOn(robot_nav_core::BaseGlobalPlanner* planner, + const robot_costmap_2d::Costmap2D* grid) { + SBPLLatticePlanner* self = dynamic_cast(planner); + if (self != NULL) { + self->setExternalGrid(grid); + } else { + robot::log_error("[sbpl_lattice_planner] setExternalGridOn: planner is not an " + "SBPLLatticePlanner instance; external grid ignored."); + } +} }; // Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias) -BOOST_DLL_ALIAS(sbpl_lattice_planner::SBPLLatticePlanner::create, SBPLLatticePlanner) +BOOST_DLL_ALIAS(sbpl_lattice_planner::SBPLLatticePlanner::create, SBPLLatticePlanner) +// Capability lưới ngoài: tra theo tên "ExternalGrid" (xem sbpl_recovery). +BOOST_DLL_ALIAS(sbpl_lattice_planner::setExternalGridOn, SBPLLatticePlannerExternalGrid)