Find a dock plate in a laser scan and say where the robot must stop

The detection chain had a gap between line segments and a navigation goal.
This is that step: segments plus the geometry of one charger, out comes the
pose base_link has to reach, in the scan's own frame.

Pure geometry, no TF and no action, so it is testable the same way the line
extractor is - build the world, cast the rays, and the answer is known before
the code runs. The tests exercise the real chain end to end, from synthetic
world through robot_line_extraction into the matcher.

The output is the goal pose, not the charger's pose. dock_planner deliberately
carries no standoff key: it derives which edge of the robot meets the dock from
which side of the goal the robot stands on, and that only works because the
goal already is where base_link must end up. The standoff is also a property of
the charger - how deep its contacts sit - so it belongs to the profile.
apex_x/apex_y keep the pre-offset vertex, because a wrong offset and a wrong
detection look identical from the final pose alone.

Matching a V:

The vertex is the intersection of the two fitted lines, not the midpoint of
their endpoints. A line is a least-squares fit over tens of rays; an endpoint
is one ray and much noisier.

Both segments must END near that intersection. Any two non-parallel walls cross
somewhere, and without this gate a corridor corner reads as a dock.

The vertex angle is measured between the two wing vectors from the apex, not
between the two normals. The two agree at exactly 90 degrees and diverge
everywhere else, so confusing them is a silent error at every other opening.

Wing length is what rejects a pallet corner: a pallet has a perfect right
angle, it just has metre-long sides.

Yaw is the bisector pointing back at the sensor, and its sign is chosen by
comparing against the sensor position rather than by the order of the two
wings. That order flips with which side the robot approaches from, and being
180 degrees out here means reversing into the plate instead of driving in.

Confidence is the worst of the three criteria, not their mean. A mean lets a
shape with a badly wrong angle through on the strength of the other two.

The search gate is not optional in a warehouse: any two perpendicular pallets
are a V. candidate_count reports how many survived every gate, so an ambiguous
scene is visible to the layer above rather than silently resolved.

A failed detection reports which gate it failed. "Nothing there" and "something
there but the wrong length" need opposite responses, and one failure line
cannot carry that.

Declaring a pattern that is not implemented is refused at configure time.
Accepting it would produce a detector that never finds anything, which looks
exactly like a charger out of range.
This commit is contained in:
duongtd
2026-08-26 12:38:29 +07:00
commit a694d5abe2
8 changed files with 1482 additions and 0 deletions

148
src/dock_profile.cpp Normal file
View File

@@ -0,0 +1,148 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* dock_pattern_detector — kiểm miền giá trị của một profile dock.
*
* Author: DuongTD
*********************************************************************/
#include <dock_pattern_detector/dock_profile.h>
namespace dock_pattern_detector
{
namespace
{
bool positive(double value)
{
return std::isfinite(value) && value > 0.0;
}
} // namespace
const char* toString(PatternType pattern)
{
switch (pattern)
{
case PatternType::kV:
return "v";
case PatternType::kRecess:
return "recess";
case PatternType::kCylinder:
return "cylinder";
case PatternType::kArc:
return "arc";
}
return "unknown";
}
bool patternFromString(const std::string& name, PatternType& out, std::string& error)
{
if (name == "v")
{
out = PatternType::kV;
return true;
}
if (name == "recess")
{
out = PatternType::kRecess;
return true;
}
if (name == "cylinder")
{
out = PatternType::kCylinder;
return true;
}
if (name == "arc")
{
out = PatternType::kArc;
return true;
}
error = "unknown pattern '" + name + "'; known patterns are: v, recess, cylinder, arc";
return false;
}
bool DockProfile::validate(std::string& error) const
{
if (!std::isfinite(vertex_angle) || vertex_angle <= 0.0 || vertex_angle >= M_PI)
{
// 0 nghĩa là hai cánh trùng nhau, pi nghĩa là chúng thành một đường thẳng. Cả hai đều không
// phải chữ V, và cả hai đều làm phép giao hai đường suy biến.
error = "vertex_angle must be in (0, pi) rad";
return false;
}
if (!positive(wing_length))
{
error = "wing_length must be finite and > 0";
return false;
}
if (!positive(angle_tolerance) || angle_tolerance >= M_PI / 2.0)
{
// Nới tới 90 độ thì mọi cặp đoạn đều "khớp góc" — cổng góc mất tác dụng hoàn toàn.
error = "angle_tolerance must be in (0, pi/2) rad";
return false;
}
if (!positive(length_tolerance) || length_tolerance >= wing_length)
{
// Dung sai >= chính chiều dài cánh nghĩa là chấp nhận cả cánh dài 0 — cổng chiều dài vô nghĩa.
error = "length_tolerance must be finite, > 0 and < wing_length";
return false;
}
if (!positive(vertex_gap))
{
error = "vertex_gap must be finite and > 0";
return false;
}
if (vertex_gap >= wing_length)
{
// Khe đỉnh rộng bằng cả cánh thì hai bức tường cắt nhau ở bất kỳ đâu cũng lọt cổng — mất đúng
// cái cổng phân biệt chữ V thật với giao điểm ngẫu nhiên.
error = "vertex_gap must be < wing_length, otherwise any two crossing walls pass as a V";
return false;
}
if (has_prior)
{
if (!std::isfinite(prior_x) || !std::isfinite(prior_y))
{
error = "prior_x/prior_y must be finite when has_prior is set";
return false;
}
if (!positive(search_radius))
{
error = "search_radius must be finite and > 0 when has_prior is set";
return false;
}
}
if (!std::isfinite(search_fov) || search_fov >= M_PI)
{
error = "search_fov must be finite and < pi rad (<= 0 disables the sector gate)";
return false;
}
if (!std::isfinite(offset_x) || !std::isfinite(offset_y) || !std::isfinite(offset_yaw))
{
error = "offset_x/offset_y/offset_yaw must be finite";
return false;
}
if (min_wing_points < 2)
{
// Hai điểm là tối thiểu tuyệt đối để có một đoạn; dưới đó không có gì để khớp.
error = "min_wing_points must be >= 2";
return false;
}
if (!std::isfinite(min_confidence) || min_confidence < 0.0 || min_confidence > 1.0)
{
error = "min_confidence must be in [0, 1]";
return false;
}
if (pattern != PatternType::kV)
{
// Nói thẳng thay vì nhận config rồi không bao giờ dò ra gì.
error = std::string("pattern '") + toString(pattern) +
"' is declared but not implemented yet; only 'v' is available";
return false;
}
return true;
}
} // namespace dock_pattern_detector

311
src/v_pattern_matcher.cpp Normal file
View File

@@ -0,0 +1,311 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* dock_pattern_detector — khớp chữ V.
*
* Author: DuongTD
*********************************************************************/
#include <dock_pattern_detector/v_pattern_matcher.h>
#include <algorithm>
#include <array>
#include <cmath>
namespace dock_pattern_detector
{
namespace
{
using robot_line_extraction::Line;
struct Point
{
double x = 0.0;
double y = 0.0;
};
double dist(const Point& a, const Point& b)
{
return std::hypot(a.x - b.x, a.y - b.y);
}
Point startOf(const Line& line)
{
return { line.getStart()[0], line.getStart()[1] };
}
Point endOf(const Line& line)
{
return { line.getEnd()[0], line.getEnd()[1] };
}
/**
* @brief Giao điểm hai đường ở dạng cực.
*
* Đường i: `x*cos(a_i) + y*sin(a_i) = r_i`. Định thức là `sin(a_2 - a_1)`, bằng 0 đúng khi hai
* đường song song — khi ấy không có đỉnh nào để nói tới.
*/
bool intersect(const Line& l1, const Line& l2, Point& out)
{
const double a1 = l1.getAngle();
const double a2 = l2.getAngle();
const double det = std::cos(a1) * std::sin(a2) - std::sin(a1) * std::cos(a2);
if (std::fabs(det) < 1e-9)
{
return false;
}
const double r1 = l1.getRadius();
const double r2 = l2.getRadius();
out.x = (r1 * std::sin(a2) - r2 * std::sin(a1)) / det;
out.y = (r2 * std::cos(a1) - r1 * std::cos(a2)) / det;
return std::isfinite(out.x) && std::isfinite(out.y);
}
/// @brief Đầu mút của @p line xa @p apex nhất — đó là đầu MÚT cánh; đầu kia là chân cánh tại đỉnh.
Point farEndpoint(const Line& line, const Point& apex)
{
const Point s = startOf(line);
const Point e = endOf(line);
return dist(s, apex) >= dist(e, apex) ? s : e;
}
/// @brief Đầu mút của @p line gần @p apex nhất.
Point nearEndpoint(const Line& line, const Point& apex)
{
const Point s = startOf(line);
const Point e = endOf(line);
return dist(s, apex) < dist(e, apex) ? s : e;
}
/// @brief Điểm khớp trong [0, 1]: 1 khi lệch bằng 0, 0 khi lệch chạm dung sai.
double score(double deviation, double tolerance)
{
if (tolerance <= 0.0)
{
return 0.0;
}
return std::max(0.0, 1.0 - std::fabs(deviation) / tolerance);
}
} // namespace
bool VPatternMatcher::configure(const DockProfile& profile, std::string& error)
{
if (!profile.validate(error))
{
return false; // Giữ bộ cũ; một profile áp nửa vời còn tệ hơn không áp.
}
profile_ = profile;
return true;
}
Detection VPatternMatcher::match(const std::vector<Line>& lines) const
{
Detection best;
if (lines.size() < 2)
{
best.reason = "need 2 line segments, scan yielded " + std::to_string(lines.size());
return best;
}
// Vì sao đếm riêng từng lý do loại: "thấy nhiều cặp nhưng cặp nào cũng sai góc" và "không cặp nào
// có đầu mút chụm" đòi hai cách xử trí khác hẳn nhau — chỉnh dung sai, hay chỉnh chỗ đứng.
std::size_t rejected_vertex_gap = 0;
std::size_t rejected_angle = 0;
std::size_t rejected_length = 0;
std::size_t rejected_support = 0;
std::size_t rejected_prior = 0;
std::size_t rejected_confidence = 0;
std::size_t accepted = 0;
for (std::size_t i = 0; i + 1 < lines.size(); ++i)
{
for (std::size_t j = i + 1; j < lines.size(); ++j)
{
const Line& l1 = lines[i];
const Line& l2 = lines[j];
if (l1.numPoints() < profile_.min_wing_points || l2.numPoints() < profile_.min_wing_points)
{
++rejected_support;
continue;
}
Point apex;
if (!intersect(l1, l2, apex))
{
continue; // Song song. Không phải "gần đúng chữ V", chỉ là không phải chữ V.
}
// Cổng quyết định: hai ĐẦU ĐOẠN phải nằm ngay tại giao điểm. Hai bức tường không song song
// nào cũng cắt nhau ở đâu đó; chỉ chữ V thật mới có hai đoạn kết thúc tại chỗ cắt.
const Point near1 = nearEndpoint(l1, apex);
const Point near2 = nearEndpoint(l2, apex);
if (dist(near1, apex) > profile_.vertex_gap || dist(near2, apex) > profile_.vertex_gap)
{
++rejected_vertex_gap;
continue;
}
// Góc TRONG tại đỉnh, đo giữa hai vector cánh. Không đo giữa hai pháp tuyến: hai cách trùng
// nhau ở đúng 90 độ và lệch nhau ở mọi góc khác, nên nhầm là sai âm thầm.
const Point tip1 = farEndpoint(l1, apex);
const Point tip2 = farEndpoint(l2, apex);
const double v1x = tip1.x - apex.x;
const double v1y = tip1.y - apex.y;
const double v2x = tip2.x - apex.x;
const double v2y = tip2.y - apex.y;
const double len1 = std::hypot(v1x, v1y);
const double len2 = std::hypot(v2x, v2y);
if (len1 < 1e-9 || len2 < 1e-9)
{
continue;
}
const double cos_vertex = (v1x * v2x + v1y * v2y) / (len1 * len2);
const double vertex = std::acos(std::max(-1.0, std::min(1.0, cos_vertex)));
const double angle_dev = vertex - profile_.vertex_angle;
if (std::fabs(angle_dev) > profile_.angle_tolerance)
{
++rejected_angle;
continue;
}
const double len_dev1 = len1 - profile_.wing_length;
const double len_dev2 = len2 - profile_.wing_length;
if (std::fabs(len_dev1) > profile_.length_tolerance ||
std::fabs(len_dev2) > profile_.length_tolerance)
{
++rejected_length;
continue;
}
// Phân giác, rồi lật cho hướng RA phía cảm biến. Chọn dấu bằng vị trí cảm biến chứ không bằng
// thứ tự hai cánh: thứ tự đổi theo phía robot đứng, và lệch 180 độ ở đây là robot lùi vào
// tấm sạc thay vì tiến vào.
double bx = v1x / len1 + v2x / len2;
double by = v1y / len1 + v2y / len2;
const double bn = std::hypot(bx, by);
if (bn < 1e-9)
{
continue; // Hai cánh ngược chiều nhau: một đường thẳng, không phải chữ V.
}
bx /= bn;
by /= bn;
// Gốc cảm biến là (0, 0) trong frame của scan, nên vector từ đỉnh về phía cảm biến là -apex.
if (bx * (-apex.x) + by * (-apex.y) < 0.0)
{
bx = -bx;
by = -by;
}
const double yaw = std::atan2(by, bx);
if (profile_.has_prior)
{
const double d = std::hypot(apex.x - profile_.prior_x, apex.y - profile_.prior_y);
if (d > profile_.search_radius)
{
++rejected_prior;
continue;
}
}
if (profile_.search_fov > 0.0 && std::fabs(std::atan2(apex.y, apex.x)) > profile_.search_fov)
{
++rejected_prior;
continue;
}
// Điểm tin: trục tệ nhất trong ba tiêu chí, không phải trung bình. Trung bình cho một hình
// sai hẳn góc nhưng đúng chiều dài lọt qua bằng điểm của hai tiêu chí kia.
const double support = std::min(1.0, static_cast<double>(std::min(l1.numPoints(),
l2.numPoints())) /
static_cast<double>(profile_.min_wing_points * 2));
const double confidence =
std::min({ score(angle_dev, profile_.angle_tolerance),
score(len_dev1, profile_.length_tolerance),
score(len_dev2, profile_.length_tolerance), support });
if (confidence < profile_.min_confidence)
{
++rejected_confidence;
continue;
}
++accepted;
if (confidence <= best.confidence && best.valid)
{
continue;
}
best.valid = true;
best.confidence = confidence;
best.apex_x = apex.x;
best.apex_y = apex.y;
best.measured_vertex_angle = vertex;
best.measured_wing_length[0] = len1;
best.measured_wing_length[1] = len2;
// Pose đích = đỉnh dịch theo offset của profile, trong hệ của CHÍNH hình: x dọc pháp tuyến
// hướng ra phía robot, y sang trái.
const double cos_y = std::cos(yaw);
const double sin_y = std::sin(yaw);
best.x = apex.x + cos_y * profile_.offset_x - sin_y * profile_.offset_y;
best.y = apex.y + sin_y * profile_.offset_x + cos_y * profile_.offset_y;
best.yaw = std::atan2(std::sin(yaw + profile_.offset_yaw),
std::cos(yaw + profile_.offset_yaw));
}
}
best.candidate_count = accepted;
if (!best.valid)
{
// Lý do cụ thể nhất trước: cái đếm nào lớn nhất nói đúng chỗ đang hỏng. "Không thấy gì" và
// "thấy nhưng méo" đòi hai cách xử trí ngược nhau, mà một dòng "detection failed" thì không.
if (rejected_prior > 0)
{
best.reason = std::to_string(rejected_prior) +
" candidate(s) matched the shape but fell outside the search gate";
}
else if (rejected_confidence > 0)
{
best.reason = std::to_string(rejected_confidence) +
" candidate(s) matched but scored below min_confidence";
}
else if (rejected_length > 0)
{
best.reason = std::to_string(rejected_length) + " pair(s) had the right vertex angle but the "
"wrong wing length";
}
else if (rejected_angle > 0)
{
best.reason =
std::to_string(rejected_angle) + " pair(s) met at a vertex but at the wrong angle";
}
else if (rejected_vertex_gap > 0)
{
best.reason = std::to_string(rejected_vertex_gap) +
" pair(s) of lines cross but do not end at the crossing — not a V";
}
else if (rejected_support > 0)
{
best.reason = std::to_string(rejected_support) +
" pair(s) had too few supporting rays; move closer or lower min_wing_points";
}
else
{
best.reason = "no pair of segments forms a vertex";
}
}
return best;
}
} // namespace dock_pattern_detector