slam,odometry,perception: di tren doc (G4, slam.yaml slope.enabled, mac dinh tat) -- z robot = tich -ds*sin(pitch IMU) kep phang < 1.5 do va neo vao ban do (HeightEstimator), odometry ngang, scan cho SLAM bu nghieng + bo tia cham san/doc theo ban do do cao tu depth (ScanLeveler, ElevationMap), z/roll/pitch luu vao node + do thi z 1-D + mat san theo node (height_map), voxel dat o z that va vat can tinh tu san cuc bo, xoa tuong gia LiDAR tren doc noi camera da thay mat san, web z uoc luong, --sim-imu-hz

This commit is contained in:
trung09122002
2026-10-04 00:03:02 +07:00
parent 6735b53423
commit f064dcf3ec
32 changed files with 1799 additions and 10 deletions

View File

@@ -115,6 +115,19 @@ Dinh vi lai tu dong: dat robot o cho khac, **khong** cho pose ban dau.
--slam-reloc --slam-reloc-auto 2>&1 | tee logs/sim_reloc.log
```
Di tren doc: bat `slope.enabled: true` trong `slam.yaml` (xem ghi chu khoi `slope:`).
World thu `slope_test.world` co 5 lan doc 5/10/15/20/30 do noi hai mat bang chenh 1.5 m.
`--sim-imu-hz 100` cho IMU mo phong giong WT61PC sau khi doi 115200 baud.
```sh
./build/app/vslam_node --sim --sim-gl --sim-imu-hz 100 --world resources/worlds/slope_test.world \
--x 6.4 --y 4.0 --yaw 1.5708 --max-speed 0.3 --token t \
--slam --slam-db "slope_{stamp}.db" --slam-mode mapping 2>&1 | tee logs/sim_slope.log
```
Web hien `z uoc luong` canh `z that`. Robot that: **doi WT61PC sang 115200 baud / 100 Hz
va dat `mcu.baud: 115200` truoc khi bat** -- IMU 10 Hz cho sai ~19 cm moi doc 1.5 m (sim).
### Robot that (Jetson)
```sh

View File

@@ -624,6 +624,45 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"slam.yaml voxel: obstacle_z_min phai nho hon obstacle_z_max");
}
}
// Khoi `slope:` -- di tren doc. Vang mat = tat.
if (!root["slope"].IsNull()) {
const ConfigNode v = root["slope"];
const StatusResponse r = Reject(
v, "slam.yaml slope",
{"enabled", "clamp_deg", "sigma_rel", "sigma_flat", "sigma_anchor", "anchor_radius_m",
"horizontal_odom", "level_scan", "floor_margin_m", "below_ground_m",
"elevation_cell_m", "elevation_radius_m", "elevation_max_depth_m", "depth_stride"});
if (!r.ok()) return r;
SlopeConfig& c = out->slope;
c.enabled = v.get<bool>("enabled", c.enabled);
c.clamp_deg = v.get<double>("clamp_deg", c.clamp_deg);
c.sigma_rel = v.get<double>("sigma_rel", c.sigma_rel);
c.sigma_flat = v.get<double>("sigma_flat", c.sigma_flat);
c.sigma_anchor = v.get<double>("sigma_anchor", c.sigma_anchor);
c.anchor_radius_m = v.get<double>("anchor_radius_m", c.anchor_radius_m);
c.horizontal_odom = v.get<bool>("horizontal_odom", c.horizontal_odom);
c.level_scan = v.get<bool>("level_scan", c.level_scan);
c.floor_margin_m = v.get<double>("floor_margin_m", c.floor_margin_m);
c.below_ground_m = v.get<double>("below_ground_m", c.below_ground_m);
c.elevation_cell_m = v.get<double>("elevation_cell_m", c.elevation_cell_m);
c.elevation_radius_m = v.get<double>("elevation_radius_m", c.elevation_radius_m);
c.elevation_max_depth_m = v.get<double>("elevation_max_depth_m", c.elevation_max_depth_m);
c.depth_stride = v.get<int>("depth_stride", c.depth_stride);
if (c.clamp_deg < 0.0 || c.clamp_deg > 10.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope.clamp_deg phai trong [0, 10]");
}
if (c.sigma_rel < 0.0 || c.sigma_flat < 0.0 || c.sigma_anchor <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope: sigma_rel/sigma_flat >= 0, sigma_anchor > 0");
}
if (c.elevation_cell_m <= 0.0 || c.elevation_radius_m <= 0.0 || c.depth_stride < 1) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml slope: elevation_cell_m, elevation_radius_m > 0, depth_stride >= 1");
}
}
}
#endif

View File

@@ -66,6 +66,30 @@ struct VoxelConfig {
size_t min_node_hits = 1;
};
// Di tren doc (G4). Doc tu khoi `slope:` trong slam.yaml. enabled = false thi
// moi duong cu giu nguyen tung byte -- xem slam.yaml.
struct SlopeConfig {
bool enabled = false;
// z = tich -ds*sin(pitch IMU); |pitch| < clamp -> coi la phang (dz = 0).
double clamp_deg = 1.5;
double sigma_rel = 0.05;
double sigma_flat = 0.005;
double sigma_anchor = 0.03;
// Neo z vao node ban do trong ban kinh nay (che do localization).
double anchor_radius_m = 0.6;
// Quang duong banh x cos(pitch) truoc khi vao EKF (doc 15 do: -3.4%).
bool horizontal_odom = true;
// Bu nghieng scan + bo tia cham san cho SLAM / dinh vi lai (KHONG cho an toan).
bool level_scan = true;
double floor_margin_m = 0.08;
double below_ground_m = 0.05;
// Ban do do cao san cuc bo tu depth camera.
double elevation_cell_m = 0.10;
double elevation_radius_m = 8.0;
double elevation_max_depth_m = 4.0;
int depth_stride = 4;
};
struct ThreadConfig {
int safety_priority = 50;
int driver_priority = 45;
@@ -127,6 +151,7 @@ struct AppConfig {
ThreadConfig threads;
SlamRuntimeConfig slam_runtime;
VoxelConfig voxel;
SlopeConfig slope;
RecordConfig record;
std::string log_level = "info";

View File

@@ -59,6 +59,8 @@ void Usage(const char* argv0) {
" --no-gamepad tat tay cam du system.yaml co bat\n"
" --sim-gl ve camera mo phong bang GPU: depth + anh IR co\n"
" texture (can --world, build VSLAM_SIM_WITH_GL=ON)\n"
" --sim-imu-hz N IMU mo phong phat N Hz (mac dinh moi buoc vat ly,\n"
" 200 Hz). 100 = WT61PC sau khi doi 115200 baud.\n"
" --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
" LiDAR/depth KHONG thay; chi sieu am + bumper.\n"
" --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
@@ -166,6 +168,7 @@ int main(int argc, char** argv) {
else if (a == "--no-gamepad") opts.gamepad_override = -1;
else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str());
else if (a == "--sim-gl") opts.sim_gl = true;
else if (a == "--sim-imu-hz") opts.sim_imu_hz = std::atof(next().c_str());
else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
else if (a == "--slam") opts.force_slam = true;
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }

View File

@@ -81,6 +81,7 @@ StatusResponse Runtime::OpenSource() {
sc.lidar_rate_hz = cfg_->sensors.lidar_hz;
sc.camera_rate_hz = cfg_->sensors.camera_hz;
sc.imu_rate_hz = cfg_->sensors.imu_hz;
sc.imu_output_hz = opts_.sim_imu_hz;
sc.enable_depth_camera = cfg_->sensors.camera_enable;
source_->sim.reset(new SimSource(sc));
@@ -629,6 +630,39 @@ StatusResponse Runtime::Start() {
}
#endif
// ---- Di tren doc (slam.yaml `slope:`) ----
// Tat thi khong tao gi: moi duong ben duoi kiem `slope_on_` truoc.
slope_on_ = cfg_->slope.enabled;
if (slope_on_) {
const SlopeConfig& sp = cfg_->slope;
HeightEstimatorConfig hc;
hc.clamp_rad = sp.clamp_deg * M_PI / 180.0;
hc.sigma_rel = sp.sigma_rel;
hc.sigma_flat = sp.sigma_flat;
hc.sigma_anchor = sp.sigma_anchor;
height_.reset(new HeightEstimator(hc));
ElevationMapConfig ec;
ec.cell_m = sp.elevation_cell_m;
ec.radius_m = sp.elevation_radius_m;
elev_.reset(new ElevationMap(ec));
level_cfg_.floor_margin = sp.floor_margin_m;
level_cfg_.below_ground = sp.below_ground_m;
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base_static_)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slope: robot.yaml khong co duong laser -> base_link");
}
have_cam_to_base_ = cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame,
&cam_to_base_static_);
#ifdef VSLAM_HAVE_SLAM
if (slam_) slam_->SetUseHeights(true);
#endif
VSLAM_INFO("slope: BAT -- z = tich -ds*sin(pitch IMU), kep phang < " << sp.clamp_deg
<< " do, neo vao node trong " << sp.anchor_radius_m << " m; odometry ngang "
<< (sp.horizontal_odom ? "BAT" : "tat") << "; bu nghieng scan cho SLAM "
<< (sp.level_scan ? "BAT" : "tat") << " (an toan van dung scan tho). "
<< "Can IMU >= 100 Hz -- 10 Hz cho sai ~19 cm moi doc 1.5 m (sim G3).");
}
{
const StatusResponse st = Wire();
if (!st.ok()) return st;
@@ -1080,12 +1114,15 @@ void Runtime::SlamLoop() {
LaserScanPtr scan;
{
std::lock_guard<std::mutex> lk(scan_mu_);
scan = latest_scan_; // chi copy shared_ptr
// Ban cho SLAM: bu nghieng khi di tren doc, con lai CHINH latest_scan_.
scan = latest_slam_scan_; // chi copy shared_ptr
}
Pose2D odom;
bool have_odom = false;
double z_now = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
if (slope_on_) z_now = height_->z();
// ⚠️ Dua cho SLAM pose cua EKF, KHONG phai cua wheel_odom.
//
// `map_correction` ma RTAB-Map tra ve la phep bien doi
@@ -1167,10 +1204,53 @@ void Runtime::SlamLoop() {
in.depth_info = depth_info.get();
in.infra1 = infra1.get();
in.camera_to_base = depth ? &cam_now : nullptr;
if (slope_on_) {
in.has_height = true;
in.z = z_now;
in.roll = tilt_roll_.load(std::memory_order_relaxed);
in.pitch = tilt_pitch_.load(std::memory_order_relaxed);
}
// --- KHONG MOT MUTEX NAO duoc giu qua dong nay ---
const SlamOutput out = slam_->Process(in);
// --- Di tren doc: z ban do + neo z robot ---
// Do thi z giai lai khi do thi doi (theo nhip, toi da 1 lan/giay -- getGraph
// va giai Cholesky vai ms cho ca nghin node). Neo: z robot keo ve mat san
// cua node gan nhat. O mapping node gan nhat thuong la chinh node vua tao
// (neo khong doi gi) -- co tac dung sau mot lan dong vong lam z do thi doi.
if (slope_on_) {
const auto now_h = std::chrono::steady_clock::now();
if (out.map_version != heights_version_ &&
std::chrono::duration<double>(now_h - heights_at_).count() >= 1.0) {
ZGraphConfig zc;
zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0;
zc.sigma_rel = cfg_->slope.sigma_rel;
size_t nz = 0;
if (slam_->UpdateHeights(zc, &nz).ok()) {
heights_version_ = out.map_version;
heights_at_ = now_h;
VSLAM_INFO_THROTTLE(30.0, "slope: do thi z " << nz << " node");
}
}
double z_ref = 0.0;
if (out.localized &&
slam_->HeightAt(out.pose_map.x, out.pose_map.y, cfg_->slope.anchor_radius_m, &z_ref)) {
std::lock_guard<std::mutex> lk(odom_mu_);
if (!height_anchored_) {
// Lan dau: robot co the dung o tang tren (z 1.5 m) trong khi uoc
// luong bat dau tu 0 -- cong cua Anchor() se tu choi mai.
height_->Reset(z_ref, cfg_->slope.sigma_anchor);
height_anchored_ = true;
VSLAM_INFO("slope: z robot = " << z_ref << " m theo ban do tai ("
<< out.pose_map.x << ", " << out.pose_map.y << ")");
} else if (!height_->Anchor(z_ref)) {
VSLAM_WARN_THROTTLE(10.0, "slope: bo neo z -- ban do " << z_ref << " m, uoc luong "
<< height_->z() << " m (node sai tang / sai cho?)");
}
}
}
bool need_map = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
@@ -1325,8 +1405,20 @@ void Runtime::SlamLoop() {
// Grid/* cua RTAB-Map keo pose lech (do 2026-09-24: TB 0.020 ->
// 0.052 m). Phai lam TRUOC khi `vg` bi move ben duoi.
if (st.ok()) {
// Di tren doc: do cao tinh tu SAN tai cho (mat doc khong la tuong).
const FloorModel* floor =
slope_on_ && !slam_->floor_model().empty() ? &slam_->floor_model() : nullptr;
if (floor != nullptr) {
// Tren doc lop LiDAR nhuong cho camera: tuong gia (LiDAR thay mat
// doc tu xa) xoa di noi camera da thay mat san. TRUOC lop vat
// can camera, de vat can that tren doc duoc danh lai.
const size_t nc = ClearLidarOnSeenRamps(
&grid, slam_->floor_cells(), cfg_->voxel.emit_size_m, *floor,
cfg_->slope.clamp_deg * M_PI / 180.0, 1.0);
VSLAM_INFO_THROTTLE(30.0, "slope: xoa " << nc << " o LiDAR tren doc (camera thay mat san)");
}
const size_t n = MarkVoxelObstacles(vg, cfg_->voxel.obstacle_z_min,
cfg_->voxel.obstacle_z_max, &grid);
cfg_->voxel.obstacle_z_max, &grid, floor);
VSLAM_INFO_THROTTLE(30.0, "slam: " << n << " o vat can tu camera ("
<< cfg_->voxel.obstacle_z_min << "-"
<< cfg_->voxel.obstacle_z_max
@@ -1932,6 +2024,25 @@ void Runtime::RelocFinish(const Pose2D& map_from_odom, const Pose2D& odom,
return;
}
reloc_active_ = false;
if (slope_on_) {
// z robot theo ban do tai pose vua chot. Do thi z chua giai (RTAB-Map chua
// nhan khung nao trong luc dinh vi) thi giai ngay.
if (slam_->floor_model().empty()) {
ZGraphConfig zc;
zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0;
zc.sigma_rel = cfg_->slope.sigma_rel;
slam_->UpdateHeights(zc);
}
double z_ref = 0.0;
if (slam_->HeightAt(pose.x, pose.y, 2.0, &z_ref)) {
std::lock_guard<std::mutex> lk(odom_mu_);
height_->Reset(z_ref, cfg_->slope.sigma_anchor);
height_anchored_ = true;
VSLAM_INFO("slope: z robot = " << z_ref << " m theo ban do sau dinh vi lai");
} else {
height_anchored_ = false;
}
}
if (opts_.slam_reloc_auto && reloc_exec_ != RelocExec::kOff) {
// Chot roi thi DUNG HAN tu chay, ke ca dang nhuong nguoi.
if (reloc_exec_ != RelocExec::kHalted) RelocCommand(0.0, 0.0);
@@ -2106,6 +2217,13 @@ void Runtime::WebLoop() {
snap.roll = tilt_roll_.load(std::memory_order_relaxed);
snap.pitch = tilt_pitch_.load(std::memory_order_relaxed);
snap.accel_ok = tilt_accel_ok_.load(std::memory_order_relaxed);
if (slope_on_) {
std::lock_guard<std::mutex> lk(odom_mu_);
snap.have_height = true;
snap.height_z = height_->z();
snap.height_sigma = height_->sigma();
snap.on_slope = height_->on_slope();
}
{
std::lock_guard<std::mutex> lk(safety_mu_);

View File

@@ -39,9 +39,12 @@
#include "app_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h"
#include "vslam/elevation_map.h"
#include "vslam/gamepad.h"
#include "vslam/geometry.h"
#include "vslam/height_estimator.h"
#include "vslam/perception_pipeline.h"
#include "vslam/scan_leveler.h"
#include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h"
#include "vslam/teleop_model.h"
@@ -93,6 +96,8 @@ struct RuntimeOptions {
// Ve camera mo phong bang GPU (vslam_sim_gl): depth + anh IR co texture.
// Can --world va node build voi -DVSLAM_SIM_WITH_GL=ON.
bool sim_gl = false;
// Tan so PHAT IMU cua sim (SimConfig::imu_output_hz). 0 = moi buoc vat ly.
double sim_imu_hz = 0.0;
bool force_slam = false; // --slam: ghi de slam.yaml enabled
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
std::string slam_db;
@@ -130,6 +135,8 @@ class Runtime {
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
// file .launch cua ban ROS.
StatusResponse Wire();
// Di tren doc: mot khung depth -> ban do do cao san cuc bo (luong camera).
void AddDepthToElevation(const CameraFrame& f);
// runtime.cc
StatusResponse OpenSource();
@@ -231,6 +238,9 @@ class Runtime {
// web_tx doc.
mutable std::mutex scan_mu_;
LaserScanPtr latest_scan_;
// Scan cho SLAM / dinh vi lai / canh lac: BU NGHIENG khi slope_on_ (xem
// ScanLeveler), con lai CHINH la latest_scan_. An toan + web dung ban tho.
LaserScanPtr latest_slam_scan_;
// odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
// kia chi doc ban sao pose.
@@ -476,6 +486,29 @@ class Runtime {
std::atomic<double> tilt_pitch_{0.0};
std::atomic<bool> tilt_accel_ok_{false};
// ---- Di tren doc (slam.yaml `slope:`) ----
// slope_on_ doc-only sau Start(). Tat thi KHONG doi tuong nao duoi day
// duoc tao, va moi duong cu giu nguyen.
bool slope_on_ = false;
// Duoi odom_mu_: luong encoder cong buoc, luong slam neo.
std::unique_ptr<HeightEstimator> height_;
// elev_mu_: ban do do cao san cuc bo + thong ke bu nghieng scan. THU TU
// KHOA: odom_mu_ roi moi elev_mu_, KHONG BAO GIO nguoc lai.
mutable std::mutex elev_mu_;
std::unique_ptr<ElevationMap> elev_;
ScanLevelerConfig level_cfg_;
ScanLevelStats level_stats_;
UnixTime elev_pruned_;
// Tinh, doc-only sau Start(): base_link <- laser_link / camera optical.
Transform laser_to_base_static_ = TransformIdentity();
Transform cam_to_base_static_ = TransformIdentity();
bool have_cam_to_base_ = false;
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).
bool height_anchored_ = false;
uint64_t heights_version_ = 0;
std::chrono::steady_clock::time_point heights_at_{};
std::atomic<bool> estop_{false};
std::atomic<bool> stop_{false};

View File

@@ -18,10 +18,14 @@
#include "runtime.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/json_parse.h"
#include "vslam/log.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace vslam {
@@ -36,8 +40,32 @@ StatusResponse Runtime::Wire() {
// rieng thi "cai nao chay truoc" la mot bay co that.
auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get());
// Di tren doc: ban BU NGHIENG + bo tia cham san cho SLAM / dinh vi lai.
// An toan va web giu ban tho. Tat thi hai con tro la MOT.
LaserScanPtr slam_scan = copy;
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
auto lv = std::make_shared<LaserScan>();
{
std::lock_guard<std::mutex> lk(elev_mu_);
LevelScan(*copy, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
}
slam_scan = lv;
}
std::lock_guard<std::mutex> lk(scan_mu_);
latest_scan_ = copy;
latest_slam_scan_ = slam_scan;
});
}
@@ -162,8 +190,23 @@ StatusResponse Runtime::Wire() {
gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9;
const double var_tr = std::max(o.twist.covariance[0] * dt * dt, 1e-12);
ekf_->UpdateOdomDelta(e.stamp, d_trans, d_theta, d_theta_gyro,
// Di tren doc: z cong tu quang duong DOC mat doc; EKF (SE(2)) nhan
// quang duong NGANG -- doc 15 do ma khong chieu thi ban do gian 3.4%.
double d_trans_ekf = d_trans;
if (slope_on_) {
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
height_->OnWheelStep(d_trans, pitch);
if (cfg_->slope.horizontal_odom) d_trans_ekf = d_trans * std::cos(pitch);
}
ekf_->UpdateOdomDelta(e.stamp, d_trans_ekf, d_theta, d_theta_gyro,
var_tr, var_th_enc, var_th_gyro);
if (slope_on_) {
// Vet banh: san duoi robot o dung z robot. Thu tu khoa odom_mu_ ->
// elev_mu_ (xem runtime.h).
const Pose2D p = ekf_->pose();
std::lock_guard<std::mutex> lk2(elev_mu_);
elev_->AddFootprint(p.x, p.y, height_->z(), 0.15, e.stamp);
}
}
gyro_dtheta_ = 0.0;
gyro_dt_ = 0.0;
@@ -234,6 +277,9 @@ StatusResponse Runtime::Wire() {
have_depth_ = true;
}
// Di tren doc: depth -> ban do do cao san cuc bo (cho ScanLeveler).
if (slope_on_ && have_cam_to_base_) AddDepthToElevation(f);
// Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
// camera.
@@ -397,4 +443,62 @@ StatusResponse Runtime::Wire() {
return StatusResponse::Ok();
}
void Runtime::AddDepthToElevation(const CameraFrame& f) {
const Image& d = *f.depth;
if (d.data == nullptr || d.width == 0 || d.height == 0) return;
const CameraInfo& ci = f.depth_info;
const double fx = ci.fx_binned(), fy = ci.fy_binned();
const double cx = ci.cx_binned(), cy = ci.cy_binned();
if (fx <= 0.0 || fy <= 0.0) return;
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
// base_footprint DA CAN <- optical: CHUNG TiltLift voi GravityAlign va
// ScanLeveler -- ba ban hinh hoc lech nhau la lop loi da co trong repo cu.
const Transform fp_from_cam = TransformCompose(
TiltLift(roll, pitch, cfg_->robot.geometry().wheel_radius), cam_to_base_static_);
const double c = std::cos(od.theta), s = std::sin(od.theta);
const int stride = std::max(1, cfg_->slope.depth_stride);
const double dmax = cfg_->slope.elevation_max_depth_m;
std::vector<PointXYZ> pts;
pts.reserve((d.width / stride + 1) * (d.height / stride + 1));
for (uint32_t v = 0; v < d.height; v += static_cast<uint32_t>(stride)) {
const uint8_t* row = d.data + static_cast<size_t>(v) * d.step;
for (uint32_t u = 0; u < d.width; u += static_cast<uint32_t>(stride)) {
double depth = 0.0;
if (d.format == PixelFormat::kMono16) {
uint16_t raw;
std::memcpy(&raw, row + 2 * u, 2);
depth = raw * static_cast<double>(d.depth_scale);
} else if (d.format == PixelFormat::kFloat32) {
float raw;
std::memcpy(&raw, row + 4 * u, 4);
depth = raw;
} else {
return;
}
if (!(depth > 0.2) || depth > dmax) continue;
const Point p = TransformPoint(
fp_from_cam, Point{(u - cx) / fx * depth, (v - cy) / fy * depth, depth});
pts.push_back(PointXYZ{static_cast<float>(od.x + c * p.x - s * p.y),
static_cast<float>(od.y + s * p.x + c * p.y),
static_cast<float>(z + p.z)});
}
}
std::lock_guard<std::mutex> lk(elev_mu_);
elev_->AddPoints(pts, f.header.stamp);
if (SecondsBetween(f.header.stamp, elev_pruned_) > 1.0) {
elev_->Prune(od.x, od.y, f.header.stamp);
elev_pruned_ = f.header.stamp;
}
}
} // namespace vslam

View File

@@ -170,6 +170,42 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# ============ DI TREN DOC (G4) ============
# Pose SLAM van la SE(2) (Reg/Force3DoF). Khoi nay them, BEN CANH no:
# * z robot = tich -ds*sin(pitch IMU), kep ve 0 khi |pitch| < clamp_deg, neo
# vao z cua node ban do o che do localization;
# * z / roll / pitch luu vao MOI node (userData cua RTAB-Map) -> ban do 3D va
# lop vat can tinh theo SAN cuc bo, doc khong con bi coi la tuong;
# * quang duong banh x cos(pitch) truoc EKF (odometry NGANG);
# * scan cho SLAM / dinh vi lai duoc bu nghieng va bo tia cham san / mat doc
# (ban do do cao san cuc bo tu depth). Lop AN TOAN van dung scan tho.
#
# ⚠️ CAN IMU >= 100 Hz. Do trong sim (G3, 03/10): IMU 100 Hz -> sai dz qua doc
# 1.5 m trung vi 1.8 cm, max 8 cm; IMU 10 Hz (WT61PC mac dinh, 9600 baud) ->
# 19 cm, va khong chinh bo loc nao cuu duoc. Doi cam bien sang 115200 baud /
# 100 Hz va dat `mcu.baud: 115200` trong sensors.yaml TRUOC khi bat.
#
# ⚠️ Gioi han NOI RO: doc that < clamp_deg bi coi la phang; tuong gia o chan
# doc LEN chi bo duoc khi camera da thay mat doc truoc do (re vao doc o goc
# hep thi con). Nhieu tang chong len nhau tai cung (x, y) KHONG ho tro.
#
# enabled: false = moi duong cu giu nguyen.
slope:
enabled: false
clamp_deg: 1.5 # duoi nguong = mat bang (doc xe lan >= 2.9 do)
sigma_rel: 0.05 # sai he thong tren doc: 5% do cao da leo
sigma_flat: 0.005 # troi tren mat bang, m / sqrt(m)
sigma_anchor: 0.03 # sai z ban do dung de neo
anchor_radius_m: 0.6 # neo vao node trong ban kinh nay
horizontal_odom: true
level_scan: true
floor_margin_m: 0.08 # cao hon san da biet duoi nguong = cham san
below_ground_m: 0.05 # thap hon mat dat duoi robot = san duoi chan doc
elevation_cell_m: 0.10
elevation_radius_m: 8.0
elevation_max_depth_m: 4.0
depth_stride: 4 # lay 1/4 x 1/4 diem anh depth cho ban do do cao
# ============ KHOI RTAB-MAP ============
# Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung
# mac dinh -- do la lua chon dung cho hau het truong hop.

View File

@@ -7,6 +7,7 @@ vslam_add_library(vslam_odometry
PUBLIC_HDRS
wheel_odometry.h
ekf_se2.h
height_estimator.h
PUBLIC_DEPS
vslam_common
FIND_DEPS

View File

@@ -0,0 +1,102 @@
#ifndef VSLAM_HEIGHT_ESTIMATOR_H
#define VSLAM_HEIGHT_ESTIMATOR_H
// Do cao z cua robot (base_footprint) khi di tren doc: bo loc Kalman MOT
// chieu.
//
// ================== VI SAO KHONG LAY TU SLAM ==================
// Pose SLAM la SE(2) (`Reg/Force3DoF`): RTAB-Map khong co z. Lop nay tinh z
// BEN CANH, roi z di vao node ban do (userData), ban do 3D va web.
//
// ================== DU DOAN ==================
// dz = -ds * sin(pitch)
// ds = quang duong banh (DOC mat doc), pitch = GravityAlign (duong = mui chuc
// xuong, nen len doc pitch am). Da so trong sim (G3, 03/10): IMU 100 Hz cho sai
// dz qua doc 1.5 m trung vi 1.8 cm, max 8 cm -- tot hon odometry thi giac F2M
// (6 / 33 cm). IMU 10 Hz thi KHONG du (19 cm): bo loc bu cua GravityAlign o
// 10 Hz co hang so thoi gian 5 s, bias gyro bi khuech dai thanh ~0.6 do.
//
// KEP MAT BANG: |pitch| < clamp -> dz = 0. Bias gia toc ke 0.02 m/s^2 lam
// lech pitch 0.12 do = 21 cm troi moi 100 m tren san PHANG; kep la triet tieu
// no. Doi lai: doc that < clamp (mac dinh 1.5 do) bi coi la phang -- 1 do qua
// 30 m la 52 cm mat. Doc tiep can cho xe lan la >= 2.9 do (1:20), nen nguong
// 1.5 do khong cat doc nao trong pham vi du an.
//
// ================== NEO ==================
// `Anchor(z_ref)`: z cua ban do tai cho robot dang dung (node gan nhat). Do
// khong chac lon dan theo do cao DA LEO tu lan neo truoc (sai ti le tren doc)
// va theo quang duong (sai nho tren phang), nen sau mot doan doc thi neo keo
// manh, tren san phang thi neo keo nhe. Lech qua xa -> tu choi (node sai tang,
// sai cho).
//
// ⚠️ Sai tren doc la sai HE THONG (truot banh, lech pitch cung dau suot doan
// doc), nen no tang TUYEN TINH theo do cao da leo: sigma = rel * sum|dz|.
// Cong phuong sai tung buoc (sum (rel*dz)^2) la coi moi buoc doc lap -- ra
// sigma 3 mm sau 1.4 m doc thay vi 7 cm, va neo khong keo duoc gi.
//
// Khong khoa: nguoi goi giu mutex (luong encoder ghi, luong slam neo).
#include <cstdint>
namespace vslam {
struct HeightEstimatorConfig {
double clamp_rad = 0.0261799; // 1.5 do: duoi nguong = mat bang, dz = 0
// Sai tuong doi cua dz tren doc (truot banh, sai pitch): sigma = rel * |dz|
// cong don tu lan neo truoc.
double sigma_rel = 0.05;
// Troi tren mat bang, m / sqrt(m): sigma = flat * sqrt(quang duong).
double sigma_flat = 0.005;
// Sai cua z ban do dung de neo (z node + noi suy theo doc), m.
double sigma_anchor = 0.03;
// Neo lech hon max(gate_min, gate_sigma * sigma) thi tu choi.
double gate_min = 0.30;
double gate_sigma = 4.0;
};
struct HeightEstimatorStats {
uint64_t steps = 0;
uint64_t clamped = 0; // buoc bi kep ve 0 (mat bang)
uint64_t anchors = 0;
uint64_t anchors_rejected = 0;
double last_anchor_err = 0.0; // z_ref - z truoc khi neo
double climbed = 0.0; // tong |dz| da cong
};
class HeightEstimator {
public:
explicit HeightEstimator(HeightEstimatorConfig cfg = {});
// Dat lai z (vd sau dinh vi lai: z cua ban do tai pose moi). sigma = do
// khong chac ban dau.
void Reset(double z, double sigma);
// Mot buoc banh: ds co dau (lui = am), pitch cua than LUC do.
void OnWheelStep(double ds, double pitch);
// Keo z ve z_ref (z ban do tai cho robot). Tra false neu bi tu choi.
bool Anchor(double z_ref);
double z() const { return z_; }
double sigma() const;
double pitch() const { return pitch_; } // pitch cua buoc cuoi
bool on_slope() const { return on_slope_; } // buoc cuoi KHONG bi kep
const HeightEstimatorStats& stats() const { return stats_; }
const HeightEstimatorConfig& config() const { return cfg_; }
private:
HeightEstimatorConfig cfg_;
double P() const;
double z_ = 0.0;
double P_base_ = 0.0; // phuong sai sau lan neo / reset cuoi
double climb_ = 0.0; // sum |dz| tu do
double dist_ = 0.0; // sum |ds| tu do
double pitch_ = 0.0;
bool on_slope_ = false;
HeightEstimatorStats stats_;
};
} // namespace vslam
#endif // VSLAM_HEIGHT_ESTIMATOR_H

View File

@@ -0,0 +1,60 @@
#include "vslam/height_estimator.h"
#include <algorithm>
#include <cmath>
#include <utility>
namespace vslam {
HeightEstimator::HeightEstimator(HeightEstimatorConfig cfg) : cfg_(std::move(cfg)) {}
void HeightEstimator::Reset(double z, double sigma) {
z_ = z;
P_base_ = sigma * sigma;
climb_ = 0.0;
dist_ = 0.0;
}
double HeightEstimator::P() const {
const double rel = cfg_.sigma_rel * climb_;
return P_base_ + rel * rel + cfg_.sigma_flat * cfg_.sigma_flat * dist_;
}
double HeightEstimator::sigma() const { return std::sqrt(P()); }
void HeightEstimator::OnWheelStep(double ds, double pitch) {
stats_.steps++;
pitch_ = pitch;
on_slope_ = std::fabs(pitch) >= cfg_.clamp_rad;
double dz = 0.0;
if (on_slope_) {
dz = -ds * std::sin(pitch);
} else {
stats_.clamped++;
}
z_ += dz;
stats_.climbed += std::fabs(dz);
climb_ += std::fabs(dz);
dist_ += std::fabs(ds);
}
bool HeightEstimator::Anchor(double z_ref) {
const double err = z_ref - z_;
stats_.last_anchor_err = err;
const double R = cfg_.sigma_anchor * cfg_.sigma_anchor;
const double P_now = P();
const double gate = std::max(cfg_.gate_min, cfg_.gate_sigma * std::sqrt(P_now + R));
if (std::fabs(err) > gate) {
stats_.anchors_rejected++;
return false;
}
const double K = P_now / (P_now + R);
z_ += K * err;
P_base_ = (1.0 - K) * P_now;
climb_ = 0.0;
dist_ = 0.0;
stats_.anchors++;
return true;
}
} // namespace vslam

View File

@@ -19,6 +19,8 @@ vslam_add_library(vslam_perception
gravity_align.h
cliff_detect.h
perception_pipeline.h
elevation_map.h
scan_leveler.h
FIND_DEPS
vslam_common
)

View File

@@ -0,0 +1,72 @@
#ifndef VSLAM_ELEVATION_MAP_H
#define VSLAM_ELEVATION_MAP_H
// Ban do do cao SAN cuc bo, frame odom: moi o 10 cm giu do cao THAP NHAT da
// thay (diem depth) hoac do cao noi banh xe DA cham (vet robot).
//
// ================== VI SAO ==================
// LiDAR mot mat phang cao 0.2165 m tren san. Lai tren san phang toi chan mot
// doc len, tia ngang cham mat doc o 0.2165 / tan(goc) truoc chan doc (15 do:
// 0.81 m, 30 do: 0.38 m) -- mot "buc tuong" tai MOT diem co dinh tren the gioi,
// tuc trong y het tuong that va bi ve vao ban do (G0, 03/10). Rieng scan thi
// khong phan biet duoc. Camera thay mat doc tu 1.1 m den ~4 m TRUOC khi robot
// toi do, nen tich lai do cao san o day roi hoi lai khi loc scan
// (ScanLeveler). Camera mu duoi 1.1 m, nen phai TICH LAI qua thoi gian, khong
// dung duoc mat na depth tung khung.
//
// Gia tri moi o la MIN: o co ca san lan vat can (chan tuong, chan ban) van ra
// do cao san mien la camera thay duoc chan. Nhieu depth keo min xuong vai cm
// -- an toan cho phep "cham san?" (nguong 8 cm).
//
// KHONG khoa -- nguoi goi giu mutex.
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct ElevationMapConfig {
double cell_m = 0.10;
// Bo o xa robot hon / cu hon nguong nay (Prune). z robot troi dan, nen o
// cu lau thi do cao cua no khong con cung goc voi z hien tai.
double radius_m = 8.0;
double max_age_sec = 60.0;
};
class ElevationMap {
public:
explicit ElevationMap(ElevationMapConfig cfg = {});
// Diem DA o frame odom (x, y, z tuyet doi).
void AddPoints(const std::vector<PointXYZ>& pts, UnixTime stamp);
// Banh xe dang cham san tai (x, y) o do cao z: moi o trong ban kinh r lay
// DUNG z (ghi de -- vet banh la do cao san chac chan nhat).
void AddFootprint(double x, double y, double z, double r, UnixTime stamp);
// Do cao san tai (x, y); false neu chua biet.
bool FloorAt(double x, double y, double* z) const;
void Prune(double cx, double cy, UnixTime now);
void Clear() { cells_.clear(); }
size_t size() const { return cells_.size(); }
const ElevationMapConfig& config() const { return cfg_; }
private:
struct Cell {
float z;
int64_t stamp_ns;
};
uint64_t Key(double x, double y) const;
ElevationMapConfig cfg_;
std::unordered_map<uint64_t, Cell> cells_;
};
} // namespace vslam
#endif // VSLAM_ELEVATION_MAP_H

View File

@@ -0,0 +1,70 @@
#ifndef VSLAM_SCAN_LEVELER_H
#define VSLAM_SCAN_LEVELER_H
// Bu nghieng scan LiDAR cho SLAM 2D tren doc.
//
// ================== VAN DE ==================
// RTAB-Map 2D coi moi diem scan nam tren MOT mat phang ngang. Tren doc thi sai
// theo hai kieu:
// 1. Than nghieng -> tia nghieng: tuong cach 2 m tren doc 15 do doc ra
// 2 / cos(15) = 2.07 m, va goc cua tia lech di (tia 45 do -> 46 do).
// 2. Tia CHAM SAN / MAT DOC: dung tren san phang truoc doc len, tia cham
// mat doc o 0.2165 / tan(goc) (tuong gia co dinh tren the gioi); dang
// xuong doc (chuc mui), tia cham san duoi chan doc.
//
// ================== CACH LAM ==================
// Moi tia: diem cham -> frame base_link (ngoai lai tinh) -> base_footprint DA
// CAN trong luc (TiltLift, CHUNG ham voi GravityAlign / CliffDetect) -> do cao
// h so voi mat dat duoi robot, va do cao tuyet doi H = z_robot + h.
// * Biet do cao san tai do (ElevationMap) va H - san < floor_margin -> tia
// cham san/doc -> BO (NaN).
// * Khong biet san va h < -below_ground -> diem THAP hon cho robot dung, tuc
// san duoi chan doc khi dang xuong -> BO.
// * Con lai: chieu xuong mat phang ngang, tinh lai khoang cach va goc tu goc
// LiDAR (vi tri TINH trong base_link -- RTAB-Map dat lai diem dung cho do),
// xep vao o goc gan nhat, giu tia gan nhat moi o.
// Tia bo thanh NaN ("khong do duoc"), KHONG phai inf ("trong toi range_max"):
// inf se xoa trang ca vung sau mat doc tren luoi 2D.
//
// ⚠️ GIOI HAN: tuong gia khi tien toi chan doc LEN chi bo duoc neu camera da
// thay mat doc (ElevationMap co o do). Re vao chan doc o goc hep / camera bi
// che thi tuong gia van con.
//
// Chi cap cho SLAM / dinh vi lai / canh lac. Lop AN TOAN van dung scan THO:
// heuristic o day khong bao gio duoc xoa mot vat can that khoi luong dung xe.
#include <cstdint>
#include "vslam/elevation_map.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct ScanLevelerConfig {
// Diem cao hon san da biet duoi nguong nay = cham san / mat doc.
double floor_margin = 0.08;
// Khong biet san: diem thap hon mat dat duoi robot qua nguong nay = san duoi
// chan doc.
double below_ground = 0.05;
};
struct ScanLevelStats {
uint64_t scans = 0;
uint64_t rays = 0; // tia huu han vao
uint64_t kept = 0;
uint64_t dropped_floor = 0; // cham san theo ElevationMap
uint64_t dropped_below = 0; // thap hon mat dat duoi robot
uint64_t rebinned = 0; // doi sang o goc khac sau khi chieu
};
// laser_to_base: base_link <- laser_link (tinh). roll/pitch: nghieng than
// (GravityAlign). odom: base_footprint trong odom; z_robot: do cao robot
// (HeightEstimator). em co the null.
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats);
} // namespace vslam
#endif // VSLAM_SCAN_LEVELER_H

View File

@@ -0,0 +1,66 @@
#include "vslam/elevation_map.h"
#include <cmath>
#include <utility>
namespace vslam {
ElevationMap::ElevationMap(ElevationMapConfig cfg) : cfg_(std::move(cfg)) {}
uint64_t ElevationMap::Key(double x, double y) const {
// Hai chi so 32 bit co dau gop vao 64 bit KHONG dau: dich trai so am la hanh
// vi khong xac dinh truoc C++20.
const int32_t ix = static_cast<int32_t>(std::floor(x / cfg_.cell_m));
const int32_t iy = static_cast<int32_t>(std::floor(y / cfg_.cell_m));
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) << 32) | static_cast<uint32_t>(iy);
}
void ElevationMap::AddPoints(const std::vector<PointXYZ>& pts, UnixTime stamp) {
const int64_t ns = stamp.toNSec();
for (const PointXYZ& p : pts) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
auto it = cells_.find(Key(p.x, p.y));
if (it == cells_.end()) {
cells_.emplace(Key(p.x, p.y), Cell{p.z, ns});
} else {
if (p.z < it->second.z) it->second.z = p.z;
it->second.stamp_ns = ns;
}
}
}
void ElevationMap::AddFootprint(double x, double y, double z, double r, UnixTime stamp) {
const int64_t ns = stamp.toNSec();
const int n = static_cast<int>(std::ceil(r / cfg_.cell_m));
for (int dx = -n; dx <= n; ++dx) {
for (int dy = -n; dy <= n; ++dy) {
const double px = x + dx * cfg_.cell_m, py = y + dy * cfg_.cell_m;
if (std::hypot(px - x, py - y) > r) continue;
cells_[Key(px, py)] = Cell{static_cast<float>(z), ns};
}
}
}
bool ElevationMap::FloorAt(double x, double y, double* z) const {
auto it = cells_.find(Key(x, y));
if (it == cells_.end()) return false;
*z = it->second.z;
return true;
}
void ElevationMap::Prune(double cx, double cy, UnixTime now) {
const int64_t now_ns = now.toNSec();
const int64_t max_age = static_cast<int64_t>(cfg_.max_age_sec * 1e9);
for (auto it = cells_.begin(); it != cells_.end();) {
const int32_t ix = static_cast<int32_t>(static_cast<uint32_t>(it->first >> 32));
const int32_t iy = static_cast<int32_t>(static_cast<uint32_t>(it->first & 0xffffffffu));
const double x = (ix + 0.5) * cfg_.cell_m, y = (iy + 0.5) * cfg_.cell_m;
if (std::hypot(x - cx, y - cy) > cfg_.radius_m || now_ns - it->second.stamp_ns > max_age) {
it = cells_.erase(it);
} else {
++it;
}
}
}
} // namespace vslam

View File

@@ -0,0 +1,87 @@
#include "vslam/scan_leveler.h"
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
namespace vslam {
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats) {
ScanLevelStats local;
ScanLevelStats& st = stats != nullptr ? *stats : local;
st.scans++;
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f) return;
const float nan = std::numeric_limits<float>::quiet_NaN();
out->ranges.assign(n, nan);
if (!out->intensities.empty()) out->intensities.assign(n, 0.0f);
// base_footprint (can trong luc) <- laser_link.
const Transform fp_from_laser =
TransformCompose(TiltLift(roll, pitch, wheel_radius), laser_to_base);
// Goc LiDAR TINH tren mat phang ngang (RTAB-Map dat diem bang ngoai lai
// tinh, nen tinh lai khoang cach/goc tu dung goc do).
const double lx0 = laser_to_base.translation.x, ly0 = laser_to_base.translation.y;
const double laser_yaw = YawFromQuaternion(laser_to_base.rotation);
const double c_th = std::cos(odom.theta), s_th = std::sin(odom.theta);
// Luot 1: tia KHONG huu han va sentinel cua sector mask giu nguyen o cu.
// Sentinel (> range_max) = than robot bi cat -- khong tia nao duoc de len.
std::vector<char> masked(n, 0);
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (std::isnan(r)) continue;
if (std::isinf(r)) {
out->ranges[i] = r;
} else if (r > in.range_max) {
out->ranges[i] = r;
masked[i] = 1;
}
}
// Luot 2: tia huu han -> chieu, loc, xep lai.
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
st.rays++;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
const Point p = TransformPoint(fp_from_laser, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double h = p.z;
const double wx = odom.x + c_th * p.x - s_th * p.y;
const double wy = odom.y + s_th * p.x + c_th * p.y;
double floor = 0.0;
if (em != nullptr && em->FloorAt(wx, wy, &floor)) {
if (z_robot + h - floor < cfg.floor_margin) {
st.dropped_floor++;
continue;
}
} else if (h < -cfg.below_ground) {
st.dropped_below++;
continue;
}
const double dx = p.x - lx0, dy = p.y - ly0;
const double rh = std::hypot(dx, dy);
const double ah = NormalizeAngle(std::atan2(dy, dx) - laser_yaw);
const long j = std::lround((ah - in.angle_min) / in.angle_increment);
if (j < 0 || j >= static_cast<long>(n) || masked[static_cast<size_t>(j)]) continue;
if (static_cast<size_t>(j) != i) st.rebinned++;
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rh < slot) {
slot = static_cast<float>(rh);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
st.kept++;
}
}
} // namespace vslam

View File

@@ -38,6 +38,7 @@ vslam_add_library(vslam_slam
sensor_data_builder.h
occupancy_export.h
voxel_export.h
height_map.h
global_localizer.h
vpr_encoder.h
visual_verifier.h

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_HEIGHT_MAP_H
#define VSLAM_HEIGHT_MAP_H
// z cua ban do khi pose SLAM la SE(2): do cao tung node va mat san quanh no.
//
// ================== NGUON ==================
// Moi node mang z / roll / pitch DO luc tao (HeightEstimator + GravityAlign),
// luu trong userData cua RTAB-Map. z do co troi (truot banh, sai pitch), va
// do thi SE(2) cua RTAB-Map khong biet gi ve no.
//
// ================== DO THI z 1-D ==================
// Sau moi lan toi uu cua RTAB-Map, giai lai z bang binh phuong toi thieu:
// * lien ket LANG GIENG (node lien tiep): z_j - z_i = z_do_j - z_do_i,
// sigma = min + rel * |dz| (sai he thong ti le voi do cao leo);
// * lien ket VONG / lan can (cung cho, hai lan qua): z_j - z_i = mat phang
// doc cua node i keo toi node j. Ca hai node PHANG (|pitch| < clamp) ->
// 0, chat (3 cm). Tren doc -> theo pitch, long hon (hai node cach 1 m tren
// doc 30 do lech 0.58 m -- dz = 0 o day la SAI);
// * node dau tien neo o z do cua no; moi node co mot prior rat long ve z do
// de do thi khong lien thong van giai duoc.
// Nho vay khi robot quay ve cho cu sau mot vong co doc, sai z don ra deu
// tren vong thay vi don het vao mot cho.
//
// ================== MAT SAN ==================
// FloorModel: do cao san tai (x, y) = MAT PHANG cua node GAN NHAT (z, pitch,
// roll cua no) keo toi do. Dung cho: cat voxel theo do cao TREN san, lop vat
// can tinh theo san cuc bo (doc khong con la tuong), va neo z robot luc dinh
// vi. Node gan nhat chu khong trung binh: canh dinh doc, trung binh hai mat
// phang (doc + chieu nghi) cho ra mot san khong co that.
//
// Khong phu thuoc RTAB-Map -- test duoc rieng.
#include <map>
#include <vector>
namespace vslam {
struct NodeHeight {
double z = 0.0; // do cao base_footprint (mat san duoi robot), m
double roll = 0.0; // nghieng than luc tao node (ROS: duong = trai len)
double pitch = 0.0; // duong = mui chuc xuong
};
struct ZGraphLink {
int from = 0;
int to = 0;
bool neighbor = false; // lien tiep (odometry) hay vong / lan can
// Vi tri node `to` trong frame node `from` (mat phang ngang), m.
double dx = 0.0;
double dy = 0.0;
};
struct ZGraphConfig {
double clamp_rad = 0.0261799; // 1.5 do: duoi nguong = phang
double sigma_neighbor = 0.01;
double sigma_rel = 0.05;
double sigma_loop_flat = 0.03;
double sigma_loop_slope = 0.10;
double sigma_first = 0.01;
double sigma_prior = 2.0; // prior long ve z do cua MOI node
};
// Tra z da toi uu cho moi node trong `meas`. Lien ket toi node khong co trong
// `meas` bi bo qua.
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg = {});
struct FloorNode {
double x = 0.0, y = 0.0, theta = 0.0; // pose (da toi uu) trong frame map
double z = 0.0, roll = 0.0, pitch = 0.0;
};
class FloorModel {
public:
// radius: chi dung node trong ban kinh nay (camera thay toi ~4 m).
void Build(const std::vector<FloorNode>& nodes, double radius = 4.0, double cell = 0.25);
// Do cao san tai (x, y) theo mat phang node gan nhat; false neu khong node
// nao trong ban kinh. `dist`: khoang cach toi node do.
bool FloorAt(double x, double y, double* z, double* dist = nullptr) const;
// Node gan nhat (trong ban kinh) cua (x, y); false neu khong co.
bool NearestNode(double x, double y, FloorNode* node, double* dist = nullptr) const;
bool empty() const { return nodes_.empty(); }
size_t size() const { return nodes_.size(); }
private:
std::vector<FloorNode> nodes_;
double radius_ = 4.0, cell_ = 0.25, x0_ = 0.0, y0_ = 0.0;
int w_ = 0, h_ = 0;
std::vector<int> nearest_; // moi o: chi so node gan nhat, -1 = khong co
};
// Do cao mat phang cua node n tai (x, y).
double PlaneZ(const FloorNode& n, double x, double y);
} // namespace vslam
#endif // VSLAM_HEIGHT_MAP_H

View File

@@ -24,6 +24,7 @@
#include <opencv2/core.hpp>
#include "vslam/height_map.h"
#include "vslam/rtabmap_params.h"
#include "vslam/slam_types.h"
#include "vslam/voxel_export.h"
@@ -101,6 +102,20 @@ class RtabmapSlam {
std::vector<int> MapNodeIds() const;
StatusResponse GetNodeView(int id, bool with_depth, NodeView* out);
// ---- z ban do khi di tren doc (height_map.h) ----
// Giai lai do thi z tu z DO cua node (userData) va lien ket cua do thi,
// dung lai mat san. Node chua co z do thi nap tu DB (ban do quet truoc).
// CHI luong slam goi. `nodes_out`: so node co z.
StatusResponse UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out = nullptr);
// Do cao san tai (x, y) frame map theo mat phang node gan nhat, chi khi
// node do trong `radius`. false neu khong co. CHI luong slam goi.
bool HeightAt(double x, double y, double radius, double* z) const;
const FloorModel& floor_model() const;
// Bat dung z node + mat san cho ban do voxel (sau UpdateHeights).
void SetUseHeights(bool on);
// O 2D noi camera thay mat san trong lan ExportVoxels cuoi (che do doc).
const std::vector<uint64_t>& floor_cells() const;
StatusResponse Close(bool save_database);
const SlamStats& stats() const;

View File

@@ -51,6 +51,13 @@ struct SlamInput {
// Than robot chuc len/xuong khi tang/giam toc. Coi camera nam ngang thi san
// o 3 m bi day len ~0.2 m va thanh vat can gia trong ban do 3D.
const Transform* camera_to_base = nullptr;
// Di tren doc (slam.yaml `slope:`): do cao base_footprint va nghieng than
// luc nay. Co thi luu vao node (userData cua RTAB-Map) -- xem height_map.h.
bool has_height = false;
double z = 0.0;
double roll = 0.0;
double pitch = 0.0;
};
struct SlamOutput {

View File

@@ -22,9 +22,11 @@
#include <cstddef>
#include <cstdint>
#include <map>
#include <unordered_map>
#include <vector>
#include "vslam/height_map.h"
#include "vslam/vslam_common.h"
namespace rtabmap {
@@ -65,13 +67,32 @@ struct VoxelExportOptions {
// nhieu depth va nguoi di ngang chi o 1-2 khung; tuong, ban ghe dung yen
// thi nhieu node thay. 1 = giu moi voxel (hanh vi cu).
size_t min_node_hits = 1;
// Di tren doc: z cua tung node (do thi z) + mat san. Co ca hai thi diem dat
// o z THAT (z node + z cuc bo), va dai z_min..z_max tinh tu SAN tai cho diem
// do (mat doc khong lot vao ban do nhu vat can). Null = duong cu (moi node
// o z = 0, dai tinh tu san duoi node).
const std::map<int, double>* node_z = nullptr;
const FloorModel* floor = nullptr;
// Che do doc: thu cac o 2D (kich thuoc emit_size_m, khoa PackFloorCell) noi
// camera THAY MAT SAN (|cao - san| <= floor_band). Dung cho
// ClearLidarOnSeenRamps. Null = khong thu.
std::vector<uint64_t>* floor_cells = nullptr;
double floor_band = 0.05;
};
// Khoa o 2D (ix, iy) cua floor_cells.
inline uint64_t PackFloorCell(int32_t ix, int32_t iy) {
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) << 32) | static_cast<uint32_t>(iy);
}
// Diem cua tung node, o frame CUA NODE, da gom voxel. Tinh MOT lan roi giu:
// depth cua node khong doi, chi pose cua no doi sau moi lan toi uu.
// CHI luong slam cham vao.
struct VoxelNodeCache {
std::unordered_map<int, std::vector<float>> nodes; // id -> x,y,z,x,y,z...
// Diem node da cat theo dai z RONG (che do doc). Doi che do thi xoa cache.
bool wide = false;
};
// Gom diem -> tap voxel. KHONG chua kieu nao cua RTAB-Map, nen test duoc ma
@@ -156,8 +177,26 @@ void NodeCloudFromSensorData(const rtabmap::SensorData& data,
// mat san). La LOP VAT CAN tu camera cho nhung thu LiDAR (0.22 m) khong cat
// ngang: mat ghe, khung giuong, ke thap. Chi THEM o bi chiem, khong xoa.
// Tra ve so o moi danh dau (truoc do trong/chua biet).
//
// `floor` (di tren doc): do cao tinh tu SAN TAI CHO voxel (FloorModel) thay vi
// tu z = 0 -- mat doc va san tang tren khong con bi danh la tuong. Null =
// duong cu.
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid);
OccupancyGrid* grid, const FloorModel* floor = nullptr);
// Di tren doc: TREN DOC, lop LiDAR nhuong cho camera.
//
// LiDAR ngang thay mat doc len tu xa (> 4 m, ngoai tam depth) nhu mot buc
// tuong -- tuong gia vao node TRUOC khi camera kip thay mat doc, va cac scan
// sau BO tia cham doc (NaN) nen khong tia nao xoa duoc no. O day: o LiDAR bi
// chiem ma (1) node ban do gan nhat (trong `max_node_dist`) dang TREN DOC
// (|pitch| >= clamp) va (2) camera da THAY MAT SAN o do (floor_cells) -> tra
// ve trong. Vat can THAT tren doc van duoc MarkVoxelObstacles danh lai (goi
// SAU ham nay). Camera chua thay thi giu nguyen -- khong co bang chung.
// Tra ve so o da xoa.
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist);
// Hieu hai tap DA SAP XEP: `added` co trong `now` ma khong co trong `prev`,
// `removed` thi nguoc lai. O(n + m), mot luot.

View File

@@ -0,0 +1,150 @@
#include "vslam/height_map.h"
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <algorithm>
#include <cmath>
#include <limits>
namespace vslam {
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg) {
std::map<int, double> out;
if (meas.empty()) return out;
std::map<int, int> index;
for (const auto& kv : meas) {
const int k = static_cast<int>(index.size());
index[kv.first] = k;
}
const int n = static_cast<int>(index.size());
// Phuong trinh chuan H z = g, H = sum w a a^T.
std::vector<Eigen::Triplet<double>> trip;
Eigen::VectorXd g = Eigen::VectorXd::Zero(n);
auto add_rel = [&](int i, int j, double dz, double sigma) {
// z_j - z_i = dz
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
trip.emplace_back(j, j, w);
trip.emplace_back(i, j, -w);
trip.emplace_back(j, i, -w);
g(i) -= w * dz;
g(j) += w * dz;
};
auto add_abs = [&](int i, double z, double sigma) {
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
g(i) += w * z;
};
for (const auto& kv : meas) add_abs(index[kv.first], kv.second.z, cfg.sigma_prior);
add_abs(index[meas.begin()->first], meas.begin()->second.z, cfg.sigma_first);
for (const ZGraphLink& l : links) {
auto a = meas.find(l.from), b = meas.find(l.to);
if (a == meas.end() || b == meas.end() || l.from == l.to) continue;
const int i = index[l.from], j = index[l.to];
if (l.neighbor) {
const double dz = b->second.z - a->second.z;
add_rel(i, j, dz, cfg.sigma_neighbor + cfg.sigma_rel * std::fabs(dz));
continue;
}
const bool flat_a = std::fabs(a->second.pitch) < cfg.clamp_rad;
const bool flat_b = std::fabs(b->second.pitch) < cfg.clamp_rad;
if (flat_a && flat_b) {
add_rel(i, j, 0.0, cfg.sigma_loop_flat);
} else {
// Mat phang doc cua node `from`, keo toi `to`.
FloorNode fa;
fa.roll = a->second.roll;
fa.pitch = a->second.pitch;
const double dz = PlaneZ(fa, l.dx, l.dy);
add_rel(i, j, dz, cfg.sigma_loop_slope + cfg.sigma_rel * std::fabs(dz));
}
}
Eigen::SparseMatrix<double> H(n, n);
H.setFromTriplets(trip.begin(), trip.end());
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(H);
if (solver.info() != Eigen::Success) {
for (const auto& kv : meas) out[kv.first] = kv.second.z;
return out;
}
const Eigen::VectorXd z = solver.solve(g);
for (const auto& kv : index) out[kv.first] = z(kv.second);
return out;
}
double PlaneZ(const FloorNode& n, double x, double y) {
const double dx = x - n.x, dy = y - n.y;
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double fwd = c * dx + s * dy;
const double left = -s * dx + c * dy;
// Ry(pitch): +x chuc xuong khi pitch duong; Rx(roll): +y len khi roll duong.
return n.z - fwd * std::tan(n.pitch) + left * std::tan(n.roll);
}
void FloorModel::Build(const std::vector<FloorNode>& nodes, double radius, double cell) {
nodes_ = nodes;
radius_ = radius;
cell_ = cell;
nearest_.clear();
w_ = h_ = 0;
if (nodes_.empty()) return;
double xmin = std::numeric_limits<double>::max(), ymin = xmin;
double xmax = std::numeric_limits<double>::lowest(), ymax = xmax;
for (const FloorNode& f : nodes_) {
xmin = std::min(xmin, f.x);
xmax = std::max(xmax, f.x);
ymin = std::min(ymin, f.y);
ymax = std::max(ymax, f.y);
}
x0_ = xmin - radius - cell;
y0_ = ymin - radius - cell;
w_ = static_cast<int>(std::ceil((xmax - xmin + 2 * radius + 2 * cell) / cell));
h_ = static_cast<int>(std::ceil((ymax - ymin + 2 * radius + 2 * cell) / cell));
nearest_.assign(static_cast<size_t>(w_) * h_, -1);
std::vector<float> best(nearest_.size(), std::numeric_limits<float>::max());
const int rc = static_cast<int>(std::ceil(radius / cell));
const double r2 = radius * radius;
for (size_t k = 0; k < nodes_.size(); ++k) {
const FloorNode& f = nodes_[k];
const int cx = static_cast<int>((f.x - x0_) / cell), cy = static_cast<int>((f.y - y0_) / cell);
for (int iy = std::max(0, cy - rc); iy <= std::min(h_ - 1, cy + rc); ++iy) {
for (int ix = std::max(0, cx - rc); ix <= std::min(w_ - 1, cx + rc); ++ix) {
const double px = x0_ + (ix + 0.5) * cell, py = y0_ + (iy + 0.5) * cell;
const double d2 = (px - f.x) * (px - f.x) + (py - f.y) * (py - f.y);
if (d2 > r2) continue;
const size_t i = static_cast<size_t>(iy) * w_ + ix;
if (d2 < best[i]) {
best[i] = static_cast<float>(d2);
nearest_[i] = static_cast<int>(k);
}
}
}
}
}
bool FloorModel::NearestNode(double x, double y, FloorNode* node, double* dist) const {
if (nodes_.empty()) return false;
const int ix = static_cast<int>(std::floor((x - x0_) / cell_));
const int iy = static_cast<int>(std::floor((y - y0_) / cell_));
if (ix < 0 || iy < 0 || ix >= w_ || iy >= h_) return false;
const int k = nearest_[static_cast<size_t>(iy) * w_ + ix];
if (k < 0) return false;
*node = nodes_[static_cast<size_t>(k)];
if (dist != nullptr) *dist = std::hypot(x - node->x, y - node->y);
return true;
}
bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const {
FloorNode f;
if (!NearestNode(x, y, &f, dist)) return false;
*z = PlaneZ(f, x, y);
return true;
}
} // namespace vslam

View File

@@ -11,6 +11,7 @@
#include <algorithm>
#include <chrono>
#include <mutex>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
@@ -45,6 +46,14 @@ class RtabmapSlamImpl {
// Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham.
VoxelNodeCache voxel_cache;
// ---- z ban do (di tren doc). CHI luong slam cham. ----
std::map<int, NodeHeight> node_meas; // z DO luc tao node
std::set<int> node_no_height; // node DB khong co userData z
std::map<int, double> node_z; // z sau do thi z
FloorModel floor;
bool use_heights = false;
std::vector<uint64_t> floor_cells;
void RecordMs(double ms) {
stats.last_ms = ms;
stats.max_ms = std::max(stats.max_ms, ms);
@@ -282,6 +291,15 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
in.camera_to_base != nullptr ? *in.camera_to_base
: impl_->camera_to_base,
impl_->next_id++);
if (in.has_height) {
// z / roll / pitch DO cua node -> DB (userData). Ban do quet xong mo lai
// o localization van co z.
cv::Mat ud(1, 3, CV_64FC1);
ud.at<double>(0) = in.z;
ud.at<double>(1) = in.roll;
ud.at<double>(2) = in.pitch;
data.setUserData(ud);
}
// Phuong sai odom: nguoi goi dat thi dung, khong thi lay tu slam.yaml.
const double lin_var = in.odom_linear_var > 0.0
@@ -319,6 +337,12 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
}
impl_->stats.frames_processed++;
if (in.has_height && impl_->cfg.mode == SlamMode::kMapping) {
// RTAB-Map tu sinh id node (Mem/GenerateIds) -- id cua SensorData chi la
// goi y. Node vua them la node cuoi cua bo nho.
const int id = impl_->rtabmap.getLastLocationId();
if (id > 0) impl_->node_meas[id] = NodeHeight{in.z, in.roll, in.pitch};
}
out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
auto stat = [&](const std::string& k, double dflt) {
@@ -377,9 +401,109 @@ StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
if (impl_->use_heights && !impl_->node_z.empty()) {
VoxelExportOptions o = opt;
o.node_z = &impl_->node_z;
o.floor = &impl_->floor;
impl_->floor_cells.clear();
o.floor_cells = &impl_->floor_cells;
return ExportVoxelGrid(impl_->rtabmap, o, &impl_->voxel_cache, out);
}
return ExportVoxelGrid(impl_->rtabmap, opt, &impl_->voxel_cache, out);
}
void RtabmapSlam::SetUseHeights(bool on) { impl_->use_heights = on; }
const std::vector<uint64_t>& RtabmapSlam::floor_cells() const { return impl_->floor_cells; }
const FloorModel& RtabmapSlam::floor_model() const { return impl_->floor; }
StatusResponse RtabmapSlam::UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
std::map<int, rtabmap::Transform> poses;
std::multimap<int, rtabmap::Link> links;
impl_->rtabmap.getGraph(poses, links, /*optimized=*/true, /*global=*/false);
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "do thi rong");
}
// Node chua co z do: nap userData tu DB (ban do quet o phien truoc). Node
// DB khong co (quet truoc khi co che do doc) thi nho lai, khong hoi mai.
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
for (const auto& kv : poses) {
const int id = kv.first;
if (id <= 0 || impl_->node_meas.count(id) || impl_->node_no_height.count(id)) continue;
if (mem == nullptr) break;
const rtabmap::SensorData d = mem->getNodeData(id, false, false, true, false);
cv::Mat ud;
d.uncompressDataConst(nullptr, nullptr, nullptr, &ud);
if (ud.type() == CV_64FC1 && ud.total() == 3) {
impl_->node_meas[id] = NodeHeight{ud.at<double>(0), ud.at<double>(1), ud.at<double>(2)};
} else {
impl_->node_no_height.insert(id);
}
}
std::map<int, NodeHeight> meas;
for (const auto& kv : poses) {
auto it = impl_->node_meas.find(kv.first);
if (it != impl_->node_meas.end()) meas[kv.first] = it->second;
}
std::vector<ZGraphLink> zl;
for (const auto& kv : links) {
const rtabmap::Link& l = kv.second;
ZGraphLink z;
z.from = l.from();
z.to = l.to();
switch (l.type()) {
case rtabmap::Link::kNeighbor:
case rtabmap::Link::kNeighborMerged:
z.neighbor = true;
break;
case rtabmap::Link::kGlobalClosure:
case rtabmap::Link::kLocalSpaceClosure:
case rtabmap::Link::kLocalTimeClosure:
case rtabmap::Link::kUserClosure:
z.neighbor = false;
break;
default:
continue;
}
if (l.transform().isNull()) continue;
z.dx = l.transform().x();
z.dy = l.transform().y();
zl.push_back(z);
}
impl_->node_z = SolveZGraph(meas, zl, cfg);
std::vector<FloorNode> fn;
fn.reserve(impl_->node_z.size());
for (const auto& kv : impl_->node_z) {
const auto p = poses.find(kv.first);
if (p == poses.end() || p->second.isNull()) continue;
const NodeHeight& m = meas[kv.first];
FloorNode f;
f.x = p->second.x();
f.y = p->second.y();
f.theta = p->second.theta();
f.z = kv.second;
f.roll = m.roll;
f.pitch = m.pitch;
fn.push_back(f);
}
impl_->floor.Build(fn);
if (nodes_out != nullptr) *nodes_out = impl_->node_z.size();
return StatusResponse::Ok();
}
bool RtabmapSlam::HeightAt(double x, double y, double radius, double* z) const {
double d = 0.0;
if (!impl_->floor.FloorAt(x, y, z, &d)) return false;
return d <= radius;
}
namespace {
cv::Matx44d ToMatx44(const rtabmap::Transform& t) {
return cv::Matx44d(t.r11(), t.r12(), t.r13(), t.x(), t.r21(), t.r22(), t.r23(), t.y(),

View File

@@ -230,13 +230,17 @@ void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
}
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid) {
OccupancyGrid* grid, const FloorModel* floor) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f) return 0;
const double r = vg.resolution;
const double inv = 1.0 / grid->resolution;
size_t marked = 0;
for (const VoxelIndex& k : vg.cells) {
const double z = vg.origin_z + (k.z + 0.5) * r;
double z = vg.origin_z + (k.z + 0.5) * r;
if (floor != nullptr) {
double f = 0.0;
if (floor->FloorAt(vg.origin_x + (k.x + 0.5) * r, vg.origin_y + (k.y + 0.5) * r, &f)) z -= f;
}
if (z < z_min || z > z_max) continue;
// Luoi 2D khong xoay (occupancy_export dat orientation = dong nhat), va
// hang 0 la ymin -- cung quy uoc voi RTAB-Map/map_server.
@@ -255,6 +259,38 @@ size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
return marked;
}
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f || floor_cells.empty()) {
return 0;
}
std::vector<uint64_t> seen(floor_cells);
std::sort(seen.begin(), seen.end());
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
const double res = grid->resolution;
const double inv = 1.0 / cell_size;
size_t cleared = 0;
for (uint32_t r = 0; r < grid->height; ++r) {
for (uint32_t c = 0; c < grid->width; ++c) {
int8_t& v = grid->data[static_cast<size_t>(r) * grid->width + c];
if (v < 50) continue;
const double x = grid->origin.position.x + (c + 0.5) * res;
const double y = grid->origin.position.y + (r + 0.5) * res;
FloorNode n;
double d = 0.0;
if (!floor.NearestNode(x, y, &n, &d) || d > max_node_dist) continue;
if (std::fabs(n.pitch) < clamp_rad) continue;
const uint64_t k = PackFloorCell(static_cast<int32_t>(std::floor(x * inv)),
static_cast<int32_t>(std::floor(y * inv)));
if (!std::binary_search(seen.begin(), seen.end(), k)) continue;
v = 0;
++cleared;
}
}
return cleared;
}
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out) {
@@ -298,11 +334,30 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
it = poses.count(it->first) ? std::next(it) : cache->nodes.erase(it);
}
// Di tren doc: diem dat o z THAT, va dai z cat theo SAN tai cho diem -- ca
// hai viec lam O DAY, nen bo gom nhan moi z. Cache diem cua node giu dai
// rong hon (mat doc xuong phia truoc o z am so voi node).
const bool use_floor = opt.node_z != nullptr && opt.floor != nullptr;
VoxelExportOptions acc_opt = opt;
if (use_floor) {
acc_opt.z_min = -1e9;
acc_opt.z_max = 1e9;
}
VoxelExportOptions node_opt = opt;
if (use_floor) {
node_opt.z_min = opt.z_min - 3.0;
node_opt.z_max = opt.z_max + 3.0;
}
if (cache->wide != use_floor) {
cache->nodes.clear();
cache->wide = use_floor;
}
// min_node_hits > 1: dem so node thay moi voxel (loc diem bay, nguoi di
// ngang). = 1: duong cu, re hon.
const bool count_hits = opt.min_node_hits > 1;
VoxelAccumulator acc(opt);
VoxelHitCounter hits(opt);
VoxelAccumulator acc(acc_opt);
VoxelHitCounter hits(acc_opt);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
for (const auto& kv : poses) {
@@ -320,7 +375,7 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
// moi node va ban do 3D im lang rong khong.
data.uncompressData();
std::vector<float> pts;
NodeCloudFromSensorData(data, opt, &pts);
NodeCloudFromSensorData(data, node_opt, &pts);
it = cache->nodes.emplace(kv.first, std::move(pts)).first;
}
const std::vector<float>& pts = it->second;
@@ -336,12 +391,31 @@ StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const float r10 = T.r21(), r11 = T.r22(), r12 = T.r23(), ty = T.y();
const float r20 = T.r31(), r21 = T.r32(), r22 = T.r33(), tz = T.z();
double z_off = 0.0;
if (use_floor) {
const auto zi = opt.node_z->find(kv.first);
if (zi != opt.node_z->end()) z_off = zi->second;
}
if (count_hits) hits.BeginNode();
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
const float px = pts[i], py = pts[i + 1], pz = pts[i + 2];
const double wx = r00 * px + r01 * py + r02 * pz + tx;
const double wy = r10 * px + r11 * py + r12 * pz + ty;
const double wz = r20 * px + r21 * py + r22 * pz + tz;
double wz = r20 * px + r21 * py + r22 * pz + tz;
if (use_floor) {
wz += z_off;
double f = z_off;
opt.floor->FloorAt(wx, wy, &f);
const double h = wz - f;
if (opt.floor_cells != nullptr && std::fabs(h) <= opt.floor_band) {
const double inv = 1.0 / opt.emit_size_m;
opt.floor_cells->push_back(
PackFloorCell(static_cast<int32_t>(std::floor(wx * inv)),
static_cast<int32_t>(std::floor(wy * inv))));
}
if (h < opt.z_min || h > opt.z_max) continue;
}
if (count_hits) hits.AddPoint(wx, wy, wz);
else acc.AddPoint(wx, wy, wz);
}

View File

@@ -138,6 +138,13 @@ struct WebSnapshot {
double pitch = 0.0;
bool accel_ok = true;
// Di tren doc (slam.yaml `slope:`): z UOC LUONG cua robot. Chi xuat khi bat
// -- 0 khi tat la noi doi, client khong phan biet duoc "o san" voi "khong biet".
bool have_height = false;
double height_z = 0.0;
double height_sigma = 0.0;
bool on_slope = false;
// ============ GROUND TRUTH ============
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong
// repo cu, noi ghi ro "khong estimator nao duoc subscribe".

View File

@@ -115,6 +115,15 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
Num("x", s.pose_map.x, 3, out); Comma(out);
Num("y", s.pose_map.y, 3, out); Comma(out);
Num("yaw", s.pose_map.theta, 4, out);
if (s.have_height) {
// z + nghieng: khung 3D dat robot len doc. Chi khi BAT che do doc.
Comma(out);
Num("z", s.height_z, 3, out); Comma(out);
Num("roll", s.roll, 4, out); Comma(out);
Num("pitch", s.pitch, 4, out); Comma(out);
Num("z_sigma", s.height_sigma, 3, out); Comma(out);
Bool("on_slope", s.on_slope, out);
}
out->push_back('}'); Comma(out);
// Bu do tre cua scan: quy tia tu pose HIEN TAI ve pose LUC QUET. Cloud

View File

@@ -396,6 +396,11 @@ function onState(s) {
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--');
// Do cao san THAT (sim co doc). Pose uoc luong hien la 2D: chua co z.
txt('gtZ', s.gt && s.gt.z !== undefined ? fmt(s.gt.z, 3) + ' m' : '--');
// z uoc luong: chi co khi slam.yaml slope.enabled. +-sigma, (doc) khi |pitch|
// vuot nguong kep.
txt('estZ', s.pose && s.pose.z !== undefined
? fmt(s.pose.z, 3) + ' m \u00b1' + fmt(s.pose.z_sigma, 2) + (s.pose.on_slope ? ' (doc)' : '')
: '--');
state.slamMode = s.slam.mode;
txt('mode', s.slam.mode);

View File

@@ -74,6 +74,7 @@
cho biet uoc luong dang tot hay te. -->
<tr><td>sai so</td><td id="gtErr">--</td></tr>
<!-- Do cao san that (mo phong co doc). Uoc luong chua co z. -->
<tr><td>z uoc luong</td><td id="estZ">--</td></tr>
<tr><td>z that</td><td id="gtZ">--</td></tr>
</table>
</section>

View File

@@ -52,6 +52,7 @@ endif()
if(VSLAM_BUILD_ODOMETRY)
vslam_add_test(test_wheel_odometry LIBS vslam_odometry vslam_common)
vslam_add_test(test_ekf_se2 LIBS vslam_odometry vslam_common)
vslam_add_test(test_height_estimator LIBS vslam_odometry vslam_common)
endif()
if(VSLAM_BUILD_SAFETY)
@@ -73,6 +74,7 @@ endif()
if(VSLAM_BUILD_PERCEPTION)
vslam_add_test(test_perception LIBS vslam_perception vslam_common)
vslam_add_test(test_scan_leveler LIBS vslam_perception vslam_common)
if(VSLAM_BUILD_SIM)
# Test TICH HOP sim -> perception. Khoa quy uoc Z-depth cua anh mo phong
# va bai "san phang thi khong duoc bao vuc" -- thu ma ban ROS chi kiem
@@ -107,6 +109,7 @@ endif()
if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common)
vslam_add_test(test_voxel_export LIBS vslam_slam vslam_common)
vslam_add_test(test_height_map LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif()

View File

@@ -0,0 +1,89 @@
// HeightEstimator: z tren doc tu ds*sin(pitch), kep mat bang, neo ban do.
#include <gtest/gtest.h>
#include <cmath>
#include "vslam/height_estimator.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
// Lai `dist` m doc mat doc voi pitch co dinh, buoc 1 cm.
void Drive(HeightEstimator* h, double dist, double pitch) {
const double step = dist >= 0 ? 0.01 : -0.01;
const int n = static_cast<int>(std::round(std::fabs(dist) / 0.01));
for (int i = 0; i < n; ++i) h->OnWheelStep(step, pitch);
}
} // namespace
TEST(HeightEstimator, LenDocDungDoCao) {
// Doc 15 do, cao 1.5 m: duong doc dai 1.5 / sin(15) = 5.796 m. Len doc thi
// mui NGOC len: pitch AM (quy uoc ROS, duong = chuc xuong).
HeightEstimator h;
Drive(&h, 3.0, 0.0);
Drive(&h, 1.5 / std::sin(15 * kDeg), -15 * kDeg);
Drive(&h, 3.0, 0.0);
EXPECT_NEAR(h.z(), 1.5, 0.002);
}
TEST(HeightEstimator, LuiXuongDocCungDung) {
// Lui xuong doc: ds am, mui van ngoc (pitch am) -> z giam.
HeightEstimator h;
h.Reset(1.5, 0.0);
Drive(&h, -1.5 / std::sin(10 * kDeg), -10 * kDeg);
EXPECT_NEAR(h.z(), 0.0, 0.002);
}
TEST(HeightEstimator, KepMatBangTrietTieuBiasPitch) {
// Bias pitch 0.5 do tren san phang 100 m: khong kep la 87 cm, kep la 0.
HeightEstimator h;
Drive(&h, 100.0, 0.5 * kDeg);
EXPECT_DOUBLE_EQ(h.z(), 0.0);
EXPECT_EQ(h.stats().clamped, h.stats().steps);
EXPECT_FALSE(h.on_slope());
}
TEST(HeightEstimator, DocNhoHonNguongBiCoiLaPhang) {
// Gioi han NOI RO: doc 1 do < nguong 1.5 do -> bi bo qua.
HeightEstimator h;
Drive(&h, 30.0, -1.0 * kDeg);
EXPECT_DOUBLE_EQ(h.z(), 0.0);
}
TEST(HeightEstimator, NeoKeoVeZBanDo) {
// Sau mot doc, z lech 10 cm (vd truot banh): neo keo ve gan ban do.
HeightEstimator h;
Drive(&h, 5.0 * 1.1, -15 * kDeg); // truot 10%: dem nhieu hon that
const double z_true = 5.0 * std::sin(15 * kDeg);
ASSERT_GT(h.z() - z_true, 0.1);
EXPECT_TRUE(h.Anchor(z_true));
EXPECT_LT(std::fabs(h.z() - z_true), 0.03);
// Neo lan nua thi sat hon, P giam.
const double s1 = h.sigma();
EXPECT_TRUE(h.Anchor(z_true));
EXPECT_LT(h.sigma(), s1);
}
TEST(HeightEstimator, NeoQuaXaBiTuChoi) {
// z ban do lech 1 m so voi uoc luong vua di 3 m phang: nhieu kha nang la
// node sai tang / sai cho -- khong duoc keo.
HeightEstimator h;
Drive(&h, 3.0, 0.0);
EXPECT_FALSE(h.Anchor(1.0));
EXPECT_DOUBLE_EQ(h.z(), 0.0);
EXPECT_EQ(h.stats().anchors_rejected, 1u);
}
TEST(HeightEstimator, TrenPhangNeoKeoNhe) {
// Di 50 m phang (P nho): neo lech 5 cm chi keo mot phan -- mot node ban do
// khong duoc dat lai z o noi robot da biet chac.
HeightEstimator h;
h.Reset(0.0, 0.0);
Drive(&h, 1.0, 0.0);
h.Anchor(0.05);
EXPECT_GT(h.z(), 0.0);
EXPECT_LT(h.z(), 0.03);
}

99
test/test_height_map.cc Normal file
View File

@@ -0,0 +1,99 @@
// Do thi z 1-D va mat san theo node (height_map.h).
#include <gtest/gtest.h>
#include <cmath>
#include <map>
#include <vector>
#include "vslam/height_map.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
}
TEST(ZGraph, VongCoDocDonSaiDeuVaKhepVe0) {
// Vong: 10 node phang z=0, 6 node len doc 15 do (+0.25 moi node), 10 node
// phang tren z=1.5, 6 node xuong, 10 node phang ve gan cho xuat phat. z DO
// troi them 1 cm moi node tren doc (truot banh): ve den noi dz do = +0.12.
std::map<int, NodeHeight> meas;
int id = 1;
double z = 0.0;
auto push = [&](int n, double step, double pitch) {
for (int k = 0; k < n; ++k) {
z += step;
meas[id++] = NodeHeight{z, 0.0, pitch};
}
};
push(10, 0.0, 0.0);
push(6, 0.25 + 0.01, -15 * kDeg);
push(10, 0.0, 0.0);
push(6, -0.25 + 0.01, 15 * kDeg);
push(10, 0.0, 0.0);
const int last = id - 1;
ASSERT_NEAR(meas[last].z, 0.12, 1e-9);
std::vector<ZGraphLink> links;
for (int i = 1; i < last; ++i) links.push_back(ZGraphLink{i, i + 1, true, 1.0, 0.0});
// Ve dung cho cu: vong dong node cuoi -> node dau, ca hai phang.
links.push_back(ZGraphLink{last, 1, false, 0.05, 0.0});
const std::map<int, double> zo = SolveZGraph(meas, links);
EXPECT_NEAR(zo.at(last), zo.at(1), 0.02);
EXPECT_NEAR(zo.at(1), 0.0, 0.01);
// San tren: that 1.5, do 1.56. Sai don ra -> gan 1.5 hon so do.
EXPECT_LT(std::fabs(zo.at(20) - 1.5), std::fabs(meas.at(20).z - 1.5));
}
TEST(ZGraph, VongTrenDocTheoMatPhangDoc) {
// Hai lan qua CUNG doc 15 do: node B nam 1 m phia truoc node A (doc len). dz
// dung = 1 * tan(15) = 0.268, KHONG phai 0. So do cua B lech 0.2 m.
std::map<int, NodeHeight> meas;
meas[1] = NodeHeight{0.5, 0.0, -15 * kDeg};
meas[2] = NodeHeight{0.5 + 0.268 + 0.2, 0.0, -15 * kDeg};
std::vector<ZGraphLink> links{ZGraphLink{1, 2, false, 1.0, 0.0}};
ZGraphConfig cfg;
cfg.sigma_first = 0.001;
const std::map<int, double> zo = SolveZGraph(meas, links, cfg);
EXPECT_NEAR(zo.at(2) - zo.at(1), std::tan(15 * kDeg), 0.02);
}
TEST(ZGraph, NodeKhongLienKetGiuZDo) {
std::map<int, NodeHeight> meas;
meas[1] = NodeHeight{0.0, 0.0, 0.0};
meas[7] = NodeHeight{1.5, 0.0, 0.0};
const std::map<int, double> zo = SolveZGraph(meas, {});
EXPECT_NEAR(zo.at(7), 1.5, 1e-6);
}
TEST(FloorModel, MatPhangDocVaNodeGanNhat) {
// Node phang o x = -2 (z 0), node tren doc 15 do o x = 0 (z 0.5, huong +x,
// mui ngoc = pitch am).
std::vector<FloorNode> nodes(2);
nodes[0].x = -2.0;
nodes[1].z = 0.5;
nodes[1].pitch = -15 * kDeg;
FloorModel fm;
fm.Build(nodes, 4.0, 0.25);
double z = 0;
ASSERT_TRUE(fm.FloorAt(1.0, 0.0, &z));
EXPECT_NEAR(z, 0.5 + std::tan(15 * kDeg), 1e-6);
// Gan node phang hon -> mat phang phang.
ASSERT_TRUE(fm.FloorAt(-1.7, 0.1, &z));
EXPECT_NEAR(z, 0.0, 1e-9);
// Ngoai ban kinh moi node.
EXPECT_FALSE(fm.FloorAt(10.0, 0.0, &z));
}
TEST(FloorModel, RollNghiengSangTrai) {
// roll duong = ben TRAI (+y) cao len.
std::vector<FloorNode> nodes(1);
nodes[0].theta = M_PI / 2; // huong +y cua map; ben trai = -x
nodes[0].roll = 5 * kDeg;
FloorModel fm;
fm.Build(nodes);
double z = 0;
ASSERT_TRUE(fm.FloorAt(-1.0, 0.0, &z));
EXPECT_NEAR(z, std::tan(5 * kDeg), 1e-6);
}

237
test/test_scan_leveler.cc Normal file
View File

@@ -0,0 +1,237 @@
// ScanLeveler + ElevationMap: bu nghieng scan LiDAR tren doc, bo tia cham
// san / mat doc.
//
// Hinh hoc robot nay: laser_link o (0, 0, 0.13) tren base_link, banh r 0.0865
// -> LiDAR cao 0.2165 m tren san khi robot nam ngang.
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/elevation_map.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/scan_leveler.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
constexpr double kWheel = 0.0865;
Transform LaserToBase() {
Transform t = TransformIdentity();
t.translation.z = 0.13;
return t;
}
// 360 tia, 1 do / tia, tia i o goc -180 + i do.
LaserScan EmptyScan() {
LaserScan s;
s.angle_min = static_cast<float>(-M_PI);
s.angle_increment = static_cast<float>(kDeg);
s.angle_max = static_cast<float>(-M_PI + 359 * kDeg);
s.range_min = 0.05f;
s.range_max = 30.0f;
s.ranges.assign(360, std::numeric_limits<float>::infinity());
return s;
}
size_t Bin(double deg) { return static_cast<size_t>(std::lround(deg + 180.0)); }
// Goc LiDAR trong frame base_footprint da can, luc than nghieng (roll, pitch).
Point LaserOrigin(double roll, double pitch) {
const Transform T = TransformCompose(TiltLift(roll, pitch, kWheel), LaserToBase());
return TransformPoint(T, Point{0, 0, 0});
}
// Huong tia goc a trong frame da can. CHI phep quay: `TransformVector` cua
// repo cong ca tinh tien.
Vector3 RayDir(double a, double roll, double pitch) {
const Transform T = TransformCompose(TiltLift(roll, pitch, kWheel), LaserToBase());
return RotateVector(T.rotation, Vector3{std::cos(a), std::sin(a), 0.0});
}
} // namespace
TEST(ScanLeveler, NamNgangThiGiuNguyen) {
// Tuong x = 3 m: robot ngang thi scan ra phai Y HET vao.
LaserScan in = EmptyScan();
for (int d = -60; d <= 60; ++d) in.ranges[Bin(d)] = static_cast<float>(3.0 / std::cos(d * kDeg));
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out, &st);
ASSERT_EQ(out.ranges.size(), in.ranges.size());
for (size_t i = 0; i < in.ranges.size(); ++i) {
if (std::isfinite(in.ranges[i])) {
EXPECT_NEAR(out.ranges[i], in.ranges[i], 1e-4) << "tia " << i;
} else {
EXPECT_TRUE(std::isinf(out.ranges[i])) << "tia " << i;
}
}
EXPECT_EQ(st.rebinned, 0u);
EXPECT_EQ(st.kept, 121u);
}
TEST(ScanLeveler, LenDocTuongDoRaKhoangCachNgang) {
// Than ngoc 15 do (pitch AM). Tuong dung o x = 2.0 m trong frame
// base_footprint da can: tia 0 do di xien len, cham tuong o r > 2, va scan
// can phai bao DUNG 2.0 m (RTAB-Map dat diem bang ngoai lai tinh (0, 0)).
const double pitch = -15 * kDeg;
const Point o = LaserOrigin(0.0, pitch);
const Vector3 d = RayDir(0.0, 0.0, pitch);
const double r = (2.0 - o.x) / d.x;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(r);
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_GT(r, 2.05);
EXPECT_NEAR(out.ranges[Bin(0)], 2.0, 1e-4);
}
TEST(ScanLeveler, TiaXienDoiSangOGocMoi) {
// Than ngoc 15 do: tia 45 do chieu xuong mat phang ngang thanh ~46 do.
const double pitch = -15 * kDeg;
LaserScan in = EmptyScan();
in.ranges[Bin(45)] = 3.0f;
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out, &st);
const double a_new = std::atan2(std::sin(45 * kDeg), std::cos(45 * kDeg) * std::cos(15 * kDeg));
const size_t j = Bin(std::round(a_new / kDeg));
EXPECT_NE(j, Bin(45));
EXPECT_TRUE(std::isfinite(out.ranges[j]));
// O cu khong con tia nao: "khong do duoc" (NaN), khong phai "trong" (inf).
EXPECT_TRUE(std::isnan(out.ranges[Bin(45)]));
EXPECT_EQ(st.rebinned, 1u);
}
TEST(ScanLeveler, XuongDocTiaChamSanDuoiBiBo) {
// Dang xuong doc 15 do (chuc mui = pitch DUONG), giua doc o z = 0.75: tia
// truoc cam xuong san duoi chan doc. Khong co ElevationMap van bo duoc vi
// diem cham THAP hon mat dat duoi robot.
const double pitch = 15 * kDeg, z_robot = 0.75;
const Point o = LaserOrigin(0.0, pitch);
const Vector3 d = RayDir(0.0, 0.0, pitch);
const double r = (o.z + z_robot) / -d.z; // toi z tuyet doi = 0
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(r);
LaserScan out;
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, pitch, kWheel, Pose2D{}, z_robot, nullptr, ScanLevelerConfig{},
&out, &st);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
EXPECT_EQ(st.dropped_below, 1u);
}
TEST(ScanLeveler, TuongGiaChanDocLenBoKhiCameraDaThayDoc) {
// Robot ngang tren san, chan doc 15 do o x = 1.0 m: tia ngang cao 0.2165 m
// cham mat doc o x = 1.0 + 0.2165 / tan(15) = 1.808 m -- "tuong" gia.
const double foot = 1.0, t15 = std::tan(15 * kDeg);
const double h_laser = LaserOrigin(0.0, 0.0).z;
const double x_hit = foot + h_laser / t15;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(x_hit);
// Khong co ban do do cao: khong phan biet duoc voi tuong that -> GIU (gioi
// han da noi ro trong scan_leveler.h).
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_NEAR(out.ranges[Bin(0)], x_hit, 1e-4);
// Camera da thay mat doc (diem moi 2 cm tren be mat): bo.
ElevationMap em;
std::vector<PointXYZ> pts;
for (double x = 0.0; x < 4.0; x += 0.02) {
for (double y = -0.5; y <= 0.5; y += 0.02) {
pts.push_back(PointXYZ{static_cast<float>(x), static_cast<float>(y),
static_cast<float>(x > foot ? (x - foot) * t15 : 0.0)});
}
}
em.AddPoints(pts, UnixTime::fromNSec(1));
ScanLevelStats st;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, &em, ScanLevelerConfig{}, &out, &st);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
EXPECT_EQ(st.dropped_floor, 1u);
}
TEST(ScanLeveler, TuongThatCanhDocVanGiu) {
// Tuong that o x = 1.8 m ngay canh vung doc: san duoi chan tuong (camera
// thay) o z = 0 -> diem cao 0.2165 m tren san -> GIU.
ElevationMap em;
std::vector<PointXYZ> pts;
for (double x = 0.0; x < 3.0; x += 0.02) pts.push_back(PointXYZ{static_cast<float>(x), 0.0f, 0.0f});
em.AddPoints(pts, UnixTime::fromNSec(1));
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = 1.8f;
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{}, 0.0, &em, ScanLevelerConfig{}, &out, nullptr);
EXPECT_NEAR(out.ranges[Bin(0)], 1.8, 1e-4);
}
TEST(ScanLeveler, PoseOdomDungTrongElevationMap) {
// ElevationMap o frame ODOM: robot o (10, 5) quay 90 do, tia 0 do huong +y
// cua odom. Mat doc o vung y > 6 chi co o odom -- phai tra dung o.
const double t15 = std::tan(15 * kDeg);
ElevationMap em;
std::vector<PointXYZ> pts;
for (double y = 5.0; y < 9.0; y += 0.02) {
for (double x = 9.5; x <= 10.5; x += 0.02) {
pts.push_back(PointXYZ{static_cast<float>(x), static_cast<float>(y),
static_cast<float>(y > 6.0 ? (y - 6.0) * t15 : 0.0)});
}
}
em.AddPoints(pts, UnixTime::fromNSec(1));
const double h_laser = LaserOrigin(0.0, 0.0).z;
LaserScan in = EmptyScan();
in.ranges[Bin(0)] = static_cast<float>(1.0 + h_laser / t15);
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, 0.0, kWheel, Pose2D{10.0, 5.0, M_PI / 2}, 0.0, &em,
ScanLevelerConfig{}, &out, nullptr);
EXPECT_TRUE(std::isnan(out.ranges[Bin(0)]));
}
TEST(ScanLeveler, SentinelSectorMaskGiuNguyen) {
// Tia bi sector mask cat (range_max + 1 = than robot): giu nguyen, va khong
// tia nao duoc xep de len o do.
LaserScan in = EmptyScan();
in.ranges[Bin(90)] = in.range_max + 1.0f;
in.ranges[Bin(89)] = 2.0f;
LaserScan out;
LevelScan(in, LaserToBase(), 0.0, -15 * kDeg, kWheel, Pose2D{}, 0.0, nullptr, ScanLevelerConfig{}, &out,
nullptr);
EXPECT_FLOAT_EQ(out.ranges[Bin(90)], in.range_max + 1.0f);
}
TEST(ElevationMap, MinVetBanhVaPrune) {
ElevationMap em;
double z = 0;
EXPECT_FALSE(em.FloorAt(0.05, 0.05, &z));
// Hai diem cung o: giu MIN.
em.AddPoints({PointXYZ{0.05f, 0.05f, 0.30f}, PointXYZ{0.06f, 0.04f, 0.10f}}, UnixTime::fromNSec(1));
ASSERT_TRUE(em.FloorAt(0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 0.10f);
// Toa do am khong dung o voi toa do duong (khoa ghep hai chi so co dau).
em.AddPoints({PointXYZ{-0.05f, 0.05f, 1.0f}, PointXYZ{0.05f, -0.05f, 2.0f}}, UnixTime::fromNSec(1));
ASSERT_TRUE(em.FloorAt(-0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 1.0f);
ASSERT_TRUE(em.FloorAt(0.05, -0.05, &z));
EXPECT_FLOAT_EQ(z, 2.0f);
// Vet banh GHI DE (ke ca cao hon min cu).
em.AddFootprint(0.0, 0.0, 0.5, 0.25, UnixTime::fromNSec(2));
ASSERT_TRUE(em.FloorAt(0.05, 0.05, &z));
EXPECT_FLOAT_EQ(z, 0.5f);
// Prune: o xa hon ban kinh bi bo.
em.AddPoints({PointXYZ{20.0f, 0.0f, 0.0f}}, UnixTime::fromNSec(3));
em.Prune(0.0, 0.0, UnixTime::fromNSec(4));
EXPECT_FALSE(em.FloorAt(20.0, 0.0, &z));
EXPECT_TRUE(em.FloorAt(0.05, 0.05, &z));
// Prune: o cu hon max_age bi bo.
em.Prune(0.0, 0.0, UnixTime::fromNSec(static_cast<int64_t>(61e9)));
EXPECT_EQ(em.size(), 0u);
}