Files
robot_line_extraction/src/line_extractor.cpp
duongtd 8df353ded6 fix: a merged segment lost the scan it was built from, so pointAt read past the end
The constructor mergeLines uses took only the fitted parameters and the ray
indices, leaving c_data_ and r_data_ default-constructed. pointAt indexes
r_data_.xs directly, so asking a merged segment where one of its own rays is
read past the end of an empty vector.

Two callers already do exactly that. The reflective-tape check walks the ray
span of a wing and reads each point; the arc matcher gathers the points of
adjacent segments to fit a circle to them. The arc matcher is how it surfaced -
it segfaulted, and AddressSanitizer put it on line.cpp:58.

It stayed hidden because mergeLines almost never fires with the default
parameters: a gap wide enough to split at is already wider than max_line_gap,
which is the gate merging has to pass. That is the merge gate working as
intended, and it is also why this could not be reached from a synthesized
scene - a scene-based test here would guard nothing, so the regression test
builds a merged Line directly instead.

The constructor now takes the scan data, like the other one. A merged segment
is still built from the same scan, so there was never a reason for it to lose
it, and a consumer cannot tell a merged segment from a fresh one - the
invariant has to be that every segment answers for every ray it supports.

pointAt also bounds-checks now and returns NaN for a ray it does not carry.
That is a second line of defence, not the fix: every caller already has to
reject non-finite points because a real scan contains them, so a future
constructor that forgets the data degrades instead of reading out of bounds.
2026-08-26 20:09:06 +07:00

428 lines
15 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_line_extraction — split-and-merge over one ordered range scan.
*
* Author: DuongTD
* Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS.
*********************************************************************/
#include <robot_line_extraction/line_extractor.h>
#include <algorithm>
#include <cmath>
#include <Eigen/Dense>
namespace robot_line_extraction
{
namespace
{
/// @brief Mahalanobis-style distance between two lines, given their covariances.
double chiSquared(const Eigen::Vector2d& dL, const Eigen::Matrix2d& P_1, const Eigen::Matrix2d& P_2)
{
return dL.transpose() * (P_1 + P_2).inverse() * dL;
}
/// Two segments merge when their parameters agree this closely relative to their own uncertainty.
/// 3 is roughly the 78% ellipse for two degrees of freedom: loose enough to rejoin one wall broken
/// by a passing reflection, tight enough to leave the two arms of a dock plate apart.
constexpr double kMergeChiSquaredThresh = 3.0;
Eigen::Matrix2d toMatrix(const std::array<double, 4>& covariance)
{
Eigen::Matrix2d P;
P << covariance[0], covariance[1], covariance[2], covariance[3];
return P;
}
} // namespace
bool LineExtractor::configure(const LineExtractionParams& params, std::string& error)
{
if (!params.validate(error))
{
return false; // Keep the previous set; a half-applied parameter block is worse than none.
}
params_ = params;
return true;
}
bool LineExtractor::extract(const ScanGeometry& geometry, const std::vector<double>& ranges,
std::vector<Line>& lines, std::string& error)
{
lines.clear();
if (!geometry.validate(error))
{
return false;
}
if (ranges.size() != geometry.size)
{
error = "ranges.size() (" + std::to_string(ranges.size()) + ") does not match geometry.size (" +
std::to_string(geometry.size) + ")";
return false;
}
// The bearing tables depend only on the layout, which a sensor repeats frame after frame.
// Recomputing a thousand sines every cycle for a constant is exactly the kind of waste a control
// loop cannot afford.
if (!cache_valid_ || geometry_ != geometry)
{
rebuildCache(geometry);
}
projectRanges(ranges);
filtered_indices_ = c_data_.indices;
lines_.clear();
filterCloseAndFarPoints();
filterOutlierPoints();
// Nothing left to fit is a normal answer — an empty room, or a sensor pointed at open space.
if (filtered_indices_.size() <= std::max<std::size_t>(params_.min_line_points, 3))
{
return true;
}
split(filtered_indices_);
filterLines();
// Refine every surviving run. A run that will not converge KEEPS its endpoint fit and stays in
// the output — it only loses its covariance.
//
// Dropping it was wrong and measurably so: on a two-wing dock plate at 2 m, 34 rays, both wings
// split correctly with 17 points each and lengths right to a few millimetres, yet one of the two
// vanished on roughly half the scans because its weighted fit ran out of iterations. Everything
// downstream then saw one line where there were two, and the corner disappeared. Angle, radius,
// endpoints and support are all still good on a failed refinement; only the covariance is not,
// and mergeLines is the only step that reads it.
for (Line& line : lines_)
{
line.leastSqFit();
}
if (lines_.size() > 1)
{
mergeLines();
}
lines = lines_;
return true;
}
// ================================================================================================
// Per-scan preparation
// ================================================================================================
void LineExtractor::rebuildCache(const ScanGeometry& geometry)
{
geometry_ = geometry;
cache_valid_ = true;
const std::size_t n = geometry.size;
c_data_.bearings.resize(n);
c_data_.cos_bearings.resize(n);
c_data_.sin_bearings.resize(n);
c_data_.indices.resize(n);
for (std::size_t i = 0; i < n; ++i)
{
const double bearing = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
c_data_.bearings[i] = bearing;
c_data_.cos_bearings[i] = std::cos(bearing);
c_data_.sin_bearings[i] = std::sin(bearing);
// Identity mapping, and everything downstream depends on it: RangeData is indexed by ray
// number, so xs[i] is only the Cartesian form of ray i while this holds.
c_data_.indices[i] = static_cast<unsigned int>(i);
}
}
void LineExtractor::projectRanges(const std::vector<double>& ranges)
{
r_data_.ranges = ranges;
r_data_.xs.resize(ranges.size());
r_data_.ys.resize(ranges.size());
for (std::size_t i = 0; i < ranges.size(); ++i)
{
r_data_.xs[i] = c_data_.cos_bearings[i] * ranges[i];
r_data_.ys[i] = c_data_.sin_bearings[i] * ranges[i];
}
}
double LineExtractor::distBetweenPoints(unsigned int index_1, unsigned int index_2) const
{
return std::hypot(r_data_.xs[index_1] - r_data_.xs[index_2],
r_data_.ys[index_1] - r_data_.ys[index_2]);
}
// ================================================================================================
// Point filtering
// ================================================================================================
void LineExtractor::filterCloseAndFarPoints()
{
std::vector<unsigned int> output;
output.reserve(filtered_indices_.size());
for (const unsigned int index : filtered_indices_)
{
const double range = r_data_.ranges[index];
// NaN fails both comparisons and is dropped here, which is why a sensor that reports misses as
// NaN needs no special case anywhere else. Infinity fails the upper bound the same way.
if (range >= params_.min_range && range <= params_.max_range)
{
output.push_back(index);
}
}
filtered_indices_ = output;
}
void LineExtractor::filterOutlierPoints()
{
if (filtered_indices_.size() < 3)
{
return;
}
std::vector<unsigned int> output;
output.reserve(filtered_indices_.size());
for (std::size_t i = 0; i < filtered_indices_.size(); ++i)
{
const unsigned int p_i = filtered_indices_[i];
unsigned int p_j = 0;
unsigned int p_k = 0;
if (i == 0)
{
p_j = filtered_indices_[i + 1];
p_k = filtered_indices_[i + 2];
}
else if (i == filtered_indices_.size() - 1)
{
p_j = filtered_indices_[i - 1];
p_k = filtered_indices_[i - 2];
}
else
{
p_j = filtered_indices_[i - 1];
p_k = filtered_indices_[i + 1];
}
if (std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_j]) > params_.outlier_dist &&
std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_k]) > params_.outlier_dist)
{
// Far from both neighbours in range. That is still not enough to call it an outlier: a real
// corner looks the same. Only drop it if it also sits off the line joining those neighbours.
Line line(c_data_, r_data_, params_, { p_j, p_k });
line.endpointFit();
if (line.distToPoint(p_i) > params_.min_split_dist)
{
continue;
}
}
output.push_back(p_i);
}
filtered_indices_ = output;
}
// ================================================================================================
// Splitting
// ================================================================================================
void LineExtractor::split(const std::vector<unsigned int>& indices)
{
// Explicit stack rather than recursion. Depth is bounded only by the ray count, and a noisy scan
// that splits at nearly every point would recurse a thousand deep in the control thread — a
// stack overflow, not a slow frame. Pushing the right half first keeps the output in scan order,
// which mergeLines depends on since it only ever compares neighbours.
std::vector<std::vector<unsigned int>> pending;
pending.push_back(indices);
while (!pending.empty())
{
const std::vector<unsigned int> run = std::move(pending.back());
pending.pop_back();
// A single point is not a line. It reaches here when a gap orphans it, and dropping it is the
// right answer rather than emitting a zero-length segment.
if (run.size() < 2)
{
continue;
}
Line line(c_data_, r_data_, params_, run);
line.endpointFit();
double dist_max = 0.0;
std::size_t i_dist = 0;
bool have_dist = false;
double gap_max = 0.0;
std::size_t i_gap = 0;
bool have_gap = false;
// Interior points only: the endpoints are on the fitted line by construction, so splitting at
// one of them would produce a one-point half and make no progress.
for (std::size_t i = 1; i + 1 < run.size(); ++i)
{
const double dist = line.distToPoint(run[i]);
if (dist > dist_max)
{
dist_max = dist;
i_dist = i;
have_dist = true;
}
}
for (std::size_t i = 0; i + 1 < run.size(); ++i)
{
const double gap = distBetweenPoints(run[i], run[i + 1]);
if (gap > gap_max)
{
gap_max = gap;
i_gap = i;
have_gap = true;
}
}
const bool split_on_dist = have_dist && dist_max >= params_.min_split_dist;
const bool split_on_gap = have_gap && gap_max >= params_.max_line_gap;
if (!split_on_dist && !split_on_gap)
{
lines_.push_back(line);
continue;
}
std::vector<unsigned int> first;
std::vector<unsigned int> second;
if (split_on_dist)
{
// The corner point belongs to BOTH halves. It is the last point of one wall and the first of
// the next, and a dock plate needs each arm to keep its apex endpoint — giving it to one side
// shortens the other arm by a ray and tilts its fit.
first.assign(run.begin(), run.begin() + static_cast<std::ptrdiff_t>(i_dist) + 1);
second.assign(run.begin() + static_cast<std::ptrdiff_t>(i_dist), run.end());
}
else
{
// A gap means the two sides are not the same surface, so nothing is shared across it.
first.assign(run.begin(), run.begin() + static_cast<std::ptrdiff_t>(i_gap) + 1);
second.assign(run.begin() + static_cast<std::ptrdiff_t>(i_gap) + 1, run.end());
}
// Both halves are strictly shorter than the run, so this always terminates. Upstream sliced
// with `&indices[i_split - 1]` and `&indices.back()`, which silently dropped a point off each
// half at every split — the arms of anything angular came out a ray short on both ends.
pending.push_back(std::move(second));
pending.push_back(std::move(first));
}
}
// ================================================================================================
// Line filtering and merging
// ================================================================================================
void LineExtractor::filterLines()
{
std::vector<Line> output;
output.reserve(lines_.size());
for (const Line& line : lines_)
{
if (line.length() >= params_.min_line_length && line.numPoints() >= params_.min_line_points)
{
output.push_back(line);
}
}
lines_ = output;
}
void LineExtractor::mergeLines()
{
std::vector<Line> merged_lines;
merged_lines.reserve(lines_.size());
for (std::size_t i = 1; i < lines_.size(); ++i)
{
// Đoạn không hội tụ mang hiệp phương sai vô nghĩa, mà bước gộp quyết định BẰNG hiệp phương sai.
// Không gộp nó — giữ nguyên đoạn còn hơn gộp theo một con số không có cơ sở.
if (!lines_[i - 1].hasCovariance() || !lines_[i].hasCovariance())
{
merged_lines.push_back(lines_[i - 1]);
if (i == lines_.size() - 1)
{
merged_lines.push_back(lines_[i]);
}
continue;
}
const Eigen::Vector2d L_1(lines_[i - 1].getRadius(), lines_[i - 1].getAngle());
const Eigen::Vector2d L_2(lines_[i].getRadius(), lines_[i].getAngle());
const Eigen::Matrix2d P_1 = toMatrix(lines_[i - 1].getCovariance());
const Eigen::Matrix2d P_2 = toMatrix(lines_[i].getCovariance());
// Two conditions, and the second is not upstream's. Merging on line parameters alone rejoins
// anything collinear no matter how far apart, so a wall either side of a doorway comes back as
// one segment spanning the doorway — and split had already separated them for exactly that
// reason. Requiring the facing endpoints to be within max_line_gap makes split and merge agree
// on what "one surface" means, so a gap that forced a split cannot be undone here. It also
// stops a later consumer measuring a bridged segment: a dock detector checking wing length
// would otherwise accept one.
const double endpoint_gap = std::hypot(lines_[i].getStart()[0] - lines_[i - 1].getEnd()[0],
lines_[i].getStart()[1] - lines_[i - 1].getEnd()[1]);
// Góc giữa hai đường, quy về (-pi, pi]. Đây là cổng CHÍNH chống gộp qua một góc thật: chi-squared
// so tham số theo hiệp phương sai của chính chúng, mà trên một đoạn mươi tia thì hiệp phương sai
// đủ rộng để hai bức tường vuông góc "không phân biệt được", và góc biến mất.
const double angle_gap = std::fabs(piToPi(lines_[i].getAngle() - lines_[i - 1].getAngle()));
if (angle_gap <= params_.merge_max_angle && endpoint_gap <= params_.max_line_gap &&
chiSquared(L_1 - L_2, P_1, P_2) < kMergeChiSquaredThresh)
{
const Eigen::Matrix2d P_m = (P_1.inverse() + P_2.inverse()).inverse();
const Eigen::Vector2d L_m = P_m * (P_1.inverse() * L_1 + P_2.inverse() * L_2);
const std::array<double, 4> cov{ { P_m(0, 0), P_m(0, 1), P_m(1, 0), P_m(1, 1) } };
// Concatenate the support of both. Upstream called resize() and then inserted at end(),
// which left the first half of the vector zero-filled and doubled numPoints() — a merged
// line then reported twice its real support, and every index in the first half read ray 0.
const std::vector<unsigned int>& ind_1 = lines_[i - 1].getIndices();
const std::vector<unsigned int>& ind_2 = lines_[i].getIndices();
std::vector<unsigned int> indices;
indices.reserve(ind_1.size() + ind_2.size());
indices.insert(indices.end(), ind_1.begin(), ind_1.end());
indices.insert(indices.end(), ind_2.begin(), ind_2.end());
Line merged_line(c_data_, r_data_, L_m[1], L_m[0], cov, lines_[i - 1].getStart(),
lines_[i].getEnd(), indices);
merged_line.projectEndpoints();
lines_[i] = merged_line;
}
else
{
merged_lines.push_back(lines_[i - 1]);
}
if (i == lines_.size() - 1)
{
merged_lines.push_back(lines_[i]);
}
}
lines_ = merged_lines;
}
} // namespace robot_line_extraction