Files
lane_route_core/src/lattice_cspace.cpp
duongtd b0a3954541 feat(lane_route): smooth lattice paths (R2) and expose the lattice tier in the plugin (R3)
- lane_route_core: port of the S3 smoother for lattice paths (direct,
  greedy and bounded graph improvement over witness anchors, then
  clothoid corners when budget remains), shape metrics and smoother
  diagnostics in PlanInfo and lane_route_eval.
- lane_route_planner: loads the lattice keys from YAML, logs a config
  summary at start-up and one debug/fallback line per lattice request.

regress7: coverage unchanged from R1, every lattice path smoothed, 0 bad
in the independent recheck. Local snapshot for history only; not pushed.
2026-11-09 16:11:34 +07:00

265 lines
13 KiB
C++

#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;
if (context_.smooth_checks) ++*context_.smooth_checks;
else ++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