Compare commits
2 Commits
rename/rob
...
feature/di
| Author | SHA1 | Date | |
|---|---|---|---|
| 471d13410c | |||
| 47dd76f39e |
@@ -138,6 +138,7 @@ endif()
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/sbpl_lattice_planner.cpp
|
||||
src/directional_environment.cpp
|
||||
)
|
||||
|
||||
# Header sbpl phải là bản mà SBPL_DIR chọn, ĐỨNG TRƯỚC mọi include của catkin: /opt/ros/noetic/include
|
||||
@@ -235,3 +236,14 @@ else()
|
||||
message(STATUS "Dependencies: robot_visualization_msgs, robot_nav_msgs, robot_std_msgs, robot_geometry_msgs, tf3, robot_tf3_geometry_msgs, robot_time, data_convert, robot_costmap_2d, robot_nav_core, robot_protocol_msgs, robot_cpp, Eigen3, Boost")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
|
||||
option(BUILD_SBPL_LATTICE_TESTS "Build sbpl_lattice_planner test executables" ${BUILDING_WITH_CATKIN})
|
||||
if(BUILD_SBPL_LATTICE_TESTS)
|
||||
find_package(GTest REQUIRED)
|
||||
add_executable(direction_environment_test test/direction_environment_test.cpp)
|
||||
target_include_directories(direction_environment_test BEFORE PRIVATE ${SBPL_INCLUDE_DIRS})
|
||||
target_compile_definitions(direction_environment_test PRIVATE
|
||||
DIRECTION_TEST_MPRIM="${CMAKE_CURRENT_SOURCE_DIR}/test/data/unicycle_0125.mprim")
|
||||
target_link_libraries(direction_environment_test PRIVATE ${PROJECT_NAME} ${SBPL_LIBRARIES}
|
||||
robot_costmap_2d GTest::GTest GTest::Main)
|
||||
endif()
|
||||
|
||||
73
include/sbpl_lattice_planner/directional_environment.h
Normal file
73
include/sbpl_lattice_planner/directional_environment.h
Normal file
@@ -0,0 +1,73 @@
|
||||
#ifndef SBPL_LATTICE_PLANNER_DIRECTIONAL_ENVIRONMENT_H_
|
||||
#define SBPL_LATTICE_PLANNER_DIRECTIONAL_ENVIRONMENT_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_costmap_2d/direction_field.h>
|
||||
#include <sbpl/discrete_space_information/environment_navxythetalat.h>
|
||||
|
||||
namespace sbpl_lattice_planner
|
||||
{
|
||||
|
||||
/** @brief Search-time decision for a single immutable direction snapshot. */
|
||||
struct DirectionDecision
|
||||
{
|
||||
enum class Result { kDisabled, kPending, kGeometryMismatch, kReady };
|
||||
Result result;
|
||||
bool force_scratch;
|
||||
};
|
||||
|
||||
/** @brief Decide whether a snapshot can be used with the active grid. */
|
||||
DirectionDecision decideDirection(const robot_costmap_2d::DirectionFieldSnapshot& snapshot,
|
||||
bool have_previous, robot_costmap_2d::DirectionFieldState previous_state,
|
||||
uint64_t previous_generation,
|
||||
const robot_costmap_2d::DirectionGeometry& grid);
|
||||
|
||||
/** @brief Lattice environment that removes actions violating the direction field.
|
||||
* The attached field is non-owning and must outlive all search and path conversion calls.
|
||||
*/
|
||||
class DirectionalEnvironmentNAVXYTHETALAT : public EnvironmentNAVXYTHETALAT
|
||||
{
|
||||
public:
|
||||
/** @brief A direction mask for one cell relative to the action source. */
|
||||
struct CellMask { int64_t dx, dy; uint8_t mask; };
|
||||
|
||||
/** @brief Rebuild after InitializeEnv or a deviation change.
|
||||
* @param max_deviation_rad Maximum inclusive deviation [rad], in (0, pi).
|
||||
* @return False for invalid deviation or primitive geometry; the previous table is retained.
|
||||
*/
|
||||
bool buildDirectionTable(double max_deviation_rad);
|
||||
/** @brief Deviation [rad] used for the current table, or NaN before a successful build. */
|
||||
double tableMaxDeviationRad() const { return table_max_deviation_rad_; }
|
||||
/** @brief Attach a snapshot owned by the caller, or detach with nullptr. */
|
||||
void setDirectionField(const robot_costmap_2d::DirectionField* field) { field_ = field; }
|
||||
/** @brief Reset per-plan rejection statistics. */
|
||||
void resetDirectionRejections() { rejections_ = 0; }
|
||||
/** @brief Number of actions rejected by direction or field bounds. */
|
||||
uint64_t directionRejections() const { return rejections_; }
|
||||
/** @brief Inspect precomputed masks for a given action. */
|
||||
const std::vector<CellMask>& cells() const { return cells_; }
|
||||
/** @brief Offsets into cells(), indexed by theta * actionWidth() + action. */
|
||||
const std::vector<size_t>& offsets() const { return offsets_; }
|
||||
/** @brief Number of actions per source orientation. */
|
||||
int actionWidth() const { return EnvNAVXYTHETALATCfg.actionwidth; }
|
||||
/** @brief Number of discretized source orientations. */
|
||||
int thetaCount() const { return EnvNAVXYTHETALATCfg.NumThetaDirs; }
|
||||
/** @brief Inspect an SBPL action using valid theta and action indices. */
|
||||
const EnvNAVXYTHETALATAction_t& action(int theta, int index) const
|
||||
{ return EnvNAVXYTHETALATCfg.ActionsV[theta][index]; }
|
||||
|
||||
int GetActionCost(int source_x, int source_y, int source_theta,
|
||||
EnvNAVXYTHETALATAction_t* action) override;
|
||||
private:
|
||||
const robot_costmap_2d::DirectionField* field_ = nullptr;
|
||||
uint64_t rejections_ = 0;
|
||||
std::vector<CellMask> cells_;
|
||||
std::vector<size_t> offsets_;
|
||||
double table_max_deviation_rad_ = std::numeric_limits<double>::quiet_NaN();
|
||||
};
|
||||
} // namespace sbpl_lattice_planner
|
||||
#endif
|
||||
@@ -2,10 +2,12 @@
|
||||
#define SBPL_LATTICE_PLANNER_H
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
// sbpl headers
|
||||
#include <sbpl/headers.h>
|
||||
|
||||
// ROBOT
|
||||
#include <robot/robot.h>
|
||||
@@ -15,13 +17,14 @@ using namespace std;
|
||||
// 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>
|
||||
|
||||
#include <sbpl_lattice_planner/directional_environment.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace sbpl_lattice_planner{
|
||||
|
||||
class SBPLLatticePlanner : public robot_nav_core::BaseGlobalPlanner,
|
||||
@@ -111,7 +114,15 @@ private:
|
||||
|
||||
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_;
|
||||
DirectionalEnvironmentNAVXYTHETALAT* env_;
|
||||
bool have_previous_direction_ = false;
|
||||
bool direction_scratch_pending_ = false;
|
||||
robot_costmap_2d::DirectionFieldState previous_direction_state_ = robot_costmap_2d::DirectionFieldState::kDisabled;
|
||||
uint64_t previous_direction_generation_ = 0;
|
||||
std::chrono::steady_clock::time_point last_direction_pending_log_{};
|
||||
std::chrono::steady_clock::time_point direction_pending_since_{};
|
||||
std::chrono::steady_clock::time_point last_direction_geometry_log_{};
|
||||
double current_env_resolution_ = 0.0;
|
||||
|
||||
std::string planner_type_; /**< sbpl method to use for planning. choices are ARAPlanner and ADPlanner */
|
||||
|
||||
|
||||
124
src/directional_environment.cpp
Normal file
124
src/directional_environment.cpp
Normal file
@@ -0,0 +1,124 @@
|
||||
#include <sbpl_lattice_planner/directional_environment.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <utility>
|
||||
|
||||
#include <sbpl/utils/key.h>
|
||||
|
||||
namespace sbpl_lattice_planner
|
||||
{
|
||||
DirectionDecision decideDirection(const robot_costmap_2d::DirectionFieldSnapshot& snapshot,
|
||||
bool have_previous, robot_costmap_2d::DirectionFieldState previous_state,
|
||||
uint64_t previous_generation, const robot_costmap_2d::DirectionGeometry& grid)
|
||||
{
|
||||
using State = robot_costmap_2d::DirectionFieldState;
|
||||
using Result = DirectionDecision::Result;
|
||||
const bool changed = !have_previous || snapshot.state != previous_state || snapshot.generation != previous_generation;
|
||||
if (snapshot.state == State::kDisabled)
|
||||
return {Result::kDisabled, changed};
|
||||
if (snapshot.state == State::kPending)
|
||||
return {Result::kPending, changed};
|
||||
if (snapshot.state != State::kReady || !snapshot.field)
|
||||
return {Result::kGeometryMismatch, changed};
|
||||
const auto& g = snapshot.field->geometry();
|
||||
const auto equal = [](double a, double b)
|
||||
{
|
||||
return std::isfinite(a) && std::isfinite(b) && std::abs(a - b) <= 1e-6;
|
||||
};
|
||||
if (g.width != grid.width || g.height != grid.height || !equal(g.resolution, grid.resolution) ||
|
||||
!equal(g.origin_x, grid.origin_x) || !equal(g.origin_y, grid.origin_y))
|
||||
return {Result::kGeometryMismatch, changed};
|
||||
return {Result::kReady, changed};
|
||||
}
|
||||
|
||||
bool DirectionalEnvironmentNAVXYTHETALAT::buildDirectionTable(double max_deviation_rad)
|
||||
{
|
||||
std::vector<CellMask> cells;
|
||||
std::vector<size_t> offsets;
|
||||
const double resolution = EnvNAVXYTHETALATCfg.cellsize_m;
|
||||
if (!std::isfinite(max_deviation_rad) || max_deviation_rad <= 0 || max_deviation_rad >= M_PI ||
|
||||
!std::isfinite(resolution) || resolution <= 0 || !EnvNAVXYTHETALATCfg.ActionsV)
|
||||
return false;
|
||||
// Snap near boundaries before DDA: binary rounding must not create a spurious sliver cell.
|
||||
const auto snap = [](double q)
|
||||
{
|
||||
const double n = std::round(q);
|
||||
return std::abs(q - n) <= 1e-9 ? n : q;
|
||||
};
|
||||
for (int theta = 0; theta < thetaCount(); ++theta)
|
||||
{
|
||||
for (int a = 0; a < actionWidth(); ++a)
|
||||
{
|
||||
offsets.push_back(cells.size());
|
||||
const auto& primitive = action(theta, a);
|
||||
std::map<std::pair<int64_t, int64_t>, uint8_t> masks;
|
||||
auto segment = [&](double x0, double y0, double x1, double y1)
|
||||
{
|
||||
const double dx = x1 - x0;
|
||||
const double dy = y1 - y0;
|
||||
if (dx == 0 && dy == 0)
|
||||
return true;
|
||||
const uint8_t mask = robot_costmap_2d::allowedDirectionMask(dx, dy, max_deviation_rad);
|
||||
return robot_costmap_2d::traverseGridSegment(snap(0.5 + x0 / resolution), snap(0.5 + y0 / resolution),
|
||||
snap(0.5 + x1 / resolution), snap(0.5 + y1 / resolution), [&](int64_t x, int64_t y)
|
||||
{
|
||||
auto result = masks.emplace(std::make_pair(x, y), mask);
|
||||
if (!result.second)
|
||||
result.first->second &= mask;
|
||||
return true;
|
||||
});
|
||||
};
|
||||
const auto& points = primitive.intermptV;
|
||||
if (points.empty())
|
||||
{
|
||||
// SBPL's deprecated built-in primitives have no samples; their motion is a straight cell displacement.
|
||||
if (!segment(0, 0, primitive.dX * resolution, primitive.dY * resolution))
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (size_t i = 1; i < points.size(); ++i)
|
||||
if (!segment(points[i - 1].x, points[i - 1].y, points[i].x, points[i].y))
|
||||
return false;
|
||||
if (points.size() == 1 && (primitive.dX != 0 || primitive.dY != 0))
|
||||
return false;
|
||||
}
|
||||
for (const auto& entry : masks)
|
||||
cells.push_back({entry.first.first, entry.first.second, entry.second});
|
||||
}
|
||||
}
|
||||
offsets.push_back(cells.size());
|
||||
cells_.swap(cells);
|
||||
offsets_.swap(offsets);
|
||||
table_max_deviation_rad_ = max_deviation_rad;
|
||||
return true;
|
||||
}
|
||||
|
||||
int DirectionalEnvironmentNAVXYTHETALAT::GetActionCost(int source_x, int source_y, int source_theta,
|
||||
EnvNAVXYTHETALATAction_t* primitive)
|
||||
{
|
||||
const int cost = EnvironmentNAVXYTHETALAT::GetActionCost(source_x, source_y, source_theta, primitive);
|
||||
if (cost >= INFINITECOST || !field_)
|
||||
return cost;
|
||||
const int theta = static_cast<unsigned char>(primitive->starttheta);
|
||||
const size_t index = static_cast<size_t>(theta) * actionWidth() + primitive->aind;
|
||||
if (theta >= thetaCount() || primitive->aind >= actionWidth() || index + 1 >= offsets_.size())
|
||||
{
|
||||
++rejections_;
|
||||
return INFINITECOST;
|
||||
}
|
||||
for (size_t i = offsets_[index]; i < offsets_[index + 1]; ++i)
|
||||
{
|
||||
const auto& cell = cells_[i];
|
||||
uint8_t code = 0;
|
||||
if (!field_->codeAt(static_cast<int64_t>(source_x) + cell.dx, static_cast<int64_t>(source_y) + cell.dy, &code) ||
|
||||
(code != 0 && (code > 8 || !(cell.mask & (1u << (code - 1))))))
|
||||
{
|
||||
++rejections_;
|
||||
return INFINITECOST;
|
||||
}
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
} // namespace sbpl_lattice_planner
|
||||
@@ -39,6 +39,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
@@ -292,7 +293,7 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
|
||||
|
||||
if ("XYThetaLattice" == environment_type_){
|
||||
robot::log_debug("Using a 3D costmap for theta lattice\n");
|
||||
env_ = new EnvironmentNAVXYTHETALAT();
|
||||
env_ = new DirectionalEnvironmentNAVXYTHETALAT();
|
||||
}
|
||||
else{
|
||||
robot::log_error("XYThetaLattice is currently the only supported environment!\n");
|
||||
@@ -356,7 +357,8 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
|
||||
perimeterptsV, init_grid->getResolution(), nominalvel_mpersecs,
|
||||
timetoturn45degsinplace_secs, obst_cost_thresh,
|
||||
primitive_filename_.c_str());
|
||||
ret = true;
|
||||
if (ret) ret = env_->buildDirectionTable(M_PI / 2.0);
|
||||
current_env_resolution_ = init_grid->getResolution();
|
||||
current_env_width_ = init_grid->getSizeInCellsX();
|
||||
current_env_height_ = init_grid->getSizeInCellsY();
|
||||
// robot::log_warning("DEBUG 3000");
|
||||
@@ -366,8 +368,10 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
|
||||
ret = false;
|
||||
}
|
||||
if(!ret){
|
||||
robot::log_error("SBPL initialization failed!");
|
||||
exit(1);
|
||||
robot::log_error("SBPL initialization or direction table construction failed!");
|
||||
delete env_;
|
||||
env_ = NULL;
|
||||
return false;
|
||||
}
|
||||
for (ssize_t ix(0); ix < init_grid->getSizeInCellsX(); ++ix)
|
||||
for (ssize_t iy(0); iy < init_grid->getSizeInCellsY(); ++iy)
|
||||
@@ -485,8 +489,37 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
// 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();
|
||||
|
||||
const auto direction_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot();
|
||||
const robot_costmap_2d::DirectionGeometry initial_geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(),
|
||||
grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()};
|
||||
const auto initial_decision = decideDirection(direction_snapshot, have_previous_direction_,
|
||||
previous_direction_state_, previous_direction_generation_, initial_geometry);
|
||||
if (initial_decision.result == DirectionDecision::Result::kPending) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (direction_pending_since_ == std::chrono::steady_clock::time_point{}) direction_pending_since_ = now;
|
||||
if (last_direction_pending_log_ == std::chrono::steady_clock::time_point{} ||
|
||||
now - last_direction_pending_log_ >= std::chrono::seconds(5)) {
|
||||
const double waited = std::chrono::duration<double>(now - direction_pending_since_).count();
|
||||
robot::log_error("[sbpl_lattice_planner] direction field is not ready (%.1f s); refusing to plan", waited);
|
||||
last_direction_pending_log_ = now;
|
||||
}
|
||||
direction_scratch_pending_ = direction_scratch_pending_ || initial_decision.force_scratch;
|
||||
have_previous_direction_ = true;
|
||||
previous_direction_state_ = direction_snapshot.state;
|
||||
previous_direction_generation_ = direction_snapshot.generation;
|
||||
if (debug_plan_) robot::log_info("[sbpl_lattice_planner] direction state=PENDING generation=%llu rejected=0",
|
||||
static_cast<unsigned long long>(direction_snapshot.generation));
|
||||
return false;
|
||||
}
|
||||
direction_pending_since_ = {};
|
||||
last_direction_pending_log_ = {};
|
||||
|
||||
bool do_init = false;
|
||||
if (current_env_width_ != grid->getSizeInCellsX() ||
|
||||
if (current_env_resolution_ != grid->getResolution()) {
|
||||
robot::log_info("Costmap resolution has changed, reinitializing sbpl_lattice_planner.");
|
||||
do_init = true;
|
||||
}
|
||||
else 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_,
|
||||
@@ -526,7 +559,69 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
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_);
|
||||
if (!initialize(name_, costmap_robot_)) return false;
|
||||
}
|
||||
|
||||
// The snapshot owns the field through search, conversion and the optional realignment retry.
|
||||
struct DirectionGuard {
|
||||
DirectionalEnvironmentNAVXYTHETALAT* env;
|
||||
const robot_costmap_2d::DirectionFieldSnapshot& snapshot;
|
||||
bool debug;
|
||||
~DirectionGuard() {
|
||||
if (debug) {
|
||||
const char* state = snapshot.state == robot_costmap_2d::DirectionFieldState::kReady ? "READY" :
|
||||
snapshot.state == robot_costmap_2d::DirectionFieldState::kPending ? "PENDING" : "DISABLED";
|
||||
robot::log_info("[sbpl_lattice_planner] direction state=%s generation=%llu rejected=%llu", state,
|
||||
static_cast<unsigned long long>(snapshot.generation),
|
||||
static_cast<unsigned long long>(env->directionRejections()));
|
||||
}
|
||||
env->setDirectionField(nullptr);
|
||||
}
|
||||
} guard{env_, direction_snapshot, debug_plan_};
|
||||
env_->resetDirectionRejections();
|
||||
const robot_costmap_2d::DirectionGeometry geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(),
|
||||
grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()};
|
||||
const auto decision = decideDirection(direction_snapshot, have_previous_direction_, previous_direction_state_,
|
||||
previous_direction_generation_, geometry);
|
||||
using DirectionResult = DirectionDecision::Result;
|
||||
direction_scratch_pending_ = direction_scratch_pending_ || decision.force_scratch;
|
||||
have_previous_direction_ = true;
|
||||
previous_direction_state_ = direction_snapshot.state;
|
||||
previous_direction_generation_ = direction_snapshot.generation;
|
||||
if (decision.result == DirectionResult::kGeometryMismatch) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (last_direction_geometry_log_ == std::chrono::steady_clock::time_point{} ||
|
||||
now - last_direction_geometry_log_ >= std::chrono::seconds(5)) {
|
||||
robot::log_error("[sbpl_lattice_planner] direction field geometry does not match the active grid");
|
||||
last_direction_geometry_log_ = now;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
last_direction_geometry_log_ = {};
|
||||
if (decision.result == DirectionResult::kReady &&
|
||||
direction_snapshot.field->maxDeviationRad() != env_->tableMaxDeviationRad()) {
|
||||
const double old_deviation = env_->tableMaxDeviationRad();
|
||||
const double new_deviation = direction_snapshot.field->maxDeviationRad();
|
||||
bool rebuilt = false;
|
||||
try {
|
||||
rebuilt = env_->buildDirectionTable(new_deviation);
|
||||
} catch (const std::exception& e) {
|
||||
robot::log_error("[sbpl_lattice_planner] direction table rebuild exception: %s", e.what());
|
||||
}
|
||||
if (!rebuilt) {
|
||||
robot::log_error("[sbpl_lattice_planner] direction table rebuild failed; refusing to plan");
|
||||
env_->setDirectionField(nullptr);
|
||||
direction_scratch_pending_ = true;
|
||||
return false;
|
||||
}
|
||||
robot::log_info("[sbpl_lattice_planner] direction table max deviation changed %.3f -> %.3f deg",
|
||||
old_deviation * 180.0 / M_PI, new_deviation * 180.0 / M_PI);
|
||||
direction_scratch_pending_ = true;
|
||||
}
|
||||
env_->setDirectionField(decision.result == DirectionResult::kReady ? direction_snapshot.field.get() : nullptr);
|
||||
if (direction_scratch_pending_) {
|
||||
planner_->force_planning_from_scratch();
|
||||
direction_scratch_pending_ = false;
|
||||
}
|
||||
|
||||
plan.clear();
|
||||
@@ -980,6 +1075,20 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
// plan_pub_.publish(gui_path);
|
||||
// publishStats(solution_cost, sbpl_path.size(), start, goal);
|
||||
|
||||
// The search and realignment use one immutable snapshot. Refuse to hand off a path
|
||||
// for an older map or field when the provider changed while planning.
|
||||
const auto handoff_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot();
|
||||
const bool both_disabled = direction_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled &&
|
||||
handoff_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled;
|
||||
if (!both_disabled && (direction_snapshot.state != handoff_snapshot.state ||
|
||||
direction_snapshot.generation != handoff_snapshot.generation)) {
|
||||
plan.clear();
|
||||
robot::log_warning("[sbpl_lattice_planner] direction field changed during planning "
|
||||
"(generation %llu -> %llu); discarding path",
|
||||
static_cast<unsigned long long>(direction_snapshot.generation),
|
||||
static_cast<unsigned long long>(handoff_snapshot.generation));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
7
test/data/README.md
Normal file
7
test/data/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
`unicycle_0125.mprim` is derived from this package's
|
||||
`matlab/mprim/unicycle_5cm_expensive_turn_in_place.mprim`. Its resolution was
|
||||
scaled from 0.05 m to 0.125 m, and each x/y sample was rounded to 1/4096 cell.
|
||||
Thus sample coordinates and source translations are exactly representable in
|
||||
binary, including grid-boundary ties in the table-versus-DDA test. Primitive
|
||||
indices, headings, end cells and action multipliers are unchanged. This fixture
|
||||
is for tests only; it is not a robot motion model.
|
||||
1683
test/data/unicycle_0125.mprim
Normal file
1683
test/data/unicycle_0125.mprim
Normal file
File diff suppressed because it is too large
Load Diff
215
test/direction_environment_test.cpp
Normal file
215
test/direction_environment_test.cpp
Normal file
@@ -0,0 +1,215 @@
|
||||
#include <sbpl_lattice_planner/directional_environment.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <sbpl/planners/araplanner.h>
|
||||
#include <sbpl/utils/key.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using sbpl_lattice_planner::DirectionalEnvironmentNAVXYTHETALAT;
|
||||
using robot_costmap_2d::DirectionField;
|
||||
using robot_costmap_2d::DirectionFieldSnapshot;
|
||||
using robot_costmap_2d::DirectionFieldState;
|
||||
using robot_costmap_2d::DirectionGeometry;
|
||||
constexpr double kResolution = 0.125;
|
||||
constexpr int kWidth = 50, kHeight = 35;
|
||||
using Masks = std::map<std::pair<int64_t, int64_t>, uint8_t>;
|
||||
|
||||
DirectionGeometry geometry() { return {kWidth, kHeight, kResolution, 0, 0, "map"}; }
|
||||
robot_nav_msgs::OccupancyGrid grid()
|
||||
{
|
||||
robot_nav_msgs::OccupancyGrid g;
|
||||
g.header.frame_id = "map";
|
||||
g.info.width = kWidth; g.info.height = kHeight; g.info.resolution = kResolution;
|
||||
g.data.assign(kWidth * kHeight, 0);
|
||||
return g;
|
||||
}
|
||||
std::shared_ptr<const DirectionField> makeField(const robot_nav_msgs::OccupancyGrid& g)
|
||||
{ return DirectionField::create(g, geometry(), M_PI / 2.0); }
|
||||
|
||||
class DirectionEnvironmentTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
DirectionalEnvironmentNAVXYTHETALAT env;
|
||||
void SetUp() override
|
||||
{
|
||||
std::vector<sbpl_2Dpt_t> footprint;
|
||||
ASSERT_TRUE(env.InitializeEnv(kWidth, kHeight, nullptr, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
footprint, kResolution, 1.0, 1.0, 254, DIRECTION_TEST_MPRIM));
|
||||
ASSERT_TRUE(env.buildDirectionTable(M_PI / 2.0));
|
||||
}
|
||||
EnvNAVXYTHETALATAction_t* action(int theta, int dx, int dy, bool rotation = false)
|
||||
{
|
||||
for (int i = 0; i < env.actionWidth(); ++i) {
|
||||
auto& a = const_cast<EnvNAVXYTHETALATAction_t&>(env.action(theta, i));
|
||||
if (a.dX == dx && a.dY == dy && (!rotation || a.endtheta != a.starttheta)) return &a;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
// Coordinates in this rescaled copy are exact multiples of 1/4096 cell, so translating
|
||||
// to large source indices does not introduce new binary rounding at grid boundaries.
|
||||
TEST_F(DirectionEnvironmentTest, TableMatchesDirectTraversalAtMultipleSources)
|
||||
{
|
||||
for (int theta = 0; theta < env.thetaCount(); ++theta) {
|
||||
for (int a = 0; a < env.actionWidth(); ++a) {
|
||||
const auto& p = env.action(theta, a).intermptV;
|
||||
for (const auto& source : {std::make_pair(0, 0), std::make_pair(37, 19), std::make_pair(1000000, 800000)}) {
|
||||
Masks reference, actual;
|
||||
for (size_t i = 1; i < p.size(); ++i) {
|
||||
const double dx = p[i].x - p[i-1].x, dy = p[i].y - p[i-1].y;
|
||||
if (dx == 0 && dy == 0) continue;
|
||||
const uint8_t mask = robot_costmap_2d::allowedDirectionMask(dx, dy, M_PI / 2.0);
|
||||
ASSERT_TRUE(robot_costmap_2d::traverseGridSegment(source.first + 0.5 + p[i-1].x/kResolution,
|
||||
source.second + 0.5 + p[i-1].y/kResolution, source.first + 0.5 + p[i].x/kResolution,
|
||||
source.second + 0.5 + p[i].y/kResolution, [&](int64_t x, int64_t y) {
|
||||
auto entry = reference.emplace(std::make_pair(x-source.first, y-source.second), mask);
|
||||
if (!entry.second) entry.first->second &= mask;
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
const size_t index = theta * env.actionWidth() + a;
|
||||
for (size_t i = env.offsets()[index]; i < env.offsets()[index+1]; ++i) {
|
||||
const auto& c = env.cells()[i]; actual[{c.dx, c.dy}] = c.mask;
|
||||
}
|
||||
EXPECT_EQ(reference, actual) << theta << "," << a << " source " << source.first;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DirectionEnvironmentTest, ActionCostsRespectDisplacementAndObstacles)
|
||||
{
|
||||
auto* forward = action(0, 1, 0); auto* reverse = action(0, -1, 0); auto* turn = action(0, 0, 0, true);
|
||||
auto* long_forward = action(0, 8, 0);
|
||||
ASSERT_TRUE(forward && reverse && turn && long_forward);
|
||||
const int base = env.GetActionCost(20, 15, 0, forward);
|
||||
ASSERT_LT(base, INFINITECOST);
|
||||
auto g = grid();
|
||||
std::fill(g.data.begin(), g.data.end(), 1); // east
|
||||
auto east = makeField(g); ASSERT_TRUE(east); env.setDirectionField(east.get());
|
||||
EXPECT_EQ(base, env.GetActionCost(20, 15, 0, forward));
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, reverse), INFINITECOST);
|
||||
EXPECT_LT(env.GetActionCost(20, 15, 0, turn), INFINITECOST);
|
||||
std::fill(g.data.begin(), g.data.end(), 5); // west
|
||||
auto west = makeField(g); ASSERT_TRUE(west); env.setDirectionField(west.get());
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
EXPECT_LT(env.GetActionCost(20, 15, 0, reverse), INFINITECOST);
|
||||
std::fill(g.data.begin(), g.data.end(), 0);
|
||||
g.data[15*kWidth + 24] = 5; // Neither endpoint is in this clipped cell.
|
||||
auto clip = makeField(g); ASSERT_TRUE(clip); env.setDirectionField(clip.get());
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, long_forward), INFINITECOST);
|
||||
env.UpdateCost(21, 15, 254);
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
env.UpdateCost(21, 15, 0);
|
||||
env.setDirectionField(nullptr);
|
||||
EXPECT_EQ(base, env.GetActionCost(20, 15, 0, forward));
|
||||
// A narrower field makes a base-valid action leave the direction grid.
|
||||
auto small_g = grid(); small_g.info.width = 21; small_g.data.assign(21*kHeight, 0);
|
||||
auto small_geo = geometry(); small_geo.width = 21;
|
||||
auto small = DirectionField::create(small_g, small_geo, M_PI / 2.0); ASSERT_TRUE(small);
|
||||
env.setDirectionField(small.get());
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
env.setDirectionField(nullptr);
|
||||
}
|
||||
|
||||
TEST_F(DirectionEnvironmentTest, RebuildChangesPerpendicularActionCost)
|
||||
{
|
||||
auto* forward = action(0, 1, 0);
|
||||
ASSERT_TRUE(forward);
|
||||
auto g = grid();
|
||||
std::fill(g.data.begin(), g.data.end(), 3); // +Y zone.
|
||||
const auto wide = makeField(g);
|
||||
const auto narrow = DirectionField::create(g, geometry(), M_PI / 4.0);
|
||||
ASSERT_TRUE(wide && narrow);
|
||||
env.setDirectionField(wide.get());
|
||||
EXPECT_LT(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
ASSERT_TRUE(env.buildDirectionTable(narrow->maxDeviationRad()));
|
||||
EXPECT_DOUBLE_EQ(env.tableMaxDeviationRad(), M_PI / 4.0);
|
||||
env.setDirectionField(narrow.get());
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
EXPECT_FALSE(env.buildDirectionTable(0));
|
||||
EXPECT_DOUBLE_EQ(env.tableMaxDeviationRad(), M_PI / 4.0);
|
||||
EXPECT_GE(env.GetActionCost(20, 15, 0, forward), INFINITECOST);
|
||||
env.setDirectionField(nullptr);
|
||||
}
|
||||
|
||||
TEST(DirectionDecisionTest, StatesGeometryAndGeneration)
|
||||
{
|
||||
using sbpl_lattice_planner::decideDirection;
|
||||
using R = sbpl_lattice_planner::DirectionDecision::Result;
|
||||
DirectionFieldSnapshot s;
|
||||
EXPECT_EQ(decideDirection(s, true, s.state, 0, geometry()).result, R::kDisabled);
|
||||
s.state = DirectionFieldState::kPending;
|
||||
EXPECT_EQ(decideDirection(s, true, DirectionFieldState::kDisabled, 0, geometry()).result, R::kPending);
|
||||
s.state = DirectionFieldState::kReady; s.field = makeField(grid()); s.generation = 2;
|
||||
ASSERT_TRUE(s.field);
|
||||
auto different = geometry(); different.origin_x = 0.01;
|
||||
EXPECT_EQ(decideDirection(s, true, s.state, 1, different).result, R::kGeometryMismatch);
|
||||
for (int axis = 0; axis < 4; ++axis) {
|
||||
different = geometry();
|
||||
if (axis == 0) ++different.width;
|
||||
if (axis == 1) ++different.height;
|
||||
if (axis == 2) different.resolution += 0.01;
|
||||
if (axis == 3) different.origin_y += 0.01;
|
||||
EXPECT_EQ(decideDirection(s, true, s.state, 1, different).result, R::kGeometryMismatch);
|
||||
}
|
||||
EXPECT_TRUE(decideDirection(s, true, DirectionFieldState::kPending, 2, geometry()).force_scratch);
|
||||
EXPECT_TRUE(decideDirection(s, true, s.state, 1, geometry()).force_scratch);
|
||||
EXPECT_FALSE(decideDirection(s, true, s.state, 2, geometry()).force_scratch);
|
||||
EXPECT_EQ(decideDirection(s, true, s.state, 2, geometry()).result, R::kReady);
|
||||
}
|
||||
|
||||
TEST_F(DirectionEnvironmentTest, SearchDetoursAndReplansForBothSearchDirections)
|
||||
{
|
||||
// The near passage permits eastward travel only; the far passage remains unconstrained.
|
||||
for (int x = 22; x <= 26; ++x)
|
||||
for (int y = 0; y < kHeight; ++y)
|
||||
if (!((y >= 6 && y <= 10) || (y >= 24 && y <= 28))) env.UpdateCost(x, y, 254);
|
||||
auto g = grid();
|
||||
for (int x = 20; x <= 28; ++x)
|
||||
for (int y = 4; y <= 12; ++y) g.data[y*kWidth+x] = 1;
|
||||
auto east = makeField(g); ASSERT_TRUE(east);
|
||||
for (bool forward_search : {true, false}) {
|
||||
// SBPL planners store their state index in the environment and clear it only in
|
||||
// force_planning_from_scratch(), not in the destructor. A second planner on the same
|
||||
// environment would read the first planner's indices into its own empty state array.
|
||||
for (int* row : env.StateID2IndexMapping)
|
||||
std::fill(row, row + NUMOFINDICES_STATEID2IND, -1);
|
||||
ARAPlanner planner(&env, forward_search);
|
||||
planner.set_initialsolution_eps(1.0);
|
||||
planner.set_search_mode(true);
|
||||
const int start = env.SetStart(38.5*kResolution, 8.5*kResolution, 0);
|
||||
const int goal = env.SetGoal(10.5*kResolution, 8.5*kResolution, 0);
|
||||
ASSERT_GE(start, 0); ASSERT_GE(goal, 0);
|
||||
ASSERT_EQ(planner.set_start(start), 1); ASSERT_EQ(planner.set_goal(goal), 1);
|
||||
auto solve = [&]() {
|
||||
std::vector<int> states; std::vector<EnvNAVXYTHETALAT3Dpt_t> path;
|
||||
const int ok = planner.replan(10.0, &states);
|
||||
if (ok) env.ConvertStateIDPathintoXYThetaPath(&states, &path);
|
||||
return path;
|
||||
};
|
||||
env.setDirectionField(nullptr);
|
||||
const auto direct = solve(); ASSERT_FALSE(direct.empty());
|
||||
EXPECT_LT(std::max_element(direct.begin(), direct.end(), [](const auto& a, const auto& b) {
|
||||
return a.y < b.y; })->y, 20*kResolution);
|
||||
env.setDirectionField(east.get()); planner.force_planning_from_scratch();
|
||||
const auto detour = solve(); ASSERT_FALSE(detour.empty());
|
||||
EXPECT_GT(std::max_element(detour.begin(), detour.end(), [](const auto& a, const auto& b) {
|
||||
return a.y < b.y; })->y, 20*kResolution);
|
||||
for (int x = 22; x <= 26; ++x) for (int y = 24; y <= 28; ++y) env.UpdateCost(x, y, 254);
|
||||
planner.force_planning_from_scratch();
|
||||
EXPECT_TRUE(solve().empty());
|
||||
for (int x = 22; x <= 26; ++x) for (int y = 24; y <= 28; ++y) env.UpdateCost(x, y, 0);
|
||||
env.setDirectionField(nullptr);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
Reference in New Issue
Block a user