From 24822f54084fbfdadff220ec030b7c12321a46ab 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 | 81 + include/lane_route_core/clothoid.h | 35 + include/lane_route_core/costmap_backend.h | 126 ++ include/lane_route_core/graph_compiler.h | 68 + include/lane_route_core/grid_checks.h | 89 ++ include/lane_route_core/path_verifier.h | 38 + include/lane_route_core/route_planner.h | 114 ++ include/lane_route_core/swing_chain.h | 84 ++ include/lane_route_core/types.h | 154 ++ package.xml | 15 + src/clothoid.cpp | 147 ++ src/graph_compiler.cpp | 314 ++++ src/grid_checks.cpp | 635 ++++++++ src/lattice_cspace.cpp | 263 ++++ src/lattice_heuristic.cpp | 194 +++ src/lattice_internal.h | 154 ++ src/lattice_search.cpp | 515 +++++++ src/lattice_tier.cpp | 79 + src/path_verifier.cpp | 250 +++ src/route_graph_path.cpp | 711 +++++++++ src/route_graph_search.cpp | 302 ++++ src/route_graph_tier.cpp | 423 ++++++ src/route_planner.cpp | 262 ++++ src/route_planner_internal.h | 173 +++ src/swing_chain.cpp | 387 +++++ test/lane_route_core_test.cpp | 1669 +++++++++++++++++++++ tools/lane_route_eval.cpp | 354 +++++ 27 files changed, 7636 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 include/lane_route_core/clothoid.h create mode 100644 include/lane_route_core/costmap_backend.h create mode 100644 include/lane_route_core/graph_compiler.h create mode 100644 include/lane_route_core/grid_checks.h create mode 100644 include/lane_route_core/path_verifier.h create mode 100644 include/lane_route_core/route_planner.h create mode 100644 include/lane_route_core/swing_chain.h create mode 100644 include/lane_route_core/types.h create mode 100644 package.xml create mode 100644 src/clothoid.cpp create mode 100644 src/graph_compiler.cpp create mode 100644 src/grid_checks.cpp create mode 100644 src/lattice_cspace.cpp create mode 100644 src/lattice_heuristic.cpp create mode 100644 src/lattice_internal.h create mode 100644 src/lattice_search.cpp create mode 100644 src/lattice_tier.cpp create mode 100644 src/path_verifier.cpp create mode 100644 src/route_graph_path.cpp create mode 100644 src/route_graph_search.cpp create mode 100644 src/route_graph_tier.cpp create mode 100644 src/route_planner.cpp create mode 100644 src/route_planner_internal.h create mode 100644 src/swing_chain.cpp create mode 100644 test/lane_route_core_test.cpp create mode 100644 tools/lane_route_eval.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..2904bd4 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,81 @@ +cmake_minimum_required(VERSION 3.0.2) +project(lane_route_core VERSION 0.1.0 LANGUAGES CXX) + +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) +else() + set(BUILDING_WITH_CATKIN FALSE) +endif() + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# The tests and the eval tool build coarse graphs with robot_costmap_2d. The library itself does not use it. +option(BUILD_LANE_ROUTE_TESTS "Build lane_route_core tests and eval tool" ${BUILDING_WITH_CATKIN}) + +if(BUILDING_WITH_CATKIN) + find_package(catkin REQUIRED COMPONENTS robot_costmap_2d) + catkin_package( + INCLUDE_DIRS include + LIBRARIES lane_route_core + CATKIN_DEPENDS robot_costmap_2d + ) +else() + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif() + +add_library(lane_route_core SHARED + src/clothoid.cpp + src/graph_compiler.cpp + src/grid_checks.cpp + src/lattice_cspace.cpp + src/lattice_heuristic.cpp + src/lattice_search.cpp + src/lattice_tier.cpp + src/path_verifier.cpp + src/route_graph_path.cpp + src/route_graph_search.cpp + src/route_graph_tier.cpp + src/route_planner.cpp + src/swing_chain.cpp +) +target_include_directories(lane_route_core PUBLIC + $ + $ +) +# The workspace builds Debug by default. This runs on the planner thread of a 2-core NUC, so it stays optimised. +target_compile_options(lane_route_core PRIVATE -O3) + +if(BUILD_LANE_ROUTE_TESTS) + find_package(GTest REQUIRED) + if(BUILDING_WITH_CATKIN) + set(COSTMAP_INCLUDES ${catkin_INCLUDE_DIRS}) + set(COSTMAP_LIBRARIES ${catkin_LIBRARIES}) + else() + set(COSTMAP_LIBRARIES robot_costmap_2d) + endif() + + add_executable(lane_route_core_test test/lane_route_core_test.cpp) + target_include_directories(lane_route_core_test PRIVATE tools ${COSTMAP_INCLUDES}) + target_link_libraries(lane_route_core_test PRIVATE lane_route_core ${COSTMAP_LIBRARIES} GTest::GTest GTest::Main) + + add_executable(lane_route_eval tools/lane_route_eval.cpp) + target_include_directories(lane_route_eval PRIVATE tools ${COSTMAP_INCLUDES}) + target_link_libraries(lane_route_eval PRIVATE lane_route_core ${COSTMAP_LIBRARIES}) + target_compile_options(lane_route_eval PRIVATE -O2) +endif() + +if(BUILDING_WITH_CATKIN) + install(TARGETS lane_route_core + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}) + install(DIRECTORY include/lane_route_core DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}) +else() + install(TARGETS lane_route_core + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin) + install(DIRECTORY include/lane_route_core DESTINATION include) +endif() diff --git a/include/lane_route_core/clothoid.h b/include/lane_route_core/clothoid.h new file mode 100644 index 0000000..2443896 --- /dev/null +++ b/include/lane_route_core/clothoid.h @@ -0,0 +1,35 @@ +#ifndef LANE_ROUTE_CORE_CLOTHOID_H_ +#define LANE_ROUTE_CORE_CLOTHOID_H_ + +#include + +#include + +namespace lane_route_core +{ + +/** @brief Fresnel integrals S and C with the pi t^2 / 2 kernel, power series, accurate for |x| <= 1.5. + * Corners stay inside that range: the argument never exceeds sqrt(angle / pi) <= 1. */ +void fresnelSeries(double x, double* s, double* c); + +/** @brief Symmetric clothoid, arc, clothoid in the tangent frame: starts at the origin along +X. + * @param angle Signed turn [rad], 0 < |angle| < pi. + * @param radius Arc radius [m]. + * @param sharpness Curvature rate [1/m^2]. + * @param spacing Sample spacing [m]. Phase boundaries are added as samples. + * @return Samples with x, y [m], yaw [rad], curvature [1/m]. + * @throws std::invalid_argument when an input is out of range. */ +Path clothoidCorner(double angle, double radius, double sharpness, double spacing); + +/** @brief Distance [m] from the corner's entry to the crossing of its two tangent lines. */ +double tangentTrim(double angle, const Path& curve); + +/** @brief Corner at vertex b between lines a-b and b-c, placed in the global frame. + * @param trim Output [m], distance from b to the curve's entry along a-b. + * @return Curve samples, empty when the turn is too small or close to a reversal. */ +Path placedCorner(const Point2& a, const Point2& b, const Point2& c, double radius, double sharpness, double spacing, + double* trim); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_CLOTHOID_H_ diff --git a/include/lane_route_core/costmap_backend.h b/include/lane_route_core/costmap_backend.h new file mode 100644 index 0000000..a9428cb --- /dev/null +++ b/include/lane_route_core/costmap_backend.h @@ -0,0 +1,126 @@ +#ifndef LANE_ROUTE_CORE_COSTMAP_BACKEND_H_ +#define LANE_ROUTE_CORE_COSTMAP_BACKEND_H_ + +#include +#include + +#include + +#include + +namespace lane_route_core +{ + +inline robot_costmap_2d::DirectionGeometry geometryOf(const GridRef& grid) +{ + robot_costmap_2d::DirectionGeometry geometry{}; + geometry.width = static_cast(grid.width); + geometry.height = static_cast(grid.height); + geometry.resolution = grid.resolution; + geometry.origin_x = grid.origin_x; + geometry.origin_y = grid.origin_y; + geometry.frame_id = "map"; + return geometry; +} + +inline robot_costmap_2d::ReferenceGraphParams ridgeParams(const PlannerConfig& config) +{ + robot_costmap_2d::ReferenceGraphParams params; + params.min_clearance_m = config.clearance_hard_m; + return params; +} + +inline std::vector rectangleFootprint(double half_x, double half_y) +{ + std::vector footprint(4); + const double xs[4] = { half_x, -half_x, -half_x, half_x }; + const double ys[4] = { half_y, half_y, -half_y, -half_y }; + for (int i = 0; i < 4; ++i) + { + footprint[static_cast(i)].x = xs[i]; + footprint[static_cast(i)].y = ys[i]; + } + return footprint; +} + +inline CoarseGraph toCoarseGraph(const robot_costmap_2d::ReferenceGraph& graph, const std::atomic* cancel = nullptr) +{ + CoarseGraph coarse; + coarse.nodes.reserve(graph.nodes.size()); + for (const robot_costmap_2d::ReferencePoint& node : graph.nodes) + { + if (cancel && cancel->load(std::memory_order_relaxed)) return {}; + coarse.nodes.push_back({ node.x, node.y }); + } + coarse.edges.reserve(graph.edges.size()); + for (const robot_costmap_2d::VoronoiEdge& edge : graph.edges) + { + if (cancel && cancel->load(std::memory_order_relaxed)) return {}; + CoarseEdge out; + out.from = static_cast(edge.from); + out.to = static_cast(edge.to); + out.points.reserve(edge.points.size()); + for (const robot_costmap_2d::ReferencePoint& point : edge.points) + out.points.push_back({ point.x, point.y }); + coarse.edges.push_back(std::move(out)); + } + coarse.lanes.reserve(graph.lanes.size()); + for (const robot_costmap_2d::ReferenceLane& lane : graph.lanes) + { + if (cancel && cancel->load(std::memory_order_relaxed)) return {}; + coarse.lanes.push_back({ lane.direction_index, { lane.entry.x, lane.entry.y }, { lane.exit.x, lane.exit.y }, lane.length_m, lane.offset_from_centre_m }); + } + return coarse; +} + +/** Steps 1 and 2 from robot_costmap_2d, as the LaneRoutePlanner adapter will call them. */ +inline CoarseGraph buildCoarseGraph(const GridRef& grid, const PlannerConfig& config, + const robot_costmap_2d::ReferenceGraphParams& params, + const std::atomic* cancel = nullptr) +{ + robot_costmap_2d::ReferenceGridView view; + view.cost = grid.cost; + view.clearance_mm = grid.clearance_mm; + view.direction_codes = grid.direction; + view.geometry = geometryOf(grid); + const robot_costmap_2d::VoronoiSkeleton skeleton = robot_costmap_2d::computeVoronoiSkeleton(view, params, cancel); + if (cancel != nullptr && cancel->load(std::memory_order_relaxed)) + return {}; + return toCoarseGraph(robot_costmap_2d::buildReferenceGraph(view, skeleton, rectangleFootprint(config.half_x_m, config.half_y_m), params, cancel), cancel); +} + +inline CoarseGraph buildCoarseGraph(const GridRef& grid, const PlannerConfig& config) +{ + return buildCoarseGraph(grid, config, ridgeParams(config)); +} + +/** Use the worker parameters for both live ridges and preferred-region extraction. */ +inline RidgeBackend makeRidgeBackend(const PlannerConfig& config, + const robot_costmap_2d::ReferenceGraphParams& params) +{ + RidgeBackend backend; + backend.build_coarse = [config, params](const GridRef& window, const std::atomic* cancel) { return buildCoarseGraph(window, config, params, cancel); }; + backend.region_centre_edges = [params](const std::vector& mask, const GridRef& grid, std::vector* nodes, + std::vector* edges, const std::atomic* cancel) { + if (cancel && cancel->load(std::memory_order_relaxed)) return; + const robot_costmap_2d::DirectionGeometry geometry = geometryOf(grid); + const std::vector line = robot_costmap_2d::computeRegionCentreLine(mask, geometry, params); + if (cancel && cancel->load(std::memory_order_relaxed)) return; + robot_costmap_2d::ReferenceGraph graph; + robot_costmap_2d::extractVoronoiEdges(line, grid.direction, geometry, nullptr, &graph.nodes, &graph.edges, cancel); + if (cancel && cancel->load(std::memory_order_relaxed)) return; + const CoarseGraph coarse = toCoarseGraph(graph, cancel); + *nodes = coarse.nodes; + *edges = coarse.edges; + }; + return backend; +} + +inline RidgeBackend makeRidgeBackend(const PlannerConfig& config) +{ + return makeRidgeBackend(config, ridgeParams(config)); +} + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_COSTMAP_BACKEND_H_ diff --git a/include/lane_route_core/graph_compiler.h b/include/lane_route_core/graph_compiler.h new file mode 100644 index 0000000..1114913 --- /dev/null +++ b/include/lane_route_core/graph_compiler.h @@ -0,0 +1,68 @@ +#ifndef LANE_ROUTE_CORE_GRAPH_COMPILER_H_ +#define LANE_ROUTE_CORE_GRAPH_COMPILER_H_ + +#include +#include + +#include + +namespace lane_route_core +{ + +enum class EdgeKind : uint8_t +{ + kVoronoi, ///< Ridge in free space. Costs more than a lane, so routes prefer lanes. + kLane, ///< One-way lane with its straight leads. Its vertices are never moved. + kJunction, ///< Straight link from a lane end to the network. + kPreferredRidge, ///< Centre line of a preferred region. + kPreferredAttach, ///< Straight link from that centre line to the network. + kAttach, ///< Query time: straight link from start or goal to the network. + kDirect, ///< Query time: straight line from start to goal. + kTemporaryLane ///< Query time: lane through a start or goal inside a zone. Locked like kLane. +}; + +inline bool isLocked(EdgeKind kind) { return kind == EdgeKind::kLane || kind == EdgeKind::kTemporaryLane; } + +/** @brief Directed graph edge. */ +struct GraphEdge +{ + int32_t from, to; + std::vector points; ///< [m] from -> to. + EdgeKind kind; + double cost; ///< Length [m] plus lane offset and low clearance penalties. +}; + +/** @brief Directed graph for one direction limit, ready for route queries. Immutable after compileGraph. */ +struct CompiledGraph +{ + double deviation_deg = 0.0; + std::vector nodes; + std::vector edges; + std::vector> outgoing; ///< Per node: indices into edges, ascending. + // Master costmap sample cells per edge, so traversal factors can be read again on every query. + std::vector sample_offsets; ///< edges.size() + 1 entries. + std::vector sample_cells; ///< Grid cell, -1 off the grid. + std::vector sample_weights; ///< [m] +}; + +/** @brief Step 3 of the graph: keep Voronoi edges legal for this limit, add lanes, leads, junctions and the preferred region. + * @param coarse Output of steps 1 and 2. + * @param grid Compile grid. A route query rechecks every used edge against the live grid. + * @param master Master costmap values, read for the preferred region only. + * @param deviation_deg Direction limit [deg]. + * @param config Planner parameters. + * @param backend region_centre_edges is used when `master` holds preferred cells. */ +CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const uint8_t* master, double deviation_deg, + const PlannerConfig& config, const RidgeBackend& backend, + const std::atomic* cancel = nullptr); + +/** @brief Traversal factor of an edge from master values: its cost-weighted length over its length, infinity when blocked. */ +double edgeFactor(const std::vector& points, const uint8_t* master, const GridRef& grid); + +/** @brief Traversal factors of all compiled edges from its stored sample cells. + * @param factors Output, resized to graph.edges.size(). */ +void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector* factors); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_GRAPH_COMPILER_H_ diff --git a/include/lane_route_core/grid_checks.h b/include/lane_route_core/grid_checks.h new file mode 100644 index 0000000..b16fb41 --- /dev/null +++ b/include/lane_route_core/grid_checks.h @@ -0,0 +1,89 @@ +#ifndef LANE_ROUTE_CORE_GRID_CHECKS_H_ +#define LANE_ROUTE_CORE_GRID_CHECKS_H_ + +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ + +inline double wrapAngle(double angle) { return std::remainder(angle, 2.0 * kPi); } +inline double headingOf(const Point2& a, const Point2& b) { return std::atan2(b.y - a.y, b.x - a.x); } +inline double distanceOf(const Point2& a, const Point2& b) { return std::hypot(b.x - a.x, b.y - a.y); } + +/** @brief Threshold [mm] for comparing against GridRef::clearance_mm, which is rounded down. */ +inline int clearanceThresholdMm(double metres) { return static_cast(std::ceil(metres * 1000.0 - 1e-9)); } + +/** @brief Straight line legal for the centre: free cells, enough clearance, direction within `deviation_deg`. */ +bool lineOk(const GridRef& grid, const Point2& a, const Point2& b, double deviation_deg, int min_clearance_mm); +bool polylineOk(const GridRef& grid, const std::vector& points, double deviation_deg, int min_clearance_mm); + +/** @brief Rectangle against lethal and unknown cell squares. Leaving the grid or a blocked centre cell also counts. */ +bool footprintCollides(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y); + +/** @brief Traversal factor of a master costmap value. Inflation stays 1: the graph's clearance term covers it. */ +double costFactor(uint8_t value); + +/** @brief Length [m] weighted by costFactor. Infinity when a sample is blocked or off the grid. */ +double lineCost(const Point2& a, const Point2& b, const uint8_t* master, const GridRef& grid); + +/** @brief Dense centre check of the free-space clearance rule. Cells inside a zone are exempt. */ +bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm); +bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm, const std::atomic* cancel, + const std::chrono::steady_clock::time_point* deadline); + +/** @brief Path starts at `start` and ends at `goal`, yaw included when requested. */ +bool endpointOk(const Path& path, const Pose2& start, const Pose2& goal); + +/** @brief Reason string when an in-place turn at a path end hits something, otherwise null. */ +const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y); + +/** @brief True only when start and goal lie in different 8-connected components of free cells: no centre path exists. */ +bool enclosedByObstacles(const GridRef& grid, const Point2& start, const Point2& goal, + const std::atomic* cancel = nullptr); + +/** @brief Bounded shortest 8-connected directed route on the grid. + * @param length_m Output, set when found. + * @return False when no route shorter than `bound_m` was found. That never rejects a verified path. */ +bool shortestDirectedReference(const GridRef& grid, const Point2& start, const Point2& goal, double deviation_deg, + double bound_m, double* length_m, const std::atomic* cancel = nullptr); + +/** @brief True when every sample of the segment lies on the grid and outside all zones. */ +bool outsideZones(const Point2& a, const Point2& b, const GridRef& grid); + +/** @brief Result of the hard footprint gap rule. */ +struct GapCheck +{ + bool valid = false; + bool exemption_used = false; ///< A path end used its allowance. + double exemption_min_m = 0.0; ///< [m] Smallest gap inside the allowance. Meaningful with exemption_used. + double min_gap_m = 0.0; ///< [m] Infinity when no lethal cell is near. +}; + +/** @brief Exact rectangle to cell-square gap at sampled poses, at most 4 cm and 0.03 rad apart. + * + * A touch is always a failure. Near a path end the robot may already stand closer than `minimum_m`, so + * until the path first reaches it, the gap may not drop more than 1 mm below that end pose. */ +GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y, + const std::atomic* cancel = nullptr); +/** @param count_unknown Also measure the gap to unknown cells. The graph tier keeps false; the lattice tier passes true. */ +GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline, + bool count_unknown = false); + +/** @brief Same rule on a ready gap sequence, separated so it can be tested by hand. */ +GapCheck applyGapRule(const std::vector& gaps, double minimum_m); + +/** @brief Nodes among the first `count` of `nodes` closer than `upper_bound`, nearest first, at most `k`. + * @return Pairs of distance [m] and node index. */ +std::vector> nearestNodes(const std::vector& nodes, int32_t count, const Point2& point, + int32_t k, double upper_bound); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_GRID_CHECKS_H_ diff --git a/include/lane_route_core/path_verifier.h b/include/lane_route_core/path_verifier.h new file mode 100644 index 0000000..1a0a7db --- /dev/null +++ b/include/lane_route_core/path_verifier.h @@ -0,0 +1,38 @@ +#ifndef LANE_ROUTE_CORE_PATH_VERIFIER_H_ +#define LANE_ROUTE_CORE_PATH_VERIFIER_H_ + +#include +#include + +#include + +namespace lane_route_core +{ + +/** @brief Hard rules of a finished path. */ +struct PathCheck +{ + bool valid = false; + int zone_violations = 0; ///< Segment and cell pairs against the direction limit. + int footprint_collisions = 0; ///< Sampled poses hitting lethal or unknown cells, at most 1 cm and 0.03 rad apart. + int self_crossings = 0; ///< Crossings between non-neighbouring parts of the path. + int kinks = 0; ///< In-place turns away from both ends, plus bends above 8 deg over 0.1 m. + double max_curvature = 0.0; ///< [1/m] + double max_bend_deg = 0.0; ///< [deg] Largest bend over 0.1 m. +}; + +/** @brief Check a path against the grid, sharing no geometry with the code that built it. + * @param path Output poses. + * @param grid Live grid. + * @param deviation_deg Direction limit [deg]. + * @param config Footprint and tightest allowed radius. */ +PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config, + const std::atomic* cancel = nullptr); + +/** Bounded variant; an expired deadline returns an invalid result. */ +PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_PATH_VERIFIER_H_ diff --git a/include/lane_route_core/route_planner.h b/include/lane_route_core/route_planner.h new file mode 100644 index 0000000..a273ea8 --- /dev/null +++ b/include/lane_route_core/route_planner.h @@ -0,0 +1,114 @@ +#ifndef LANE_ROUTE_CORE_ROUTE_PLANNER_H_ +#define LANE_ROUTE_CORE_ROUTE_PLANNER_H_ + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace lane_route_core +{ + +/** @brief One planning request. */ +struct RouteRequest +{ + Pose2 start; + Pose2 goal; + std::vector changed_boxes; ///< Where the live grid differs from the compiled one. See changedBoxes(). + const std::atomic* cancel = nullptr; ///< Optional, owned by caller for the duration of the request. + bool lattice_only = false; ///< Offline diagnostics: skip the graph tier when lattice is enabled. +}; + +/** @brief What happened during a request. `reason` is "verified" on success, otherwise the failure. */ +struct PlanInfo +{ + std::string reason; + double rung_used_deg = -1.0; ///< Direction limit that produced the path, -1 on failure. + std::vector rung_reasons; + int retries = 0; ///< Route retries over all passes and rungs. + int gap_failures = 0; ///< Candidate paths below the footprint gap. + bool soft_cost_ignored = false; ///< The path came from the pass that ignores soft cost values. + std::string live_ridge; ///< "", "used", "failed" or "skipped_size": retry on a ridge from the live grid. + double gap_shortcut_raise_m = 0.0; ///< [m] Raise that met the gap, 0 when none was needed. + double min_gap_m = 0.0; ///< [m] Smallest footprint gap on the returned path. + bool gap_exemption_used = false; + std::vector radii_m; ///< Corner radii of the returned path. + double query_ms = 0.0; + double compile_ms = 0.0; ///< Graphs compiled by this request. + double search_ms = 0.0; + double build_ms = 0.0; + double verify_ms = 0.0; + double live_ridge_ms = 0.0; + int swing_windows = 0; ///< Sections with a swing searched again by least turning. + long swing_line_checks = 0; ///< Line checks spent on those searches. + int swing_builds = 0; ///< Extra path builds for those searches. + int swing_selected = 0; ///< Paths taken from those searches. + std::string tier_used; ///< "graph", "lattice" or empty on failure. + std::string graph_reason; ///< Most recent graph tier reason. + std::string lattice_reason; ///< Most recent lattice tier reason. + std::vector graph_rung_reasons; ///< Graph reasons, in attempted-rung order. + std::vector lattice_rung_reasons; ///< Lattice reasons, in attempted-rung order. + uint64_t lattice_states_expanded = 0; + uint64_t lattice_pose_checks = 0; + uint64_t lattice_field_cells = 0; + uint64_t lattice_tiles_built = 0; + uint64_t lattice_peak_bytes = 0; + uint64_t lattice_crossing_rejects = 0; ///< Rejected candidates across all rungs. + double lattice_ms = 0.0; ///< [ms] Accumulated lattice work across rungs. + double lattice_field_ms = 0.0; ///< [ms] Field construction across rungs. + double lattice_search_ms = 0.0; ///< [ms] Search excluding final candidate verification. + double lattice_verify_ms = 0.0; ///< [ms] Final candidate checks, included in lattice_ms. +}; + +/** @brief Outcome of a request. */ +struct PlanResult +{ + bool ok = false; + Path path; + PathCheck check; + PlanInfo info; +}; + +/** @brief Returns the compiled graph for a direction limit. May compile it and cache it. */ +using GraphProvider = std::function(double deviation_deg)>; + +/** @brief Plan with the direction ladder: stricter limits first, the configured limit last, one shared deadline. + * + * Each rung tries the route graph, then ignores soft cost values, then rebuilds a ridge from the live grid + * when the map changed. It never relaxes a hard rule, and no path means failure, for the backup planner. + * @param graphs Graph source. Its graphs must come from the same map and direction grid as `live`. + * @param request Start, goal and changed regions. + * @param live Live grid: master costmap values with clearance that includes new obstacles. + * @param config Planner parameters. + * @param backend Ridge computations. Empty functions disable the live retry and the preferred region. + * @return The path, or ok == false with info.reason. Never throws on a planning failure. */ +PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, + const PlannerConfig& config, const RidgeBackend& backend); + +/** @brief Regions where lethal or unknown cells differ between the compiled grid and the live grid. Inflation does not count. + * @param compiled_cost Compile grid, same layout as `live`. + * @return One box per 4-connected region of changed cells. */ +std::vector changedBoxes(const uint8_t* compiled_cost, const GridRef& live, + const std::atomic* cancel = nullptr, + std::vector* scratch = nullptr, std::vector* stack = nullptr); + +/** @brief Clearance of the live grid: the compiled clearance, lowered around lethal cells the compiled grid lacks. + * + * Only `radius_m` around each new cell is updated, which costs far less than a full distance transform. + * Keep it above every clearance threshold in PlannerConfig. + * @param compiled_cost Compile grid. + * @param compiled_clearance_mm Its clearance [mm]. + * @param live Live grid. Its clearance_mm is not read. + * @param radius_m Update radius [m]. + * @param clearance_mm Output, resized to the grid. */ +void patchClearance(const uint8_t* compiled_cost, const uint16_t* compiled_clearance_mm, const GridRef& live, + double radius_m, std::vector* clearance_mm, const std::atomic* cancel = nullptr); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_ROUTE_PLANNER_H_ diff --git a/include/lane_route_core/swing_chain.h b/include/lane_route_core/swing_chain.h new file mode 100644 index 0000000..b34c669 --- /dev/null +++ b/include/lane_route_core/swing_chain.h @@ -0,0 +1,84 @@ +#ifndef LANE_ROUTE_CORE_SWING_CHAIN_H_ +#define LANE_ROUTE_CORE_SWING_CHAIN_H_ + +#include +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ + +/** @brief Route points in travel order, before any shortcut. + * + * Greedy shortcutting takes the farthest visible point, so one point of the coarse graph decides what the next + * step can see: it can stop at a ridge peak and leave a hump although a straight line of the same clearance exists. + * This module picks the vertices of such a section again, this time by least turning. */ +struct RawChain +{ + std::vector vertices; + std::vector locked; ///< Lane points. They stay in every chain. + std::vector> boundaries; ///< (vertex index, route edge index) where edges join. +}; + +/** @brief What one shortcut needs from the grid. */ +struct SwingSearch +{ + std::function line_ok; ///< Legal at this clearance [mm]. + std::function line_cost; ///< Soft cost, as a shortcut must not cost more. + int tiers_mm[2] = { 0, 0 }; ///< Preferred clearance, then the minimum, with any raise already applied. + std::chrono::steady_clock::time_point deadline; + const std::atomic* cancel = nullptr; +}; + +/** @brief Work counters of a search. */ +struct SwingStats +{ + int windows = 0; + int oversize_windows = 0; ///< Still too long after trimming, left as they were. + int trimmed_windows = 0; + long line_checks = 0; +}; + +/** @brief Indices j where the turns at vertices j and j + 1 have opposite signs. */ +std::vector oppositePairs(const std::vector& chain); + +/** @brief Sum of absolute turn angles along a vertex chain [rad]. */ +double chainTurning(const std::vector& chain); + +/** @brief Sum of absolute heading changes while moving [rad]. Spins in place at the ends do not count. */ +double movingTurning(const Path& path); + +/** @brief True when the candidate replaces the baseline: less turning, and not a long way round for it. + * + * Less turning alone is not enough. On a real map 3.4 degrees less turning cost 2 m of extra path. */ +bool preferLessTurning(const Path& candidate, const Path& baseline); + +/** @brief Choose vertices start..end of the raw points by least turning. + * + * An allowed step uses the same clearance tiers as the greedy shortcut. Cost per step is the absolute turn in + * degrees, plus a length term, plus a penalty when the turn changes sign. + * @param preceding Chain vertex before the window, or null. Its turn into the window counts. + * @param preceding_sign Sign of the last turn before the window, 0 when none. + * @param following Chain vertex after the window, or null. + * @param following_sign Sign of the first turn after the window, 0 when none. + * @param selected Chosen raw indices, ascending, always holding start, end and every locked point between. + * @return False when out of time or the window is too long. */ +bool solveSwingWindow(const std::vector& raw, const std::vector& locked, std::size_t start, std::size_t end, + const SwingSearch& search, const Point2* preceding, int preceding_sign, const Point2* following, + int following_sign, SwingStats* stats, std::vector* selected); + +/** @brief Replace the sections of a greedy chain that hold opposite turns. + * @param greedy Chain from the greedy shortcut. + * @param indices Raw indices of the new chain. + * @return False when the greedy chain has no opposite turns, or nothing changed. */ +bool optimizeSwingChain(const RawChain& raw, const std::vector& greedy, const SwingSearch& search, SwingStats* stats, + std::vector* vertices, std::vector* indices); + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_SWING_CHAIN_H_ diff --git a/include/lane_route_core/types.h b/include/lane_route_core/types.h new file mode 100644 index 0000000..9599540 --- /dev/null +++ b/include/lane_route_core/types.h @@ -0,0 +1,154 @@ +#ifndef LANE_ROUTE_CORE_TYPES_H_ +#define LANE_ROUTE_CORE_TYPES_H_ + +#include +#include +#include +#include +#include + +namespace lane_route_core +{ + +// Same values as robot_costmap_2d/cost_values.h. The core stays free of costmap dependencies, +// so the adapter that fills GridRef relies on these two tables agreeing. +constexpr uint8_t kCriticalSpace = 0; +constexpr uint8_t kPreferredSpace = 20; +constexpr uint8_t kFreeSpace = 60; +constexpr uint8_t kUnpreferredSpace = 100; +constexpr uint8_t kInscribedCost = 253; +constexpr uint8_t kLethalCost = 254; +constexpr uint8_t kNoInformation = 255; + +constexpr double kPi = 3.141592653589793; + +struct Point2 +{ + double x = 0.0, y = 0.0; ///< [m] Global frame. +}; + +/** @brief Pose request. A start without yaw means the robot may leave along the first line. */ +struct Pose2 +{ + double x = 0.0, y = 0.0; ///< [m] Global frame. + double yaw = 0.0; ///< [rad] + bool has_yaw = true; +}; + +/** @brief One output pose. */ +struct PathPoint +{ + double x, y; ///< [m] Global frame. + double yaw; ///< [rad] + double curvature; ///< [1/m] Signed, 0 on lines and in-place turns. +}; +using Path = std::vector; + +/** @brief World box [m] holding cells that differ from the compiled map. */ +struct WorldBox +{ + double x_min, y_min, x_max, y_max; +}; + +/** @brief Aligned non-owning grids, row-major. The caller keeps them alive during the call. */ +struct GridRef +{ + int32_t width = 0, height = 0; ///< [cells] + double resolution = 0.0; ///< [m/cell] + double origin_x = 0.0, origin_y = 0.0; ///< [m] Lower-left corner. + const uint8_t* cost = nullptr; ///< Master costmap values, see the constants above. + const uint16_t* clearance_mm = nullptr; ///< [mm] Distance to the nearest lethal cell, rounded down. + const uint8_t* direction = nullptr; ///< May be null. 0 unconstrained, 1..8 direction index + 1, CCW from +X. +}; + +/** @brief Undirected ridge segment from the coarse graph. */ +struct CoarseEdge +{ + int32_t from, to; ///< Indices into CoarseGraph::nodes. + std::vector points; ///< [m] from -> to. +}; + +/** @brief Straight one-way lane from the coarse graph, in travel direction. */ +struct CoarseLane +{ + uint8_t direction_index; ///< 0..7 CCW from +X. + Point2 entry, exit; ///< [m] + double length_m; ///< [m] + double offset_from_centre_m; ///< [m] +}; + +/** @brief Steps 1 and 2 of the graph, computed outside this library. */ +struct CoarseGraph +{ + std::vector nodes; + std::vector edges; + std::vector lanes; +}; + +/** @brief Ridge computations the core needs but does not own: they live in robot_costmap_2d. + * An empty function disables the feature that needs it, so a test can run without them. */ +struct RidgeBackend +{ + /** Steps 1 and 2 on a grid window whose clearance_mm comes from the whole map. Used by the live retry. */ + std::function* cancel)> build_coarse; + /** Nodes and edges of the centre line of `mask`, split at direction changes. Used for the preferred region. */ + std::function& mask, const GridRef& grid, std::vector* nodes, + std::vector* edges, const std::atomic* cancel)> + region_centre_edges; +}; + +/** @brief Planner parameters. Lengths [m], angles [deg]. Defaults match the approved SEHC simulation margins. */ +struct PlannerConfig +{ + double half_x_m = 0.30; ///< Footprint rectangle half length. + double half_y_m = 0.30; ///< Footprint rectangle half width. + double clearance_hard_m = 0.335; ///< Centre clearance on every graph line. + double clearance_min_m = 0.335; ///< Centre clearance of the final path outside zones. + double clearance_preferred_m = 0.60; ///< Clearance tried first when pulling a line straight. + double collision_check_distance_m = 0.48; ///< Closer than this, a curve pose gets the full footprint test. + double min_turn_radius_m = 1.06; ///< Tightest curve the final check accepts. + std::vector corner_radii_m{ 1.9, 1.75, 1.6, 1.45, 1.3, 1.18, 1.08 }; ///< Tried in order. + double footprint_min_gap_m = 0.03; ///< Smallest footprint to lethal gap on the whole path. + std::vector footprint_gap_shortcut_raise_m{ 0.05, 0.10 }; ///< Empty: check only. + double max_deviation_deg = 90.0; ///< Configured direction limit, the last ladder rung. + std::vector deviation_ladder_deg{ 0.01 }; ///< Stricter rungs tried first. + double route_too_long_ratio = 1.5; ///< Refuse paths longer than ratio * shortest directed grid route + margin. + double route_too_long_margin_m = 2.0; + double suspicious_ratio = 1.3; ///< Only paths above ratio * straight distance + margin run that search. + double suspicious_margin_m = 2.0; + int max_route_attempts = 24; ///< Route retries per pass. Each failed corner bans one edge pair, so reaching a gate can take about 20. + double time_limit_s = 20.0; ///< Shared by every rung and pass. + double output_step_m = 0.04; ///< Spacing of output poses. + double live_ridge_pad_m = 6.0; ///< Margin of the live retry window around start and goal. + int64_t live_ridge_max_cells = 1500000; ///< Larger windows skip the live retry. + + bool lattice_enabled = false; ///< Enable fallback after the graph tier. + int lattice_heading_bins = 72; ///< Heading divisions per revolution, even. + double lattice_closed_resolution_m = 0.10; ///< [m] Maximum x/y search bin size. + double lattice_heuristic_weight = 3.0; ///< Weighted A* heuristic multiplier. 3.0 solved the most regress7 runs within 3 s (kit +10 over 1.5). + double lattice_bucket_width_m = 0.25; ///< [m] FIFO priority bucket width; 0 uses exact heap priority. + double lattice_field_clearance_weight_m = 0.25; ///< [m] Reverse-field clearance cost; 0.25 matches lattice_wall_weight_m so the heuristic and the path cost agree. + double lattice_wall_weight_m = 0.25; ///< [m] Search clearance cost. + double lattice_switch_cost_m = 0.35; ///< [m] Penalty for changing nonzero steering sign. + double lattice_steer_cost_m = 0.012; ///< [m] Penalty per basic curved step. + int lattice_primitive_multiple_1 = 1; ///< First primitive length in basic steps. + int lattice_primitive_multiple_2 = 3; ///< Second primitive length in basic steps. + int lattice_primitive_multiple_3 = 6; ///< Third primitive length in basic steps. + double lattice_analytic_radius_m = 1.08; ///< [m] Analytic radius, clamped to min_turn_radius_m. + int lattice_analytic_interval = 20000; ///< Expansions between analytic attempts. + double lattice_analytic_near_goal_m = 2.0; ///< [m] Also attempt analytic connection inside this distance. + int lattice_analytic_goal_headings = 16; ///< Uniform arrival headings for analytic Dubins candidates, 0 disables the set. + double lattice_field_time_fraction = 0.4; ///< Fraction of a rung's fallback slice for the field. + int lattice_field_cell_factor = 0; ///< 0 selects automatically, 1 uses the original grid resolution. + int64_t lattice_field_max_cells = 1000000; ///< Maximum cells for automatic field sizing. + double fallback_time_limit_s = 3.0; ///< [s] Shared across all lattice rungs and later smoothing. + double lattice_end_relax_radius_m = 1.0; ///< [m] Within this distance of start or goal the C-space gap is that end pose's own gap minus 1 mm (capped at footprint_min_gap_m); the final gap check still applies. + int64_t lattice_max_memory_mb = 512; ///< [MiB] Cap on tracked lattice allocations; see R1_design.md. + + /** @return Empty when valid, otherwise a description of the first bad value. */ + std::string validate() const; +}; + +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_TYPES_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..9c41ace --- /dev/null +++ b/package.xml @@ -0,0 +1,15 @@ + + lane_route_core + 0.1.0 + + Global route planning on a coarse graph of Voronoi ridges and one-way lanes: directed graph per + direction limit, route search, clothoid paths and independent checks. Plain algorithms with no + ROS and no costmap dependency. The optional costmap backend header, tests and eval tool use robot_costmap_2d. + + duongtd + BSD + + catkin + robot_costmap_2d + robot_costmap_2d + diff --git a/src/clothoid.cpp b/src/clothoid.cpp new file mode 100644 index 0000000..f6c46a5 --- /dev/null +++ b/src/clothoid.cpp @@ -0,0 +1,147 @@ +#include + +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ + +void fresnelSeries(double x, double* s, double* c) +{ + const double half_pi = kPi / 2.0; + const double x2 = x * x; + const double step = half_pi * half_pi * x2 * x2; + double term = x; + double sum = 0.0; + for (int k = 0; k < 40; ++k) + { + const double add = term / (4 * k + 1); + sum += add; + if (std::abs(add) < 1e-19 && k > 1) + break; + term = -term * step / ((2 * k + 1) * (2 * k + 2)); + } + *c = sum; + term = half_pi * x2 * x; + sum = 0.0; + for (int k = 0; k < 40; ++k) + { + const double add = term / (4 * k + 3); + sum += add; + if (std::abs(add) < 1e-19 && k > 1) + break; + term = -term * step / ((2 * k + 2) * (2 * k + 3)); + } + *s = sum; +} + +Path clothoidCorner(double angle, double radius, double sharpness, double spacing) +{ + const double a = std::abs(angle); + if (!(a > 0.0 && a < kPi && radius > 0.0 && sharpness > 0.0 && spacing > 0.0)) + throw std::invalid_argument("clothoidCorner: angle, radius, sharpness or spacing out of range"); + + using Complex = std::complex; + const Complex unit(0.0, 1.0); + const double spiral_length = std::min(1.0 / (radius * sharpness), std::sqrt(a / sharpness)); + const double k = sharpness * spiral_length; + const double arc_length = std::max(0.0, (a - sharpness * spiral_length * spiral_length) / k); + const double length = 2.0 * spiral_length + arc_length; + + const double scale = std::sqrt(kPi / sharpness); + const double to_argument = std::sqrt(sharpness / kPi); + const auto spiral = [&](double s) { + double fs = 0.0, fc = 0.0; + fresnelSeries(s * to_argument, &fs, &fc); + return Complex(scale * fc, scale * fs); + }; + const Complex z1 = spiral(spiral_length); + const double h1 = sharpness * spiral_length * spiral_length / 2.0; + const Complex za = (std::exp(unit * (h1 + k * arc_length)) - std::exp(unit * h1)) / (unit * k); + + // Uniform samples plus the phase boundaries, sorted and without near-duplicates. + const int count = static_cast(std::ceil(length / spacing)) + 1; + std::vector raw; + raw.reserve(static_cast(count) + 2); + const double uniform = count > 1 ? length / (count - 1) : 0.0; + for (int i = 0; i < count; ++i) + raw.push_back(i == count - 1 ? length : i * uniform); + raw.push_back(spiral_length); + raw.push_back(spiral_length + arc_length); + std::sort(raw.begin(), raw.end()); + raw.erase(std::unique(raw.begin(), raw.end()), raw.end()); + std::vector samples; + samples.reserve(raw.size()); + for (std::size_t i = 0; i < raw.size(); ++i) + if (i == 0 || raw[i] - raw[i - 1] > 1e-8) + samples.push_back(raw[i]); + if (length - samples.back() > 1e-8) + samples.push_back(length); + else + samples.back() = length; + + const double sign = angle > 0.0 ? 1.0 : -1.0; + Path output; + output.reserve(samples.size()); + for (double s : samples) + { + Complex z; + double heading, curvature; + if (s <= spiral_length) + { + z = spiral(s); + heading = sharpness * s * s / 2.0; + curvature = sharpness * s; + } + else if (s <= spiral_length + arc_length) + { + const double t = s - spiral_length; + z = z1 + (std::exp(unit * (h1 + k * t)) - std::exp(unit * h1)) / (unit * k); + heading = h1 + k * t; + curvature = k; + } + else + { + const double t = s - spiral_length - arc_length; + const double rest = spiral_length - t; + z = z1 + za + std::exp(unit * a) * std::conj(z1 - spiral(rest)); + heading = a - sharpness * rest * rest / 2.0; + curvature = sharpness * rest; + } + output.push_back({ z.real(), sign * z.imag(), sign * heading, sign * curvature }); + } + return output; +} + +double tangentTrim(double angle, const Path& curve) { return curve.back().y / std::sin(angle); } + +Path placedCorner(const Point2& a, const Point2& b, const Point2& c, double radius, double sharpness, double spacing, + double* trim) +{ + const double h0 = headingOf(a, b); + const double angle = wrapAngle(headingOf(b, c) - h0); + if (std::abs(angle) < 1e-8 || std::abs(angle) >= kPi - 1e-5) + return Path(); + Path curve = clothoidCorner(angle, radius, sharpness, spacing); + *trim = tangentTrim(angle, curve); + const double co = std::cos(h0); + const double si = std::sin(h0); + const double entry_x = b.x - *trim * co; + const double entry_y = b.y - *trim * si; + for (PathPoint& point : curve) + { + const double x = point.x; + const double y = point.y; + point.x = entry_x + co * x - si * y; + point.y = entry_y + si * x + co * y; + point.yaw += h0; + } + return curve; +} + +} // namespace lane_route_core diff --git a/src/graph_compiler.cpp b/src/graph_compiler.cpp new file mode 100644 index 0000000..8a69550 --- /dev/null +++ b/src/graph_compiler.cpp @@ -0,0 +1,314 @@ +#include + +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace +{ + +constexpr double kLeadStepM = 0.25; +constexpr int kLeadSteps = 10; // Straight lead of at most 2.5 m on each lane end. +// Must not exceed the depth of a gate zone. Gates are about 0.5 m deep, and a strict rung has no other way through them. +constexpr double kMinCompiledLaneM = 0.3; +constexpr double kLaneOffsetPenalty = 2.8; // Per metre off the zone's main lane, so routes stay on it when they can. +constexpr double kShortLeads[4] = { 0.25, 0.5, 1.0, 1.5 }; +constexpr double kJunctionRadiusM = 6.0; +constexpr int32_t kJunctionCandidates = 50; +constexpr int kJunctionLinks = 12; +constexpr double kPreferredAttachRadiusM = 6.0; +constexpr int32_t kPreferredAttachCandidates = 30; +constexpr double kMinLinkM = 0.05; +constexpr double kClearancePenalty = 0.25; +constexpr double kClearancePenaltyStartM = 0.6; + +double polylineLength(const std::vector& points) +{ + double total = 0.0; + for (std::size_t i = 0; i + 1 < points.size(); ++i) + total += distanceOf(points[i], points[i + 1]); + return total; +} + +/** Sample cells of one polyline, spaced at most half a cell. */ +template +void forEachSample(const std::vector& points, const GridRef& grid, Visit visit) +{ + const double half = grid.resolution * 0.5; + for (std::size_t i = 0; i + 1 < points.size(); ++i) + { + const double dx = points[i + 1].x - points[i].x; + const double dy = points[i + 1].y - points[i].y; + const double length = std::hypot(dx, dy); + if (length < 1e-12) + continue; + const int samples = std::max(1, static_cast(std::ceil(length / half))); + const double weight = length / samples; + for (int j = 0; j < samples; ++j) + { + const double t = (j + 0.5) / samples; + const double fx = std::floor((points[i].x + dx * t - grid.origin_x) / grid.resolution); + const double fy = std::floor((points[i].y + dy * t - grid.origin_y) / grid.resolution); + const bool inside = fx >= 0.0 && fy >= 0.0 && fx < grid.width && fy < grid.height; + visit(inside ? static_cast(fy) * grid.width + static_cast(fx) : -1, weight); + } + } +} + +/** Length-weighted mean of the cost factors. Blocked or off-grid samples make the edge impassable. */ +class FactorSum +{ +public: + void add(int32_t cell, double weight, const uint8_t* master) + { + const uint8_t value = cell >= 0 ? master[cell] : kNoInformation; + cost_ += weight * costFactor(value); + length_ += weight; + blocked_ = blocked_ || value >= kInscribedCost; + } + double factor() const + { + if (blocked_) + return std::numeric_limits::infinity(); + return length_ > 0.0 ? cost_ / length_ : 1.0; + } + +private: + double cost_ = 0.0, length_ = 0.0; + bool blocked_ = false; +}; + +} // namespace + +double edgeFactor(const std::vector& points, const uint8_t* master, const GridRef& grid) +{ + FactorSum sum; + forEachSample(points, grid, [&](int32_t cell, double weight) { sum.add(cell, weight, master); }); + return sum.factor(); +} + +void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector* factors) +{ + factors->resize(graph.edges.size()); + for (std::size_t i = 0; i < graph.edges.size(); ++i) + { + FactorSum sum; + for (int32_t k = graph.sample_offsets[i]; k < graph.sample_offsets[i + 1]; ++k) + sum.add(graph.sample_cells[static_cast(k)], graph.sample_weights[static_cast(k)], master); + (*factors)[i] = sum.factor(); + } +} + +CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const uint8_t* master, double deviation_deg, + const PlannerConfig& config, const RidgeBackend& backend, const std::atomic* cancel) +{ + const auto cancelled = [cancel]() { return cancel && cancel->load(std::memory_order_relaxed); }; + if (cancelled()) return {}; + const int hard_mm = clearanceThresholdMm(config.clearance_hard_m); + const auto line_ok = [&](const Point2& a, const Point2& b) { return lineOk(grid, a, b, deviation_deg, hard_mm); }; + const auto poly_ok = [&](const std::vector& points) { return polylineOk(grid, points, deviation_deg, hard_mm); }; + + CompiledGraph graph; + graph.deviation_deg = deviation_deg; + graph.nodes = coarse.nodes; + const int32_t voronoi_nodes = static_cast(graph.nodes.size()); + + const auto add_both_ways = [&](int32_t from, int32_t to, const std::vector& points, EdgeKind kind) { + const double length = polylineLength(points); + if (poly_ok(points)) + graph.edges.push_back({ from, to, points, kind, length }); + std::vector reversed(points.rbegin(), points.rend()); + if (poly_ok(reversed)) + graph.edges.push_back({ to, from, std::move(reversed), kind, length }); + }; + for (const CoarseEdge& edge : coarse.edges) + { + if (cancelled()) return {}; + add_both_ways(edge.from, edge.to, edge.points, EdgeKind::kVoronoi); + } + + // Lanes with the longest legal straight lead on each end. + std::vector lane_ends; + const auto add_node = [&](const Point2& point) { + graph.nodes.push_back(point); + return static_cast(graph.nodes.size()) - 1; + }; + for (const CoarseLane& lane : coarse.lanes) + { + if (cancelled()) return {}; + if (lane.length_m < kMinCompiledLaneM) + continue; + const double angle = lane.direction_index * kPi / 4.0; + const double ux = std::cos(angle); + const double uy = std::sin(angle); + const Point2 a = lane.entry; + const Point2 b = lane.exit; + const auto along = [&](const Point2& origin, double distance) { + return Point2{ origin.x + distance * ux, origin.y + distance * uy }; + }; + Point2 left = a; + Point2 right = b; + for (int k = 1; k <= kLeadSteps; ++k) + { + const Point2 candidate = along(a, -kLeadStepM * k); + if (!line_ok(candidate, a)) + break; + left = candidate; + } + for (int k = 1; k <= kLeadSteps; ++k) + { + const Point2 candidate = along(b, kLeadStepM * k); + if (!line_ok(b, candidate)) + break; + right = candidate; + } + const std::vector full{ left, a, b, right }; + if (!poly_ok(full)) + continue; + const double penalty = kLaneOffsetPenalty * lane.offset_from_centre_m; + const int32_t u = add_node(left); + const int32_t v = add_node(right); + graph.edges.push_back({ u, v, full, EdgeKind::kLane, polylineLength(full) + penalty }); + lane_ends.push_back(u); + lane_ends.push_back(v); + + // A goal may lie just outside a zone: shorter exits on the straight lead, without turning off the lane. + std::vector> exits{ { v, right } }; + const double lead_out = distanceOf(b, right); + for (double distance : kShortLeads) + { + if (distance >= lead_out - 0.02) + continue; + const Point2 stop = along(b, distance); + const int32_t w = add_node(stop); + exits.emplace_back(w, stop); + const std::vector shorter{ left, a, b, stop }; + graph.edges.push_back({ u, w, shorter, EdgeKind::kLane, polylineLength(shorter) + penalty }); + } + // Entries on the lead as well. With only the far entry, a start beside the lead has to pass it + // and circle back to enter the lane, which is how self-crossing loops appeared. + const double lead_in = distanceOf(a, left); + for (double distance : kShortLeads) + { + if (distance >= lead_in - 0.02) + continue; + const Point2 begin = along(a, -distance); + const int32_t w = add_node(begin); + for (const auto& target : exits) + { + const std::vector shorter{ begin, a, b, target.second }; + graph.edges.push_back({ w, target.first, shorter, EdgeKind::kLane, polylineLength(shorter) + penalty }); + } + } + } + + // Links between lane ends and the network, both ways where the direction limit allows. + std::vector junction_ids(static_cast(voronoi_nodes)); + for (int32_t i = 0; i < voronoi_nodes; ++i) + junction_ids[static_cast(i)] = i; + junction_ids.insert(junction_ids.end(), lane_ends.begin(), lane_ends.end()); + std::vector junction_points; + junction_points.reserve(junction_ids.size()); + for (int32_t id : junction_ids) + junction_points.push_back(graph.nodes[static_cast(id)]); + const int32_t junction_count = static_cast(junction_points.size()); + for (int32_t u : lane_ends) + { + if (cancelled()) return {}; + const Point2 here = graph.nodes[static_cast(u)]; + int accepted = 0; + for (const auto& found : nearestNodes(junction_points, junction_count, here, + std::min(junction_count, kJunctionCandidates), kJunctionRadiusM)) + { + const int32_t v = junction_ids[static_cast(found.second)]; + if (v == u || found.first < kMinLinkM) + continue; + const Point2 there = graph.nodes[static_cast(v)]; + if (line_ok(here, there)) + graph.edges.push_back({ u, v, { here, there }, EdgeKind::kJunction, found.first }); + if (line_ok(there, here)) + graph.edges.push_back({ v, u, { there, here }, EdgeKind::kJunction, found.first }); + if (++accepted >= kJunctionLinks) + break; + } + } + + // Preferred region: its centre line joins the network. Direction grid and real clearance still gate each edge. + const std::size_t cell_count = static_cast(grid.width) * static_cast(grid.height); + if (master != nullptr && backend.region_centre_edges && std::find(master, master + cell_count, kPreferredSpace) != master + cell_count) + { + std::vector mask(cell_count, 0); + for (std::size_t i = 0; i < cell_count; ++i) + { + if ((i & 4095u) == 0 && cancelled()) return {}; + mask[i] = master[i] == kPreferredSpace && grid.cost[i] < kInscribedCost ? 1 : 0; + } + std::vector preferred_nodes; + std::vector preferred_edges; + if (cancelled()) return {}; + backend.region_centre_edges(mask, grid, &preferred_nodes, &preferred_edges, cancel); + if (cancelled()) return {}; + const int32_t base = static_cast(graph.nodes.size()); + graph.nodes.insert(graph.nodes.end(), preferred_nodes.begin(), preferred_nodes.end()); + for (const CoarseEdge& edge : preferred_edges) + add_both_ways(base + edge.from, base + edge.to, edge.points, EdgeKind::kPreferredRidge); + if (base > 0) + { + for (std::size_t local = 0; local < preferred_nodes.size(); ++local) + { + if (cancelled()) return {}; + const Point2 here = preferred_nodes[local]; + const int32_t id = base + static_cast(local); + for (const auto& found : nearestNodes(graph.nodes, base, here, std::min(base, kPreferredAttachCandidates), kPreferredAttachRadiusM)) + { + if (found.first < kMinLinkM) + continue; + const Point2 there = graph.nodes[static_cast(found.second)]; + if (line_ok(there, here)) + graph.edges.push_back({ found.second, id, { there, here }, EdgeKind::kPreferredAttach, found.first }); + if (line_ok(here, there)) + graph.edges.push_back({ id, found.second, { here, there }, EdgeKind::kPreferredAttach, found.first }); + } + } + } + } + + // Penalise low clearance without changing the hard clearance rule. + for (GraphEdge& edge : graph.edges) + { + if (cancelled()) return {}; + int minimum_mm = std::numeric_limits::max(); + for (const Point2& point : edge.points) + { + const int32_t ix = std::min(grid.width - 1, std::max(0, static_cast(std::floor((point.x - grid.origin_x) / grid.resolution)))); + const int32_t iy = std::min(grid.height - 1, std::max(0, static_cast(std::floor((point.y - grid.origin_y) / grid.resolution)))); + minimum_mm = std::min(minimum_mm, grid.clearance_mm[iy * grid.width + ix]); + } + const double clearance = minimum_mm / 1000.0; + edge.cost += kClearancePenalty * polylineLength(edge.points) * + std::max(0.0, (kClearancePenaltyStartM - clearance) / kClearancePenaltyStartM); + } + + graph.outgoing.resize(graph.nodes.size()); + graph.sample_offsets.reserve(graph.edges.size() + 1); + graph.sample_offsets.push_back(0); + for (std::size_t i = 0; i < graph.edges.size(); ++i) + { + if (cancelled()) return {}; + graph.outgoing[static_cast(graph.edges[i].from)].push_back(static_cast(i)); + forEachSample(graph.edges[i].points, grid, [&](int32_t cell, double weight) { + graph.sample_cells.push_back(cell); + graph.sample_weights.push_back(weight); + }); + graph.sample_offsets.push_back(static_cast(graph.sample_cells.size())); + } + return graph; +} + +} // namespace lane_route_core diff --git a/src/grid_checks.cpp b/src/grid_checks.cpp new file mode 100644 index 0000000..0c9306e --- /dev/null +++ b/src/grid_checks.cpp @@ -0,0 +1,635 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace lane_route_core +{ +namespace +{ + +constexpr double kInfinity = std::numeric_limits::infinity(); +constexpr double kEndpointGapToleranceM = 0.001; + +/** Floor division on the grid. Returns false off the grid. */ +inline bool cellOf(const GridRef& grid, double x, double y, int32_t* cell) +{ + const double fx = std::floor((x - grid.origin_x) / grid.resolution); + const double fy = std::floor((y - grid.origin_y) / grid.resolution); + if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height) + return false; + *cell = static_cast(fy) * grid.width + static_cast(fx); + return true; +} + +/** Python-style modulo, which the prototype's direction test is written with. */ +inline double positiveMod(double value, double modulus) +{ + const double result = std::fmod(value, modulus); + return result != 0.0 && result < 0.0 ? result + modulus : result; +} + +/** Exact gap between an oriented rectangle and one axis-aligned cell square. Zero when they touch. */ +double rectangleCellGap(double centre_x, double centre_y, double x, double y, double c, double s, double half_x, + double half_y, double half_cell) +{ + const double dx = centre_x - x; + const double dy = centre_y - y; + const double lx = c * dx + s * dy; + const double ly = -s * dx + c * dy; + const double abs_c = std::abs(c); + const double abs_s = std::abs(s); + const double projected = half_cell * (abs_c + abs_s); + if (std::abs(dx) <= half_x * abs_c + half_y * abs_s + half_cell && + std::abs(dy) <= half_x * abs_s + half_y * abs_c + half_cell && std::abs(lx) <= half_x + projected && + std::abs(ly) <= half_y + projected) + return 0.0; + // Disjoint convex polygons: the closest pair always has a vertex of one of them. + double best = kInfinity; + for (double a : { -half_cell, half_cell }) + { + for (double b : { -half_cell, half_cell }) + { + const double px = lx + c * a + s * b; + const double py = ly - s * a + c * b; + best = std::min(best, std::hypot(std::max(std::abs(px) - half_x, 0.0), std::max(std::abs(py) - half_y, 0.0))); + } + } + for (double a : { -half_x, half_x }) + { + for (double b : { -half_y, half_y }) + { + const double px = c * a - s * b - dx; + const double py = s * a + c * b - dy; + best = std::min(best, std::hypot(std::max(std::abs(px) - half_cell, 0.0), std::max(std::abs(py) - half_cell, 0.0))); + } + } + return best; +} + +} // namespace + +std::string PlannerConfig::validate() const +{ + std::ostringstream error; + const auto positive = [](double value) { return std::isfinite(value) && value > 0.0; }; + const auto not_negative = [](double value) { return std::isfinite(value) && value >= 0.0; }; + if (!positive(half_x_m) || !positive(half_y_m)) + error << "footprint half sizes must be finite and > 0"; + else if (!not_negative(clearance_hard_m) || !not_negative(clearance_min_m) || !not_negative(clearance_preferred_m)) + error << "clearances must be finite and >= 0"; + else if (!positive(collision_check_distance_m) || !positive(min_turn_radius_m)) + error << "collision_check_distance_m and min_turn_radius_m must be finite and > 0"; + else if (corner_radii_m.empty()) + error << "corner_radii_m must not be empty"; + else if (std::any_of(corner_radii_m.begin(), corner_radii_m.end(), [&](double r) { return !positive(r) || r < min_turn_radius_m; })) + error << "corner_radii_m must be finite and not below min_turn_radius_m"; + else if (!not_negative(footprint_min_gap_m)) + error << "footprint_min_gap_m must be finite and >= 0"; + else if (std::any_of(footprint_gap_shortcut_raise_m.begin(), footprint_gap_shortcut_raise_m.end(), [&](double v) { return !positive(v); })) + error << "footprint_gap_shortcut_raise_m values must be finite and > 0"; + else if (!std::isfinite(max_deviation_deg) || max_deviation_deg < 0.0 || max_deviation_deg >= 180.0) + error << "max_deviation_deg must be in [0, 180)"; + else if (std::any_of(deviation_ladder_deg.begin(), deviation_ladder_deg.end(), [&](double v) { return !not_negative(v); })) + error << "deviation_ladder_deg values must be finite and >= 0"; + else if (!positive(route_too_long_ratio) || !not_negative(route_too_long_margin_m) || !positive(suspicious_ratio) || + !not_negative(suspicious_margin_m)) + error << "route length limits must be finite, ratios > 0, margins >= 0"; + else if (max_route_attempts < 1) + error << "max_route_attempts must be >= 1"; + else if (!positive(time_limit_s) || !positive(output_step_m)) + error << "time_limit_s and output_step_m must be finite and > 0"; + else if (!not_negative(live_ridge_pad_m) || live_ridge_max_cells < 0) + error << "live ridge limits must be >= 0"; + else if (lattice_enabled && (lattice_heading_bins < 8 || lattice_heading_bins > 1024 || lattice_heading_bins % 2 != 0)) + error << "lattice_heading_bins must be even and in [8, 1024]"; + else if (lattice_enabled && (!positive(lattice_closed_resolution_m) || !std::isfinite(lattice_heuristic_weight) || lattice_heuristic_weight < 1.0 || + !not_negative(lattice_bucket_width_m) || + !not_negative(lattice_field_clearance_weight_m) || !not_negative(lattice_wall_weight_m) || + !not_negative(lattice_switch_cost_m) || !not_negative(lattice_steer_cost_m))) + error << "invalid lattice resolution or cost weights"; + else if (lattice_enabled && (lattice_primitive_multiple_1 != 1 || lattice_primitive_multiple_2 < 1 || lattice_primitive_multiple_3 < lattice_primitive_multiple_2 || + lattice_primitive_multiple_3 > 64)) + error << "lattice primitive multiples must start at 1 and be ordered, up to 64"; + else if (lattice_enabled && (!positive(lattice_analytic_radius_m) || lattice_analytic_interval < 1 || !not_negative(lattice_analytic_near_goal_m) || + lattice_analytic_goal_headings < 0 || lattice_analytic_goal_headings > 360 || + !std::isfinite(lattice_field_time_fraction) || lattice_field_time_fraction < 0.0 || lattice_field_time_fraction > 1.0 || + lattice_field_cell_factor < 0 || lattice_field_max_cells < 1 || + lattice_field_max_cells > std::numeric_limits::max() || + !positive(fallback_time_limit_s) || fallback_time_limit_s > 86400.0 || !not_negative(lattice_end_relax_radius_m) || + lattice_max_memory_mb < 1 || lattice_max_memory_mb > 1048576)) + error << "invalid lattice analytic, time or memory limits"; + return error.str(); +} + +namespace +{ +constexpr int kLineWideStep = 16; // Samples: at half-cell sampling on a 0.05 m grid this is 0.4 m. +} // namespace + +bool lineOk(const GridRef& grid, const Point2& a, const Point2& b, double deviation_deg, int min_clearance_mm) +{ + const double dx = b.x - a.x; + const double dy = b.y - a.y; + const double length = std::hypot(dx, dy); + if (length < 1e-9) + return true; + + bool allowed[9]; + allowed[0] = true; + if (grid.direction != nullptr) + { + const double angle = std::atan2(dy, dx); + const double limit = deviation_deg * kPi / 180.0 + 1e-9; + for (int code = 1; code <= 8; ++code) + { + const double delta = std::abs(positiveMod(angle - (code - 1) * kPi / 4.0 + kPi, 2.0 * kPi) - kPi); + allowed[code] = !(delta > limit); + } + } + + const int samples = std::max(2, static_cast(std::ceil(length / (grid.resolution * 0.5))) + 1); + const double step = 1.0 / (samples - 1); + const auto sample_ok = [&](int i) { + const double t = i == samples - 1 ? 1.0 : i * step; + int32_t cell = 0; + if (!cellOf(grid, a.x + dx * t, a.y + dy * t, &cell)) + return false; + if (grid.cost[cell] >= kInscribedCost || grid.clearance_mm[cell] < min_clearance_mm) + return false; + if (grid.direction != nullptr) + { + const uint8_t code = grid.direction[cell]; + if (code <= 8 && !allowed[code]) + return false; + } + return true; + }; + // Every sample must pass, so their order changes only the time. Cells below the clearance form a band about twice + // the threshold wide around an obstacle, so a line that crosses one fails within a few wide steps. Walking from the + // start would first read every free cell before it, and most long lines tried by the shortcut search do fail. + for (int i = 0; i < samples; i += kLineWideStep) + if (!sample_ok(i)) + return false; + for (int i = 0; i < samples; ++i) + if (i % kLineWideStep != 0 && !sample_ok(i)) + return false; + return true; +} + +bool polylineOk(const GridRef& grid, const std::vector& points, double deviation_deg, int min_clearance_mm) +{ + for (std::size_t i = 0; i + 1 < points.size(); ++i) + if (!lineOk(grid, points[i], points[i + 1], deviation_deg, min_clearance_mm)) + return false; + return true; +} + +bool footprintCollides(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y) +{ + const double c = std::cos(yaw); + const double s = std::sin(yaw); + const double abs_c = std::abs(c); + const double abs_s = std::abs(s); + const double resolution = grid.resolution; + const double half_cell = resolution / 2.0; + const double reach_x = half_x * abs_c + half_y * abs_s; + const double reach_y = half_x * abs_s + half_y * abs_c; + const double low_x = std::floor((x - reach_x - grid.origin_x) / resolution); + const double high_x = std::floor((x + reach_x - grid.origin_x) / resolution); + const double low_y = std::floor((y - reach_y - grid.origin_y) / resolution); + const double high_y = std::floor((y + reach_y - grid.origin_y) / resolution); + if (low_x < 0.0 || low_y < 0.0 || high_x >= grid.width || high_y >= grid.height) + return true; + int32_t centre = 0; + if (!cellOf(grid, x, y, ¢re) || grid.cost[centre] >= kInscribedCost) + return true; + const double projected = half_cell * (abs_c + abs_s); + for (int32_t iy = static_cast(low_y); iy <= static_cast(high_y); ++iy) + { + const uint8_t* row = grid.cost + static_cast(iy) * grid.width; + for (int32_t ix = static_cast(low_x); ix <= static_cast(high_x); ++ix) + { + if (row[ix] < kLethalCost) + continue; + const double dx = grid.origin_x + (ix + 0.5) * resolution - x; + const double dy = grid.origin_y + (iy + 0.5) * resolution - y; + if (std::abs(dx) <= reach_x + half_cell && std::abs(dy) <= reach_y + half_cell && + std::abs(c * dx + s * dy) <= half_x + projected && std::abs(-s * dx + c * dy) <= half_y + projected) + return true; + } + } + return false; +} + +double costFactor(uint8_t value) +{ + switch (value) + { + case kCriticalSpace: + return 0.2; + case kPreferredSpace: + return 0.4; + case kUnpreferredSpace: + return 1.6; + default: + return 1.0; + } +} + +double lineCost(const Point2& a, const Point2& b, const uint8_t* master, const GridRef& grid) +{ + const double dx = b.x - a.x; + const double dy = b.y - a.y; + const double length = std::hypot(dx, dy); + if (length < 1e-12) + return 0.0; + const int samples = std::max(1, static_cast(std::ceil(length / (grid.resolution * 0.5)))); + double sum = 0.0; + for (int i = 0; i < samples; ++i) + { + const double t = (i + 0.5) / samples; + int32_t cell = 0; + if (!cellOf(grid, a.x + dx * t, a.y + dy * t, &cell) || master[cell] >= kInscribedCost) + return kInfinity; + sum += costFactor(master[cell]); + } + return length * (sum / samples); +} + +bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm) +{ + return freeClearanceOk(path, grid, min_clearance_mm, nullptr, nullptr); +} + +bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm, const std::atomic* cancel, + const std::chrono::steady_clock::time_point* deadline) +{ + if (path.size() < 2) + return false; + for (std::size_t i = 0; i + 1 < path.size(); ++i) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return false; + const PathPoint& a = path[i]; + const PathPoint& b = path[i + 1]; + const int segments = std::max(1, static_cast(std::ceil(std::hypot(b.x - a.x, b.y - a.y) / 0.01))); + for (int j = 0; j <= segments; ++j) + { + const double t = j == segments ? 1.0 : static_cast(j) / segments; + int32_t cell = 0; + if (!cellOf(grid, a.x + t * (b.x - a.x), a.y + t * (b.y - a.y), &cell)) + return false; + const bool in_zone = grid.direction != nullptr && grid.direction[cell] != 0; + if (!in_zone && grid.clearance_mm[cell] < min_clearance_mm) + return false; + } + } + return true; +} + +bool endpointOk(const Path& path, const Pose2& start, const Pose2& goal) +{ + if (path.empty()) + return false; + const PathPoint& first = path.front(); + const PathPoint& last = path.back(); + if (std::hypot(first.x - start.x, first.y - start.y) > 1e-6 || std::hypot(last.x - goal.x, last.y - goal.y) > 0.01) + return false; + if (start.has_yaw && std::abs(wrapAngle(first.yaw - start.yaw)) > 1e-6) + return false; + if (goal.has_yaw && std::abs(wrapAngle(last.yaw - goal.yaw)) > kPi / 180.0) + return false; + return true; +} + +const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y) +{ + const auto turn_hits = [&](const PathPoint& a, const PathPoint& b) { + const double delta = wrapAngle(b.yaw - a.yaw); + if (std::abs(delta) < 1e-12) + return false; + const int samples = std::max(1, static_cast(std::ceil(std::abs(delta) / 0.03))); + for (int j = 0; j <= samples; ++j) + if (footprintCollides(grid, a.x, a.y, a.yaw + delta * j / samples, half_x, half_y)) + return true; + return false; + }; + for (std::size_t i = 0; i + 1 < path.size(); ++i) + { + if (std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y) > 1e-7) + break; + if (turn_hits(path[i], path[i + 1])) + return "start_turn_blocked"; + } + for (std::size_t i = path.size(); i-- > 1;) + { + if (std::hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y) > 1e-7) + break; + if (turn_hits(path[i - 1], path[i])) + return "goal_turn_blocked"; + } + return nullptr; +} + +bool enclosedByObstacles(const GridRef& grid, const Point2& start, const Point2& goal, const std::atomic* cancel) +{ + int32_t from = 0, to = 0; + if (!cellOf(grid, start.x, start.y, &from) || !cellOf(grid, goal.x, goal.y, &to)) + return false; + if (grid.cost[from] >= kInscribedCost || grid.cost[to] >= kInscribedCost) + return false; + if (from == to) + return false; + std::vector visited(static_cast(grid.width) * static_cast(grid.height), 0); + std::vector stack(1, from); + visited[static_cast(from)] = 1; + while (!stack.empty()) + { + if (cancel && cancel->load(std::memory_order_relaxed)) return false; + const int32_t cell = stack.back(); + stack.pop_back(); + const int32_t cx = cell % grid.width; + const int32_t cy = cell / grid.width; + for (int32_t y = std::max(cy - 1, 0); y <= std::min(cy + 1, grid.height - 1); ++y) + { + for (int32_t x = std::max(cx - 1, 0); x <= std::min(cx + 1, grid.width - 1); ++x) + { + const int32_t other = y * grid.width + x; + if (visited[static_cast(other)] != 0 || grid.cost[other] >= kInscribedCost) + continue; + if (other == to) + return false; + visited[static_cast(other)] = 1; + stack.push_back(other); + } + } + } + return true; +} + +bool shortestDirectedReference(const GridRef& grid, const Point2& start, const Point2& goal, double deviation_deg, + double bound_m, double* length_m, const std::atomic* cancel) +{ + int32_t from = 0, to = 0; + if (!cellOf(grid, start.x, start.y, &from) || !cellOf(grid, goal.x, goal.y, &to)) + return false; + if (grid.cost[from] >= kInscribedCost || grid.cost[to] >= kInscribedCost) + return false; + const int32_t width = grid.width; + const double resolution = grid.resolution; + const int32_t goal_x = to % width; + const int32_t goal_y = to / width; + const auto heuristic = [&](int32_t x, int32_t y) { + return std::hypot(static_cast(goal_x - x), static_cast(goal_y - y)) * resolution; + }; + + struct Move + { + int dy, dx; + double cost; + bool allowed[9]; + }; + std::vector moves; + for (int dy = -1; dy <= 1; ++dy) + { + for (int dx = -1; dx <= 1; ++dx) + { + if (dx == 0 && dy == 0) + continue; + Move move; + move.dy = dy; + move.dx = dx; + move.cost = std::hypot(static_cast(dx), static_cast(dy)) * resolution; + move.allowed[0] = true; + const double angle = std::atan2(static_cast(dy), static_cast(dx)); + for (int code = 1; code <= 8; ++code) + move.allowed[code] = std::abs(wrapAngle(angle - (code - 1) * kPi / 4.0)) * 180.0 / kPi <= deviation_deg + 1e-9; + moves.push_back(move); + } + } + + using Entry = std::pair>; // f, then g and cell + std::priority_queue, std::greater> queue; + std::unordered_map best; + best.reserve(4096); + best[from] = 0.0; + queue.push({ heuristic(from % width, from / width), { 0.0, from } }); + while (!queue.empty()) + { + if (cancel && cancel->load(std::memory_order_relaxed)) return false; + const Entry top = queue.top(); + queue.pop(); + if (top.first > bound_m + 1e-9) + return false; + const double g = top.second.first; + const int32_t cell = top.second.second; + if (g > best[cell] + 1e-10) + continue; + if (cell == to) + { + *length_m = g; + return true; + } + const int32_t x = cell % width; + const int32_t y = cell / width; + for (const Move& move : moves) + { + const int32_t ny = y + move.dy; + const int32_t nx = x + move.dx; + if (ny < 0 || nx < 0 || ny >= grid.height || nx >= width) + continue; + const int32_t other = ny * width + nx; + if (grid.cost[other] >= kInscribedCost) + continue; + if (grid.direction != nullptr) + { + const auto legal = [&](int32_t index) { + const uint8_t code = grid.direction[index]; + return code > 8 || move.allowed[code]; + }; + if (!legal(cell) || !legal(other)) + continue; + // A diagonal step also touches the two cells at the shared corner. + if (move.dx != 0 && move.dy != 0 && (!legal(y * width + nx) || !legal(ny * width + x))) + continue; + } + const double next = g + move.cost; + if (next + heuristic(nx, ny) > bound_m + 1e-9) + continue; + const auto known = best.find(other); + if (known != best.end() && next >= known->second - 1e-10) + continue; + best[other] = next; + queue.push({ next + heuristic(nx, ny), { next, other } }); + } + } + return false; +} + +bool outsideZones(const Point2& a, const Point2& b, const GridRef& grid) +{ + const double length = distanceOf(a, b); + const int samples = std::max(2, static_cast(std::ceil(length / (grid.resolution * 0.5))) + 1); + const double step = 1.0 / (samples - 1); + for (int i = 0; i < samples; ++i) + { + const double t = i == samples - 1 ? 1.0 : i * step; + int32_t cell = 0; + if (!cellOf(grid, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, &cell)) + return false; + if (grid.direction != nullptr && grid.direction[cell] != 0) + return false; + } + return true; +} + +namespace +{ +GapCheck applyGapRuleBounded(const std::vector& gaps, double minimum_m, const std::atomic* cancel, + const std::chrono::steady_clock::time_point* deadline) +{ + GapCheck result; + if (gaps.empty()) + return result; + const std::size_t count = gaps.size(); + const double start_floor = std::max(0.0, gaps.front() - kEndpointGapToleranceM); + const double goal_floor = std::max(0.0, gaps.back() - kEndpointGapToleranceM); + + // The allowance of each end holds until the path first reaches the minimum, walking in from that end. + std::vector in_start(count, 0), in_goal(count, 0); + if (gaps.front() < minimum_m) + for (std::size_t i = 0; i < count && gaps[i] < minimum_m; ++i) + { + if ((i & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return {}; + in_start[i] = 1; + } + if (gaps.back() < minimum_m) + for (std::size_t i = count; i-- > 0 && gaps[i] < minimum_m;) + { + if ((i & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return {}; + in_goal[i] = 1; + } + + result.valid = true; + result.min_gap_m = kInfinity; + result.exemption_min_m = kInfinity; + for (std::size_t i = 0; i < count; ++i) + { + if ((i & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return {}; + double allowed = minimum_m; + if (in_start[i] != 0 && in_goal[i] != 0) + allowed = std::min(start_floor, goal_floor); + else if (in_start[i] != 0) + allowed = start_floor; + else if (in_goal[i] != 0) + allowed = goal_floor; + const double gap = gaps[i]; + if (gap <= 1e-12 || gap + 1e-10 < allowed) + result.valid = false; + result.min_gap_m = std::min(result.min_gap_m, gap); + if ((in_start[i] != 0 || in_goal[i] != 0) && gap < minimum_m) + { + result.exemption_used = true; + result.exemption_min_m = std::min(result.exemption_min_m, gap); + } + } + return result; +} + +} // namespace + +GapCheck applyGapRule(const std::vector& gaps, double minimum_m) +{ + return applyGapRuleBounded(gaps, minimum_m, nullptr, nullptr); +} + +GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y, + const std::atomic* cancel) +{ + return checkFootprintGap(path, grid, minimum_m, half_x, half_y, cancel, nullptr); +} + +GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline, + bool count_unknown) +{ + std::vector poses; + if (path.empty()) + return GapCheck(); + poses.push_back(path.front()); + for (std::size_t i = 0; i + 1 < path.size(); ++i) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return {}; + const PathPoint& a = path[i]; + const PathPoint& b = path[i + 1]; + const double distance = std::hypot(b.x - a.x, b.y - a.y); + const double angle = wrapAngle(b.yaw - a.yaw); + const int samples = std::max({ 1, static_cast(std::ceil(distance / 0.04)), static_cast(std::ceil(std::abs(angle) / 0.03)) }); + for (int j = 1; j <= samples; ++j) + { + const double t = static_cast(j) / samples; + poses.push_back({ a.x + t * (b.x - a.x), a.y + t * (b.y - a.y), a.yaw + t * angle, 0.0 }); + } + } + + const double resolution = grid.resolution; + const double half_cell = resolution / 2.0; + const double radius = std::hypot(half_x, half_y) + std::sqrt(2.0) * half_cell + minimum_m + 1e-9; + const double squared_radius = radius * radius; + std::vector gaps(poses.size(), kInfinity); + for (std::size_t i = 0; i < poses.size(); ++i) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return {}; + const PathPoint& pose = poses[i]; + const double c = std::cos(pose.yaw); + const double s = std::sin(pose.yaw); + const int32_t x0 = std::max(0, static_cast(std::floor((pose.x - radius - grid.origin_x) / resolution))); + const int32_t x1 = std::min(grid.width - 1, static_cast(std::ceil((pose.x + radius - grid.origin_x) / resolution))); + const int32_t y0 = std::max(0, static_cast(std::floor((pose.y - radius - grid.origin_y) / resolution))); + const int32_t y1 = std::min(grid.height - 1, static_cast(std::ceil((pose.y + radius - grid.origin_y) / resolution))); + for (int32_t iy = y0; iy <= y1; ++iy) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return {}; + const uint8_t* row = grid.cost + static_cast(iy) * grid.width; + const double centre_y = grid.origin_y + (iy + 0.5) * resolution; + for (int32_t ix = x0; ix <= x1; ++ix) + { + if (row[ix] != kLethalCost && !(count_unknown && row[ix] == kNoInformation)) + continue; + const double centre_x = grid.origin_x + (ix + 0.5) * resolution; + const double dx = centre_x - pose.x; + const double dy = centre_y - pose.y; + if (dx * dx + dy * dy > squared_radius) + continue; + gaps[i] = std::min(gaps[i], rectangleCellGap(centre_x, centre_y, pose.x, pose.y, c, s, half_x, half_y, half_cell)); + } + } + } + return applyGapRuleBounded(gaps, minimum_m, cancel, deadline); +} + +std::vector> nearestNodes(const std::vector& nodes, int32_t count, const Point2& point, + int32_t k, double upper_bound) +{ + std::vector> found; + for (int32_t i = 0; i < count; ++i) + { + const double distance = distanceOf(point, nodes[static_cast(i)]); + if (distance < upper_bound) + found.emplace_back(distance, i); + } + std::sort(found.begin(), found.end()); + if (found.size() > static_cast(k)) + found.resize(static_cast(k)); + return found; +} + +} // namespace lane_route_core diff --git a/src/lattice_cspace.cpp b/src/lattice_cspace.cpp new file mode 100644 index 0000000..5c64f90 --- /dev/null +++ b/src/lattice_cspace.cpp @@ -0,0 +1,263 @@ +#include "lattice_internal.h" + +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace detail +{ +namespace +{ + +bool hitsCell(double x0, double y0, double x1, double y1, int32_t x, int32_t y, double padding) +{ + // A centre line on a cell edge touches both cells. World to cell division leaves rounding of about 1e-14 cells, so the + // edge test carries a small slack in cell units; a wider band only makes the zone test more conservative. + padding += 1e-9; + double low = 0.0, high = 1.0; + const double points[2] = { x0, y0 }, delta[2] = { x1 - x0, y1 - y0 }; + const double cell[2] = { static_cast(x), static_cast(y) }; + for (int axis = 0; axis < 2; ++axis) + { + if (std::abs(delta[axis]) < 1e-14) + { + if (points[axis] < cell[axis] - padding || points[axis] > cell[axis] + 1.0 + padding) + return false; + } + else + { + const double a = (cell[axis] - padding - points[axis]) / delta[axis]; + const double b = (cell[axis] + 1.0 + padding - points[axis]) / delta[axis]; + low = std::max(low, std::min(a, b)); + high = std::min(high, std::max(a, b)); + if (low > high + 1e-12) + return false; + } + } + return true; +} + +} // namespace + +LatticeCSpace::LatticeCSpace(LatticeContext& context) + : context_(context), tiles_(&context.memory), blocked_prefix_(&context.memory) +{ + start_floor_ = endFloor(context.request.start); + goal_floor_ = endFloor(context.request.goal); +} + +double LatticeCSpace::endFloor(const Pose2& pose) const +{ + // The final lattice check measures the gap to lethal and unknown cells and lets the path stay down to the end pose gap minus 1 mm + // until it first reaches the minimum. Near this end the C-space asks for exactly that floor: no less, so a path cannot end a few + // millimetres from unknown space as it could with a zero margin, and no more, so a robot parked close to a rack can still leave. + const PlannerConfig& c = context_.config; + const auto gap_at = [&](double yaw) { + const Path probe{ { pose.x, pose.y, yaw, 0.0 }, { pose.x, pose.y, yaw, 0.0 } }; + const GapCheck check = checkFootprintGap(probe, context_.grid, 0.0, c.half_x_m, c.half_y_m, nullptr, nullptr, true); + return check.valid ? check.min_gap_m : 0.0; + }; + double gap = 0.0; + if (pose.has_yaw) + gap = gap_at(pose.yaw); + else + for (int h = 0; h < c.lattice_heading_bins; ++h) + gap = std::max(gap, gap_at(h * 2.0 * kPi / c.lattice_heading_bins)); + return std::min(c.footprint_min_gap_m, std::max(0.0, gap - 0.001)); +} + +bool LatticeCSpace::buildBlockedPrefix() +{ + if (prefix_ready_) return true; + const GridRef& g = context_.grid; + const std::size_t width = static_cast(g.width); + const std::size_t height = static_cast(g.height); + if (width == 0 || height == 0 || height > std::numeric_limits::max() / width || + height + 1 > std::numeric_limits::max() / (width + 1)) return false; + const std::size_t stride = width + 1; + blocked_prefix_.assign((height + 1) * stride, 0); + for (std::size_t y = 0; y < height; ++y) + { + if (context_.expired()) return false; + uint32_t row = 0; + for (std::size_t x = 0; x < width; ++x) + { + if (g.cost[y * width + x] >= kLethalCost) ++row; + blocked_prefix_[(y + 1) * stride + x + 1] = blocked_prefix_[y * stride + x + 1] + row; + } + } + prefix_ready_ = true; + return true; +} + +uint32_t LatticeCSpace::blockedCount(int32_t x0, int32_t y0, int32_t x1, int32_t y1) const +{ + const std::size_t stride = static_cast(context_.grid.width) + 1; + const auto at = [&](int32_t x, int32_t y) { return blocked_prefix_[static_cast(y) * stride + static_cast(x)]; }; + return at(x1, y1) - at(x0, y1) - at(x1, y0) + at(x0, y0); +} + +bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin, double centre_sweep) +{ + if (context_.expired()) return false; + ++context_.info.lattice_pose_checks; + const GridRef& g = context_.grid; + const PlannerConfig& c = context_.config; + const double fx = std::floor((x - g.origin_x) / g.resolution); + const double fy = std::floor((y - g.origin_y) / g.resolution); + if (!(fx >= 0.0 && fy >= 0.0 && fx < g.width && fy < g.height)) return false; + const int32_t ix = static_cast(fx), iy = static_cast(fy); + const std::size_t cell = static_cast(iy) * static_cast(g.width) + static_cast(ix); + if (g.cost[cell] >= kInscribedCost || + ((g.direction == nullptr || g.direction[cell] == 0) && g.clearance_mm[cell] < clearanceThresholdMm(c.clearance_min_m))) + return false; + const Pose2& start = context_.request.start; + const Pose2& goal = context_.request.goal; + const double relax = c.lattice_end_relax_radius_m; + const bool near_start = std::hypot(x - start.x, y - start.y) + centre_sweep <= relax; + const bool near_goal = std::hypot(x - goal.x, y - goal.y) + centre_sweep <= relax; + // Away from the ends: full gap plus the sweep bound, conservative. Near an end: the floor of that end without the sweep bound, + // because the final check is the authority there and adding the sweep could lock in a robot parked closer than gap plus sweep. + double margin = c.footprint_min_gap_m + std::max(0.0, sweep_margin); + if (near_start || near_goal) + margin = std::min(near_start ? start_floor_ : c.footprint_min_gap_m, near_goal ? goal_floor_ : c.footprint_min_gap_m); + const double hx = c.half_x_m + margin, hy = c.half_y_m + margin; + const double ca = std::abs(std::cos(yaw)), sa = std::abs(std::sin(yaw)); + const double reach_x = hx * ca + hy * sa, reach_y = hx * sa + hy * ca; + if (x - reach_x < g.origin_x || y - reach_y < g.origin_y || + x + reach_x >= g.origin_x + g.width * g.resolution || y + reach_y >= g.origin_y + g.height * g.resolution) + return false; + + // Clearance is to lethal cell centres only; the prefix independently checks the live lethal/unknown cells. + const double clear_m = g.clearance_mm[cell] / 1000.0; + // Two half-cell diagonals bound pose/cell-centre and obstacle-square rounding; 1 mm covers flooring. + const double rounding = std::sqrt(2.0) * g.resolution + 0.001; + const double outer = std::hypot(hx, hy); + const double inner = std::min(hx, hy); + if ((clear_m > outer + rounding || clear_m + rounding < inner) && buildBlockedPrefix()) + { + const auto bound = [](double v, int32_t limit) { + if (v <= 0.0) return int32_t{0}; + if (v >= limit) return limit; + return static_cast(std::floor(v)); + }; + if (clear_m > outer + rounding) + { + const double r = outer + g.resolution / std::sqrt(2.0); + const int32_t x0 = bound((x - r - g.origin_x) / g.resolution, g.width); + const int32_t y0 = bound((y - r - g.origin_y) / g.resolution, g.height); + const int32_t x1 = bound(std::floor((x + r - g.origin_x) / g.resolution) + 1.0, g.width); + const int32_t y1 = bound(std::floor((y + r - g.origin_y) / g.resolution) + 1.0, g.height); + if (blockedCount(x0, y0, x1, y1) == 0) return true; + } + else + { + // Cell centres in this square lie strictly inside the rectangle's inscribed disc. + const double r = std::max(0.0, inner / std::sqrt(2.0) - 1e-9); + const int32_t x0 = bound(std::ceil((x - r - g.origin_x) / g.resolution - 0.5), g.width); + const int32_t y0 = bound(std::ceil((y - r - g.origin_y) / g.resolution - 0.5), g.height); + const int32_t x1 = bound(std::floor((x + r - g.origin_x) / g.resolution - 0.5) + 1.0, g.width); + const int32_t y1 = bound(std::floor((y + r - g.origin_y) / g.resolution - 0.5) + 1.0, g.height); + if (x0 < x1 && y0 < y1 && blockedCount(x0, y0, x1, y1) != 0) return false; + } + } + if (context_.expired()) return false; + constexpr int32_t kTile = 32; + const uint64_t tile = (static_cast(static_cast(iy / kTile)) << 32) | static_cast(ix / kTile); + const int bins = c.lattice_heading_bins; + auto inserted = tiles_.try_emplace(tile, &context_.memory, static_cast(kTile) * kTile * bins); + if (inserted.second) ++context_.info.lattice_tiles_built; + if (context_.expired()) return false; + double positive_yaw = std::fmod(yaw, 2.0 * kPi); + if (positive_yaw < 0.0) positive_yaw += 2.0 * kPi; + const int heading = static_cast(std::floor(positive_yaw * bins / (2.0 * kPi) + 0.5)) % bins; + const std::size_t local = (static_cast(iy % kTile) * kTile + static_cast(ix % kTile)) * bins + heading; + uint8_t& packed = inserted.first->second.samples[local / 4]; + const unsigned shift = static_cast((local % 4) * 2); + uint8_t cached = static_cast((packed >> shift) & 3u); + const double cx = g.origin_x + (ix + 0.5) * g.resolution; + const double cy = g.origin_y + (iy + 0.5) * g.resolution; + const double h = heading * 2.0 * kPi / bins; + const double quantization = g.resolution / std::sqrt(2.0) + + 2.0 * std::hypot(c.half_x_m, c.half_y_m) * std::sin(kPi / (2.0 * bins)); + if (cached == 0) + { + const double margin = c.footprint_min_gap_m + quantization; + const bool safe = !footprintCollides(g, cx, cy, h, c.half_x_m + margin, c.half_y_m + margin); + cached = safe ? 1 : 2; + packed = static_cast(packed | (cached << shift)); + } + // A cached free sample must cover the actual displacement and yaw difference. + const double actual_error = std::hypot(x - cx, y - cy) + 2.0 * std::hypot(c.half_x_m, c.half_y_m) * + std::sin(std::abs(wrapAngle(yaw - h)) / 2.0); + if (cached == 1 && actual_error + sweep_margin <= quantization) return true; + // Away from the ends the final check demands the full gap. Testing only collision there would let the search reach the goal area + // through a spot narrower than the gap, and those states would then hold the closed bins that a wider, legal route needs. Near an end + // the final check may grant the end allowance of applyGapRule, so only collision is tested there and the final check decides. + return !footprintCollides(g, x, y, yaw, hx, hy); +} + +bool LatticeCSpace::segmentLegal(const PathPoint& a, const PathPoint& b) +{ + const GridRef& g = context_.grid; + if (context_.expired()) return false; + const double dx = b.x - a.x, dy = b.y - a.y; + const double distance = std::hypot(dx, dy); + const double yaw_delta = wrapAngle(b.yaw - a.yaw); + // Bound the arc's deviation from the same-parameter chord interpolation, not just its midpoint sagitta. + const double turn = std::abs(yaw_delta); + const double curve_error = turn < 1e-12 ? 0.0 : distance * turn * turn / (16.0 * std::sin(turn / 2.0)); + if (distance > 1e-12) + { + const double x0 = (a.x - g.origin_x) / g.resolution, y0 = (a.y - g.origin_y) / g.resolution; + const double x1 = (b.x - g.origin_x) / g.resolution, y1 = (b.y - g.origin_y) / g.resolution; + const double padding = curve_error / g.resolution; + const int32_t xlo = std::max(0, static_cast(std::floor(std::min(x0, x1) - padding - 1e-10))); + const int32_t xhi = std::min(g.width - 1, static_cast(std::floor(std::max(x0, x1) + padding + 1e-10))); + const int32_t ylo = std::max(0, static_cast(std::floor(std::min(y0, y1) - padding - 1e-10))); + const int32_t yhi = std::min(g.height - 1, static_cast(std::floor(std::max(y0, y1) + padding + 1e-10))); + const double angle = std::atan2(dy, dx); + for (int32_t y = ylo; y <= yhi; ++y) + { + if (context_.expired()) return false; + for (int32_t x = xlo; x <= xhi; ++x) + { + if (!hitsCell(x0, y0, x1, y1, x, y, padding)) continue; + const std::size_t cell = static_cast(y) * g.width + x; + const uint8_t code = g.direction == nullptr ? 0 : g.direction[cell]; + if (g.cost[cell] >= kInscribedCost || (code == 0 && + g.clearance_mm[cell] < clearanceThresholdMm(context_.config.clearance_min_m))) return false; + if (code != 0) + { + const double zone_angle = (code - 1) * kPi / 4.0; + const double worst = std::min(kPi, std::abs(wrapAngle(angle - zone_angle)) + std::abs(yaw_delta) / 2.0); + if (worst * 180.0 / kPi > context_.deviation_deg + 1e-9) return false; + } + } + } + } + const int count = std::max({ 1, static_cast(std::ceil(distance / 0.025)), static_cast(std::ceil(std::abs(yaw_delta) / 0.03)) }); + const double centre_sweep = distance / (2.0 * count) + curve_error; + const double radius = std::hypot(context_.config.half_x_m + context_.config.footprint_min_gap_m, + context_.config.half_y_m + context_.config.footprint_min_gap_m); + const double sweep = centre_sweep + 2.0 * radius * std::sin(std::abs(yaw_delta) / (4.0 * count)); + for (int i = 0; i < count; ++i) + { + const double t = (static_cast(i) + 0.5) / count; + if (!poseFree(a.x + t * dx, a.y + t * dy, a.yaw + t * yaw_delta, sweep, centre_sweep)) return false; + } + return true; +} + +bool LatticeCSpace::spinLegal(double x, double y, double from, double to) +{ + return segmentLegal({ x, y, from, 0.0 }, { x, y, to, 0.0 }); +} + +} // namespace detail +} // namespace lane_route_core diff --git a/src/lattice_heuristic.cpp b/src/lattice_heuristic.cpp new file mode 100644 index 0000000..bd2d06d --- /dev/null +++ b/src/lattice_heuristic.cpp @@ -0,0 +1,194 @@ +#include "lattice_internal.h" + +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace detail +{ +namespace +{ +struct FieldEntry +{ + float distance; + int32_t cell; + bool operator>(const FieldEntry& other) const + { + return distance != other.distance ? distance > other.distance : cell > other.cell; + } +}; + +bool allows(uint8_t code, double heading, double deviation) +{ + return code == 0 || std::abs(wrapAngle(heading - (code - 1) * kPi / 4.0)) * 180.0 / kPi <= deviation + 1e-9; +} +} // namespace + +double LatticeField::at(double x, double y, const LatticeContext& context) const +{ + const GridRef& g = context.grid; + const double maximum = std::numeric_limits::max() / 4.0; + const double fallback = std::min(maximum, std::hypot(context.request.goal.x - x, context.request.goal.y - y)); + const double fx = std::floor((x - g.origin_x) / g.resolution); + const double fy = std::floor((y - g.origin_y) / g.resolution); + if (values.empty() || fx < 0.0 || fy < 0.0 || fx >= g.width || fy >= g.height) return fallback; + const int32_t field_width = width > 0 ? width : g.width; + const std::size_t cell = (static_cast(fy) / static_cast(factor)) * + static_cast(field_width) + static_cast(fx) / static_cast(factor); + if (settled[cell] != 0) return static_cast(values[cell]); + return complete ? std::min(maximum, frontier + fallback) : std::max(frontier, fallback); +} + +bool buildLatticeField(LatticeContext& context, LatticeField* field, TimePoint field_deadline) +{ + const GridRef& g = context.grid; + const auto cellCount = [&](int factor) -> int64_t { + return ((static_cast(g.width) + factor - 1) / factor) * + ((static_cast(g.height) + factor - 1) / factor); + }; + int factor = context.config.lattice_field_cell_factor; + if (factor == 0) + { + int low = 1, high = std::max(g.width, g.height); + while (low < high) + { + const int middle = low + (high - low) / 2; + if (cellCount(middle) <= context.config.lattice_field_max_cells) high = middle; + else low = middle + 1; + } + factor = low; + } + field->factor = factor; + field->width = static_cast((static_cast(g.width) + factor - 1) / factor); + field->height = static_cast((static_cast(g.height) + factor - 1) / factor); + const int32_t width = field->width, height = field->height; + const double field_resolution = g.resolution * factor; + if (!std::isfinite(field_resolution)) return true; + const auto index = [&](const Pose2& p) -> int64_t { + const double x = std::floor((p.x - g.origin_x) / g.resolution); + const double y = std::floor((p.y - g.origin_y) / g.resolution); + if (x < 0.0 || y < 0.0 || x >= g.width || y >= g.height) return -1; + return (static_cast(y) / factor) * width + static_cast(x) / factor; + }; + const int64_t start = index(context.request.start), goal = index(context.request.goal); + if (start < 0 || goal < 0) return true; + const int64_t cells64 = static_cast(width) * height; + if (cells64 > std::numeric_limits::max()) return true; + const std::size_t cells = static_cast(cells64); + + // A cell counts as free only when the robot centre fits there: below kInscribedCost and with clearance to lethal cell centres of at + // least the narrow footprint half width plus the gap, less one cell for rounding (the prototype's rule). Cost alone is not enough: + // a grid without an inscribed ring has walls one or two cells thick, and a block rule on cost alone opened passages through them, + // so the heuristic pointed through walls and the search flooded (warehouse p0: 1.1 M states, no path; full resolution: 339 states). + const PlannerConfig& config = context.config; + const double fit_m = std::min(config.half_x_m, config.half_y_m) + config.footprint_min_gap_m - g.resolution; + const uint16_t fit_mm = static_cast(std::max(0.0, std::min(65535.0, std::floor(fit_m * 1000.0)))); + const auto fits = [&](std::size_t cell) { return g.cost[cell] < kInscribedCost && g.clearance_mm[cell] >= fit_mm; }; + std::pmr::vector passable(&context.memory), direction(&context.memory); + std::pmr::vector clearance(&context.memory); + if (factor > 1) + { + passable.resize(cells, 0); + direction.resize(cells, 0); + clearance.resize(cells, 0); + for (int32_t by = 0; by < height; ++by) + { + if (context.expired()) return false; + if (Clock::now() >= field_deadline) return true; + const int64_t y0 = static_cast(by) * factor; + const int64_t y1 = std::min(g.height, y0 + factor); + for (int32_t bx = 0; bx < width; ++bx) + { + if ((bx & 255) == 0 && context.expired()) return false; + if ((bx & 255) == 0 && Clock::now() >= field_deadline) return true; + const int64_t x0 = static_cast(bx) * factor; + const int64_t x1 = std::min(g.width, x0 + factor); + const std::size_t block = static_cast(by) * width + bx; + for (int64_t y = y0; y < y1; ++y) + { + if ((y & 255) == 0 && context.expired()) return false; + if ((y & 255) == 0 && Clock::now() >= field_deadline) return true; + for (int64_t x = x0; x < x1; ++x) + { + if ((x & 4095) == 0 && context.expired()) return false; + if ((x & 4095) == 0 && Clock::now() >= field_deadline) return true; + const std::size_t cell = static_cast(y) * g.width + static_cast(x); + if (fits(cell)) passable[block] = 1; + clearance[block] = std::max(clearance[block], g.clearance_mm[cell]); + } + } + if (g.direction != nullptr) + { + const std::size_t centre = static_cast((y0 + y1) / 2) * g.width + static_cast((x0 + x1) / 2); + direction[block] = g.direction[centre]; + } + } + } + } + // Start and goal are always free here: a robot parked closer than the fit rule must still get a field; the C-space decides the rest. + const auto isFree = [&](int32_t cell) { + if (cell == start || cell == goal) return true; + return factor == 1 ? fits(static_cast(cell)) : passable[static_cast(cell)] != 0; + }; + const auto zone = [&](int32_t cell) -> uint8_t { + return factor == 1 ? (g.direction == nullptr ? 0 : g.direction[cell]) : direction[static_cast(cell)]; + }; + const auto clear = [&](int32_t cell) -> uint16_t { return factor == 1 ? g.clearance_mm[cell] : clearance[static_cast(cell)]; }; + field->values.reserve(cells); + field->settled.reserve(cells); + for (std::size_t i = 0; i < cells; ++i) + { + if ((i & 4095u) == 0 && context.expired()) return false; + field->values.push_back(std::numeric_limits::infinity()); + field->settled.push_back(0); + } + using QueueStorage = std::pmr::vector; + std::priority_queue> queue{ std::greater(), QueueStorage(&context.memory) }; + field->values[static_cast(goal)] = 0.0f; + queue.push({ 0.0f, static_cast(goal) }); + while (!queue.empty()) + { + if (context.expired()) return false; + if (Clock::now() >= field_deadline) break; + const FieldEntry top = queue.top(); + queue.pop(); + if (top.distance != field->values[static_cast(top.cell)]) continue; + if (field->settled[static_cast(top.cell)] != 0) continue; + field->settled[static_cast(top.cell)] = 1; + field->frontier = top.distance; + ++context.info.lattice_field_cells; + if (top.cell == start) break; + const int32_t x = top.cell % width, y = top.cell / width; + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + { + if (dx == 0 && dy == 0) continue; + const int32_t nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue; + const int32_t next = ny * width + nx; + if (!isFree(next)) continue; + const double angle = std::atan2(-dy, -dx); + if (!allows(zone(next), angle, context.deviation_deg) || !allows(zone(top.cell), angle, context.deviation_deg)) continue; + const double clearance_m = std::max(0.05, clear(top.cell) / 1000.0); + const float next_distance = static_cast(top.distance + std::hypot(dx, dy) * field_resolution * + (1.0 + context.config.lattice_field_clearance_weight_m / clearance_m)); + if (next_distance < field->values[static_cast(next)]) + { + field->values[static_cast(next)] = next_distance; + queue.push({ next_distance, next }); + } + } + } + // A stop at start leaves its neighbours unexpanded, even if the queue is empty. + field->complete = queue.empty() && field->settled[static_cast(start)] == 0; + return true; +} + +} // namespace detail +} // namespace lane_route_core diff --git a/src/lattice_internal.h b/src/lattice_internal.h new file mode 100644 index 0000000..c8bf0cb --- /dev/null +++ b/src/lattice_internal.h @@ -0,0 +1,154 @@ +#ifndef LANE_ROUTE_CORE_LATTICE_INTERNAL_H_ +#define LANE_ROUTE_CORE_LATTICE_INTERNAL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "route_planner_internal.h" + +namespace lane_route_core +{ +namespace detail +{ + +// All persistent search containers use this resource, including temporary growth during reallocation. +class LatticeMemory final : public std::pmr::memory_resource +{ +public: + explicit LatticeMemory(std::size_t limit) : limit_(limit) {} + std::size_t peak() const { return peak_; } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override + { + if (bytes > limit_ - used_) + throw std::bad_alloc(); + void* p = std::pmr::new_delete_resource()->allocate(bytes, alignment); + used_ += bytes; + if (used_ > peak_) + peak_ = used_; + return p; + } + void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override + { + std::pmr::new_delete_resource()->deallocate(p, bytes, alignment); + used_ -= bytes; + } + bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { return this == &other; } + std::size_t limit_, used_ = 0, peak_ = 0; +}; + +struct LatticeContext +{ + const RouteRequest& request; + const GridRef& grid; + const PlannerConfig& config; + double deviation_deg; + TimePoint deadline; + PlanInfo& info; + LatticeMemory& memory; + + bool cancelled() const { return request.cancel && request.cancel->load(std::memory_order_relaxed); } + bool expired() const { return cancelled() || Clock::now() >= deadline; } +}; + +struct LatticeTierInput +{ + const RouteRequest& request; + const GridRef& grid; + const PlannerConfig& config; + double deviation_deg; + TimePoint deadline; +}; + +struct LatticeStateKey +{ + int32_t x, y, heading; + bool operator==(const LatticeStateKey& other) const { return x == other.x && y == other.y && heading == other.heading; } +}; + +struct LatticeOpenEntry +{ + long double priority; + uint64_t serial; + std::size_t node; +}; + +inline long double latticeBucketPriority(double f, double width_m) +{ + return width_m > 0.0 ? std::floor(static_cast(f) / width_m) : static_cast(f); +} + +struct LatticeOpenOrder +{ + bool operator()(const LatticeOpenEntry& a, const LatticeOpenEntry& b) const + { + return a.priority != b.priority ? a.priority > b.priority : a.serial > b.serial; + } +}; + +double latticeMotionCost(double length, double clearance, int steer, int last_steer, int multiple, const PlannerConfig& config); + +struct LatticePointConnector +{ + double curvature, arc_length_m, straight_length_m, arrival_yaw; +}; + +bool latticePointConnector(const PathPoint& start, const Point2& goal, double radius, int turn, + LatticePointConnector* connector); + +// One tile stores lazy C-space samples, not a cropped search window. A zero entry is unknown, +// one is conservatively free and two requires an exact check at the actual pose. +class LatticeCSpace +{ +public: + explicit LatticeCSpace(LatticeContext& context); + bool poseFree(double x, double y, double yaw, double sweep_margin = 0.0, double centre_sweep = 0.0); + bool segmentLegal(const PathPoint& a, const PathPoint& b); + bool spinLegal(double x, double y, double from, double to); + +private: + struct Tile + { + Tile(std::pmr::memory_resource* resource, std::size_t size) : samples(resource) { samples.resize((size + 3) / 4, 0); } + std::pmr::vector samples; + }; + LatticeContext& context_; + std::pmr::unordered_map tiles_; + std::pmr::vector blocked_prefix_; + bool prefix_ready_ = false; + double start_floor_ = 0.0; // [m] Gap margin allowed near the start, see endFloor(). + double goal_floor_ = 0.0; // [m] Same near the goal. + double endFloor(const Pose2& pose) const; + bool buildBlockedPrefix(); + uint32_t blockedCount(int32_t x0, int32_t y0, int32_t x1, int32_t y1) const; +}; + +struct LatticeField +{ + explicit LatticeField(std::pmr::memory_resource* resource) : values(resource), settled(resource) {} + std::pmr::vector values; + std::pmr::vector settled; + int32_t width = 0, height = 0; + int factor = 1; + double frontier = 0.0; + bool complete = false; + double at(double x, double y, const LatticeContext& context) const; +}; + +bool rejectLatticeCrossing(LatticeContext& context, const Path& path); +bool verifyLatticeCandidate(LatticeContext& context, const Path& path, PathCheck* check); +bool buildLatticeField(LatticeContext& context, LatticeField* field, TimePoint field_deadline); +bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* path, PathCheck* check); +bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output); + +} // namespace detail +} // namespace lane_route_core + +#endif // LANE_ROUTE_CORE_LATTICE_INTERNAL_H_ diff --git a/src/lattice_search.cpp b/src/lattice_search.cpp new file mode 100644 index 0000000..10b8d7d --- /dev/null +++ b/src/lattice_search.cpp @@ -0,0 +1,515 @@ +#include "lattice_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace detail +{ +namespace +{ + +struct Motion +{ + double curvature; + double length; +}; +struct DubinsWord +{ + std::array motion; + double length; +}; +struct AnalyticCandidate +{ + DubinsWord word; + double arrival_yaw; + std::size_t serial; +}; + +double mod2pi(double angle) +{ + double a = std::fmod(angle, 2.0 * kPi); + return a < 0.0 ? a + 2.0 * kPi : a; +} + +PathPoint integrate(const PathPoint& p, double curvature, double length) +{ + if (std::abs(curvature) < 1e-12) + return { p.x + length * std::cos(p.yaw), p.y + length * std::sin(p.yaw), p.yaw, 0.0 }; + const double yaw = p.yaw + curvature * length; + return { p.x + (std::sin(yaw) - std::sin(p.yaw)) / curvature, + p.y - (std::cos(yaw) - std::cos(p.yaw)) / curvature, yaw, curvature }; +} + +// All six forward Dubins words, normalized by the requested turning radius. +int dubinsWords(const PathPoint& start, double gx, double gy, double gyaw, double radius, std::array* out) +{ + const double dx = gx - start.x, dy = gy - start.y; + const double d = std::hypot(dx, dy) / radius; + const double theta = d > 1e-9 ? std::atan2(dy, dx) : 0.0; + const double a = mod2pi(start.yaw - theta), b = mod2pi(gyaw - theta); + const double sa = std::sin(a), ca = std::cos(a), sb = std::sin(b), cb = std::cos(b), cab = std::cos(a - b); + int n = 0; + const auto add = [&](int s0, int s1, int s2, double t, double p, double q) { + // mod2pi turns a tiny negative angle into almost 2*pi, which adds a full loop of radius R and always fails the crossing test. + const auto snap = [](double angle) { return angle > 2.0 * kPi - 1e-9 ? 0.0 : angle; }; + t = snap(t); + q = snap(q); + if (s1 != 0) + p = snap(p); + DubinsWord word{{ Motion{ s0 / radius, t * radius }, Motion{ s1 / radius, p * radius }, + Motion{ s2 / radius, q * radius } }, (t + p + q) * radius }; + (*out)[n++] = word; + }; + double p2 = 2.0 + d*d - 2.0*cab + 2.0*d*(sa-sb); + if (p2 >= 0.0) + { + const double u = std::atan2(cb-ca, d+sa-sb); + add(1, 0, 1, mod2pi(u-a), std::sqrt(p2), mod2pi(b-u)); + } + p2 = 2.0 + d*d - 2.0*cab + 2.0*d*(sb-sa); + if (p2 >= 0.0) + { + const double u = std::atan2(ca-cb, d-sa+sb); + add(-1, 0, -1, mod2pi(a-u), std::sqrt(p2), mod2pi(u-b)); + } + p2 = -2.0 + d*d + 2.0*cab + 2.0*d*(sa+sb); + if (p2 >= 0.0) + { + const double p = std::sqrt(p2), u = std::atan2(-ca-cb, d+sa+sb) - std::atan2(-2.0, p); + add(1, 0, -1, mod2pi(u-a), p, mod2pi(u-b)); + } + p2 = -2.0 + d*d + 2.0*cab - 2.0*d*(sa+sb); + if (p2 >= 0.0) + { + const double p = std::sqrt(p2), u = std::atan2(ca+cb, d-sa-sb) - std::atan2(2.0, p); + add(-1, 0, 1, mod2pi(a-u), p, mod2pi(b-u)); + } + double u = (6.0-d*d+2.0*cab+2.0*d*(sa-sb))/8.0; + if (std::abs(u) <= 1.0) + { + const double p = mod2pi(2.0*kPi-std::acos(u)); + const double t = mod2pi(a-std::atan2(ca-cb,d-sa+sb)+p/2.0); + add(-1, 1, -1, t, p, mod2pi(a-b-t+p)); + } + u = (6.0-d*d+2.0*cab+2.0*d*(sb-sa))/8.0; + if (std::abs(u) <= 1.0) + { + const double p = mod2pi(2.0*kPi-std::acos(u)); + const double t = mod2pi(-a-std::atan2(ca-cb,d+sa-sb)+p/2.0); + add(1, -1, 1, t, p, mod2pi(b-a-t+p)); + } + std::sort(out->begin(), out->begin()+n, [](const DubinsWord& x, const DubinsWord& y) { return x.length < y.length; }); + return n; +} + +struct Node +{ + PathPoint pose; + double g; + int64_t parent; + double motion_curvature; + double motion_length; + int heading; + int last_steer; +}; +struct KeyHash +{ + std::size_t operator()(const LatticeStateKey& k) const + { + std::size_t h = std::hash{}(k.x); + for (int32_t v : { k.y, k.heading }) + h ^= std::hash{}(v) + 0x9e3779b9u + (h << 6) + (h >> 2); + return h; + } +}; + +bool appendMotion(LatticeContext& context, LatticeCSpace& space, const Motion& motion, Path* path, bool check = true) +{ + if (motion.length < 1e-12) return true; + const PathPoint begin = path->back(); + const double spacing = std::min(context.config.output_step_m, 0.04); + const double step_count = std::max(std::ceil(motion.length / spacing), std::ceil(std::abs(motion.curvature * motion.length) / 0.03)); + if (!std::isfinite(step_count) || step_count > static_cast(std::numeric_limits::max())) + { + context.info.lattice_reason = "lattice_resource_limit"; + return false; + } + const int steps = std::max(1, static_cast(step_count)); + for (int i = 1; i <= steps; ++i) + { + if (context.expired()) return false; + const PathPoint point = integrate(begin, motion.curvature, motion.length * i / steps); + if (check && !space.segmentLegal(path->back(), point)) return false; + path->push_back(point); + } + return true; +} + +bool appendSpin(LatticeContext& context, LatticeCSpace& space, double target, Path* path, bool check = true) +{ + const PathPoint begin = path->back(); + const double angle = wrapAngle(target - begin.yaw); + if (check && !space.spinLegal(begin.x, begin.y, begin.yaw, target)) return false; + const int steps = std::max(1, static_cast(std::ceil(std::abs(angle) / 0.03))); + for (int i = 1; i <= steps; ++i) + { + if (context.expired()) return false; + path->push_back({ begin.x, begin.y, begin.yaw + angle * i / steps, 0.0 }); + } + return true; +} + +// Test all non-adjacent moving chords; the public verifier also performs its own independent crossing check. +bool hasCrossing(LatticeContext& context, const Path& path) +{ + // Each segment is tested only against segments that share a 0.5 m bucket. The all-pairs test cost about 10 ms on a 100 m path and + // ran for every analytic candidate (kit sehc pair_23: 566 candidates, 2.4 s of verification). Segments that share no bucket cannot + // meet, so the answer is the same as all pairs. + const auto orient = [](const PathPoint& a, const PathPoint& b, const PathPoint& p) { + return (b.x-a.x)*(p.y-a.y) - (b.y-a.y)*(p.x-a.x); + }; + const auto onSegment = [](const PathPoint& a, const PathPoint& b, const PathPoint& p) { + constexpr double e = 1e-10; + return p.x >= std::min(a.x,b.x)-e && p.x <= std::max(a.x,b.x)+e && + p.y >= std::min(a.y,b.y)-e && p.y <= std::max(a.y,b.y)+e; + }; + const auto crosses = [&](std::size_t i, std::size_t j) { + const PathPoint& a = path[i]; + const PathPoint& b = path[i+1]; + const PathPoint& c = path[j]; + const PathPoint& d = path[j+1]; + constexpr double e = 1e-12; + const double ab_c = orient(a,b,c), ab_d = orient(a,b,d), cd_a = orient(c,d,a), cd_b = orient(c,d,b); + if (((ab_c > e && ab_d < -e) || (ab_c < -e && ab_d > e)) && + ((cd_a > e && cd_b < -e) || (cd_a < -e && cd_b > e))) return true; + return (std::abs(ab_c) <= e && onSegment(a,b,c)) || (std::abs(ab_d) <= e && onSegment(a,b,d)) || + (std::abs(cd_a) <= e && onSegment(c,d,a)) || (std::abs(cd_b) <= e && onSegment(c,d,b)); + }; + constexpr double kBucketM = 0.5; + constexpr double kPad = 1e-9; + const auto cellOf = [](double v) { return static_cast(std::floor(v / kBucketM)); }; + const auto keyOf = [](int64_t x, int64_t y) { + return (static_cast(static_cast(x)) << 32) | static_cast(y); + }; + std::unordered_map> buckets; + std::vector moving; + for (std::size_t i = 0; i+1 < path.size(); ++i) + { + if ((i & 1023u) == 0 && context.expired()) return false; + const PathPoint& a = path[i]; + const PathPoint& b = path[i+1]; + if (std::hypot(b.x-a.x,b.y-a.y) < 1e-10) continue; + moving.push_back(i); + for (int64_t x = cellOf(std::min(a.x,b.x)-kPad); x <= cellOf(std::max(a.x,b.x)+kPad); ++x) + for (int64_t y = cellOf(std::min(a.y,b.y)-kPad); y <= cellOf(std::max(a.y,b.y)+kPad); ++y) + buckets[keyOf(x, y)].push_back(i); + } + for (std::size_t k = 0; k < moving.size(); ++k) + { + if ((k & 255u) == 0 && context.expired()) return false; + const std::size_t i = moving[k]; + const PathPoint& a = path[i]; + const PathPoint& b = path[i+1]; + for (int64_t x = cellOf(std::min(a.x,b.x)-kPad); x <= cellOf(std::max(a.x,b.x)+kPad); ++x) + for (int64_t y = cellOf(std::min(a.y,b.y)-kPad); y <= cellOf(std::max(a.y,b.y)+kPad); ++y) + for (std::size_t j : buckets[keyOf(x, y)]) + if (j >= i+2 && crosses(i, j)) return true; + } + return false; +} + +bool verifyCandidateImpl(LatticeContext& context, const Path& path, PathCheck* check) +{ + if (context.expired() || path.size() < 2 || !endpointOk(path, context.request.start, context.request.goal)) return false; + const Pose2& goal = context.request.goal; + if (std::hypot(path.back().x - goal.x, path.back().y - goal.y) > 1e-6 || + (goal.has_yaw && std::abs(wrapAngle(path.back().yaw - goal.yaw)) > 1e-6)) return false; + if (rejectLatticeCrossing(context, path)) return false; + if (context.expired()) return false; + *check = verifyPath(path, context.grid, context.deviation_deg, context.config, context.request.cancel, &context.deadline); + if (context.expired()) return false; + if (check->self_crossings > 0) + { + ++context.info.lattice_crossing_rejects; + return false; + } + if (!check->valid || !freeClearanceOk(path, context.grid, clearanceThresholdMm(context.config.clearance_min_m), context.request.cancel, &context.deadline) || + blockedEndpointTurn(path, context.grid, context.config.half_x_m, context.config.half_y_m) != nullptr) return false; + if (context.expired()) return false; + const GapCheck gap = checkFootprintGap(path, context.grid, context.config.footprint_min_gap_m, + context.config.half_x_m, context.config.half_y_m, context.request.cancel, &context.deadline, + true); + if (context.expired() || !gap.valid) return false; + context.info.min_gap_m = gap.min_gap_m; + context.info.gap_exemption_used = gap.exemption_used; + return true; +} + +} // namespace + +bool rejectLatticeCrossing(LatticeContext& context, const Path& path) +{ + if (!hasCrossing(context, path)) return false; + ++context.info.lattice_crossing_rejects; + return true; +} + +bool verifyLatticeCandidate(LatticeContext& context, const Path& path, PathCheck* check) +{ + const TimePoint began = Clock::now(); + try + { + const bool result = verifyCandidateImpl(context, path, check); + context.info.lattice_verify_ms += msSince(began); + return result; + } + catch (...) + { + context.info.lattice_verify_ms += msSince(began); + throw; + } +} + +bool latticePointConnector(const PathPoint& start, const Point2& goal, double radius, int turn, + LatticePointConnector* connector) +{ + if (connector == nullptr || !(radius > 0.0) || (turn != 1 && turn != -1)) return false; + const double cx = start.x - turn * radius * std::sin(start.yaw); + const double cy = start.y + turn * radius * std::cos(start.yaw); + const double dx = goal.x - cx, dy = goal.y - cy; + const double distance = std::hypot(dx, dy); + if (!std::isfinite(distance) || distance < radius) return false; + const double arrival = std::atan2(dy, dx) + turn * std::asin(std::min(1.0, radius / distance)); + double delta = wrapAngle(arrival - start.yaw); + if (std::abs(delta) < 1e-12) delta = 0.0; + const double arc = radius * mod2pi(turn * delta); + const double line = std::sqrt(std::max(0.0, (distance - radius) * (distance + radius))); + if (!std::isfinite(arc) || !std::isfinite(line)) return false; + *connector = { turn / radius, arc, line, arrival }; + return true; +} + +double latticeMotionCost(double length, double clearance, int steer, int last_steer, int multiple, const PlannerConfig& config) +{ + return length * (1.0 + config.lattice_wall_weight_m / std::max(0.05, clearance)) + + (steer != 0 && last_steer != 0 && steer != last_steer ? config.lattice_switch_cost_m : 0.0) + + (steer != 0 ? config.lattice_steer_cost_m * multiple : 0.0); +} + +bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* output, PathCheck* check) +{ + const PlannerConfig& c = context.config; + const GridRef& grid = context.grid; + const double angle = 2.0 * kPi / c.lattice_heading_bins; + const double basic = c.min_turn_radius_m * angle; + const std::size_t grid_cells = static_cast(grid.width) * static_cast(grid.height); + const double bin_resolution = grid_cells > 2000000u ? c.lattice_closed_resolution_m : + std::min(c.lattice_closed_resolution_m, grid.resolution); + if (!std::isfinite(bin_resolution) || bin_resolution <= 0.0 || + grid.width * grid.resolution / bin_resolution > std::numeric_limits::max() || + grid.height * grid.resolution / bin_resolution > std::numeric_limits::max()) + { + context.info.lattice_reason = "lattice_resource_limit"; + return false; + } + using NodeVector = std::pmr::vector; + using OpenVector = std::pmr::vector; + NodeVector nodes(&context.memory); + std::priority_queue open{ LatticeOpenOrder{}, OpenVector(&context.memory) }; + std::pmr::unordered_map best(&context.memory); + std::pmr::unordered_set analytic_attempted(&context.memory); + uint64_t serial = 0; + const auto keyOf = [&](const PathPoint& p, int heading) -> LatticeStateKey { + return { static_cast(std::floor((p.x-grid.origin_x)/bin_resolution)), + static_cast(std::floor((p.y-grid.origin_y)/bin_resolution)), heading }; + }; + const auto offer = [&](const Node& node) { + const LatticeStateKey key = keyOf(node.pose, node.heading); + const auto previous = best.find(key); + // A basic step (0.0925 m at R 1.06 m and 72 headings) is shorter than a 0.10 m closed bin, so a straight child can land in its own + // parent's bin. Comparing it with the parent would always drop it, and a lane that only allows basic steps could never be left + // (sehc pair_11 at 0 degrees: exhausted after 83 states with 72 headings, solved with 8 to 48). The parent is already expanded, so + // the child takes its place in the bin. + if (previous != best.end() && static_cast(previous->second) != node.parent && nodes[previous->second].g <= node.g) return; + const std::size_t id = nodes.size(); + nodes.push_back(node); + best[key] = id; + const double f = node.g + c.lattice_heuristic_weight * field.at(node.pose.x, node.pose.y, context); + open.push({ latticeBucketPriority(f, c.lattice_bucket_width_m), serial++, id }); + }; + const Pose2& start = context.request.start; + if (start.has_yaw) + { + const double normalized = mod2pi(start.yaw); + const int nearest = static_cast(std::floor(normalized / angle + 0.5)) % c.lattice_heading_bins; + if (std::abs(wrapAngle(start.yaw - nearest * angle)) > 1e-10 && space.poseFree(start.x, start.y, start.yaw)) + { + // The off-bin family keeps its exact yaw offset through all primitive turns. + offer({ {start.x, start.y, start.yaw, 0.0}, 0.0, -1, 0.0, 0.0, c.lattice_heading_bins + nearest, 0 }); + } + } + for (int h = 0; h < c.lattice_heading_bins; ++h) + { + if (context.expired()) return false; + const double yaw = h * angle; + if (!space.poseFree(start.x, start.y, yaw)) continue; + if (start.has_yaw && std::abs(wrapAngle(yaw - start.yaw)) > 1e-10 && + !space.spinLegal(start.x, start.y, start.yaw, yaw)) continue; + offer({ {start.x, start.y, yaw, 0.0}, 0.0, -1, 0.0, 0.0, h, 0 }); + } + uint64_t last_analytic = 0; + uint64_t rung_expanded = 0; + while (!open.empty()) + { + if (context.expired()) return false; + const LatticeOpenEntry entry = open.top(); open.pop(); + const Node current = nodes[entry.node]; + const auto known = best.find(keyOf(current.pose, current.heading)); + if (known == best.end() || known->second != entry.node) continue; + ++context.info.lattice_states_expanded; + ++rung_expanded; + const double distance = std::hypot(current.pose.x-context.request.goal.x, current.pose.y-context.request.goal.y); + if ((rung_expanded == 1 || rung_expanded-last_analytic >= static_cast(c.lattice_analytic_interval) || + distance <= c.lattice_analytic_near_goal_m) && analytic_attempted.insert(keyOf(current.pose, current.heading)).second) + { + last_analytic = rung_expanded; + const Pose2& goal = context.request.goal; + const double bearing = std::atan2(goal.y-current.pose.y, goal.x-current.pose.x); + const double radius = std::max(c.min_turn_radius_m, c.lattice_analytic_radius_m); + const double length_limit = 1.8 * distance + 3.0; + std::pmr::vector candidates(&context.memory); + candidates.reserve(2 + 6 * static_cast(c.lattice_analytic_goal_headings + 3)); + for (int turn : { 1, -1 }) + { + LatticePointConnector point; + if (!latticePointConnector(current.pose, { goal.x, goal.y }, radius, turn, &point)) continue; + const DubinsWord word{{ Motion{ point.curvature, point.arc_length_m }, Motion{ 0.0, point.straight_length_m }, + Motion{ 0.0, 0.0 } }, point.arc_length_m + point.straight_length_m }; + if (word.length <= length_limit) candidates.push_back({ word, point.arrival_yaw, candidates.size() }); + } + std::array headings; + std::size_t heading_count = 0; + const auto addHeading = [&](double yaw) { + for (std::size_t i = 0; i < heading_count; ++i) + if (std::abs(wrapAngle(headings[i] - yaw)) < 1e-12) return; + headings[heading_count++] = yaw; + }; + for (int i = 0; i < c.lattice_analytic_goal_headings; ++i) + { + if ((i & 31) == 0 && context.expired()) return false; + addHeading(i * 2.0 * kPi / c.lattice_analytic_goal_headings); + } + // Keep the previous exact heading candidates as well, including a fixed yaw that cannot spin. + if (goal.has_yaw) addHeading(goal.yaw); + addHeading(bearing); + addHeading(current.pose.yaw); + for (std::size_t h = 0; h < heading_count; ++h) + { + if (context.expired()) return false; + const double target_yaw = headings[h]; + std::array words; + const int count = dubinsWords(current.pose, goal.x, goal.y, target_yaw, radius, &words); + for (int w = 0; w < count; ++w) + { + if (std::isfinite(words[w].length) && words[w].length <= length_limit) + candidates.push_back({ words[w], target_yaw, candidates.size() }); + } + } + std::sort(candidates.begin(), candidates.end(), [](const AnalyticCandidate& a, const AnalyticCandidate& b) { + return a.word.length != b.word.length ? a.word.length < b.word.length : a.serial < b.serial; + }); + for (const AnalyticCandidate& option : candidates) + { + if (context.expired()) return false; + Path connector(1, current.pose); + bool legal = true; + for (const Motion& motion : option.word.motion) + if (legal) legal = appendMotion(context, space, motion, &connector); + if (context.info.lattice_reason == "lattice_resource_limit") return false; + if (!legal || context.expired()) continue; + if (std::hypot(connector.back().x-goal.x, connector.back().y-goal.y) > 1e-6 || + std::abs(wrapAngle(connector.back().yaw-option.arrival_yaw)) > 1e-6) continue; + if (goal.has_yaw && std::abs(wrapAngle(connector.back().yaw-goal.yaw)) > 1e-12 && + !appendSpin(context, space, goal.yaw, &connector)) continue; + + // Prefix motions and the start spin were checked when their states were offered. + std::pmr::vector chain(&context.memory); + for (int64_t id = static_cast(entry.node); id >= 0; id = nodes[static_cast(id)].parent) + { + if (context.expired()) return false; + chain.push_back(static_cast(id)); + } + std::reverse(chain.begin(), chain.end()); + Path candidate; + const Node& root = nodes[chain.front()]; + candidate.push_back({ start.x, start.y, start.has_yaw ? start.yaw : root.pose.yaw, 0.0 }); + if (start.has_yaw && std::abs(wrapAngle(root.pose.yaw-start.yaw)) > 1e-12 && + !appendSpin(context, space, root.pose.yaw, &candidate, false)) continue; + for (std::size_t i = 1; i < chain.size() && legal; ++i) + { + const Node& node = nodes[chain[i]]; + legal = appendMotion(context, space, { node.motion_curvature, node.motion_length }, &candidate, false); + } + if (context.info.lattice_reason == "lattice_resource_limit") return false; + if (!legal || context.expired()) continue; + candidate.insert(candidate.end(), connector.begin() + 1, connector.end()); + if (candidate.size() == 1) candidate.push_back(candidate.front()); + if (verifyLatticeCandidate(context, candidate, check)) + { + *output = std::move(candidate); + return true; + } + } + } + const int multiples[] = { c.lattice_primitive_multiple_1, c.lattice_primitive_multiple_2, c.lattice_primitive_multiple_3 }; + for (int multi : multiples) + for (int steer : { 0, 1, -1 }) + { + if (context.expired()) return false; + const double length = basic * multi; + const double curvature = steer / c.min_turn_radius_m; + if (multi > 1) + { + const int32_t x = static_cast(std::floor((current.pose.x-grid.origin_x)/grid.resolution)); + const int32_t y = static_cast(std::floor((current.pose.y-grid.origin_y)/grid.resolution)); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height || + grid.clearance_mm[static_cast(y)*grid.width+x]/1000.0 <= + std::hypot(c.half_x_m,c.half_y_m)+c.footprint_min_gap_m+length+std::sqrt(2.0)*grid.resolution) continue; + } + Path piece(1, current.pose); + if (!appendMotion(context, space, { curvature, length }, &piece)) + { + if (context.info.lattice_reason == "lattice_resource_limit") return false; + continue; + } + const PathPoint next = piece.back(); + const int family = current.heading / c.lattice_heading_bins; + const int bin = current.heading % c.lattice_heading_bins; + const int heading = family * c.lattice_heading_bins + + (bin + steer * multi % c.lattice_heading_bins + c.lattice_heading_bins) % c.lattice_heading_bins; + const int last = steer == 0 ? current.last_steer : steer; + const int32_t x = static_cast(std::floor((next.x-grid.origin_x)/grid.resolution)); + const int32_t y = static_cast(std::floor((next.y-grid.origin_y)/grid.resolution)); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) continue; + const double clear = std::max(0.05, grid.clearance_mm[static_cast(y)*grid.width+x]/1000.0); + const double cost = latticeMotionCost(length, clear, steer, current.last_steer, multi, c); + offer({ next, current.g+cost, static_cast(entry.node), curvature, length, heading, last }); + } + } + context.info.lattice_reason = "lattice_exhausted"; + return false; +} + +} // namespace detail +} // namespace lane_route_core diff --git a/src/lattice_tier.cpp b/src/lattice_tier.cpp new file mode 100644 index 0000000..8c04714 --- /dev/null +++ b/src/lattice_tier.cpp @@ -0,0 +1,79 @@ +#include "lattice_internal.h" + +#include +#include +#include +#include + +namespace lane_route_core +{ +namespace detail +{ +namespace +{ +class StageTimer +{ +public: + StageTimer(double& target, const double* excluded = nullptr) + : target_(target), excluded_(excluded), previous_(excluded ? *excluded : 0.0), began_(Clock::now()) {} + ~StageTimer() + { + const double child = excluded_ ? *excluded_ - previous_ : 0.0; + target_ += std::max(0.0, msSince(began_) - child); + } +private: + double& target_; + const double* excluded_; + double previous_; + TimePoint began_; +}; +} // namespace + +bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) +{ + const TimePoint began = Clock::now(); + const std::size_t limit = static_cast(input.config.lattice_max_memory_mb) * 1024u * 1024u; + LatticeMemory memory(limit); + LatticeContext context{ input.request, input.grid, input.config, input.deviation_deg, input.deadline, output.info, memory }; + output.info.lattice_reason.clear(); + bool ok = false; + try + { + LatticeCSpace space(context); + LatticeField field(&memory); + const auto slice = input.deadline - began; + const TimePoint field_deadline = began + std::chrono::duration_cast(slice * input.config.lattice_field_time_fraction); + bool field_ok = false; + { + StageTimer timer(output.info.lattice_field_ms); + field_ok = buildLatticeField(context, &field, field_deadline); + } + if (field_ok) + { + StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); + ok = searchLattice(context, space, field, &output.path, &output.check); + } + } + catch (const std::bad_alloc&) + { + output.info.lattice_reason = "lattice_resource_limit"; + } + output.info.lattice_peak_bytes = std::max(output.info.lattice_peak_bytes, static_cast(memory.peak())); + output.info.lattice_ms += msSince(began); + const bool cancelled = context.cancelled(); + const bool timed_out = Clock::now() >= input.deadline; + if (cancelled) output.info.lattice_reason = "cancelled"; + else if (timed_out) output.info.lattice_reason = "lattice_timeout"; + else if (ok) output.info.lattice_reason = "verified"; + else if (output.info.lattice_reason.empty()) output.info.lattice_reason = "lattice_exhausted"; + if (!ok || cancelled || timed_out) + { + output.path.clear(); + return false; + } + output.info.reason = "verified"; + return true; +} + +} // namespace detail +} // namespace lane_route_core diff --git a/src/path_verifier.cpp b/src/path_verifier.cpp new file mode 100644 index 0000000..011ed63 --- /dev/null +++ b/src/path_verifier.cpp @@ -0,0 +1,250 @@ +#include + +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace +{ + +constexpr double kRadToDeg = 180.0 / kPi; +constexpr double kBendSpacingM = 0.10; +constexpr double kBendLimitDeg = 8.0; // A 1.06 m arc turns 5.4 deg over 0.1 m, so a legal curve stays below this. + +/** Segment against a unit cell, slab test in grid coordinates. */ +bool segmentHitsCell(double x0, double y0, double x1, double y1, int32_t ix, int32_t iy) +{ + double low = 0.0, high = 1.0; + const double points[2] = { x0, y0 }; + const double deltas[2] = { x1 - x0, y1 - y0 }; + const double bounds[2] = { static_cast(ix), static_cast(iy) }; + for (int axis = 0; axis < 2; ++axis) + { + if (std::abs(deltas[axis]) < 1e-14) + { + if (points[axis] < bounds[axis] || points[axis] > bounds[axis] + 1.0) + return false; + } + else + { + const double a = (bounds[axis] - points[axis]) / deltas[axis]; + const double b = (bounds[axis] + 1.0 - points[axis]) / deltas[axis]; + low = std::max(low, std::min(a, b)); + high = std::min(high, std::max(a, b)); + if (low > high + 1e-12) + return false; + } + } + return true; +} + +int zoneViolations(const PathPoint& a, const PathPoint& b, const GridRef& grid, double deviation_deg) +{ + if (grid.direction == nullptr) + return 0; + const double x0 = (a.x - grid.origin_x) / grid.resolution; + const double y0 = (a.y - grid.origin_y) / grid.resolution; + const double x1 = (b.x - grid.origin_x) / grid.resolution; + const double y1 = (b.y - grid.origin_y) / grid.resolution; + if (std::hypot(x1 - x0, y1 - y0) < 1e-12) + return 0; + const double angle = std::atan2(b.y - a.y, b.x - a.x); + int count = 0; + const int32_t first_y = std::max(0, static_cast(std::floor(std::min(y0, y1) - 1e-10))); + const int32_t last_y = std::min(grid.height - 1, static_cast(std::floor(std::max(y0, y1) + 1e-10))); + const int32_t first_x = std::max(0, static_cast(std::floor(std::min(x0, x1) - 1e-10))); + const int32_t last_x = std::min(grid.width - 1, static_cast(std::floor(std::max(x0, x1) + 1e-10))); + for (int32_t y = first_y; y <= last_y; ++y) + { + for (int32_t x = first_x; x <= last_x; ++x) + { + const uint8_t code = grid.direction[y * grid.width + x]; + if (code == 0 || !segmentHitsCell(x0, y0, x1, y1, x, y)) + continue; + if (std::abs(wrapAngle(angle - (code - 1) * kPi / 4.0)) * kRadToDeg > deviation_deg + 1e-9) + ++count; + } + } + return count; +} + +bool kinkMetrics(const Path& path, int* kinks, double* max_bend_deg, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline) +{ + std::vector along(path.size(), 0.0); + for (std::size_t i = 0; i + 1 < path.size(); ++i) + { + if ((i & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return false; + along[i + 1] = along[i] + std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y); + } + const double total = along.back(); + + int spins = 0; + std::size_t i = 0; + const std::size_t segments = path.size() - 1; + while (i < segments) + { + const double step = along[i + 1] - along[i]; + if (step < 1e-4 && std::abs(wrapAngle(path[i + 1].yaw - path[i].yaw)) > 1e-3) + { + std::size_t j = i; + while (j < segments && along[j + 1] - along[j] < 1e-4) + ++j; + if (along[i] > 0.02 && total - along[i] > 0.02) + ++spins; + i = j; + } + else + { + ++i; + } + } + + std::vector keep(1, 0); + for (std::size_t k = 1; k < path.size(); ++k) + if (along[k] - along[keep.back()] >= kBendSpacingM) + keep.push_back(k); + int over = 0; + double largest = 0.0; + for (std::size_t k = 0; k + 2 < keep.size(); ++k) + { + const PathPoint& a = path[keep[k]]; + const PathPoint& b = path[keep[k + 1]]; + const PathPoint& c = path[keep[k + 2]]; + const double bend = std::abs(wrapAngle(std::atan2(c.y - b.y, c.x - b.x) - std::atan2(b.y - a.y, b.x - a.x))) * kRadToDeg; + largest = std::max(largest, bend); + if (bend > kBendLimitDeg) + ++over; + } + *kinks = spins + over; + *max_bend_deg = largest; + return true; +} + +int selfCrossings(const Path& path, const std::atomic* cancel, + const std::chrono::steady_clock::time_point* deadline) +{ + constexpr double kStep = 0.1; + constexpr std::size_t kIgnore = 3; + std::vector distinct; + std::vector along; + for (const PathPoint& point : path) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return -1; + const Point2 here{ point.x, point.y }; + if (distinct.empty()) + { + distinct.push_back(here); + along.push_back(0.0); + } + else if (distanceOf(distinct.back(), here) > 1e-6) + { + along.push_back(along.back() + distanceOf(distinct.back(), here)); + distinct.push_back(here); + } + } + if (distinct.size() < 3) + return 0; + + std::vector samples; + std::size_t segment = 0; + const double total = along.back(); + for (std::size_t k = 0; k * kStep < total + kStep / 2.0; ++k) + { + if ((k & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return -1; + const double s = std::min(k * kStep, total); + while (segment + 2 < distinct.size() && along[segment + 1] < s) + ++segment; + const double span = along[segment + 1] - along[segment]; + const double t = span > 0.0 ? (s - along[segment]) / span : 0.0; + samples.push_back({ distinct[segment].x + t * (distinct[segment + 1].x - distinct[segment].x), + distinct[segment].y + t * (distinct[segment + 1].y - distinct[segment].y) }); + } + if (samples.size() < kIgnore + 3) + return 0; + + int count = 0; + const std::size_t lines = samples.size() - 1; + for (std::size_t i = 0; i + kIgnore + 1 < lines; ++i) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return -1; + const Point2& a = samples[i]; + const Point2& b = samples[i + 1]; + const double wx = b.x - a.x; + const double wy = b.y - a.y; + for (std::size_t j = i + kIgnore + 1; j < lines; ++j) + { + if ((j & 1023u) == 0 && ((cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline))) return -1; + const Point2& c = samples[j]; + const Point2& e = samples[j + 1]; + const double vx = e.x - c.x; + const double vy = e.y - c.y; + const double o1 = wx * (c.y - a.y) - wy * (c.x - a.x); + const double o2 = wx * (e.y - a.y) - wy * (e.x - a.x); + const double o3 = vx * (a.y - c.y) - vy * (a.x - c.x); + const double o4 = vx * (b.y - c.y) - vy * (b.x - c.x); + if (o1 * o2 < 0.0 && o3 * o4 < 0.0) + ++count; + } + } + return count; +} + +} // namespace + +PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config, + const std::atomic* cancel) +{ + return verifyPath(path, grid, deviation_deg, config, cancel, nullptr); +} + +PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline) +{ + PathCheck check; + if (path.size() < 2) + return check; + for (const PathPoint& point : path) + if (!std::isfinite(point.x) || !std::isfinite(point.y) || !std::isfinite(point.yaw)) + return check; + + if (!kinkMetrics(path, &check.kinks, &check.max_bend_deg, cancel, deadline)) return check; + for (std::size_t i = 0; i + 1 < path.size(); ++i) + { + if ((cancel && cancel->load(std::memory_order_relaxed)) || (deadline && std::chrono::steady_clock::now() >= *deadline)) return check; + const PathPoint& a = path[i]; + const PathPoint& b = path[i + 1]; + const double dx = b.x - a.x; + const double dy = b.y - a.y; + const double distance = std::hypot(dx, dy); + const double turn = wrapAngle(b.yaw - a.yaw); + if (distance > 1e-7) + { + // The displacement is a chord: recover arc length before estimating curvature. + const double arc = std::abs(turn) < 1e-9 ? distance : distance * std::abs(turn) / (2.0 * std::abs(std::sin(turn / 2.0))); + check.max_curvature = std::max(check.max_curvature, std::abs(turn) / arc); + } + check.zone_violations += zoneViolations(a, b, grid, deviation_deg); + const int samples = std::max({ 1, static_cast(std::ceil(distance / 0.01)), static_cast(std::ceil(std::abs(turn) / 0.03)) }); + for (int j = 0; j <= samples; ++j) + { + const double t = static_cast(j) / samples; + if (footprintCollides(grid, a.x + t * dx, a.y + t * dy, a.yaw + t * turn, config.half_x_m, config.half_y_m)) + ++check.footprint_collisions; + } + } + check.self_crossings = selfCrossings(path, cancel, deadline); + if (check.self_crossings < 0) return check; + check.valid = check.zone_violations == 0 && check.footprint_collisions == 0 && check.kinks == 0 && + check.self_crossings == 0 && check.max_curvature <= 1.0 / config.min_turn_radius_m + 1e-6; + return check; +} + +} // namespace lane_route_core diff --git a/src/route_graph_path.cpp b/src/route_graph_path.cpp new file mode 100644 index 0000000..e389e86 --- /dev/null +++ b/src/route_graph_path.cpp @@ -0,0 +1,711 @@ +#include "route_planner_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace lane_route_core +{ +namespace detail +{ + +namespace +{ + +struct Simplified +{ + std::vector vertices; + /** Per vertex: the graph transitions it stands for, so a dead corner can ban exactly those. */ + std::vector>> provenance; +}; + +/** Route points in travel order, before any shortcut. */ +RawChain routeRawChain(const QueryGraph& query, const std::vector& route) +{ + RawChain raw; + for (std::size_t edge_index = 0; edge_index < route.size(); ++edge_index) + { + const GraphEdge& edge = query.edge(route[edge_index]); + const bool lock = isLocked(edge.kind); + for (const Point2& point : edge.points) + { + if (!raw.vertices.empty() && distanceOf(raw.vertices.back(), point) < 1e-7) + { + if (lock) + raw.locked.back() = 1; + continue; + } + raw.vertices.push_back(point); + raw.locked.push_back(lock ? 1 : 0); + } + if (edge_index + 1 < route.size()) + raw.boundaries.emplace_back(raw.vertices.size() - 1, edge_index); + } + return raw; +} + +/** Clearance tiers of a shortcut [mm]: preferred, then minimum. A raise lifts both. */ +void shortcutTiers(const QueryContext& context, double shortcut_minimum_m, int tiers[2]) +{ + const bool raised = shortcut_minimum_m > 0.0; + const int raised_mm = raised ? clearanceThresholdMm(shortcut_minimum_m) : 0; + tiers[0] = raised ? std::max(context.preferred_mm, raised_mm) : context.preferred_mm; + tiers[1] = raised ? std::max(context.min_mm, raised_mm) : context.min_mm; +} + +/** Per chain vertex: the graph transitions it stands for. */ +std::vector>> chainProvenance(const std::vector& indices, + const std::vector>& boundaries, + const std::vector& route) +{ + std::vector>> provenance(indices.size()); + for (std::size_t j = 1; j + 1 < indices.size(); ++j) + { + std::size_t nearest = std::numeric_limits::max(); + for (const auto& boundary : boundaries) + { + if (indices[j - 1] <= boundary.first && boundary.first <= indices[j + 1]) + { + const std::size_t distance = boundary.first > indices[j] ? boundary.first - indices[j] : indices[j] - boundary.first; + nearest = std::min(nearest, distance); + } + } + for (const auto& boundary : boundaries) + { + if (indices[j - 1] <= boundary.first && boundary.first <= indices[j + 1]) + { + const std::size_t distance = boundary.first > indices[j] ? boundary.first - indices[j] : indices[j] - boundary.first; + if (distance == nearest) + provenance[j].emplace_back(route[boundary.second], route[boundary.second + 1]); + } + } + } + return provenance; +} + +/** Freeze lane points. In free sections pull the farthest visible point, with preferred clearance first. */ +bool simplifyRoute(const QueryGraph& query, const std::vector& route, const QueryContext& context, const uint8_t* master, + double shortcut_minimum_m, Simplified* result) +{ + const RawChain raw = routeRawChain(query, route); + const std::vector& vertices = raw.vertices; + const std::vector& locked = raw.locked; + if (vertices.size() < 2) + return false; + + std::vector prefix(vertices.size(), 0.0); + for (std::size_t i = 0; i + 1 < vertices.size(); ++i) + prefix[i + 1] = prefix[i] + lineCost(vertices[i], vertices[i + 1], master, context.grid); + + int thresholds[2]; + shortcutTiers(context, shortcut_minimum_m, thresholds); + + std::vector out(1, vertices[0]); + std::vector indices(1, 0); + std::size_t i = 0; + while (i + 1 < vertices.size()) + { + std::size_t boundary = vertices.size() - 1; + for (std::size_t j = i + 1; j < vertices.size(); ++j) + { + if (locked[j] != 0) + { + boundary = j; + break; + } + } + std::size_t found = i + 1; + for (int threshold : thresholds) + { + for (std::size_t j = boundary; j > i; --j) + { + if (lineOk(context.grid, vertices[i], vertices[j], context.deviation_deg, threshold) && + lineCost(vertices[i], vertices[j], master, context.grid) <= prefix[j] - prefix[i] + 1e-8) + { + found = j; + break; + } + } + if (found > i + 1) + break; + } + out.push_back(vertices[found]); + indices.push_back(found); + i = found; + } + + // Remove collinear vertices without changing the lane itself. + bool changed = true; + while (changed && out.size() > 2) + { + changed = false; + for (std::size_t k = 1; k + 1 < out.size(); ++k) + { + if (std::abs(wrapAngle(headingOf(out[k], out[k + 1]) - headingOf(out[k - 1], out[k]))) < 1e-7) + { + out.erase(out.begin() + static_cast(k)); + indices.erase(indices.begin() + static_cast(k)); + changed = true; + break; + } + } + } + + result->provenance = chainProvenance(indices, raw.boundaries, route); + result->vertices = std::move(out); + return true; +} + +/** A curve is usable when every pose is free, poses near obstacles pass the footprint test, and the direction holds. */ +bool curveLegal(const Path& curve, const QueryContext& context) +{ + const GridRef& grid = context.grid; + std::vector cells(curve.size()); + for (std::size_t i = 0; i < curve.size(); ++i) + { + const double fx = std::floor((curve[i].x - grid.origin_x) / grid.resolution); + const double fy = std::floor((curve[i].y - grid.origin_y) / grid.resolution); + if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height) + return false; + cells[i] = static_cast(fy) * grid.width + static_cast(fx); + if (grid.cost[cells[i]] >= kInscribedCost) + return false; + } + for (std::size_t i = 0; i < curve.size(); ++i) + if (grid.clearance_mm[cells[i]] < context.collision_mm && + footprintCollides(grid, curve[i].x, curve[i].y, curve[i].yaw, context.config.half_x_m, context.config.half_y_m)) + return false; + if (grid.direction == nullptr) + return true; + const double limit = context.deviation_deg * kPi / 180.0 + 1e-9; + for (std::size_t i = 0; i + 1 < curve.size(); ++i) + { + const double dx = curve[i + 1].x - curve[i].x; + const double dy = curve[i + 1].y - curve[i].y; + if (std::hypot(dx, dy) <= 1e-9) + continue; + const double angle = std::atan2(dy, dx); + for (int32_t cell : { cells[i], cells[i + 1] }) + { + const uint8_t code = grid.direction[cell]; + if (code != 0 && std::abs(wrapAngle(angle - (code - 1) * kPi / 4.0)) > limit) + return false; + } + } + return true; +} + +void appendLine(Path* out, const Point2& start, const Point2& end, double yaw, double step) +{ + const double distance = distanceOf(start, end); + if (distance < 1e-9) + return; + const int samples = std::max(1, static_cast(std::ceil(distance / step))); + for (int i = 1; i <= samples; ++i) + { + if (i == samples) + { + out->push_back({ end.x, end.y, yaw, 0.0 }); + } + else + { + const double t = static_cast(i) / samples; + out->push_back({ start.x + t * (end.x - start.x), start.y + t * (end.y - start.y), yaw, 0.0 }); + } + } +} + +void appendSpin(Path* out, double yaw) +{ + const PathPoint from = out->back(); + const double delta = wrapAngle(yaw - from.yaw); + if (std::abs(delta) < 1e-8) + return; + const int samples = static_cast(std::ceil(std::abs(delta) / kSpinStepRad)); + for (int i = 1; i <= samples; ++i) + out->push_back({ from.x, from.y, from.yaw + delta * i / samples, 0.0 }); +} + +/** Lines joined by clothoid corners. Each corner keeps every legal radius and sharpness; only neighbours interact. */ +bool buildPath(const std::vector& vertices, const Pose2& start, const Pose2& goal, QueryContext* context, Path* path, + BuildFailure* failure, std::vector* radii) +{ + using Option = QueryContext::CornerOption; + const std::size_t corner_count = vertices.size() - 2; + std::vector> corners(corner_count); + for (std::size_t i = 1; i + 1 < vertices.size(); ++i) + { + const Point2& a = vertices[i - 1]; + const Point2& b = vertices[i]; + const Point2& c = vertices[i + 1]; + if (std::abs(wrapAngle(headingOf(b, c) - headingOf(a, b))) < 1e-7) + { + corners[i - 1] = { Option{ 0.0, nullptr, 0.0 } }; + continue; + } + const std::array key{ a.x, a.y, b.x, b.y, c.x, c.y }; + const auto cached = context->corner_options.find(key); + std::vector