feat(reflector_pair): add ReflectorPairMatcher for two flat reflective strips on a wall

Pure geometry core for the upcoming wall reflector detection action. The wall
line is fitted from dark rays only; each strip edge is the half-step bearing
between the intensity core and its neighbour, intersected with that line, so
the range bias of bright returns never enters the pose. Exactly one valid pair
is required; two or more report ambiguous. Synthetic tests cover geometry,
quantisation, bloom, bright range bias, realistic range noise, wall ends,
occluders, ambiguity and malformed input.
This commit is contained in:
2026-11-12 10:12:57 +07:00
parent 5c1688ac50
commit 7ce7c7db52
8 changed files with 1981 additions and 0 deletions

View File

@@ -69,6 +69,8 @@ add_library(dock_pattern_detector SHARED
src/leg_profile.cpp
src/leg_pose_fit.cpp
src/leg_pattern_matcher.cpp
src/reflector_pair_profile.cpp
src/reflector_pair_matcher.cpp
)
target_compile_options(dock_pattern_detector PRIVATE -Wall -Wextra)
@@ -269,4 +271,14 @@ if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
endif()
endforeach()
catkin_add_gtest(reflector_pair_matcher_test test/reflector_pair_matcher_test.cpp)
if(TARGET reflector_pair_matcher_test)
set_target_properties(reflector_pair_matcher_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
target_compile_options(reflector_pair_matcher_test PRIVATE -Wall -Wextra)
target_include_directories(reflector_pair_matcher_test PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/test)
target_include_directories(reflector_pair_matcher_test SYSTEM PRIVATE ${EIGEN3_INCLUDE_DIRS})
target_link_libraries(reflector_pair_matcher_test dock_pattern_detector pthread)
endif()
endif()

View File

@@ -259,3 +259,31 @@ thước hay ground truth.
Test chạy đúng chuỗi mà handler sẽ chạy: dựng thế giới → chiếu tia → `robot_line_extraction` →
matcher. Nhóm **từ chối** quan trọng hơn nhóm dò đúng, và mỗi ca từ chối khẳng định luôn *lý do* —
một test chỉ kiểm `!valid` sẽ pass cả khi extractor không ra đoạn nào, tức matcher chưa hề bị thử.
## Hai dải phản quang phẳng trên tường — `ReflectorPairMatcher`
`ReflectorPairProfile` và `ReflectorPairMatcher` là lõi độc lập với profile sạc và chân xe, không
đọc YAML, TF, ROS hay thời gian. `configure()` từ chối kích thước/ngưỡng bắt buộc chưa khai. `match()`
nhận `ScanGeometry`, ranges và intensities cùng chỉ số, `ReflectorPairLimits` và pose scan trong frame
prior; trả marker và target **trong frame prior**, width, spacing, sai số fit, support, bất định mép,
số cặp và `reason`. Range 0 không được dùng ở cả hai giá trị `zero_range_is_no_echo`; nếu nằm
trong vùng support thì P1 từ chối. Trục +X marker là pháp tuyến tường hướng về cảm biến. Target dùng offset theo
marker; handler sau này cộng π cho hướng forward. Không phát TF hoặc vận tốc.
Tách bright run/core theo hai ngưỡng, loại core thiếu hoặc hòa, mask toàn bộ run và bloom, fit TLS
các điểm tối trong cửa sổ hai bên. Cổng so chênh lệch residual trung bình giữa trái, giữa và phải
trên cùng đường TLS dùng `wall_merge_distance`; không fit góc riêng trên hai đoạn ngắn. Cửa sổ
dừng trước tia invalid và có thể tiếp tục mở về phía còn support. Cổng residual, gap và support kiểm vật
chắn; các tia mép giao với đường tường, không dùng range sáng làm vị trí. Range sáng chỉ được dùng
trong cổng đồng mặt: sai lệch theo pháp tuyến phải ≤ `wall_max_residual + wall_merge_distance`.
Cổng này không phân biệt được một vật sáng nằm trong giới hạn bias đó với dải thật; cần hiệu chuẩn.
`wall_merge_angle` đã bỏ khỏi profile; chọn `wall_merge_distance` phù hợp nhiễu và khoảng cách giữa
các mặt cần phân biệt. `wall_max_gap` phải bao phủ dải cộng cả hai skirt bloom tại tầm xa nhất. Kiểm kích thước,
prior và quạt; hai cặp hợp lệ trở lên trả `ambiguous`, vượt giới hạn xử lý trả `capacity_*`.
`tape_core_intensity`, mask bloom và `edge_bias_bound` phải hiệu chuẩn theo cảm biến, vật liệu, góc và
cự ly. Thấy core ổn định không chứng minh đó là mép vật lý, nhất là khi saturation/bloom. Cận mép
trả về chỉ gồm lượng tử góc và bound hiệu chuẩn, chưa bao gồm sai số fit tường, TF hay localization.
Không có ground truth tường thật hoặc chứng nhận độ chính xác trong package. Cách dựng và cổng kiểm
được mô tả trong [kế hoạch P1](../../../../Test/docs/wall_reflector_detection_action/WALL_REFLECTOR_DETECTION_PLAN.md)
của workspace phát triển.

View File

@@ -0,0 +1,165 @@
#ifndef DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_MATCHER_H_
#define DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_MATCHER_H_
#include <array>
#include <cstddef>
#include <string>
#include <vector>
#include <robot_line_extraction/types.h>
#include <dock_pattern_detector/reflector_pair_profile.h>
namespace dock_pattern_detector
{
/// @brief Pose 2D trong frame được ghi ở hợp đồng của từng API.
struct ReflectorPose2D
{
double x = 0.0; ///< [m]
double y = 0.0; ///< [m]
double yaw = 0.0; ///< [rad]
};
/// @brief Giới hạn theo sensor và ngân sách tính toán cho một scan.
struct ReflectorPairLimits
{
double min_range = 0.1; ///< [m]
double max_range = 3.0; ///< [m]
/// Range 0 không dùng ở cả hai chế độ; 0 trong vùng support làm scan bị từ chối.
bool zero_range_is_no_echo = true;
std::size_t max_candidates = 16;
std::size_t max_pairs = 120;
std::size_t max_scan_rays = 4096;
};
/**
* @brief Kết quả một scan. Marker và target cùng nằm trong frame prior, chưa cộng π cho forward.
*
* `reason` rỗng khi valid. Giá trị khi thất bại:
* - `not_configured`: chưa nhận profile hợp lệ.
* - `invalid_limits_or_transform`: limits hoặc pose scan không hợp lệ.
* - `invalid_scan_geometry_or_ranges`: geometry hay kích thước ranges không hợp lệ.
* - `no_intensity_data`, `intensity_size_mismatch`: thiếu hoặc sai kích thước intensities.
* - `capacity_scan_rays`, `capacity_candidates`, `capacity_pairs`: vượt ngân sách tương ứng.
* - `insufficient_candidates`, `insufficient_candidates_or_core`: thiếu run hoặc core hợp lệ.
* - `wall_support`: thiếu support hai phía, vùng giữa, hoặc span cần thiết.
* - `wall_occluded_or_invalid`, `wall_gap_or_occlusion`: tia không hợp lệ hoặc gap trong cửa sổ.
* - `wall_degenerate`, `wall_span`: TLS suy biến hoặc span chiếu trên tường quá ngắn.
* - `wall_residual_or_occlusion`, `wall_not_same_line`: residual hoặc sai lệch nhóm vượt ngưỡng.
* - `wall_occlusion_unknown`, `wall_occlusion`, `bright_off_wall`: không kiểm được tia mask,
* phát hiện tia tối ở trước tường hoặc tia sáng lệch quá xa khỏi tường.
* - `edge_parallel`, `edge_behind_sensor`, `wall_extrapolation`, `edge_uncertainty`: giao mép
* quá xiên, ở sau sensor, ngoài support hoặc có uncertainty quá lớn.
* - `width`, `spacing`, `prior`, `search_fov`: trượt cổng hình học hoặc ROI tương ứng.
* - `nonfinite_pose`: pose tính được không hữu hạn.
* - `ambiguous`: có nhiều hơn một cặp qua mọi cổng; không trả pose của một cặp bất kỳ.
* - `no_valid_pair`: không có cặp hợp lệ và không có lý do cụ thể hơn.
*
* Khi nhiều cặp đều bị loại, reason là lý do của cặp cuối được xét; counters vẫn cho biết quy mô.
*/
struct ReflectorPairDetection
{
bool valid = false;
ReflectorPose2D marker;
ReflectorPose2D target;
std::array<double, 2> widths{{0.0, 0.0}}; ///< [m] theo thứ tự chỉ số tia
double spacing = 0.0; ///< [m]
double wall_rms = 0.0; ///< [m]
double wall_max_residual = 0.0; ///< [m]
std::array<std::size_t, 2> wall_support{{0, 0}}; ///< Số tia tối ngoài cặp mỗi phía
std::array<double, 4> edge_uncertainty{{0.0, 0.0, 0.0, 0.0}}; ///< [m]
std::size_t candidate_count = 0;
std::size_t valid_pairs = 0;
std::size_t tested_pairs = 0;
std::size_t rejected_runs = 0;
std::string reason;
};
/**
* @brief Dò hai dải phẳng trên một tường bằng một scan ranges/intensities thô.
*
* Kiểm geometry → phân đoạn run/core và mask bloom → fit TLS tường từ tia tối trong cửa sổ
* đủ support → kiểm residual từng vùng, gap và vật chắn → giao tia mép với tường → kiểm width,
* spacing, prior và ROI → yêu cầu đúng một cặp. Pháp tuyến hướng về sensor; offset tạo target.
* Range sáng chỉ dùng kiểm đồng mặt, không làm tọa độ tường hoặc mép. Không tự lật thứ tự tia;
* `angle_increment` âm được xử lý theo đúng geometry đầu vào.
*
* Buffer được giữ theo mức sử dụng lớn nhất; không lưu state static. Matcher không thread-safe,
* mỗi consumer dùng một instance. Kết quả chưa chứng nhận độ chính xác thực địa.
*/
class ReflectorPairMatcher
{
public:
/// @brief Nhận profile mới; sai thì giữ profile cũ và ghi lỗi cụ thể vào error.
bool configure(const ReflectorPairProfile& profile, std::string& error);
bool configured() const
{
return configured_;
}
const ReflectorPairProfile& profile() const
{
return profile_;
}
/**
* @brief Xử lý một scan trong giới hạn đã cho.
* @param geometry Layout tia; angle_increment được phép âm nhưng không bằng 0.
* @param ranges [m] Range thô, cùng thứ tự và kích thước với intensities.
* @param intensities Cường độ theo thang driver; không được rỗng.
* @param limits Miền range và giới hạn số tia, ứng viên, cặp.
* @param scan_in_prior Pose của frame scan trong frame prior; marker và target trả cùng frame prior.
*/
ReflectorPairDetection match(const robot_line_extraction::ScanGeometry& geometry,
const std::vector<double>& ranges,
const std::vector<float>& intensities,
const ReflectorPairLimits& limits,
const ReflectorPose2D& scan_in_prior);
private:
struct Ray
{
double range = 0.0;
double x = 0.0;
double y = 0.0;
bool valid = false;
bool bright = false;
bool masked = false;
};
struct Candidate
{
std::size_t first = 0;
std::size_t last = 0;
std::size_t core_first = 0;
std::size_t core_last = 0;
};
struct Line
{
double nx = 0.0;
double ny = 0.0;
double rho = 0.0;
double rms = 0.0;
double max_residual = 0.0;
};
bool fitLine(const std::vector<std::size_t>& indices, Line& line) const;
bool evaluatePair(const Candidate& first, const Candidate& second,
const robot_line_extraction::ScanGeometry& geometry,
const ReflectorPose2D& scan_in_prior, ReflectorPairDetection& result,
const char*& reason);
ReflectorPairProfile profile_;
bool configured_ = false;
std::vector<Ray> rays_;
std::vector<Candidate> candidates_;
std::vector<std::size_t> support_;
std::vector<std::size_t> left_support_;
std::vector<std::size_t> right_support_;
};
} // namespace dock_pattern_detector
#endif // DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_MATCHER_H_

View File

@@ -0,0 +1,122 @@
#ifndef DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_PROFILE_H_
#define DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_PROFILE_H_
#include <cstddef>
#include <limits>
#include <string>
namespace dock_pattern_detector
{
/**
* @brief Cấu hình hình học và các cổng kiểm của cặp dải trên một tường phẳng.
*
* Giá trị mặc định NaN là bắt buộc đo và khai; không phải cấu hình dùng được trên robot.
* Dung sai lớn giúp chịu nhiễu nhưng có thể nhận nhầm một vật khác. `validate()` kiểm mọi khóa
* và ràng buộc chéo trước khi matcher nhận profile.
*/
struct ReflectorPairProfile
{
/// [m] Bề rộng vật lý mỗi dải theo tường. Tăng khi dải thực rộng hơn; phải đo, không tùy ý nới.
double tape_width = std::numeric_limits<double>::quiet_NaN();
/// [m] Sai lệch width cho phép. Tăng chịu lượng tử/bloom hơn nhưng dễ nhận nhầm vật sáng.
double width_tolerance = std::numeric_limits<double>::quiet_NaN();
/// [m] Khoảng cách tâm–tâm hai dải. Tăng khi cặp thực rộng hơn; phải đo ở mặt phẳng scan.
double tape_spacing = std::numeric_limits<double>::quiet_NaN();
/// [m] Sai lệch spacing cho phép. Tăng giảm bỏ sót nhưng dễ ghép nhầm hai vật sáng.
double spacing_tolerance = std::numeric_limits<double>::quiet_NaN();
/// [đơn vị driver] Ngưỡng tạo run sáng. Tăng giảm bloom nhưng có thể mất tia tape.
double tape_min_intensity = std::numeric_limits<double>::quiet_NaN();
/// [đơn vị driver] Ngưỡng core trong run. Tăng thu hẹp core, có thể bỏ mất dải ở xa.
double tape_core_intensity = std::numeric_limits<double>::quiet_NaN();
/// [tia] Số tia core tối thiểu mỗi dải. Tăng chống nhiễu nhưng thu hẹp tầm hoặc góc phát hiện.
std::size_t tape_min_points = 3;
/// [rad] Vùng mask mỗi phía run để tránh bloom vào fit tường. Tăng loại nhiều support hơn.
double tape_bloom_max_angle = std::numeric_limits<double>::quiet_NaN();
/// [-] Tỉ lệ tối thiểu core/run. Tăng loại run loang nhiều hơn nhưng có thể bỏ dải thật.
double tape_plateau_min_fraction = std::numeric_limits<double>::quiet_NaN();
/// [m] Cận bias mép đã hiệu chuẩn; tăng làm uncertainty bảo thủ hơn, không tự sửa mép.
double edge_bias_bound = std::numeric_limits<double>::quiet_NaN();
/// [m] Trần uncertainty mỗi mép. Tăng cho phép quan sát kém chính xác hơn đi qua.
double max_edge_uncertainty = std::numeric_limits<double>::quiet_NaN();
/// [-] Trị tuyệt đối cos nhỏ nhất giữa tia mép và pháp tuyến tường. Tăng loại góc xiên sớm hơn.
double min_ray_wall_cos = 0.35;
/// [tia] Số điểm tối ngoài cặp mỗi phía. Tăng ổn định fit nhưng khó dò gần mép tường hơn.
std::size_t wall_min_points_each_side = 5;
/// [m] Baseline tối thiểu của support tường. Tăng ổn định yaw nhưng cần nhiều tường nhìn thấy hơn.
double wall_min_span = std::numeric_limits<double>::quiet_NaN();
/// [m] RMS residual tối đa của fit chung. Tăng chịu nhiễu hơn nhưng dễ lọt tường không phẳng.
double wall_max_rms = std::numeric_limits<double>::quiet_NaN();
/// [m] Residual tuyệt đối lớn nhất. Tăng chịu outlier hơn nhưng dễ nhận vật chắn.
double wall_max_residual = std::numeric_limits<double>::quiet_NaN();
/**
* [m] Khoảng trống tối đa giữa hai tia support tối liên tiếp. Mask loại cả dải và bloom, nên
* giá trị phải bao phủ width dải cộng cả hai skirt bloom ở cự ly xa nhất, cộng lượng tử/nhiễu.
* Tăng giúp nối tường qua tape nhưng cũng có thể che khuất một lỗ hoặc vật chắn lớn hơn.
*/
double wall_max_gap = std::numeric_limits<double>::quiet_NaN();
/// [m] Cho phép ngoại suy mép ngoài support. Tăng nới điều kiện thấy tường, giảm độ tin cậy.
double wall_max_extrapolation = 0.0;
/**
* [m] Chênh lệch phần dư trung bình có dấu tối đa giữa các vùng trái/giữa/phải so với TLS chung.
* Tăng chịu nhiễu hơn nhưng có thể gộp hai mặt khác nhau. Cũng góp vào dung sai kiểm range sáng.
*/
double wall_merge_distance = std::numeric_limits<double>::quiet_NaN();
/// [-] Bật prior marker trong frame prior. Bật thu hẹp vùng chọn, không xác minh ID của trạm.
bool has_prior = false;
/// [m] Hoành độ tâm marker kỳ vọng trong frame prior. Thay đổi để chọn vùng trạm khác.
double prior_x = 0.0;
/// [m] Tung độ tâm marker kỳ vọng trong frame prior. Thay đổi để chọn vùng trạm khác.
double prior_y = 0.0;
/// [rad] Yaw pháp tuyến hướng ra kỳ vọng. Thay đổi để chọn hướng tường khác.
double prior_yaw = 0.0;
/// [m] Bán kính quanh prior khi bật prior. Tăng nhận nhiều vị trí hơn và có thể tăng mơ hồ.
double prior_position_tolerance = std::numeric_limits<double>::quiet_NaN();
/// [rad] Sai lệch yaw prior tối đa khi bật prior. Tăng chấp nhận nhiều hướng tường hơn.
double prior_yaw_tolerance = std::numeric_limits<double>::quiet_NaN();
/// [rad] Hướng giữa quạt tìm kiếm trong frame prior. Thay đổi để hướng quạt về phía trạm.
double search_center_yaw = 0.0;
/// [rad] Nửa góc quạt tìm kiếm. Tăng mở rộng ROI nhưng có thể gặp nhiều cặp hơn; π là toàn hướng.
double search_fov = 3.14159265358979323846;
/// [m] Khoảng từ marker ra target theo pháp tuyến. Tăng đưa gốc robot xa tường hơn; bắt buộc > 0.
double offset_x = std::numeric_limits<double>::quiet_NaN();
/// [m] Dịch target theo +Y marker. Tăng dịch theo tiếp tuyến dương của marker.
double offset_y = 0.0;
/// [rad] Hiệu chỉnh yaw target so với marker. Tăng quay goal ngược chiều kim đồng hồ.
double offset_yaw = 0.0;
/// @brief Trả false kèm tên khóa, giá trị lỗi và miền hợp lệ; không sửa profile.
bool validate(std::string& error) const;
};
} // namespace dock_pattern_detector
#endif // DOCK_PATTERN_DETECTOR_REFLECTOR_PAIR_PROFILE_H_

View File

@@ -0,0 +1,586 @@
#include <dock_pattern_detector/reflector_pair_matcher.h>
#include <algorithm>
#include <cmath>
#include <limits>
namespace dock_pattern_detector
{
namespace
{
constexpr double kPi = 3.14159265358979323846;
constexpr double kEpsilon = 1e-9;
double wrap(double angle)
{
return std::atan2(std::sin(angle), std::cos(angle));
}
bool finitePose(const ReflectorPose2D& p)
{
return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.yaw);
}
} // namespace
bool ReflectorPairMatcher::configure(const ReflectorPairProfile& profile, std::string& error)
{
if (!profile.validate(error))
{
return false;
}
profile_ = profile;
configured_ = true;
return true;
}
bool ReflectorPairMatcher::fitLine(const std::vector<std::size_t>& indices, Line& line) const
{
if (indices.size() < 3)
{
return false;
}
double mx = 0.0;
double my = 0.0;
for (const auto index : indices)
{
mx += rays_[index].x;
my += rays_[index].y;
}
mx /= static_cast<double>(indices.size());
my /= static_cast<double>(indices.size());
double xx = 0.0;
double xy = 0.0;
double yy = 0.0;
for (const auto i : indices)
{
const double dx = rays_[i].x - mx;
const double dy = rays_[i].y - my;
xx += dx * dx;
xy += dx * dy;
yy += dy * dy;
}
if (!std::isfinite(xx + yy) || xx + yy < kEpsilon ||
std::hypot(xx - yy, 2.0 * xy) < kEpsilon)
{
return false;
}
const double angle = 0.5 * std::atan2(2.0 * xy, xx - yy);
line.nx = -std::sin(angle);
line.ny = std::cos(angle);
line.rho = line.nx * mx + line.ny * my;
// n phải hướng từ tường về gốc sensor, nghĩa là rho mang dấu âm.
if (line.rho > 0.0)
{
line.nx = -line.nx;
line.ny = -line.ny;
line.rho = -line.rho;
}
if (line.rho >= -kEpsilon)
{
return false;
}
double sum = 0.0;
line.max_residual = 0.0;
for (const auto i : indices)
{
const double e = std::abs(line.nx * rays_[i].x + line.ny * rays_[i].y - line.rho);
sum += e * e;
line.max_residual = std::max(line.max_residual, e);
}
line.rms = std::sqrt(sum / static_cast<double>(indices.size()));
return std::isfinite(line.rms) && std::isfinite(line.max_residual);
}
bool ReflectorPairMatcher::evaluatePair(const Candidate& first_candidate, const Candidate& second_candidate,
const robot_line_extraction::ScanGeometry& geometry,
const ReflectorPose2D& scan_in_prior, ReflectorPairDetection& out,
const char*& reason)
{
const auto fail = [&reason](const char* why)
{
reason = why;
return false;
};
support_.clear();
left_support_.clear();
right_support_.clear();
std::size_t lo = first_candidate.first;
std::size_t hi = second_candidate.last;
bool left_open = true;
bool right_open = true;
// Khi gặp mép tường, giữ chỉ số tia hợp lệ cuối; phía còn lại vẫn có thể bù baseline.
for (;;)
{
const bool have_sides = left_support_.size() >= profile_.wall_min_points_each_side &&
right_support_.size() >= profile_.wall_min_points_each_side;
bool have_span = false;
if (have_sides &&
std::hypot(rays_[left_support_.back()].x - rays_[right_support_.back()].x,
rays_[left_support_.back()].y - rays_[right_support_.back()].y) >=
profile_.wall_min_span)
{
// Span phải đo theo TLS, không theo dây nối hai đầu: nhiễu pháp tuyến làm dây dài giả.
support_.clear();
for (std::size_t index = lo; index <= hi; ++index)
{
if (!rays_[index].valid)
{
return fail("wall_occluded_or_invalid");
}
if (!rays_[index].masked)
{
support_.push_back(index);
}
}
Line provisional_wall;
if (!fitLine(support_, provisional_wall))
{
return fail("wall_degenerate");
}
double minimum = std::numeric_limits<double>::infinity();
double maximum = -minimum;
for (const std::size_t index : support_)
{
const double along = -provisional_wall.ny * rays_[index].x +
provisional_wall.nx * rays_[index].y;
minimum = std::min(minimum, along);
maximum = std::max(maximum, along);
}
have_span = maximum - minimum >= profile_.wall_min_span;
}
if (have_sides && have_span)
{
break;
}
bool advanced = false;
if (left_open && (left_support_.size() < profile_.wall_min_points_each_side || !have_span))
{
if (lo == 0 || !rays_[lo - 1].valid)
{
left_open = false;
}
else
{
--lo;
if (!rays_[lo].masked)
{
left_support_.push_back(lo);
}
advanced = true;
}
}
if (right_open && (right_support_.size() < profile_.wall_min_points_each_side || !have_span))
{
if (hi + 1 >= rays_.size() || !rays_[hi + 1].valid)
{
right_open = false;
}
else
{
++hi;
if (!rays_[hi].masked)
{
right_support_.push_back(hi);
}
advanced = true;
}
}
if (!advanced)
{
return fail("wall_support");
}
}
support_.clear();
for (std::size_t i = lo; i <= hi; ++i)
{
if (!rays_[i].valid)
{
return fail("wall_occluded_or_invalid");
}
if (!rays_[i].masked)
{
if (!support_.empty())
{
const Ray& prev = rays_[support_.back()];
if (std::hypot(rays_[i].x - prev.x, rays_[i].y - prev.y) > profile_.wall_max_gap)
{
return fail("wall_gap_or_occlusion");
}
}
support_.push_back(i);
}
}
Line wall;
if (!fitLine(support_, wall))
{
return fail("wall_degenerate");
}
if (wall.rms > profile_.wall_max_rms || wall.max_residual > profile_.wall_max_residual)
{
return fail("wall_residual_or_occlusion");
}
// Range sáng không tham gia fit hay tọa độ mép; chỉ dùng để loại vật sáng rõ ràng
// nằm ngoài mặt tường. Dung sai này cho phép bias range phản quang hữu hạn, cần hiệu chuẩn.
for (std::size_t i = lo; i <= hi; ++i)
{
if (!rays_[i].masked)
{
continue;
}
const double angle = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
const double ray_normal_dot = wall.nx * std::cos(angle) + wall.ny * std::sin(angle);
if (std::abs(ray_normal_dot) < kEpsilon)
{
return fail("wall_occlusion_unknown");
}
const double expected = wall.rho / ray_normal_dot;
if (expected <= 0.0 || !std::isfinite(expected))
{
return fail("wall_occlusion_unknown");
}
const double observed = rays_[i].range;
if (rays_[i].bright)
{
if (std::abs(observed - expected) * std::abs(ray_normal_dot) >
profile_.wall_max_residual + profile_.wall_merge_distance)
{
return fail("bright_off_wall");
}
}
else if ((expected - observed) * std::abs(ray_normal_dot) > profile_.wall_max_residual)
{
return fail("wall_occlusion");
}
}
// So phần dư trung bình có dấu của hai đầu và vùng giữa trên CÙNG đường fit.
// Góc fit riêng trên đoạn ngắn rất nhạy với nhiễu range và không đo được hai mặt bền vững.
double left_residual = 0.0;
double middle_residual = 0.0;
double right_residual = 0.0;
std::size_t middle_count = 0;
for (const std::size_t index : support_)
{
const double residual = wall.nx * rays_[index].x + wall.ny * rays_[index].y - wall.rho;
if (index < first_candidate.first)
{
left_residual += residual;
}
else if (index > second_candidate.last)
{
right_residual += residual;
}
else
{
middle_residual += residual;
++middle_count;
}
}
if (middle_count == 0)
{
return fail("wall_support");
}
left_residual /= static_cast<double>(left_support_.size());
right_residual /= static_cast<double>(right_support_.size());
middle_residual /= static_cast<double>(middle_count);
if (std::abs(left_residual - middle_residual) > profile_.wall_merge_distance ||
std::abs(right_residual - middle_residual) > profile_.wall_merge_distance ||
std::abs(left_residual - right_residual) > profile_.wall_merge_distance)
{
return fail("wall_not_same_line");
}
const double tangent_x = -wall.ny;
const double tangent_y = wall.nx;
double support_min = std::numeric_limits<double>::infinity();
double support_max = -support_min;
for (const auto i : support_)
{
const double v = tangent_x * rays_[i].x + tangent_y * rays_[i].y;
support_min = std::min(support_min, v);
support_max = std::max(support_max, v);
}
if (support_max - support_min < profile_.wall_min_span)
{
return fail("wall_span");
}
const std::array<std::size_t, 4> core{{first_candidate.core_first, first_candidate.core_last,
second_candidate.core_first, second_candidate.core_last}};
std::array<double, 4> edge_x{};
std::array<double, 4> edge_y{};
std::array<double, 4> uncertainty{};
for (std::size_t j = 0; j < 4; ++j)
{
const double index = static_cast<double>(core[j]) + (j % 2 == 0 ? -0.5 : 0.5);
const double angle = geometry.angle_min + index * geometry.angle_increment;
const double ux = std::cos(angle);
const double uy = std::sin(angle);
const double denominator = wall.nx * ux + wall.ny * uy;
if (std::abs(denominator) < profile_.min_ray_wall_cos)
{
return fail("edge_parallel");
}
const double distance = wall.rho / denominator;
if (!std::isfinite(distance) || distance <= 0.0)
{
return fail("edge_behind_sensor");
}
edge_x[j] = distance * ux;
edge_y[j] = distance * uy;
const double along = tangent_x * edge_x[j] + tangent_y * edge_y[j];
if (along < support_min - profile_.wall_max_extrapolation ||
along > support_max + profile_.wall_max_extrapolation)
{
return fail("wall_extrapolation");
}
uncertainty[j] = std::abs(wall.rho) * std::abs(geometry.angle_increment) /
(2.0 * denominator * denominator) + profile_.edge_bias_bound;
if (!std::isfinite(uncertainty[j]) || uncertainty[j] > profile_.max_edge_uncertainty)
{
return fail("edge_uncertainty");
}
}
const double first_width = std::hypot(edge_x[1] - edge_x[0], edge_y[1] - edge_y[0]);
const double second_width = std::hypot(edge_x[3] - edge_x[2], edge_y[3] - edge_y[2]);
if (std::abs(first_width - profile_.tape_width) > profile_.width_tolerance ||
std::abs(second_width - profile_.tape_width) > profile_.width_tolerance)
{
return fail("width");
}
const double first_center_x = (edge_x[0] + edge_x[1]) / 2.0;
const double first_center_y = (edge_y[0] + edge_y[1]) / 2.0;
const double second_center_x = (edge_x[2] + edge_x[3]) / 2.0;
const double second_center_y = (edge_y[2] + edge_y[3]) / 2.0;
const double spacing = std::hypot(second_center_x - first_center_x, second_center_y - first_center_y);
if (std::abs(spacing - profile_.tape_spacing) > profile_.spacing_tolerance)
{
return fail("spacing");
}
const double cos_yaw = std::cos(scan_in_prior.yaw);
const double sin_yaw = std::sin(scan_in_prior.yaw);
const double center_x = (first_center_x + second_center_x) / 2.0;
const double center_y = (first_center_y + second_center_y) / 2.0;
const double yaw = wrap(std::atan2(wall.ny, wall.nx) + scan_in_prior.yaw);
ReflectorPose2D marker{scan_in_prior.x + cos_yaw * center_x - sin_yaw * center_y,
scan_in_prior.y + sin_yaw * center_x + cos_yaw * center_y, yaw};
if (!finitePose(marker))
{
return fail("nonfinite_pose");
}
if (std::abs(wrap(std::atan2(marker.y, marker.x) - profile_.search_center_yaw)) > profile_.search_fov)
{
return fail("search_fov");
}
if (profile_.has_prior &&
(std::hypot(marker.x - profile_.prior_x, marker.y - profile_.prior_y) > profile_.prior_position_tolerance ||
std::abs(wrap(marker.yaw - profile_.prior_yaw)) > profile_.prior_yaw_tolerance))
{
return fail("prior");
}
const double nx = std::cos(yaw);
const double ny = std::sin(yaw);
ReflectorPose2D target{marker.x + profile_.offset_x * nx - profile_.offset_y * ny,
marker.y + profile_.offset_x * ny + profile_.offset_y * nx,
wrap(yaw + profile_.offset_yaw)};
if (!finitePose(target))
{
return fail("nonfinite_pose");
}
out.marker = marker;
out.target = target;
out.widths = {{first_width, second_width}};
out.spacing = spacing;
out.wall_rms = wall.rms;
out.wall_max_residual = wall.max_residual;
out.wall_support = {{left_support_.size(), right_support_.size()}};
out.edge_uncertainty = uncertainty;
return true;
}
ReflectorPairDetection ReflectorPairMatcher::match(
const robot_line_extraction::ScanGeometry& geometry, const std::vector<double>& ranges,
const std::vector<float>& intensities, const ReflectorPairLimits& limits,
const ReflectorPose2D& scan_in_prior)
{
ReflectorPairDetection result;
const auto fail = [&result](const char* why)
{
result.reason = why;
return result;
};
if (!configured_)
{
return fail("not_configured");
}
if (!std::isfinite(limits.min_range) || !std::isfinite(limits.max_range) ||
limits.min_range < 0.0 || limits.max_range <= limits.min_range ||
limits.max_candidates < 2 || limits.max_candidates > 128 ||
limits.max_pairs < 1 || limits.max_pairs > 8128 ||
limits.max_scan_rays < 2 || limits.max_scan_rays > 65536 || !finitePose(scan_in_prior))
{
return fail("invalid_limits_or_transform");
}
if (geometry.size > limits.max_scan_rays)
{
return fail("capacity_scan_rays");
}
std::string geometry_error;
if (!geometry.validate(geometry_error) || ranges.size() != geometry.size ||
!std::isfinite(geometry.angle_min + (geometry.size - 1) * geometry.angle_increment))
{
return fail("invalid_scan_geometry_or_ranges");
}
if (intensities.empty())
{
return fail("no_intensity_data");
}
if (intensities.size() != ranges.size())
{
return fail("intensity_size_mismatch");
}
rays_.resize(geometry.size);
candidates_.clear();
// Reserve theo scan lớn nhất từng thấy, không tạo vector tạm cho từng cặp.
support_.reserve(geometry.size);
left_support_.reserve(geometry.size);
right_support_.reserve(geometry.size);
candidates_.reserve(limits.max_candidates);
for (std::size_t i = 0; i < geometry.size; ++i)
{
Ray& ray = rays_[i];
ray = Ray{};
const double r = ranges[i];
ray.valid = std::isfinite(r) && r > 0.0 && r >= limits.min_range && r <= limits.max_range &&
std::isfinite(intensities[i]);
if (ray.valid)
{
ray.range = r;
ray.bright = intensities[i] >= profile_.tape_min_intensity;
if (!ray.bright)
{
const double angle = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
ray.x = r * std::cos(angle);
ray.y = r * std::sin(angle);
}
}
}
const double steps_d = std::ceil(profile_.tape_bloom_max_angle / std::abs(geometry.angle_increment));
const std::size_t skirt = steps_d >= static_cast<double>(geometry.size)
? geometry.size : static_cast<std::size_t>(steps_d);
for (std::size_t i = 0; i < geometry.size;)
{
if (!rays_[i].valid || !rays_[i].bright)
{
++i;
continue;
}
const std::size_t first = i;
while (i < geometry.size && rays_[i].valid && rays_[i].bright)
{
++i;
}
const std::size_t last = i - 1;
const std::size_t mask_first = first > skirt ? first - skirt : 0;
const std::size_t mask_last = last + std::min(skirt, geometry.size - 1 - last);
for (std::size_t j = mask_first; j <= mask_last; ++j)
{
rays_[j].masked = true;
}
std::size_t best_start = 0;
std::size_t best_len = 0;
std::size_t ties = 0;
for (std::size_t j = first; j <= last;)
{
if (intensities[j] < profile_.tape_core_intensity)
{
++j;
continue;
}
const std::size_t start = j;
while (j <= last && intensities[j] >= profile_.tape_core_intensity)
{
++j;
}
const std::size_t length = j - start;
if (length > best_len)
{
best_start = start;
best_len = length;
ties = 1;
}
else if (length == best_len)
{
++ties;
}
}
if (best_len < profile_.tape_min_points || ties != 1 ||
static_cast<double>(best_len) / static_cast<double>(last - first + 1) <
profile_.tape_plateau_min_fraction || best_start == 0 ||
best_start + best_len >= geometry.size || !rays_[best_start - 1].valid ||
!rays_[best_start + best_len].valid ||
intensities[best_start - 1] >= profile_.tape_core_intensity ||
intensities[best_start + best_len] >= profile_.tape_core_intensity)
{
++result.rejected_runs;
continue;
}
if (candidates_.size() >= limits.max_candidates)
{
result.candidate_count = candidates_.size() + 1;
return fail("capacity_candidates");
}
candidates_.push_back(Candidate{first, last, best_start, best_start + best_len - 1});
}
result.candidate_count = candidates_.size();
if (candidates_.size() < 2)
{
return fail(result.rejected_runs ? "insufficient_candidates_or_core" : "insufficient_candidates");
}
const std::size_t count = candidates_.size() * (candidates_.size() - 1) / 2;
if (count > limits.max_pairs)
{
return fail("capacity_pairs");
}
const char* last_reason = "no_valid_pair";
for (std::size_t i = 0; i < candidates_.size(); ++i)
{
for (std::size_t j = i + 1; j < candidates_.size(); ++j)
{
++result.tested_pairs;
ReflectorPairDetection pair;
if (evaluatePair(candidates_[i], candidates_[j], geometry, scan_in_prior, pair, last_reason))
{
++result.valid_pairs;
if (result.valid_pairs == 1)
{
result.marker = pair.marker;
result.target = pair.target;
result.widths = pair.widths;
result.spacing = pair.spacing;
result.wall_rms = pair.wall_rms;
result.wall_max_residual = pair.wall_max_residual;
result.wall_support = pair.wall_support;
result.edge_uncertainty = pair.edge_uncertainty;
}
}
}
}
if (result.valid_pairs > 1)
{
// Không trả pose tùy ý khi còn nhiều cặp hợp lệ.
result.marker = ReflectorPose2D{};
result.target = ReflectorPose2D{};
result.widths = {{0.0, 0.0}};
result.spacing = 0.0;
result.wall_rms = 0.0;
result.wall_max_residual = 0.0;
result.wall_support = {{0, 0}};
result.edge_uncertainty = {{0.0, 0.0, 0.0, 0.0}};
return fail("ambiguous");
}
if (result.valid_pairs == 0)
{
result.reason = last_reason;
return result;
}
result.valid = true;
result.reason.clear();
return result;
}
} // namespace dock_pattern_detector

View File

@@ -0,0 +1,178 @@
#include <dock_pattern_detector/reflector_pair_profile.h>
#include <cmath>
#include <sstream>
namespace dock_pattern_detector
{
namespace
{
constexpr double kPi = 3.14159265358979323846;
bool validateValue(bool valid, const char* name, double value, const char* range,
std::string& error)
{
if (valid)
{
return true;
}
std::ostringstream message;
message << name << "=" << value << " must be " << range;
error = message.str();
return false;
}
} // namespace
bool ReflectorPairProfile::validate(std::string& error) const
{
error.clear();
const auto check = [&error](const char* name, double value, bool valid, const char* range)
{
return validateValue(std::isfinite(value) && valid, name, value, range, error);
};
if (!check("tape_width", tape_width, tape_width > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("width_tolerance", width_tolerance, width_tolerance > 0.0 && width_tolerance < tape_width,
"finite and in (0, tape_width) [m]"))
{
return false;
}
if (!check("tape_spacing", tape_spacing, tape_spacing > tape_width,
"finite and > tape_width [m]"))
{
return false;
}
if (!check("spacing_tolerance", spacing_tolerance,
spacing_tolerance > 0.0 && spacing_tolerance < tape_spacing,
"finite and in (0, tape_spacing) [m]"))
{
return false;
}
if (!check("tape_min_intensity", tape_min_intensity, tape_min_intensity >= 0.0,
"finite and >= 0 [driver units]"))
{
return false;
}
if (!check("tape_core_intensity", tape_core_intensity, tape_core_intensity >= tape_min_intensity,
"finite and >= tape_min_intensity [driver units]"))
{
return false;
}
if (!validateValue(tape_min_points >= 3, "tape_min_points", static_cast<double>(tape_min_points),
">= 3 [rays]", error))
{
return false;
}
if (!check("tape_bloom_max_angle", tape_bloom_max_angle,
tape_bloom_max_angle >= 0.0 && tape_bloom_max_angle < kPi,
"finite and in [0, pi) [rad]"))
{
return false;
}
if (!check("tape_plateau_min_fraction", tape_plateau_min_fraction,
tape_plateau_min_fraction > 0.0 && tape_plateau_min_fraction <= 1.0,
"finite and in (0, 1]"))
{
return false;
}
if (!check("edge_bias_bound", edge_bias_bound, edge_bias_bound >= 0.0,
"finite and >= 0 [m]"))
{
return false;
}
if (!check("max_edge_uncertainty", max_edge_uncertainty, max_edge_uncertainty > 0.0,
"finite and > 0 [m]"))
{
return false;
}
if (!check("min_ray_wall_cos", min_ray_wall_cos, min_ray_wall_cos > 0.0 && min_ray_wall_cos <= 1.0,
"finite and in (0, 1]"))
{
return false;
}
if (!validateValue(wall_min_points_each_side >= 3, "wall_min_points_each_side",
static_cast<double>(wall_min_points_each_side), ">= 3 [rays]", error))
{
return false;
}
if (!check("wall_min_span", wall_min_span, wall_min_span > tape_spacing,
"finite and > tape_spacing [m]"))
{
return false;
}
if (!check("wall_max_rms", wall_max_rms, wall_max_rms > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("wall_max_residual", wall_max_residual, wall_max_residual >= wall_max_rms,
"finite and >= wall_max_rms [m]"))
{
return false;
}
if (!check("wall_max_gap", wall_max_gap, wall_max_gap >= tape_width,
"finite and >= tape_width [m]"))
{
return false;
}
if (!check("wall_max_extrapolation", wall_max_extrapolation, wall_max_extrapolation >= 0.0,
"finite and >= 0 [m]"))
{
return false;
}
if (!check("wall_merge_distance", wall_merge_distance, wall_merge_distance > 0.0,
"finite and > 0 [m]"))
{
return false;
}
if (!check("prior_x", prior_x, true, "finite [m]"))
{
return false;
}
if (!check("prior_y", prior_y, true, "finite [m]"))
{
return false;
}
if (!check("prior_yaw", prior_yaw, true, "finite [rad]"))
{
return false;
}
if (has_prior)
{
if (!check("prior_position_tolerance", prior_position_tolerance, prior_position_tolerance > 0.0,
"finite and > 0 [m] when has_prior"))
{
return false;
}
if (!check("prior_yaw_tolerance", prior_yaw_tolerance,
prior_yaw_tolerance > 0.0 && prior_yaw_tolerance <= kPi,
"finite and in (0, pi] [rad] when has_prior"))
{
return false;
}
}
if (!check("search_center_yaw", search_center_yaw, true, "finite [rad]"))
{
return false;
}
if (!check("search_fov", search_fov, search_fov > 0.0 && search_fov <= kPi,
"finite and in (0, pi] [rad]"))
{
return false;
}
if (!check("offset_x", offset_x, offset_x > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("offset_y", offset_y, true, "finite [m]"))
{
return false;
}
if (!check("offset_yaw", offset_yaw, true, "finite [rad]"))
{
return false;
}
return true;
}
} // namespace dock_pattern_detector

View File

@@ -0,0 +1,688 @@
#include <dock_pattern_detector/reflector_pair_matcher.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "wall_scan_sim.h"
namespace
{
using dock_pattern_detector::ReflectorPairDetection;
using dock_pattern_detector::ReflectorPairLimits;
using dock_pattern_detector::ReflectorPairMatcher;
using dock_pattern_detector::ReflectorPairProfile;
using dock_pattern_detector::ReflectorPose2D;
constexpr double kPi = 3.14159265358979323846;
constexpr double kFrontStep = 0.003926990554;
constexpr double kNanoStep = 0.0058824;
// TEST-ONLY: không phải kích thước hay hiệu chỉnh của trạm thật.
ReflectorPairProfile profile()
{
ReflectorPairProfile test_profile;
test_profile.tape_width = 0.05;
test_profile.width_tolerance = 0.025;
test_profile.tape_spacing = 0.40;
test_profile.spacing_tolerance = 0.025;
test_profile.tape_min_intensity = 8000;
test_profile.tape_core_intensity = 15000;
test_profile.tape_bloom_max_angle = 0.0;
test_profile.tape_plateau_min_fraction = 0.5;
test_profile.edge_bias_bound = 0.0;
test_profile.max_edge_uncertainty = 0.04;
test_profile.wall_min_span = 0.65;
test_profile.wall_max_rms = 0.006;
test_profile.wall_max_residual = 0.02;
test_profile.wall_max_gap = 0.15;
test_profile.wall_merge_distance = 0.02;
test_profile.offset_x = 0.6;
return test_profile;
}
ReflectorPairDetection detect(ReflectorPairProfile test_profile, const wall_scan_sim::World& world,
const robot_line_extraction::ScanGeometry& geometry,
ReflectorPairLimits limits = {}, ReflectorPose2D scan_in_prior = {})
{
ReflectorPairMatcher matcher;
std::string error;
if (!matcher.configure(test_profile, error))
{
ADD_FAILURE() << error;
return {};
}
limits.max_range = 6.0;
const auto scan = wall_scan_sim::rayCast(world, geometry);
return matcher.match(geometry, scan.ranges, scan.intensities, limits, scan_in_prior);
}
double yawError(double actual_yaw, double expected_yaw)
{
const double difference = actual_yaw - expected_yaw;
return std::abs(std::atan2(std::sin(difference), std::cos(difference)));
}
// Cận lượng tử dùng worst-case đạo hàm trong nửa bước quanh mọi mép vật lý; không lấy dung sai gate.
double quantisationBound(const wall_scan_sim::World& world, double step)
{
const double nx = std::cos(world.normal_yaw);
const double ny = std::sin(world.normal_yaw);
const double tx = -ny;
const double ty = nx;
const double rho = std::abs(nx * world.x + ny * world.y);
double min_cos = 1.0;
for (const auto& tape : world.tapes)
{
for (const double sign : {-1.0, 1.0})
{
const double v = tape.center + sign * tape.width / 2.0;
const double x = world.x + tx * v;
const double y = world.y + ty * v;
const double incidence = std::acos(std::clamp(rho / std::hypot(x, y), 0.0, 1.0));
min_cos = std::min(min_cos, std::cos(incidence + std::abs(step) / 2.0));
}
}
return rho * std::abs(step) / (2.0 * min_cos * min_cos) + 1e-9;
}
// Xây lại support từ số tia hai phía của detection để tính phương sai fit từ hình học thực tế.
// Xấp xỉ tuyến tính nhiễu độc lập: Var(offset tại s) <= sigma²(1/N + (s-mean)²/Sxx),
// Var(yaw) <= sigma²/Sxx. Hệ số 6 là cận thống kê cho seed thử, không phải cận Gaussian tuyệt đối.
std::array<double, 2> fitNoiseBounds(const wall_scan_sim::World& world,
const robot_line_extraction::ScanGeometry& geometry,
const ReflectorPairDetection& detection,
double minimum_cosine)
{
const auto scan = wall_scan_sim::rayCast(world, geometry);
std::size_t first_bright = geometry.size;
std::size_t last_bright = 0;
for (std::size_t index = 0; index < geometry.size; ++index)
{
if (scan.intensities[index] >= 8000)
{
first_bright = std::min(first_bright, index);
last_bright = index;
}
}
if (first_bright == geometry.size)
{
return {{0.0, 0.0}};
}
std::size_t first = first_bright;
std::size_t last = last_bright;
for (std::size_t count = 0; count < detection.wall_support[0] && first > 0;)
{
--first;
if (std::isfinite(scan.ranges[first]) && scan.intensities[first] < 8000)
{
++count;
}
}
for (std::size_t count = 0; count < detection.wall_support[1] && last + 1 < geometry.size;)
{
++last;
if (std::isfinite(scan.ranges[last]) && scan.intensities[last] < 8000)
{
++count;
}
}
const double tangent_x = -std::sin(world.normal_yaw);
const double tangent_y = std::cos(world.normal_yaw);
std::vector<double> along;
for (std::size_t index = first; index <= last; ++index)
{
if (!std::isfinite(scan.ranges[index]) || scan.intensities[index] >= 8000)
{
continue;
}
const double angle = geometry.angle_min + index * geometry.angle_increment;
along.push_back(scan.ranges[index] *
(tangent_x * std::cos(angle) + tangent_y * std::sin(angle)));
}
if (along.size() < 3)
{
return {{0.0, 0.0}};
}
double mean = 0.0;
for (const double position : along)
{
mean += position;
}
mean /= static_cast<double>(along.size());
double sum_squared = 0.0;
for (const double position : along)
{
sum_squared += (position - mean) * (position - mean);
}
if (sum_squared <= 0.0)
{
return {{0.0, 0.0}};
}
double max_offset = 0.0;
const double center_along = tangent_x * world.x + tangent_y * world.y;
for (const auto& tape : world.tapes)
{
for (const double sign : {-1.0, 1.0})
{
max_offset = std::max(max_offset,
std::abs(center_along + tape.center + sign * tape.width / 2.0 - mean));
}
}
const double position_sigma = world.noise_sigma *
std::sqrt(1.0 / static_cast<double>(along.size()) + max_offset * max_offset / sum_squared) /
minimum_cosine;
const double yaw_sigma = world.noise_sigma / (std::sqrt(sum_squared) * minimum_cosine);
return {{6.0 * position_sigma, 6.0 * yaw_sigma}};
}
TEST(ReflectorPairProfile, RequiredFieldsRejectUnsetNonfiniteAndOutOfRange)
{
const double nan = std::numeric_limits<double>::quiet_NaN();
const std::vector<std::pair<const char*, double ReflectorPairProfile::*>> fields = {
{"tape_width", &ReflectorPairProfile::tape_width}, {"width_tolerance", &ReflectorPairProfile::width_tolerance},
{"tape_spacing", &ReflectorPairProfile::tape_spacing}, {"spacing_tolerance", &ReflectorPairProfile::spacing_tolerance},
{"tape_min_intensity", &ReflectorPairProfile::tape_min_intensity}, {"tape_core_intensity", &ReflectorPairProfile::tape_core_intensity},
{"tape_bloom_max_angle", &ReflectorPairProfile::tape_bloom_max_angle},
{"tape_plateau_min_fraction", &ReflectorPairProfile::tape_plateau_min_fraction},
{"edge_bias_bound", &ReflectorPairProfile::edge_bias_bound}, {"max_edge_uncertainty", &ReflectorPairProfile::max_edge_uncertainty},
{"wall_min_span", &ReflectorPairProfile::wall_min_span}, {"wall_max_rms", &ReflectorPairProfile::wall_max_rms},
{"wall_max_residual", &ReflectorPairProfile::wall_max_residual}, {"wall_max_gap", &ReflectorPairProfile::wall_max_gap},
{"wall_merge_distance", &ReflectorPairProfile::wall_merge_distance}, {"offset_x", &ReflectorPairProfile::offset_x}};
for (const auto& field : fields)
{
for (double bad : {nan, std::numeric_limits<double>::infinity(), -1.0})
{
auto test_profile = profile();
test_profile.*field.second = bad;
std::string error;
EXPECT_FALSE(test_profile.validate(error)) << field.first;
EXPECT_NE(error.find(field.first), std::string::npos) << error;
}
}
ReflectorPairProfile unset;
std::string error;
EXPECT_FALSE(unset.validate(error));
EXPECT_NE(error.find("tape_width"), std::string::npos);
}
TEST(ReflectorPairProfile, ValidationErrorIncludesValueAndRange)
{
auto test_profile = profile();
test_profile.offset_x = -2.5;
std::string error;
EXPECT_FALSE(test_profile.validate(error));
EXPECT_NE(error.find("offset_x"), std::string::npos);
EXPECT_NE(error.find("-2.5"), std::string::npos);
EXPECT_NE(error.find("> 0"), std::string::npos);
}
TEST(ReflectorPairProfile, CrossKeyAndConditionalPriorValidation)
{
std::string error;
auto test_profile = profile();
EXPECT_TRUE(test_profile.validate(error));
test_profile.has_prior = true;
EXPECT_FALSE(test_profile.validate(error));
EXPECT_NE(error.find("prior_position_tolerance"), std::string::npos);
test_profile.prior_position_tolerance = 0.1;
EXPECT_FALSE(test_profile.validate(error));
EXPECT_NE(error.find("prior_yaw_tolerance"), std::string::npos);
test_profile.prior_yaw_tolerance = 0.2;
EXPECT_TRUE(test_profile.validate(error));
test_profile = profile();
test_profile.tape_spacing = test_profile.tape_width;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.wall_min_span = test_profile.tape_spacing;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.tape_core_intensity = test_profile.tape_min_intensity - 1;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.wall_max_residual = test_profile.wall_max_rms / 2;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.width_tolerance = test_profile.tape_width;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.tape_min_points = 2;
EXPECT_FALSE(test_profile.validate(error));
test_profile = profile();
test_profile.wall_min_points_each_side = 2;
EXPECT_FALSE(test_profile.validate(error));
}
TEST(ReflectorPairGeometry, DistancesAnglesAndPhase)
{
for (double distance : {0.5, 1.0, 1.5, 2.0})
{
for (double degrees : {-50.0, -30.0, 0.0, 30.0, 50.0})
{
for (double phase : {0.0, 0.25, 0.5, 0.75})
{
wall_scan_sim::World world;
world.x = distance;
world.normal_yaw = kPi + degrees * kPi / 180.0;
const auto geometry = wall_scan_sim::geometry(kFrontStep, phase * kFrontStep);
const auto detection = detect(profile(), world, geometry);
ASSERT_TRUE(detection.valid) << distance << ' ' << degrees << ' ' << phase << ' ' << detection.reason;
const double bound = quantisationBound(world, kFrontStep);
EXPECT_LE(std::hypot(detection.marker.x - world.x, detection.marker.y - world.y), bound);
EXPECT_LT(yawError(detection.marker.yaw, world.normal_yaw), 1e-6);
EXPECT_LE(std::abs(detection.spacing - 0.4), 2.0 * bound);
}
}
}
}
TEST(ReflectorPairGeometry, NanoScaleAndReverseRayOrder)
{
wall_scan_sim::World world;
world.x = 1.5;
world.wall_intensity = 205;
world.tape_intensity = 255;
auto test_profile = profile();
test_profile.tape_min_intensity = 230;
test_profile.tape_core_intensity = 245;
const auto forward_order = detect(test_profile, world, wall_scan_sim::geometry(kNanoStep));
const auto reverse_order = detect(test_profile, world, wall_scan_sim::geometry(kNanoStep, 0.0, true));
ASSERT_TRUE(forward_order.valid) << forward_order.reason;
ASSERT_TRUE(reverse_order.valid) << reverse_order.reason;
EXPECT_NEAR(forward_order.marker.x, reverse_order.marker.x, 1e-9);
EXPECT_NEAR(forward_order.marker.y, reverse_order.marker.y, 1e-9);
EXPECT_LT(yawError(forward_order.marker.yaw, reverse_order.marker.yaw), 1e-9);
EXPECT_LE(std::hypot(forward_order.marker.x-world.x, forward_order.marker.y-world.y), quantisationBound(world, kNanoStep));
}
TEST(ReflectorPairGeometry, TargetOffsetsAndPriorFrameYawWrap)
{
wall_scan_sim::World world;
auto test_profile = profile();
test_profile.offset_y = 0.12;
test_profile.offset_yaw = 0.15;
const ReflectorPose2D scan_in_prior{0.3, -0.2, 0.1};
const auto detection = detect(test_profile, world, wall_scan_sim::geometry(kFrontStep), {}, scan_in_prior);
ASSERT_TRUE(detection.valid) << detection.reason;
EXPECT_NEAR(detection.target.x, detection.marker.x + test_profile.offset_x*std::cos(detection.marker.yaw) - test_profile.offset_y*std::sin(detection.marker.yaw), 1e-9);
EXPECT_NEAR(detection.target.y, detection.marker.y + test_profile.offset_x*std::sin(detection.marker.yaw) + test_profile.offset_y*std::cos(detection.marker.yaw), 1e-9);
EXPECT_LT(yawError(detection.target.yaw, detection.marker.yaw + test_profile.offset_yaw), 1e-9);
EXPECT_LT(yawError(detection.marker.yaw, -kPi + 0.1), 1e-9);
EXPECT_NEAR(detection.marker.x, scan_in_prior.x + std::cos(scan_in_prior.yaw), quantisationBound(world,kFrontStep));
}
TEST(ReflectorPairGeometry, RejectsParallelEdgesAndInvalidTransform)
{
wall_scan_sim::World world;
world.normal_yaw = kPi + 50*kPi/180;
auto test_profile = profile();
test_profile.min_ray_wall_cos = 0.95;
const auto detection = detect(test_profile,world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason, "edge_parallel");
ReflectorPose2D scan_in_prior;
scan_in_prior.yaw = std::numeric_limits<double>::quiet_NaN();
EXPECT_EQ(detect(profile(),world,wall_scan_sim::geometry(kFrontStep),{},scan_in_prior).reason, "invalid_limits_or_transform");
}
TEST(ReflectorPairBloom, BrightRangeBiasAndAsymmetricBloom)
{
wall_scan_sim::World world;
world.x = 1.2;
world.bloom_left = 1;
world.bloom_right = 2;
auto test_profile = profile();
test_profile.tape_bloom_max_angle = 2*kFrontStep;
test_profile.tape_plateau_min_fraction = 0.45;
const auto geometry = wall_scan_sim::geometry(kFrontStep);
const auto ref = detect(test_profile,world,geometry);
ASSERT_TRUE(ref.valid) << ref.reason;
for (double bias : {-0.01, -0.02, -0.03, 0.03})
{
world.bright_range_bias = bias;
const auto detection = detect(test_profile,world,geometry);
ASSERT_TRUE(detection.valid) << detection.reason;
EXPECT_NEAR(detection.marker.x, ref.marker.x, 1e-10);
EXPECT_NEAR(detection.marker.y, ref.marker.y, 1e-10);
EXPECT_LE(std::hypot(detection.marker.x-world.x,detection.marker.y-world.y), quantisationBound(world,kFrontStep));
}
}
TEST(ReflectorPairBloom, CoreTiesAndInseparableOrHighUncertaintyReject)
{
wall_scan_sim::World world;
world.bloom_left = 4;
world.bloom_right = 4;
auto test_profile = profile();
test_profile.tape_plateau_min_fraction = 0.95;
EXPECT_FALSE(detect(test_profile,world,wall_scan_sim::geometry(kFrontStep)).valid);
world.bloom_left = 0;
world.bloom_right = 0;
test_profile = profile();
test_profile.edge_bias_bound = 0.03;
test_profile.max_edge_uncertainty = 0.02;
const auto detection = detect(test_profile,world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason, "edge_uncertainty");
// Hai core dài bằng nhau trong một run: không chọn tùy ý.
test_profile = profile();
const auto geometry = wall_scan_sim::geometry(kFrontStep);
auto scan = wall_scan_sim::rayCast(world,geometry);
for (std::size_t index = 1; index + 1 < scan.ranges.size(); ++index)
{
if (scan.intensities[index] >= test_profile.tape_core_intensity &&
scan.intensities[index - 1] < test_profile.tape_min_intensity)
{
std::size_t end = index;
while (end < scan.intensities.size() &&
scan.intensities[end] >= test_profile.tape_core_intensity)
{
++end;
}
ASSERT_GE(end - index, 7u);
for (std::size_t ray = index; ray < end; ++ray)
{
scan.intensities[ray] = 9000;
}
for (std::size_t ray = 0; ray < 3; ++ray)
{
scan.intensities[index + ray] = 20000;
scan.intensities[end - 1 - ray] = 20000;
}
break;
}
}
ReflectorPairMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(test_profile,error));
const auto tied = matcher.match(geometry,scan.ranges,scan.intensities,{},{});
EXPECT_FALSE(tied.valid);
EXPECT_EQ(tied.reason, "insufficient_candidates_or_core");
}
TEST(ReflectorPairPairing, WrongWidthSpacingAndOcclusionReject)
{
wall_scan_sim::World world;
const auto geometry = wall_scan_sim::geometry(kFrontStep);
world.tapes[1].center = 0.30;
auto detection = detect(profile(),world,geometry);
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"spacing");
world.tapes[1].center = 0.2;
world.tapes[1].width = 0.09;
detection = detect(profile(),world,geometry);
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"width");
world.tapes[1].width = 0.05;
world.boxes.push_back({0.5,0.6,0.08,0.16,1000});
detection = detect(profile(),world,geometry);
EXPECT_FALSE(detection.valid);
}
TEST(ReflectorPairPairing, OccluderWithinWallSupportRejects)
{
wall_scan_sim::World world;
world.boxes.push_back({0.75,0.8,-0.05,0.05,1000});
const auto detection = detect(profile(),world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_TRUE(detection.reason == "wall_gap_or_occlusion" || detection.reason == "wall_residual_or_occlusion" ||
detection.reason == "wall_not_same_line") << detection.reason;
}
TEST(ReflectorPairPairing, BrightObjectInFrontOfTapeIsNotSameWall)
{
wall_scan_sim::World world;
world.boxes.push_back({0.50, 0.51, 0.087, 0.113, 20000});
const auto detection = detect(profile(),world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason, "bright_off_wall");
}
TEST(ReflectorPairPairing, ThreeBrightRunsAndTwoPairsAreAmbiguous)
{
wall_scan_sim::World world;
world.tapes = {{-0.4,0.05},{0.0,0.05},{0.4,0.05}};
auto detection = detect(profile(),world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"ambiguous");
EXPECT_EQ(detection.valid_pairs,2u);
world.tapes = {{-0.7,0.05},{-0.3,0.05},{0.3,0.05},{0.7,0.05}};
detection = detect(profile(),world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"ambiguous");
EXPECT_GE(detection.valid_pairs,2u);
}
TEST(ReflectorPairPairing, PriorAndFanOperateOnMarkerNotTarget)
{
wall_scan_sim::World world;
auto test_profile = profile();
test_profile.has_prior = true;
test_profile.prior_x = 1.0;
test_profile.prior_y = 0.0;
test_profile.prior_yaw = kPi;
test_profile.prior_position_tolerance = 0.05;
test_profile.prior_yaw_tolerance = 0.1;
auto detection = detect(test_profile,world,wall_scan_sim::geometry(kFrontStep));
ASSERT_TRUE(detection.valid) << detection.reason;
test_profile.prior_y = 0.5;
detection = detect(test_profile,world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"prior");
test_profile = profile();
test_profile.search_center_yaw = kPi;
test_profile.search_fov = 0.2;
detection = detect(test_profile,world,wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(detection.valid);
EXPECT_EQ(detection.reason,"search_fov");
}
TEST(ReflectorPairInputs, EmptyMismatchedAndInvalidRays)
{
const auto geometry = wall_scan_sim::geometry(kFrontStep);
wall_scan_sim::World world;
auto scan = wall_scan_sim::rayCast(world,geometry);
ReflectorPairMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(profile(),error));
EXPECT_EQ(matcher.match(geometry,scan.ranges,{}, {},{}).reason,"no_intensity_data");
auto wrong = scan.intensities;
wrong.pop_back();
EXPECT_EQ(matcher.match(geometry,scan.ranges,wrong,{},{}).reason,"intensity_size_mismatch");
robot_line_extraction::ScanGeometry empty;
EXPECT_FALSE(matcher.match(empty,{}, {},{},{}).valid);
std::fill(scan.ranges.begin(),scan.ranges.end(),std::numeric_limits<double>::quiet_NaN());
EXPECT_FALSE(matcher.match(geometry,scan.ranges,scan.intensities,{},{}).valid);
scan = wall_scan_sim::rayCast(world,geometry);
for (std::size_t index = 1; index < scan.ranges.size(); ++index)
{
if (scan.intensities[index] >= 15000 && scan.intensities[index - 1] < 15000)
{
scan.ranges[index - 1] = std::numeric_limits<double>::infinity();
break;
}
}
EXPECT_FALSE(matcher.match(geometry,scan.ranges,scan.intensities,{},{}).valid);
scan = wall_scan_sim::rayCast(world,geometry);
for (std::size_t index = 1; index < scan.ranges.size(); ++index)
{
if (scan.intensities[index] >= 15000 && scan.intensities[index - 1] < 15000)
{
scan.intensities[index - 1] = std::numeric_limits<float>::quiet_NaN();
break;
}
}
EXPECT_FALSE(matcher.match(geometry,scan.ranges,scan.intensities,{},{}).valid);
}
TEST(ReflectorPairInputs, ZeroRangesInfiniteIntensityAndShortWallReject)
{
wall_scan_sim::World world;
const auto geometry=wall_scan_sim::geometry(kFrontStep);
auto scan=wall_scan_sim::rayCast(world,geometry);
ReflectorPairMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(profile(),error));
for (auto& range : scan.ranges)
{
range = 0.0;
}
EXPECT_FALSE(matcher.match(geometry,scan.ranges,scan.intensities,{},{}).valid);
scan=wall_scan_sim::rayCast(world,geometry);
for (auto& intensity : scan.intensities)
{
if (intensity >= 15000)
{
intensity = std::numeric_limits<float>::infinity();
}
}
EXPECT_FALSE(matcher.match(geometry,scan.ranges,scan.intensities,{},{}).valid);
world.half_length=0.23;
EXPECT_FALSE(detect(profile(),world,geometry).valid);
}
TEST(ReflectorPairInputs, RejectsCapacityAndPreservesPreviousValidProfile)
{
wall_scan_sim::World world;
world.tapes={{-0.4,0.05},{0,0.05},{0.4,0.05}};
auto geometry=wall_scan_sim::geometry(kFrontStep);
auto scan=wall_scan_sim::rayCast(world,geometry);
ReflectorPairMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(profile(),error));
auto bad=profile();
bad.tape_width=0;
EXPECT_FALSE(matcher.configure(bad,error));
EXPECT_TRUE(matcher.configured());
ReflectorPairLimits limits;
limits.max_scan_rays=100;
EXPECT_EQ(matcher.match(geometry,scan.ranges,scan.intensities,limits,{}).reason,"capacity_scan_rays");
limits.max_scan_rays=4096;
limits.max_candidates=2;
EXPECT_EQ(matcher.match(geometry,scan.ranges,scan.intensities,limits,{}).reason,"capacity_candidates");
limits.max_candidates=16;
limits.max_pairs=1;
EXPECT_EQ(matcher.match(geometry,scan.ranges,scan.intensities,limits,{}).reason,"capacity_pairs");
}
TEST(ReflectorPairInputs, DeterministicNoiseWithinQuantisationPlusNoiseAllowance)
{
wall_scan_sim::World world;
world.noise_sigma=0.0002;
const auto detection=detect(profile(),world,wall_scan_sim::geometry(kFrontStep));
ASSERT_TRUE(detection.valid) << detection.reason;
// Nhiễu Gaussian không có cận tất định: 6σ ở đây là giả định riêng cho mẫu seed cố định.
const double bound=quantisationBound(world,kFrontStep)+6*world.noise_sigma;
EXPECT_LE(std::hypot(detection.marker.x-world.x,detection.marker.y-world.y),bound);
}
TEST(ReflectorPairNoise, FlatWallAtRealisticNoiseLevels)
{
// TEST-ONLY: RMS = 2σ, max residual = 5σ; cổng nhóm = 1.2σ, tối thiểu 25 tia mỗi phía.
// Cận 6σ dùng N, Sxx và vị trí mép từ support thật (fitNoiseBounds), có tính góc nhìn.
// Đây là cận thống kê tuyến tính cho seed cố định, không phải bảo đảm Gaussian tuyệt đối.
for (const double sigma : {0.005, 0.010})
{
for (const double distance : {1.0, 2.0})
{
for (const double angle_degrees : {0.0, 30.0})
{
for (const unsigned int seed : {3u, 7u, 19u, 42u})
{
wall_scan_sim::World world;
world.x = distance;
world.normal_yaw = kPi + angle_degrees * kPi / 180.0;
world.noise_sigma = sigma;
world.seed = seed;
auto test_profile = profile();
test_profile.wall_min_points_each_side = 25;
test_profile.wall_max_rms = 2.0 * sigma;
test_profile.wall_max_residual = 5.0 * sigma;
test_profile.wall_merge_distance = 1.2 * sigma;
const auto result = detect(test_profile, world, wall_scan_sim::geometry(kFrontStep));
ASSERT_TRUE(result.valid) << sigma << ' ' << distance << ' ' << angle_degrees << ' '
<< seed << ' ' << result.reason;
const auto geometry = wall_scan_sim::geometry(kFrontStep);
const auto noise_bounds = fitNoiseBounds(world, geometry, result,
test_profile.min_ray_wall_cos);
ASSERT_GT(noise_bounds[0], 0.0);
ASSERT_GT(noise_bounds[1], 0.0);
EXPECT_LE(std::hypot(result.marker.x - world.x, result.marker.y - world.y),
quantisationBound(world, kFrontStep) + noise_bounds[0]);
EXPECT_LE(yawError(result.marker.yaw, world.normal_yaw), noise_bounds[1]);
}
}
}
}
}
TEST(ReflectorPairNoise, ThreeCentimetrePlaneStepRejectsWithSameNoiseProfile)
{
for (const double sigma : {0.005, 0.010})
{
wall_scan_sim::World world;
world.x = 1.0;
world.step_start = 0.225;
world.step_depth = 0.03;
world.noise_sigma = sigma;
world.seed = 7;
auto test_profile = profile();
test_profile.wall_min_points_each_side = 25;
test_profile.wall_max_rms = 2.0 * sigma;
test_profile.wall_max_residual = 5.0 * sigma;
test_profile.wall_merge_distance = 1.2 * sigma;
const auto result = detect(test_profile, world, wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(result.valid);
EXPECT_TRUE(result.reason == "wall_not_same_line" ||
result.reason == "wall_residual_or_occlusion") << result.reason;
}
}
TEST(ReflectorPairWindow, WallEndAfterEnoughSupportKeepsOtherSideGrowing)
{
wall_scan_sim::World world;
world.max_along = 0.30;
auto test_profile = profile();
test_profile.wall_min_span = 0.90;
const auto result = detect(test_profile, world, wall_scan_sim::geometry(kFrontStep));
EXPECT_TRUE(result.valid) << result.reason;
}
TEST(ReflectorPairWindow, InvalidRayInsideSupportStillRejects)
{
wall_scan_sim::World world;
const auto geometry = wall_scan_sim::geometry(kFrontStep);
auto scan = wall_scan_sim::rayCast(world, geometry);
const auto center_ray = static_cast<std::size_t>(std::lround(-geometry.angle_min /
geometry.angle_increment));
ASSERT_LT(center_ray, scan.ranges.size());
ASSERT_LT(scan.intensities[center_ray], 8000.0f);
scan.ranges[center_ray] = std::numeric_limits<double>::quiet_NaN();
ReflectorPairMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(profile(), error)) << error;
const auto result = matcher.match(geometry, scan.ranges, scan.intensities, {}, {});
EXPECT_FALSE(result.valid);
EXPECT_EQ(result.reason, "wall_occluded_or_invalid");
}
TEST(ReflectorPairWindow, WallEndBeforeEnoughSupportRejects)
{
wall_scan_sim::World world;
world.max_along = 0.235;
auto test_profile = profile();
test_profile.wall_min_span = 0.90;
const auto result = detect(test_profile, world, wall_scan_sim::geometry(kFrontStep));
EXPECT_FALSE(result.valid);
EXPECT_EQ(result.reason, "wall_support");
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

202
test/wall_scan_sim.h Normal file
View File

@@ -0,0 +1,202 @@
#ifndef DOCK_PATTERN_DETECTOR_TEST_WALL_SCAN_SIM_H_
#define DOCK_PATTERN_DETECTOR_TEST_WALL_SCAN_SIM_H_
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <random>
#include <vector>
#include <robot_line_extraction/types.h>
namespace wall_scan_sim
{
struct Interval
{
double center = 0.0;
double width = 0.05;
};
struct Box
{
double min_x;
double max_x;
double min_y;
double max_y;
float intensity = 1000.0f;
};
struct Scan
{
std::vector<double> ranges;
std::vector<float> intensities;
};
struct World
{
double x = 1.0;
double y = 0.0;
double normal_yaw = 3.14159265358979323846;
double half_length = 2.0;
double min_along = -std::numeric_limits<double>::infinity();
double max_along = std::numeric_limits<double>::infinity();
double step_start = std::numeric_limits<double>::infinity();
double step_depth = 0.0;
float wall_intensity = 1000.0f;
float tape_intensity = 20000.0f;
float bloom_intensity = 9000.0f;
std::vector<Interval> tapes{{-0.2, 0.05}, {0.2, 0.05}};
std::vector<Box> boxes;
int bloom_left = 0;
int bloom_right = 0;
double bright_range_bias = 0.0;
double noise_sigma = 0.0;
unsigned int seed = 7;
};
inline robot_line_extraction::ScanGeometry geometry(double step, double phase = 0.0,
bool reversed = false)
{
robot_line_extraction::ScanGeometry scan_geometry;
scan_geometry.size = static_cast<std::size_t>(std::ceil(2.0 * 3.14159265358979323846 / step));
scan_geometry.angle_min = -3.14159265358979323846 + phase;
scan_geometry.angle_increment = step;
if (reversed)
{
scan_geometry.angle_min += (scan_geometry.size - 1) * step;
scan_geometry.angle_increment = -step;
}
return scan_geometry;
}
inline Scan rayCast(const World& world, const robot_line_extraction::ScanGeometry& scan_geometry)
{
Scan scan;
const double infinity = std::numeric_limits<double>::infinity();
scan.ranges.assign(scan_geometry.size, infinity);
scan.intensities.assign(scan_geometry.size, 0.0f);
const double normal_x = std::cos(world.normal_yaw);
const double normal_y = std::sin(world.normal_yaw);
const double tangent_x = -normal_y;
const double tangent_y = normal_x;
const double rho = normal_x * world.x + normal_y * world.y;
std::mt19937 random(world.seed);
std::normal_distribution<double> noise(0.0, world.noise_sigma);
std::vector<bool> is_tape(scan_geometry.size, false);
std::vector<bool> wall_hit(scan_geometry.size, false);
for (std::size_t index = 0; index < scan_geometry.size; ++index)
{
const double angle = scan_geometry.angle_min + index * scan_geometry.angle_increment;
const double ray_x = std::cos(angle);
const double ray_y = std::sin(angle);
const double denominator = normal_x * ray_x + normal_y * ray_y;
if (std::abs(denominator) > 1e-12)
{
double range = rho / denominator;
double along = tangent_x * (range * ray_x - world.x) + tangent_y * (range * ray_y - world.y);
if (along >= world.step_start)
{
range = (rho - world.step_depth) / denominator;
along = tangent_x * (range * ray_x - world.x) + tangent_y * (range * ray_y - world.y);
}
if (range > 0.0 && std::abs(along) <= world.half_length &&
along >= world.min_along && along <= world.max_along)
{
scan.ranges[index] = range;
wall_hit[index] = true;
scan.intensities[index] = world.wall_intensity;
for (const auto& tape : world.tapes)
{
if (std::abs(along - tape.center) <= tape.width / 2.0)
{
is_tape[index] = true;
scan.intensities[index] = world.tape_intensity;
}
}
}
}
// Ray casting với hộp chắn, lấy giao điểm gần nhất theo phương pháp slabs.
for (const auto& box : world.boxes)
{
double near = 0.0;
double far = infinity;
const auto slab = [&near, &far](double component, double minimum, double maximum)
{
if (std::abs(component) < 1e-12)
{
return minimum <= 0.0 && maximum >= 0.0;
}
double first = minimum / component;
double last = maximum / component;
if (first > last)
{
std::swap(first, last);
}
near = std::max(near, first);
far = std::min(far, last);
return far >= near;
};
if (slab(ray_x, box.min_x, box.max_x) && slab(ray_y, box.min_y, box.max_y) &&
near > 0.0 && near < scan.ranges[index])
{
scan.ranges[index] = near;
scan.intensities[index] = box.intensity;
is_tape[index] = false;
wall_hit[index] = false;
}
}
}
for (std::size_t index = 0; index < scan_geometry.size;)
{
if (!is_tape[index])
{
++index;
continue;
}
const std::size_t first = index;
while (index < scan_geometry.size && is_tape[index])
{
++index;
}
const std::size_t last = index - 1;
for (int offset = 1; offset <= world.bloom_left && static_cast<std::size_t>(offset) <= first;
++offset)
{
if (wall_hit[first - offset] && !is_tape[first - offset])
{
scan.intensities[first - offset] = world.wall_intensity +
(world.bloom_intensity - world.wall_intensity) *
static_cast<float>(world.bloom_left - offset + 1) / world.bloom_left;
}
}
for (int offset = 1; offset <= world.bloom_right && last + offset < scan_geometry.size;
++offset)
{
if (wall_hit[last + offset] && !is_tape[last + offset])
{
scan.intensities[last + offset] = world.wall_intensity +
(world.bloom_intensity - world.wall_intensity) *
static_cast<float>(world.bloom_right - offset + 1) / world.bloom_right;
}
}
}
for (std::size_t index = 0; index < scan_geometry.size; ++index)
{
if (!std::isfinite(scan.ranges[index]))
{
continue;
}
if (is_tape[index])
{
scan.ranges[index] += world.bright_range_bias;
}
if (world.noise_sigma > 0.0)
{
scan.ranges[index] += noise(random);
}
}
return scan;
}
} // namespace wall_scan_sim
#endif // DOCK_PATTERN_DETECTOR_TEST_WALL_SCAN_SIM_H_