#include "route_planner_internal.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace lane_route_core { namespace detail { namespace { 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; } double segmentDistanceSquared(const Point2& p, const Point2& a, const Point2& b) { const double dx = b.x - a.x, dy = b.y - a.y; const double squared = dx * dx + dy * dy; const double t = squared > 0.0 ? std::clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / squared, 0.0, 1.0) : 0.0; const double x = a.x + t * dx - p.x, y = a.y + t * dy - p.y; return x * x + y * y; } /** 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* changed, TimePoint deadline, bool allow_soft_fallback, const GridRef& verify_grid, const PlannerConfig& config, Path* path, PathCheck* check, PlanInfo* info, const std::atomic* cancel, GraphTrace* trace, const char* trace_source) { 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(grid.width) * static_cast(grid.height); const double max_straight_m = std::hypot(static_cast(grid.height), static_cast(grid.width)) * grid.resolution; QueryGraph query(graph, grid, config.zone_deviation_weight); 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 neutral; std::vector 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 blocked(static_cast(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(i)] = 1; } } GraphTraceRun* trace_run = nullptr; if (trace != nullptr) { trace->runs.emplace_back(); trace_run = &trace->runs.back(); trace_run->deviation_deg = dev; trace_run->min_turn_radius_m = config.min_turn_radius_m; trace_run->max_kink_deg = config.max_kink_deg; trace_run->voronoi_weight = kVoronoiWeight; trace_run->corner_radii_m = config.corner_radii_m; trace_run->source = trace_source; trace_run->base_nodes = query.baseNodes(); trace_run->base_edges = query.baseEdges(); trace_run->start_node = s; trace_run->goal_node = g; trace_run->nodes.reserve(static_cast(query.nodeCount())); trace_run->edges.reserve(static_cast(query.edgeCount())); for (int32_t i = 0; i < query.nodeCount(); ++i) trace_run->nodes.push_back(query.node(i)); for (int32_t i = 0; i < query.edgeCount(); ++i) trace_run->edges.push_back(query.edge(i)); trace_run->factors = factors; for (int32_t i = 0; i < query.edgeCount(); ++i) if (blocked[static_cast(i)] != 0) trace_run->initially_blocked_edges.push_back(i); } std::string reason; std::vector route; CandidateHistory candidates_seen; 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)); if (trace_run != nullptr) trace_run->neutral_factors = factors; reason.clear(); } std::set> blocked_pairs; for (int attempt = 0; attempt < config.max_route_attempts; ++attempt) { GraphTraceAttempt* trace_attempt = nullptr; if (trace_run != nullptr) { trace_run->attempts.emplace_back(); trace_attempt = &trace_run->attempts.back(); trace_attempt->pass = pass; trace_attempt->attempt = attempt; } const auto trace_reason = [&](const auto& value) { if (trace_attempt != nullptr) { trace_attempt->reason = value; if (trace_attempt->reason.empty()) trace_attempt->reason = "unspecified_rejection"; } }; if (context.expired()) { reason = "timeout"; if (trace_attempt != nullptr) trace_reason(context.cancel && context.cancel->load(std::memory_order_relaxed) ? "cancelled" : reason); 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 (trace_attempt != nullptr && found) trace_attempt->route = route; if (!found) { if (context.cancel && context.cancel->load(std::memory_order_relaxed)) { trace_reason("cancelled"); 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"; if (trace_attempt != nullptr) trace_reason(reason.empty() ? "search_exhausted" : "search_exhausted: " + reason); 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) { if (trace_attempt != nullptr) trace_attempt->rejected_edge = bad; blocked[static_cast(bad)] = 1; ++info->retries; reason = "edge_blocked"; trace_reason(reason); 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"; trace_reason(reason); break; } std::string why = candidate.why.reason; bool has_corner = candidate.why.has_corner; const Point2 corner = candidate.why.corner; bool has_failure_location = false; Point2 failure_location{}; const bool duplicate = candidate.ok && candidates_seen.seenOrRemember(candidate.path); if (duplicate) { const auto previous = candidates_seen.failure(candidate.path); why = previous.reason.empty() ? "independent_verification_failed" : previous.reason; has_failure_location = previous.located; failure_location = previous.location; has_corner = false; } if (candidate.ok && !duplicate) { if (trace_attempt != nullptr) trace_attempt->candidate_length_m = pathLength(candidate.path); timer = Clock::now(); PathCheck path_check = verifyPath(candidate.path, verify_grid, dev, config, context.cancel, &deadline); has_failure_location = path_check.has_failure_location; failure_location = path_check.failure_location; if (trace_attempt != nullptr) { trace_attempt->zone_violations = path_check.zone_violations; trace_attempt->footprint_collisions = path_check.footprint_collisions; trace_attempt->has_failure_location = has_failure_location; trace_attempt->failure_location = failure_location; } 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; trace_reason(reason); break; } bool gap_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, nullptr, true); 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 || candidates_seen.seenOrRemember(alternative.path)) continue; timer = Clock::now(); const PathCheck alternative_check = verifyPath(alternative.path, verify_grid, dev, config, context.cancel, &deadline); 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, nullptr, true); info->verify_ms += msSince(timer); if (!usable) continue; if (!alternative_gap.valid) { ++info->gap_failures; continue; } const double length = pathLength(alternative.path); candidate = std::move(alternative); if (trace_attempt != nullptr) trace_attempt->candidate_length_m = length; path_check = alternative_check; if (trace_attempt != nullptr) { trace_attempt->zone_violations = path_check.zone_violations; trace_attempt->footprint_collisions = path_check.footprint_collisions; } gap = alternative_gap; ends_ok = true; clear_ok = true; raise_used = extra; break; } if (context.expired()) { reason = "timeout"; trace_reason(reason); break; } } const bool passed = path_check.valid && ends_ok && clear_ok && gap_checked && gap.valid; // The 2D reference does not prove a forward, footprint-zone-legal shortcut exists. // A ratio against it therefore cannot invalidate a fully verified candidate. 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; trace_reason("verified"); 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"; candidates_seen.setFailure(candidate.path, {why, has_failure_location, failure_location}); has_corner = false; } if (candidate.vertices.empty()) { reason = why; trace_reason(reason); break; } std::vector> pairs; if (!has_corner) { // A shortcut may span several edges. Change the transition nearest the failure without // declaring either entire edge illegal for other routes. if (route.size() > 1) { std::size_t index = std::min(static_cast(attempt), route.size() - 2); if (has_failure_location) { double nearest = kInfinity; for (std::size_t j = 0; j < route.size(); ++j) { const auto& points = query.edge(route[j]).points; for (std::size_t k = 1; k < points.size(); ++k) { const double d = segmentDistanceSquared(failure_location, points[k-1], points[k]); if (d < nearest) { nearest = d; index = std::min(j, 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()) { if (!has_corner && route.size() == 1) { blocked[static_cast(route.front())] = 1; if (trace_attempt != nullptr) trace_attempt->rejected_edge = route.front(); ++info->retries; reason = why; trace_reason(reason); continue; } reason = why; trace_reason(reason); break; } blocked_pairs.insert(pairs.begin(), pairs.end()); if (trace_attempt != nullptr) trace_attempt->blocked_pairs_added = pairs; ++info->retries; reason = why; trace_reason(reason); } } 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, GraphTrace* trace) { const std::vector* 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, trace, "compiled")) 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(0, static_cast(std::floor((std::min(request.start.x, request.goal.x) - pad - live.origin_x) / resolution))); const int32_t x1 = std::min(live.width, static_cast(std::ceil((std::max(request.start.x, request.goal.x) + pad - live.origin_x) / resolution))); const int32_t y0 = std::max(0, static_cast(std::floor((std::min(request.start.y, request.goal.y) - pad - live.origin_y) / resolution))); const int32_t y1 = std::min(live.height, static_cast(std::ceil((std::max(request.start.y, request.goal.y) + pad - live.origin_y) / resolution))); const int64_t width = std::max(0, x1 - x0); const int64_t height = std::max(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(width * height); std::vector window_cost(cells), window_direction; std::vector 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((y + y0) * live.width + x0); const std::size_t to = static_cast(y * width); const std::size_t count = static_cast(width); std::copy_n(live.cost + from, count, window_cost.begin() + static_cast(to)); std::copy_n(live.clearance_mm + from, count, window_clearance.begin() + static_cast(to)); if (live.direction != nullptr) std::copy_n(live.direction + from, count, window_direction.begin() + static_cast(to)); } GridRef window; window.width = static_cast(width); window.height = static_cast(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, trace, "live_ridge"); } info->retries += live_info.retries; info->gap_failures += live_info.gap_failures; info->graph_standability_tests += live_info.graph_standability_tests; info->graph_standability_rejected += live_info.graph_standability_rejected; if (live_info.graph_reference_length_m > 0.0) info->graph_reference_length_m = live_info.graph_reference_length_m; 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, input.trace); } } // namespace detail } // namespace lane_route_core