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).
This commit is contained in:
2026-09-22 15:51:26 +07:00
parent 34c74cb541
commit 3fff3b15cd
13 changed files with 2510 additions and 100 deletions

View File

@@ -0,0 +1,34 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Exact squared Euclidean distance transform on a binary grid (Felzenszwalb & Huttenlocher,
* separable lower-envelope passes, O(w*h)). Used by the path smoother to answer "is the whole
* footprint clear here?" for free with a single lookup wherever the nearest obstacle is farther
* than the circumscribed radius, instead of rasterising the footprint at every sample.
*
* Author: DuongTD
*********************************************************************/
#ifndef SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_
#define SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_
#include <cstdint>
#include <vector>
namespace sbpl_lattice_planner
{
/**
* @brief Squared distance [cells^2] from every cell to the nearest cell with obstacle != 0.
* @param obstacle w*h, row-major (index = y*w + x), non-zero = obstacle.
* @param dist2 resized to w*h; a grid without obstacles gets kFarAway everywhere.
*/
void squaredDistanceTransform(const std::vector<uint8_t>& obstacle, int w, int h,
std::vector<float>& dist2);
/// Value stored where no obstacle exists within range (bigger than any real w*h distance).
constexpr float kFarAway = 1.0e12f;
} // namespace sbpl_lattice_planner
#endif // SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_

View File

@@ -0,0 +1,127 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Shortcut + fillet smoother for lattice paths. Pure geometry: collision queries come in as
* callbacks so the class knows nothing about costmaps and can be unit-tested on a synthetic grid.
*
* Author: DuongTD
*********************************************************************/
#ifndef SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_
#define SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_
#include <cstddef>
#include <functional>
#include <vector>
namespace sbpl_lattice_planner
{
/// Pose on the path, world frame, [m] and [rad].
struct SmoothPose
{
double x = 0.0;
double y = 0.0;
double theta = 0.0;
};
/**
* @brief What a costmap cell means for the robot centre. Mirrors the lattice environment's own
* rule (EnvironmentNAVXYTHETALAT::GetActionCost): the centre may never stand on a cell at
* or above the inscribed cost; on cells at or above the "possibly circumscribed" cost the
* whole footprint has to be checked; below that the footprint is known to be clear.
*/
enum class CellClass
{
kBlocked, ///< centre may not be here (>= inscribed, lethal, unknown when not allowed, off-map)
kFree, ///< centre ok and footprint guaranteed clear
kNearObstacle ///< centre ok but footprint must be checked at this pose
};
struct SmootherConfig
{
bool enabled = false;
double max_shortcut_m = 80.0; ///< [m] longest straight segment tried (bounds the work)
double fillet_radius_m = 1.06; ///< [m] arc radius at corners; 0 = every corner sharp
double min_fillet_radius_m = 0.8; ///< [m] corner gets a sharp turn below this radius (1/kappa the base can hold at speed)
double sample_step_m = 0.05; ///< [m] output pose spacing
double check_step_m = 0.025; ///< [m] collision sampling along segments and arcs
double min_corner_deg = 3.0; ///< [deg] corners flatter than this get no fillet
/// [deg] Where a shortcut meets a stretch of untouched lattice path (no room for a fillet), the
/// chord may differ from the lattice heading by at most this much; a farther but misaligned
/// end point is skipped in favour of a nearer aligned one. 0 = off (farthest visible wins).
double max_junction_deg = 20.0;
};
struct SmootherStats
{
std::size_t in_pts = 0;
std::size_t out_pts = 0;
int anchors = 0; ///< polyline vertices after string-pulling (incl. both ends)
int fillets = 0; ///< corners that received an arc
int fillets_rejected = 0; ///< corners kept sharp: arc collided or segments too short
double in_len_m = 0.0;
double out_len_m = 0.0;
};
/**
* @class PathSmoother
* @brief Greedy line-of-sight shortcutting ("string pulling") of a dense path against the live
* costmap, then tangent-continuous fillet arcs at the remaining corners.
*
* Why: the lattice search returns the cheapest chain of motion primitives inside whatever it was
* allowed to explore (an eps>1 anytime bound, a Voronoi corridor, 16 discrete headings). All three
* leave visible detours where the floor is open — a 12 % longer path with 11 wiggles on a 100 m
* goal in the 2026-09-22 measurements. The smoother keeps the search's topology (which gap, which
* side of an island) and straightens everything the footprint can actually cross.
*
* Contract:
* - Output starts at the input's first point with the heading of the first straight run, ends
* at the input's last point with the input's final heading (goal yaw).
* - Every sampled pose is collision-free under the same rule as the lattice (see CellClass).
* - Sharp corners keep a duplicate position with two headings — the local planner turns in
* place there, exactly as it does for lattice turn-in-place primitives.
* - Paths containing reverse motion are returned untouched (false): shortcutting across a cusp
* would silently turn a planned reverse into a forward drive.
*/
class PathSmoother
{
public:
using CellQuery = std::function<CellClass(double x, double y)>;
using PoseQuery = std::function<bool(double x, double y, double theta)>; ///< footprint clear?
PathSmoother(const SmootherConfig& cfg, CellQuery cell, PoseQuery pose);
/**
* @brief Smooth @p in into @p out. Returns false (and leaves @p out empty) when the input is
* too short, contains reverse motion, or the first segment could not even be verified —
* the caller keeps the lattice path in that case.
*/
bool smooth(const std::vector<SmoothPose>& in, std::vector<SmoothPose>& out,
SmootherStats* stats = nullptr) const;
/// Straight segment a->b (world) free for the footprint? Exposed for tests.
bool segmentFree(const SmoothPose& a, const SmoothPose& b) const;
private:
/// Pose free for the footprint under the lattice rule (centre class, then footprint if needed).
bool poseFree(double x, double y, double theta) const;
/// Arc from @p from, centre @p c, radius @p r, sweeping @p sweep [rad] (signed). Samples at
/// check_step_m. When @p out is given the samples (excluding the last) are appended at
/// sample_step_m.
bool arcFree(double cx, double cy, double r, double a0, double sweep) const;
void appendArc(double cx, double cy, double r, double a0, double sweep,
std::vector<SmoothPose>& out) const;
void appendSegment(const SmoothPose& a, const SmoothPose& b, std::vector<SmoothPose>& out) const;
SmootherConfig cfg_;
CellQuery cell_;
PoseQuery pose_;
};
/// Sum of segment lengths [m].
double pathLength(const std::vector<SmoothPose>& p);
} // namespace sbpl_lattice_planner
#endif // SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_

View File

@@ -2,7 +2,9 @@
#define SBPL_LATTICE_PLANNER_H
#include <atomic>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
@@ -22,10 +24,19 @@ using namespace std;
#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_nav_core::Preemptable,
public robot_sensor_ports::SensorConsumer {
public:
/**
@@ -89,6 +100,12 @@ public:
*/
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();
@@ -117,6 +134,17 @@ private:
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 */
@@ -177,6 +205,76 @@ private:
/// @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 */
@@ -184,6 +282,19 @@ private:
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;
};
};