This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

View File

@@ -0,0 +1,482 @@
#include "vslam/cliff_detect.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Trung vi cua z tren mot khoang da sap xep theo r; tra ve luon r tai giua
// khoang. Hai trung vi -> mot duong thang. Ben vung hon binh phuong toi thieu:
// mot vet vat can sot lai khong duoc phep keo ca duong.
void MedianOf(std::vector<std::pair<double, double>>::iterator b,
std::vector<std::pair<double, double>>::iterator e, double* r_out,
double* z_out) {
const size_t m = static_cast<size_t>(std::distance(b, e));
std::vector<double> zs;
zs.reserve(m);
for (auto it = b; it != e; ++it) zs.push_back(it->second);
std::nth_element(zs.begin(), zs.begin() + m / 2, zs.end());
*z_out = zs[m / 2];
*r_out = (b + static_cast<long>(m / 2))->first; // da sap xep theo r
}
// Khop BEN VUNG bang hai trung vi, khong dung binh phuong toi thieu: mot vet
// vat can sot lai khong duoc phep keo ca duong thang.
// Tra ve true neu doc bi kep (dau hieu phep khop hong).
bool FitFloorLine(std::vector<std::pair<double, double>>& rz, double* z0,
double* slope, double* slope_raw, double* mad,
double max_slope) {
const size_t n = rz.size(), h = n / 2;
double r1, z1, r2, z2;
MedianOf(rz.begin(), rz.begin() + static_cast<long>(h), &r1, &z1);
MedianOf(rz.begin() + static_cast<long>(h), rz.end(), &r2, &z2);
bool clamped = false;
if (r2 - r1 > 0.15) { // du duong day de uoc luong doc
double sl = (z2 - z1) / (r2 - r1);
*slope_raw = sl; // giu doc TRUOC khi kep, de in ra hieu chuan
// Doc vuot tran = dau hieu phep khop hong, KHONG phai san doc that.
// Ramp la san doc THAT va robot phai di duoc; cong phan biet ramp/vuc la
// MAD, khong phai do lon cua doc.
if (std::fabs(sl) > max_slope) {
clamped = true;
sl = (sl > 0 ? max_slope : -max_slope);
}
*slope = sl;
*z0 = z1 - *slope * r1;
} else {
*slope = 0.0;
*z0 = z1;
}
// MAD cua phan du: duong khop co THUC SU ta duoc mat san khong?
std::vector<double> resid;
resid.reserve(n);
for (const auto& pr : rz) {
resid.push_back(std::fabs(pr.second - (*z0 + *slope * pr.first)));
}
std::nth_element(resid.begin(), resid.begin() + static_cast<long>(n / 2),
resid.end());
*mad = resid[n / 2];
return clamped;
}
} // namespace
const char* CliffBailName(CliffBail b) {
switch (b) {
case CliffBail::kNone: return "none";
case CliffBail::kDisabled: return "disabled";
case CliffBail::kNoRollPitch: return "no_roll_pitch";
case CliffBail::kAccelGated: return "accel_gated";
case CliffBail::kBadGeometry: return "bad_geometry";
case CliffBail::kTzDeviation: return "tz_deviation";
case CliffBail::kFewSamples: return "few_samples";
case CliffBail::kSlopeClamped: return "slope_clamped";
case CliffBail::kResidualLarge: return "residual_large";
case CliffBail::kBadEncoding: return "bad_encoding";
case CliffBail::kObstructed: return "obstructed";
case CliffBail::kOffsetLarge: return "offset_large";
}
return "?";
}
CliffDetect::CliffDetect(CliffDetectConfig cfg) : cfg_(std::move(cfg)) {
if (cfg_.pixel_step < 1) cfg_.pixel_step = 1;
}
void CliffDetect::Reset() {
have_rp_ = false;
bailing_ = false;
stats_ = CliffDetectStats{};
}
void CliffDetect::SetTilt(UnixTime stamp, double roll, double pitch, bool accel_ok) {
roll_ = roll;
pitch_ = pitch;
accel_ok_ = accel_ok;
last_rp_ = stamp;
have_rp_ = true;
}
CliffResult CliffDetect::Bail(CliffBail why, bool immediate, UnixTime now) {
if (!bailing_) {
bailing_ = true;
bail_since_ = now;
}
const double held = SecondsBetween(now, bail_since_);
CliffResult r;
r.judged = false;
r.bail = why;
r.bail_held = held;
// immediate = true -> mot khung du de bao nguy (hinh hoc vo nghia, robot
// dang nghieng / nhoai len vat)
// immediate = false -> mot khung xau la nhieu nhat thoi; nhung mu LIEN TUC
// qua fail_safe_after giay thi bao nguy.
//
// ============ TRU `kObstructed` RA KHOI FAIL-SAFE ============
//
// Fail-safe ton tai cho truong hop "toi khong thay san va KHONG BIET vi
// sao": khong du mau, khop hong, mat phang vo nghia. Luc do khong loai tru
// duoc mot cai vuc, nen phai dung.
//
// `kObstructed` khac han. No la mot quan sat KHANG DINH: cua so nhin san bi
// mot vat DAC lap kin. Vat dac khong phai vuc, va da co nguoi lo -- LiDAR
// thay no va FSM dung robot qua SCAN_SLOW/SCAN_STOP.
//
// Do duoc tren ban do benh vien that: dung o (0.5, 0) cach tuong 2.0 m --
// cua so nhin san 1.1-2.5 m bi buc tuong lap kin -- ra 209/240 khung "bao
// vuc" voi ly do `obstructed`. Hau qua: robot KHONG BAO GIO lai gan tuong
// duoi ~2.5 m duoc, tuc khong di duoc trong bat ky toa nha that nao. Ban do
// SLAM ket o 1.55 x 1.05 m sau 50 giay lai.
//
// ⚠️ Van BAO CAO bail nhu cu (`judged = false`): nguoi van hanh phai thay
// detector dang mu. Chi khong bien cai mu DA GIAI THICH DUOC thanh lenh
// dung.
const bool blind_for_unknown_reason = (why != CliffBail::kObstructed);
r.detected = cfg_.fail_safe && blind_for_unknown_reason &&
(immediate || held > cfg_.fail_safe_after);
stats_.bailed++;
stats_.bail_by[static_cast<size_t>(why)]++;
if (r.detected) stats_.detected++;
return r;
}
CliffResult CliffDetect::Process(const Image& depth, const CameraInfo& info,
const Transform& cam_to_base, UnixTime now) {
stats_.frames++;
if (!cfg_.enabled) {
CliffResult r;
r.judged = false;
r.bail = CliffBail::kDisabled;
return r;
}
if (depth.data == nullptr ||
(depth.format != PixelFormat::kMono16 && depth.format != PixelFormat::kFloat32)) {
return Bail(CliffBail::kBadEncoding, false, now);
}
const bool rp_fresh =
have_rp_ && SecondsBetween(now, last_rp_) < cfg_.imu_timeout;
double roll = 0.0, pitch = 0.0;
if (rp_fresh) {
roll = roll_;
pitch = pitch_;
}
// Khong co roll/pitch moi -> gia dinh phang va di tiep. Ket qua KHONG dang
// tin khi robot nghieng, nhung mot camera gan chac phang van tot hon la
// khong phan xet gi.
// gravity_align dang khong neo duoc vao trong luc -> pitch la gyro thuan va
// dang troi. Hinh hoc cat tia x san khong dung tin o trang thai nay.
if (cfg_.require_accel_ok && rp_fresh && !accel_ok_) {
return Bail(CliffBail::kAccelGated, false, now);
}
// Cung mot hinh hoc voi GravityAlign -- dung chung TiltLift().
const Transform T = TransformCompose(TiltLift(roll, pitch, cfg_.wheel_radius),
cam_to_base);
// Hang thu 3 cua ma tran quay: lay bang cach quay ba vector co so.
const double r20 = RotateVector(T.rotation, Vector3{1, 0, 0}).z;
const double r21 = RotateVector(T.rotation, Vector3{0, 1, 0}).z;
const double r22 = RotateVector(T.rotation, Vector3{0, 0, 1}).z;
const double tz = T.translation.z;
// Tia chi cham san khi no chuc XUONG trong base_footprint, va camera phai o
// TREN san.
if (tz <= 0.0) return Bail(CliffBail::kBadGeometry, true, now);
// Camera lech khoi chieu cao danh dinh => robot dang nghieng / da nhoai len
// vat gi do. Dung luc do phep khop mat san se bam theo TANG DUOI va bao
// "khong co vuc" -- im lang khi that su co vuc la kieu hong nguy hiem nhat.
if (std::fabs(tz - cfg_.nominal_tz) > cfg_.max_tz_dev) {
return Bail(CliffBail::kTzDeviation, true, now);
}
// KHONG duoc doc thang info.K. crop_decimate giao anh 320x240 nhung
// CameraInfo van mang K cua 640x480 va bao muc gop qua binning_x/y = 2.
// Doc thang K thi moi tia bi coi nhu nam ngang -> r_floor [3.5, 134] m thay
// vi [1.07, 3.18] -> khong tia nao roi vao cua so -> detector im lang hoan
// toan MA KHONG BAO LOI GI.
const double fx = info.fx_binned(), fy = info.fy_binned();
const double cx = info.cx_binned(), cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return Bail(CliffBail::kBadGeometry, true, now);
const double tan_unc = std::tan(cfg_.pitch_uncertainty_deg * M_PI / 180.0);
const int W = static_cast<int>(depth.width);
const int H = static_cast<int>(depth.height);
const int step = cfg_.pixel_step;
const int gw = (W + step - 1) / step;
const int gh = (H + step - 1) / step;
const size_t ncell = static_cast<size_t>(gw) * static_cast<size_t>(gh);
cand_.assign(ncell, 0);
pos_x_.assign(ncell, 0.0);
pos_y_.assign(ncell, 0.0);
CliffResult res;
res.judged = true;
res.tz = tz;
double r_min = 1e9, r_max = -1e9, z_lowest = 1e9;
// ============ LUOT 1: DO MUC SAN THAM CHIEU ============
// Tru di muc nay bien phep do thanh VI SAI -> sai so pitch, sai so chieu cao
// camera va lun caster deu la common-mode va bi triet.
// z_ref(r) = lvl_z0 + lvl_slope * r
double lvl_z0 = 0.0, lvl_slope = 0.0, lvl_mad = 0.0, lvl_slope_raw = 0.0;
bool leveled = false;
int64_t n_high = 0, n_window = 0;
if (cfg_.self_level) {
rz_.clear();
rz_.reserve(2048);
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) continue;
const double z_exp = -tz / denom;
if (z_exp <= 0.0) continue;
const Point pf = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double rf = std::hypot(pf.x, pf.y);
if (rf < cfg_.min_dist || rf > cfg_.max_dist) continue;
const double d = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
if (!std::isfinite(d) || d <= 0.0) continue;
const Point po = TransformPoint(T, Point{d * a, d * b, d});
// Cong nay lam CA HAI viec: loai vat the (mat ban 0.7 m, mat ghe
// 0.45 m) VA loai vuc that (z ~ -1 m) khoi phep khop. Nho ve thu hai
// ma khop duoc tren TOAN cua so ma khong nuot mat chinh cai vuc dang
// can tim.
n_window++;
if (po.z > cfg_.level_gate) {
n_high++; // diem CAO: vat can che mat san (tuong, ban, ghe)
continue;
}
if (po.z < -cfg_.level_gate) continue; // diem THAP: co the la vuc
rz_.emplace_back(rf, po.z);
}
}
res.lvl_high = n_high;
res.lvl_window = n_window;
// Phan lon cua so bi vat can che -> khong nhin thay san -> KHONG phan xet.
// Phai kiem TRUOC min_level_samples: mot buc tuong gan van de lai du 40
// mau z thap de "khop duoc" mot mat phang khong co that.
if (n_window > 0 &&
static_cast<double>(n_high) > cfg_.max_obstructed_frac * n_window) {
return Bail(CliffBail::kObstructed, false, now);
}
if (static_cast<int>(rz_.size()) < cfg_.min_level_samples) {
// Khong du mau -> khong biet san o dau -> KHONG phan xet. Im lang con
// hon bao gia: bao gia se chan duong robot giua nha hang va nguoi van
// hanh se tat han node di.
return Bail(CliffBail::kFewSamples, false, now);
}
res.lvl_samples = static_cast<int64_t>(rz_.size());
std::sort(rz_.begin(), rz_.end(),
[](const std::pair<double, double>& p, const std::pair<double, double>& q) {
return p.first < q.first;
});
res.lvl_r_lo = rz_.front().first;
res.lvl_r_hi = rz_.back().first;
bool slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
// --- LOAI NGOAI LAI ROI KHOP LAI ---
//
// Phep khop hai-trung-vi chi theo BAN KINH: z = z0 + doc*r. No gop mat
// chieu phuong vi, nen mot buc tuong o MOT BEN lam lech ca vanh.
//
// Do duoc: hanh lang 3.0 m (tuong cach 1.5 m) -> tia nham r > 1.5 dap vao
// tuong o z = 0.8*(1 - 1.5/r); tai r = 2.0 cho z = 0.20, VUA DU lot cong
// level_gate 0.25. Duong khop bi keo len o giua cua so, roi tia san THAT
// o 2.5 m bi do voi mat phang do -> roi duoi nguong -> vuc gia.
// Cong `max_obstructed_frac` KHONG bat duoc: quet ngưỡng tu 0.60 xuong
// 0.20 deu cho dung 6/210 khung sai o be rong 3.0 m, va che% = 0.0 o moi
// nguong -- tuc la vat can chua du nhieu de kich cong.
//
// Mot luot loai ngoai lai giai quyet dung goc: diem tuong la THIEU SO nen
// bi loai, con neu chung la DA SO thi MAD phinh ra va cong
// max_level_residual kich. Khong the lam vuc that bien mat: diem vuc cung
// bi loai khoi phep khop, ma loai chung ra thi mat san tham chieu cang
// dung -> vuc CANG de thay o luot 2.
if (lvl_mad > 1e-6 && rz_.size() >= 8) {
const double cut = std::max(3.0 * lvl_mad, 0.01);
size_t keep = 0;
for (size_t i = 0; i < rz_.size(); ++i) {
if (std::fabs(rz_[i].second - (lvl_z0 + lvl_slope * rz_[i].first)) <= cut) {
rz_[keep++] = rz_[i];
}
}
if (static_cast<int>(keep) >= cfg_.min_level_samples && keep < rz_.size()) {
rz_.resize(keep);
slope_clamped = FitFloorLine(rz_, &lvl_z0, &lvl_slope, &lvl_slope_raw,
&lvl_mad, cfg_.max_level_slope);
}
}
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_mad = lvl_mad;
if (slope_clamped) return Bail(CliffBail::kSlopeClamped, false, now);
if (std::fabs(lvl_z0) > cfg_.max_level_offset) {
// Mat phang khop duoc khong di qua cho robot dang dung -> no khong phai
// mat san. Xem ghi chu o max_level_offset.
return Bail(CliffBail::kOffsetLarge, false, now);
}
if (lvl_mad > cfg_.max_level_residual) {
// Khung nhin khong phai mot mat phang san -> khong co goc quy chieu dang
// tin -> KHONG phan xet.
return Bail(CliffBail::kResidualLarge, false, now);
}
leveled = true;
}
// ============ LUOT 2: PHAN XET TUNG TIA ============
for (int gy = 0; gy < gh; ++gy) {
const int v = gy * step;
if (v >= H) break;
for (int gx = 0; gx < gw; ++gx) {
const int u = gx * step;
if (u >= W) break;
res.n_total++;
const double a = (u - cx) / fx;
const double b = (v - cy) / fy;
const double denom = r20 * a + r21 * b + r22;
if (denom > -1e-6) {
res.n_up++; // tia khong chuc xuong -> khong cham san
continue;
}
const double z_exp = -tz / denom; // depth ma san LE RA phai o do
if (z_exp <= 0.0) {
res.n_zneg++;
continue;
}
const Point p_floor = TransformPoint(T, Point{z_exp * a, z_exp * b, z_exp});
const double r_floor = std::hypot(p_floor.x, p_floor.y);
r_min = std::min(r_min, r_floor);
r_max = std::max(r_max, r_floor);
if (r_floor < cfg_.min_dist || r_floor > cfg_.max_dist) {
res.n_range++;
continue;
}
res.n_inwin++;
const double d_obs = DepthAtMeters(depth, static_cast<uint32_t>(u),
static_cast<uint32_t>(v));
// Nguong no ra theo tam: bu sai so pitch con lai sau tu hieu chuan.
const double z_ref = lvl_z0 + lvl_slope * r_floor;
const double thr = z_ref - (cfg_.cliff_margin + r_floor * tan_unc);
bool is_cand = false;
if (!std::isfinite(d_obs) || d_obs <= 0.0) {
// LO: le ra phai thay san o day ma khong co so do nao. Day la ca cau
// thang TOI, va la ly do phai chay tren anh depth.
is_cand = true;
res.n_hole++;
} else {
const Point p_obs = TransformPoint(T, Point{d_obs * a, d_obs * b, d_obs});
z_lowest = std::min(z_lowest, p_obs.z);
if (p_obs.z < thr) {
is_cand = true; // SUT: be mat thap hon san qua nguong
res.n_drop++;
}
}
if (is_cand) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
cand_[idx] = 1;
// MARK TAI MEP (giao tia x mat san), khong tai diem tra ve. Diem tra
// ve nam duoi day vuc -- hoac khong ton tai.
pos_x_[idx] = p_floor.x;
pos_y_[idx] = p_floor.y;
}
}
}
// ============ DOI CUM: LOAI PIXEL LE ============
res.edge_cloud.header = depth.header;
res.edge_cloud.header.frame_id = kBaseFootprintFrame;
res.edge_cloud.points.clear();
res.edge_cloud.is_dense = true;
const float mark_z = static_cast<float>(-(cfg_.cliff_margin + 0.05));
for (int gy = 0; gy < gh; ++gy) {
for (int gx = 0; gx < gw; ++gx) {
const size_t idx = static_cast<size_t>(gy) * static_cast<size_t>(gw) + gx;
if (!cand_[idx]) continue;
int neigh = 0;
for (int dy = -1; dy <= 1; ++dy) {
const int ny = gy + dy;
if (ny < 0 || ny >= gh) continue;
for (int dx = -1; dx <= 1; ++dx) {
const int nx = gx + dx;
if (nx < 0 || nx >= gw) continue;
if (dx == 0 && dy == 0) continue;
neigh += cand_[static_cast<size_t>(ny) * static_cast<size_t>(gw) + nx];
}
}
if (neigh < cfg_.min_neighbors) continue;
// GIU z AM, khong nang len. Trong costmap cu, vat can ao dat o z duong
// bi chinh tia clearing cua camera xoa ngay frame sau. Khong con costmap
// nua nhung giu nguyen quy uoc de doc lai log cu van khop.
res.edge_cloud.points.push_back(PointXYZ{static_cast<float>(pos_x_[idx]),
static_cast<float>(pos_y_[idx]), mark_z});
res.n_cliff++;
}
}
res.detected = (res.n_cliff >= cfg_.min_cluster);
res.r_min = (r_min > 1e8 ? 0.0 : r_min);
res.r_max = (r_max < -1e8 ? 0.0 : r_max);
res.z_lowest = (z_lowest > 1e8 ? 0.0 : z_lowest);
res.lvl_z0 = lvl_z0;
res.lvl_slope = lvl_slope;
res.lvl_slope_raw = lvl_slope_raw;
res.lvl_mad = lvl_mad;
res.leveled = leveled;
// Den day nghia la da phan xet duoc -> chuoi "khong biet" ket thuc.
bailing_ = false;
stats_.judged++;
if (res.detected) stats_.detected++;
return res;
}
} // namespace vslam

View File

@@ -0,0 +1,123 @@
#include "vslam/depth_filter.h"
#include <cmath>
#include <cstdint>
#include "vslam/log.h"
namespace vslam {
int64_t VoxelKey(double x, double y, double z, double size) {
const int64_t ix = static_cast<int64_t>(std::floor(x / size));
const int64_t iy = static_cast<int64_t>(std::floor(y / size));
const int64_t iz = static_cast<int64_t>(std::floor(z / size));
// Doi sang khong dau 21 bit roi goi. Khong kiem tran o day: voi voxel 3 cm
// thi dai la +-31 km, va mot diem ngoai dai do da la rac tu truoc.
constexpr int64_t kBias = 1 << 20;
const int64_t ux = (ix + kBias) & 0x1FFFFF;
const int64_t uy = (iy + kBias) & 0x1FFFFF;
const int64_t uz = (iz + kBias) & 0x1FFFFF;
return (ux << 42) | (uy << 21) | uz;
}
DepthFilter::DepthFilter(DepthFilterConfig cfg) : cfg_(std::move(cfg)) {}
void DepthFilter::Reset() {
voxels_.clear();
have_output_ = false;
stats_ = DepthFilterStats{};
}
bool DepthFilter::Apply(const PointCloudXYZ& in, UnixTime stamp,
PointCloudXYZ* out) {
stats_.frames_in++;
stats_.points_in += in.points.size();
// Gioi han tan so theo STAMP CUA BAN TIN, khong phai dong ho tuong.
// Dung dong ho tuong se bop nham khi phat lai ban ghi nhanh hon thoi gian
// that -- va bai regression se cho ket qua khac live.
if (cfg_.max_rate > 0.0 && have_output_) {
const double dt = SecondsBetween(stamp, last_output_);
if (dt >= 0.0 && dt < 1.0 / cfg_.max_rate) {
stats_.frames_rate_limited++;
return false;
}
}
// --- 1. PassThrough theo z (khoang cach toi camera) ---
// Duoi Min-Z la vung mu cua D410, khong phai vat can o khoang cach do.
// Tren max_range thi do chinh xac cua stereo giam nhanh theo binh phuong.
std::unordered_map<int64_t, VoxelHit> frame_voxels;
frame_voxels.reserve(in.points.size() / 4 + 16);
size_t after_range = 0;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.z)) continue; // NaN cua cloud to chuc theo anh
if (p.z < cfg_.min_range || p.z > cfg_.max_range) continue;
if (!std::isfinite(p.x) || !std::isfinite(p.y)) continue;
after_range++;
// --- 2. VoxelGrid: gop diem trong cung o ---
const int64_t key = VoxelKey(p.x, p.y, p.z, cfg_.voxel_size);
VoxelHit& h = frame_voxels[key];
h.centroid.x += p.x;
h.centroid.y += p.y;
h.centroid.z += p.z;
h.count++;
}
stats_.points_after_range += after_range;
stats_.points_after_voxel += frame_voxels.size();
out->header = in.header;
out->header.stamp = stamp;
out->points.clear();
out->points.reserve(frame_voxels.size());
out->is_dense = true;
if (!cfg_.enable_temporal) {
for (auto& kv : frame_voxels) {
VoxelHit& h = kv.second;
const float inv = 1.0f / static_cast<float>(h.count);
out->points.push_back(PointXYZ{h.centroid.x * inv, h.centroid.y * inv,
h.centroid.z * inv});
}
} else {
// --- 3. Xac nhan theo thoi gian ---
// Mot voxel phai duoc thay `min_hits` lan trong `temporal_window` moi
// duoc xuat. Loc nhieu nhap nhay cua depth, doi lai mot do tre bang
// (min_hits - 1) khung.
for (auto& kv : frame_voxels) {
VoxelHit& cur = kv.second;
VoxelHit& acc = voxels_[kv.first];
if (acc.hits > 0 &&
SecondsBetween(stamp, acc.last_seen) > cfg_.temporal_window) {
acc.hits = 0; // qua cu -> bat dau dem lai
}
acc.hits++;
acc.last_seen = stamp;
const float inv = 1.0f / static_cast<float>(cur.count);
acc.centroid = PointXYZ{cur.centroid.x * inv, cur.centroid.y * inv,
cur.centroid.z * inv};
if (acc.hits >= cfg_.min_hits) {
out->points.push_back(acc.centroid);
}
}
// Don voxel qua han. Khong don thi map phinh vo han khi robot di xa.
for (auto it = voxels_.begin(); it != voxels_.end();) {
if (SecondsBetween(stamp, it->second.last_seen) > cfg_.temporal_window * 2.0) {
it = voxels_.erase(it);
} else {
++it;
}
}
}
stats_.points_out += out->points.size();
stats_.frames_out++;
last_output_ = stamp;
have_output_ = true;
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,93 @@
#include "vslam/depth_to_cloud.h"
#include <cmath>
#include <cstring>
#include <limits>
namespace vslam {
// Doc mot diem anh depth ra met. Tra NaN neu khong hop le.
//
// Quy uoc cua RealSense va cua depth_image_proc:
// uint16 : 0 = khong do duoc
// float32: NaN = khong do duoc
double DepthAtMeters(const Image& img, uint32_t u, uint32_t v) {
const size_t row = static_cast<size_t>(v) * img.step;
if (img.format == PixelFormat::kMono16) {
const size_t off = row + static_cast<size_t>(u) * 2;
const uint16_t raw = static_cast<uint16_t>(img.data[off]) |
(static_cast<uint16_t>(img.data[off + 1]) << 8);
if (raw == 0) return std::numeric_limits<double>::quiet_NaN();
return raw * static_cast<double>(img.depth_scale);
}
if (img.format == PixelFormat::kFloat32) {
float f;
std::memcpy(&f, img.data + row + static_cast<size_t>(u) * 4, 4);
return f;
}
return std::numeric_limits<double>::quiet_NaN();
}
void DepthToCloud(const Image& depth, const CameraInfo& info, PointCloudXYZ* out) {
out->header = depth.header;
out->points.assign(static_cast<size_t>(depth.width) * depth.height, PointXYZ{});
out->is_dense = false;
if (depth.data == nullptr) return;
// fx/cx DA BU BINNING. crop_decimate cap nhat binning chu khong chia lai K;
// quen bu la moi diem lech theo he so decimate, va cloud van "trong nhu
// that" -- chi la sai ti le.
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
const float nan_v = std::numeric_limits<float>::quiet_NaN();
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
PointXYZ& p = out->points[static_cast<size_t>(v) * depth.width + u];
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) {
p.x = p.y = p.z = nan_v;
continue;
}
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
}
}
}
void DepthToCloudDense(const Image& depth, const CameraInfo& info,
PointCloudXYZ* out) {
out->header = depth.header;
out->points.clear();
out->is_dense = true;
if (depth.data == nullptr) return;
const double fx = info.fx_binned();
const double fy = info.fy_binned();
const double cx = info.cx_binned();
const double cy = info.cy_binned();
if (!(fx > 0.0) || !(fy > 0.0)) return;
out->points.reserve(static_cast<size_t>(depth.width) * depth.height / 2);
for (uint32_t v = 0; v < depth.height; ++v) {
for (uint32_t u = 0; u < depth.width; ++u) {
const double d = DepthAtMeters(depth, u, v);
if (!std::isfinite(d) || d <= 0.0) continue;
PointXYZ p;
p.x = static_cast<float>((u - cx) * d / fx);
p.y = static_cast<float>((v - cy) * d / fy);
p.z = static_cast<float>(d);
out->points.push_back(p);
}
}
}
} // namespace vslam

View File

@@ -0,0 +1,167 @@
#include "vslam/gravity_align.h"
#include <cmath>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
GravityAlign::GravityAlign(GravityAlignConfig cfg) : cfg_(std::move(cfg)) {}
void GravityAlign::Reset() {
initialized_ = false;
roll_ = pitch_ = 0.0;
lpf_init_ = false;
have_odom_ = false;
accel_ok_ = false;
stats_ = GravityAlignStats{};
}
void GravityAlign::FeedOdom(UnixTime stamp, double vx, double vyaw) {
if (have_odom_) {
const double dt = SecondsBetween(stamp, last_odom_);
if (dt > 0.0 && dt < 1.0) {
// Dao ham van toc, loc thong thap. Dao ham tho qua nhieu de tru truc
// tiep khoi gia toc ke.
const double a = (vx - v_prev_) / dt;
a_lin_ = cfg_.odom_accel_alpha * a + (1.0 - cfg_.odom_accel_alpha) * a_lin_;
}
}
v_prev_ = vx;
w_ = vyaw;
last_odom_ = stamp;
have_odom_ = true;
}
void GravityAlign::FeedImu(const Imu& imu) {
const UnixTime now = imu.header.stamp;
stats_.imu_samples++;
if (!initialized_) {
last_imu_ = now;
initialized_ = true;
return;
}
const double dt = SecondsBetween(now, last_imu_);
last_imu_ = now;
if (dt <= 0.0 || dt > 1.0) {
// Nhay thoi gian (reset mo phong / phat lai ban ghi) -> bo qua mau nay.
return;
}
// --- Du doan bang gyro ---
roll_ += imu.angular_velocity.x * dt;
pitch_ += imu.angular_velocity.y * dt;
// --- Loc thong thap accel TRUOC khi dung ---
// Accel tho dao dong manh do rung tiep xuc banh-san; ap cong |a| ~ g len
// mau tho se tu choi gan nhu moi mau, va bo loc chi con lai tich phan gyro
// -- tuc la troi tu do.
const double ax_raw = imu.linear_acceleration.x;
const double ay_raw = imu.linear_acceleration.y;
const double az_raw = imu.linear_acceleration.z;
if (!lpf_init_) {
ax_f_ = ax_raw;
ay_f_ = ay_raw;
az_f_ = az_raw;
lpf_init_ = true;
} else {
const double a = cfg_.accel_lpf_alpha;
ax_f_ = a * ax_raw + (1.0 - a) * ax_f_;
ay_f_ = a * ay_raw + (1.0 - a) * ay_f_;
az_f_ = a * az_raw + (1.0 - a) * az_f_;
}
// --- Hieu chinh bang accel, CHI khi dang gan trang thai tinh ---
const double ax = ax_f_, ay = ay_f_, az = az_f_;
// TRU gia toc cua CHINH ROBOT truoc khi coi phan con lai la trong luc.
// axc: gia toc tinh tien (dv/dt)
// ayc: gia toc huong tam khi quay (v * omega)
double axc = ax, ayc = ay;
const bool odom_fresh =
have_odom_ && SecondsBetween(now, last_odom_) < cfg_.odom_timeout;
if (cfg_.use_odom_accel && odom_fresh) {
axc = ax - a_lin_;
ayc = ay - v_prev_ * w_;
}
const double norm = std::sqrt(axc * axc + ayc * ayc + az * az);
stats_.last_accel_norm = norm;
if (std::fabs(norm - kGravity) < cfg_.accel_gate && norm > 1e-3) {
const double roll_acc = std::atan2(ayc, az);
const double pitch_acc = std::atan2(-axc, std::sqrt(ayc * ayc + az * az));
// Bo loc bu: gyro cho ngan han, accel keo ve dai han.
roll_ = cfg_.alpha * roll_ + (1.0 - cfg_.alpha) * roll_acc;
pitch_ = cfg_.alpha * pitch_ + (1.0 - cfg_.alpha) * pitch_acc;
accel_ok_ = true;
stats_.accel_accepted++;
} else {
// Dang tang toc / phanh / va cham -> khong biet dau la trong luc ->
// chi tich phan gyro. Troi cham con hon nghieng sai.
accel_ok_ = false;
stats_.accel_rejected++;
}
}
Transform TiltLift(double roll, double pitch, double wheel_radius) {
// Ghep hai phep bien doi:
// tilt : Ry(pitch) * Rx(roll) -- DUNG dau duong.
// Bo loc bu cho ra pitch = atan2(-ax, |a_yz|); voi robot tinh
// nghieng goc theta quanh +Y, gia toc ke doc ax = -g sin(theta),
// az = g cos(theta) => pitch = theta. Do la phep quay body->the
// gioi, tuc dung chieu de dua diem tu base_link ve mat phang ngang.
// Phu dinh o day se lam nghieng GAP DOI thay vi trie^t tieu.
// lift : base_link (tam truc) -> base_footprint (mat dat).
Transform tilt = TransformIdentity();
tilt.rotation = QuaternionFromRPY(roll, pitch, 0.0);
Transform lift = TransformIdentity();
lift.translation = Vector3{0.0, 0.0, wheel_radius};
return TransformCompose(lift, tilt);
}
bool GravityAlign::Align(const PointCloudXYZ& in, const Transform& cam_to_base,
UnixTime stamp, PointCloudXYZ* out) const {
if (!initialized_) return false;
stats_.clouds_in++;
stats_.points_in += in.points.size();
// Ghep ba phep bien doi:
// lift : base_link -> base_footprint (nang len chieu cao banh xe)
// tilt : bu nghieng DO duoc (nghich dao cua nghieng than)
// cam : camera -> base_link (tinh, tu robot.yaml)
const Transform total =
TransformCompose(TiltLift(roll_, pitch_, cfg_.wheel_radius), cam_to_base);
out->header = in.header;
out->header.stamp = stamp;
out->header.frame_id = kBaseFootprintFrame;
out->points.clear();
out->points.reserve(in.points.size());
out->is_dense = true;
for (const PointXYZ& p : in.points) {
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
const Point q = TransformPoint(total, Point{p.x, p.y, p.z});
// Cat dai chieu cao SAU khi xoay: duoi min_height la san, tren max_height
// la tran va den.
if (q.z < cfg_.min_height || q.z > cfg_.max_height) continue;
out->points.push_back(PointXYZ{static_cast<float>(q.x), static_cast<float>(q.y),
static_cast<float>(q.z)});
}
stats_.clouds_out++;
stats_.points_out += out->points.size();
return true;
}
} // namespace vslam

View File

@@ -0,0 +1,89 @@
#include "vslam/perception_pipeline.h"
#include <algorithm>
#include <chrono>
#include "vslam/depth_to_cloud.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
PerceptionPipeline::PerceptionPipeline(PerceptionConfig cfg, const Clock& clock)
: cfg_(std::move(cfg)),
clock_(clock),
cam_to_base_(TransformIdentity()),
gravity_(cfg_.gravity),
filter_(cfg_.filter),
cliff_(cfg_.cliff) {}
void PerceptionPipeline::SetCameraExtrinsic(const Transform& cam_to_base) {
cam_to_base_ = cam_to_base;
}
void PerceptionPipeline::FeedImu(const Imu& imu) { gravity_.FeedImu(imu); }
void PerceptionPipeline::FeedOdom(UnixTime stamp, double vx, double vyaw) {
gravity_.FeedOdom(stamp, vx, vyaw);
}
void PerceptionPipeline::Reset() {
gravity_.Reset();
filter_.Reset();
cliff_.Reset();
stats_ = PerceptionStats{};
}
PerceptionOutput PerceptionPipeline::Process(const Image& depth, const CameraInfo& info) {
// steady_clock cho do thoi gian -- KHONG dung UnixTime. Mot buoc NTP giua
// hai moc se cho ra "khung xu ly het -3 giay".
const auto t0 = std::chrono::steady_clock::now();
stats_.frames_in++;
PerceptionOutput out;
out.stamp = depth.header.stamp;
out.roll = gravity_.roll();
out.pitch = gravity_.pitch();
out.tilt_valid = gravity_.valid();
out.accel_ok = gravity_.accel_ok();
// --- Duong cliff: chay tren ANH DEPTH, khong qua cloud ---
// Dat TRUOC duong cloud vi no la duong an toan. Neu duong cloud nem hay
// cham, cliff van da chay xong.
if (cfg_.enable_cliff) {
cliff_.SetTilt(depth.header.stamp, gravity_.roll(), gravity_.pitch(),
gravity_.accel_ok());
CliffResult cr = cliff_.Process(depth, info, cam_to_base_, clock_.Now());
out.cliff_detected = cr.detected;
out.cliff_detail = cr.judged ? "judged" : CliffBailName(cr.bail);
if (!cr.edge_cloud.points.empty()) {
out.cloud_cliff = std::make_shared<const PointCloudXYZ>(std::move(cr.edge_cloud));
}
}
// --- Duong cloud: cho SLAM va cho hien thi ---
if (cfg_.enable_cloud) {
DepthToCloudDense(depth, info, &buf_raw_);
out.cloud_raw = std::make_shared<const PointCloudXYZ>(buf_raw_);
if (filter_.Apply(buf_raw_, depth.header.stamp, &buf_filt_)) {
out.cloud_filtered = std::make_shared<const PointCloudXYZ>(buf_filt_);
if (gravity_.Align(buf_filt_, cam_to_base_, depth.header.stamp, &buf_align_)) {
out.cloud_aligned = std::make_shared<const PointCloudXYZ>(buf_align_);
}
}
}
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0)
.count();
stats_.frames_out++;
stats_.last_ms = ms;
stats_.max_ms = std::max(stats_.max_ms, ms);
// Trung binh truot: du de bao cao, khong giu lich su.
stats_.avg_ms += (ms - stats_.avg_ms) * 0.05;
return out;
}
} // namespace vslam