Files
sbpl_lattice_planner/include/sbpl_lattice_planner/sbpl_lattice_planner.h
duongtd 3fff3b15cd feat: dai hanh lang theo route graph (Voronoi) cho goal xa, anytime ARA* dung ReplanParams, smoother path
- Anytime dung nghia (pha 0): replan() qua ReplanParams thay vi replan(double) - nghiem dau o
  initial_epsilon, ha dan eps_step toi final_epsilon trong repair_time; return_first_solution
  de bench. eps=1.0 (A* thuan) tren map rong gan chac chan het gio.
- Route graph corridor: nhan robot_sensor_ports::SensorConsumer, doc RouteGraph tu kho (host
  bien dich Voronoi tu map, day qua addRouteGraph), doi chieu map_hash voi static layer song.
  Goal >= min_range_m + co graph -> gan start/goal (BFS), Dijkstra ra tuyen, dong dau mask quanh
  tuyen; o NGOAI mask nhan cost inscribed (hard) hoac bi phat (soft) - search + heuristic 2D chi
  no trong dai (~3% map thay 100% tren sehc). Khong graph/lech/gan that bai = chay full nhu cu,
  log [debug/corridor] noi ly do; "route graph REJECTED" la LOI khong tat duoc. Nguong nghen ->
  noi rong (widen_factor, toi da max_widen) -> bo dai chay full voi thoi gian con lai.
- Path smoother (distance_map.h/.cpp, path_smoother.h/.cpp): keo day doan lattice di thang duoc
  tren costmap SONG (distance-transform giu khoang cach voi LETHAL, khong chi nhin cost), bo goc
  bang cung ban kinh co dinh khop bo mprim - giu nguyen doan lui (cusp). Do tren sehc: path
  lattice dai hon toi uu 2D 12%, 11 lan doi chieu re; smoother giam duoc phan lon.
- Log "metrics: ... detour= turn_deg= arcs= wiggles= plan_ms= corridor= corridor_ms= smooth=
  raw_m= smooth_ms= anchors= fillets=" moi lan plan thanh cong - so dai on/off, hard/soft, eps
  qua script tools/eval_plan_bag.py.
- Test moi: test/path_smoother_test.cpp (path_smoother la hinh hoc thuan, khong SBPL/costmap,
  chay duoc moi noi co gtest). CMakeLists them target catkin_add_gtest + nhanh standalone.
- Phu thuoc build moi: robot_sensor_ports, route_graph (repo rieng, da co remote).
- YAML: schema initial_epsilon/final_epsilon/eps_step/repair_time/return_first_solution,
  khoi voronoi_corridor (12 khoa) va smooth_path (7 khoa) trong cfg/sbpl_global_params.yaml
  (dong bo tu pnkx_nav_core c52cbe5 / move_base2 f4f9965).
2026-09-22 15:51:26 +07:00

303 lines
16 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#ifndef SBPL_LATTICE_PLANNER_H
#define SBPL_LATTICE_PLANNER_H
#include <atomic>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// ROBOT
#include <robot/robot.h>
#include <robot_geometry_msgs/PoseStamped.h>
#include <robot_visualization_msgs/Marker.h>
// Costmap used for the map representation
#include <robot_costmap_2d/costmap_2d_robot.h>
// sbpl headers
#include <sbpl/headers.h>
// global representation
#include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/preemptable.h>
// route graph corridor (2026-09-21): graph injected by the host through the shared sensor store
#include <robot_sensor_ports/sensor_consumer.h>
#include <robot_sensor_ports/sensor_reader.h>
#include <route_graph/corridor.h>
#include <route_graph/graph.h>
#include "sbpl_lattice_planner/path_smoother.h"
namespace sbpl_lattice_planner{
class SBPLLatticePlanner : public robot_nav_core::BaseGlobalPlanner,
public robot_nav_core::Preemptable,
public robot_sensor_ports::SensorConsumer {
public:
/**
* @brief Default constructor for the NavFnROBOT object
*/
SBPLLatticePlanner();
/**
* @brief Constructor for the SBPLLatticePlanner object
* @param name The name of this planner
* @param costmap_robot A pointer to the ROBOT wrapper of the costmap to use
*/
SBPLLatticePlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot);
/**
* @brief Initialization function for the SBPLLatticePlanner object
* @param name The name of this planner
* @param costmap_robot A pointer to the ROBOT wrapper of the costmap to use
*/
virtual bool initialize(std::string name,
robot_costmap_2d::Costmap2DROBOT* costmap_robot);
/**
* @brief Given a goal pose in the world, compute a plan
* @param start The start pose
* @param goal The goal pose
* @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,
std::vector<robot_geometry_msgs::PoseStamped>& plan);
/**
* @brief Cắt lượt makePlan đang chạy (robot_nav_core::Preemptable, 2026-09-11).
*
* Gọi từ thread KHÁC thread đang ở trong makePlan: một atomic store, không lock. ARA* thấy cờ ở
* vòng expand kế và trả "không có nghiệm"; các lượt replan nội bộ (retry heading thật, căn lại
* heading) không được khởi động nữa. makePlan trả false. Cờ được xoá ở đầu mỗi makePlan.
*
* Chỉ có hiệu lực khi libsbpl đang nạp có abort flag (SBPL_HAS_ABORT_FLAG + probe
* sbpl_abort_flag_abi_version lúc initialize); không có thì preempt() chỉ đặt cờ cho phần kiểm
* giữa các lượt replan, còn một lượt ARA* đang chạy vẫn đi tới hết allocated_time.
*/
void preempt() override;
/**
* @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);
/**
* @brief Nhận cổng đọc kho cảm biến dùng chung (robot_sensor_ports::SensorConsumer). PlannerRunner
* gọi TRƯỚC initialize(); null = không có kho -> corridor không bao giờ bật.
*/
void setSensorReader(const robot_sensor_ports::SensorReader* reader) override;
virtual ~SBPLLatticePlanner(){};
static robot_nav_core::BaseGlobalPlanner::Ptr create();
private:
unsigned char costMapCostToSBPLCost(unsigned char newcost);
unsigned char computeCircumscribedCost();
static void transformFootprintToEdges(const robot_geometry_msgs::Pose& robot_pose,
const std::vector<robot_geometry_msgs::Point>& footprint,
std::vector<robot_geometry_msgs::Point>& out_footprint);
void getFootprintList(const std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path, const std::string& path_frame_id,
robot_visualization_msgs::Marker& ma);
bool initialized_;
SBPLPlanner* planner_;
std::atomic<bool> preempt_{false}; ///< Cờ cắt lượt makePlan đang chạy (Preemptable).
bool sbpl_abort_supported_ = false; ///< libsbpl đang nạp hiểu set_abort_flag (probe lúc initialize).
EnvironmentNAVXYTHETALAT* env_;
std::string planner_type_; /**< sbpl method to use for planning. choices are ARAPlanner and ADPlanner */
double allocated_time_; /**< amount of time allowed for search */
double initial_epsilon_; /**< initial epsilon for beginning the anytime search */
// ---- Anytime đúng nghĩa (pha 0, 2026-09-21): replan() qua ReplanParams thay vì replan(double) --
// replan(double) cũ = eps đặt một lần, chạy tới eps=1.0 hoặc hết giờ: eps 1.0 là A* thuần, goal xa
// nở hàng triệu state. Với ReplanParams: nghiệm đầu ở initial_epsilon (nhanh), rồi hạ dần eps_step
// tới final_epsilon chừng nào tổng thời gian còn < repair_time. Lưu ý ARA* đo bằng clock() = CPU
// time CẢ tiến trình, nên ngân sách tính theo wall ngắn hơn khi thread khác bận.
double final_epsilon_; /**< eps dừng hạ; 1.0 = tối ưu, >1 = chấp nhận sub-optimal chừng đó */
double eps_step_; /**< mỗi vòng ARA* hạ eps đi ngần này */
double repair_time_; /**< [s] sau khi có nghiệm đầu, tổng thời gian tối đa còn được hạ eps; <= 0 = tới hết ngân sách */
bool return_first_solution_; /**< true = trả ngay nghiệm đầu (eps = initial), không hạ eps */
/// @brief Tham số cho một lượt replan với ngân sách @p budget_s, từ 4 khoá trên.
ReplanParams makeReplanParams(double budget_s) const;
std::string environment_type_; /** what type of environment in which to plan. choices are 2D and XYThetaLattice. */
std::string cost_map_topic_; /** what topic is being used for the costmap topic */
bool forward_search_; /** whether to use forward or backward search */
std::string primitive_filename_; /** where to find the motion primitives for the current robot */
int force_scratch_limit_; /** the number of cells that have to be changed in the costmap to force the planner to plan from scratch even if its an incremental planner */
unsigned char lethal_obstacle_;
unsigned char inscribed_inflated_obstacle_;
unsigned char circumscribed_cost_;
unsigned char sbpl_cost_multiplier_;
bool publish_footprint_path_;
int visualizer_skip_poses_;
bool allow_unknown_;
/** Bỏ ràng buộc heading tại điểm xuất phát, đả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). Dùng khi local
* planner tự quay tại chỗ về hướng path trước khi bám (turn_around_priority) — 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 lúc goal nằm phía sau robot. Cơ chế: plan lần 1 với heading seed hướng tới
* goal; nếu đoạn đầu vẫn cong thì căn heading theo đoạn thẳng đầu tiên của path và
* plan lại một lần. Không ra nghiệm thì retry với heading thật. */
bool free_start_heading_;
// ---- Chẩn đoán lập plan (2026-09-18) ----------------------------------------------------------
// Một lượt makePlan fail phải tự nói được: goal/start đứng trên ô gì, có đường 2D không, search
// dừng vì cạn hay hết giờ. Dòng LỖI (goal bị từ chối, NO SOLUTION) không nằm sau công tắc nào.
/// Nhóm log `debug_plan`: audit goal/start khi hợp lệ, h 2D khi hữu hạn, thống kê `solved:`.
bool debug_plan_;
/// [ô] Bán kính cửa sổ lưới in ASCII quanh goal và start khi search fail. 0 = tắt.
int debug_grid_window_;
/// @brief Kết quả soi một pose trên lưới đang có hiệu lực.
struct PoseAudit
{
bool in_map = false; ///< Ô tâm nằm trong lưới.
unsigned int mx = 0, my = 0; ///< Chỉ số ô tâm (chỉ có nghĩa khi in_map).
unsigned char cost = 0; ///< Cost costmap tại ô tâm (0..255).
bool footprint_ok = false; ///< Footprint tại (x, y, theta) không đè lethal / mép lưới.
};
/// @return tên lớp cost để in log: FREE / INFLATED / INSCRIBED / LETHAL / UNKNOWN.
static const char* costClassName(unsigned char cost);
/// @brief Soi pose: ô tâm, cost, footprint. Không đổi trạng thái env.
PoseAudit auditPose(const robot_costmap_2d::Costmap2D* grid, double wx, double wy,
double theta) const;
/// @brief In cửa sổ ASCII (2r+1)^2 ô quanh (cx, cy); đánh dấu S (start) và G (goal).
void logGridWindow(const robot_costmap_2d::Costmap2D* grid, int radius, unsigned int cx,
unsigned int cy, unsigned int sx, unsigned int sy, unsigned int gx,
unsigned int gy, const char* label) const;
/// @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;
// ---- Route graph corridor (2026-09-21) --------------------------------------------------------
// Graph tuyến (Voronoi) do host biên dịch sẵn từ map và tiêm vào kho `robot_sensor_ports`. Planner
// KHÔNG dựng graph; chỉ nhận, đối chiếu với static layer (kích thước + hash mask vật cản) rồi dùng
// để khoanh vùng tìm kiếm cho goal xa: ô ngoài dải quanh tuyến nhận cost INSCRIBED (không lethal),
// search + heuristic 2D của SBPL tự giới hạn trong dải. Không graph / lệch map = chạy full như cũ.
/// Config khối `voronoi_corridor` trong YAML. Đơn vị mét, quy ra ô lúc initialize().
struct CorridorConfig
{
bool enabled = false; ///< Bật/tắt toàn bộ cơ chế.
std::string route_graph_topic = "/route_graph"; ///< Khoá kho, trùng sensor_store_params.yaml.
std::string static_layer_name; ///< Rỗng = StaticLayer đầu tiên theo kiểu; đặt tên khi có nhiều.
double min_range_m = 15.0; ///< [m] Goal gần hơn -> không dùng dải.
double half_width_m = 1.5; ///< [m] Nửa bề rộng tối thiểu của dải.
double clearance_scale = 0.8; ///< Nửa bề rộng = max(min, scale × clearance tuyến).
double max_half_width_m = 6.0; ///< [m] Trần nửa bề rộng.
double attach_max_radius_m = 10.0; ///< [m] Bán kính BFS gắn start/goal vào graph.
double route_min_clearance_m = -1.0; ///< [m] Edge hẹp hơn không đi; < 0 = bán kính nội tiếp footprint.
std::string outside_mode = "hard"; ///< hard: ngoài dải = inscribed (chặn); soft: chỉ phạt cost.
int soft_penalty_cost = 200; ///< [0..252, thang costmap] cost ô ngoài dải khi soft.
double widen_factor = 2.0; ///< Nhân bề rộng mỗi lần nới khi search cạn.
int max_widen = 1; ///< Số lần nới tối đa trước khi bỏ dải.
double budget_fraction = 0.6; ///< Phần allocated_time cấp cho pha có dải.
bool fallback_full_search = true; ///< false CHỈ để đo: cạn trong dải thì trả fail luôn.
bool debug_corridor = true; ///< Nhóm log [debug/corridor].
};
/// Kết quả một lần dựng dải, để log và để bench đọc.
struct CorridorStats
{
bool active = false;
bool graph_from_store = false;
bool attach_start_ok = false, attach_goal_ok = false;
std::size_t route_cells = 0;
double route_length_m = 0.0;
double route_min_clearance_m = 0.0; ///< Ngưỡng đã dùng để lọc edge hẹp.
std::size_t mask_cells = 0;
int widen_level = 0;
double build_ms = 0.0;
};
/**
* @brief Đọc kho: có bản RouteGraph mới thì đối chiếu với static layer sống (version, kích thước,
* resolution, origin, map_hash theo luật trong `source`) và nhận nếu khớp. Gọi ở cuối
* initialize() và đầu mỗi makePlan; không có bản mới thì rẻ (một lần so cursor).
* Lệch -> log LỖI (không tắt được) một lần cho bản đó, corridor tắt.
*/
void tryAdoptRouteGraph();
/// @return static layer của global costmap (lớp nguồn của graph), null nếu không có.
const robot_costmap_2d::Costmap2D* staticLayerGrid() const;
/**
* @brief Dựng dải cho lượt này: gắn start/goal vào graph, Dijkstra, đóng dấu mask với nửa bề rộng
* `half_width_m × widen_factor^widen_level`. Ghi vào corridor_mask_ (rỗng = không dải).
* @return true khi có dải.
*/
bool buildCorridor(const robot_costmap_2d::Costmap2D* grid, unsigned int sx, unsigned int sy,
unsigned int gx, unsigned int gy, int widen_level, CorridorStats& stats);
CorridorConfig corridor_cfg_;
const robot_sensor_ports::SensorReader* sensors_ = nullptr; ///< Non-owning, có thể null.
uint64_t route_graph_cursor_ = 0; ///< Cursor kho: chỉ xử lý bản mới hơn.
route_graph::Graph route_graph_; ///< Graph đã nhận; rỗng = chưa có / bị từ chối.
bool route_graph_ready_ = false;
std::vector<uint8_t> corridor_mask_; ///< 1 = trong dải; rỗng = không dải cho lượt này.
unsigned char masked_cost_ = 0; ///< Cost SBPL gán cho ô ngoài dải (hard: inscribed; soft: phạt).
bool corridor_hard_ = true; ///< outside_mode == hard.
CorridorStats last_corridor_;
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<robot_geometry_msgs::Point> footprint_;
std::vector<robot_geometry_msgs::Point> footprint_prev_;
unsigned int current_env_width_;
unsigned int current_env_height_;
/**
* @brief Post-search smoothing (khối YAML `smooth_path`): kéo dây (line-of-sight) rồi bo góc bằng
* cung R cố định trên costmap SỐNG, luật va chạm y hệt lattice (tâm < inscribed, footprint
* khi ô >= circumscribed). Sửa "đi thẳng được mà ngoằn ngoèo" do eps>1, dải Voronoi và lưới
* 16 hướng để lại. Path lùi (cusp) không được làm mượt.
*/
SmootherConfig smoother_cfg_;
int smoother_max_cell_cost_ = 252; /**< [thang costmap] ô tâm có cost cao hơn = chặn với smoother */
double smoother_min_clearance_m_ = -1.0; /**< [m] tâm phải cách ô LETHAL ít nhất ngần này (EDT); <0 = bán kính ngoại tiếp */
/// Chạy smoother trên @p sbpl_path (toạ độ tương đối origin lưới); trả false = giữ path lattice.
bool smoothLatticePath(const robot_costmap_2d::Costmap2D* grid,
std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path, SmootherStats* stats) const;
};
};
#endif