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.
This commit is contained in:
2026-11-09 13:44:17 +07:00
commit 24822f5408
27 changed files with 7636 additions and 0 deletions

81
CMakeLists.txt Normal file
View File

@@ -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
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
# 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()

View File

@@ -0,0 +1,35 @@
#ifndef LANE_ROUTE_CORE_CLOTHOID_H_
#define LANE_ROUTE_CORE_CLOTHOID_H_
#include <vector>
#include <lane_route_core/types.h>
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_

View File

@@ -0,0 +1,126 @@
#ifndef LANE_ROUTE_CORE_COSTMAP_BACKEND_H_
#define LANE_ROUTE_CORE_COSTMAP_BACKEND_H_
#include <utility>
#include <vector>
#include <robot_costmap_2d/reference_graph.h>
#include <lane_route_core/types.h>
namespace lane_route_core
{
inline robot_costmap_2d::DirectionGeometry geometryOf(const GridRef& grid)
{
robot_costmap_2d::DirectionGeometry geometry{};
geometry.width = static_cast<uint32_t>(grid.width);
geometry.height = static_cast<uint32_t>(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<robot_geometry_msgs::Point> rectangleFootprint(double half_x, double half_y)
{
std::vector<robot_geometry_msgs::Point> 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<std::size_t>(i)].x = xs[i];
footprint[static_cast<std::size_t>(i)].y = ys[i];
}
return footprint;
}
inline CoarseGraph toCoarseGraph(const robot_costmap_2d::ReferenceGraph& graph, const std::atomic<bool>* 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<int32_t>(edge.from);
out.to = static_cast<int32_t>(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<bool>* 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<bool>* cancel) { return buildCoarseGraph(window, config, params, cancel); };
backend.region_centre_edges = [params](const std::vector<uint8_t>& mask, const GridRef& grid, std::vector<Point2>* nodes,
std::vector<CoarseEdge>* edges, const std::atomic<bool>* cancel) {
if (cancel && cancel->load(std::memory_order_relaxed)) return;
const robot_costmap_2d::DirectionGeometry geometry = geometryOf(grid);
const std::vector<uint8_t> 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_

View File

@@ -0,0 +1,68 @@
#ifndef LANE_ROUTE_CORE_GRAPH_COMPILER_H_
#define LANE_ROUTE_CORE_GRAPH_COMPILER_H_
#include <cstdint>
#include <vector>
#include <lane_route_core/types.h>
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<Point2> 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<Point2> nodes;
std::vector<GraphEdge> edges;
std::vector<std::vector<int32_t>> 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<int32_t> sample_offsets; ///< edges.size() + 1 entries.
std::vector<int32_t> sample_cells; ///< Grid cell, -1 off the grid.
std::vector<double> 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<bool>* 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<Point2>& 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<double>* factors);
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_GRAPH_COMPILER_H_

View File

@@ -0,0 +1,89 @@
#ifndef LANE_ROUTE_CORE_GRID_CHECKS_H_
#define LANE_ROUTE_CORE_GRID_CHECKS_H_
#include <chrono>
#include <cmath>
#include <cstdint>
#include <utility>
#include <vector>
#include <lane_route_core/types.h>
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<int>(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<Point2>& 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<bool>* 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<bool>* 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<bool>* 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<bool>* 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<bool>* 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<double>& 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<std::pair<double, int32_t>> nearestNodes(const std::vector<Point2>& nodes, int32_t count, const Point2& point,
int32_t k, double upper_bound);
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_GRID_CHECKS_H_

View File

@@ -0,0 +1,38 @@
#ifndef LANE_ROUTE_CORE_PATH_VERIFIER_H_
#define LANE_ROUTE_CORE_PATH_VERIFIER_H_
#include <chrono>
#include <vector>
#include <lane_route_core/types.h>
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<bool>* 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<bool>* cancel, const std::chrono::steady_clock::time_point* deadline);
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_PATH_VERIFIER_H_

View File

@@ -0,0 +1,114 @@
#ifndef LANE_ROUTE_CORE_ROUTE_PLANNER_H_
#define LANE_ROUTE_CORE_ROUTE_PLANNER_H_
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <lane_route_core/graph_compiler.h>
#include <lane_route_core/path_verifier.h>
#include <lane_route_core/types.h>
namespace lane_route_core
{
/** @brief One planning request. */
struct RouteRequest
{
Pose2 start;
Pose2 goal;
std::vector<WorldBox> changed_boxes; ///< Where the live grid differs from the compiled one. See changedBoxes().
const std::atomic<bool>* 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<std::string> 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<double> 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<std::string> graph_rung_reasons; ///< Graph reasons, in attempted-rung order.
std::vector<std::string> 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<std::shared_ptr<const CompiledGraph>(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<WorldBox> changedBoxes(const uint8_t* compiled_cost, const GridRef& live,
const std::atomic<bool>* cancel = nullptr,
std::vector<uint8_t>* scratch = nullptr, std::vector<int32_t>* 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<uint16_t>* clearance_mm, const std::atomic<bool>* cancel = nullptr);
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_ROUTE_PLANNER_H_

View File

@@ -0,0 +1,84 @@
#ifndef LANE_ROUTE_CORE_SWING_CHAIN_H_
#define LANE_ROUTE_CORE_SWING_CHAIN_H_
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <utility>
#include <vector>
#include <lane_route_core/types.h>
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<Point2> vertices;
std::vector<uint8_t> locked; ///< Lane points. They stay in every chain.
std::vector<std::pair<std::size_t, std::size_t>> boundaries; ///< (vertex index, route edge index) where edges join.
};
/** @brief What one shortcut needs from the grid. */
struct SwingSearch
{
std::function<bool(const Point2&, const Point2&, int)> line_ok; ///< Legal at this clearance [mm].
std::function<double(const Point2&, const Point2&)> 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<bool>* 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<std::size_t> oppositePairs(const std::vector<Point2>& chain);
/** @brief Sum of absolute turn angles along a vertex chain [rad]. */
double chainTurning(const std::vector<Point2>& 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<Point2>& raw, const std::vector<uint8_t>& 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<std::size_t>* 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<Point2>& greedy, const SwingSearch& search, SwingStats* stats,
std::vector<Point2>* vertices, std::vector<std::size_t>* indices);
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_SWING_CHAIN_H_

View File

@@ -0,0 +1,154 @@
#ifndef LANE_ROUTE_CORE_TYPES_H_
#define LANE_ROUTE_CORE_TYPES_H_
#include <atomic>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
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<PathPoint>;
/** @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<Point2> 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<Point2> nodes;
std::vector<CoarseEdge> edges;
std::vector<CoarseLane> 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<CoarseGraph(const GridRef& window, const std::atomic<bool>* cancel)> build_coarse;
/** Nodes and edges of the centre line of `mask`, split at direction changes. Used for the preferred region. */
std::function<void(const std::vector<uint8_t>& mask, const GridRef& grid, std::vector<Point2>* nodes,
std::vector<CoarseEdge>* edges, const std::atomic<bool>* 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<double> 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<double> 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<double> 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_

15
package.xml Normal file
View File

@@ -0,0 +1,15 @@
<package>
<name>lane_route_core</name>
<version>0.1.0</version>
<description>
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.
</description>
<maintainer email="duongtd160902@gmail.com">duongtd</maintainer>
<license>BSD</license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>robot_costmap_2d</build_depend>
<run_depend>robot_costmap_2d</run_depend>
</package>

147
src/clothoid.cpp Normal file
View File

@@ -0,0 +1,147 @@
#include <lane_route_core/clothoid.h>
#include <algorithm>
#include <cmath>
#include <complex>
#include <cstddef>
#include <stdexcept>
#include <lane_route_core/grid_checks.h>
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<double>;
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<int>(std::ceil(length / spacing)) + 1;
std::vector<double> raw;
raw.reserve(static_cast<std::size_t>(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<double> 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

314
src/graph_compiler.cpp Normal file
View File

@@ -0,0 +1,314 @@
#include <lane_route_core/graph_compiler.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <utility>
#include <lane_route_core/grid_checks.h>
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<Point2>& 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 <typename Visit>
void forEachSample(const std::vector<Point2>& 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<int>(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<int32_t>(fy) * grid.width + static_cast<int32_t>(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<double>::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<Point2>& 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<double>* 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<std::size_t>(k)], graph.sample_weights[static_cast<std::size_t>(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<bool>* 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<Point2>& 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<int32_t>(graph.nodes.size());
const auto add_both_ways = [&](int32_t from, int32_t to, const std::vector<Point2>& points, EdgeKind kind) {
const double length = polylineLength(points);
if (poly_ok(points))
graph.edges.push_back({ from, to, points, kind, length });
std::vector<Point2> 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<int32_t> lane_ends;
const auto add_node = [&](const Point2& point) {
graph.nodes.push_back(point);
return static_cast<int32_t>(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<Point2> 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<std::pair<int32_t, Point2>> 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<Point2> 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<Point2> 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<int32_t> junction_ids(static_cast<std::size_t>(voronoi_nodes));
for (int32_t i = 0; i < voronoi_nodes; ++i)
junction_ids[static_cast<std::size_t>(i)] = i;
junction_ids.insert(junction_ids.end(), lane_ends.begin(), lane_ends.end());
std::vector<Point2> junction_points;
junction_points.reserve(junction_ids.size());
for (int32_t id : junction_ids)
junction_points.push_back(graph.nodes[static_cast<std::size_t>(id)]);
const int32_t junction_count = static_cast<int32_t>(junction_points.size());
for (int32_t u : lane_ends)
{
if (cancelled()) return {};
const Point2 here = graph.nodes[static_cast<std::size_t>(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<std::size_t>(found.second)];
if (v == u || found.first < kMinLinkM)
continue;
const Point2 there = graph.nodes[static_cast<std::size_t>(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<std::size_t>(grid.width) * static_cast<std::size_t>(grid.height);
if (master != nullptr && backend.region_centre_edges && std::find(master, master + cell_count, kPreferredSpace) != master + cell_count)
{
std::vector<uint8_t> 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<Point2> preferred_nodes;
std::vector<CoarseEdge> 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<int32_t>(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<int32_t>(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<std::size_t>(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<int>::max();
for (const Point2& point : edge.points)
{
const int32_t ix = std::min(grid.width - 1, std::max<int32_t>(0, static_cast<int32_t>(std::floor((point.x - grid.origin_x) / grid.resolution))));
const int32_t iy = std::min(grid.height - 1, std::max<int32_t>(0, static_cast<int32_t>(std::floor((point.y - grid.origin_y) / grid.resolution))));
minimum_mm = std::min<int>(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<std::size_t>(graph.edges[i].from)].push_back(static_cast<int32_t>(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<int32_t>(graph.sample_cells.size()));
}
return graph;
}
} // namespace lane_route_core

635
src/grid_checks.cpp Normal file
View File

@@ -0,0 +1,635 @@
#include <lane_route_core/grid_checks.h>
#include <algorithm>
#include <cstddef>
#include <limits>
#include <queue>
#include <sstream>
#include <unordered_map>
#include <utility>
namespace lane_route_core
{
namespace
{
constexpr double kInfinity = std::numeric_limits<double>::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<int32_t>(fy) * grid.width + static_cast<int32_t>(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<int32_t>::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<int>(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<Point2>& 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, &centre) || grid.cost[centre] >= kInscribedCost)
return true;
const double projected = half_cell * (abs_c + abs_s);
for (int32_t iy = static_cast<int32_t>(low_y); iy <= static_cast<int32_t>(high_y); ++iy)
{
const uint8_t* row = grid.cost + static_cast<std::ptrdiff_t>(iy) * grid.width;
for (int32_t ix = static_cast<int32_t>(low_x); ix <= static_cast<int32_t>(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<int>(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<bool>* 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<int>(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<double>(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<int>(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<bool>* 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<uint8_t> visited(static_cast<std::size_t>(grid.width) * static_cast<std::size_t>(grid.height), 0);
std::vector<int32_t> stack(1, from);
visited[static_cast<std::size_t>(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<std::size_t>(other)] != 0 || grid.cost[other] >= kInscribedCost)
continue;
if (other == to)
return false;
visited[static_cast<std::size_t>(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<bool>* 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<double>(goal_x - x), static_cast<double>(goal_y - y)) * resolution;
};
struct Move
{
int dy, dx;
double cost;
bool allowed[9];
};
std::vector<Move> 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<double>(dx), static_cast<double>(dy)) * resolution;
move.allowed[0] = true;
const double angle = std::atan2(static_cast<double>(dy), static_cast<double>(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<double, std::pair<double, int32_t>>; // f, then g and cell
std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> queue;
std::unordered_map<int32_t, double> 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<int>(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<double>& gaps, double minimum_m, const std::atomic<bool>* 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<uint8_t> 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<double>& 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<bool>* 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<bool>* cancel, const std::chrono::steady_clock::time_point* deadline,
bool count_unknown)
{
std::vector<PathPoint> 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<int>(std::ceil(distance / 0.04)), static_cast<int>(std::ceil(std::abs(angle) / 0.03)) });
for (int j = 1; j <= samples; ++j)
{
const double t = static_cast<double>(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<double> 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<int32_t>(std::floor((pose.x - radius - grid.origin_x) / resolution)));
const int32_t x1 = std::min(grid.width - 1, static_cast<int32_t>(std::ceil((pose.x + radius - grid.origin_x) / resolution)));
const int32_t y0 = std::max(0, static_cast<int32_t>(std::floor((pose.y - radius - grid.origin_y) / resolution)));
const int32_t y1 = std::min(grid.height - 1, static_cast<int32_t>(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<std::ptrdiff_t>(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<std::pair<double, int32_t>> nearestNodes(const std::vector<Point2>& nodes, int32_t count, const Point2& point,
int32_t k, double upper_bound)
{
std::vector<std::pair<double, int32_t>> found;
for (int32_t i = 0; i < count; ++i)
{
const double distance = distanceOf(point, nodes[static_cast<std::size_t>(i)]);
if (distance < upper_bound)
found.emplace_back(distance, i);
}
std::sort(found.begin(), found.end());
if (found.size() > static_cast<std::size_t>(k))
found.resize(static_cast<std::size_t>(k));
return found;
}
} // namespace lane_route_core

263
src/lattice_cspace.cpp Normal file
View File

@@ -0,0 +1,263 @@
#include "lattice_internal.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include <lane_route_core/grid_checks.h>
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<double>(x), static_cast<double>(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<std::size_t>(g.width);
const std::size_t height = static_cast<std::size_t>(g.height);
if (width == 0 || height == 0 || height > std::numeric_limits<uint32_t>::max() / width ||
height + 1 > std::numeric_limits<std::size_t>::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<std::size_t>(context_.grid.width) + 1;
const auto at = [&](int32_t x, int32_t y) { return blocked_prefix_[static_cast<std::size_t>(y) * stride + static_cast<std::size_t>(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<int32_t>(fx), iy = static_cast<int32_t>(fy);
const std::size_t cell = static_cast<std::size_t>(iy) * static_cast<std::size_t>(g.width) + static_cast<std::size_t>(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<int32_t>(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<uint64_t>(static_cast<uint32_t>(iy / kTile)) << 32) | static_cast<uint32_t>(ix / kTile);
const int bins = c.lattice_heading_bins;
auto inserted = tiles_.try_emplace(tile, &context_.memory, static_cast<std::size_t>(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<int>(std::floor(positive_yaw * bins / (2.0 * kPi) + 0.5)) % bins;
const std::size_t local = (static_cast<std::size_t>(iy % kTile) * kTile + static_cast<std::size_t>(ix % kTile)) * bins + heading;
uint8_t& packed = inserted.first->second.samples[local / 4];
const unsigned shift = static_cast<unsigned>((local % 4) * 2);
uint8_t cached = static_cast<uint8_t>((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<uint8_t>(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<int32_t>(0, static_cast<int32_t>(std::floor(std::min(x0, x1) - padding - 1e-10)));
const int32_t xhi = std::min<int32_t>(g.width - 1, static_cast<int32_t>(std::floor(std::max(x0, x1) + padding + 1e-10)));
const int32_t ylo = std::max<int32_t>(0, static_cast<int32_t>(std::floor(std::min(y0, y1) - padding - 1e-10)));
const int32_t yhi = std::min<int32_t>(g.height - 1, static_cast<int32_t>(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<std::size_t>(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<int>(std::ceil(distance / 0.025)), static_cast<int>(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<double>(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

194
src/lattice_heuristic.cpp Normal file
View File

@@ -0,0 +1,194 @@
#include "lattice_internal.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <queue>
#include <vector>
#include <lane_route_core/grid_checks.h>
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<double>::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<std::size_t>(fy) / static_cast<std::size_t>(factor)) *
static_cast<std::size_t>(field_width) + static_cast<std::size_t>(fx) / static_cast<std::size_t>(factor);
if (settled[cell] != 0) return static_cast<double>(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<int64_t>(g.width) + factor - 1) / factor) *
((static_cast<int64_t>(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<int32_t>((static_cast<int64_t>(g.width) + factor - 1) / factor);
field->height = static_cast<int32_t>((static_cast<int64_t>(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<int64_t>(y) / factor) * width + static_cast<int64_t>(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<int64_t>(width) * height;
if (cells64 > std::numeric_limits<int32_t>::max()) return true;
const std::size_t cells = static_cast<std::size_t>(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<uint16_t>(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<uint8_t> passable(&context.memory), direction(&context.memory);
std::pmr::vector<uint16_t> 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<int64_t>(by) * factor;
const int64_t y1 = std::min<int64_t>(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<int64_t>(bx) * factor;
const int64_t x1 = std::min<int64_t>(g.width, x0 + factor);
const std::size_t block = static_cast<std::size_t>(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<std::size_t>(y) * g.width + static_cast<std::size_t>(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<std::size_t>((y0 + y1) / 2) * g.width + static_cast<std::size_t>((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<std::size_t>(cell)) : passable[static_cast<std::size_t>(cell)] != 0;
};
const auto zone = [&](int32_t cell) -> uint8_t {
return factor == 1 ? (g.direction == nullptr ? 0 : g.direction[cell]) : direction[static_cast<std::size_t>(cell)];
};
const auto clear = [&](int32_t cell) -> uint16_t { return factor == 1 ? g.clearance_mm[cell] : clearance[static_cast<std::size_t>(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<float>::infinity());
field->settled.push_back(0);
}
using QueueStorage = std::pmr::vector<FieldEntry>;
std::priority_queue<FieldEntry, QueueStorage, std::greater<FieldEntry>> queue{ std::greater<FieldEntry>(), QueueStorage(&context.memory) };
field->values[static_cast<std::size_t>(goal)] = 0.0f;
queue.push({ 0.0f, static_cast<int32_t>(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<std::size_t>(top.cell)]) continue;
if (field->settled[static_cast<std::size_t>(top.cell)] != 0) continue;
field->settled[static_cast<std::size_t>(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<float>(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<std::size_t>(next)])
{
field->values[static_cast<std::size_t>(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<std::size_t>(start)] == 0;
return true;
}
} // namespace detail
} // namespace lane_route_core

154
src/lattice_internal.h Normal file
View File

@@ -0,0 +1,154 @@
#ifndef LANE_ROUTE_CORE_LATTICE_INTERNAL_H_
#define LANE_ROUTE_CORE_LATTICE_INTERNAL_H_
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <memory_resource>
#include <new>
#include <unordered_map>
#include <vector>
#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<long double>(f) / width_m) : static_cast<long double>(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<uint8_t> samples;
};
LatticeContext& context_;
std::pmr::unordered_map<uint64_t, Tile> tiles_;
std::pmr::vector<uint32_t> 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<float> values;
std::pmr::vector<uint8_t> 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_

515
src/lattice_search.cpp Normal file
View File

@@ -0,0 +1,515 @@
#include "lattice_internal.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <limits>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <lane_route_core/grid_checks.h>
namespace lane_route_core
{
namespace detail
{
namespace
{
struct Motion
{
double curvature;
double length;
};
struct DubinsWord
{
std::array<Motion, 3> 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<DubinsWord, 6>* 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<int32_t>{}(k.x);
for (int32_t v : { k.y, k.heading })
h ^= std::hash<int32_t>{}(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<double>(std::numeric_limits<int>::max()))
{
context.info.lattice_reason = "lattice_resource_limit";
return false;
}
const int steps = std::max(1, static_cast<int>(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<int>(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<int64_t>(std::floor(v / kBucketM)); };
const auto keyOf = [](int64_t x, int64_t y) {
return (static_cast<uint64_t>(static_cast<uint32_t>(x)) << 32) | static_cast<uint32_t>(y);
};
std::unordered_map<uint64_t, std::vector<std::size_t>> buckets;
std::vector<std::size_t> 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<std::size_t>(grid.width) * static_cast<std::size_t>(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<int32_t>::max() ||
grid.height * grid.resolution / bin_resolution > std::numeric_limits<int32_t>::max())
{
context.info.lattice_reason = "lattice_resource_limit";
return false;
}
using NodeVector = std::pmr::vector<Node>;
using OpenVector = std::pmr::vector<LatticeOpenEntry>;
NodeVector nodes(&context.memory);
std::priority_queue<LatticeOpenEntry, OpenVector, LatticeOpenOrder> open{ LatticeOpenOrder{}, OpenVector(&context.memory) };
std::pmr::unordered_map<LatticeStateKey, std::size_t, KeyHash> best(&context.memory);
std::pmr::unordered_set<LatticeStateKey, KeyHash> analytic_attempted(&context.memory);
uint64_t serial = 0;
const auto keyOf = [&](const PathPoint& p, int heading) -> LatticeStateKey {
return { static_cast<int32_t>(std::floor((p.x-grid.origin_x)/bin_resolution)),
static_cast<int32_t>(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<int64_t>(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<int>(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<uint64_t>(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<AnalyticCandidate> candidates(&context.memory);
candidates.reserve(2 + 6 * static_cast<std::size_t>(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<double, 363> 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<DubinsWord, 6> 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<std::size_t> chain(&context.memory);
for (int64_t id = static_cast<int64_t>(entry.node); id >= 0; id = nodes[static_cast<std::size_t>(id)].parent)
{
if (context.expired()) return false;
chain.push_back(static_cast<std::size_t>(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<int32_t>(std::floor((current.pose.x-grid.origin_x)/grid.resolution));
const int32_t y = static_cast<int32_t>(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<std::size_t>(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<int32_t>(std::floor((next.x-grid.origin_x)/grid.resolution));
const int32_t y = static_cast<int32_t>(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<std::size_t>(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<int64_t>(entry.node), curvature, length, heading, last });
}
}
context.info.lattice_reason = "lattice_exhausted";
return false;
}
} // namespace detail
} // namespace lane_route_core

79
src/lattice_tier.cpp Normal file
View File

@@ -0,0 +1,79 @@
#include "lattice_internal.h"
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <new>
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<std::size_t>(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<Clock::duration>(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<uint64_t>(output.info.lattice_peak_bytes, static_cast<uint64_t>(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

250
src/path_verifier.cpp Normal file
View File

@@ -0,0 +1,250 @@
#include <lane_route_core/path_verifier.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <lane_route_core/grid_checks.h>
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<double>(ix), static_cast<double>(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<int32_t>(0, static_cast<int32_t>(std::floor(std::min(y0, y1) - 1e-10)));
const int32_t last_y = std::min<int32_t>(grid.height - 1, static_cast<int32_t>(std::floor(std::max(y0, y1) + 1e-10)));
const int32_t first_x = std::max<int32_t>(0, static_cast<int32_t>(std::floor(std::min(x0, x1) - 1e-10)));
const int32_t last_x = std::min<int32_t>(grid.width - 1, static_cast<int32_t>(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<bool>* cancel, const std::chrono::steady_clock::time_point* deadline)
{
std::vector<double> 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<std::size_t> 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<bool>* cancel,
const std::chrono::steady_clock::time_point* deadline)
{
constexpr double kStep = 0.1;
constexpr std::size_t kIgnore = 3;
std::vector<Point2> distinct;
std::vector<double> 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<Point2> 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<bool>* 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<bool>* 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<int>(std::ceil(distance / 0.01)), static_cast<int>(std::ceil(std::abs(turn) / 0.03)) });
for (int j = 0; j <= samples; ++j)
{
const double t = static_cast<double>(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

711
src/route_graph_path.cpp Normal file
View File

@@ -0,0 +1,711 @@
#include "route_planner_internal.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/swing_chain.h>
namespace lane_route_core
{
namespace detail
{
namespace
{
struct Simplified
{
std::vector<Point2> vertices;
/** Per vertex: the graph transitions it stands for, so a dead corner can ban exactly those. */
std::vector<std::vector<std::pair<int32_t, int32_t>>> provenance;
};
/** Route points in travel order, before any shortcut. */
RawChain routeRawChain(const QueryGraph& query, const std::vector<int32_t>& 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<std::vector<std::pair<int32_t, int32_t>>> chainProvenance(const std::vector<std::size_t>& indices,
const std::vector<std::pair<std::size_t, std::size_t>>& boundaries,
const std::vector<int32_t>& route)
{
std::vector<std::vector<std::pair<int32_t, int32_t>>> provenance(indices.size());
for (std::size_t j = 1; j + 1 < indices.size(); ++j)
{
std::size_t nearest = std::numeric_limits<std::size_t>::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<int32_t>& route, const QueryContext& context, const uint8_t* master,
double shortcut_minimum_m, Simplified* result)
{
const RawChain raw = routeRawChain(query, route);
const std::vector<Point2>& vertices = raw.vertices;
const std::vector<uint8_t>& locked = raw.locked;
if (vertices.size() < 2)
return false;
std::vector<double> 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<Point2> out(1, vertices[0]);
std::vector<std::size_t> 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<std::ptrdiff_t>(k));
indices.erase(indices.begin() + static_cast<std::ptrdiff_t>(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<int32_t> 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<int32_t>(fy) * grid.width + static_cast<int32_t>(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<int>(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<double>(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<int>(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<Point2>& vertices, const Pose2& start, const Pose2& goal, QueryContext* context, Path* path,
BuildFailure* failure, std::vector<double>* radii)
{
using Option = QueryContext::CornerOption;
const std::size_t corner_count = vertices.size() - 2;
std::vector<std::vector<Option>> 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<double, 6> key{ a.x, a.y, b.x, b.y, c.x, c.y };
const auto cached = context->corner_options.find(key);
std::vector<Option> options;
if (cached != context->corner_options.end())
{
options = cached->second;
}
else
{
bool complete = true;
const double room = 0.999 * std::min(distanceOf(a, b), distanceOf(b, c));
for (double radius : context->config.corner_radii_m)
{
if (context->expired())
{
complete = false;
break;
}
for (double sharpness : kSharpness)
{
double trim = 0.0;
Path curve = placedCorner(a, b, c, radius, sharpness, context->config.output_step_m, &trim);
if (curve.empty() || trim >= room || !curveLegal(curve, *context))
continue;
options.push_back(Option{ trim, std::make_shared<const Path>(std::move(curve)), radius });
}
}
if (complete)
context->corner_options[key] = options;
}
if (options.empty())
{
failure->reason = "corner_no_legal_clothoid";
failure->has_corner = true;
failure->vertex = static_cast<int>(i);
failure->corner = b;
return false;
}
corners[i - 1] = std::move(options);
}
// Adjacent trims must fit their shared line. Work back to find which options can still finish,
// then take the most preferred option on the way forward.
std::vector<std::vector<Option>> usable(corner_count);
for (std::size_t n = corner_count; n-- > 0;)
{
if (n + 1 == corner_count)
{
usable[n] = corners[n];
continue;
}
if (usable[n + 1].empty())
continue;
const double room = distanceOf(vertices[n + 1], vertices[n + 2]) - 1e-7;
double shortest = kInfinity;
for (const Option& option : usable[n + 1])
shortest = std::min(shortest, option.trim);
for (const Option& option : corners[n])
if (option.trim + shortest <= room)
usable[n].push_back(option);
}
std::vector<Option> selected;
for (std::size_t n = 0; n < corner_count; ++n)
{
const double room = n > 0 ? distanceOf(vertices[n], vertices[n + 1]) - 1e-7 : kInfinity;
const Option* chosen = nullptr;
for (const Option& option : usable[n])
{
if (n == 0 || selected.back().trim + option.trim <= room)
{
chosen = &option;
break;
}
}
if (chosen == nullptr)
{
failure->reason = "corner_trims_overlap";
failure->has_corner = true;
failure->vertex = static_cast<int>(n) + 1;
failure->corner = vertices[n + 1];
return false;
}
selected.push_back(*chosen);
}
const double step = context->config.output_step_m;
const double first = headingOf(vertices[0], vertices[1]);
path->clear();
radii->clear();
path->push_back({ start.x, start.y, start.has_yaw ? start.yaw : first, 0.0 });
appendSpin(path, first);
for (std::size_t n = 0; n < selected.size(); ++n)
{
if (selected[n].curve == nullptr)
continue;
const Path& curve = *selected[n].curve;
appendLine(path, Point2{ path->back().x, path->back().y }, Point2{ curve[0].x, curve[0].y }, headingOf(vertices[n], vertices[n + 1]), step);
path->insert(path->end(), curve.begin() + 1, curve.end());
radii->push_back(selected[n].radius);
}
appendLine(path, Point2{ path->back().x, path->back().y }, vertices.back(), headingOf(vertices[vertices.size() - 2], vertices.back()), step);
if (goal.has_yaw)
appendSpin(path, goal.yaw);
return true;
}
/** Intersect the tangent lines around a short section, shortening only leads outside zones. */
bool repairCorner(const std::vector<Point2>& vertices, int index, const QueryContext& context, std::vector<Point2>* result)
{
if (index < 1 || static_cast<std::size_t>(index) + 2 >= vertices.size())
return false;
const Point2& a = vertices[static_cast<std::size_t>(index) - 1];
const Point2& b = vertices[static_cast<std::size_t>(index)];
const Point2& c = vertices[static_cast<std::size_t>(index) + 1];
const Point2& d = vertices[static_cast<std::size_t>(index) + 2];
const double ux = b.x - a.x, uy = b.y - a.y;
const double vx = d.x - c.x, vy = d.y - c.y;
const double denominator = ux * vy - uy * vx;
if (std::abs(denominator) < 1e-9)
return false;
const double t = ((c.x - a.x) * vy - (c.y - a.y) * vx) / denominator;
// The crossing may lie past b: a lane exit can stop short of the next line. lineLegal below still decides.
if (t <= 0.0)
return false;
const Point2 cross{ a.x + t * ux, a.y + t * uy };
if (((cross.x - c.x) * vx + (cross.y - c.y) * vy) / (vx * vx + vy * vy) >= 1.0)
return false;
if (!outsideZones(cross, b, context.grid) || !outsideZones(b, c, context.grid))
return false;
if (!context.lineLegal(a, cross) || !context.lineLegal(cross, d))
return false;
result->assign(vertices.begin(), vertices.begin() + index);
result->push_back(cross);
result->insert(result->end(), vertices.begin() + index + 2, vertices.end());
return true;
}
double verticesLength(const std::vector<Point2>& vertices)
{
double total = 0.0;
for (std::size_t i = 0; i + 1 < vertices.size(); ++i)
total += distanceOf(vertices[i], vertices[i + 1]);
return total;
}
using PointSet = std::set<std::pair<double, double>>;
/** Remove the vertices of a swing when no crossing of the outer lines exists, as with nearly parallel outer lines.
* Must turn less overall: a removal next to a lane exit can shorten the chain and still add a dip below the lane. */
bool skipSwingVertices(const std::vector<Point2>& merged, std::size_t j, const QueryContext& context, const PointSet& protected_points,
int minimum_mm, std::vector<Point2>* result)
{
const Point2 a = merged[j - 1], b = merged[j], c = merged[j + 1], d = merged[j + 2];
if (!outsideZones(a, b, context.grid) || !outsideZones(b, c, context.grid) || !outsideZones(c, d, context.grid))
return false;
const bool b_free = protected_points.count({ b.x, b.y }) == 0;
const bool c_free = protected_points.count({ c.x, c.y }) == 0;
const struct
{
bool allowed;
std::vector<Point2> kept;
} options[3] = { { b_free && c_free, { a, d } }, { b_free, { a, c, d } }, { c_free, { a, b, d } } };
const double length = verticesLength(merged);
const double turning = chainTurning(merged);
for (const auto& option : options)
{
if (!option.allowed)
continue;
bool legal = true;
for (std::size_t k = 0; legal && k + 1 < option.kept.size(); ++k)
legal = outsideZones(option.kept[k], option.kept[k + 1], context.grid) &&
lineOk(context.grid, option.kept[k], option.kept[k + 1], context.deviation_deg, minimum_mm);
if (!legal)
continue;
std::vector<Point2> trial(merged.begin(), merged.begin() + static_cast<std::ptrdiff_t>(j) - 1);
trial.insert(trial.end(), option.kept.begin(), option.kept.end());
trial.insert(trial.end(), merged.begin() + static_cast<std::ptrdiff_t>(j) + 3, merged.end());
if (verticesLength(trial) <= length + 1e-6 && chainTurning(trial) < turning - 1e-12)
{
*result = std::move(trial);
return true;
}
}
return false;
}
/** Replace neighbouring corners that turn opposite ways by one corner at the crossing of the outer lines.
* Such a pair swings past the new direction and comes back, and a smaller radius alone makes the swing bigger,
* because the arc then runs closer to the far vertex. The path may not get longer. */
std::vector<Point2> mergeSwings(const std::vector<Point2>& vertices, const QueryContext& context, const PointSet& protected_points,
double shortcut_minimum_m)
{
std::vector<Point2> merged = vertices;
const auto turn = [](const std::vector<Point2>& v, std::size_t i) {
return wrapAngle(headingOf(v[i], v[i + 1]) - headingOf(v[i - 1], v[i]));
};
int tiers[2];
shortcutTiers(context, shortcut_minimum_m, tiers);
bool changed = true;
while (changed)
{
changed = false;
for (std::size_t j = 1; j + 2 < merged.size(); ++j)
{
if (turn(merged, j) * turn(merged, j + 1) >= 0.0)
continue;
std::vector<Point2> candidate;
const bool crossing = repairCorner(merged, static_cast<int>(j), context, &candidate) &&
verticesLength(candidate) <= verticesLength(merged) + 1e-6;
if (!crossing && !skipSwingVertices(merged, j, context, protected_points, tiers[1], &candidate))
continue;
merged = std::move(candidate);
changed = true;
break;
}
}
return merged;
}
/** Geometry of a route from the greedy shortcut. The chain before any merge is left in greedy. */
Candidate constructGreedyCandidate(const std::vector<int32_t>& route, const QueryGraph& query, QueryContext* context, const uint8_t* master,
const Pose2& start, const Pose2& goal, double shortcut_minimum_m, const PointSet& protected_points,
std::vector<Point2>* greedy)
{
Candidate result;
Simplified simplified;
if (!simplifyRoute(query, route, *context, master, shortcut_minimum_m, &simplified))
{
result.why.reason = "empty_geometry";
return result;
}
result.vertices = std::move(simplified.vertices);
result.provenance = std::move(simplified.provenance);
*greedy = result.vertices;
const std::vector<Point2> merged = mergeSwings(result.vertices, *context, protected_points, shortcut_minimum_m);
if (merged.size() < result.vertices.size())
{
Path path;
BuildFailure failure;
std::vector<double> radii;
if (buildPath(merged, start, goal, context, &path, &failure, &radii) &&
verifyPath(path, context->verify_grid, context->deviation_deg, context->config, context->cancel).valid &&
freeClearanceOk(path, context->verify_grid, context->min_mm))
{
result.ok = true;
result.path = std::move(path);
result.radii = std::move(radii);
result.vertices = merged;
return result;
}
}
result.ok = buildPath(result.vertices, start, goal, context, &result.path, &result.why, &result.radii);
if (!result.ok && result.why.reason == "corner_trims_overlap")
{
std::vector<Point2> repaired = result.vertices;
for (int round = 0; round < 6; ++round)
{
std::vector<std::size_t> order;
for (std::size_t j = 1; j + 2 < repaired.size(); ++j)
order.push_back(j);
std::stable_sort(order.begin(), order.end(), [&](std::size_t x, std::size_t y) {
return distanceOf(repaired[x], repaired[x + 1]) < distanceOf(repaired[y], repaired[y + 1]);
});
bool moved = false;
for (std::size_t j : order)
{
std::vector<Point2> candidate;
if (repairCorner(repaired, static_cast<int>(j), *context, &candidate))
{
repaired = std::move(candidate);
moved = true;
break;
}
}
if (!moved)
break;
result.why = BuildFailure();
result.ok = buildPath(repaired, start, goal, context, &result.path, &result.why, &result.radii);
if (result.ok || result.why.reason != "corner_trims_overlap")
break;
}
if (result.ok)
result.vertices = repaired;
}
if (!result.ok && result.why.has_corner)
{
std::vector<Point2> adjusted;
if (repairCorner(result.vertices, result.why.vertex, *context, &adjusted))
{
BuildFailure failure;
result.ok = buildPath(adjusted, start, goal, context, &result.path, &failure, &result.radii);
result.why = failure;
}
}
return result;
}
} // namespace
double pathLength(const Path& path)
{
double total = 0.0;
for (std::size_t i = 0; i + 1 < path.size(); ++i)
total += std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y);
return total;
}
namespace
{
/** Every check the planner applies to a returned path. */
bool candidateLegal(const Path& path, const QueryContext& context, const Pose2& start, const Pose2& goal)
{
const GridRef& grid = context.verify_grid;
const PlannerConfig& config = context.config;
if (!verifyPath(path, grid, context.deviation_deg, config, context.cancel).valid || !endpointOk(path, start, goal) ||
!freeClearanceOk(path, grid, context.min_mm) || blockedEndpointTurn(path, grid, config.half_x_m, config.half_y_m) != nullptr ||
!checkFootprintGap(path, grid, config.footprint_min_gap_m, config.half_x_m, config.half_y_m, context.cancel).valid)
return false;
const Point2 start_point{ start.x, start.y };
const Point2 goal_point{ goal.x, goal.y };
const double length = pathLength(path);
if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m)
{
const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio;
double reference = 0.0;
if (shortestDirectedReference(grid, start_point, goal_point, context.deviation_deg, bound, &reference, context.cancel) &&
length > config.route_too_long_ratio * reference + config.route_too_long_margin_m)
return false;
}
return true;
}
/** Build a chain from the swing search, with the same corner repairs as the greedy chain. */
Candidate buildSwingChain(const std::vector<Point2>& chosen, QueryContext* context, const Pose2& start, const Pose2& goal,
const PointSet& protected_points, double shortcut_minimum_m)
{
Candidate result;
const auto attempt = [&](const std::vector<Point2>& chain) {
result.why = BuildFailure();
result.vertices = chain;
++context->info->swing_builds;
result.ok = buildPath(chain, start, goal, context, &result.path, &result.why, &result.radii);
};
const std::vector<Point2> merged = mergeSwings(chosen, *context, protected_points, shortcut_minimum_m);
attempt(merged);
if (!result.ok && merged.size() != chosen.size() && !context->expired())
attempt(chosen);
if (!result.ok && result.why.reason == "corner_trims_overlap")
{
std::vector<Point2> working = result.vertices;
for (int round = 0; round < 6; ++round)
{
std::vector<std::size_t> order;
for (std::size_t j = 1; j + 2 < working.size(); ++j)
order.push_back(j);
std::stable_sort(order.begin(), order.end(), [&](std::size_t x, std::size_t y) {
return distanceOf(working[x], working[x + 1]) < distanceOf(working[y], working[y + 1]);
});
bool moved = false;
for (std::size_t j : order)
{
std::vector<Point2> replacement;
if (repairCorner(working, static_cast<int>(j), *context, &replacement))
{
working = std::move(replacement);
moved = true;
break;
}
}
if (!moved || context->expired())
break;
attempt(working);
if (result.ok || result.why.reason != "corner_trims_overlap")
break;
}
}
if (!result.ok && result.why.has_corner && !context->expired())
{
std::vector<Point2> adjusted;
if (repairCorner(result.vertices, result.why.vertex, *context, &adjusted))
attempt(adjusted);
}
return result;
}
/** Choose the vertices of a section with a swing again, by least turning, and keep the better legal path.
* Runs only on a legal path that has opposite turns, so every other path stays exactly as the greedy shortcut made it. */
void improveSwings(const std::vector<int32_t>& route, const QueryGraph& query, QueryContext* context, const uint8_t* master,
const Pose2& start, const Pose2& goal, double shortcut_minimum_m, const PointSet& protected_points,
const std::vector<Point2>& greedy, Candidate* result)
{
if (oppositePairs(greedy).empty() || !result->ok || !candidateLegal(result->path, *context, start, goal))
return;
const TimePoint deadline = context->deadline;
const TimePoint search_deadline = deadline - std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(kSwingReserveS));
if (context->expired() || Clock::now() >= search_deadline)
return;
const RawChain raw = routeRawChain(query, route);
SwingSearch search;
search.line_ok = [context](const Point2& a, const Point2& b, int minimum_mm) {
return lineOk(context->grid, a, b, context->deviation_deg, minimum_mm);
};
search.line_cost = [context, master](const Point2& a, const Point2& b) { return lineCost(a, b, master, context->grid); };
shortcutTiers(*context, shortcut_minimum_m, search.tiers_mm);
search.deadline = search_deadline;
search.cancel = context->cancel;
SwingStats stats;
std::vector<Point2> chosen;
std::vector<std::size_t> indices;
const bool changed = optimizeSwingChain(raw, greedy, search, &stats, &chosen, &indices);
context->info->swing_windows += stats.windows;
context->info->swing_line_checks += stats.line_checks;
if (!changed || context->expired() || Clock::now() >= search_deadline)
return;
context->deadline = search_deadline;
Candidate trial = buildSwingChain(chosen, context, start, goal, protected_points, shortcut_minimum_m);
const bool usable = trial.ok && !context->expired() && candidateLegal(trial.path, *context, start, goal);
context->deadline = deadline;
if (!usable || !preferLessTurning(trial.path, result->path))
return;
trial.provenance = chainProvenance(indices, raw.boundaries, route);
*result = std::move(trial);
++context->info->swing_selected;
}
} // namespace
/** Geometry of a route, optionally raising the clearance of its straight shortcuts. */
Candidate constructCandidate(const std::vector<int32_t>& route, const QueryGraph& query, QueryContext* context, const uint8_t* master,
const Pose2& start, const Pose2& goal, double shortcut_minimum_m)
{
PointSet protected_points;
for (int32_t id : route)
{
const GraphEdge& edge = query.edge(id);
if (isLocked(edge.kind))
for (const Point2& point : edge.points)
protected_points.insert({ point.x, point.y });
}
std::vector<Point2> greedy;
Candidate result = constructGreedyCandidate(route, query, context, master, start, goal, shortcut_minimum_m, protected_points, &greedy);
if (!greedy.empty())
improveSwings(route, query, context, master, start, goal, shortcut_minimum_m, protected_points, greedy, &result);
return result;
}
} // namespace detail
} // namespace lane_route_core

302
src/route_graph_search.cpp Normal file
View File

@@ -0,0 +1,302 @@
#include "route_planner_internal.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/swing_chain.h>
namespace lane_route_core
{
namespace detail
{
namespace
{
struct TemporaryLane
{
bool is_start;
uint8_t direction_index;
Point2 entry, exit;
};
/** Trace from an endpoint inside a direction region until it leaves that region. */
std::vector<TemporaryLane> temporaryLanes(const Point2& start, const Point2& goal, const GridRef& grid)
{
std::vector<TemporaryLane> result;
if (grid.direction == nullptr)
return result;
const auto code_at = [&](double x, double y) -> int {
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 -1;
return grid.direction[static_cast<int32_t>(fy) * grid.width + static_cast<int32_t>(fx)];
};
for (bool is_start : { true, false })
{
const Point2 position = is_start ? start : goal;
const int code = code_at(position.x, position.y);
if (code <= 0)
continue;
const double yaw = (code - 1) * kPi / 4.0;
const double ux = std::cos(yaw);
const double uy = std::sin(yaw);
const double sign = is_start ? 1.0 : -1.0;
const double step = grid.resolution * 0.25;
Point2 last = position;
const int limit = 4 * (grid.width + grid.height);
for (int k = 1; k <= limit; ++k)
{
const Point2 trial{ position.x + sign * k * step * ux, position.y + sign * k * step * uy };
if (code_at(trial.x, trial.y) != code)
break;
last = trial;
}
if (distanceOf(position, last) > 1e-8)
{
TemporaryLane lane;
lane.is_start = is_start;
lane.direction_index = static_cast<uint8_t>(code - 1);
lane.entry = is_start ? position : last;
lane.exit = is_start ? last : position;
result.push_back(lane);
}
}
return result;
}
} // namespace
/** Start, goal, temporary lanes and translated lane exits, all as query-only nodes and edges. */
void addQueryEdges(QueryGraph* query, const QueryContext& context, const Point2& start, const Point2& goal, int32_t* start_node,
int32_t* goal_node)
{
const CompiledGraph& base = query->base();
const int32_t base_nodes = query->baseNodes();
const int32_t s = query->addNode(start);
const int32_t g = query->addNode(goal);
*start_node = s;
*goal_node = g;
for (bool is_start : { true, false })
{
const int32_t id = is_start ? s : g;
const Point2 here = is_start ? start : goal;
int accepted = 0;
for (const auto& found : nearestNodes(base.nodes, base_nodes, here, std::min(base_nodes, kStartLinks), kStartRadiusM))
{
const Point2 there = query->node(found.second);
const Point2 a = is_start ? here : there;
const Point2 b = is_start ? there : here;
if (context.lineLegal(a, b))
{
if (is_start)
query->addEdge(id, found.second, { a, b }, EdgeKind::kAttach, found.first);
else
query->addEdge(found.second, id, { a, b }, EdgeKind::kAttach, found.first);
if (++accepted >= kAttachLimit)
break;
}
}
}
if (context.lineLegal(start, goal))
query->addEdge(s, g, { start, goal }, EdgeKind::kDirect, distanceOf(start, goal));
for (const TemporaryLane& lane : temporaryLanes(start, goal, context.grid))
{
const double angle = lane.direction_index * kPi / 4.0;
const double ux = std::cos(angle);
const double uy = std::sin(angle);
const Point2 anchor = lane.is_start ? lane.exit : lane.entry;
Point2 position = anchor;
for (int step = 1; step <= 10; ++step)
{
const double distance = lane.is_start ? 0.25 * step : -0.25 * step;
const Point2 trial{ anchor.x + distance * ux, anchor.y + distance * uy };
const bool legal = lane.is_start ? context.lineLegal(position, trial) : context.lineLegal(trial, position);
if (!legal)
break;
position = trial;
}
const int32_t q = query->addNode(position);
std::vector<Point2> points;
if (lane.is_start)
points = { lane.entry, position };
else
points = { position, lane.exit };
if (!polylineOk(context.grid, points, context.deviation_deg, context.hard_mm))
continue;
const double length = distanceOf(points[0], points[1]);
if (lane.is_start)
query->addEdge(s, q, points, EdgeKind::kTemporaryLane, length);
else
query->addEdge(q, g, points, EdgeKind::kTemporaryLane, length);
int count = 0;
for (const auto& found : nearestNodes(base.nodes, base_nodes, position, std::min(base_nodes, kTemporaryLinks), kTemporaryRadiusM))
{
const Point2 there = query->node(found.second);
const Point2 a = lane.is_start ? position : there;
const Point2 b = lane.is_start ? there : position;
if (context.lineLegal(a, b))
{
if (lane.is_start)
query->addEdge(q, found.second, { a, b }, EdgeKind::kAttach, found.first);
else
query->addEdge(found.second, q, { a, b }, EdgeKind::kAttach, found.first);
if (++count >= kAttachLimit)
break;
}
}
}
// A goal close to a lane exit: translate the whole lane parallel to itself so its straight passes through the goal.
// The direction grid and live clearance still decide every segment.
std::set<std::pair<int64_t, int64_t>> seen;
for (const GraphEdge& edge : base.edges)
{
if (context.cancel && context.cancel->load(std::memory_order_relaxed)) return;
if (edge.kind != EdgeKind::kLane)
continue;
const Point2& a = edge.points.front();
const Point2& b = edge.points.back();
const double length = distanceOf(a, b);
if (length < 1.0)
continue;
const double dx = (b.x - a.x) / length;
const double dy = (b.y - a.y) / length;
const double offset = (goal.x - a.x) * -dy + (goal.y - a.y) * dx;
const double along = (goal.x - b.x) * dx + (goal.y - b.y) * dy;
if (std::abs(offset) > 1.5 || along < -2.5 || along > 2.5)
continue;
const Point2 entry{ a.x + offset * -dy, a.y + offset * dx };
const std::pair<int64_t, int64_t> key(static_cast<int64_t>(std::rint(entry.x * 100.0)), static_cast<int64_t>(std::rint(entry.y * 100.0)));
if (!seen.insert(key).second || !context.lineLegal(entry, goal))
continue;
const int32_t q = query->addNode(entry);
query->addEdge(q, g, { entry, goal }, EdgeKind::kTemporaryLane, distanceOf(entry, goal));
for (const auto& found : nearestNodes(base.nodes, base_nodes, entry, std::min(base_nodes, kTranslatedLinks), kTemporaryRadiusM))
{
const Point2 there = query->node(found.second);
if (context.lineLegal(there, entry))
query->addEdge(found.second, q, { there, entry }, EdgeKind::kAttach, found.first);
}
}
}
namespace
{
/** Only a fixed lane-to-lane turn can be rejected by this map-wide bound: even a full-map straight could not fit the trim. */
bool turnProvablyImpossible(const GraphEdge& previous, const GraphEdge& current, double max_straight_m, double min_radius_m)
{
if (!isLocked(previous.kind) || !isLocked(current.kind))
return false;
const std::vector<Point2>& p = previous.points;
const double turn = std::abs(wrapAngle(headingOf(current.points[0], current.points[1]) - headingOf(p[p.size() - 2], p[p.size() - 1])));
return turn > 1e-8 && min_radius_m * std::tan(turn / 2.0) > max_straight_m;
}
} // namespace
/** Least-cost route over (node, incoming edge), so a turn penalty can apply. */
bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std::vector<uint8_t>& blocked,
const std::set<std::pair<int32_t, int32_t>>& blocked_pairs, double max_straight_m, double min_radius_m,
const std::vector<double>& factors, std::vector<int32_t>* route, const std::atomic<bool>* cancel)
{
const auto key_of = [](int32_t node, int32_t previous) {
return (static_cast<uint64_t>(static_cast<uint32_t>(node)) << 32) | static_cast<uint32_t>(previous + 1);
};
struct Entry
{
double score;
uint64_t serial;
int32_t node, previous;
bool operator>(const Entry& other) const
{
return score != other.score ? score > other.score : serial > other.serial;
}
};
std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> queue;
std::unordered_map<uint64_t, double> best;
std::unordered_map<uint64_t, std::pair<uint64_t, int32_t>> parent;
best.reserve(8192);
parent.reserve(8192);
queue.push({ 0.0, 0, start, -1 });
best[key_of(start, -1)] = 0.0;
uint64_t serial = 1;
bool reached = false;
uint64_t final_key = 0;
while (!queue.empty())
{
if (cancel && cancel->load(std::memory_order_relaxed)) return false;
const Entry top = queue.top();
queue.pop();
const uint64_t key = key_of(top.node, top.previous);
if (top.score != best[key])
continue;
if (top.node == goal)
{
reached = true;
final_key = key;
break;
}
double previous_angle = 0.0;
if (top.previous >= 0)
{
const std::vector<Point2>& p = query.edge(top.previous).points;
previous_angle = headingOf(p[p.size() - 2], p[p.size() - 1]);
}
query.forOutgoing(top.node, [&](int32_t index) {
if (blocked[static_cast<std::size_t>(index)] != 0)
return;
const GraphEdge& edge = query.edge(index);
if (edge.to == top.node || blocked_pairs.count({ top.previous, index }) != 0)
return;
const double angle = headingOf(edge.points[0], edge.points[1]);
const double turn = top.previous < 0 ? 0.0 : std::abs(wrapAngle(angle - previous_angle));
if (top.previous >= 0 && turnProvablyImpossible(query.edge(top.previous), edge, max_straight_m, min_radius_m))
return;
const double weight = edge.kind == EdgeKind::kVoronoi ? kVoronoiWeight : 1.0;
const double traversal = edge.cost * weight * factors[static_cast<std::size_t>(index)];
if (!std::isfinite(traversal))
return;
const double next = top.score + traversal + kTurnWeight * turn;
const uint64_t next_key = key_of(edge.to, index);
const auto known = best.find(next_key);
if (known != best.end() && next >= known->second)
return;
best[next_key] = next;
parent[next_key] = { key, index };
queue.push({ next, serial++, edge.to, index });
});
}
if (!reached)
return false;
route->clear();
uint64_t cursor = final_key;
while (static_cast<int32_t>(cursor >> 32) != start)
{
const auto step = parent.at(cursor);
route->push_back(step.second);
cursor = step.first;
}
std::reverse(route->begin(), route->end());
return true;
}
} // namespace detail
} // namespace lane_route_core

423
src/route_graph_tier.cpp Normal file
View File

@@ -0,0 +1,423 @@
#include "route_planner_internal.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/swing_chain.h>
namespace lane_route_core
{
namespace detail
{
namespace
{
bool hasSoftCost(const uint8_t* master, std::size_t count)
{
for (std::size_t i = 0; i < count; ++i)
if (master[i] == kCriticalSpace || master[i] == kPreferredSpace || master[i] == kUnpreferredSpace)
return true;
return false;
}
/** Route graph, then the same without soft cost values. Hard rules hold in both passes. */
bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, const GridRef& grid, const std::vector<WorldBox>* changed,
TimePoint deadline, bool allow_soft_fallback, const GridRef& verify_grid, const PlannerConfig& config, Path* path,
PathCheck* check, PlanInfo* info, const std::atomic<bool>* cancel)
{
QueryContext context{ grid, verify_grid, config, graph.deviation_deg, deadline, clearanceThresholdMm(config.clearance_hard_m),
clearanceThresholdMm(config.clearance_min_m), clearanceThresholdMm(config.clearance_preferred_m),
clearanceThresholdMm(config.collision_check_distance_m), {} };
context.info = info;
context.cancel = cancel;
const Point2 start_point{ start.x, start.y };
const Point2 goal_point{ goal.x, goal.y };
const double dev = graph.deviation_deg;
const std::size_t cell_count = static_cast<std::size_t>(grid.width) * static_cast<std::size_t>(grid.height);
const double max_straight_m = std::hypot(static_cast<double>(grid.height), static_cast<double>(grid.width)) * grid.resolution;
QueryGraph query(graph);
int32_t s = 0, g = 0;
TimePoint timer = Clock::now();
addQueryEdges(&query, context, start_point, goal_point, &s, &g);
info->search_ms += msSince(timer);
const uint8_t* master = grid.cost;
std::vector<uint8_t> neutral;
std::vector<double> factors;
compiledEdgeFactors(graph, master, &factors);
for (const GraphEdge& edge : query.extraEdges())
factors.push_back(edgeFactor(edge.points, master, grid));
// Edits can invalidate many duplicate edges of one physical lane. Check them up front,
// so a single obstacle cannot use up all retries.
std::vector<uint8_t> blocked(static_cast<std::size_t>(query.edgeCount()), 0);
if (changed != nullptr)
{
for (int32_t i = 0; i < query.edgeCount(); ++i)
{
const GraphEdge& edge = query.edge(i);
double x_min = kInfinity, y_min = kInfinity, x_max = -kInfinity, y_max = -kInfinity;
for (const Point2& point : edge.points)
{
x_min = std::min(x_min, point.x);
x_max = std::max(x_max, point.x);
y_min = std::min(y_min, point.y);
y_max = std::max(y_max, point.y);
}
bool near = false;
for (const WorldBox& box : *changed)
near = near || (x_max >= box.x_min - 0.65 && x_min <= box.x_max + 0.65 && y_max >= box.y_min - 0.65 && y_min <= box.y_max + 0.65);
if (near && !polylineOk(grid, edge.points, dev, context.hard_mm))
blocked[static_cast<std::size_t>(i)] = 1;
}
}
std::string reason;
std::vector<int32_t> route;
for (int pass = 0; pass < 2; ++pass)
{
const bool neutral_pass = pass == 1;
if (neutral_pass)
{
if (!allow_soft_fallback || reason == "no_route_enclosed" || reason == "timeout")
break;
if (context.expired())
{
reason = "timeout";
break;
}
if (!hasSoftCost(master, cell_count))
break;
neutral.assign(master, master + cell_count);
for (uint8_t& value : neutral)
if (value == kCriticalSpace || value == kPreferredSpace || value == kUnpreferredSpace)
value = kFreeSpace;
master = neutral.data();
compiledEdgeFactors(graph, master, &factors);
for (const GraphEdge& edge : query.extraEdges())
factors.push_back(edgeFactor(edge.points, master, grid));
reason.clear();
}
std::set<std::pair<int32_t, int32_t>> blocked_pairs;
for (int attempt = 0; attempt < config.max_route_attempts; ++attempt)
{
if (context.expired())
{
reason = "timeout";
break;
}
timer = Clock::now();
const bool found = searchRoute(query, s, g, blocked, blocked_pairs, max_straight_m, config.min_turn_radius_m, factors, &route, context.cancel);
info->search_ms += msSince(timer);
if (!found)
{
if (context.cancel && context.cancel->load(std::memory_order_relaxed)) break;
// The graph is not complete, so only a component test on the grid may call this no-route.
if (enclosedByObstacles(grid, start_point, goal_point, context.cancel))
reason = "no_route_enclosed";
else if (attempt == 0)
reason = "graph_disconnected";
break;
}
// The compiled graph is rechecked lazily against the live map.
int32_t bad = -1;
for (int32_t index : route)
{
if (!polylineOk(grid, query.edge(index).points, dev, context.hard_mm))
{
bad = index;
break;
}
}
if (bad >= 0)
{
blocked[static_cast<std::size_t>(bad)] = 1;
++info->retries;
reason = "edge_blocked";
continue;
}
timer = Clock::now();
Candidate candidate = constructCandidate(route, query, &context, master, start, goal, 0.0);
info->build_ms += msSince(timer);
if (context.expired())
{
reason = "timeout";
break;
}
std::string why = candidate.why.reason;
bool has_corner = candidate.why.has_corner;
const Point2 corner = candidate.why.corner;
if (candidate.ok)
{
timer = Clock::now();
PathCheck path_check = verifyPath(candidate.path, verify_grid, dev, config, context.cancel);
bool ends_ok = endpointOk(candidate.path, start, goal);
bool clear_ok = freeClearanceOk(candidate.path, verify_grid, context.min_mm);
const char* turn_blocked = blockedEndpointTurn(candidate.path, verify_grid, config.half_x_m, config.half_y_m);
info->verify_ms += msSince(timer);
if (turn_blocked != nullptr)
{
reason = turn_blocked;
break;
}
bool gap_checked = false;
bool reference_checked = false;
double raise_used = 0.0;
GapCheck gap;
if (path_check.valid && ends_ok && clear_ok)
{
timer = Clock::now();
gap = checkFootprintGap(candidate.path, verify_grid, config.footprint_min_gap_m, config.half_x_m, config.half_y_m, context.cancel);
info->verify_ms += msSince(timer);
gap_checked = true;
if (!gap.valid)
++info->gap_failures;
// A path close to an obstacle often has a same-route twin with its shortcuts further out.
for (std::size_t r = 0; !gap.valid && r < config.footprint_gap_shortcut_raise_m.size(); ++r)
{
if (context.expired())
break;
const double extra = config.footprint_gap_shortcut_raise_m[r];
timer = Clock::now();
Candidate alternative = constructCandidate(route, query, &context, master, start, goal, config.clearance_min_m + extra);
info->build_ms += msSince(timer);
if (!alternative.ok)
continue;
timer = Clock::now();
const PathCheck alternative_check = verifyPath(alternative.path, verify_grid, dev, config, context.cancel);
const bool usable = alternative_check.valid && endpointOk(alternative.path, start, goal) &&
freeClearanceOk(alternative.path, verify_grid, context.min_mm) &&
blockedEndpointTurn(alternative.path, verify_grid, config.half_x_m, config.half_y_m) == nullptr;
GapCheck alternative_gap;
if (usable)
alternative_gap = checkFootprintGap(alternative.path, verify_grid, config.footprint_min_gap_m, config.half_x_m, config.half_y_m, context.cancel);
info->verify_ms += msSince(timer);
if (!usable)
continue;
if (!alternative_gap.valid)
{
++info->gap_failures;
continue;
}
const double length = pathLength(alternative.path);
if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m)
{
const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio;
double reference = 0.0;
if (shortestDirectedReference(verify_grid, start_point, goal_point, dev, bound, &reference, context.cancel) &&
length > config.route_too_long_ratio * reference + config.route_too_long_margin_m)
continue;
reference_checked = true;
}
candidate = std::move(alternative);
path_check = alternative_check;
gap = alternative_gap;
ends_ok = true;
clear_ok = true;
raise_used = extra;
break;
}
if (context.expired())
{
reason = "timeout";
break;
}
}
const bool passed = path_check.valid && ends_ok && clear_ok && gap_checked && gap.valid;
if (passed && !reference_checked)
{
const double length = pathLength(candidate.path);
if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m)
{
timer = Clock::now();
const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio;
double reference = 0.0;
const bool known = shortestDirectedReference(verify_grid, start_point, goal_point, dev, bound, &reference, context.cancel);
info->verify_ms += msSince(timer);
if (known && length > config.route_too_long_ratio * reference + config.route_too_long_margin_m)
{
reason = "route_too_long";
break;
}
}
}
if (passed)
{
*path = std::move(candidate.path);
*check = path_check;
info->reason = "verified";
info->radii_m = std::move(candidate.radii);
info->soft_cost_ignored = neutral_pass;
info->gap_shortcut_raise_m = raise_used;
info->min_gap_m = gap.min_gap_m;
info->gap_exemption_used = gap.exemption_used;
return true;
}
why = gap_checked && !gap.valid ? "footprint_gap_below_minimum" :
path_check.valid && ends_ok && !clear_ok ? "free_clearance_below_minimum" : "independent_verification_failed";
has_corner = false;
}
if (candidate.vertices.empty())
{
reason = why;
break;
}
std::vector<std::pair<int32_t, int32_t>> pairs;
if (!has_corner)
{
// Not proof that either edge is unusable. Try a different pair.
if (route.size() > 1)
{
const std::size_t index = std::min(static_cast<std::size_t>(attempt), route.size() - 2);
pairs.emplace_back(route[index], route[index + 1]);
}
}
else if (candidate.vertices.size() > 2)
{
// A simplified corner can stand for several graph edges: ban those it spans.
std::size_t index = 1;
double closest = kInfinity;
for (std::size_t j = 1; j + 1 < candidate.vertices.size(); ++j)
{
const double distance = distanceOf(corner, candidate.vertices[j]);
if (distance < closest)
{
closest = distance;
index = j;
}
}
if (index < candidate.provenance.size())
pairs = candidate.provenance[index];
}
if (pairs.empty())
{
reason = why;
break;
}
blocked_pairs.insert(pairs.begin(), pairs.end());
++info->retries;
reason = why;
}
}
info->reason = reason.empty() ? "fallback" : reason;
return false;
}
/** One rung: the normal core, then a ridge rebuilt from the live grid around start and goal when the map changed. */
bool planRung(const CompiledGraph& graph, const RouteRequest& request, const GridRef& live, TimePoint deadline, const PlannerConfig& config,
const RidgeBackend& backend, Path* path, PathCheck* check, PlanInfo* info)
{
const std::vector<WorldBox>* changed = request.changed_boxes.empty() ? nullptr : &request.changed_boxes;
if (planCore(graph, request.start, request.goal, live, changed, deadline, true, live, config, path, check, info, request.cancel))
return true;
if ((request.cancel && request.cancel->load(std::memory_order_relaxed)) || changed == nullptr || !backend.build_coarse || info->reason == "no_route_enclosed" || info->reason == "timeout")
return false;
const double pad = config.live_ridge_pad_m;
const double resolution = live.resolution;
const int32_t x0 = std::max<int32_t>(0, static_cast<int32_t>(std::floor((std::min(request.start.x, request.goal.x) - pad - live.origin_x) / resolution)));
const int32_t x1 = std::min<int32_t>(live.width, static_cast<int32_t>(std::ceil((std::max(request.start.x, request.goal.x) + pad - live.origin_x) / resolution)));
const int32_t y0 = std::max<int32_t>(0, static_cast<int32_t>(std::floor((std::min(request.start.y, request.goal.y) - pad - live.origin_y) / resolution)));
const int32_t y1 = std::min<int32_t>(live.height, static_cast<int32_t>(std::ceil((std::max(request.start.y, request.goal.y) + pad - live.origin_y) / resolution)));
const int64_t width = std::max<int32_t>(0, x1 - x0);
const int64_t height = std::max<int32_t>(0, y1 - y0);
if (width * height > config.live_ridge_max_cells)
{
info->live_ridge = "skipped_size";
return false;
}
if (width * height == 0 || Clock::now() >= deadline)
{
info->live_ridge = "failed";
return false;
}
const TimePoint began = Clock::now();
const std::string previous_reason = info->reason;
const std::size_t cells = static_cast<std::size_t>(width * height);
std::vector<uint8_t> window_cost(cells), window_direction;
std::vector<uint16_t> window_clearance(cells);
if (live.direction != nullptr)
window_direction.resize(cells);
for (int64_t y = 0; y < height; ++y)
{
const std::size_t from = static_cast<std::size_t>((y + y0) * live.width + x0);
const std::size_t to = static_cast<std::size_t>(y * width);
const std::size_t count = static_cast<std::size_t>(width);
std::copy_n(live.cost + from, count, window_cost.begin() + static_cast<std::ptrdiff_t>(to));
std::copy_n(live.clearance_mm + from, count, window_clearance.begin() + static_cast<std::ptrdiff_t>(to));
if (live.direction != nullptr)
std::copy_n(live.direction + from, count, window_direction.begin() + static_cast<std::ptrdiff_t>(to));
}
GridRef window;
window.width = static_cast<int32_t>(width);
window.height = static_cast<int32_t>(height);
window.resolution = resolution;
window.origin_x = live.origin_x + x0 * resolution;
window.origin_y = live.origin_y + y0 * resolution;
window.cost = window_cost.data();
window.clearance_mm = window_clearance.data();
window.direction = live.direction != nullptr ? window_direction.data() : nullptr;
bool ok = false;
PlanInfo live_info;
const CoarseGraph coarse = backend.build_coarse(window, request.cancel);
if (!coarse.nodes.empty() && Clock::now() < deadline)
{
const CompiledGraph live_graph = compileGraph(coarse, window, window.cost, graph.deviation_deg, config, backend, request.cancel);
if (Clock::now() < deadline)
ok = planCore(live_graph, request.start, request.goal, window, nullptr, deadline, false, live, config, path, check, &live_info, request.cancel);
}
info->retries += live_info.retries;
info->gap_failures += live_info.gap_failures;
info->search_ms += live_info.search_ms;
info->build_ms += live_info.build_ms;
info->verify_ms += live_info.verify_ms;
info->live_ridge_ms += msSince(began);
if (!ok)
{
info->live_ridge = "failed";
info->reason = previous_reason;
return false;
}
info->live_ridge = "used";
info->reason = live_info.reason;
info->radii_m = std::move(live_info.radii_m);
info->soft_cost_ignored = live_info.soft_cost_ignored;
info->gap_shortcut_raise_m = live_info.gap_shortcut_raise_m;
info->min_gap_m = live_info.min_gap_m;
info->gap_exemption_used = live_info.gap_exemption_used;
return true;
}
} // namespace
bool planGraphTier(const GraphTierInput& input, GraphTierOutput output)
{
return planRung(input.graph, input.request, input.live, input.deadline, input.config, input.backend,
&output.path, &output.check, &output.info);
}
} // namespace detail
} // namespace lane_route_core

262
src/route_planner.cpp Normal file
View File

@@ -0,0 +1,262 @@
#include <lane_route_core/route_planner.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/swing_chain.h>
#include "lattice_internal.h"
#include "route_planner_internal.h"
namespace lane_route_core
{
using detail::Clock;
using detail::TimePoint;
using detail::msSince;
PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config,
const RidgeBackend& backend)
{
PlanResult result;
const TimePoint began = Clock::now();
const auto finish = [&]() {
result.info.query_ms = msSince(began);
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
{
result.ok = false;
result.path.clear();
result.info.reason = "cancelled";
}
return result;
};
const std::string config_error = config.validate();
if (!config_error.empty())
{
result.info.reason = "invalid_config: " + config_error;
return finish();
}
if (live.cost == nullptr || live.clearance_mm == nullptr || live.width <= 0 || live.height <= 0 || !(live.resolution > 0.0) ||
(!graphs && !config.lattice_enabled) || !std::isfinite(request.start.x) || !std::isfinite(request.start.y) || !std::isfinite(request.goal.x) ||
!std::isfinite(request.goal.y) || (config.lattice_enabled && (!std::isfinite(live.resolution) ||
!std::isfinite(live.origin_x) || !std::isfinite(live.origin_y))) || (request.start.has_yaw && !std::isfinite(request.start.yaw)) ||
(request.goal.has_yaw && !std::isfinite(request.goal.yaw)))
{
result.info.reason = "invalid_request";
return finish();
}
const TimePoint deadline = began + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(config.time_limit_s));
// Stricter limits first. With no zones, or a strict configured limit, one rung is all there is.
const std::size_t cell_count = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
bool has_zones = false;
if (live.direction != nullptr)
has_zones = std::any_of(live.direction, live.direction + cell_count, [](uint8_t code) { return code != 0; });
std::vector<double> rungs;
if (config.max_deviation_deg > 0.0 && has_zones)
{
std::set<double> strict;
for (double value : config.deviation_ladder_deg)
if (value < config.max_deviation_deg)
strict.insert(value);
rungs.assign(strict.begin(), strict.end());
}
rungs.push_back(config.max_deviation_deg);
// R2 smoothing must share this fallback deadline instead of starting a new budget.
TimePoint fallback_deadline = deadline;
bool fallback_started = false;
for (std::size_t rung = 0; rung < rungs.size(); ++rung)
{
const double deviation = rungs[rung];
if ((request.cancel && request.cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline)
{
result.info.reason = "timeout";
break;
}
bool graph_ok = false;
if (!(config.lattice_enabled && request.lattice_only))
{
const TimePoint compile_began = Clock::now();
const std::shared_ptr<const CompiledGraph> graph = graphs ? graphs(deviation) : std::shared_ptr<const CompiledGraph>();
result.info.compile_ms += msSince(compile_began);
if (request.cancel && request.cancel->load(std::memory_order_relaxed)) break;
if (graph == nullptr || std::abs(graph->deviation_deg - deviation) > 1e-9)
result.info.reason = "graph_unavailable";
else
{
result.info.live_ridge.clear();
graph_ok = detail::planGraphTier({ *graph, request, live, deadline, config, backend },
{ result.path, result.check, result.info });
}
result.info.graph_reason = result.info.reason;
result.info.graph_rung_reasons.push_back(result.info.graph_reason);
if (graph_ok)
{
result.ok = true;
result.info.tier_used = "graph";
result.info.rung_used_deg = deviation;
result.info.rung_reasons.push_back(result.info.reason);
return finish();
}
// Preserve R0 early exits exactly while the new tier is disabled.
if (!config.lattice_enabled)
{
if (result.info.reason == "graph_unavailable") break;
result.info.rung_reasons.push_back(result.info.reason);
if (result.info.reason == "no_route_enclosed" || result.info.reason == "timeout")
break;
continue;
}
if (result.info.reason == "no_route_enclosed")
{
result.info.rung_reasons.push_back(result.info.reason);
break;
}
}
if ((request.cancel && request.cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline || result.info.reason == "timeout")
break;
const TimePoint now = Clock::now();
if (!fallback_started)
{
fallback_started = true;
fallback_deadline = std::min(deadline, now + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(config.fallback_time_limit_s)));
}
if (now >= fallback_deadline)
{
result.info.lattice_reason = "lattice_timeout";
result.info.lattice_rung_reasons.push_back(result.info.lattice_reason);
result.info.reason = result.info.lattice_reason;
result.info.rung_reasons.push_back(result.info.reason);
break;
}
const TimePoint rung_deadline = now + (fallback_deadline - now) / static_cast<Clock::duration::rep>(rungs.size() - rung);
if (detail::planLatticeTier({ request, live, config, deviation, rung_deadline },
{ result.path, result.check, result.info }))
{
result.ok = true;
result.info.tier_used = "lattice";
result.info.lattice_rung_reasons.push_back(result.info.lattice_reason);
result.info.rung_used_deg = deviation;
result.info.rung_reasons.push_back(result.info.reason);
return finish();
}
result.info.reason = result.info.lattice_reason;
result.info.lattice_rung_reasons.push_back(result.info.lattice_reason);
result.info.rung_reasons.push_back(result.info.reason);
if (result.info.reason == "cancelled" || result.info.reason == "lattice_resource_limit" || Clock::now() >= deadline)
break;
}
return finish();
}
std::vector<WorldBox> changedBoxes(const uint8_t* compiled_cost, const GridRef& live, const std::atomic<bool>* cancel,
std::vector<uint8_t>* scratch, std::vector<int32_t>* stack_scratch)
{
// Lethal and unknown only. The compiled grid comes from the static layer, so the inflated ring the master
// holds around every static obstacle would otherwise count as a change, and so would any soft value.
const auto state = [](uint8_t value) { return value < kLethalCost ? 0 : value - kLethalCost + 1; };
const std::size_t cell_count = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
std::vector<uint8_t> local_scratch;
std::vector<uint8_t>& differs = scratch ? *scratch : local_scratch;
differs.assign(cell_count, 0);
for (std::size_t i = 0; i < cell_count; ++i)
{
if ((i & 4095u) == 0 && cancel && cancel->load(std::memory_order_relaxed)) return {};
differs[i] = state(compiled_cost[i]) != state(live.cost[i]) ? 1 : 0;
}
std::vector<WorldBox> boxes;
std::vector<int32_t> local_stack;
std::vector<int32_t>& stack = stack_scratch ? *stack_scratch : local_stack;
for (std::size_t seed = 0; seed < cell_count; ++seed)
{
if ((seed & 4095u) == 0 && cancel && cancel->load(std::memory_order_relaxed)) return {};
if (differs[seed] == 0)
continue;
differs[seed] = 0;
stack.assign(1, static_cast<int32_t>(seed));
int32_t x_min = live.width, x_max = -1, y_min = live.height, y_max = -1;
while (!stack.empty())
{
if (cancel && cancel->load(std::memory_order_relaxed)) return {};
const int32_t cell = stack.back();
stack.pop_back();
const int32_t x = cell % live.width;
const int32_t y = cell / live.width;
x_min = std::min(x_min, x);
x_max = std::max(x_max, x);
y_min = std::min(y_min, y);
y_max = std::max(y_max, y);
const auto visit = [&](int32_t other) {
if (differs[static_cast<std::size_t>(other)] != 0)
{
differs[static_cast<std::size_t>(other)] = 0;
stack.push_back(other);
}
};
if (x > 0)
visit(cell - 1);
if (x + 1 < live.width)
visit(cell + 1);
if (y > 0)
visit(cell - live.width);
if (y + 1 < live.height)
visit(cell + live.width);
}
boxes.push_back({ live.origin_x + x_min * live.resolution, live.origin_y + y_min * live.resolution,
live.origin_x + (x_max + 1) * live.resolution, live.origin_y + (y_max + 1) * live.resolution });
}
return boxes;
}
void patchClearance(const uint8_t* compiled_cost, const uint16_t* compiled_clearance_mm, const GridRef& live, double radius_m,
std::vector<uint16_t>* clearance_mm, const std::atomic<bool>* cancel)
{
const std::size_t cell_count = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
clearance_mm->assign(compiled_clearance_mm, compiled_clearance_mm + cell_count);
const int32_t radius_cells = static_cast<int32_t>(std::ceil(radius_m / live.resolution));
for (int32_t y = 0; y < live.height; ++y)
{
if (cancel && cancel->load(std::memory_order_relaxed)) return;
for (int32_t x = 0; x < live.width; ++x)
{
const int32_t cell = y * live.width + x;
if (live.cost[cell] != kLethalCost || compiled_cost[cell] == kLethalCost)
continue;
(*clearance_mm)[static_cast<std::size_t>(cell)] = 0;
// Only cells on the rim of a new region set the distance for anything outside it.
const bool inner = x > 0 && y > 0 && x + 1 < live.width && y + 1 < live.height && live.cost[cell - 1] == kLethalCost &&
live.cost[cell + 1] == kLethalCost && live.cost[cell - live.width] == kLethalCost &&
live.cost[cell + live.width] == kLethalCost;
if (inner)
continue;
for (int32_t ny = std::max(0, y - radius_cells); ny <= std::min(live.height - 1, y + radius_cells); ++ny)
{
for (int32_t nx = std::max(0, x - radius_cells); nx <= std::min(live.width - 1, x + radius_cells); ++nx)
{
const double metres = std::hypot(static_cast<double>(ny - y), static_cast<double>(nx - x)) * live.resolution;
const double millimetres = std::floor(metres * 1000.0);
uint16_t& stored = (*clearance_mm)[static_cast<std::size_t>(ny * live.width + nx)];
if (millimetres < stored)
stored = static_cast<uint16_t>(millimetres);
}
}
}
}
}
} // namespace lane_route_core

View File

@@ -0,0 +1,173 @@
#ifndef LANE_ROUTE_CORE_ROUTE_PLANNER_INTERNAL_H_
#define LANE_ROUTE_CORE_ROUTE_PLANNER_INTERNAL_H_
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/route_planner.h>
namespace lane_route_core
{
namespace detail
{
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
constexpr double kInfinity = std::numeric_limits<double>::infinity();
constexpr double kTurnWeight = 0.6; // Cost per radian of turn at a route vertex.
constexpr double kVoronoiWeight = 1.6; // Free space costs more than an explicit lane.
constexpr double kSharpness[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
constexpr double kSpinStepRad = 0.04;
constexpr int32_t kStartLinks = 600; // Candidates tried around start and goal.
constexpr double kStartRadiusM = 15.0;
constexpr int kAttachLimit = 120;
constexpr int32_t kTemporaryLinks = 80;
constexpr double kTemporaryRadiusM = 8.0;
constexpr int32_t kTranslatedLinks = 100;
// Reserved from the deadline while improving a path that is already legal, so that the legal path can still be returned.
constexpr double kSwingReserveS = 1.0;
inline double msSince(TimePoint begin) { return std::chrono::duration<double, std::milli>(Clock::now() - begin).count(); }
/** Compiled graph plus the nodes and edges of one query, without copying the compiled part. */
class QueryGraph
{
public:
explicit QueryGraph(const CompiledGraph& base)
: base_(base), base_nodes_(static_cast<int32_t>(base.nodes.size())), base_edges_(static_cast<int32_t>(base.edges.size())),
extra_outgoing_(base.nodes.size())
{
}
int32_t baseNodes() const { return base_nodes_; }
int32_t baseEdges() const { return base_edges_; }
int32_t nodeCount() const { return base_nodes_ + static_cast<int32_t>(extra_nodes_.size()); }
int32_t edgeCount() const { return base_edges_ + static_cast<int32_t>(extra_edges_.size()); }
const Point2& node(int32_t i) const
{
return i < base_nodes_ ? base_.nodes[static_cast<std::size_t>(i)] : extra_nodes_[static_cast<std::size_t>(i - base_nodes_)];
}
const GraphEdge& edge(int32_t i) const
{
return i < base_edges_ ? base_.edges[static_cast<std::size_t>(i)] : extra_edges_[static_cast<std::size_t>(i - base_edges_)];
}
const std::vector<GraphEdge>& extraEdges() const { return extra_edges_; }
const CompiledGraph& base() const { return base_; }
int32_t addNode(const Point2& point)
{
extra_nodes_.push_back(point);
extra_outgoing_.emplace_back();
return nodeCount() - 1;
}
void addEdge(int32_t from, int32_t to, std::vector<Point2> points, EdgeKind kind, double cost)
{
extra_outgoing_[static_cast<std::size_t>(from)].push_back(edgeCount());
extra_edges_.push_back({ from, to, std::move(points), kind, cost });
}
template <typename Visit>
void forOutgoing(int32_t node, Visit visit) const
{
if (node < base_nodes_)
for (int32_t edge : base_.outgoing[static_cast<std::size_t>(node)])
visit(edge);
for (int32_t edge : extra_outgoing_[static_cast<std::size_t>(node)])
visit(edge);
}
private:
const CompiledGraph& base_;
int32_t base_nodes_, base_edges_;
std::vector<Point2> extra_nodes_;
std::vector<GraphEdge> extra_edges_;
std::vector<std::vector<int32_t>> extra_outgoing_;
};
/** Everything one core pass needs. The corner cache lives across retries and the neutral pass. */
struct QueryContext
{
const GridRef& grid;
const GridRef& verify_grid;
const PlannerConfig& config;
double deviation_deg;
TimePoint deadline;
int hard_mm, min_mm, preferred_mm, collision_mm;
struct CornerOption
{
double trim;
std::shared_ptr<const Path> curve; // Null on a straight vertex.
double radius;
};
std::map<std::array<double, 6>, std::vector<CornerOption>> corner_options;
PlanInfo* info = nullptr;
const std::atomic<bool>* cancel = nullptr;
bool expired() const { return (cancel && cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline; }
bool lineLegal(const Point2& a, const Point2& b) const { return lineOk(grid, a, b, deviation_deg, hard_mm); }
};
struct BuildFailure
{
std::string reason;
bool has_corner = false; // True for a failure tied to one vertex.
int vertex = -1;
Point2 corner;
};
struct Candidate
{
bool ok = false;
Path path;
BuildFailure why;
std::vector<double> radii;
std::vector<Point2> vertices;
std::vector<std::vector<std::pair<int32_t, int32_t>>> provenance;
};
void addQueryEdges(QueryGraph* query, const QueryContext& context, const Point2& start, const Point2& goal, int32_t* start_node,
int32_t* goal_node);
bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std::vector<uint8_t>& blocked,
const std::set<std::pair<int32_t, int32_t>>& blocked_pairs, double max_straight_m, double min_radius_m,
const std::vector<double>& factors, std::vector<int32_t>* route, const std::atomic<bool>* cancel);
double pathLength(const Path& path);
Candidate constructCandidate(const std::vector<int32_t>& route, const QueryGraph& query, QueryContext* context, const uint8_t* master,
const Pose2& start, const Pose2& goal, double shortcut_minimum_m);
struct GraphTierInput
{
const CompiledGraph& graph;
const RouteRequest& request;
const GridRef& live;
TimePoint deadline;
const PlannerConfig& config;
const RidgeBackend& backend;
};
struct GraphTierOutput
{
Path& path;
PathCheck& check;
PlanInfo& info;
};
bool planGraphTier(const GraphTierInput& input, GraphTierOutput output);
} // namespace detail
} // namespace lane_route_core
#endif // LANE_ROUTE_CORE_ROUTE_PLANNER_INTERNAL_H_

387
src/swing_chain.cpp Normal file
View File

@@ -0,0 +1,387 @@
#include <lane_route_core/swing_chain.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include <tuple>
#include <lane_route_core/grid_checks.h>
namespace lane_route_core
{
namespace
{
// Raw points are 0.25 m apart, so this is 50 m of route. It bounds a window at about 20000 line checks.
constexpr std::size_t kMaxRawVertices = 200;
constexpr double kLengthWeightDegPerM = 1.0;
constexpr double kReversalPenaltyDeg = 30.0;
// Turns below this keep the previous sign: a raw chain is never quite straight.
constexpr double kSignThresholdDeg = 1.0;
constexpr double kAngularTieRad = 1e-12;
// One degree less turning may cost this much length. It keeps every removal of a swing on the measured maps, where
// the dearest was 0.26 m for 12 degrees, and refuses the long way round: 2 m for 3.4 degrees, 0.36 m for 4.9 degrees.
constexpr double kLengthPerDegreeM = 0.03;
constexpr double kLengthMarginM = 0.02;
constexpr double degrees(double radians) { return radians * 180.0 / kPi; }
int classify(double turn_deg, int sign)
{
if (turn_deg >= kSignThresholdDeg)
return 1;
if (turn_deg <= -kSignThresholdDeg)
return -1;
return sign;
}
/** Same value as wrapAngle for a difference of two headings, which stays within one turn, without the division. */
double wrapHeadingDifference(double difference)
{
if (difference > kPi)
return difference - 2.0 * kPi;
return difference < -kPi ? difference + 2.0 * kPi : difference;
}
double reversalPenalty(int first, int second) { return first != 0 && second != 0 && first != second ? kReversalPenaltyDeg : 0.0; }
double pathLength(const Path& path)
{
double total = 0.0;
for (std::size_t i = 0; i + 1 < path.size(); ++i)
total += std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y);
return total;
}
/** Signs of the turns along these points that reach the threshold. */
std::vector<int> turnSigns(const std::vector<Point2>& points)
{
std::vector<int> signs;
for (std::size_t i = 0; i + 2 < points.size(); ++i)
{
const double turn = degrees(wrapAngle(headingOf(points[i + 1], points[i + 2]) - headingOf(points[i], points[i + 1])));
if (std::abs(turn) >= kSignThresholdDeg)
signs.push_back(turn > 0.0 ? 1 : -1);
}
return signs;
}
/** Where each greedy vertex sits in the raw points. */
bool locateGreedy(const std::vector<Point2>& raw, const std::vector<Point2>& greedy, std::vector<std::size_t>* indices)
{
indices->clear();
std::size_t cursor = 0;
for (const Point2& point : greedy)
{
while (cursor < raw.size() && distanceOf(raw[cursor], point) > 1e-7)
++cursor;
if (cursor == raw.size())
return false;
indices->push_back(cursor);
++cursor;
}
return true;
}
struct DpState
{
int32_t previous, current;
int sign;
double heading; // Of the step previous -> current [rad].
double cost;
int32_t parent;
};
struct DpStep
{
int32_t to;
double heading; // [rad]
double length_m;
};
} // namespace
std::vector<std::size_t> oppositePairs(const std::vector<Point2>& chain)
{
std::vector<std::size_t> pairs;
for (std::size_t j = 1; j + 2 < chain.size(); ++j)
{
const double first = wrapAngle(headingOf(chain[j], chain[j + 1]) - headingOf(chain[j - 1], chain[j]));
const double second = wrapAngle(headingOf(chain[j + 1], chain[j + 2]) - headingOf(chain[j], chain[j + 1]));
if (first * second < 0.0)
pairs.push_back(j);
}
return pairs;
}
double chainTurning(const std::vector<Point2>& chain)
{
double total = 0.0;
for (std::size_t j = 1; j + 1 < chain.size(); ++j)
total += std::abs(wrapAngle(headingOf(chain[j], chain[j + 1]) - headingOf(chain[j - 1], chain[j])));
return total;
}
double movingTurning(const Path& path)
{
double total = 0.0;
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-9)
total += std::abs(wrapAngle(path[i + 1].yaw - path[i].yaw));
return total;
}
bool preferLessTurning(const Path& candidate, const Path& baseline)
{
const double new_turn = movingTurning(candidate);
const double old_turn = movingTurning(baseline);
if (new_turn < old_turn - kAngularTieRad)
return pathLength(candidate) <= pathLength(baseline) + kLengthMarginM + kLengthPerDegreeM * degrees(old_turn - new_turn);
return std::abs(new_turn - old_turn) <= kAngularTieRad && pathLength(candidate) < pathLength(baseline);
}
bool solveSwingWindow(const std::vector<Point2>& raw, const std::vector<uint8_t>& 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<std::size_t>* selected)
{
const std::size_t count = end - start + 1;
if (end <= start || count > kMaxRawVertices)
return false;
const auto expired = [&search]() { return (search.cancel != nullptr && search.cancel->load(std::memory_order_relaxed)) ||
std::chrono::steady_clock::now() >= search.deadline; };
const Point2* v = raw.data() + start;
const uint8_t* lock = locked.data() + start;
std::vector<double> prefix(count, 0.0);
for (std::size_t i = 0; i + 1 < count; ++i)
prefix[i + 1] = prefix[i] + search.line_cost(v[i], v[i + 1]);
// Allowed steps from each point, under the same tiers as the greedy shortcut.
std::vector<std::vector<DpStep>> allowed(count - 1);
for (std::size_t i = 0; i + 1 < count; ++i)
{
if (expired())
return false;
std::size_t boundary = count - 1;
for (std::size_t j = i + 1; j < count; ++j)
{
if (lock[j] != 0)
{
boundary = j;
break;
}
}
std::vector<int32_t> steps;
for (int tier : search.tiers_mm)
{
for (std::size_t j = boundary; j > i; --j)
{
if (expired())
return false;
++stats->line_checks;
if (search.line_ok(v[i], v[j], tier) && search.line_cost(v[i], v[j]) <= prefix[j] - prefix[i] + 1e-8)
steps.push_back(static_cast<int32_t>(j));
}
bool reaches = false;
for (int32_t j : steps)
reaches = reaches || j > static_cast<int32_t>(i) + 1;
if (reaches)
break;
}
steps.push_back(static_cast<int32_t>(i) + 1);
std::sort(steps.begin(), steps.end());
steps.erase(std::unique(steps.begin(), steps.end()), steps.end());
// Each step is visited once per state arriving at i, so on a long open section the search below repeats it very
// often. Its heading and length are computed once, here.
allowed[i].reserve(steps.size());
for (int32_t j : steps)
allowed[i].push_back({ j, headingOf(v[i], v[j]), distanceOf(v[i], v[j]) });
}
// A state is the last step and the sign of the last turn, because the next turn depends on both.
const std::size_t n = count;
std::vector<int32_t> state_at(n * n * 3, -1);
const auto slot = [n](int32_t previous, int32_t current, int sign) {
return (static_cast<std::size_t>(previous) * n + static_cast<std::size_t>(current)) * 3 + static_cast<std::size_t>(sign + 1);
};
std::vector<DpState> states;
std::vector<std::vector<int32_t>> by_current(n);
const auto relax = [&](int32_t previous, const DpStep& step, int sign, double cost, int32_t parent) {
const int32_t current = step.to;
int32_t& at = state_at[slot(previous, current, sign)];
if (at < 0)
{
at = static_cast<int32_t>(states.size());
states.push_back({ previous, current, sign, step.heading, cost, parent });
by_current[static_cast<std::size_t>(current)].push_back(at);
}
else if (cost < states[static_cast<std::size_t>(at)].cost - 1e-12)
{
states[static_cast<std::size_t>(at)].cost = cost;
states[static_cast<std::size_t>(at)].parent = parent;
}
};
for (const DpStep& step : allowed[0])
{
const double turn = preceding != nullptr ? degrees(wrapAngle(step.heading - headingOf(*preceding, v[0]))) : 0.0;
const int sign = classify(turn, preceding_sign);
relax(0, step, sign, kLengthWeightDegPerM * step.length_m + std::abs(turn) + reversalPenalty(preceding_sign, sign), -1);
}
for (int32_t i = 1; i + 1 < static_cast<int32_t>(n); ++i)
{
if (expired())
return false;
// A later point can never add a state here, so this list and these costs are final.
for (int32_t id : by_current[static_cast<std::size_t>(i)])
{
const double incoming = states[static_cast<std::size_t>(id)].heading;
const int sign = states[static_cast<std::size_t>(id)].sign;
const double base = states[static_cast<std::size_t>(id)].cost;
for (const DpStep& step : allowed[static_cast<std::size_t>(i)])
{
const double turn = degrees(wrapHeadingDifference(step.heading - incoming));
const int new_sign = classify(turn, sign);
relax(i, step, new_sign, base + std::abs(turn) + kLengthWeightDegPerM * step.length_m + reversalPenalty(sign, new_sign), id);
}
}
}
const int32_t last = static_cast<int32_t>(n) - 1;
int32_t best = -1;
double best_score = std::numeric_limits<double>::infinity();
for (int32_t id : by_current[static_cast<std::size_t>(last)])
{
const DpState& state = states[static_cast<std::size_t>(id)];
double score = state.cost;
int sign = state.sign;
if (following != nullptr)
{
const double angle = degrees(wrapAngle(headingOf(v[last], *following) - state.heading));
const int updated = classify(angle, sign);
score += std::abs(angle) + reversalPenalty(sign, updated);
sign = updated;
}
score += reversalPenalty(sign, following_sign);
bool better = score < best_score;
if (!better && score == best_score && best >= 0)
{
const DpState& other = states[static_cast<std::size_t>(best)];
better = std::make_tuple(state.previous, state.current, state.sign) < std::make_tuple(other.previous, other.current, other.sign);
}
if (better)
{
best = id;
best_score = score;
}
}
if (best < 0)
return false;
selected->clear();
selected->push_back(start + static_cast<std::size_t>(last));
for (int32_t id = best; id >= 0; id = states[static_cast<std::size_t>(id)].parent)
selected->push_back(start + static_cast<std::size_t>(states[static_cast<std::size_t>(id)].previous));
std::reverse(selected->begin(), selected->end());
return true;
}
bool optimizeSwingChain(const RawChain& raw, const std::vector<Point2>& greedy, const SwingSearch& search, SwingStats* stats,
std::vector<Point2>* vertices, std::vector<std::size_t>* indices)
{
const std::vector<std::size_t> pairs = oppositePairs(greedy);
if (pairs.empty())
return false;
std::vector<std::size_t> greedy_indices;
if (!locateGreedy(raw.vertices, greedy, &greedy_indices))
return false;
// Each swing searches its whole free run, from the lane point before it to the lane point after it.
std::vector<std::pair<std::size_t, std::size_t>> windows;
const std::size_t raw_count = raw.vertices.size();
for (std::size_t j : pairs)
{
std::size_t left = 0;
for (std::size_t i = greedy_indices[j] + 1; i-- > 0;)
{
if (raw.locked[i] != 0)
{
left = i;
break;
}
}
std::size_t right = raw_count - 1;
for (std::size_t i = greedy_indices[j + 1]; i < raw_count; ++i)
{
if (raw.locked[i] != 0)
{
right = i;
break;
}
}
if (right - left + 1 > kMaxRawVertices)
{
left = greedy_indices[j >= 2 ? j - 2 : 0];
right = greedy_indices[std::min(greedy_indices.size() - 1, j + 3)];
++stats->trimmed_windows;
}
windows.emplace_back(left, right);
}
std::sort(windows.begin(), windows.end());
std::vector<std::pair<std::size_t, std::size_t>> merged;
for (const auto& window : windows)
{
if (!merged.empty() && window.first <= merged.back().second)
merged.back().second = std::max(window.second, merged.back().second);
else
merged.push_back(window);
}
std::vector<std::size_t> chosen = greedy_indices;
for (const auto& window : merged)
{
++stats->windows;
const std::size_t left = window.first, right = window.second;
if (right - left + 1 > kMaxRawVertices)
{
++stats->oversize_windows;
continue;
}
std::vector<Point2> before, after;
for (std::size_t i : chosen)
{
if (i < left)
before.push_back(raw.vertices[i]);
else if (i > right)
after.push_back(raw.vertices[i]);
}
const bool has_before = !before.empty(), has_after = !after.empty();
const Point2 previous = has_before ? before.back() : Point2{};
const Point2 next = has_after ? after.front() : Point2{};
before.push_back(raw.vertices[left]);
after.insert(after.begin(), raw.vertices[right]);
const std::vector<int> before_signs = turnSigns(before);
const std::vector<int> after_signs = turnSigns(after);
std::vector<std::size_t> selected;
if (!solveSwingWindow(raw.vertices, raw.locked, left, right, search, has_before ? &previous : nullptr,
before_signs.empty() ? 0 : before_signs.back(), has_after ? &next : nullptr,
after_signs.empty() ? 0 : after_signs.front(), stats, &selected))
continue;
std::set<std::size_t> updated(selected.begin(), selected.end());
for (std::size_t i : chosen)
if (i < left || i > right)
updated.insert(i);
chosen.assign(updated.begin(), updated.end());
}
if (chosen == greedy_indices)
return false;
vertices->clear();
for (std::size_t i : chosen)
vertices->push_back(raw.vertices[i]);
*indices = chosen;
return true;
}
} // namespace lane_route_core

File diff suppressed because it is too large Load Diff

354
tools/lane_route_eval.cpp Normal file
View File

@@ -0,0 +1,354 @@
/** Offline batch runner: plans scenes from text files and writes one JSON line per query, for comparison
* with the Python prototype. Usage:
* lane_route_eval <scenes.txt> <out.jsonl> <profile sehc|kit|hook_150> <deviations, e.g. 90,45> <ladder, e.g. 0.01 or none> [graph|fallback|lattice]
* Each scenes.txt line: id grid_file variant live_file|- has_start_yaw sx sy syaw has_goal_yaw gx gy gyaw box_count {x0 y0 x1 y1}
* Grid files are kept in memory, so scenes that share one map also share its graphs, as on the robot. */
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/route_planner.h>
#include <lane_route_core/costmap_backend.h>
using namespace lane_route_core;
namespace
{
using Clock = std::chrono::steady_clock;
double msSince(Clock::time_point begin) { return std::chrono::duration<double, std::milli>(Clock::now() - begin).count(); }
std::vector<uint8_t> readRuns(std::istream& in, const std::string& name)
{
std::string key;
std::size_t runs = 0;
in >> key >> runs;
if (key != name)
throw std::runtime_error("expected " + name + ", got " + key);
std::vector<uint8_t> out;
for (std::size_t i = 0; i < runs; ++i)
{
int value = 0;
std::size_t count = 0;
in >> value >> count;
out.insert(out.end(), count, static_cast<uint8_t>(value));
}
return out;
}
/** One map: compile grid, live grid, direction grids and the cached graphs per direction grid and limit. */
struct MapData
{
int32_t width = 0, height = 0;
double resolution = 0.0, origin_x = 0.0, origin_y = 0.0;
std::vector<uint8_t> static_cost; // No inflation, as the static layer provides.
std::vector<uint8_t> live_cost; // Master: with the inscribed ring and soft values.
std::vector<std::vector<uint8_t>> directions;
std::vector<uint16_t> clearance_mm;
double step1_ms = 0.0;
std::map<int, CoarseGraph> coarse;
std::map<std::pair<int, double>, std::shared_ptr<const CompiledGraph>> graphs;
};
std::shared_ptr<MapData> loadMap(const std::string& path, const robot_costmap_2d::ReferenceGraphParams& ridge_params)
{
std::ifstream in(path);
if (!in)
throw std::runtime_error("cannot open " + path);
auto map = std::make_shared<MapData>();
std::string key;
int version = 0, variants = 0;
in >> key >> version;
in >> key >> map->width >> map->height;
in >> key >> map->resolution;
in >> key >> map->origin_x >> map->origin_y;
map->live_cost = readRuns(in, "cost");
in >> key >> variants;
for (int i = 0; i < variants; ++i)
map->directions.push_back(readRuns(in, "direction"));
if (!in)
throw std::runtime_error("truncated grid " + path);
map->static_cost = map->live_cost;
for (uint8_t& value : map->static_cost)
if (value == kInscribedCost)
value = kFreeSpace;
GridRef grid;
grid.width = map->width;
grid.height = map->height;
grid.resolution = map->resolution;
grid.origin_x = map->origin_x;
grid.origin_y = map->origin_y;
grid.cost = map->static_cost.data();
const Clock::time_point began = Clock::now();
robot_costmap_2d::ReferenceGridView view;
view.cost = grid.cost;
view.geometry = geometryOf(grid);
map->clearance_mm = robot_costmap_2d::computeVoronoiSkeleton(view, ridge_params).clearance_mm;
map->step1_ms = msSince(began);
return map;
}
GridRef gridOf(const MapData& map, const std::vector<uint8_t>& cost, const uint16_t* clearance, int variant)
{
GridRef grid;
grid.width = map.width;
grid.height = map.height;
grid.resolution = map.resolution;
grid.origin_x = map.origin_x;
grid.origin_y = map.origin_y;
grid.cost = cost.data();
grid.clearance_mm = clearance;
grid.direction = map.directions[static_cast<std::size_t>(variant)].data();
return grid;
}
/** Offline tuning without a rebuild: LANE_ROUTE_EVAL_SET="name=value,name=value" overrides lattice and fallback fields.
* Unknown names are an error, so a typo cannot silently run the defaults. */
void applyOverrides(PlannerConfig* config)
{
const char* text = std::getenv("LANE_ROUTE_EVAL_SET");
if (text == nullptr || *text == '\0')
return;
const std::map<std::string, double*> doubles{
{ "lattice_closed_resolution_m", &config->lattice_closed_resolution_m },
{ "lattice_heuristic_weight", &config->lattice_heuristic_weight },
{ "lattice_bucket_width_m", &config->lattice_bucket_width_m },
{ "lattice_field_clearance_weight_m", &config->lattice_field_clearance_weight_m },
{ "lattice_wall_weight_m", &config->lattice_wall_weight_m },
{ "lattice_switch_cost_m", &config->lattice_switch_cost_m },
{ "lattice_steer_cost_m", &config->lattice_steer_cost_m },
{ "lattice_analytic_radius_m", &config->lattice_analytic_radius_m },
{ "lattice_analytic_near_goal_m", &config->lattice_analytic_near_goal_m },
{ "lattice_field_time_fraction", &config->lattice_field_time_fraction },
{ "fallback_time_limit_s", &config->fallback_time_limit_s },
{ "lattice_end_relax_radius_m", &config->lattice_end_relax_radius_m },
};
const std::map<std::string, int*> ints{
{ "lattice_heading_bins", &config->lattice_heading_bins },
{ "lattice_primitive_multiple_2", &config->lattice_primitive_multiple_2 },
{ "lattice_primitive_multiple_3", &config->lattice_primitive_multiple_3 },
{ "lattice_analytic_interval", &config->lattice_analytic_interval },
{ "lattice_analytic_goal_headings", &config->lattice_analytic_goal_headings },
{ "lattice_field_cell_factor", &config->lattice_field_cell_factor },
};
const std::map<std::string, int64_t*> longs{
{ "lattice_field_max_cells", &config->lattice_field_max_cells },
{ "lattice_max_memory_mb", &config->lattice_max_memory_mb },
};
std::stringstream stream(text);
std::string item;
while (std::getline(stream, item, ','))
{
const std::size_t equals = item.find('=');
if (equals == std::string::npos)
throw std::runtime_error("bad LANE_ROUTE_EVAL_SET item: " + item);
const std::string key = item.substr(0, equals);
const std::string value = item.substr(equals + 1);
if (doubles.count(key) != 0)
*doubles.at(key) = std::stod(value);
else if (ints.count(key) != 0)
*ints.at(key) = std::stoi(value);
else if (longs.count(key) != 0)
*longs.at(key) = std::stoll(value);
else
throw std::runtime_error("unknown LANE_ROUTE_EVAL_SET key: " + key);
std::cerr << "override " << key << "=" << value << std::endl;
}
}
std::vector<double> parseList(const std::string& text)
{
std::vector<double> out;
if (text == "none")
return out;
std::stringstream stream(text);
std::string item;
while (std::getline(stream, item, ','))
out.push_back(std::stod(item));
return out;
}
} // namespace
int main(int argc, char** argv)
{
if (argc != 6 && argc != 7)
{
std::cerr << "usage: lane_route_eval <scenes.txt> <out.jsonl> <sehc|kit|hook_150> <deviations> <ladder|none> [graph|fallback|lattice]" << std::endl;
return 2;
}
const std::string mode = argc == 7 ? argv[6] : "graph";
if (mode != "graph" && mode != "fallback" && mode != "lattice")
{
std::cerr << "invalid tier mode: " << mode << std::endl;
return 2;
}
PlannerConfig config;
config.lattice_enabled = mode != "graph";
if (std::string(argv[3]) == "kit")
{
config.half_x_m = 0.325;
config.half_y_m = 0.345;
config.clearance_hard_m = 0.36;
config.clearance_min_m = 0.36;
config.clearance_preferred_m = 0.625;
config.collision_check_distance_m = 0.53;
}
else if (std::string(argv[3]) == "hook_150")
{
config.half_x_m = 0.511;
config.half_y_m = 0.1955;
config.clearance_hard_m = 0.2305;
config.clearance_min_m = 0.2305;
config.clearance_preferred_m = 0.4955;
config.collision_check_distance_m = 0.603;
}
robot_costmap_2d::ReferenceGraphParams ridge_params = ridgeParams(config);
if (std::string(argv[3]) == "hook_150")
{
ridge_params.min_clearance_m = 0.335;
ridge_params.ridge_min_separation_m = 0.7;
}
config.deviation_ladder_deg = parseList(argv[5]);
const std::vector<double> deviations = parseList(argv[4]);
applyOverrides(&config);
const RidgeBackend backend = makeRidgeBackend(config, ridge_params);
std::ifstream scenes(argv[1]);
std::ofstream out(argv[2]);
if (!scenes || !out)
{
std::cerr << "cannot open input or output" << std::endl;
return 2;
}
out.precision(17);
std::map<std::string, std::shared_ptr<MapData>> maps;
std::string line;
while (std::getline(scenes, line))
{
if (line.empty())
continue;
std::istringstream row(line);
std::string id, grid_file, live_file;
int variant = 0, has_start = 0, has_goal = 0, boxes = 0;
RouteRequest request;
request.lattice_only = mode == "lattice";
row >> id >> grid_file >> variant >> live_file >> has_start >> request.start.x >> request.start.y >> request.start.yaw >> has_goal >>
request.goal.x >> request.goal.y >> request.goal.yaw >> boxes;
request.start.has_yaw = has_start != 0;
request.goal.has_yaw = has_goal != 0;
auto& map = maps[grid_file];
if (map == nullptr)
map = loadMap(grid_file, ridge_params);
// Live master: a recorded merged grid, or the map with boxes painted lethal.
std::vector<uint8_t> live_cost = map->live_cost;
if (live_file != "-")
{
std::ifstream live(live_file);
live_cost = readRuns(live, "cost");
}
const double resolution = map->resolution;
for (int b = 0; b < boxes; ++b)
{
double x_min, y_min, x_max, y_max;
row >> x_min >> y_min >> x_max >> y_max;
const int32_t x0 = std::max<int32_t>(0, static_cast<int32_t>(std::floor((x_min - map->origin_x) / resolution)));
const int32_t x1 = std::min<int32_t>(map->width, static_cast<int32_t>(std::ceil((x_max - map->origin_x) / resolution)));
const int32_t y0 = std::max<int32_t>(0, static_cast<int32_t>(std::floor((y_min - map->origin_y) / resolution)));
const int32_t y1 = std::min<int32_t>(map->height, static_cast<int32_t>(std::ceil((y_max - map->origin_y) / resolution)));
for (int32_t y = y0; y < y1; ++y)
for (int32_t x = x0; x < x1; ++x)
live_cost[static_cast<std::size_t>(y * map->width + x)] = kLethalCost;
}
const GridRef compile_grid = gridOf(*map, map->static_cost, map->clearance_mm.data(), variant);
const Clock::time_point update_began = Clock::now();
const GridRef unpatched = gridOf(*map, live_cost, map->clearance_mm.data(), variant);
request.changed_boxes = changedBoxes(map->static_cost.data(), unpatched);
std::vector<uint16_t> patched;
const uint16_t* live_clearance = map->clearance_mm.data();
if (!request.changed_boxes.empty())
{
patchClearance(map->static_cost.data(), map->clearance_mm.data(), unpatched, 1.5, &patched);
live_clearance = patched.data();
}
const double update_ms = msSince(update_began);
const GridRef live_grid = gridOf(*map, live_cost, live_clearance, variant);
double coarse_ms = 0.0;
const CoarseGraph* coarse = nullptr;
if (mode != "lattice")
{
auto found = map->coarse.find(variant);
if (found == map->coarse.end())
{
const Clock::time_point began = Clock::now();
found = map->coarse.emplace(variant, buildCoarseGraph(compile_grid, config, ridge_params)).first;
coarse_ms = msSince(began);
}
coarse = &found->second;
}
for (double deviation : deviations)
{
config.max_deviation_deg = deviation;
const GraphProvider provider = [&](double limit) -> std::shared_ptr<const CompiledGraph> {
if (coarse == nullptr) return {};
auto& slot = map->graphs[std::make_pair(variant, limit)];
if (slot == nullptr)
slot = std::make_shared<const CompiledGraph>(compileGraph(*coarse, compile_grid, compile_grid.cost, limit, config, backend));
return slot;
};
const PlanResult result = planRoute(provider, request, live_grid, config, backend);
const PlanInfo& info = result.info;
out << "{\"scene\":\"" << id << "\",\"dev\":" << deviation << ",\"ok\":" << (result.ok ? 1 : 0) << ",\"reason\":\"" << info.reason
<< "\",\"query_ms\":" << info.query_ms << ",\"compile_ms\":" << info.compile_ms << ",\"coarse_ms\":" << coarse_ms
<< ",\"update_ms\":" << update_ms << ",\"search_ms\":" << info.search_ms << ",\"build_ms\":" << info.build_ms
<< ",\"verify_ms\":" << info.verify_ms << ",\"live_ridge_ms\":" << info.live_ridge_ms << ",\"live_ridge\":\"" << info.live_ridge
<< "\",\"rung\":" << info.rung_used_deg << ",\"retries\":" << info.retries << ",\"gap_failures\":" << info.gap_failures
<< ",\"soft_ignored\":" << (info.soft_cost_ignored ? 1 : 0) << ",\"raise\":" << info.gap_shortcut_raise_m
<< ",\"swing_windows\":" << info.swing_windows << ",\"swing_checks\":" << info.swing_line_checks
<< ",\"swing_builds\":" << info.swing_builds << ",\"swing_selected\":" << info.swing_selected;
if (result.ok)
{
out << ",\"min_gap\":" << info.min_gap_m << ",\"exempt\":" << (info.gap_exemption_used ? 1 : 0) << ",\"kinks\":" << result.check.kinks
<< ",\"crossings\":" << result.check.self_crossings << ",\"zone_violations\":" << result.check.zone_violations
<< ",\"collisions\":" << result.check.footprint_collisions << ",\"path\":[";
for (std::size_t i = 0; i < result.path.size(); ++i)
{
const PathPoint& p = result.path[i];
out << (i > 0 ? "," : "") << "[" << p.x << "," << p.y << "," << p.yaw << "]";
}
out << "]";
}
out << ",\"tier\":\"" << info.tier_used << "\",\"graph_reason\":\"" << info.graph_reason
<< "\",\"lattice_reason\":\"" << info.lattice_reason << "\",\"lattice_states_expanded\":" << info.lattice_states_expanded
<< ",\"lattice_pose_checks\":" << info.lattice_pose_checks << ",\"lattice_field_cells\":" << info.lattice_field_cells
<< ",\"lattice_tiles_built\":" << info.lattice_tiles_built << ",\"lattice_peak_bytes\":" << info.lattice_peak_bytes
<< ",\"lattice_crossing_rejects\":" << info.lattice_crossing_rejects
<< ",\"lattice_field_ms\":" << info.lattice_field_ms << ",\"lattice_search_ms\":" << info.lattice_search_ms
<< ",\"lattice_verify_ms\":" << info.lattice_verify_ms
<< ",\"lattice_ms\":" << info.lattice_ms << "}\n";
std::cout << id << " " << deviation << " " << info.reason << " " << info.query_ms << " ms" << std::endl;
}
}
return 0;
}