From 0c2179fe54654ec338e4d436d696161268d896b7 Mon Sep 17 00:00:00 2001 From: duongtd Date: Mon, 9 Nov 2026 13:44:17 +0700 Subject: [PATCH] feat(lane_route): add lane_route_core and lane_route_planner (R0 + R1) lane_route_core plans on a precomputed coarse graph (Voronoi ridges and direction-zone lanes) and, when enabled, falls back to a weighted A* search over an SE(2) lattice that enforces forward motion, the minimum turn radius, end-only spins, the footprint gap and direction zones. - R0: route_planner.cpp split into graph search, path building and the graph tier; regress7 output identical to the previous build. - R1: lattice tier (lazy packed C-space tiles, direction-aware heuristic field, analytic Dubins and point connectors, end-gap floors counting unknown cells). Off by default (lattice_enabled = false). - lane_route_eval takes an optional tier mode and LANE_ROUTE_EVAL_SET overrides for offline tuning. Local snapshot for history only; not pushed. --- CMakeLists.txt | 99 +++ README.md | 24 + .../lane_route_planner/lane_route_planner.h | 64 ++ .../lane_route_planner/lane_route_session.h | 142 +++++ package.xml | 20 + src/lane_route_planner.cpp | 286 +++++++++ src/lane_route_session.cpp | 323 ++++++++++ test/lane_route_planner_test.cpp | 583 ++++++++++++++++++ 8 files changed, 1541 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 include/lane_route_planner/lane_route_planner.h create mode 100644 include/lane_route_planner/lane_route_session.h create mode 100644 package.xml create mode 100644 src/lane_route_planner.cpp create mode 100644 src/lane_route_session.cpp create mode 100644 test/lane_route_planner_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..af38616 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,99 @@ +cmake_minimum_required(VERSION 3.0.2) +project(lane_route_planner VERSION 0.1.0 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + find_package(catkin REQUIRED COMPONENTS + lane_route_core + robot_costmap_2d + robot_nav_core + robot_cpp + robot_geometry_msgs + robot_nav_msgs + robot_protocol_msgs + data_convert + robot_time + ) + catkin_package( + INCLUDE_DIRS include + LIBRARIES lane_route_planner + CATKIN_DEPENDS lane_route_core robot_costmap_2d robot_nav_core robot_cpp robot_geometry_msgs + robot_nav_msgs robot_protocol_msgs data_convert robot_time + ) +else() + set(BUILDING_WITH_CATKIN FALSE) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + # In a standalone workspace these dependencies are targets exported by the parent project. + # Installed dependencies can instead be resolved by the standard include/library search paths. + if(NOT TARGET lane_route_core) + find_path(LANE_ROUTE_CORE_INCLUDE_DIR lane_route_core/route_planner.h) + find_library(LANE_ROUTE_CORE_LIBRARY NAMES lane_route_core) + if(NOT LANE_ROUTE_CORE_INCLUDE_DIR OR NOT LANE_ROUTE_CORE_LIBRARY) + message(FATAL_ERROR "lane_route_core headers and library are required for standalone mode") + endif() + else() + set(LANE_ROUTE_CORE_LIBRARY lane_route_core) + endif() +endif() + +find_package(Boost REQUIRED COMPONENTS system filesystem thread) + +add_library(lane_route_planner SHARED + src/lane_route_planner.cpp + src/lane_route_session.cpp +) +target_include_directories(lane_route_planner PUBLIC + $ + $ + ${catkin_INCLUDE_DIRS} + ${LANE_ROUTE_CORE_INCLUDE_DIR} +) +if(BUILDING_WITH_CATKIN) + target_link_libraries(lane_route_planner + PUBLIC ${catkin_LIBRARIES} + PRIVATE Boost::system Boost::filesystem Boost::thread + ) + add_dependencies(lane_route_planner ${catkin_EXPORTED_TARGETS}) +else() + target_link_libraries(lane_route_planner + PUBLIC ${LANE_ROUTE_CORE_LIBRARY} robot_costmap_2d robot_cpp robot_time + PRIVATE Boost::system Boost::filesystem Boost::thread + ) + # These are header-only in this workspace; link targets only when a parent provides them. + foreach(header_target robot_nav_core robot_geometry_msgs robot_nav_msgs robot_protocol_msgs data_convert) + if(TARGET ${header_target}) + target_link_libraries(lane_route_planner PUBLIC ${header_target}) + endif() + endforeach() +endif() +target_compile_options(lane_route_planner PRIVATE -O3) + +option(BUILD_LANE_ROUTE_PLANNER_TESTS "Build adapter tests" ${BUILDING_WITH_CATKIN}) +if(BUILD_LANE_ROUTE_PLANNER_TESTS) + find_package(GTest REQUIRED) + find_package(Threads REQUIRED) + add_executable(lane_route_planner_test test/lane_route_planner_test.cpp) + target_link_libraries(lane_route_planner_test PRIVATE + lane_route_planner GTest::GTest GTest::Main Threads::Threads + ) +endif() + +if(BUILDING_WITH_CATKIN) + install(TARGETS lane_route_planner + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + install(DIRECTORY include/lane_route_planner DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}) +else() + install(TARGETS lane_route_planner + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin + ) + install(DIRECTORY include/lane_route_planner DESTINATION include) +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..8c23748 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# LaneRoutePlanner + +A `robot_nav_core::BaseGlobalPlanner` and `Preemptable` Boost.DLL plugin using +`lane_route_core` and the immutable `robot_costmap_2d` reference-graph and direction snapshots. +The `LaneRoutePlannerExternalGrid` capability accepts the caller's non-owning snapshot. The caller +must keep that grid alive throughout `makePlan`. A missing, pending or stale graph returns failure; +the navigation host decides whether to try another planner. No planner is selected by this package. + +The cached compiled graphs are dropped when the reference generation, footprint, direction snapshot, +or the exact preferred-cell mask changes. Other master costs are read again at query time. The core +uses the worker's ridge parameters for a live rebuild. `time_limit_s` defaults to 20 seconds. + +Cancellation is checked during graph compilation and core planning. Preferred-region centre-line +extraction does not itself accept cancellation: a request arriving during that call waits until it +returns. It runs only on compilation when the master has preferred cells; its worst-case time is +unmeasured. Live ridge skeleton and graph construction receive the cancellation flag. + +Master cost 100 is interpreted as UNPREFERRED. Inflation can produce exactly 100 under some +parameter sets, causing a small penalty and potentially an extra neutral pass on failure. The +current inflation parameters have not produced that value; no normalization is applied. + +The session tests exercise snapshots and grids without a real Costmap2DROBOT. Plugin loading, +NodeHandle parameter discovery, external-grid lifetime, snapshot synchronization, output headers, +and integration with the navigation host still require runtime validation. diff --git a/include/lane_route_planner/lane_route_planner.h b/include/lane_route_planner/lane_route_planner.h new file mode 100644 index 0000000..352dff1 --- /dev/null +++ b/include/lane_route_planner/lane_route_planner.h @@ -0,0 +1,64 @@ +#ifndef LANE_ROUTE_PLANNER_LANE_ROUTE_PLANNER_H_ +#define LANE_ROUTE_PLANNER_LANE_ROUTE_PLANNER_H_ + +#include +#include +#include +#include + +#include +#include + +#include + +namespace lane_route_planner +{ +/** @brief Boost.DLL global planner adapter. + * initialize(), makePlan() and setExternalGrid() are called on the planner thread. preempt() + * may be called concurrently from another thread and only sets an atomic flag. */ +class LaneRoutePlanner : public robot_nav_core::BaseGlobalPlanner, public robot_nav_core::Preemptable +{ +public: + /** @brief Load and validate configuration and bind the non-owning costmap on the planner thread. */ + bool initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap) override; + + /** @brief Compute a verified plan in the global frame on the planner thread. */ + bool makePlan(const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) override; + + /** @brief Request cancellation from another thread without locking or allocating. */ + void preempt() override + { + preempt_.store(true, std::memory_order_relaxed); + } + + /** @brief Set a non-owning external grid on the planner thread; nullptr selects the live costmap. + * The caller keeps the grid alive through makePlan(). */ + void setExternalGrid(const robot_costmap_2d::Costmap2D* grid) + { + external_grid_ = grid; + } + + /** @brief Create the BaseGlobalPlanner instance exported by Boost.DLL. */ + static robot_nav_core::BaseGlobalPlanner::Ptr create(); + +private: + bool initialized_ = false; + std::atomic preempt_{false}; + robot_costmap_2d::Costmap2DROBOT* costmap_ = nullptr; + const robot_costmap_2d::Costmap2D* external_grid_ = nullptr; + SessionConfig config_; + LaneRouteSession session_; + std::vector previous_footprint_; + bool have_state_ = false; + robot_costmap_2d::ReferenceGraphState graph_state_ = robot_costmap_2d::ReferenceGraphState::kDisabled; + robot_costmap_2d::DirectionFieldState direction_state_ = robot_costmap_2d::DirectionFieldState::kDisabled; + uint64_t graph_generation_ = 0; + uint64_t direction_generation_ = 0; +}; + +/** @brief ExternalGrid Boost.DLL capability; invoke on the planner thread. */ +void setExternalGridOn(robot_nav_core::BaseGlobalPlanner* planner, const robot_costmap_2d::Costmap2D* grid); +} // namespace lane_route_planner + +#endif // LANE_ROUTE_PLANNER_LANE_ROUTE_PLANNER_H_ diff --git a/include/lane_route_planner/lane_route_session.h b/include/lane_route_planner/lane_route_session.h new file mode 100644 index 0000000..7396c1f --- /dev/null +++ b/include/lane_route_planner/lane_route_session.h @@ -0,0 +1,142 @@ +#ifndef LANE_ROUTE_PLANNER_LANE_ROUTE_SESSION_H_ +#define LANE_ROUTE_PLANNER_LANE_ROUTE_SESSION_H_ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace lane_route_planner +{ +/** @brief Tunable parameters; footprint and direction limit are supplied per request by the costmap. */ +struct SessionConfig +{ + lane_route_core::PlannerConfig planner; ///< Core settings, including lengths [m] and angles [deg]. + double clearance_min_margin_m = 0.035; ///< [m] Added to inscribed radius for hard clearance. + double clearance_preferred_margin_m = 0.30; ///< [m] Added to inscribed radius for preferred clearance. + double collision_check_margin_m = 0.056; ///< [m] Added to the bounding rectangle's circumscribed radius. + bool debug_plan = true; ///< Enable plan diagnostics. + bool debug_state = true; ///< Enable state-change diagnostics. + + /** @return Empty when valid; otherwise the invalid key and its value, or the core validation error. */ + std::string validate() const; +}; + +/** @brief Inputs for one planner-thread query. Shared snapshots and live bytes must outlive plan(). */ +struct SessionRequest +{ + bool initialized = false; ///< Whether the adapter completed initialization. + lane_route_core::GridRef live; ///< Non-owning grid; resolution and origin [m]. + std::string frame; ///< Global frame for the grid and poses. + robot_costmap_2d::ReferenceGraphSnapshot graph; ///< Coarse graph and its generation. + robot_costmap_2d::DirectionFieldSnapshot direction; ///< Direction field with limit [rad], and its generation. + std::vector footprint; ///< Padded robot-frame footprint [m]. + double inscribed_radius_m = 0.0; ///< [m] Inscribed radius of the padded footprint. + robot_geometry_msgs::PoseStamped start; ///< Start position [m] and quaternion in frame. + robot_geometry_msgs::PoseStamped goal; ///< Goal position [m] and quaternion in frame. + bool start_has_yaw = true; ///< Constrain the start yaw when true. + bool goal_has_yaw = true; ///< Constrain the goal yaw when true. + const std::atomic* cancel = nullptr; ///< Optional caller-owned flag, set from another thread. +}; + +/** @brief Derive a centered bounding rectangle from a padded footprint. + * @param footprint Robot-frame polygon [m]. + * @param half_x Output maximum absolute X [m]. + * @param half_y Output maximum absolute Y [m]. + * @param centered_rectangle True when the polygon is itself a centered rectangle. + * @return False if the inputs are invalid or the bounds have no area. */ +bool footprintRectangle(const std::vector& footprint, double* half_x, double* half_y, + bool* centered_rectangle); + +/** @brief Check initialization, pose, frame and snapshot state without accessing grid bytes. + * @return Empty when valid, otherwise a distinct failure reason. */ +std::string validateState(const SessionRequest& request); + +/** @brief Check grid geometry, snapshot data and footprint after validateState() succeeds. + * @return Empty when valid, otherwise a distinct failure reason. */ +std::string validateGrid(const SessionRequest& request); + +/** @brief Apply validateState() and then validateGrid(). + * @return Empty when valid, otherwise the first failure reason. */ +std::string validateRequest(const SessionRequest& request); + +/** @brief Reusable single-planner-thread adapter. Snapshots remain owned by the request during plan(). + * The caller may set the request's atomic cancellation flag from another thread. All other methods + * and the live cost buffer are confined to the planner thread. */ +class LaneRouteSession +{ +public: + /** @brief Construct a session with validated-on-use configuration. */ + explicit LaneRouteSession(const SessionConfig& config = SessionConfig()) : config_(config) + { + } + + /** @brief Replace the configuration and invalidate all compiled graphs, on the planner thread. */ + void setConfig(const SessionConfig& config) + { + config_ = config; + clearCache(); + } + + /** @brief Plan on the planner thread; cancellation may be requested through request.cancel. */ + lane_route_core::PlanResult plan(const SessionRequest& request); + + /** @brief Reusable storage for copying the live or external master bytes before plan(). + * The planner thread resizes and fills it, then points SessionRequest::live.cost at its data. */ + std::vector& liveCostBuffer() + { + return live_cost_; + } + + /** @brief Number of currently cached deviation graphs, for diagnostics and tests. */ + std::size_t cachedGraphCount() const + { + return graphs_.size(); + } + + /** @brief Number of graphs compiled by this session, for diagnostics and tests. */ + std::size_t compileCount() const + { + return compile_count_; + } + + /** @brief Reference graph generation used by the cache, for diagnostics and tests. */ + uint64_t cachedGeneration() const + { + return graph_generation_; + } + + /** @brief Discard cached graphs and snapshot-derived data on the planner thread. */ + void clearCache(); + +private: + SessionConfig config_; + std::vector live_cost_; + std::vector directions_; + std::vector preferred_mask_; + std::vector changed_cells_; + bool preferred_mask_empty_ = true; + std::vector changed_stack_; + std::size_t compile_count_ = 0; + std::vector live_clearance_; + std::map> graphs_; + lane_route_core::CoarseGraph coarse_; + uint64_t graph_generation_ = 0; + uint64_t direction_generation_ = 0; + const robot_costmap_2d::ReferenceGraph* graph_identity_ = nullptr; + const robot_costmap_2d::DirectionField* direction_identity_ = nullptr; + double half_x_ = -1; ///< [m] Cached footprint half length. + double half_y_ = -1; ///< [m] Cached footprint half width. + double inscribed_ = -1; ///< [m] Cached inscribed radius. +}; +} // namespace lane_route_planner + +#endif // LANE_ROUTE_PLANNER_LANE_ROUTE_SESSION_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..e4eed86 --- /dev/null +++ b/package.xml @@ -0,0 +1,20 @@ + + + lane_route_planner + 0.1.0 + Reference-graph global planner adapter for robot_nav_core. + duongtd + BSD + catkin + lane_route_core + robot_costmap_2d + robot_nav_core + robot_cpp + robot_geometry_msgs + robot_nav_msgs + robot_protocol_msgs + data_convert + robot_time + boost + gtest + diff --git a/src/lane_route_planner.cpp b/src/lane_route_planner.cpp new file mode 100644 index 0000000..b923dc9 --- /dev/null +++ b/src/lane_route_planner.cpp @@ -0,0 +1,286 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +namespace lane_route_planner +{ +robot_nav_core::BaseGlobalPlanner::Ptr LaneRoutePlanner::create() +{ + return std::make_shared(); +} + +void setExternalGridOn(robot_nav_core::BaseGlobalPlanner* planner, const robot_costmap_2d::Costmap2D* grid) +{ + auto* self = dynamic_cast(planner); + if (self) + self->setExternalGrid(grid); + else + robot::log_error("[lane_route_planner] ExternalGrid: wrong planner instance"); +} + +bool LaneRoutePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap) +{ + if (initialized_) + return true; + if (!costmap || !costmap->getLayeredCostmap() || !costmap->getCostmap()) + { + robot::log_error("[lane_route_planner] initialize: missing costmap"); + return false; + } + try + { + robot::NodeHandle root; + robot::NodeHandle nh(root, name); + const auto load = [&nh](const char* key, auto& value, const auto& fallback) + { + if (nh.hasParam(key)) + { + if (!nh.getParam(key, value, fallback)) + throw std::invalid_argument(std::string("invalid parameter: ") + key); + } + else + { + value = fallback; + } + }; + SessionConfig defaults; + auto& p = config_.planner; + const auto& d = defaults.planner; + load("min_turn_radius_m", p.min_turn_radius_m, d.min_turn_radius_m); + load("corner_radii_m", p.corner_radii_m, d.corner_radii_m); + load("clearance_min_margin_m", config_.clearance_min_margin_m, defaults.clearance_min_margin_m); + load("clearance_preferred_margin_m", config_.clearance_preferred_margin_m, defaults.clearance_preferred_margin_m); + load("collision_check_margin_m", config_.collision_check_margin_m, defaults.collision_check_margin_m); + load("footprint_min_gap_m", p.footprint_min_gap_m, d.footprint_min_gap_m); + load("footprint_gap_shortcut_raise_m", p.footprint_gap_shortcut_raise_m, d.footprint_gap_shortcut_raise_m); + load("deviation_ladder_deg", p.deviation_ladder_deg, d.deviation_ladder_deg); + load("route_too_long_ratio", p.route_too_long_ratio, d.route_too_long_ratio); + load("route_too_long_margin_m", p.route_too_long_margin_m, d.route_too_long_margin_m); + load("suspicious_ratio", p.suspicious_ratio, d.suspicious_ratio); + load("suspicious_margin_m", p.suspicious_margin_m, d.suspicious_margin_m); + load("max_route_attempts", p.max_route_attempts, d.max_route_attempts); + load("time_limit_s", p.time_limit_s, d.time_limit_s); + load("output_step_m", p.output_step_m, d.output_step_m); + load("live_ridge_pad_m", p.live_ridge_pad_m, d.live_ridge_pad_m); + int max_cells = static_cast(d.live_ridge_max_cells); + load("live_ridge_max_cells", max_cells, max_cells); + p.live_ridge_max_cells = max_cells; + load("debug_plan", config_.debug_plan, defaults.debug_plan); + load("debug_state", config_.debug_state, defaults.debug_state); + const std::string error = config_.validate(); + if (!error.empty()) + { + robot::log_error("[lane_route_planner] invalid configuration: %s", error.c_str()); + return false; + } + costmap_ = costmap; + session_.setConfig(config_); + initialized_ = true; + robot::log_info("[lane_route_planner] %s: time_limit=%.2fs min_radius=%.3fm clearance_margin=%.3fm gap=%.3fm debug_plan=%d debug_state=%d", + name.c_str(), p.time_limit_s, p.min_turn_radius_m, config_.clearance_min_margin_m, + p.footprint_min_gap_m, config_.debug_plan, config_.debug_state); + if (costmap_->getLayeredCostmap()->getReferenceGraphSnapshot().state == robot_costmap_2d::ReferenceGraphState::kDisabled) + robot::log_error("[lane_route_planner] reference graph is disabled; plans will fail until enabled"); + return true; + } + catch (const std::exception& ex) + { + robot::log_error("[lane_route_planner] initialize: %s", ex.what()); + return false; + } +} + +bool LaneRoutePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) +{ + plan.clear(); + if (!initialized_) + { + robot::log_error("[lane_route_planner] not_initialized"); + return false; + } + preempt_.store(false, std::memory_order_relaxed); + try + { + auto* layered = costmap_->getLayeredCostmap(); + auto* master = costmap_->getCostmap(); + if (!layered || !master) + { + robot::log_error("[lane_route_planner] missing_costmap"); + return false; + } + SessionRequest request; + request.initialized = initialized_; + request.start = start; + request.goal = goal; + request.frame = costmap_->getGlobalFrameID(); + request.cancel = &preempt_; + request.graph = layered->getReferenceGraphSnapshot(); + request.direction = layered->getDirectionFieldSnapshot(); + if (!have_state_ || graph_state_ != request.graph.state || direction_state_ != request.direction.state || + graph_generation_ != request.graph.generation || direction_generation_ != request.direction.generation) + { + if (config_.debug_state) + robot::log_info("[lane_route_planner] [debug] graph_state=%d generation=%llu direction_state=%d generation=%llu", + static_cast(request.graph.state), static_cast(request.graph.generation), + static_cast(request.direction.state), static_cast(request.direction.generation)); + have_state_ = true; + graph_state_ = request.graph.state; + graph_generation_ = request.graph.generation; + direction_state_ = request.direction.state; + direction_generation_ = request.direction.generation; + } + // Check state and pose guards before copying the large grid. Geometry is filled below. + const std::string early = validateState(request); + if (!early.empty()) + { + robot::log_warning("[lane_route_planner] plan failed: %s", early.c_str()); + return false; + } + auto& bytes = session_.liveCostBuffer(); + { + boost::unique_lock lock(*master->getMutex()); + if (master->getSizeInCellsX() > static_cast(std::numeric_limits::max()) || + master->getSizeInCellsY() > static_cast(std::numeric_limits::max())) + { + robot::log_error("[lane_route_planner] invalid_costmap_size"); + return false; + } + request.live.width = static_cast(master->getSizeInCellsX()); + request.live.height = static_cast(master->getSizeInCellsY()); + request.live.resolution = master->getResolution(); + request.live.origin_x = master->getOriginX(); + request.live.origin_y = master->getOriginY(); + request.footprint = layered->getFootprint(); + } + const std::size_t count = static_cast(request.live.width) * request.live.height; + if (count == 0 || count > static_cast(std::numeric_limits::max())) + { + robot::log_error("[lane_route_planner] invalid_costmap_size"); + return false; + } + bytes.resize(count); + const auto matches = [&](const robot_costmap_2d::Costmap2D* grid) + { + return grid && grid->getSizeInCellsX() == static_cast(request.live.width) && + grid->getSizeInCellsY() == static_cast(request.live.height) && + grid->getResolution() == request.live.resolution && grid->getOriginX() == request.live.origin_x && + grid->getOriginY() == request.live.origin_y && grid->getCharMap(); + }; + if (external_grid_) + { + if (!matches(external_grid_)) + { + robot::log_error("[lane_route_planner] external_grid_geometry_mismatch"); + return false; + } + std::copy_n(external_grid_->getCharMap(), count, bytes.begin()); + } + else + { + boost::unique_lock lock(*master->getMutex()); + if (!matches(master)) + { + robot::log_error("[lane_route_planner] costmap_geometry_changed"); + return false; + } + std::copy_n(master->getCharMap(), count, bytes.begin()); + } + // The radius setter runs outside the costmap lock; use the same algorithm on the locked footprint copy. + if (request.footprint.size() >= 3) + { + double circumscribed = 0.0; + robot_costmap_2d::calculateMinAndMaxDistances(request.footprint, request.inscribed_radius_m, circumscribed); + } + request.live.cost = bytes.data(); + if (request.footprint != previous_footprint_) + { + previous_footprint_ = request.footprint; + double x, y; + bool rectangular; + if (footprintRectangle(request.footprint, &x, &y, &rectangular) && !rectangular) + robot::log_warning("[lane_route_planner] footprint is approximated by a centred bounding rectangle"); + } + auto result = session_.plan(request); + if (config_.debug_plan) + robot::log_info("[lane_route_planner] [debug] ok=%d reason=%s rung=%.3f retries=%d gap_failures=%d soft_ignored=%d live=%s query=%.1fms compile=%.1fms search=%.1fms build=%.1fms verify=%.1fms live_ridge=%.1fms gap=%.3fm raise=%.3fm exempt=%d swing_windows=%d swing_checks=%ld swing_builds=%d swing_selected=%d", + result.ok, result.info.reason.c_str(), result.info.rung_used_deg, result.info.retries, + result.info.gap_failures, result.info.soft_cost_ignored, result.info.live_ridge.c_str(), + result.info.query_ms, result.info.compile_ms, result.info.search_ms, result.info.build_ms, result.info.verify_ms, + result.info.live_ridge_ms, result.info.min_gap_m, result.info.gap_shortcut_raise_m, result.info.gap_exemption_used, + result.info.swing_windows, result.info.swing_line_checks, result.info.swing_builds, result.info.swing_selected); + if (!result.ok || result.path.empty() || !result.check.valid) + { + const char* reason = result.ok ? "invalid_or_empty_verified_path" : result.info.reason.c_str(); + robot::log_warning("[lane_route_planner] plan failed: %s", reason); + return false; + } + const auto final_graph = layered->getReferenceGraphSnapshot(); + const auto final_direction = layered->getDirectionFieldSnapshot(); + if (preempt_.load(std::memory_order_relaxed) || final_graph.state != request.graph.state || + final_graph.generation != request.graph.generation || final_direction.state != request.direction.state || + final_direction.generation != request.direction.generation) + { + robot::log_warning("[lane_route_planner] plan failed: cancelled_or_snapshot_changed"); + return false; + } + { + auto* latest = costmap_->getCostmap(); + if (!latest) + { + robot::log_warning("[lane_route_planner] plan failed: missing_costmap"); + return false; + } + boost::unique_lock lock(*latest->getMutex()); + if (!matches(latest) || layered->getFootprint() != request.footprint) + { + robot::log_warning("[lane_route_planner] plan failed: costmap_or_footprint_changed"); + return false; + } + } + const auto stamp = robot::Time::now(); + plan.reserve(result.path.size()); + for (const auto& point : result.path) + { + robot_geometry_msgs::PoseStamped pose; + pose.header.frame_id = request.frame; + pose.header.stamp = stamp; + pose.pose.position.x = point.x; + pose.pose.position.y = point.y; + pose.pose.position.z = start.pose.position.z; + pose.pose.orientation = data_convert::getQuaternion(point.yaw); + plan.push_back(pose); + } + plan.back().pose = goal.pose; + if (preempt_.load(std::memory_order_relaxed)) + { + plan.clear(); + robot::log_warning("[lane_route_planner] plan failed: cancelled"); + return false; + } + return true; + } + catch (const std::exception& ex) + { + plan.clear(); + robot::log_error("[lane_route_planner] plan exception: %s", ex.what()); + return false; + } +} +} // namespace lane_route_planner + +BOOST_DLL_ALIAS(lane_route_planner::LaneRoutePlanner::create, LaneRoutePlanner) +BOOST_DLL_ALIAS(lane_route_planner::setExternalGridOn, LaneRoutePlannerExternalGrid) diff --git a/src/lane_route_session.cpp b/src/lane_route_session.cpp new file mode 100644 index 0000000..b07efda --- /dev/null +++ b/src/lane_route_session.cpp @@ -0,0 +1,323 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace lane_route_planner +{ +namespace +{ +bool finitePose(const robot_geometry_msgs::PoseStamped& p) +{ + const auto& q = p.pose.orientation; + const auto& x = p.pose.position; + return std::isfinite(x.x) && std::isfinite(x.y) && std::isfinite(x.z) && std::isfinite(q.x) && + std::isfinite(q.y) && std::isfinite(q.z) && std::isfinite(q.w); +} + +bool sameGeometry(const robot_costmap_2d::DirectionGeometry& g, const lane_route_core::GridRef& grid, + const std::string& frame) +{ + return g.width == static_cast(grid.width) && g.height == static_cast(grid.height) && + std::abs(g.resolution - grid.resolution) < 1e-8 && std::abs(g.origin_x - grid.origin_x) < 1e-8 && + std::abs(g.origin_y - grid.origin_y) < 1e-8 && g.frame_id == frame; +} + +lane_route_core::Pose2 poseOf(const robot_geometry_msgs::PoseStamped& p, bool has_yaw) +{ + const auto& q = p.pose.orientation; + return { p.pose.position.x, p.pose.position.y, + std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)), has_yaw }; +} +} // namespace + +std::string SessionConfig::validate() const +{ + const auto nonnegative = [](double x) + { + return std::isfinite(x) && x >= 0.0; + }; + std::ostringstream error; + if (!nonnegative(clearance_min_margin_m)) + error << "clearance_min_margin_m must be finite and >= 0, got " << clearance_min_margin_m; + else if (!nonnegative(clearance_preferred_margin_m)) + error << "clearance_preferred_margin_m must be finite and >= 0, got " << clearance_preferred_margin_m; + else if (clearance_preferred_margin_m < clearance_min_margin_m) + error << "clearance_preferred_margin_m=" << clearance_preferred_margin_m + << " must be >= clearance_min_margin_m=" << clearance_min_margin_m; + else if (!nonnegative(collision_check_margin_m)) + error << "collision_check_margin_m must be finite and >= 0, got " << collision_check_margin_m; + if (!error.str().empty()) + return error.str(); + return planner.validate(); +} + +bool footprintRectangle(const std::vector& footprint, double* half_x, double* half_y, + bool* centered_rectangle) +{ + if (!half_x || !half_y || !centered_rectangle || footprint.size() < 3) + return false; + *half_x = 0.0; + *half_y = 0.0; + for (const auto& p : footprint) + { + if (!std::isfinite(p.x) || !std::isfinite(p.y)) + return false; + *half_x = std::max(*half_x, std::abs(p.x)); + *half_y = std::max(*half_y, std::abs(p.y)); + } + if (*half_x <= 0 || *half_y <= 0) + return false; + unsigned corners = 0; + for (const auto& p : footprint) + { + if (std::abs(std::abs(p.x) - *half_x) > 1e-9 || std::abs(std::abs(p.y) - *half_y) > 1e-9) + continue; + corners |= 1u << ((p.x > 0 ? 1 : 0) + (p.y > 0 ? 2 : 0)); + } + *centered_rectangle = footprint.size() == 4 && corners == 15; + if (*centered_rectangle) + { + for (std::size_t i = 0; i < 4; ++i) + { + const auto& a = footprint[i]; + const auto& b = footprint[(i + 1) % 4]; + if ((std::abs(a.x - b.x) < 1e-9) == (std::abs(a.y - b.y) < 1e-9)) + *centered_rectangle = false; + } + } + return true; +} + +std::string validateState(const SessionRequest& r) +{ + if (!r.initialized) + return "not_initialized"; + if (!finitePose(r.start)) + return "invalid_start_pose"; + if (!finitePose(r.goal)) + return "invalid_goal_pose"; + if (r.start.header.frame_id != r.frame || r.goal.header.frame_id != r.frame) + return "frame_mismatch"; + if (r.graph.state == robot_costmap_2d::ReferenceGraphState::kDisabled) + return "graph_disabled"; + if (r.graph.state == robot_costmap_2d::ReferenceGraphState::kPending || !r.graph.graph) + return "graph_pending"; + if (r.direction.state == robot_costmap_2d::DirectionFieldState::kPending || + (r.direction.state == robot_costmap_2d::DirectionFieldState::kReady && !r.direction.field)) + return "direction_pending"; + if (r.graph.graph->direction_generation != r.direction.generation) + return "direction_generation_mismatch"; + return {}; +} + +std::string validateGrid(const SessionRequest& r) +{ + if (r.live.width <= 0 || r.live.height <= 0 || !std::isfinite(r.live.resolution) || r.live.resolution <= 0 || + !std::isfinite(r.live.origin_x) || !std::isfinite(r.live.origin_y) || !r.live.cost || + !sameGeometry(r.graph.graph->geometry, r.live, r.frame) || + (r.direction.field && !sameGeometry(r.direction.field->geometry(), r.live, r.frame))) + return "graph_geometry_mismatch"; + const std::size_t cells = static_cast(r.live.width) * static_cast(r.live.height); + if (cells > static_cast(std::numeric_limits::max())) + return "graph_geometry_mismatch"; + if (r.graph.graph->static_cost.size() != cells || r.graph.graph->clearance_mm.size() != cells) + return "graph_data_invalid"; + double x, y; + bool rect; + if (!footprintRectangle(r.footprint, &x, &y, &rect)) + return "invalid_footprint"; + if (!std::isfinite(r.inscribed_radius_m) || r.inscribed_radius_m < 0) + return "invalid_inscribed_radius"; + return {}; +} + +std::string validateRequest(const SessionRequest& r) +{ + const std::string state_error = validateState(r); + if (!state_error.empty()) + return state_error; + return validateGrid(r); +} + +void LaneRouteSession::clearCache() +{ + graphs_.clear(); + coarse_ = {}; + preferred_mask_.clear(); + preferred_mask_empty_ = true; + directions_.clear(); + graph_identity_ = nullptr; + direction_identity_ = nullptr; + half_x_ = -1; + half_y_ = -1; + inscribed_ = -1; +} + +lane_route_core::PlanResult LaneRouteSession::plan(const SessionRequest& request) +{ + using namespace lane_route_core; + PlanResult failed; + failed.info.reason = validateRequest(request); + if (!failed.info.reason.empty()) + return failed; + const std::string error = config_.validate(); + if (!error.empty()) + { + failed.info.reason = "invalid_config: " + error; + return failed; + } + if (request.cancel && request.cancel->load(std::memory_order_relaxed)) + { + failed.info.reason = "cancelled"; + return failed; + } + const auto& reference = *request.graph.graph; + const std::size_t cells = static_cast(request.live.width) * request.live.height; + double half_x, half_y; + bool rectangle; + footprintRectangle(request.footprint, &half_x, &half_y, &rectangle); + if (graph_identity_ != request.graph.graph.get() || graph_generation_ != request.graph.generation || + half_x_ != half_x || half_y_ != half_y || inscribed_ != request.inscribed_radius_m) + { + graphs_.clear(); + preferred_mask_.clear(); + coarse_ = toCoarseGraph(reference, request.cancel); + if (request.cancel && request.cancel->load(std::memory_order_relaxed)) + { + clearCache(); + failed.info.reason = "cancelled"; + return failed; + } + graph_identity_ = request.graph.graph.get(); + graph_generation_ = request.graph.generation; + half_x_ = half_x; + half_y_ = half_y; + inscribed_ = request.inscribed_radius_m; + } + const auto* field = request.direction.field.get(); + if (direction_identity_ != field || direction_generation_ != request.direction.generation) + { + graphs_.clear(); + directions_.clear(); + direction_identity_ = field; + direction_generation_ = request.direction.generation; + if (field && field->hasConstraints()) + { + directions_.resize(cells); + for (int32_t y = 0; y < request.live.height; ++y) + for (int32_t x = 0; x < request.live.width; ++x) + directions_[static_cast(y) * request.live.width + x] = field->code(x, y); + } + } + const bool live_has_preferred = std::memchr(request.live.cost, kPreferredSpace, cells) != nullptr; + bool preferred_changed = preferred_mask_.size() != cells; + if (!preferred_changed && (live_has_preferred || !preferred_mask_empty_)) + { + for (std::size_t i = 0; i < cells; ++i) + { + if (preferred_mask_[i] != (request.live.cost[i] == kPreferredSpace)) + { + preferred_changed = true; + break; + } + } + } + if (preferred_changed) + { + graphs_.clear(); + preferred_mask_.resize(cells); + for (std::size_t i = 0; i < cells; ++i) + preferred_mask_[i] = request.live.cost[i] == kPreferredSpace; + preferred_mask_empty_ = !live_has_preferred; + } + PlannerConfig config = config_.planner; + config.half_x_m = half_x; + config.half_y_m = half_y; + config.clearance_min_m = request.inscribed_radius_m + config_.clearance_min_margin_m; + config.clearance_hard_m = config.clearance_min_m; + config.clearance_preferred_m = request.inscribed_radius_m + config_.clearance_preferred_margin_m; + config.collision_check_distance_m = std::hypot(half_x, half_y) + config_.collision_check_margin_m; + if (field) + config.max_deviation_deg = field->maxDeviationRad() * 180.0 / kPi; + GridRef compile_grid = request.live; + compile_grid.cost = reference.static_cost.data(); + compile_grid.clearance_mm = reference.clearance_mm.data(); + compile_grid.direction = directions_.empty() ? nullptr : directions_.data(); + GridRef live = request.live; + live.direction = compile_grid.direction; + live.clearance_mm = reference.clearance_mm.data(); + RouteRequest route; + route.start = poseOf(request.start, request.start_has_yaw); + route.goal = poseOf(request.goal, request.goal_has_yaw); + route.cancel = request.cancel; + route.changed_boxes = changedBoxes(reference.static_cost.data(), live, request.cancel, &changed_cells_, &changed_stack_); + if (request.cancel && request.cancel->load(std::memory_order_relaxed)) + { + failed.info.reason = "cancelled"; + return failed; + } + if (!route.changed_boxes.empty()) + { + const double radius = std::max({ 1.5, config.clearance_preferred_m, config.collision_check_distance_m, + config.clearance_hard_m, config.clearance_min_m }); + patchClearance(reference.static_cost.data(), reference.clearance_mm.data(), live, radius, &live_clearance_, request.cancel); + if (request.cancel && request.cancel->load(std::memory_order_relaxed)) + { + failed.info.reason = "cancelled"; + return failed; + } + live.clearance_mm = live_clearance_.data(); + } + const RidgeBackend backend = makeRidgeBackend(config, reference.params); + const GraphProvider provider = [&](double deviation) -> std::shared_ptr + { + auto it = graphs_.find(deviation); + if (it != graphs_.end()) + return it->second; + auto graph = std::make_shared( + compileGraph(coarse_, compile_grid, live.cost, deviation, config, backend, request.cancel)); + if (request.cancel && request.cancel->load(std::memory_order_relaxed)) + return {}; + graphs_.emplace(deviation, graph); + ++compile_count_; + return graph; + }; + PlanResult result = planRoute(provider, route, live, config, backend); + if (result.ok && !result.path.empty()) + { + // The adapter outputs the exact goal pose. Verify that final adjustment as well, while + // keeping the original core path available to callers comparing against the eval tool. + const auto verify_begin = std::chrono::steady_clock::now(); + Path exact = result.path; + exact.back().x = route.goal.x; + exact.back().y = route.goal.y; + if (route.goal.has_yaw) + exact.back().yaw = route.goal.yaw; + const PathCheck check = verifyPath(exact, live, result.info.rung_used_deg, config, request.cancel); + const bool valid = check.valid && endpointOk(exact, route.start, route.goal) && + freeClearanceOk(exact, live, clearanceThresholdMm(config.clearance_min_m)) && + !blockedEndpointTurn(exact, live, config.half_x_m, config.half_y_m) && + checkFootprintGap(exact, live, config.footprint_min_gap_m, config.half_x_m, + config.half_y_m, request.cancel).valid; + const double verify_ms = std::chrono::duration(std::chrono::steady_clock::now() - verify_begin).count(); + result.info.verify_ms += verify_ms; + result.info.query_ms += verify_ms; + if (!valid || (request.cancel && request.cancel->load(std::memory_order_relaxed))) + { + result.ok = false; + result.path.clear(); + result.info.reason = request.cancel && request.cancel->load(std::memory_order_relaxed) ? "cancelled" : "exact_goal_invalid"; + } + } + return result; +} +} // namespace lane_route_planner diff --git a/test/lane_route_planner_test.cpp b/test/lane_route_planner_test.cpp new file mode 100644 index 0000000..93666bf --- /dev/null +++ b/test/lane_route_planner_test.cpp @@ -0,0 +1,583 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +using namespace lane_route_planner; +using namespace lane_route_core; +using namespace robot_costmap_2d; + +namespace +{ +robot_geometry_msgs::PoseStamped pose(double x, double y, double yaw = 0) +{ + robot_geometry_msgs::PoseStamped p; + p.header.frame_id = "map"; + p.pose.position.x = x; + p.pose.position.y = y; + p.pose.orientation.z = std::sin(yaw / 2); + p.pose.orientation.w = std::cos(yaw / 2); + return p; +} + +SessionRequest validRequest(std::vector& cost) +{ + SessionRequest r; + r.initialized = true; + r.frame = "map"; + r.live.width = 40; + r.live.height = 40; + r.live.resolution = 0.05; + r.live.cost = cost.data(); + auto graph = std::make_shared(); + graph->geometry = { 40, 40, 0.05, 0, 0, "map" }; + graph->static_cost = cost; + graph->clearance_mm.assign(cost.size(), 1000); + r.graph = { ReferenceGraphState::kReady, graph, 1 }; + r.footprint = rectangleFootprint(0.30, 0.30); + r.inscribed_radius_m = 0.30; + r.start = pose(0.6, 0.6); + r.goal = pose(1.2, 1.2); + return r; +} + +TEST(AdapterGuard, NotInitialized) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.initialized = false; + EXPECT_EQ(validateRequest(r), "not_initialized"); +} + +TEST(AdapterGuard, InvalidStart) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.start.pose.orientation.w = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(validateRequest(r), "invalid_start_pose"); +} + +TEST(AdapterGuard, InvalidGoal) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.goal.pose.position.x = std::numeric_limits::infinity(); + EXPECT_EQ(validateRequest(r), "invalid_goal_pose"); +} + +TEST(AdapterGuard, Frame) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.goal.header.frame_id = "odom"; + EXPECT_EQ(validateRequest(r), "frame_mismatch"); +} + +TEST(AdapterGuard, DisabledGraph) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.graph.state = ReferenceGraphState::kDisabled; + EXPECT_EQ(validateRequest(r), "graph_disabled"); +} + +TEST(AdapterGuard, PendingGraph) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.graph.state = ReferenceGraphState::kPending; + EXPECT_EQ(validateRequest(r), "graph_pending"); +} + +TEST(AdapterGuard, PendingDirection) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.direction.state = DirectionFieldState::kPending; + EXPECT_EQ(validateRequest(r), "direction_pending"); +} + +TEST(AdapterGuard, MissingReadyGraph) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.graph.graph.reset(); + EXPECT_EQ(validateRequest(r), "graph_pending"); +} + +TEST(AdapterGuard, MissingReadyDirection) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.direction.state = DirectionFieldState::kReady; + EXPECT_EQ(validateRequest(r), "direction_pending"); +} + +TEST(AdapterGuard, DirectionGeneration) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.direction.generation = 2; + EXPECT_EQ(validateRequest(r), "direction_generation_mismatch"); +} + +TEST(AdapterGuard, Geometry) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.live.origin_x = 1; + EXPECT_EQ(validateRequest(r), "graph_geometry_mismatch"); +} + +TEST(AdapterGuard, Footprint) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.footprint.resize(2); + EXPECT_EQ(validateRequest(r), "invalid_footprint"); +} + +TEST(AdapterGuard, InvalidSnapshotData) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + auto g = std::make_shared(*r.graph.graph); + g->clearance_mm.clear(); + r.graph.graph = g; + EXPECT_EQ(validateRequest(r), "graph_data_invalid"); +} + +TEST(AdapterGuard, InvalidRadius) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.inscribed_radius_m = -1; + EXPECT_EQ(validateRequest(r), "invalid_inscribed_radius"); +} + +TEST(AdapterGuard, StateDoesNotRequireGrid) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + r.live = {}; + EXPECT_TRUE(validateState(r).empty()); + EXPECT_EQ(validateGrid(r), "graph_geometry_mismatch"); + EXPECT_EQ(validateRequest(r), "graph_geometry_mismatch"); + r.initialized = false; + EXPECT_EQ(validateRequest(r), "not_initialized"); +} + +TEST(AdapterConfig, RejectsInvalidParameters) +{ + SessionConfig c; + c.clearance_min_margin_m = -1; + const std::string invalid_margin = c.validate(); + EXPECT_NE(invalid_margin.find("clearance_min_margin_m"), std::string::npos); + EXPECT_NE(invalid_margin.find("-1"), std::string::npos); + + c = SessionConfig(); + c.clearance_min_margin_m = 0.2; + c.clearance_preferred_margin_m = 0.1; + const std::string inverted_margins = c.validate(); + EXPECT_NE(inverted_margins.find("clearance_preferred_margin_m"), std::string::npos); + EXPECT_NE(inverted_margins.find("0.1"), std::string::npos); + EXPECT_NE(inverted_margins.find("clearance_min_margin_m"), std::string::npos); + EXPECT_NE(inverted_margins.find("0.2"), std::string::npos); + + c = SessionConfig(); + c.clearance_preferred_margin_m = -0.5; + const std::string invalid_preferred = c.validate(); + EXPECT_NE(invalid_preferred.find("clearance_preferred_margin_m"), std::string::npos); + EXPECT_NE(invalid_preferred.find("-0.5"), std::string::npos); + + c = SessionConfig(); + c.collision_check_margin_m = -0.25; + const std::string invalid_collision = c.validate(); + EXPECT_NE(invalid_collision.find("collision_check_margin_m"), std::string::npos); + EXPECT_NE(invalid_collision.find("-0.25"), std::string::npos); + + c = SessionConfig(); + c.planner.min_turn_radius_m = 0; + EXPECT_FALSE(c.validate().empty()); + c = SessionConfig(); + c.planner.max_route_attempts = 0; + EXPECT_FALSE(c.validate().empty()); + c = SessionConfig(); + c.planner.time_limit_s = std::numeric_limits::infinity(); + EXPECT_FALSE(c.validate().empty()); +} + +TEST(AdapterConfig, FootprintBoundsAndCollisionDistances) +{ + double x, y; + bool rectangle; + auto points = rectangleFootprint(0.30, 0.30); + ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); + EXPECT_TRUE(rectangle); + EXPECT_NEAR(std::hypot(x, y) + 0.056, 0.48, 0.001); + points = rectangleFootprint(0.325, 0.345); + ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); + EXPECT_NEAR(std::hypot(x, y) + 0.056, 0.53, 0.001); + points[0].x = 0.1; + ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); + EXPECT_FALSE(rectangle); +} + +TEST(AdapterSession, ZeroDeviationUsesOneRung) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + robot_nav_msgs::OccupancyGrid msg; + msg.header.frame_id = "map"; + msg.info.width = 40; + msg.info.height = 40; + msg.info.resolution = 0.05; + msg.data.assign(1600, 1); + r.direction = { DirectionFieldState::kReady, DirectionField::create(msg, r.graph.graph->geometry, 0.0), 1 }; + ASSERT_TRUE(r.direction.field); + auto graph = std::make_shared(*r.graph.graph); + graph->direction_generation = 1; + r.graph.graph = graph; + r.goal = pose(1.2, 0.6); + LaneRouteSession session; + const auto result = session.plan(r); + EXPECT_LE(result.info.rung_reasons.size(), 1u); + if (result.ok) + EXPECT_DOUBLE_EQ(result.info.rung_used_deg, 0.0); +} + +TEST(AdapterSession, CacheDroppedOnGenerationChange) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + LaneRouteSession session; + session.plan(r); + ASSERT_GT(session.cachedGraphCount(), 0u); + const auto compiled = session.compileCount(); + EXPECT_EQ(session.cachedGeneration(), 1u); + r.graph.generation++; + std::atomic cancel{ true }; + r.cancel = &cancel; + // A cancelled request is refused before mutating the cache; the next real request drops it. + EXPECT_EQ(session.plan(r).info.reason, "cancelled"); + cancel = false; + r.live.cost = c.data(); + session.plan(r); + EXPECT_GT(session.cachedGraphCount(), 0u); + EXPECT_EQ(session.cachedGeneration(), 2u); + EXPECT_GT(session.compileCount(), compiled); +} + +TEST(AdapterSession, PreferredChangesInvalidateCache) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + LaneRouteSession session; + session.plan(r); + const auto n = session.compileCount(); + ASSERT_GT(n, 0u); + session.plan(r); + EXPECT_EQ(session.compileCount(), n); + c[0] = 100; + session.plan(r); + EXPECT_EQ(session.compileCount(), n); + c[0] = 20; + session.plan(r); + const auto preferred_count = session.compileCount(); + EXPECT_GT(preferred_count, n); + session.plan(r); + EXPECT_EQ(session.compileCount(), preferred_count); + c[0] = 60; + c[1] = 20; + session.plan(r); + const auto moved_count = session.compileCount(); + EXPECT_GT(moved_count, preferred_count); + c[1] = 60; + session.plan(r); + const auto cleared_count = session.compileCount(); + EXPECT_GT(cleared_count, moved_count); + session.plan(r); + EXPECT_EQ(session.compileCount(), cleared_count); +} + +TEST(AdapterSession, PreemptAndNextCall) +{ + std::vector c(1600, 60); + auto r = validRequest(c); + auto graph = std::make_shared(*r.graph.graph); + graph->nodes.resize(1000000, ReferencePoint{ 0.5, 0.5 }); + r.graph.graph = graph; + LaneRouteSession session; + std::atomic cancel{ false }; + r.cancel = &cancel; + PlanResult result; + std::atomic started{ false }; + const auto begin = std::chrono::steady_clock::now(); + std::thread worker([&] + { + started = true; + result = session.plan(r); + }); + while (!started.load()) + std::this_thread::yield(); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + cancel = true; + worker.join(); + EXPECT_EQ(result.info.reason, "cancelled"); + EXPECT_LT(std::chrono::duration(std::chrono::steady_clock::now() - begin).count(), 5.0); + cancel = false; + r.graph = validRequest(c).graph; + r.graph.generation = 2; + EXPECT_NE(session.plan(r).info.reason, "cancelled"); +} + +std::vector readRuns(std::istream& in, const std::string& expected) +{ + std::string key; + std::size_t n; + in >> key >> n; + if (key != expected) + throw std::runtime_error("expected " + expected + ", got " + key); + std::vector values; + for (std::size_t i = 0; i < n; ++i) + { + int value; + std::size_t count; + in >> value >> count; + values.insert(values.end(), count, static_cast(value)); + } + return values; +} + +struct Fixture +{ + DirectionGeometry geometry{}; + ReferenceGraphParams params; + std::vector cost; + std::vector direction; + std::shared_ptr graph; +}; + +Fixture loadFixture(const std::string& path) +{ + std::ifstream in(path); + if (!in) + throw std::runtime_error("cannot open fixture " + path); + Fixture f; + std::string key; + int version; + double hx, hy; + in >> key >> version; + if (key != "reference_graph_fixture" || version != 1) + throw std::runtime_error("bad fixture"); + in >> key >> f.geometry.width >> f.geometry.height >> key >> f.geometry.resolution >> key >> f.geometry.origin_x >> f.geometry.origin_y; + in >> key >> f.params.min_clearance_m >> f.params.ridge_min_separation_m >> f.params.spur_min_length_m >> + f.params.lane_offset_step_m >> hx >> hy; + f.geometry.frame_id = "map"; + f.params.debug_log = false; + f.cost = readRuns(in, "cost"); + f.direction = readRuns(in, "direction"); + ReferenceGridView view; + view.geometry = f.geometry; + view.cost = f.cost.data(); + view.direction_codes = f.direction.data(); + const auto skeleton = computeVoronoiSkeleton(view, f.params); + f.graph = std::make_shared(buildReferenceGraph(view, skeleton, rectangleFootprint(hx, hy), f.params)); + return f; +} + +struct Scene +{ + std::string id; + Pose2 start; + Pose2 goal; +}; + +std::vector loadScenes(const std::string& path) +{ + std::ifstream in(path); + if (!in) + throw std::runtime_error("cannot open scenes " + path); + std::vector scenes; + std::string line; + while (std::getline(in, line)) + { + if (line.empty()) + continue; + std::istringstream row(line); + Scene s; + std::string grid, live; + int variant, sy, gy, boxes; + row >> s.id >> grid >> variant >> live >> sy >> s.start.x >> s.start.y >> s.start.yaw >> gy >> s.goal.x >> + s.goal.y >> s.goal.yaw >> boxes; + if (!row || variant != 0 || live != "-" || boxes != 0) + throw std::runtime_error("unsupported real scene"); + s.start.has_yaw = sy != 0; + s.goal.has_yaw = gy != 0; + scenes.push_back(s); + } + return scenes; +} + +std::vector loadEvalMaster(const std::string& path) +{ + std::ifstream in(path); + if (!in) + throw std::runtime_error("cannot open eval grid"); + std::string key; + int version, w, h; + double res, ox, oy; + in >> key >> version >> key >> w >> h >> key >> res >> key >> ox >> oy; + return readRuns(in, "cost"); +} + +std::vector inflated(const Fixture& f) +{ + auto cost = f.cost; + for (std::size_t i = 0; i < cost.size(); ++i) + { + if (cost[i] >= kInscribedCost) + continue; + const double rounded_cells = f.graph->clearance_mm[i] / (1000.0 * f.geometry.resolution); + const double d = f.geometry.resolution * std::sqrt(std::round(rounded_cells * rounded_cells)); + if (d > 0.6) + continue; + unsigned value = d <= 0.30 ? kInscribedCost : static_cast(252.0 * std::exp(-15.0 * (d - 0.30))); + cost[i] = std::max(cost[i], static_cast(value)); + } + return cost; +} + +DirectionFieldSnapshot direction(const Fixture& f, double degrees, uint64_t generation) +{ + robot_nav_msgs::OccupancyGrid msg; + msg.header.frame_id = "map"; + msg.info.width = f.geometry.width; + msg.info.height = f.geometry.height; + msg.info.resolution = f.geometry.resolution; + msg.info.origin.position.x = f.geometry.origin_x; + msg.info.origin.position.y = f.geometry.origin_y; + msg.data.assign(f.direction.begin(), f.direction.end()); + return { DirectionFieldState::kReady, DirectionField::create(msg, f.geometry, degrees * kPi / 180.0), generation }; +} + +using Json = nlohmann::json; + +std::map, Json> loadReference(const std::string& path) +{ + std::ifstream in(path); + if (!in) + throw std::runtime_error("cannot open reference " + path); + std::map, Json> refs; + std::string line; + while (std::getline(in, line)) + { + std::size_t pos = 0; + while ((pos = line.find(":inf", pos)) != std::string::npos) + line.replace(pos, 4, ":null"); + Json j = Json::parse(line); + // In C++17 the right side of an assignment runs first, so the key must be read before j is moved. + const std::pair key(j.at("scene").get(), j.at("dev").get()); + refs[key] = std::move(j); + } + return refs; +} + +void runParity(bool real_inflation) +{ + const char* env = std::getenv("LANE_ROUTE_FIXTURE_DIR"); + if (!env) + { + // The installed gtest predates GTEST_SKIP. + std::cout << "[ SKIPPED ] Set LANE_ROUTE_FIXTURE_DIR to oneway_eval/results" << std::endl; + return; + } + const std::string base(env); + const auto fixture = loadFixture(base + "/r12_cpp_fixtures/text/sehc.fixture"); + auto master = real_inflation ? inflated(fixture) : loadEvalMaster(base + "/r12_cpp_eval/sehc.grid"); + const auto scenes = loadScenes(base + "/r12_cpp_eval/sehc_real.txt"); + const auto refs = loadReference(base + "/r15_cpp_eval/out_real.jsonl"); + ASSERT_EQ(scenes.size(), 12u); + ASSERT_EQ(refs.size(), 60u); + SessionConfig config; + config.collision_check_margin_m = 0.48 - std::hypot(0.30, 0.30); + LaneRouteSession session(config); + const double levels[] = { 90, 45, 22.5, 135, 179 }; + uint64_t generation = 0; + for (double level : levels) + { + ++generation; + auto g = std::make_shared(*fixture.graph); + g->direction_generation = generation; + const auto field = direction(fixture, level, generation); + ASSERT_TRUE(field.field); + for (const auto& s : scenes) + { + SCOPED_TRACE(s.id + " level=" + std::to_string(level)); + SessionRequest r; + r.initialized = true; + r.frame = "map"; + r.graph = { ReferenceGraphState::kReady, g, generation }; + r.direction = field; + r.live.width = fixture.geometry.width; + r.live.height = fixture.geometry.height; + r.live.resolution = fixture.geometry.resolution; + r.live.origin_x = fixture.geometry.origin_x; + r.live.origin_y = fixture.geometry.origin_y; + r.live.cost = master.data(); + r.footprint = rectangleFootprint(0.3, 0.3); + r.inscribed_radius_m = 0.3; + r.start = pose(s.start.x, s.start.y, s.start.yaw); + r.goal = pose(s.goal.x, s.goal.y, s.goal.yaw); + r.start_has_yaw = s.start.has_yaw; + r.goal_has_yaw = s.goal.has_yaw; + const auto found = refs.find({ s.id, level }); + ASSERT_NE(found, refs.end()); + const PlanResult result = session.plan(r); + const Json& ref = found->second; + ASSERT_EQ(result.ok, ref.at("ok").get() != 0) << result.info.reason; + EXPECT_EQ(result.info.reason, ref.at("reason").get()); + if (!result.ok) + continue; + EXPECT_TRUE(result.check.valid); + const auto& path = ref.at("path"); + ASSERT_EQ(result.path.size(), path.size()); + for (std::size_t i = 0; i < result.path.size(); ++i) + { + EXPECT_NEAR(result.path[i].x, path[i][0].get(), 1e-8); + EXPECT_NEAR(result.path[i].y, path[i][1].get(), 1e-8); + EXPECT_NEAR(result.path[i].yaw, path[i][2].get(), 1e-8); + } + } + } +} + +TEST(AdapterParity, RealCalls) +{ + runParity(false); +} + +TEST(AdapterParity, Inflation) +{ + runParity(true); +} +} // namespace