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

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