From 52089a0e90877f07e63d84ec17cdf5b987bdd871 Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 4 Nov 2026 08:52:00 +0700 Subject: [PATCH] feat(directional_layer): make the allowed deviation configurable Add max_deviation_deg (default 90, valid 0 < x < 180). The field carries the value so checkSegment and every planner use the same rule. 90 keeps the previous masks bit for bit; out-of-range values stop the layer from initialising. --- config/directional_layer_params.yaml | 9 +++ include/robot_costmap_2d/direction_field.h | 13 +++- include/robot_costmap_2d/directional_layer.h | 1 + plugins/directional_layer.cpp | 23 ++++++-- src/direction_field.cpp | 24 +++++--- test/direction_field_test.cpp | 62 ++++++++++++++++++-- test/directional_layer_test.cpp | 35 ++++++++++- 7 files changed, 147 insertions(+), 20 deletions(-) diff --git a/config/directional_layer_params.yaml b/config/directional_layer_params.yaml index 58f02ea..191b66b 100644 --- a/config/directional_layer_params.yaml +++ b/config/directional_layer_params.yaml @@ -11,5 +11,14 @@ directional_layer: map_topic: "map" # Topic grid hướng: đổi theo tên host gửi; phải khác map_topic. direction_topic: "direction_map" + # [deg] Góc lệch tối đa giữa hướng di chuyển và hướng zone, tính cả biên. + # Áp chung cho mọi zone. 90 = được đi mọi hướng có thành phần cùng chiều zone + # (đi ngang zone được, đi ngược bị cấm). + # Giảm: robot phải đi sát hướng zone hơn, cấm cắt ngang làn, phải căn hướng + # trước khi vào zone; quay tại chỗ luôn được phép. Dưới 22.5 (bước heading của + # mprim 16 hướng) SBPL có thể không tìm được đường. + # Tăng quá 90: cho phép cả hướng hơi ngược chiều zone, zone một chiều yếu đi. + # Phạm vi hợp lệ: 0 < giá trị < 180; ngoài phạm vi nav core từ chối khởi động. + max_deviation_deg: 90.0 # Bật để ghi log chuyển trạng thái; tắt để giảm log bình thường. debug_state: true diff --git a/include/robot_costmap_2d/direction_field.h b/include/robot_costmap_2d/direction_field.h index 4a40fe9..4315d78 100644 --- a/include/robot_costmap_2d/direction_field.h +++ b/include/robot_costmap_2d/direction_field.h @@ -118,9 +118,10 @@ bool traverseGridSegment(double x0, double y0, double x1, double y1, Visitor&& v /** @brief Return allowed direction indices for a displacement. * @param dx Displacement along +X [m or cells] in the global/grid frame. * @param dy Displacement along +Y [same units as dx] in the global/grid frame. - * @return Bit k is set when dot(v_k, displacement) is nonnegative within sign tolerance. + * @param max_deviation_rad Maximum inclusive angular deviation [rad], in (0, pi). + * @return Bit k is set when direction k accepts the displacement within relative tolerance. */ -uint8_t allowedDirectionMask(double dx, double dy); +uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad); /** @brief Outcome of a world-space segment query. */ enum class SegmentResult @@ -148,10 +149,12 @@ public: /** @brief Validate and construct a field; invalid input returns null. * @param grid Complete direction message in the global frame. * @param expected Master grid geometry in the global frame. + * @param max_deviation_rad Maximum inclusive deviation [rad], in (0, pi). * @param result Optional output explaining validation success or failure. */ static std::shared_ptr create(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& expected, + double max_deviation_rad, DirectionValidationResult* result = nullptr); /** @brief Return cell code: 0 unconstrained, 1..8 direction_index + 1. @@ -171,6 +174,8 @@ public: /** @brief Return the immutable master geometry and global frame. */ const DirectionGeometry& geometry() const { return geometry_; } + /** @brief Return the immutable maximum angular deviation [rad]. */ + double maxDeviationRad() const { return max_deviation_rad_; } /** @brief True if at least one cell has a nonzero direction code. */ bool hasConstraints() const { return has_constraints_; } @@ -186,9 +191,11 @@ public: SegmentViolation* first = nullptr) const; private: - DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry); + DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry, + double max_deviation_rad); DirectionGeometry geometry_; std::vector codes_; + double max_deviation_rad_; bool has_constraints_; }; diff --git a/include/robot_costmap_2d/directional_layer.h b/include/robot_costmap_2d/directional_layer.h index 3dd86f6..703a870 100644 --- a/include/robot_costmap_2d/directional_layer.h +++ b/include/robot_costmap_2d/directional_layer.h @@ -65,6 +65,7 @@ private: bool seen_map_; bool debug_state_; bool rolling_; + double max_deviation_rad_; ///< Maximum angular deviation [rad]. std::string map_topic_, direction_topic_; std::chrono::steady_clock::time_point pending_since_, last_pending_log_; }; diff --git a/plugins/directional_layer.cpp b/plugins/directional_layer.cpp index d5b9c11..e18e506 100644 --- a/plugins/directional_layer.cpp +++ b/plugins/directional_layer.cpp @@ -48,7 +48,7 @@ const char* stateName(DirectionFieldState state) } // namespace DirectionalLayer::DirectionalLayer() - : Layer(), mutex_(), snapshot_(), seen_map_(false), debug_state_(true), rolling_(false), + : Layer(), mutex_(), snapshot_(), seen_map_(false), debug_state_(true), rolling_(false), max_deviation_rad_(M_PI / 2.0), map_topic_("map"), direction_topic_("direction_map"), pending_since_(), last_pending_log_() { } @@ -58,6 +58,7 @@ void DirectionalLayer::onInitialize() robot::NodeHandle nh("~"); robot::NodeHandle priv_nh(nh, name_); const std::string filename = "directional_layer_params.yaml"; + double max_deviation_deg = 90.0; try { const char* env = std::getenv("PNKX_NAV_CORE_CONFIG_DIR"); @@ -66,6 +67,7 @@ void DirectionalLayer::onInitialize() enabled_ = loadParam(layer, "enabled", false); map_topic_ = loadParam(layer, "map_topic", std::string("map")); direction_topic_ = loadParam(layer, "direction_topic", std::string("direction_map")); + max_deviation_deg = loadParam(layer, "max_deviation_deg", 90.0); debug_state_ = loadParam(layer, "debug_state", true); if (priv_nh.hasParam("enabled")) priv_nh.getParam("enabled", enabled_, enabled_); @@ -73,6 +75,8 @@ void DirectionalLayer::onInitialize() priv_nh.getParam("map_topic", map_topic_); if (priv_nh.hasParam("direction_topic")) priv_nh.getParam("direction_topic", direction_topic_); + if (priv_nh.hasParam("max_deviation_deg")) + priv_nh.getParam("max_deviation_deg", max_deviation_deg); if (priv_nh.hasParam("debug_state")) priv_nh.getParam("debug_state", debug_state_); } @@ -80,14 +84,24 @@ void DirectionalLayer::onInitialize() { throw std::runtime_error("DirectionalLayer " + name_ + ": cannot open the default file " + filename); } + if (!std::isfinite(max_deviation_deg) || max_deviation_deg <= 0.0 || max_deviation_deg >= 180.0) + throw std::runtime_error("DirectionalLayer " + name_ + ": max_deviation_deg must be finite and in (0, 180)"); + if (max_deviation_deg < 22.5) + robot::log_warning("DirectionalLayer %s: max_deviation_deg < 22.5 may leave SBPL without a path", name_.c_str()); + max_deviation_rad_ = (max_deviation_deg / 180.0) * M_PI; + // Preserve the open interval even when conversion rounds at an extreme value. + if (max_deviation_rad_ <= 0.0) + max_deviation_rad_ = std::nextafter(0.0, M_PI); + else if (max_deviation_rad_ >= M_PI) + max_deviation_rad_ = std::nextafter(M_PI, 0.0); rolling_ = layered_costmap_->isRolling(); if (enabled_ && rolling_) robot::log_error("DirectionalLayer %s: rolling costmap is unsupported", name_.c_str()); if (enabled_ && (map_topic_.empty() || direction_topic_.empty() || topicMatches(map_topic_, direction_topic_) || topicMatches(direction_topic_, map_topic_))) throw std::runtime_error("DirectionalLayer " + name_ + ": topics must be nonempty and distinct"); - robot::log_info("DirectionalLayer %s: enabled=%d map_topic=%s direction_topic=%s debug_state=%d", - name_.c_str(), enabled_, map_topic_.c_str(), direction_topic_.c_str(), debug_state_); + robot::log_info("DirectionalLayer %s: enabled=%d map_topic=%s direction_topic=%s max_deviation_deg=%g debug_state=%d", + name_.c_str(), enabled_, map_topic_.c_str(), direction_topic_.c_str(), max_deviation_deg, debug_state_); std::lock_guard lock(mutex_); publishLocked(enabled_ ? DirectionFieldState::kPending : DirectionFieldState::kDisabled); } @@ -152,7 +166,8 @@ void DirectionalLayer::handleImpl(const void* data, const std::type_info& type, generation = snapshot_.generation; } DirectionValidationResult validation; - auto field = DirectionField::create(*static_cast(data), expected, &validation); + auto field = DirectionField::create(*static_cast(data), expected, + max_deviation_rad_, &validation); if (!field) { robot::log_error("DirectionalLayer %s: invalid direction grid: %s", name_.c_str(), validation.message.c_str()); diff --git a/src/direction_field.cpp b/src/direction_field.cpp index 0e8a4ea..cd1014b 100644 --- a/src/direction_field.cpp +++ b/src/direction_field.cpp @@ -73,31 +73,41 @@ DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyG return {DirectionValidationError::kNone, "valid"}; } -uint8_t allowedDirectionMask(double dx, double dy) +uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad) { if (!std::isfinite(dx) || !std::isfinite(dy)) return 0; constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1}; constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1}; - const long double tolerance = - 1e-9L * (std::abs(static_cast(dx)) + std::abs(static_cast(dy))); + const long double x = dx, y = dy; + const bool legacy_right_angle = max_deviation_rad == M_PI / 2.0; + const long double length = std::hypot(x, y); + const long double threshold = (std::cos(max_deviation_rad) - 1e-9L) * length; + const long double legacy_tolerance = 1e-9L * (std::abs(x) + std::abs(y)); + constexpr long double kInverseSqrtTwo = 0.707106781186547524400844362104849L; uint8_t mask = 0; for (int k = 0; k < 8; ++k) { - if (vx[k] * static_cast(dx) + vy[k] * static_cast(dy) >= -tolerance) + const long double dot = vx[k] * x + vy[k] * y; + // Preserve the exact legacy tolerance at 90 degrees, including near-boundary inputs. + if (legacy_right_angle ? dot >= -legacy_tolerance : + dot * (k % 2 ? kInverseSqrtTwo : 1.0L) >= threshold) mask |= uint8_t(1u << k); } return mask; } -DirectionField::DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry) +DirectionField::DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry, + double max_deviation_rad) : geometry_(geometry), codes_(grid.data.begin(), grid.data.end()), + max_deviation_rad_(max_deviation_rad), has_constraints_(std::any_of(codes_.begin(), codes_.end(), [](uint8_t c) { return c != 0; })) { } std::shared_ptr DirectionField::create(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& expected, + double max_deviation_rad, DirectionValidationResult* result) { auto validation = validateDirectionGrid(grid, expected); @@ -105,7 +115,7 @@ std::shared_ptr DirectionField::create(const robot_nav_msg *result = validation; if (!validation) return {}; - return std::shared_ptr(new DirectionField(grid, expected)); + return std::shared_ptr(new DirectionField(grid, expected, max_deviation_rad)); } uint8_t DirectionField::code(uint32_t x, uint32_t y) const @@ -143,7 +153,7 @@ SegmentResult DirectionField::checkSegment(double wx0, double wy0, double wx1, d if (!std::isfinite(dx) || !std::isfinite(dy)) return SegmentResult::kOutOfGrid; - const uint8_t mask = allowedDirectionMask(dx, dy); + const uint8_t mask = allowedDirectionMask(dx, dy, max_deviation_rad_); SegmentResult result = SegmentResult::kAllowed; const bool completed = traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y) { diff --git a/test/direction_field_test.cpp b/test/direction_field_test.cpp index ee603ef..bb2ead9 100644 --- a/test/direction_field_test.cpp +++ b/test/direction_field_test.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -29,7 +30,7 @@ robot_nav_msgs::OccupancyGrid grid() auto field(const robot_nav_msgs::OccupancyGrid& g) { - return DirectionField::create(g, geometry()); + return DirectionField::create(g, geometry(), M_PI / 2.0); } using Cell = std::pair; @@ -170,8 +171,8 @@ TEST(DirectionRule, AllDirectionsAndBoundaries) auto f = field(g); EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 - 1e-6, 1.7), SegmentResult::kViolation); EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 + 1e-6, 1.7), SegmentResult::kAllowed); - EXPECT_EQ(allowedDirectionMask(-1e-11, 1.0) & 1, 1); - EXPECT_EQ(allowedDirectionMask(-1e-6, 1.0) & 1, 0); + EXPECT_EQ(allowedDirectionMask(-1e-11, 1.0, M_PI / 2.0) & 1, 1); + EXPECT_EQ(allowedDirectionMask(-1e-6, 1.0, M_PI / 2.0) & 1, 0); } TEST(DirectionRule, MaskMatchesDotProducts) @@ -182,13 +183,66 @@ TEST(DirectionRule, MaskMatchesDotProducts) { for (int y = -12; y <= 12; ++y) { - auto mask = allowedDirectionMask(x, y); + auto mask = allowedDirectionMask(x, y, M_PI / 2.0); for (int k = 0; k < 8; ++k) EXPECT_EQ(bool(mask & (1u << k)), vx[k] * x + vy[k] * y >= 0); } } } +TEST(DirectionRule, RightAngleMatchesLegacySweep) +{ + constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1}; + constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1}; + const auto check = [&](double dx, double dy) + { + uint8_t reference = 0; + const long double x = dx, y = dy; + const long double tolerance = 1e-9L * (std::abs(x) + std::abs(y)); + for (int k = 0; k < 8; ++k) + if (vx[k] * x + vy[k] * y >= -tolerance) + reference |= uint8_t(1u << k); + EXPECT_EQ(allowedDirectionMask(dx, dy, M_PI / 2.0), reference) << dx << "," << dy; + }; + for (double magnitude : {1e-100, 0.01, 1.0, 1e100}) + { + for (int degree = 0; degree < 360; ++degree) + check(magnitude * std::cos(degree * M_PI / 180.0), magnitude * std::sin(degree * M_PI / 180.0)); + for (int k = 0; k < 8; ++k) + check(magnitude * vx[k], magnitude * vy[k]); + check(-1.0000000005e-9 * magnitude, magnitude); // Near the legacy tolerance boundary. + } + check(0, 0); + EXPECT_EQ(allowedDirectionMask(std::numeric_limits::infinity(), 0, M_PI / 2.0), 0); + EXPECT_EQ(allowedDirectionMask(0, std::numeric_limits::quiet_NaN(), M_PI / 2.0), 0); +} + +TEST(DirectionRule, ConfigurableAngularBoundaries) +{ + const auto mask = allowedDirectionMask(1, 0.5, M_PI / 4.0); + EXPECT_NE(mask & (1u << 0), 0); + EXPECT_NE(mask & (1u << 1), 0); + EXPECT_EQ(mask & (1u << 2), 0); + const auto boundary = allowedDirectionMask(1, 1, M_PI / 4.0); + EXPECT_NE(boundary & (1u << 0), 0); + EXPECT_NE(boundary & (1u << 2), 0); + EXPECT_EQ(allowedDirectionMask(1, 1.01, M_PI / 4.0) & 1u, 0); + EXPECT_EQ(allowedDirectionMask(0, 1, M_PI / 6.0) & 1u, 0); + EXPECT_EQ(allowedDirectionMask(0, 0, M_PI / 6.0), 255); +} + +TEST(DirectionRule, FieldUsesItsDeviationForCrossing) +{ + auto g = grid(); + g.data.assign(16, 3); // +Y zone, crossed along +X. + const auto wide = DirectionField::create(g, geometry(), M_PI / 2.0); + const auto narrow = DirectionField::create(g, geometry(), M_PI / 4.0); + ASSERT_TRUE(wide && narrow); + EXPECT_DOUBLE_EQ(narrow->maxDeviationRad(), M_PI / 4.0); + EXPECT_EQ(wide->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kAllowed); + EXPECT_EQ(narrow->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kViolation); +} + TEST(DirectionDDA, OwnedEdgesCornersEndpointsAndReverse) { EXPECT_EQ(cells(1, 0.2, 1, 2.8), (std::vector{{1, 0}, {1, 1}, {1, 2}})); diff --git a/test/directional_layer_test.cpp b/test/directional_layer_test.cpp index 703df3f..00360be 100644 --- a/test/directional_layer_test.cpp +++ b/test/directional_layer_test.cpp @@ -2,11 +2,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include @@ -51,11 +53,12 @@ protected: std::filesystem::remove_all(directory_); } - void config(bool enabled) + void config(bool enabled, double max_deviation_deg = 90.0) { std::ofstream out(directory_ + "/config/directional_layer_params.yaml"); out << "directional_layer:\n enabled: " << (enabled ? "true" : "false") - << "\n map_topic: map\n direction_topic: direction_map\n debug_state: false\n"; + << "\n map_topic: map\n direction_topic: direction_map\n max_deviation_deg: " << max_deviation_deg + << "\n debug_state: false\n"; } robot_nav_msgs::OccupancyGrid grid() @@ -70,6 +73,34 @@ protected: } }; +TEST_F(LayerTest, InvalidMaxDeviationThrows) +{ + for (double degrees : {0.0, 180.0, -5.0, 200.0}) + { + config(true, degrees); + LayeredCostmap master("map", false, false); + master.resizeMap(4, 4, 1, 0, 0); + DirectionalLayer layer; + EXPECT_THROW(layer.initialize(&master, "directional", &tf_), std::runtime_error) << degrees; + } +} + +TEST_F(LayerTest, ReadyFieldCarriesConfiguredDeviation) +{ + config(true, 45.0); + LayeredCostmap master("map", false, false); + master.resizeMap(4, 4, 1, 0, 0); + DirectionalLayer layer; + ASSERT_NO_THROW(layer.initialize(&master, "directional", &tf_)); + auto g = grid(); + layer.dataCallBack(g, "map"); + layer.dataCallBack(g, "direction_map"); + const auto snapshot = layer.directionSnapshot(); + ASSERT_EQ(snapshot.state, DirectionFieldState::kReady); + ASSERT_TRUE(snapshot.field); + EXPECT_DOUBLE_EQ(snapshot.field->maxDeviationRad(), M_PI / 4.0); +} + TEST_F(LayerTest, LifecycleAndProvider) { LayeredCostmap master("map", false, false);