#include "vslam/cliff_detect.h" #include #include #include #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>::iterator b, std::vector>::iterator e, double* r_out, double* z_out) { const size_t m = static_cast(std::distance(b, e)); std::vector 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(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>& 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(h), &r1, &z1); MedianOf(rz.begin() + static_cast(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 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(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; // Mang theo mat phang khop duoc gan nhat: voi offset_large / residual_large // / slope_clamped thi day chinh la bang chung noi vi sao bail. r.lvl_z0 = last_lvl_z0_; r.lvl_slope = last_lvl_slope_; r.lvl_mad = last_lvl_mad_; // 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(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(depth.width); const int H = static_cast(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(gw) * static_cast(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(u), static_cast(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(n_high) > cfg_.max_obstructed_frac * n_window) { return Bail(CliffBail::kObstructed, false, now); } if (static_cast(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(rz_.size()); std::sort(rz_.begin(), rz_.end(), [](const std::pair& p, const std::pair& 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(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; // Luu lai de Bail() con mang theo duoc -- xem ghi chu o khai bao. last_lvl_z0_ = lvl_z0; last_lvl_slope_ = lvl_slope; last_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(u), static_cast(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(gy) * static_cast(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(-(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(gy) * static_cast(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(ny) * static_cast(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(pos_x_[idx]), static_cast(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