Files
lane_route_core/src/route_planner.cpp
duongtd 4453f454a9 feat(lane_route): footprint standability, unknown cells in graph gap (R2.8)
- Standability: a cell is passable for the graph length reference and the
  lattice heuristic field only when the footprint plus the minimum gap fits
  at one of 16 headings; memoised per 32x32 tile, open space skips the test.
- Graph reference no longer cuts diagonal corners; route_too_long reports
  the reference length.
- Lattice field: coarse block passability decided lazily on first touch.
- ReferenceMemo: one route_too_long reference search per core pass instead
  of one per candidate.
- Graph tier counts unknown cells as obstacles for the footprint gap, like
  the lattice (user ruling 10/11).
- PlanInfo and eval JSON: standability counters, graph reference length.
2026-11-10 10:01:39 +07:00

354 lines
15 KiB
C++

#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;
namespace
{
// A tight-corner graph path replaces a large-radius one only when it is at least this much shorter, so a large radius stays the
// default shape and a tight corner appears where it removes a real detour.
constexpr double kTightMinSaving = 0.2;
double polylineLength(const Path& path)
{
double length = 0.0;
for (std::size_t i = 1; i < path.size(); ++i)
length += std::hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y);
return length;
}
} // namespace
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";
}
if (result.ok)
{
int previous_sign = 0;
double straight = 0.0;
for (std::size_t i = 1; i < result.path.size(); ++i)
{
const PathPoint& a = result.path[i - 1];
const PathPoint& b = result.path[i];
const double length = std::hypot(b.x - a.x, b.y - a.y);
if (length < 1e-9) continue;
const double turn = wrapAngle(b.yaw - a.yaw);
const double arc = std::abs(turn) < 1e-9 ? length : length * std::abs(turn) / (2.0 * std::abs(std::sin(turn / 2.0)));
result.info.path_length_m += arc;
const double curvature = turn / arc;
const int sign = curvature > 0.001 ? 1 : curvature < -0.001 ? -1 : 0;
if (sign == 0) straight += arc;
else
{
if (previous_sign != 0 && sign != previous_sign) ++result.info.curvature_sign_changes;
previous_sign = sign;
}
}
if (result.info.path_length_m > 0.0) result.info.straight_share = straight / result.info.path_length_m;
}
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);
// Radius ladder. The first graph pass and the lattice use only radii at or above regular_turn_radius_m, which is how every
// tier planned before the floor could be lowered. A lower min_turn_radius_m only adds a second graph pass with all corner
// radii, for a failed first pass or a long detour (measured 9/11: letting the route search and the lattice use the low floor
// from the start lost 25 to 84 regress7 queries).
PlannerConfig regular = config;
regular.min_turn_radius_m = std::max(config.regular_turn_radius_m, config.min_turn_radius_m);
regular.corner_radii_m.clear();
for (double radius : config.corner_radii_m)
if (radius >= regular.min_turn_radius_m - 1e-9)
regular.corner_radii_m.push_back(radius);
if (regular.corner_radii_m.empty())
regular.corner_radii_m.push_back(regular.min_turn_radius_m);
regular.max_kink_deg = 0.0;
// The second pass adds the tight radii and, at its bottom, sharp corners up to max_kink_deg.
const bool tight_corners = config.min_turn_radius_m < regular.min_turn_radius_m - 1e-9 || config.max_kink_deg > 0.0;
const PlannerConfig& lattice_config = config.lattice_tight_arcs ? config : regular;
const double chord = std::hypot(request.goal.x - request.start.x, request.goal.y - request.start.y);
// 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, tight_corners ? regular : config, backend },
{ result.path, result.check, result.info });
const bool detour = graph_ok && polylineLength(result.path) > config.suspicious_ratio * chord + config.suspicious_margin_m;
const bool stopped = (request.cancel && request.cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline ||
result.info.reason == "timeout" || result.info.reason == "no_route_enclosed";
if (tight_corners && (!graph_ok || detour) && !stopped)
{
Path tight_path;
PathCheck tight_check;
PlanInfo tight_info = result.info;
tight_info.live_ridge.clear();
const bool tight_ok = detail::planGraphTier({ *graph, request, live, deadline, config, backend },
{ tight_path, tight_check, tight_info });
// A tight corner must buy a clearly shorter path; otherwise the large-radius shape stays.
if (tight_ok && (!graph_ok || polylineLength(tight_path) < (1.0 - kTightMinSaving) * polylineLength(result.path)))
{
result.path = std::move(tight_path);
result.check = tight_check;
result.info = tight_info;
result.info.graph_radius_pass = "tight";
graph_ok = true;
}
else if (!graph_ok)
{
result.info = tight_info;
}
else
{
// Preserve diagnostics from the tight attempt even when the regular path is kept.
result.info.graph_standability_tests = tight_info.graph_standability_tests;
result.info.graph_standability_rejected = tight_info.graph_standability_rejected;
result.info.graph_reference_length_m = tight_info.graph_reference_length_m;
}
}
if (graph_ok && result.info.graph_radius_pass.empty())
result.info.graph_radius_pass = "regular";
}
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, lattice_config, deviation, rung_deadline, fallback_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