feat: chan doan makePlan fail - audit goal/start, kiem tra 2D reachability, phan biet TIMEOUT/EXHAUSTED

Truoc day fail chi in "Solution not found" - khong biet goal bi chan, khong co duong 2D,
hay search chay het gio. Them audit goal (reject truoc khi search neu cell >= INSCRIBED
hoac footprint dinh vat can), audit start, kiem tra heuristic 2D truoc khi chay ARA* (h=INF
la khong co duong ke ca cho diem), va dong log NO SOLUTION/solved: bao ca ly do
(TIMEOUT|EXHAUSTED), so lan expand, h_2d, phase. Them debug_plan/debug_grid_window de bat/tat
nhom log info; dong LOI (goal REJECTED, 2D unreachable, NO SOLUTION) khong gan cong tac.
This commit is contained in:
2026-09-18 13:32:33 +07:00
parent 7456e99372
commit 34c74cb541
3 changed files with 346 additions and 37 deletions

View File

@@ -10,6 +10,30 @@ SBPLLatticePlanner:
# (turn_around_priority) nên không cần SBPL vẽ cung quay đầu khi goal ở phía sau. # (turn_around_priority) nên không cần SBPL vẽ cung quay đầu khi goal ở phía sau.
# Nếu không ra nghiệm, planner tự retry một lần với heading thật của robot. # Nếu không ra nghiệm, planner tự retry một lần với heading thật của robot.
free_start_heading: true free_start_heading: true
# [bool] Ô UNKNOWN (chưa scan) có đi được không. Khai TƯỜNG MINH — thiếu khoá thì code rơi về true
# và log cảnh báo lúc boot.
# true : unknown = free. Goal ngoài vùng đã map vẫn có "đường điểm" qua vùng trống ngoài nhà ->
# ARA* quét toàn bộ free + unknown (6-7 s trên map 70x39 m, đo máy dev 2026-09-17) rồi
# mới báo không có đường.
# false: unknown = tường. Goal ngoài vùng đã map bị từ chối ngay ở bước "2D reachability: h=INF"
# (~0.1 s). Robot thật nên false — không lập plan xuyên chỗ chưa nhìn thấy.
# ► Giữ true ở bản này để không đổi hành vi đang chạy; đổi false sau khi đã thử trên robot.
allow_unknown: true
# ===== Chẩn đoán lập plan (2026-09-18) =====
# Dòng LỖI KHÔNG tắt được bằng khoá nào: "goal REJECTED ..." (goal đứng trên ô >= 253 hoặc footprint
# đè tường/mép lưới), "2D reachability: h=INF ..." (goal bị bịt kín), "NO SOLUTION ... reason=
# EXHAUSTED|TIMEOUT expands=... phase_elapsed=..." (search chạy mà không ra). Đọc reason:
# EXHAUSTED + h_2d hữu hạn = có đường cho ĐIỂM, không có đường cho FOOTPRINT (khe hẹp, hoặc goal
# hợp lệ nhưng không action nào kết thúc đúng (x,y,theta) đó).
# TIMEOUT = hết allocated_time -> nới allocated_time hoặc tăng initial_epsilon.
# [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>",
# "solved: ... expands= h_2d= phase=". Mặc định BẬT; tắt khi log robot thật quá dày.
debug_plan: true
# [ô] Bán kính cửa sổ lưới in ASCII quanh goal VÀ start khi goal bị từ chối / không có đường.
# 0 = tắt. 15 = 31x31 ô = 1.5 m @ 5 cm mỗi cửa sổ (62 dòng log mỗi lần fail). Trần 60.
# Ký hiệu: . free - preferred : inflated/unpreferred i inscribed # lethal ? unknown S G.
# Bật khi cần thấy VÁCH nào chặn mà không cần dump costmap; rất nặng log, tắt lại sau khi xong.
debug_grid_window: 0
nominalvel_mpersecs: 0.3 nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/mprim_gen/diff_5cm.mprim primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/mprim_gen/diff_5cm.mprim

View File

@@ -144,6 +144,36 @@ private:
* plan lại một lần. Không ra nghiệm thì retry với heading thật. */ * plan lại một lần. Không ra nghiệm thì retry với heading thật. */
bool free_start_heading_; 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. /// @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; const robot_costmap_2d::Costmap2D* activeGrid() const;

View File

@@ -37,7 +37,9 @@
#include <sbpl_lattice_planner/sbpl_lattice_planner.h> #include <sbpl_lattice_planner/sbpl_lattice_planner.h>
#include <algorithm>
#include <cmath> #include <cmath>
#include <string>
#include <cstdlib> #include <cstdlib>
#include <dlfcn.h> #include <dlfcn.h>
#include <unistd.h> #include <unistd.h>
@@ -101,6 +103,80 @@ void SBPLLatticePlanner::setExternalGrid(const robot_costmap_2d::Costmap2D* grid
const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{ const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{
return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap(); return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap();
} }
const char* SBPLLatticePlanner::costClassName(unsigned char cost){
// Semantics của costmap trong port này, không phải của SBPL: 254 lethal, 253 = trong bán kính
// inscribed của một ô lethal, 255 = chưa biết. FREE_SPACE ở đây là 60 chứ không phải 0
// (cost_values.h): dưới 60 là lane ưu tiên (PreferredLayer hạ cost), trên 60 là inflation hoặc
// vùng unpreferred.
if (cost == robot_costmap_2d::LETHAL_OBSTACLE) return "LETHAL";
if (cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) return "INSCRIBED";
if (cost == robot_costmap_2d::NO_INFORMATION) return "UNKNOWN";
if (cost == robot_costmap_2d::FREE_SPACE) return "FREE";
if (cost < robot_costmap_2d::FREE_SPACE) return "PREFERRED";
return "INFLATED/UNPREFERRED";
}
SBPLLatticePlanner::PoseAudit SBPLLatticePlanner::auditPose(
const robot_costmap_2d::Costmap2D* grid, double wx, double wy, double theta) const{
PoseAudit a;
a.in_map = grid->worldToMap(wx, wy, a.mx, a.my);
if (!a.in_map) {
return a;
}
a.cost = grid->getCost(a.mx, a.my);
// Cùng phép kiểm SBPL dùng bên trong khi mở rộng: mọi ô footprint phải trong lưới và < obsthresh.
// SetGoal() của SBPL chỉ CẢNH BÁO khi phép này false, và cảnh báo đó bị compile bỏ (SBPL_PRINTF
// rỗng) — nên goal như vậy lọt qua, rồi search quét hết map mới báo không có đường. Chỉ số ô
// của worldToMap trùng với CONTXY2DISC(x - origin) mà SetStart/SetGoal dùng cho điểm trong lưới.
a.footprint_ok = env_ != NULL &&
env_->IsValidConfiguration(static_cast<int>(a.mx), static_cast<int>(a.my),
env_->ContTheta2DiscNew(theta));
return a;
}
void SBPLLatticePlanner::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{
// Một dòng mỗi hàng, hàng y lớn in trước để nhìn như bản đồ (y hướng lên). Ký hiệu:
// . FREE (60) - PREFERRED (<60) : INFLATED/UNPREFERRED (61-252)
// i INSCRIBED (253) # LETHAL (254) ? UNKNOWN (255) S start G goal
const int W = static_cast<int>(grid->getSizeInCellsX());
const int H = static_cast<int>(grid->getSizeInCellsY());
robot::log_info("[sbpl_lattice_planner] grid window around %s: center cell (%u,%u), %d x %d cells "
"@ %.3f m | . free - preferred : inflated/unpreferred i inscribed # lethal "
"? unknown S start G goal",
label, cx, cy, 2 * radius + 1, 2 * radius + 1, grid->getResolution());
std::string row;
row.reserve(static_cast<size_t>(2 * radius + 1));
for (int dy = radius; dy >= -radius; --dy) {
row.clear();
const int y = static_cast<int>(cy) + dy;
for (int dx = -radius; dx <= radius; ++dx) {
const int x = static_cast<int>(cx) + dx;
char c;
if (x < 0 || y < 0 || x >= W || y >= H) {
c = ' '; // ngoài lưới
} else if (x == static_cast<int>(sx) && y == static_cast<int>(sy)) {
c = 'S';
} else if (x == static_cast<int>(gx) && y == static_cast<int>(gy)) {
c = 'G';
} else {
const unsigned char cost = grid->getCost(static_cast<unsigned int>(x),
static_cast<unsigned int>(y));
c = (cost == robot_costmap_2d::LETHAL_OBSTACLE) ? '#'
: (cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) ? 'i'
: (cost == robot_costmap_2d::NO_INFORMATION) ? '?'
: (cost == robot_costmap_2d::FREE_SPACE) ? '.'
: (cost < robot_costmap_2d::FREE_SPACE) ? '-'
: ':';
}
row.push_back(c);
}
robot::log_info("[sbpl_lattice_planner] %5d |%s|", y, row.c_str());
}
}
bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot){ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot){
if(!initialized_){ if(!initialized_){
@@ -164,9 +240,39 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
private_nh.param<int>("visualizer_skip_poses", visualizer_skip_poses_, 5); private_nh.param<int>("visualizer_skip_poses", visualizer_skip_poses_, 5);
private_nh.param("allow_unknown", allow_unknown_, bool(true)); private_nh.param("allow_unknown", allow_unknown_, bool(true));
if (!private_nh.hasParam("allow_unknown")) {
// Khoá này quyết định robot có được lập plan xuyên vùng chưa scan hay không, và quyết định
// goal ngoài vùng đã map fail tức thì (false) hay quét cả map 6-7 s rồi mới fail (true, đo
// 2026-09-17). Default C++ âm thầm là true — nói ra để người vận hành biết mình đang dựa vào nó.
robot::log_warning("[sbpl_lattice_planner] '%s/allow_unknown' not set in YAML — defaulting to "
"true (unknown cells are traversable). Set it explicitly.", name.c_str());
}
// chỉ bật khi local planner có bước quay tại chỗ đầu path (turn_around_priority) // chỉ bật khi local planner có bước quay tại chỗ đầu path (turn_around_priority)
private_nh.param("free_start_heading", free_start_heading_, bool(false)); private_nh.param("free_start_heading", free_start_heading_, bool(false));
// Nhóm log chẩn đoán lập plan. Mặc định BẬT: tắt là lựa chọn có ý thức của người đang không cần
// debug, không phải thứ đổi sau lưng người đang dựa vào log. Dòng LỖI không đi qua khoá này.
private_nh.param("debug_plan", debug_plan_, bool(true));
private_nh.param("debug_grid_window", debug_grid_window_, 0);
if (debug_grid_window_ < 0) {
robot::log_warning("[sbpl_lattice_planner] debug_grid_window=%d < 0, using 0 (off)",
debug_grid_window_);
debug_grid_window_ = 0;
}
constexpr int kMaxGridWindow = 60; // 121x121 ô = 6 m @5 cm; hơn nữa là spam log, không đọc nổi
if (debug_grid_window_ > kMaxGridWindow) {
robot::log_warning("[sbpl_lattice_planner] debug_grid_window=%d > %d, clamping",
debug_grid_window_, kMaxGridWindow);
debug_grid_window_ = kMaxGridWindow;
}
robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs initial_epsilon=%.2f "
"allow_unknown=%s free_start_heading=%s forward_search=%s | debug_plan=%s "
"debug_grid_window=%d",
name.c_str(), allocated_time_, initial_epsilon_,
allow_unknown_ ? "true" : "false", free_start_heading_ ? "true" : "false",
forward_search_ ? "true" : "false", debug_plan_ ? "on" : "off",
debug_grid_window_);
name_ = name; name_ = name;
costmap_robot_ = costmap_robot; costmap_robot_ = costmap_robot;
@@ -224,31 +330,35 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
perimeterptsV.push_back(pt); perimeterptsV.push_back(pt);
} }
// Kích thước env và cost ban đầu lấy từ lưới ĐANG CÓ HIỆU LỰC (activeGrid), không phải luôn là
// lưới sống. Lần initialize() đầu tiên chạy trên control thread khi external_grid_ còn NULL nên
// vẫn là lưới sống như trước. Nhưng re-init từ makePlan() (đổi kích thước map, đổi footprint)
// chạy trên thread planner — và khi PlannerRunner đã đưa bản chụp (snapshot_for_readers) thì
// thread đó KHÔNG còn giữ mutex costmap. Đọc cell sống ở đây lúc đó là đọc đua với map-update
// thread, và resizeMap realloc mảng dưới chân vòng lặp. Bản chụp cùng kích thước/origin với
// master tại thời điểm chụp nên env dựng theo nó là nhất quán với phần cost đổ vào sau.
const robot_costmap_2d::Costmap2D* init_grid = activeGrid();
robot::log_info("footprint size = %zu", perimeterptsV.size()); robot::log_info("footprint size = %zu", perimeterptsV.size());
robot::log_info("width=%d", robot::log_info("width=%d", init_grid->getSizeInCellsX());
costmap_robot_->getCostmap()->getSizeInCellsX()); robot::log_info("height=%d", init_grid->getSizeInCellsY());
robot::log_info("resolution=%f", init_grid->getResolution());
robot::log_info("height=%d",
costmap_robot_->getCostmap()->getSizeInCellsY());
robot::log_info("resolution=%f",
costmap_robot_->getCostmap()->getResolution());
bool ret; bool ret;
try{ try{
// robot::log_warning("DEBUG 2000"); // robot::log_warning("DEBUG 2000");
ret = env_->InitializeEnv(costmap_robot_->getCostmap()->getSizeInCellsX(), // width ret = env_->InitializeEnv(init_grid->getSizeInCellsX(), // width
costmap_robot_->getCostmap()->getSizeInCellsY(), // height init_grid->getSizeInCellsY(), // height
0, // mapdata 0, // mapdata
0, 0, 0, // start (x, y, theta, t) 0, 0, 0, // start (x, y, theta, t)
0, 0, 0, // goal (x, y, theta) 0, 0, 0, // goal (x, y, theta)
0, 0, 0, //goal tolerance 0, 0, 0, //goal tolerance
perimeterptsV, costmap_robot_->getCostmap()->getResolution(), nominalvel_mpersecs, perimeterptsV, init_grid->getResolution(), nominalvel_mpersecs,
timetoturn45degsinplace_secs, obst_cost_thresh, timetoturn45degsinplace_secs, obst_cost_thresh,
primitive_filename_.c_str()); primitive_filename_.c_str());
ret = true; ret = true;
current_env_width_ = costmap_robot_->getCostmap()->getSizeInCellsX(); current_env_width_ = init_grid->getSizeInCellsX();
current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY(); current_env_height_ = init_grid->getSizeInCellsY();
// robot::log_warning("DEBUG 3000"); // robot::log_warning("DEBUG 3000");
} }
catch(SBPL_Exception *e){ catch(SBPL_Exception *e){
@@ -259,9 +369,9 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
robot::log_error("SBPL initialization failed!"); robot::log_error("SBPL initialization failed!");
exit(1); exit(1);
} }
for (ssize_t ix(0); ix < costmap_robot_->getCostmap()->getSizeInCellsX(); ++ix) for (ssize_t ix(0); ix < init_grid->getSizeInCellsX(); ++ix)
for (ssize_t iy(0); iy < costmap_robot_->getCostmap()->getSizeInCellsY(); ++iy) for (ssize_t iy(0); iy < init_grid->getSizeInCellsY(); ++iy)
env_->UpdateCost(ix, iy, costMapCostToSBPLCost(costmap_robot_->getCostmap()->getCost(ix,iy))); env_->UpdateCost(ix, iy, costMapCostToSBPLCost(init_grid->getCost(ix,iy)));
if ("ARAPlanner" == planner_type_){ if ("ARAPlanner" == planner_type_){
robot::log_info("Planning with ARA*"); robot::log_info("Planning with ARA*");
@@ -393,19 +503,24 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
planner_ = NULL; planner_ = NULL;
delete env_; delete env_;
env_ = NULL; 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 // Footprint, inflation và frame vẫn lấy từ costmap SỐNG — lưới ngoài lệch kích thước với nó sẽ
// mỗi lượt. Contract của setExternalGrid cấm lệch, nhưng phát hiện được thì nói thẳng. // 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. So với lưới sống thật (getCostmap()), KHÔNG so với `grid`: `grid` chính là
// external_grid_ khi có lưới ngoài, nên phép so cũ luôn bằng nhau và không bao giờ bắn.
// Chỉ đọc hai số kích thước, không chạm cell, nên không cần mutex.
const robot_costmap_2d::Costmap2D* live = costmap_robot_->getCostmap();
if (external_grid_ != NULL && if (external_grid_ != NULL &&
(external_grid_->getSizeInCellsX() != grid->getSizeInCellsX() || (external_grid_->getSizeInCellsX() != live->getSizeInCellsX() ||
external_grid_->getSizeInCellsY() != grid->getSizeInCellsY())) { external_grid_->getSizeInCellsY() != live->getSizeInCellsY())) {
robot::log_error("[sbpl_lattice_planner] external grid (%d x %d) does not match the live " robot::log_error("[sbpl_lattice_planner] external grid (%d x %d) does not match the live "
"costmap (%d x %d); dropping the external grid.", "costmap (%d x %d); dropping the external grid.",
external_grid_->getSizeInCellsX(), external_grid_->getSizeInCellsY(), external_grid_->getSizeInCellsX(), external_grid_->getSizeInCellsY(),
grid->getSizeInCellsX(), live->getSizeInCellsX(),
grid->getSizeInCellsY()); live->getSizeInCellsY());
external_grid_ = NULL; external_grid_ = NULL;
grid = activeGrid(); grid = activeGrid();
} }
// Re-init đọc cell từ activeGrid(): bản chụp nếu có, lưới sống nếu không (xem initialize()).
initialize(name_, costmap_robot_); initialize(name_, costmap_robot_);
} }
@@ -434,12 +549,15 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
start_heading_overridden = true; start_heading_overridden = true;
} }
int start_state_id = -1;
int goal_state_id = -1;
try{ try{
int ret = env_->SetStart(start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->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){ if(ret < 0 || planner_->set_start(ret) == 0){
robot::log_error("ERROR: failed to set start state\n"); robot::log_error("ERROR: failed to set start state\n");
return false; return false;
} }
start_state_id = ret;
} }
catch(SBPL_Exception *e){ catch(SBPL_Exception *e){
robot::log_error("SBPL encountered a fatal exception while setting the start state"); robot::log_error("SBPL encountered a fatal exception while setting the start state");
@@ -449,9 +567,16 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
try{ try{
int ret = env_->SetGoal(goal.pose.position.x - grid->getOriginX(), goal.pose.position.y - grid->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){ if(ret < 0 || planner_->set_goal(ret) == 0){
robot::log_error("ERROR: failed to set goal state\n"); // Nhánh duy nhất SBPL tự từ chối: Ô goal ngoài lưới. Goal trong lưới nhưng footprint đè
// tường thì SBPL im lặng nhận — phần audit bên dưới bắt ca đó.
robot::log_error("ERROR: failed to set goal state — goal (%.3f, %.3f) is outside the "
"%u x %u grid (origin %.2f, %.2f, %.3f m/cell)\n",
goal.pose.position.x, goal.pose.position.y, grid->getSizeInCellsX(),
grid->getSizeInCellsY(), grid->getOriginX(), grid->getOriginY(),
grid->getResolution());
return false; return false;
} }
goal_state_id = ret;
} }
catch(SBPL_Exception *e){ catch(SBPL_Exception *e){
robot::log_error("SBPL encountered a fatal exception while setting the goal state"); robot::log_error("SBPL encountered a fatal exception while setting the goal state");
@@ -508,6 +633,100 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return false; return false;
} }
// ================================================================================================
// Chẩn đoán TRƯỚC khi search (2026-09-18). Env đã nhận cost mới ở vòng trên, nên soi ở đây mới
// đúng lưới mà ARA* sắp dùng. Ba câu hỏi, trả lời xong mới chạy search:
// 1. Goal đứng trên ô gì, footprint tại goal có hợp lệ không? -> không thì từ chối ngay.
// 2. Start đứng trên ô gì? -> chỉ báo, không từ chối.
// 3. Có đường 2D (điểm) từ start tới goal qua ô < inscribed? -> không thì từ chối ngay.
// Từ chối sớm không đổi kết quả (ARA* cũng sẽ trả false) nhưng bỏ 6-14 s quét map + retry
// heading, và log nói thẳng nguyên nhân thay vì "Solution not found".
// ================================================================================================
const PoseAudit goal_audit = auditPose(grid, goal.pose.position.x, goal.pose.position.y, theta_goal);
const PoseAudit start_audit = auditPose(grid, start.pose.position.x, start.pose.position.y, theta_start);
const auto dump_windows = [&](const char* why) {
if (debug_grid_window_ <= 0 || !goal_audit.in_map || !start_audit.in_map) {
return;
}
robot::log_info("[sbpl_lattice_planner] grid dump (%s)", why);
logGridWindow(grid, debug_grid_window_, goal_audit.mx, goal_audit.my, start_audit.mx,
start_audit.my, goal_audit.mx, goal_audit.my, "GOAL");
logGridWindow(grid, debug_grid_window_, start_audit.mx, start_audit.my, start_audit.mx,
start_audit.my, goal_audit.mx, goal_audit.my, "START");
};
// (1) Goal. Một action không bao giờ được KẾT THÚC trên ô >= cost_inscribed_thresh (253), và
// footprint tại goal phải trong lưới + không đè lethal — hai điều kiện SBPL kiểm khi mở rộng
// nhưng KHÔNG kiểm khi SetGoal. Goal vi phạm = không có successor nào trùng goal = chắc chắn fail
// sau khi quét hết vùng nối với robot.
const bool goal_cell_blocked =
goal_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE &&
!(allow_unknown_ && goal_audit.cost == robot_costmap_2d::NO_INFORMATION);
if (!goal_audit.in_map || goal_cell_blocked || !goal_audit.footprint_ok) {
robot::log_error("[sbpl_lattice_planner] goal REJECTED at (%.3f, %.3f, yaw %.2f): cell (%u,%u) "
"cost=%u %s, footprint %s — SBPL never ends an action on a cell >= 253 or with "
"the footprint on lethal/map edge; the search would sweep the whole reachable "
"map and fail anyway. Move the goal >= inscribed radius (%.2f m) away from "
"walls/keepout, or check the map/zone layers.\n",
goal.pose.position.x, goal.pose.position.y, theta_goal, goal_audit.mx,
goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost),
goal_audit.footprint_ok ? "valid" : "INVALID",
costmap_robot_->getLayeredCostmap()->getInscribedRadius());
dump_windows("goal rejected");
return false;
}
// (2) Start. Robot đang đứng trong tường là chuyện của recovery (clear costmap), planner chỉ nói.
if (start_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || !start_audit.footprint_ok) {
robot::log_error("[sbpl_lattice_planner] start audit at (%.3f, %.3f, yaw %.2f%s): cell (%u,%u) "
"cost=%u %s, footprint %s — robot is inside/next to lethal; expect few or no "
"valid first actions.\n",
start.pose.position.x, start.pose.position.y, theta_start,
start_heading_overridden ? " (free heading)" : "", start_audit.mx,
start_audit.my, start_audit.cost, costClassName(start_audit.cost),
start_audit.footprint_ok ? "valid" : "INVALID");
}
else if (debug_plan_) {
robot::log_info("[sbpl_lattice_planner] audit: start cell (%u,%u) cost=%u %s | goal cell (%u,%u) "
"cost=%u %s footprint valid | grid %u x %u @ %.3f m origin (%.2f, %.2f) | "
"allow_unknown=%s",
start_audit.mx, start_audit.my, start_audit.cost, costClassName(start_audit.cost),
goal_audit.mx, goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost),
grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(),
grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false");
}
// (3) Nối 2D. Heuristic của SBPL là Dijkstra 2D từ goal trên ô < cost_inscribed_thresh — đúng tập
// ô mà tâm robot được phép đi qua trong search 3D. Vậy h(start) = INF nghĩa là KHÔNG tồn tại
// đường 3D; ARA* sẽ dừng sau 0 expansion, nhưng vẫn tốn khởi tạo + retry heading, và log chỉ
// nói "Solution not found". Gọi trước để nói rõ, rồi từ chối. GetGoalHeuristic chia cho
// nominalvel nên INF (1e9) có thể tràn int thành số ÂM — bắt cả hai dạng.
int h_2d = 0;
try{
env_->EnsureHeuristicsUpdated(forward_search_);
h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id)
: env_->GetStartHeuristic(goal_state_id);
}
catch(SBPL_Exception *e){
robot::log_error("SBPL encountered a fatal exception while computing the 2D heuristic");
return false;
}
const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST);
if (h_2d_infinite) {
robot::log_error("[sbpl_lattice_planner] 2D reachability start->goal: h=INF — no point path "
"through cells < 253 (allow_unknown=%s). Goal region is sealed off from the "
"robot by lethal/inscribed cells%s. REJECTED without running the lattice search.\n",
allow_unknown_ ? "true" : "false",
allow_unknown_ ? "" : " or by unknown space (allow_unknown=false)");
dump_windows("2D unreachable");
return false;
}
if (debug_plan_) {
// h tính bằng đơn vị cost SBPL (mm / nominalvel): chỉ dùng để so tương đối giữa các lượt.
robot::log_info("[sbpl_lattice_planner] 2D reachability start->goal: h=%d (finite) — point path "
"exists, running lattice search", h_2d);
}
//setting planner parameters //setting planner parameters
robot::log_debug("allocated:%f, init eps:%f\n",allocated_time_,initial_epsilon_); robot::log_debug("allocated:%f, init eps:%f\n",allocated_time_,initial_epsilon_);
planner_->set_initialsolution_eps(initial_epsilon_); planner_->set_initialsolution_eps(initial_epsilon_);
@@ -517,14 +736,20 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
const robot::Time plan_started = robot::Time::now(); const robot::Time plan_started = robot::Time::now();
// NGÂN SÁCH CHUNG (2026-09-11): `allocated_time` là trần của CẢ lượt makePlan, không phải của // NGÂN SÁCH CHUNG (2026-09-11): `allocated_time` là trần của CẢ lượt makePlan, không phải của
// từng lượt replan nội bộ. Trước đây ba lượt (free heading → heading thật → căn lại heading) mỗi // từng lượt replan nội bộ. Trước đây ba lượt (free heading → heading thật → căn lại heading) mỗi
// lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và // lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và khi
// PlannerRunner giữ costmap mutex suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget. // PlannerRunner còn giữ costmap mutex (global_costmap.snapshot_for_readers = false) thì map-update
// thread đứng suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget.
constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì
const auto budget_left = [&]() { const auto budget_left = [&]() {
return allocated_time_ - (robot::Time::now() - plan_started).toSec(); return allocated_time_ - (robot::Time::now() - plan_started).toSec();
}; };
vector<int> solution_stateIDs; vector<int> solution_stateIDs;
int solution_cost; int solution_cost;
// Khám nghiệm khi fail cần biết pha cuối chạy với ngân sách nào và bắt đầu lúc nào — "hết giờ"
// hay "cạn" chỉ phân biệt được bằng elapsed/budget của ĐÚNG pha đó.
const char* phase_name = start_heading_overridden ? "free_heading" : "actual_heading";
double phase_budget = allocated_time_;
robot::Time phase_started = plan_started;
try{ try{
int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost); int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost);
if(preempt_.load(std::memory_order_relaxed)){ if(preempt_.load(std::memory_order_relaxed)){
@@ -535,13 +760,18 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){ if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){
// Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường // Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường
// 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. // 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, " robot::log_warning("[sbpl_lattice_planner] no solution with free start heading after %d "
"retrying with actual robot heading (%.2f s left)", budget_left()); "expansions in %.0f ms, retrying with actual robot heading (%.2f s left)",
planner_->get_n_expands(),
(robot::Time::now() - plan_started).toSec() * 1000.0, budget_left());
int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(),
start.pose.position.y - grid->getOriginY(), start.pose.position.y - grid->getOriginY(),
theta_start_actual); theta_start_actual);
if(sid >= 0 && planner_->set_start(sid) != 0){ if(sid >= 0 && planner_->set_start(sid) != 0){
ret = planner_->replan(budget_left(), &solution_stateIDs, &solution_cost); phase_name = "actual_heading_retry";
phase_budget = budget_left();
phase_started = robot::Time::now();
ret = planner_->replan(phase_budget, &solution_stateIDs, &solution_cost);
} }
if(preempt_.load(std::memory_order_relaxed)){ if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)", robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)",
@@ -557,16 +787,41 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// `allocated_time` chỉ là suy đoán từ thời gian đo được. // `allocated_time` chỉ là suy đoán từ thời gian đo được.
// //
// Đọc thế nào: eps == initial_epsilon nghĩa là hết giờ ngay ở nấc đầu — nới `allocated_time` // Đọc thế nào: eps == initial_epsilon nghĩa là hết giờ ngay ở nấc đầu — nới `allocated_time`
// hoặc hạ `initial_epsilon`. eps == 1.0 nghĩa là đã tới nghiệm tối ưu. // hoặc hạ `initial_epsilon`. eps == 1.0 nghĩa là đã tới nghiệm tối ưu. expands= là số state
robot::log_info("[sbpl_lattice_planner] solved: eps=%.3f (init %.2f), cost=%d, %zu state(s), " // ARA* đã mở: so giữa hai lượt cùng goal để thấy map/cost đổi hay không.
"%.0f ms of %.2f s allowed", if (debug_plan_) {
planner_->get_final_epsilon(), initial_epsilon_, solution_cost, robot::log_info("[sbpl_lattice_planner] solved: eps=%.3f (init %.2f), cost=%d, %zu state(s), "
solution_stateIDs.size(), "%.0f ms of %.2f s allowed, expands=%d, h_2d=%d, phase=%s",
(robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_); planner_->get_final_epsilon(), initial_epsilon_, solution_cost,
solution_stateIDs.size(),
(robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_,
planner_->get_n_expands(), h_2d, phase_name);
}
} }
else{ else{
robot::log_info("Solution not found\n"); // Dòng LỖI, không tắt được. Ba nguyên nhân phân biệt bằng elapsed của pha cuối:
// publishStats(solution_cost, 0, start, goal); // EXHAUSTED: dừng trước khi hết ngân sách -> OPEN list cạn -> KHÔNG có đường 3D dù 2D có
// (footprint/primitive không lọt khe, hoặc goal ở ô hợp lệ nhưng không có action
// nào kết thúc đúng (x,y,theta) đó). Kèm h_2d hữu hạn ở trên = đúng ca này.
// TIMEOUT: chạy sát ngân sách -> map lớn/eps=1.0/goal xa, nới allocated_time hoặc tăng
// initial_epsilon.
// (preempt đã return sớm ở trên, không tới đây.)
const double phase_elapsed = (robot::Time::now() - phase_started).toSec();
const double total_elapsed = (robot::Time::now() - plan_started).toSec();
constexpr double kTimeoutFraction = 0.95; // sát trần ngần này coi là hết giờ
const bool timed_out = phase_budget > 0.0 && phase_elapsed >= kTimeoutFraction * phase_budget;
robot::log_error("[sbpl_lattice_planner] NO SOLUTION start=(%.3f,%.3f) goal=(%.3f,%.3f) "
"dist=%.1f m | phase=%s reason=%s expands=%d phase_elapsed=%.0f ms of %.0f ms "
"total=%.0f ms of %.0f ms eps=%.2f h_2d=%d allow_unknown=%s\n",
start.pose.position.x, start.pose.position.y, goal.pose.position.x,
goal.pose.position.y,
std::hypot(goal.pose.position.x - start.pose.position.x,
goal.pose.position.y - start.pose.position.y),
phase_name, timed_out ? "TIMEOUT" : "EXHAUSTED", planner_->get_n_expands(),
phase_elapsed * 1000.0, phase_budget * 1000.0, total_elapsed * 1000.0,
allocated_time_ * 1000.0, planner_->get_final_epsilon(), h_2d,
allow_unknown_ ? "true" : "false");
dump_windows("no solution");
return false; return false;
} }
} }