Compare commits

...

2 Commits

Author SHA1 Message Date
trung09122002
3b5703e41a tools: gen_world_from_db.py -- sinh world mo phong tu DB ban do that: dia hinh tu do cao node, tuong tu luoi log-odds (bo tia LiDAR cham san doc), ban SAO DB ha Admin.version 0.23 -> 0.21 de may dev mo duoc; in cho xuat phat (dinh doc lon nhat) + lenh sim 2026-10-08 15:52:02 +07:00
trung09122002
fc03420d2c slope: test doc tu dong (--slope-test) -- dinh vi lai xong robot tu tim truc doc tren ban do (do cao san cua node), quay mat xuong doc, cho nut Y (gamepad.button_test) roi chay N luot xuong/len, moi luot mot van toc (mac dinh 10 luot 0.10..0.46 m/s)
Lenh di qua FSM an toan nhu moi lenh khac; dung han khi lech duong > 0.4 m, scan mat khop 1.5 s, pose nhay > 0.3 m, nghieng > 20 do. Do lech dinh vi 2 lan/giay (khop scan voi likelihood field, doc lap RTAB-Map) ra logs/slope_test_<gio>.csv + bang tong. Sim 08/10 (slope_two_ramps, 10 luot): lech that trung vi 0.9 cm, max 3.0 cm, sai z trung vi 0.3 cm, khong troi tu luot 1 den 10.
2026-10-08 15:52:02 +07:00
14 changed files with 1969 additions and 1 deletions

View File

@@ -269,6 +269,35 @@ Bo `--slam-reloc-vpr` thi chi dung LiDAR (chua co engine TensorRT, hoac camera h
Dong nay in TRUOC khi mo camera nen camera hong van thay -- chi tin dong chot.
- DB quet tren Jetson (RTAB-Map 0.23) khong mo duoc bang RTAB-Map 0.21 cua may dev.
**Test doc tu dong** (`--slope-test`): dat robot o DINH doc (cho phang, gan dau doc), chay dinh vi
lai kem `--slope-test`. Chot xong robot TU tim truc doc tren ban do (do cao san cua node), ve dinh
doc neu dinh vi lai da tu chay ra giua doc, quay mat XUONG doc, roi **cho bam Y** tren tay cam (mo
phong: tu chay). Moi luot: xuong toi chan doc (phang + 0.5 m), dung 3 s, quay dau, len lai dinh,
dung 3 s. Mac dinh 10 luot, van toc moi luot 0.10, 0.14, ..., 0.46 m/s (`--slope-test-loops N`,
`--slope-test-speeds 0.1,0.2,...` hoac `0.3:1.0` = chia deu cho so luot; toi da = tran an toan
0.5 m/s, sim nang bang `--max-speed V`; robot that bi base kep o `robot.yaml base.max_linear`).
```sh
./build/jetson/app/vslam_node --live --gamepad --token "$VSLAM_TOKEN" \
--slam --slam-db $MAP --slam-mode localization \
--slam-reloc --slam-reloc-auto --slope-test 2>&1 | tee -i logs/real_slope_test_$(date +%m%d_%H%M).log
```
- Doi dong `slope_test: da quay mat xuong doc ... Bam Y` va NHIN robot: mat phai huong xuong doc.
Sai huong (vd quay vao tuong -- dinh vi lai chot nham cho) thi KHONG bam Y, Ctrl-C.
- Gat can tay cam / web / e-stop luc nao = **TAM DUNG**; bam Y de chay tiep.
- Tu **DUNG HAN** khi: lech khoi duong > 0.4 m, scan khong khop ban do 1.5 s, pose nhay > 0.3 m,
nghieng > 20 do, mot luot qua thoi gian. Lenh van qua lop an toan nhu moi lenh khac.
- ⚠️ `cliff_detect` dang TAT: luon co nguoi cam e-stop canh doc; chan doc can ~1 m phang de quay
dau. Khong chay lui (sau lung la quat mu LiDAR).
- Ket qua: 2 lan / giay ghi `logs/slope_test_<gio>.csv` -- lech dinh vi (doi pose de scan KHOP luoi
ban do nhat, doc lap voi RTAB-Map), goc, sai z so voi san ban do, do khop. Xong du luot thi in
**BANG TONG** theo luot / chieu + xu huong lech luot dau -> luot cuoi, ghi ra
`logs/slope_test_<gio>_tong.txt`, roi node **TU THOAT**. Ctrl-C giua chung cung in bang. Dung han
thi node CHAY TIEP de lai tay ra khoi doc, Ctrl-C de thoat. Sim 08/10: phep do bao du
~1-2 cm so voi ground truth (lech that 0.6-1.3 cm) va co diem vot khi scan it rang buoc doc truc
doc (doc dai giua hai tuong song song) -- dung de SO giua van toc / luot, khong phai thuoc tuyet doi.
**Lay log ve may dev:**
```sh

View File

@@ -765,7 +765,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"min_angular_kick", "idle_publish_sec", "reopen_period_sec",
"turbo_linear", "turbo_angular", "slow_linear", "slow_angular",
"axis_linear", "axis_linear_dpad", "axis_angular",
"axis_angular_dpad", "button_enable", "button_zero",
"axis_angular_dpad", "button_enable", "button_zero", "button_test",
"button_turbo", "button_slow", "invert_linear",
"invert_angular", "lt_stop", "axis_lt", "lt_press_above"});
if (!r.ok()) return r;
@@ -805,6 +805,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
out->gamepad.button_enable =
gp.get<int>("button_enable", out->gamepad.button_enable);
out->gamepad.button_zero = gp.get<int>("button_zero", out->gamepad.button_zero);
out->gamepad.button_test = gp.get<int>("button_test", out->gamepad.button_test);
out->gamepad.button_turbo =
gp.get<int>("button_turbo", out->gamepad.button_turbo);
out->gamepad.button_slow = gp.get<int>("button_slow", out->gamepad.button_slow);

View File

@@ -84,6 +84,15 @@ void Usage(const char* argv0) {
" kem --slam-reloc: CAMERA cung dinh vi lai (VPR + PnP,\n"
" chot khi trung LiDAR). Can build -DVSLAM_WITH_TENSORRT=ON;\n"
" mac dinh $VSLAM_RESOURCE_DIR/vpr/eigenplaces_r50_fp16.plan\n"
" --slope-test kem --slam-reloc: TEST DOC TU DONG. Dat robot o DINH doc;\n"
" chot xong tu tim doc tren ban do, quay mat xuong, cho Y\n"
" tren tay cam (mo phong: tu chay), roi xuong / len N luot,\n"
" moi luot mot van toc. Do lech dinh vi + z 2 Hz,\n"
" CSV logs/slope_test_*.csv + bang tong. Gat can = tam dung.\n"
" --slope-test-loops N so luot (mac dinh 10)\n"
" --slope-test-speeds V1,V2,.. van toc moi luot, m/s (toi da = tran an toan\n"
" 0.5; sim nang bang --max-speed). A:B = chia deu A -> B\n"
" cho so luot. Mac dinh 0.10,0.14,...,0.46\n"
" --check nap va KIEM cau hinh roi thoat, khong chay gi\n",
argv0, vslam::ConfigDir().c_str());
}
@@ -189,6 +198,27 @@ int main(int argc, char** argv) {
opts.slam_reloc_vpr = true;
if (i + 1 < argc && argv[i + 1][0] != '-') opts.vpr_engine = argv[++i];
}
else if (a == "--slope-test") opts.slope_test = true;
else if (a == "--slope-test-loops") opts.slope_test_loops = std::atoi(next().c_str());
else if (a == "--slope-test-speeds") {
const std::string v = next();
// "A:B" = chia deu A -> B cho so luot (runtime tinh, vi --slope-test-loops
// co the dung sau).
const size_t colon = v.find(':');
if (colon != std::string::npos) {
opts.slope_test_vmin = std::atof(v.substr(0, colon).c_str());
opts.slope_test_vmax = std::atof(v.substr(colon + 1).c_str());
continue;
}
size_t b = 0;
while (b <= v.size()) {
const size_t e = v.find(',', b);
const std::string tok = v.substr(b, e == std::string::npos ? std::string::npos : e - b);
if (!tok.empty()) opts.slope_test_speeds.push_back(std::atof(tok.c_str()));
if (e == std::string::npos) break;
b = e + 1;
}
}
else if (a == "--check") check_only = true;
else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; }
else {

View File

@@ -2,14 +2,17 @@
#include <pthread.h>
#include <sched.h>
#include <sys/stat.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <deque>
#include <limits>
#include <sstream>
#include "vslam/binary_codec.h"
#include "vslam/clock.h"
@@ -835,12 +838,58 @@ StatusResponse Runtime::Start() {
safety_thread_ = std::thread([this] { SafetyLoop(); });
ApplyThreadPriority(&safety_thread_, cfg_->threads.safety_priority, "safety");
#ifdef VSLAM_HAVE_SLAM
// --- Test doc tu dong (--slope-test) ---
if (opts_.slope_test) {
if (!slam_enabled_ || !opts_.slam_reloc || !reloc_field_) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"--slope-test can --slam --slam-mode localization --slam-reloc: dung luoi ban do de "
"tim doc va do sai so");
}
SlopeTestConfig sc;
sc.loops = std::max(1, opts_.slope_test_loops);
if (!opts_.slope_test_speeds.empty()) sc.speeds = opts_.slope_test_speeds;
if (opts_.slope_test_vmax > 0.0) {
// A:B -> chia deu cho so luot (1 luot = A).
sc.speeds.clear();
for (int k = 0; k < sc.loops; ++k) {
const double u = sc.loops > 1 ? static_cast<double>(k) / (sc.loops - 1) : 0.0;
sc.speeds.push_back(opts_.slope_test_vmin + u * (opts_.slope_test_vmax - opts_.slope_test_vmin));
}
}
// Tran = tran cua lop an toan: 0.5 m/s (safety.yaml); sim --max-speed V nang
// ca ba tang (teleop, safety, base sim). Robot that: base ZLAC con tu kep o
// robot.yaml base.max_linear -- nang tran that la quyet dinh AN TOAN rieng.
const double vcap = cfg_->safety.max_linear;
std::string sp;
for (const double v : sc.speeds) {
if (!(v > 0.0) || v > vcap + 1e-9) {
std::ostringstream os;
os << "--slope-test-speeds: moi van toc phai trong (0, " << vcap
<< "] m/s (tran an toan" << (opts_.source == SourceKind::kSim ? "; sim: them --max-speed V" : "")
<< ")";
return StatusResponse::Error(StatusCode::kInvalidArgument, os.str());
}
sp += (sp.empty() ? "" : " / ") + std::to_string(v).substr(0, 4);
}
slope_test_.reset(new SlopeTest(sc));
VSLAM_INFO("slope_test: BAT -- " << sc.loops << " luot (xuong + len), van toc moi luot " << sp
<< " m/s. Dinh vi lai xong se tu tim doc tren ban do va quay mat xuong, roi "
<< (opts_.source == SourceKind::kSim ? "TU CHAY (mo phong)." : "cho bam Y."));
}
#endif
if (slam_enabled_) {
slam_thread_ = std::thread([this] { SlamLoop(); });
// CFS, KHONG realtime. Luong nay chan hang tram ms; cho no uu tien cao la
// cach chac chan nhat de treo vong an toan.
}
#ifdef VSLAM_HAVE_SLAM
if (slope_test_) slope_thread_ = std::thread([this] { SlopeLoop(); });
#endif
web_thread_ = std::thread([this] { WebLoop(); });
// web_tx chay CFS: no khong o trong vong an toan, va nang no len se lay mat
// CPU cua luong dang giu robot khong dam vao tuong.
@@ -872,11 +921,26 @@ void Runtime::Join() {
// `raw_cmd_` con duoc ghi ma khong con ai don no ve 0.
if (gamepad_thread_.joinable()) gamepad_thread_.join();
if (gamepad_) gamepad_->Close();
#ifdef VSLAM_HAVE_SLAM
// Test doc cung la NGUON LENH: tat truoc vong safety, cung ly do voi tay cam.
if (slope_thread_.joinable()) slope_thread_.join();
#endif
if (safety_thread_.joinable()) safety_thread_.join();
if (web_thread_.joinable()) web_thread_.join();
if (slam_thread_.joinable()) slam_thread_.join();
if (source_thread_.joinable()) source_thread_.join();
#ifdef VSLAM_HAVE_SLAM
// Ctrl-C giua chung: van in bang tong phan da do (luong slam da dung).
if (slope_test_ && !slope_summary_done_) {
SlopeTestPhase ph;
{
std::lock_guard<std::mutex> lk(slope_mu_);
ph = slope_test_->phase();
}
SlopeTestSummary(ph);
}
#endif
// Dung base TRUOC khi dong web: neu dong web truoc thi trong khoang giua,
// khong con ai gui lenh nhung robot van con van toc cuoi cung.
@@ -1120,6 +1184,12 @@ void Runtime::GamepadLoop() {
while (!stop_.load()) {
const GamepadState s = gamepad_->Snapshot();
GamepadCommand c = gamepad_map_->Step(s, clock_->Now());
#ifdef VSLAM_HAVE_SLAM
if (c.test_pressed) {
slope_button_.fetch_add(1);
if (slope_test_) VSLAM_INFO("gamepad: bam Y (test doc)");
}
#endif
if (c.connected_changed && s.connected) {
VSLAM_INFO("gamepad: da ket noi (" << gamepad_->DeviceInfo()
@@ -1268,6 +1338,11 @@ void Runtime::SlamLoop() {
// sai 1 m (docs/SLAM.md). Chot roi thi pose ban dau tinh tu CHINH odom
// nay -- khong tre, khong phai cho robot dung nhu ban ROS.
if (reloc_active_) {
if (slope_test_) {
// Dinh vi lai chay LAI sau khi test da co duong = mat dinh vi giua chung.
std::lock_guard<std::mutex> lk(slope_mu_);
if (slope_planned_) slope_lost_.store(true);
}
RelocStep(*scan, odom);
if (reloc_active_) continue;
}
@@ -1384,6 +1459,9 @@ void Runtime::SlamLoop() {
}
}
// --- Test doc tu dong: lap duong sau khi chot, do 2 Hz ---
if (slope_test_) SlopeTestSlamStep(out, *scan);
bool need_map = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
@@ -3126,4 +3204,368 @@ void Runtime::WebLoop() {
}
}
#ifdef VSLAM_HAVE_SLAM
// ============================================================================
// Test doc tu dong (--slope-test). Logic lai o vslam/slope_test.h; o day chi
// noi day: lap duong tu ban do, lai 20 Hz, do 2 Hz, ghi CSV, bang tong.
// ============================================================================
void Runtime::SlopeLoop() {
const auto t0 = std::chrono::steady_clock::now();
auto next = t0;
int seen = slope_button_.load();
while (!stop_.load()) {
next += std::chrono::milliseconds(50);
bool planned = false;
{
std::lock_guard<std::mutex> lk(slope_mu_);
planned = slope_planned_;
}
const int b = slope_button_.load();
if (planned) {
SlopeTestInput in;
in.t = 1.0 + std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
Pose2D corr;
bool loc = false;
{
std::lock_guard<std::mutex> lk(slam_mu_);
corr = map_correction_;
loc = slam_localized_;
}
Pose2D od;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
}
// Pose MAP 20 Hz: phep nan cua RTAB-Map (3 Hz) x EKF (44 Hz).
in.pose = Pose2DCompose(corr, od);
// Chi tin DO DOC LAP: dinh vi lai chay lai / scan khop kem lien tiep
// (SlopeTestSlamStep). `slam_localized_` cua RTAB-Map khong dung duoc o day:
// localization chi bat no sau khi robot da chay.
(void)loc;
in.localized = !slope_lost_.load();
in.roll = tilt_roll_.load(std::memory_order_relaxed);
in.pitch = tilt_pitch_.load(std::memory_order_relaxed);
// Tay cam / web vua ra lenh, hoac e-stop: nhuong NGAY, cho bam Y.
in.human = RelocHumanCommanding() || estop_.load();
in.start = b != seen;
SlopeTestOutput o;
{
std::lock_guard<std::mutex> lk(slope_mu_);
o = slope_test_->Step(in);
}
// CUNG duong voi dinh vi lai tu dong: raw_cmd_ -> FSM an toan -> base.
if (o.command) RelocCommand(o.v, o.w);
if (!o.event.empty()) VSLAM_INFO("slope_test: " << o.event);
}
seen = b;
std::this_thread::sleep_until(next);
}
}
void Runtime::SlopeTestSlamStep(const SlamOutput& out, const LaserScan& scan) {
if (!reloc_field_) return;
const LikelihoodField& lf = *reloc_field_;
bool planned = false;
bool approaching = false;
SlopeTestPhase ph = SlopeTestPhase::kIdle;
int loop = 0;
bool down = true;
double speed = 0.0, along = 0.0, cross = 0.0;
{
std::lock_guard<std::mutex> lk(slope_mu_);
planned = slope_planned_;
ph = slope_test_->phase();
approaching = slope_test_->approaching();
loop = slope_test_->loop();
down = slope_test_->down();
speed = slope_test_->speed();
along = slope_test_->along();
cross = slope_test_->cross();
}
if (!planned) {
// ---- Lap duong, MOT lan, ngay sau khi chot ----
// Toi duoc day nghia la dinh vi lai DA CHOT (vong slam `continue` khi chua).
// KHONG cho `out.localized`: o localization no chi bat khi RTAB-Map tu khop
// duoc -- can robot DA CHAY, ma robot dang dung cho chinh test nay.
if (slope_plan_failed_) return;
const FloorModel& fm = slam_->floor_model();
if (fm.empty()) {
VSLAM_WARN("slope_test: ban do khong co do cao node (slam.yaml slope.enabled? ban do quet "
"truoc khi co che do doc?) -- KHONG chay.");
slope_plan_failed_ = true;
return;
}
// O trong VA du cho than robot: ban kinh than + 10 cm, tren luoi ban do.
const double clear = cfg_->robot.geometry().robot_radius + 0.10;
const double res = lf.resolution();
const int rr = static_cast<int>(std::ceil(clear / res));
auto free = [&](double x, double y) {
// Robot DA di qua cho nay luc quet -> di duoc. Luoi dinh vi lai (dung thang
// tu DB) con TUONG GIA o chan doc (tia LiDAR cham mat doc tu xa) -- lop
// camera chi xoa chung tren ban do hien thi. Sim 08/10: chan het moi huong
// xuong doc ngay chan doc.
FloorNode n;
double dn = 0.0;
if (fm.NearestNode(x, y, &n, &dn) && dn <= 0.35) return true;
// Goc luoi RTAB-Map la GOC o (0, 0) (xep o bang phep cat): tra bang floor.
const int c0 = static_cast<int>(std::floor((x - lf.origin_x()) / res));
const int r0 = static_cast<int>(std::floor((y - lf.origin_y()) / res));
for (int dr = -rr; dr <= rr; ++dr) {
for (int dc = -rr; dc <= rr; ++dc) {
if ((dr * dr + dc * dc) * res * res > clear * clear) continue;
if (!lf.Free(r0 + dr, c0 + dc)) return false;
}
}
return true;
};
// Chi tin mat san gan node da quet (doc rong quet theo lan: giua hai lan ~1.5 m).
auto floor = [&](double x, double y, double* z) {
double d = 0.0;
return fm.FloorAt(x, y, z, &d) && d <= 2.0;
};
SlopePath p;
std::string why, fan;
if (!PlanSlopePath(out.pose_map.x, out.pose_map.y, floor, free, SlopePathConfig{}, &p, &why,
&fan)) {
VSLAM_WARN("slope_test: " << why << " -- KHONG chay.");
slope_plan_failed_ = true;
return;
}
{
std::lock_guard<std::mutex> lk(slope_mu_);
slope_test_->SetPath(p, opts_.source == SourceKind::kSim);
slope_planned_ = true;
}
slope_t0_ = std::chrono::steady_clock::now();
VSLAM_INFO("slope_test: duong thu A (" << p.a.x << ", " << p.a.y << ") -> B (" << p.bx << ", "
<< p.by << "): dai " << p.length << " m, xuong " << p.drop << " m, huong "
<< p.a.theta * 180.0 / M_PI << " do. Dang quay mat xuong doc...");
VSLAM_INFO("slope_test: cac huong da thu (huong:duong trong:dung vi:ket qua):" << fan);
// CSV: logs/ o thu muc chay (goc repo).
::mkdir("logs", 0755);
char stamp[32];
const std::time_t tt = std::time(nullptr);
std::tm tmv{};
localtime_r(&tt, &tmv);
std::strftime(stamp, sizeof(stamp), "%Y%m%d_%H%M%S", &tmv);
slope_csv_path_ = std::string("logs/slope_test_") + stamp + ".csv";
slope_csv_ = std::fopen(slope_csv_path_.c_str(), "w");
if (slope_csv_ != nullptr) {
std::fprintf(slope_csv_,
"t_s,luot,chieu,van_toc,pha,doc_duong_m,lech_ngang_cm,x,y,yaw_deg,khop,"
"khop_tot_nhat,dx_cm,dy_cm,dyaw_deg,lech_cm,z_uoc_luong,z_ban_do,z_sai_cm\n");
} else {
VSLAM_WARN("slope_test: khong mo duoc " << slope_csv_path_ << " -- chi log.");
}
return;
}
if (ph == SlopeTestPhase::kDone || ph == SlopeTestPhase::kHalted) {
if (!slope_summary_done_) {
SlopeTestSummary(ph);
if (ph == SlopeTestPhase::kDone) {
// Xong du luot: TU THOAT (cung duong voi Ctrl-C: dung base, dong DB).
// Truoc day node chay tiep va log khac day troi mat bang tong.
VSLAM_INFO("slope_test: xong -- node tu thoat.");
RequestStop();
} else {
// Dung han (vi pham an toan): robot co the dang GIUA doc -- giu node de
// nguoi lai tay ra khoi doc.
VSLAM_WARN("slope_test: DUNG HAN -- node van chay de lai tay ra khoi doc; "
"Ctrl-C de thoat. Bang tong o tren.");
}
}
return;
}
if (ph != SlopeTestPhase::kDrive && ph != SlopeTestPhase::kDwell) return;
if (approaching) return; // dang ve A: chua phai luot do
const auto now = std::chrono::steady_clock::now();
if (now - slope_meas_at_ < std::chrono::milliseconds(500)) return;
slope_meas_at_ = now;
// ---- Do: lech dinh vi = phep doi pose lam scan KHOP ban do nhat ----
// Do doc lap voi RTAB-Map: chi scan hien tai + luoi ban do. Tho (+-20 cm,
// +-3 do) roi tinh (1 cm, 0.25 do).
const Pose2D pose = out.pose_map;
std::vector<Point> pts = ScanToFrame(scan, pose);
if (pts.size() > 400) {
std::vector<Point> sub;
const size_t stride = (pts.size() + 399) / 400;
for (size_t i = 0; i < pts.size(); i += stride) sub.push_back(pts[i]);
pts.swap(sub);
}
if (pts.size() < 50) return;
const double res = lf.resolution(), ox = lf.origin_x(), oy = lf.origin_y();
auto score = [&](double dx, double dy, double dth) {
const double c = std::cos(dth), s = std::sin(dth);
double sum = 0.0;
for (const Point& q : pts) {
const double rx = q.x - pose.x, ry = q.y - pose.y;
const double qx = pose.x + c * rx - s * ry + dx;
const double qy = pose.y + s * rx + c * ry + dy;
// floor, KHONG lround: goc luoi la GOC o (0, 0). lround lech nua o (2.5 cm
// moi truc) -- sim 08/10: lech gia -4 / -4 cm khi dinh vi that sai 1 cm.
sum += lf.At(static_cast<int>(std::floor((qy - oy) / res)),
static_cast<int>(std::floor((qx - ox) / res)));
}
return sum / static_cast<double>(pts.size());
};
const double deg = M_PI / 180.0;
const double s0 = score(0.0, 0.0, 0.0);
double bx = 0.0, by = 0.0, bth = 0.0, bs = s0;
for (int it = -3; it <= 3; ++it) {
for (int ix = -5; ix <= 5; ++ix) {
for (int iy = -5; iy <= 5; ++iy) {
const double v = score(ix * 0.04, iy * 0.04, it * deg);
if (v > bs) {
bs = v;
bx = ix * 0.04;
by = iy * 0.04;
bth = it * deg;
}
}
}
}
const double cx = bx, cy = by, cth = bth;
for (int it = -3; it <= 3; ++it) {
for (int ix = -4; ix <= 4; ++ix) {
for (int iy = -4; iy <= 4; ++iy) {
const double dx = cx + ix * 0.01, dy = cy + iy * 0.01, dth = cth + it * 0.25 * deg;
const double v = score(dx, dy, dth);
if (v > bs) {
bs = v;
bx = dx;
by = dy;
bth = dth;
}
}
}
}
// Mat dinh vi: scan khop KEM 3 lan do lien tiep (1.5 s) -> luong lai dung han.
if (s0 < 0.15) {
if (++slope_low_ >= 3) slope_lost_.store(true);
} else {
slope_low_ = 0;
}
bool have_z = false;
double z_est = 0.0, z_map = 0.0;
if (slope_on_) {
{
std::lock_guard<std::mutex> lk(odom_mu_);
z_est = height_->z();
}
have_z = slam_->HeightAt(pose.x, pose.y, 1.0, &z_map);
}
SlopeSample smp;
smp.loop = loop;
smp.down = down;
smp.speed = speed;
smp.moving = ph == SlopeTestPhase::kDrive;
smp.err_cm = std::hypot(bx, by) * 100.0;
smp.dth_deg = bth / deg;
smp.score = s0;
smp.have_z = have_z;
smp.zerr_cm = have_z ? (z_est - z_map) * 100.0 : 0.0;
slope_samples_.push_back(smp);
if (slope_csv_ != nullptr) {
const double t = std::chrono::duration<double>(now - slope_t0_).count();
std::fprintf(slope_csv_,
"%.2f,%d,%s,%.2f,%s,%.2f,%.1f,%.3f,%.3f,%.2f,%.3f,%.3f,%.1f,%.1f,%.2f,%.1f,%s,%s,%s\n",
t, loop, down ? "xuong" : "len", speed, smp.moving ? "chay" : "dung", along,
cross * 100.0, pose.x, pose.y, pose.theta / deg, s0, bs, bx * 100.0, by * 100.0,
smp.dth_deg, smp.err_cm, have_z ? std::to_string(z_est).c_str() : "",
have_z ? std::to_string(z_map).c_str() : "",
have_z ? std::to_string(smp.zerr_cm).c_str() : "");
std::fflush(slope_csv_);
}
}
void Runtime::SlopeTestSummary(SlopeTestPhase end) {
slope_summary_done_ = true;
if (slope_csv_ != nullptr) {
std::fclose(slope_csv_);
slope_csv_ = nullptr;
}
// Moi dong vua log vua ghi ra logs/slope_test_<gio>_tong.txt: terminal con in
// log khac sau do (node chay tiep khi dung han) va bang troi mat.
std::FILE* tong = nullptr;
std::string tong_path;
if (!slope_csv_path_.empty()) {
tong_path = slope_csv_path_.substr(0, slope_csv_path_.size() - 4) + "_tong.txt";
tong = std::fopen(tong_path.c_str(), "w");
}
auto out = [&](const std::string& line) {
VSLAM_INFO("slope_test: " << line);
if (tong != nullptr) std::fprintf(tong, "%s\n", line.c_str());
};
if (slope_samples_.empty()) {
out(std::string("khong co mau do nao (") + SlopeTestPhaseName(end) + ").");
if (tong != nullptr) std::fclose(tong);
return;
}
// "trung vi / 95% / lon nhat" cua |x|.
auto stats = [](std::vector<double> v) {
for (double& x : v) x = std::fabs(x);
std::sort(v.begin(), v.end());
char buf[64];
if (v.empty()) return std::string("--");
const double med = v[v.size() / 2];
const double p95 = v[std::min(v.size() - 1, static_cast<size_t>(0.95 * (v.size() - 1) + 0.5))];
std::snprintf(buf, sizeof(buf), "%5.1f /%5.1f /%5.1f", med, p95, v.back());
return std::string(buf);
};
out("===== BANG TONG (" + std::string(SlopeTestPhaseName(end)) + ", " +
std::to_string(slope_samples_.size()) + " lan do, 2 Hz) =====");
out(" luot chieu v m/s n | lech cm tv / 95% / max | goc do tv / 95% / max"
" | z sai cm tv / 95% / max | khop tb");
int max_loop = 0;
for (const SlopeSample& s : slope_samples_) max_loop = std::max(max_loop, s.loop);
std::vector<double> first_err, last_err;
for (int l = 1; l <= max_loop; ++l) {
for (const bool dn : {true, false}) {
std::vector<double> e, a, z;
double sc = 0.0, v = 0.0;
for (const SlopeSample& s : slope_samples_) {
if (s.loop != l || s.down != dn) continue;
e.push_back(s.err_cm);
a.push_back(s.dth_deg);
if (s.have_z) z.push_back(s.zerr_cm);
sc += s.score;
v = s.speed;
}
if (e.empty()) continue;
if (l == 1) first_err.insert(first_err.end(), e.begin(), e.end());
if (l == max_loop) last_err.insert(last_err.end(), e.begin(), e.end());
char head[64];
std::snprintf(head, sizeof(head), "%4d %-5s %.2f %3zu", l, dn ? "xuong" : "len", v, e.size());
char sc_buf[16];
std::snprintf(sc_buf, sizeof(sc_buf), "%.3f", sc / e.size());
out(std::string(head) + " | " + stats(e) + " | " + stats(a) + " | " + stats(z) + " | " +
sc_buf);
}
}
std::vector<double> all_e, all_a, all_z;
for (const SlopeSample& s : slope_samples_) {
all_e.push_back(s.err_cm);
all_a.push_back(s.dth_deg);
if (s.have_z) all_z.push_back(s.zerr_cm);
}
out(" TONG | " + stats(all_e) + " | " + stats(all_a) + " | " + stats(all_z) + " |");
if (max_loop > 1) {
out("xu huong lech (trung vi) luot 1 -> luot " + std::to_string(max_loop) + ": " +
stats(first_err).substr(0, 5) + " -> " + stats(last_err).substr(0, 5) +
" cm (tang deu = ban do / dinh vi troi dan)");
}
if (!slope_csv_path_.empty()) out("CSV: " + slope_csv_path_);
if (tong != nullptr) {
std::fclose(tong);
VSLAM_INFO("slope_test: bang tong da ghi ra " << tong_path);
}
}
#endif
} // namespace vslam

View File

@@ -28,6 +28,7 @@
#include <atomic>
#include <chrono>
#include <cstdio>
#include <deque>
#include <functional>
#include <memory>
@@ -57,6 +58,7 @@
#include "vslam/global_localizer.h"
#include "vslam/rtabmap_slam.h"
#include "vslam/visual_verifier.h"
#include "vslam/slope_test.h"
#include "vslam/voxel_export.h"
#include "vslam/vpr_encoder.h"
#endif
@@ -119,6 +121,14 @@ struct RuntimeOptions {
// roi chay bang LiDAR nhu cu.
bool slam_reloc_vpr = false;
std::string vpr_engine; // rong = $VSLAM_RESOURCE_DIR/vpr/eigenplaces_r50_fp16.plan
// --slope-test: test doc tu dong sau khi dinh vi lai (can --slam-reloc). Robot tu
// tim huong doc tren ban do, quay mat xuong, cho nut Y (sim: tu chay), roi xuong /
// len `slope_test_loops` luot, moi luot mot van toc. Xem vslam/slope_test.h.
bool slope_test = false;
int slope_test_loops = 10;
std::vector<double> slope_test_speeds; // rong = mac dinh SlopeTestConfig
// `--slope-test-speeds A:B`: chia DEU tu A toi B cho so luot (vmax > 0 = dung).
double slope_test_vmin = 0.0, slope_test_vmax = 0.0;
};
class Runtime {
@@ -206,6 +216,13 @@ class Runtime {
// node anh. true = da CHOT (da vao RelocBeginSettle).
bool RelocCamera(const LaserScan& scan, const Pose2D& odom,
std::chrono::steady_clock::time_point now);
// Test doc tu dong (--slope-test). Luong slam: lap duong sau khi chot, do 2 Hz
// (lech dinh vi theo do khop scan-ban do, z), ghi CSV, bang tong khi xong.
void SlopeTestSlamStep(const SlamOutput& out, const LaserScan& scan);
void SlopeTestSummary(SlopeTestPhase end);
// Luong RIENG 20 Hz: lai. Vong slam khung 100-600 ms moi lan RTAB-Map xu ly --
// lenh tu do se cu qua cmd_timeout cua FSM va xe giat cuc.
void SlopeLoop();
#endif
void ApplyThreadPriority(std::thread* t, int prio, const char* name);
@@ -472,6 +489,32 @@ class Runtime {
UnixTime reloc_cam_last_stamp_;
int reloc_cam_shots_ = 0; // anh da thu trong vong gom nay
int reloc_cam_best_inl_ = 0; // inlier PnP tot nhat vong nay
// ---- Test doc tu dong (--slope-test) ----
std::mutex slope_mu_; // slope_test_ + slope_planned_
std::unique_ptr<SlopeTest> slope_test_; // null = khong bat
bool slope_planned_ = false;
std::atomic<int> slope_button_{0}; // so lan bam Y (luong tay cam ghi)
std::atomic<bool> slope_lost_{false}; // luong slam bao: mat dinh vi
std::thread slope_thread_;
// CHI luong slam.
bool slope_plan_failed_ = false;
std::chrono::steady_clock::time_point slope_meas_at_;
int slope_low_ = 0; // so lan do lien tiep scan khop kem
std::FILE* slope_csv_ = nullptr;
std::string slope_csv_path_;
std::chrono::steady_clock::time_point slope_t0_;
struct SlopeSample {
int loop;
bool down;
double speed;
bool moving;
double err_cm, dth_deg, score;
bool have_z;
double zerr_cm;
};
std::vector<SlopeSample> slope_samples_;
bool slope_summary_done_ = false;
#endif
// Doc-only sau Start(), nen khong can mutex.

View File

@@ -161,6 +161,7 @@ gamepad:
button_zero: 1 # B -- ve 0 ngay
button_turbo: 5 # RB
button_slow: 4 # LB
button_test: 3 # Y -- test doc tu dong (--slope-test): bat dau / chay tiep
# ⚠️ BAT CA HAI -- DO TREN CHINH CON ROBOT NAY.
#

View File

@@ -100,6 +100,9 @@ struct GamepadConfig {
int button_zero = 1; // B -- ve 0 ngay
int button_turbo = 5; // RB
int button_slow = 4; // LB
// Y -- test doc tu dong (--slope-test): bat dau / chay tiep sau tam dung.
// Bat ke dang bat dieu khien hay khong.
int button_test = 3;
// Duong thoat khi bo tay cam nguoc chieu. Doi mot dong YAML thay vi sua code
// roi build lai -- chieu truc chi kiem duoc bang cach cam tay cam vao robot
@@ -191,6 +194,9 @@ struct GamepadCommand {
// Chuyen trang thai, chi de LOG. Mapper khong tu log: no thuan.
bool enabled_changed = false;
bool connected_changed = false;
// Vua BAM nut test (canh len) -- runtime dem so lan bam.
bool test_pressed = false;
};
// Tho -> van toc. THUAN: khong doc dong ho, khong doc file, khong log.
@@ -215,6 +221,7 @@ class GamepadMapper {
bool enable_pressed_ = false; // chong dap phim, = start_pressed_ ben kia
bool was_connected_ = false;
bool have_active_ = false; // da tung co lenh chuyen dong
bool test_prev_ = false; // nut test vong truoc (bat canh len)
UnixTime last_active_;
};

View File

@@ -91,6 +91,7 @@ GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
enabled_ = false;
enable_pressed_ = false;
was_connected_ = false;
test_prev_ = false;
}
out.enabled = false;
// Van gui 0 trong cua so idle: rut day giua luc dang chay thi lenh cuoi
@@ -108,6 +109,12 @@ GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
out.connected_changed = true;
}
// --- Nut test (Y): canh len, BAT KE dang bat dieu khien hay khong ---------
// Dat TRUOC moi nhanh `return` ben duoi (nut B, coc LT, chua bat).
const bool test_now = s.Button(cfg_.button_test);
out.test_pressed = test_now && !test_prev_;
test_prev_ = test_now;
// --- Nut Start: BAT/TAT dieu khien --------------------------------------
// joy_control_node.cpp:180-194. Chong dap phim bang co canh len.
if (s.Button(cfg_.button_enable)) {

View File

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

View File

@@ -0,0 +1,159 @@
#ifndef VSLAM_SLOPE_TEST_H
#define VSLAM_SLOPE_TEST_H
// Test DOC tu dong (08/10): dat robot o DINH doc, dinh vi lai xong robot tu tim
// huong doc tren ban do, quay mat xuong, roi XUONG / LEN nhieu luot -- moi luot
// MOT van toc -- de do sai so dinh vi (va z) theo van toc va theo thoi gian.
//
// Chi la LOGIC: lap duong thu tu ban do (PlanSlopePath) va may trang thai lai
// (SlopeTest). Khong cham phan cung: runtime dua pose / co / nut vao, lay lenh
// (v, w) ra va dua qua DUNG duong FSM an toan nhu moi lenh khac (tay cam, web,
// dinh vi lai tu dong).
//
// A (cho robot dung) ──XUONG, v_k──> B (chan doc da phang + 0.5 m)
// dung do, quay dau dung do, quay dau
// <──LEN, v_k── x loops luot, v_k = speeds[k]
#include <functional>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
struct SlopePathConfig {
double max_len = 15.0; // m, xa nhat tu A
double step = 0.10; // m, buoc do doc duong
double heading_step_deg = 2.0;
double min_drop = 0.20; // m, san phai xuong it nhat chung nay
double flat_tol = 0.04; // m, "phang lai": z lech z thap nhat < nguong nay ...
double flat_len = 1.0; // m, ... lien tiep chung nay
double past_bottom = 0.5; // m, B = cho bat dau phang + doan nay
double stop_margin = 0.6; // m, B cach o khong trong / khong biet san it nhat
double level_deg = 3.0; // san 'phang': do doc mat san duoi nguong nay
double level_h = 0.25; // m, buoc sai phan do do doc
};
struct SlopePath {
Pose2D a; // x, y; theta = huong A -> B (XUONG doc)
double bx = 0.0, by = 0.0;
double length = 0.0; // m
double drop = 0.0; // m, z(A) - z(B) > 0
};
// floor(x, y, &z): do cao san trong ban do; false = khong biet san o do.
// free(x, y): o TRONG va du cho than robot (nguoi goi da tinh lan).
using FloorFn = std::function<bool(double, double, double*)>;
using FreeFn = std::function<bool(double, double)>;
// Thu moi huong quanh (x, y): di thang tren ban do, buoc `step`, toi khi gap o
// khong trong hoac khong biet san. Huong hop le: san XUONG >= min_drop roi PHANG
// lai >= flat_len truoc khi het duong. Chon huong xuong het doc NGAN NHAT -- tuc
// la doc theo truc doc, khong xien. false + `why` neu khong co huong nao.
//
// A = DINH doc phang (robot dang giua doc thi di nguoc len theo truc toi cho
// phang), B = CHAN doc phang + past_bottom. `diag` (tuy chon): moi huong da
// thu, "huong:duong trong:dung vi:ket qua" -- de doc khi khong ra duong.
bool PlanSlopePath(double x, double y, const FloorFn& floor, const FreeFn& free,
const SlopePathConfig& cfg, SlopePath* out, std::string* why,
std::string* diag = nullptr);
struct SlopeTestConfig {
int loops = 10;
// Van toc MOI LUOT (xuong + len cung mot van toc), tang dan: luot dau cham,
// an toan nhat. Het danh sach thi quay vong.
std::vector<double> speeds = {0.10, 0.14, 0.18, 0.22, 0.26, 0.30, 0.34, 0.38, 0.42, 0.46};
double dwell_s = 3.0; // dung o moi dau de do
double turn_rate = 0.5; // rad/s, quay tai cho toi da
double turn_min = 0.15; // rad/s, toi thieu (vuot vung chet cua base)
double turn_tol_deg = 3.0;
double arrive_tol = 0.10; // m
double slow_zone = 0.8; // m, giam toc truoc dich
double min_speed = 0.06; // m/s
double k_heading = 1.5; // w = k * loi huong
double k_cross = 1.0; // huong dich = huong duong - atan(k * lech ngang)
double max_w = 0.6; // rad/s khi dang chay
double drive_turn_deg = 25.0; // loi huong lon hon -> dung lai quay truoc
double cross_max = 0.40; // m, lech khoi duong -> DUNG HAN
double jump_max = 0.30; // m giua hai buoc, pose nhay -> DUNG HAN
double tilt_max_deg = 20.0; // nghieng hon -> DUNG HAN
double leg_timeout_extra = 20.0; // s, cong vao 2 * L / v
// Robot khong o A (dinh vi lai tu chay ra giua doc): chay CHAM ve A truoc.
double approach_speed = 0.15; // m/s
};
enum class SlopeTestPhase {
kIdle, // chua co duong
kFace, // quay mat xuong doc (truoc khi cho nut)
kWaitStart, // da quay mat, cho nguoi bam bat dau
kTurn, // quay theo huong luot dang chay
kDrive, // dang chay tren duong
kDwell, // dung o mot dau de do
kPaused, // nguoi vua lai -- im, cho bam tiep tuc
kHalted, // vi pham an toan -- dung han
kDone, // xong moi luot
};
const char* SlopeTestPhaseName(SlopeTestPhase p);
struct SlopeTestInput {
double t = 0.0; // s, dong ho don dieu
Pose2D pose; // pose MAP
bool localized = false; // false = mat dinh vi / scan khong khop ban do
double roll = 0.0, pitch = 0.0; // rad, nghieng than
bool human = false; // nguon khac (tay cam, web) vua ra lenh
bool start = false; // vua bam nut bat dau / chay tiep
};
struct SlopeTestOutput {
bool command = false; // ghi lenh khong; false = im, nhuong nguon khac
double v = 0.0, w = 0.0;
std::string event; // dong log moi; rong = khong co gi moi
};
class SlopeTest {
public:
explicit SlopeTest(SlopeTestConfig cfg = SlopeTestConfig());
// Dat duong; vao kFace. autostart: quay mat xong thi chay luon (mo phong --
// khong co tay cam), khong thi cho `start`.
void SetPath(const SlopePath& p, bool autostart);
SlopeTestOutput Step(const SlopeTestInput& in);
SlopeTestPhase phase() const { return phase_; }
const SlopePath& path() const { return path_; }
int loops() const { return cfg_.loops; }
int loop() const { return loop_; } // 1-based; 0 = chua chay
bool down() const { return down_; } // luot hien tai dang XUONG
double speed() const; // van toc luot hien tai
bool approaching() const { return approach_; } // dang ve A (khong phai luot do)
double along() const { return along_; } // m, da di tu dau luot
double cross() const { return cross_; } // m, lech ngang (+ = ben trai)
const std::string& halt_reason() const { return halt_; }
private:
void BeginLeg(double t);
SlopeTestOutput Halt(const std::string& why);
bool Unsafe(const SlopeTestInput& in, std::string* why) const;
SlopeTestConfig cfg_;
SlopePath path_;
SlopeTestPhase phase_ = SlopeTestPhase::kIdle;
SlopeTestPhase paused_from_ = SlopeTestPhase::kIdle;
bool autostart_ = false;
bool approach_ = false; // dang chay ve A
bool approached_ = false; // da kiem can ve A chua
int loop_ = 0;
bool down_ = true;
double from_x_ = 0.0, from_y_ = 0.0, to_x_ = 0.0, to_y_ = 0.0, heading_ = 0.0, len_ = 0.0;
double leg_t0_ = 0.0, dwell_t0_ = 0.0;
double along_ = 0.0, cross_ = 0.0;
bool have_prev_ = false;
Pose2D prev_;
std::string halt_;
};
} // namespace vslam
#endif // VSLAM_SLOPE_TEST_H

View File

@@ -0,0 +1,480 @@
#include "vslam/slope_test.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include "vslam/geometry.h"
namespace vslam {
const char* SlopeTestPhaseName(SlopeTestPhase p) {
switch (p) {
case SlopeTestPhase::kIdle: return "chua co duong";
case SlopeTestPhase::kFace: return "quay mat xuong doc";
case SlopeTestPhase::kWaitStart: return "cho bam bat dau";
case SlopeTestPhase::kTurn: return "quay theo luot";
case SlopeTestPhase::kDrive: return "dang chay";
case SlopeTestPhase::kDwell: return "dung do";
case SlopeTestPhase::kPaused: return "tam dung";
case SlopeTestPhase::kHalted: return "dung han";
case SlopeTestPhase::kDone: return "xong";
}
return "?";
}
// ---------------------------------------------------------------------------
// Lap duong
// ---------------------------------------------------------------------------
bool PlanSlopePath(double x, double y, const FloorFn& floor, const FreeFn& free,
const SlopePathConfig& cfg, SlopePath* out, std::string* why,
std::string* diag) {
double z0 = 0.0;
if (!floor(x, y, &z0)) {
*why = "khong biet do cao san cho robot dung (ban do khong co z node? slope.enabled?)";
return false;
}
// San PHANG tai (px, py): do doc bang sai phan +-level_h theo x va y. Chi nhin
// z doc theo tia la khong du: di CHEO tren doc 10 do thi z doi cham, trong
// nhu phang (sim 08/10: chon duong ngang doc, xuong 0.2 m).
const double level_tan = std::tan(cfg.level_deg * M_PI / 180.0);
auto level = [&](double px, double py) {
double zx0 = 0.0, zx1 = 0.0, zy0 = 0.0, zy1 = 0.0;
const double h = cfg.level_h;
if (!floor(px - h, py, &zx0) || !floor(px + h, py, &zx1) || !floor(px, py - h, &zy0) ||
!floor(px, py + h, &zy1)) {
return false;
}
return std::hypot(zx1 - zx0, zy1 - zy0) / (2.0 * h) < level_tan;
};
struct Cand {
double th, len, drop;
};
std::vector<Cand> ok;
std::ostringstream fan;
double best_drop_seen = 0.0;
const int nh = std::max(8, static_cast<int>(std::lround(360.0 / cfg.heading_step_deg)));
for (int k = 0; k < nh; ++k) {
const double th = NormalizeAngle(2.0 * M_PI * k / nh);
const double c = std::cos(th), s = std::sin(th);
std::vector<double> ss, zs;
const char* stop = "max";
for (double d = cfg.step; d <= cfg.max_len + 1e-9; d += cfg.step) {
const double px = x + c * d, py = y + s * d;
if (!free(px, py)) {
stop = "vc";
break;
}
double z = 0.0;
if (!floor(px, py, &z)) {
stop = "ks";
break;
}
ss.push_back(d);
zs.push_back(z);
}
if (ss.empty()) continue;
const double s_end = ss.back();
double drop_here = 0.0;
for (const double z : zs) drop_here = std::max(drop_here, z0 - z);
best_drop_seen = std::max(best_drop_seen, drop_here);
if (drop_here < cfg.min_drop) continue;
// Chan doc: diem DAU TIEN da xuong >= min_drop ma flat_len tiep theo PHANG.
const char* res = "khong phang";
for (size_t i = 0; i < ss.size(); ++i) {
if (z0 - zs[i] < cfg.min_drop) continue;
if (ss[i] + cfg.flat_len > s_end) {
res = "het duong";
break;
}
bool flat = true;
for (size_t j = i; j < ss.size() && ss[j] <= ss[i] + cfg.flat_len + 1e-9; ++j) {
if (!level(x + c * ss[j], y + s * ss[j])) {
flat = false;
break;
}
}
if (!flat) continue;
const double len = ss[i] + cfg.past_bottom;
if (len > s_end - cfg.stop_margin) {
res = "B sat vat can";
break;
}
double zb = zs[i];
floor(x + c * len, y + s * len, &zb);
ok.push_back(Cand{th, len, z0 - zb});
res = "OK";
break;
}
fan << " " << std::lround(th * 180.0 / M_PI) << "d:" << s_end << "m:" << stop << ":" << res;
}
if (diag != nullptr) *diag = fan.str();
if (ok.empty()) {
std::ostringstream os;
os << "khong thay doc tu cho robot dung (xuong toi da " << best_drop_seen << " m, can >= "
<< cfg.min_drop << " m roi PHANG " << cfg.flat_len << " m truoc vat can) -- dat robot gan "
<< "dinh doc hon. Huong:duong trong:dung vi (vc vat can, ks khong biet san):ket qua --"
<< fan.str();
*why = os.str();
return false;
}
// Uu tien xuong HET doc (>= 80% do sut lon nhat) -- loai duong cheo / ngang chi
// cat qua mep doc; roi NGAN NHAT = truc doc. Doc rong: mot dai huong gan truc
// ngan bang nhau (luong tu 10 cm) -- lay huong GIUA cua dai do.
double max_drop = 0.0;
for (const Cand& c : ok) max_drop = std::max(max_drop, c.drop);
double min_len = 1e9;
for (const Cand& c : ok) {
if (c.drop >= 0.8 * max_drop) min_len = std::min(min_len, c.len);
}
double sx = 0.0, sy = 0.0;
for (const Cand& c : ok) {
if (c.drop < 0.8 * max_drop || c.len > min_len + 0.05) continue;
sx += std::cos(c.th);
sy += std::sin(c.th);
}
const double th = std::atan2(sy, sx);
const double ux = std::cos(th), uy = std::sin(th);
// Day doc B: di lai theo HUONG DA CHON (huong trung binh co the lech vai do).
double b_len = -1.0;
{
std::vector<double> ss, zs;
for (double d = cfg.step; d <= cfg.max_len + 1e-9; d += cfg.step) {
double z = 0.0;
if (!free(x + ux * d, y + uy * d) || !floor(x + ux * d, y + uy * d, &z)) break;
ss.push_back(d);
zs.push_back(z);
}
for (size_t i = 0; i < ss.size() && b_len < 0.0; ++i) {
if (z0 - zs[i] < cfg.min_drop || ss[i] + cfg.flat_len > ss.back()) continue;
bool flat = true;
for (size_t j = i; j < ss.size() && ss[j] <= ss[i] + cfg.flat_len + 1e-9; ++j) {
if (!level(x + ux * ss[j], y + uy * ss[j])) {
flat = false;
break;
}
}
if (flat && ss[i] + cfg.past_bottom <= ss.back() - cfg.stop_margin) {
b_len = ss[i] + cfg.past_bottom;
}
}
}
if (b_len < 0.0) {
*why = "huong trung binh cua truc doc khong toi duoc chan doc phang -- dat robot thang truc doc hon";
return false;
}
// Dinh doc A: robot co the DANG o giua doc (dinh vi lai tu chay toi 1 m moi
// lan, sim 08/10: 3.5 m). Di NGUOC len theo truc toi cho phang flat_len, roi
// them past_bottom. Robot da o cho phang thi A = cho robot.
double a_back = 0.0;
bool at_top = true;
for (double d = 0.0; d <= cfg.flat_len + 1e-9; d += cfg.step) {
if (!level(x - ux * d, y - uy * d)) {
at_top = false;
break;
}
}
if (!at_top) {
bool found = false;
for (double d = cfg.step; d <= cfg.max_len + 1e-9 && !found; d += cfg.step) {
if (!free(x - ux * d, y - uy * d)) break;
bool flat = true;
for (double e = d; e <= d + cfg.flat_len + 1e-9; e += cfg.step) {
if (!level(x - ux * e, y - uy * e)) {
flat = false;
break;
}
}
if (flat) {
a_back = d + cfg.past_bottom;
found = true;
}
}
if (!found) {
*why = "dang o giua doc ma khong tim thay dinh doc phang phia tren -- dat robot o dinh doc";
return false;
}
for (double d = cfg.step; d <= a_back + 1e-9; d += cfg.step) {
if (!free(x - ux * d, y - uy * d)) {
*why = "duong len dinh doc vuong vat can -- dat robot o dinh doc";
return false;
}
}
}
out->a = Pose2D{x - ux * a_back, y - uy * a_back, th};
out->bx = x + ux * b_len;
out->by = y + uy * b_len;
out->length = a_back + b_len;
double za = z0, zb = z0;
floor(out->a.x, out->a.y, &za);
floor(out->bx, out->by, &zb);
out->drop = za - zb;
return true;
}
// ---------------------------------------------------------------------------
// May trang thai
// ---------------------------------------------------------------------------
SlopeTest::SlopeTest(SlopeTestConfig cfg) : cfg_(std::move(cfg)) {
if (cfg_.speeds.empty()) cfg_.speeds.push_back(0.2);
if (cfg_.loops < 1) cfg_.loops = 1;
}
void SlopeTest::SetPath(const SlopePath& p, bool autostart) {
path_ = p;
autostart_ = autostart;
phase_ = SlopeTestPhase::kFace;
loop_ = 0;
down_ = true;
have_prev_ = false;
approach_ = false;
approached_ = false;
leg_t0_ = 0.0;
halt_.clear();
}
double SlopeTest::speed() const {
if (approach_) return cfg_.approach_speed;
const size_t i = loop_ > 0 ? static_cast<size_t>(loop_ - 1) % cfg_.speeds.size() : 0;
return cfg_.speeds[i];
}
void SlopeTest::BeginLeg(double t) {
if (down_) {
from_x_ = path_.a.x;
from_y_ = path_.a.y;
to_x_ = path_.bx;
to_y_ = path_.by;
} else {
from_x_ = path_.bx;
from_y_ = path_.by;
to_x_ = path_.a.x;
to_y_ = path_.a.y;
}
heading_ = std::atan2(to_y_ - from_y_, to_x_ - from_x_);
len_ = std::hypot(to_x_ - from_x_, to_y_ - from_y_);
along_ = 0.0;
cross_ = 0.0;
phase_ = SlopeTestPhase::kTurn;
leg_t0_ = t;
}
SlopeTestOutput SlopeTest::Halt(const std::string& why) {
phase_ = SlopeTestPhase::kHalted;
halt_ = why;
SlopeTestOutput o;
o.command = true; // MOT lenh dung, roi im
o.event = "DUNG HAN -- " + why;
return o;
}
bool SlopeTest::Unsafe(const SlopeTestInput& in, std::string* why) const {
if (!in.localized) {
*why = "mat dinh vi / scan khong khop ban do";
return true;
}
const double tilt = cfg_.tilt_max_deg * M_PI / 180.0;
if (std::fabs(in.roll) > tilt || std::fabs(in.pitch) > tilt) {
std::ostringstream os;
os << "nghieng qua " << cfg_.tilt_max_deg << " do (roll " << in.roll * 180.0 / M_PI
<< ", pitch " << in.pitch * 180.0 / M_PI << ")";
*why = os.str();
return true;
}
if (have_prev_) {
const double j = std::hypot(in.pose.x - prev_.x, in.pose.y - prev_.y);
if (j > cfg_.jump_max) {
std::ostringstream os;
os << "pose nhay " << j << " m trong mot buoc (dinh vi sai?)";
*why = os.str();
return true;
}
}
return false;
}
SlopeTestOutput SlopeTest::Step(const SlopeTestInput& in) {
SlopeTestOutput o;
const double tol = cfg_.turn_tol_deg * M_PI / 180.0;
auto turn = [&](double err) {
double w = std::max(-cfg_.turn_rate, std::min(cfg_.turn_rate, cfg_.k_heading * err));
if (std::fabs(w) < cfg_.turn_min) w = std::copysign(cfg_.turn_min, err);
return w;
};
auto leg_name = [&]() {
std::ostringstream os;
if (approach_) {
os << "ve dinh doc (A) " << speed() << " m/s";
return os.str();
}
os << "luot " << loop_ << "/" << cfg_.loops << " " << (down_ ? "XUONG" : "LEN") << " "
<< speed() << " m/s";
return os.str();
};
switch (phase_) {
case SlopeTestPhase::kIdle:
case SlopeTestPhase::kHalted:
case SlopeTestPhase::kDone:
return o; // im
case SlopeTestPhase::kPaused:
if (in.start) {
// Chay tiep: dang chay / quay thi quay lai theo huong luot roi chay tiep.
phase_ = paused_from_ == SlopeTestPhase::kDrive ? SlopeTestPhase::kTurn : paused_from_;
if (phase_ == SlopeTestPhase::kDwell) dwell_t0_ = in.t;
leg_t0_ = in.t;
have_prev_ = false;
o.event = "chay tiep (" + std::string(SlopeTestPhaseName(phase_)) + ").";
}
return o;
case SlopeTestPhase::kWaitStart:
if (in.start) {
loop_ = 1;
down_ = true;
BeginLeg(in.t);
have_prev_ = false;
o.event = "BAT DAU " + leg_name();
}
return o;
default:
break;
}
// Cac pha DANG ra lenh: nguoi lai thi nhuong ngay, im cho toi khi bam tiep.
if (in.human) {
paused_from_ = phase_;
phase_ = SlopeTestPhase::kPaused;
o.event = "nguoi dang lai -- TAM DUNG. Bam Y de chay tiep.";
return o;
}
std::string why;
if (Unsafe(in, &why)) return Halt(why);
prev_ = in.pose;
have_prev_ = true;
o.command = true; // tu day: luon ghi lenh (ke ca 0 = giu dung)
switch (phase_) {
case SlopeTestPhase::kFace: {
// Lan dau: robot khong o A (dinh vi lai tu chay ra giua doc) -> ve A truoc.
if (!approached_) {
approached_ = true;
const double d = std::hypot(path_.a.x - in.pose.x, path_.a.y - in.pose.y);
if (d > 1.5 * cfg_.arrive_tol) {
approach_ = true;
from_x_ = in.pose.x;
from_y_ = in.pose.y;
to_x_ = path_.a.x;
to_y_ = path_.a.y;
heading_ = std::atan2(to_y_ - from_y_, to_x_ - from_x_);
len_ = d;
along_ = cross_ = 0.0;
phase_ = SlopeTestPhase::kTurn;
leg_t0_ = in.t;
std::ostringstream os;
os << "robot cach dinh doc (A) " << d << " m -- chay CHAM ve A truoc.";
o.event = os.str();
return o;
}
}
const double err = NormalizeAngle(path_.a.theta - in.pose.theta);
if (std::fabs(err) < tol) {
std::ostringstream os;
os << "da quay mat xuong doc (xuong " << path_.drop << " m, dai " << path_.length << " m). ";
if (autostart_) {
loop_ = 1;
down_ = true;
BeginLeg(in.t);
os << "Tu chay (mo phong): " << leg_name();
} else {
phase_ = SlopeTestPhase::kWaitStart;
os << "Bam Y de chay " << cfg_.loops << " luot.";
}
o.event = os.str();
return o;
}
if (in.t - leg_t0_ > 30.0 && leg_t0_ > 0.0) return Halt("quay mat xuong doc qua 30 s");
if (leg_t0_ <= 0.0) leg_t0_ = in.t;
o.w = turn(err);
return o;
}
case SlopeTestPhase::kTurn: {
const double err = NormalizeAngle(heading_ - in.pose.theta);
if (std::fabs(err) < tol) {
phase_ = SlopeTestPhase::kDrive;
leg_t0_ = in.t;
return o;
}
if (in.t - leg_t0_ > 30.0) return Halt("quay dau qua 30 s (vat can chan quay?)");
o.w = turn(err);
return o;
}
case SlopeTestPhase::kDrive: {
const double ux = std::cos(heading_), uy = std::sin(heading_);
const double rx = in.pose.x - from_x_, ry = in.pose.y - from_y_;
along_ = rx * ux + ry * uy;
cross_ = ux * ry - uy * rx;
if (std::fabs(cross_) > cfg_.cross_max) {
std::ostringstream os;
os << "lech khoi duong " << cross_ << " m (" << leg_name() << ")";
return Halt(os.str());
}
const double timeout = 2.0 * len_ / std::max(speed(), 0.05) + cfg_.leg_timeout_extra;
if (in.t - leg_t0_ > timeout) {
std::ostringstream os;
os << "qua " << timeout << " s ma chua toi dau doc (" << leg_name() << ")";
return Halt(os.str());
}
const double d = len_ - along_;
if (d <= cfg_.arrive_tol && approach_) {
approach_ = false;
phase_ = SlopeTestPhase::kFace;
leg_t0_ = in.t;
o.event = "da ve dinh doc (A).";
return o;
}
if (d <= cfg_.arrive_tol) {
phase_ = SlopeTestPhase::kDwell;
dwell_t0_ = in.t;
std::ostringstream os;
os << leg_name() << ": toi " << (down_ ? "CHAN" : "DINH") << " doc sau " << in.t - leg_t0_
<< " s, lech ngang " << cross_ * 100.0 << " cm";
o.event = os.str();
return o;
}
const double psi_d = heading_ - std::atan(cfg_.k_cross * cross_);
const double err = NormalizeAngle(psi_d - in.pose.theta);
o.w = std::max(-cfg_.max_w, std::min(cfg_.max_w, cfg_.k_heading * err));
if (std::fabs(err) < cfg_.drive_turn_deg * M_PI / 180.0) {
o.v = std::max(cfg_.min_speed, speed() * std::min(1.0, d / cfg_.slow_zone));
}
return o;
}
case SlopeTestPhase::kDwell: {
if (in.t - dwell_t0_ < cfg_.dwell_s) return o; // dung yen
if (down_) {
down_ = false;
} else if (loop_ >= cfg_.loops) {
phase_ = SlopeTestPhase::kDone;
std::ostringstream os;
os << "XONG " << cfg_.loops << " luot.";
o.event = os.str();
return o;
} else {
++loop_;
down_ = true;
}
BeginLeg(in.t);
o.event = "bat dau " + leg_name();
return o;
}
default:
return o;
}
}
} // namespace vslam

View File

@@ -111,6 +111,7 @@ 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_slope_test LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif()

260
test/test_slope_test.cc Normal file
View File

@@ -0,0 +1,260 @@
// Test doc tu dong (08/10): lap duong tu ban do + may trang thai lai.
// Robot gia lap: mo hinh xe hai banh, tich phan lenh (v, w) cua chinh SlopeTest.
#include <gtest/gtest.h>
#include <cmath>
#include <string>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/slope_test.h"
using namespace vslam;
namespace {
// Doc gia doc truc x: tang tren z 1.2 (x < 2), doc xuong toi z 0 o x = 8, san
// duoi phang. Nha |y| < 3, x trong (-1, 11); tinh lan 0.3 m cho than robot.
bool Floor(double x, double y, double* z) {
if (x < -1.0 || x > 11.0 || std::fabs(y) > 3.0) return false;
if (x < 2.0) *z = 1.2;
else if (x < 8.0) *z = 1.2 * (8.0 - x) / 6.0;
else *z = 0.0;
return true;
}
bool Free(double x, double y) { return x > -0.7 && x < 10.7 && std::fabs(y) < 2.7; }
struct Sim {
SlopeTest t;
Pose2D p;
double now = 1.0;
std::vector<std::string> events;
double vmax_leg = 0.0;
explicit Sim(SlopeTestConfig c) : t(std::move(c)) {}
// Mot buoc 50 ms. Tra output de test kiem tra.
SlopeTestOutput Step(bool start = false, bool human = false, bool localized = true) {
SlopeTestInput in;
in.t = now;
in.pose = p;
in.localized = localized;
in.start = start;
in.human = human;
const SlopeTestOutput o = t.Step(in);
if (!o.event.empty()) events.push_back(o.event);
if (o.command) {
const double dt = 0.05;
p.theta = NormalizeAngle(p.theta + o.w * dt);
p.x += o.v * std::cos(p.theta) * dt;
p.y += o.v * std::sin(p.theta) * dt;
vmax_leg = std::max(vmax_leg, o.v);
}
now += 0.05;
return o;
}
// Chay toi khi gap pha `ph` (hoac het so buoc).
bool RunUntil(SlopeTestPhase ph, int max_steps = 20000) {
for (int i = 0; i < max_steps; ++i) {
if (t.phase() == ph) return true;
Step();
}
return t.phase() == ph;
}
};
SlopeTestConfig Cfg() {
SlopeTestConfig c;
c.loops = 3;
c.speeds = {0.10, 0.30, 0.45};
c.dwell_s = 1.0;
return c;
}
bool Has(const std::vector<std::string>& ev, const std::string& s) {
for (const auto& e : ev) {
if (e.find(s) != std::string::npos) return true;
}
return false;
}
} // namespace
TEST(PlanSlopePath, TimDungTrucDocVaChanDoc) {
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.a.theta, 0.0, 3.0 * M_PI / 180.0); // xuong doc theo +x
EXPECT_NEAR(p.drop, 1.2, 0.05);
// Chan doc: mat san PHANG (do doc < 3 do, sai phan +-0.25 m) tu x = 8.25, + 0.5 m.
EXPECT_NEAR(p.bx, 8.75, 0.2);
EXPECT_NEAR(p.by, 0.2, 0.2);
// Robot da o dinh phang: A = cho robot.
EXPECT_NEAR(p.a.x, 0.5, 1e-9);
}
TEST(PlanSlopePath, GiuaDocThiADatODinhDoc) {
// Dinh vi lai tu chay ra GIUA doc (sim 08/10: 3.5 m). A phai la DINH phang,
// KHONG phai cho robot dung.
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(4.0, 0.2, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.a.theta, 0.0, 3.0 * M_PI / 180.0);
EXPECT_NEAR(p.a.x, 1.25, 0.15); // phang tu x = 1.75 (+-0.25) lui 1 m, + 0.5 m
EXPECT_NEAR(p.bx, 8.75, 0.2);
EXPECT_NEAR(p.drop, 1.2, 0.05);
}
TEST(PlanSlopePath, KhongChonDuongCheoNgangDoc) {
// Doc rong (|y| < 3) dung SAT tuong y = 2.5: huong cheo cat qua doc ngan hon
// nhung khong xuong het -- phai chon truc doc (xuong 1.2 m).
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(3.0, 2.3, Floor, Free, SlopePathConfig{}, &p, &why)) << why;
EXPECT_NEAR(p.drop, 1.2, 0.05);
EXPECT_NEAR(p.a.theta, 0.0, 6.0 * M_PI / 180.0);
}
TEST(PlanSlopePath, KhongCoDocThiBaoLoi) {
SlopePath p;
std::string why;
// San phang toan bo: khong huong nao xuong.
auto flat = [](double x, double y, double* z) {
*z = 0.0;
return std::fabs(x) < 5.0 && std::fabs(y) < 5.0;
};
auto free = [](double x, double y) { return std::fabs(x) < 4.7 && std::fabs(y) < 4.7; };
EXPECT_FALSE(PlanSlopePath(0.0, 0.0, flat, free, SlopePathConfig{}, &p, &why));
EXPECT_NE(why.find("khong thay doc"), std::string::npos);
}
TEST(SlopeTest, QuayMatXuongDocRoiChoNut) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 2.0}; // dang nhin xien sau reloc
s.t.SetPath(p, false);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 2000));
EXPECT_NEAR(NormalizeAngle(s.p.theta - p.a.theta), 0.0, 4.0 * M_PI / 180.0);
// Cho nut: KHONG ra lenh, robot dung yen.
const Pose2D before = s.p;
for (int i = 0; i < 100; ++i) EXPECT_FALSE(s.Step().command);
EXPECT_DOUBLE_EQ(s.p.x, before.x);
}
TEST(SlopeTest, GiuaDocThiVeDinhTruoc) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(4.0, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{4.0, 0.2, 2.0};
s.t.SetPath(p, false);
s.Step();
EXPECT_TRUE(s.t.approaching());
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 4000));
EXPECT_LT(std::hypot(s.p.x - p.a.x, s.p.y - p.a.y), 0.15);
EXPECT_NEAR(NormalizeAngle(s.p.theta - p.a.theta), 0.0, 4.0 * M_PI / 180.0);
EXPECT_TRUE(Has(s.events, "chay CHAM ve A"));
EXPECT_LE(s.vmax_leg, 0.15 + 1e-9); // ve A cham
}
TEST(SlopeTest, DuLuotDungThuTuVaVanToc) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, false);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kWaitStart, 2000));
s.Step(true); // bam Y
const double speeds[] = {0.10, 0.30, 0.45};
for (int k = 0; k < 3; ++k) {
for (bool down : {true, false}) {
s.vmax_leg = 0.0;
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDwell)) << "luot " << k + 1 << (down ? " xuong" : " len");
EXPECT_EQ(s.t.loop(), k + 1);
EXPECT_EQ(s.t.down(), down);
// Van toc luot nay: dat toi, khong vuot.
EXPECT_NEAR(s.vmax_leg, speeds[k], 1e-9);
// Toi dung dau doc.
const double tx = down ? p.bx : p.a.x, ty = down ? p.by : p.a.y;
EXPECT_LT(std::hypot(s.p.x - tx, s.p.y - ty), 0.15);
// Roi pha dung do.
for (int i = 0; i < 40 && s.t.phase() == SlopeTestPhase::kDwell; ++i) s.Step();
}
}
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDone, 200));
EXPECT_TRUE(Has(s.events, "XONG 3 luot"));
EXPECT_TRUE(Has(s.events, "luot 2/3 XUONG 0.3 m/s"));
EXPECT_TRUE(Has(s.events, "luot 3/3 LEN 0.45 m/s"));
// Xong thi im.
EXPECT_FALSE(s.Step().command);
}
TEST(SlopeTest, NguoiLaiThiTamDungRoiChayTiep) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true); // tu chay
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
for (int i = 0; i < 40; ++i) s.Step();
// Nguoi gat can: tam dung, IM ngay.
EXPECT_FALSE(s.Step(false, true).command);
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kPaused);
for (int i = 0; i < 50; ++i) EXPECT_FALSE(s.Step().command);
// Bam Y: chay tiep toi chan doc.
s.Step(true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDwell));
EXPECT_LT(std::hypot(s.p.x - p.bx, s.p.y - p.by), 0.15);
}
TEST(SlopeTest, LechDuongThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
for (int i = 0; i < 20; ++i) s.Step();
s.p.y += 0.25; // truot ngang (khong nhay qua jump_max)
s.Step();
s.p.y += 0.25;
const SlopeTestOutput o = s.Step();
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_TRUE(o.command); // MOT lenh dung
EXPECT_DOUBLE_EQ(o.v, 0.0);
EXPECT_NE(s.t.halt_reason().find("lech khoi duong"), std::string::npos);
EXPECT_FALSE(s.Step().command); // roi im
}
TEST(SlopeTest, MatDinhViThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
s.Step(false, false, false);
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_NE(s.t.halt_reason().find("mat dinh vi"), std::string::npos);
}
TEST(SlopeTest, PoseNhayThiDungHan) {
Sim s(Cfg());
SlopePath p;
std::string why;
ASSERT_TRUE(PlanSlopePath(0.5, 0.2, Floor, Free, SlopePathConfig{}, &p, &why));
s.p = Pose2D{0.5, 0.2, 0.0};
s.t.SetPath(p, true);
ASSERT_TRUE(s.RunUntil(SlopeTestPhase::kDrive, 2000));
s.Step();
s.p.x += 0.5; // dinh vi nhay 0.5 m
s.Step();
EXPECT_EQ(s.t.phase(), SlopeTestPhase::kHalted);
EXPECT_NE(s.t.halt_reason().find("pose nhay"), std::string::npos);
}

507
tools/gen_world_from_db.py Normal file
View File

@@ -0,0 +1,507 @@
#!/usr/bin/env python3
"""World mo phong tu MOT ban do that (DB RTAB-Map cua vslam_cpp): tuong + mat dat.
De chay lai test doc (--slope-test) tren chinh con doc that khi khong dua duoc
robot ra hien truong. Moi thu lay tu DB:
* mat dat = z do cua tung node (userData, ghi khi slope.enabled), noi suy
Gauss quanh node (SIGMA, xa node thi rong dan) thanh luoi tam giac TRES
phu CA khung ban do -- o sim khong co dia hinh la san z = 0, de ho thi
mep vung da biet thanh mot bac dung;
* tuong = o BI CHIEM cua luoi 2D (log-odds tu luoi cuc bo tung node + pose
toi uu, cung GridGlobal/* voi slam.yaml), dung cao WALL_H tu mat dat. Bo
hai loai tuong GIA:
- tia LiDAR cham MAT DAT: o ma mat dat nho cao hon mat phang duoi robot
(cua node nhin thay o do) qua LIDAR_H - GROUND_TOL -- chan doc nhin tu
duoi, chan doc nhin tu tren khi dang xuong;
- o trong vong ROBOT_R + 5 cm quanh duong robot DA DI (chac chan trong);
* goi y diem dat robot: dinh doan doc lon nhat, theo pose node that.
Frame world = frame ban do, nen sai so so voi ground truth cua sim co nghia.
Sim chay tren BAN SAO cua DB trong thu muc ra (localization co the ghi DB).
Gioi han: anh camera sim khong giong anh that -> dinh vi lai bang LiDAR (KHONG
--slam-reloc-vpr); khong co nguoi / do vat di dong; vat thap duoi tam LiDAR
khong co; mat dat chi dung doc theo duong robot da di (ngang ra thi keo dai).
Chay tu goc repo (in ra lenh sim day du):
python3 tools/gen_world_from_db.py resources/maps/real_YYYYMMDD_HHMMSS.db \\
--preview logs/real_YYYYMMDD_HHMMSS_world.png
"""
import argparse
import math
import os
import re
import shutil
import sqlite3
import struct
import zlib
import numpy as np
import gen_slope_world as base
RES = 0.05 # o luoi 2D, bang Grid/CellSize
TRES = 0.20 # o luoi mat dat
SIGMA = 0.5 # noi suy z: do rong Gauss quanh node gan nhat, m
WALL_H = 2.0 # tuong cao bao nhieu tren mat dat
LIDAR_H = 0.2165 # tam LiDAR tren san: robot.yaml laser_link z 0.13 + wheel_radius 0.0865
GROUND_TOL = 0.08 # dat nho hon mat phang robot >= LIDAR_H - cai nay: tia cham DAT
ROBOT_R = 0.24 # robot.yaml robot_radius
SLOPE_DEG = 3.0 # mat dat doc hon cai nay la doc
PAD = 1.0 # le quanh khung ban do, m
MAX_GAP = 1.0 # hai node lien tiep xa hon (RGBD/LinearUpdate 0.1) = dut duong
def mat(blob):
"""Blob nen cua RTAB-Map: zlib + 12 byte (rows, cols, type) -> (bytes, so kenh)."""
typ = struct.unpack('3i', blob[-12:])[2]
return zlib.decompress(blob[:-12]), (typ >> 3) + 1
def grid_params(root):
"""GridGlobal/* cua slam.yaml (thieu thi mac dinh RTAB-Map)."""
p = {'ProbHit': 0.7, 'ProbMiss': 0.4, 'ProbClampingMin': 0.1192, 'ProbClampingMax': 0.971}
path = os.path.join(root, 'configuration_files', 'slam.yaml')
text = open(path).read() if os.path.exists(path) else ''
for k in p:
m = re.search(r'GridGlobal/%s:\s*"?([0-9.]+)' % k, text)
if m:
p[k] = float(m.group(1))
return p
def logit(p):
return math.log(p / (1.0 - p))
def connect(db):
return sqlite3.connect('file:%s?mode=ro' % db, uri=True).cursor()
def load(db):
"""-> ids tang dan, pose {id: 3x4}, do {id: (z, roll, pitch)}, nguon pose."""
c = connect(db)
row = c.execute('select opt_ids, opt_poses from Admin').fetchone()
if row is not None and row[0] is not None and row[1] is not None:
ids = np.frombuffer(mat(row[0])[0], dtype=np.int32)
P = np.frombuffer(mat(row[1])[0], dtype=np.float32).reshape(-1, 3, 4)
pose = {int(i): P[k].astype(np.float64) for k, i in enumerate(ids)}
src = 'pose toi uu (Admin)'
else:
pose = {int(i): np.frombuffer(b, dtype=np.float32).reshape(3, 4).astype(np.float64)
for i, b in c.execute('select id, pose from Node where pose is not null')}
src = 'pose ODOM (bang Node) -- DB chua co pose toi uu: node bi tat ngang?'
tilt = {}
for nid, ud in c.execute('select id, user_data from Data where user_data is not null'):
if nid not in pose:
continue
try:
raw, _ = mat(ud)
except (zlib.error, struct.error):
continue
if len(raw) >= 24:
tilt[nid] = struct.unpack_from('3d', raw)
return sorted(pose), pose, tilt, src
def cells(db, pose):
"""Luoi cuc bo tung node, theo id (= theo thoi gian, nhu RTAB-Map ghep):
-> (id, o trong xy, o chiem xy) trong frame ban do. Doc dan, khong giu
het trong RAM -- ban do lon co hang chuc trieu o trong."""
for nid, em, ob in connect(db).execute(
'select id, empty_cells, obstacle_cells from Data order by id'):
if nid not in pose or (em is None and ob is None):
continue
T = pose[nid]
out = []
for blob in (em, ob):
if blob is None:
out.append(np.zeros((0, 2)))
continue
raw, ch = mat(blob)
q = np.frombuffer(raw, dtype=np.float32).reshape(-1, ch)[:, :2].astype(np.float64)
out.append(q @ T[:2, :2].T + T[:2, 3])
yield nid, out[0], out[1]
def bilinear(G, x0, y0, step):
"""Ham lay mau song tuyen luoi G (goc (x0, y0), buoc step) tai (x, y)."""
TH, TW = G.shape
def f(x, y):
fx = np.clip((np.asarray(x, float) - x0) / step, 0, TW - 1 - 1e-9)
fy = np.clip((np.asarray(y, float) - y0) / step, 0, TH - 1 - 1e-9)
i, j = fx.astype(int), fy.astype(int)
ax, ay = fx - i, fy - j
return ((1 - ay) * ((1 - ax) * G[j, i] + ax * G[j, i + 1])
+ ay * ((1 - ax) * G[j + 1, i] + ax * G[j + 1, i + 1]))
return f
def dilate(mask, r):
"""O True lan thanh hinh tron ban kinh r o (khong vong qua mep nhu np.roll)."""
H, W = mask.shape
out = mask.copy()
for dy in range(-r, r + 1):
for dx in range(-r, r + 1):
if dx * dx + dy * dy > r * r:
continue
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] |= \
mask[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
return out
def path_mask(xy, keep, x0, y0, H, W):
"""O luoi duong robot di qua: noi cac node lien tiep cung `keep`, cach < MAX_GAP."""
pts = [xy[keep]]
for k in range(len(xy) - 1):
if not (keep[k] and keep[k + 1]):
continue
a, b = xy[k], xy[k + 1]
d = math.hypot(*(b - a))
if RES / 2 < d < MAX_GAP:
t = np.linspace(0.0, 1.0, int(d / (RES / 2)) + 2)[1:-1, None]
pts.append(a + t * (b - a))
p = np.concatenate(pts)
m = np.zeros((H, W), bool)
m[((p[:, 1] - y0) / RES).astype(int).clip(0, H - 1),
((p[:, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
return m
def terrain_obj(header, gx, gy, Z):
"""Luoi do cao -> OBJ dung chung dinh (nho hon nhieu so voi Obj.quad)."""
TH, TW = Z.shape
lines = ['# ' + l for l in header.splitlines()]
for j in range(TH):
lines.extend('v %.3f %.3f %.4f' % (gx[i], gy[j], Z[j, i]) for i in range(TW))
for j in range(TH - 1):
for i in range(TW - 1):
a = j * TW + i + 1 # nguoc kim dong ho nhin tu tren: mat huong LEN
lines.append('f %d %d %d' % (a, a + 1, a + TW + 1))
lines.append('f %d %d %d' % (a, a + TW + 1, a + TW))
return '\n'.join(lines) + '\n'
def fill_gaps(occ):
"""Lap khe <= 2 o (10 cm) giua hai doan tuong thang hang (ngang, doc, cheo).
Luoi 'lan nhin moi nhat thang' xoa o tuong ma tia sau suot qua, nen tuong
that thanh net dut -- trong sim tia LiDAR lot qua khe. Chi lap o nam GIUA
hai o chiem, khong noi rong dam (nguoi da roi di khong quay lai)."""
H, W = occ.shape
def shift(m, dy, dx): # out[y, x] = m[y - dy, x - dx], ngoai mep = False
out = np.zeros_like(m)
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] = \
m[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
return out
fill = np.zeros_like(occ)
for dy, dx in ((0, 1), (1, 0), (1, 1), (1, -1)):
a1, a2 = shift(occ, dy, dx), shift(occ, 2 * dy, 2 * dx)
b1, b2 = shift(occ, -dy, -dx), shift(occ, -2 * dy, -2 * dx)
fill |= (a1 & b1) | (a1 & b2) | (a2 & b1)
return occ | fill
def local_rtabmap_version(root):
"""Ban RTAB-Map ma build may nay link: build/CMakeCache.txt -> RTABMapConfigVersion.cmake."""
try:
cache = open(os.path.join(root, 'build', 'CMakeCache.txt')).read()
d = re.search(r'^RTABMap_DIR:PATH=(.+)$', cache, re.M).group(1).strip()
cfg = open(os.path.join(d, 'RTABMapConfigVersion.cmake')).read()
return re.search(r'set\(PACKAGE_VERSION "([0-9.]+)"\)', cfg).group(1)
except (OSError, AttributeError):
return None
def vtuple(v):
return tuple(int(x) for x in re.findall(r'\d+', v))
def wall_rects(occ):
"""Gop o chiem thanh hinh chu nhat: doan lien tiep tren hang, keo dai xuong
cac hang co dung doan do. -> [(i0, j0, i1, j1)] (bao gom hai dau)."""
H = occ.shape[0]
rects, opened = [], {}
for j in range(H + 1):
cur = set()
if j < H:
d = np.diff(np.concatenate(([0], occ[j].astype(np.int8), [0])))
cur = set(zip(np.nonzero(d == 1)[0].tolist(), (np.nonzero(d == -1)[0] - 1).tolist()))
for key in [k for k in opened if k not in cur]:
rects.append((key[0], opened.pop(key), key[1], j - 1))
for key in cur:
opened.setdefault(key, j)
return rects
def slope_runs(xy, zz, steep):
"""Doan doc tren quy dao: node lien tiep cung doc, chenh z >= 0.2 m.
-> [(k dau, k cuoi, chenh z, dai)]."""
runs, k = [], 0
while k < len(xy):
if not steep[k]:
k += 1
continue
e = k
while e + 1 < len(xy) and steep[e + 1] and math.hypot(*(xy[e + 1] - xy[e])) < MAX_GAP:
e += 1
dz = float(zz[k:e + 1].max() - zz[k:e + 1].min())
length = float(np.hypot(*np.diff(xy[k:e + 1], axis=0).T).sum()) if e > k else 0.0
if dz >= 0.2:
runs.append((k, e, dz, length))
k = e + 1
return runs
def walk_out(xy, k, step, dist):
"""Tu node k di theo quy dao (step = +1 / -1) toi khi duoc `dist` m hoac dut."""
s = 0.0
while 0 <= k + step < len(xy):
d = math.hypot(*(xy[k + step] - xy[k]))
if d >= MAX_GAP:
break
s += d
k += step
if s >= dist:
break
return k
def preview(path, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0):
import cv2
H, W = occ.shape
img = np.full((H, W, 3), 128, np.uint8)
img[seen] = (255, 255, 255)
img[ground] = (0, 140, 255) # cam: tia cham dat (bo)
img[cleared] = (255, 200, 0) # xanh: tren duong da di (bo)
img[occ] = (0, 0, 0)
span = max(float(zz.max() - zz.min()), 1e-3)
col = cv2.applyColorMap(((zz - zz.min()) / span * 255).astype(np.uint8).reshape(-1, 1),
cv2.COLORMAP_JET).reshape(-1, 3)
px = ((xy - (x0, y0)) / RES).astype(int)
for (u, v), c in zip(px, col):
cv2.circle(img, (int(u), int(v)), 2, tuple(int(t) for t in c), -1)
for k, e, _, _ in runs:
cv2.polylines(img, [px[k:e + 1].reshape(-1, 1, 2).astype(np.int32)], False, (0, 0, 255), 1)
if spawn is not None:
sx, sy, syaw = spawn
u, v = int((sx - x0) / RES), int((sy - y0) / RES)
cv2.circle(img, (u, v), 8, (0, 200, 0), 2)
cv2.line(img, (u, v), (int(u + 16 * math.cos(syaw)), int(v + 16 * math.sin(syaw))), (0, 200, 0), 2)
cv2.imwrite(path, img[::-1]) # y len tren
print('anh xem truoc:', path, '(den = tuong, cam = tia cham dat da bo, xanh = bo tren duong '
'da di, cham = node theo z xanh->do, do = doan doc, vong xanh la = diem dat)')
def main():
here = os.path.dirname(os.path.abspath(__file__))
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('db', help='DB ban do that, vd resources/maps/real_YYYYMMDD_HHMMSS.db')
ap.add_argument('--name', help='ten world (mac dinh: ten DB)')
ap.add_argument('--out', help='thu muc ra (mac dinh: <thu muc DB>/sim_<ten> -- da gitignore)')
ap.add_argument('--root', default=os.path.dirname(here), help='goc repo (doc slam.yaml)')
ap.add_argument('--preview', help='ghi anh PNG xem truoc tuong / mat dat / doc')
a = ap.parse_args()
name = a.name or os.path.splitext(os.path.basename(a.db))[0]
out = os.path.abspath(a.out or os.path.join(os.path.dirname(os.path.abspath(a.db)), 'sim_' + name))
terrain, walls = 'vslam_terrain_' + name, 'vslam_walls_' + name
ids, pose, tilt, src = load(a.db)
if not ids:
raise SystemExit('DB khong co node nao')
xy = np.array([pose[i][:2, 3] for i in ids])
yaw = np.array([math.atan2(pose[i][1, 0], pose[i][0, 0]) for i in ids])
zz = np.array([tilt[i][0] if i in tilt else 0.0 for i in ids])
print('%d node, %s; %d node co z do (userData), z %.2f .. %.2f m'
% (len(ids), src, len(tilt), zz.min(), zz.max()))
if not tilt:
print(' !! khong node nao co z (slope.enabled tat luc quet?) -> mat dat PHANG')
# z hai LUOT qua cung mot cho (cach >= 30 node): lech = troi z cua ban do.
lech = []
idx = np.arange(len(ids))
for k in range(len(ids)):
m = (np.hypot(xy[:, 0] - xy[k, 0], xy[:, 1] - xy[k, 1]) < 0.3) & (np.abs(idx - k) > 30)
if m.any():
lech.append(float(np.abs(zz[m] - zz[k]).max()))
if lech:
print(' z giua cac luot qua cung cho (%d node): trung vi %.1f cm, 95%% %.1f cm, max %.1f cm'
% (len(lech), 100 * np.median(lech), 100 * np.percentile(lech, 95), 100 * max(lech)))
# Luot 1 qua DB: khung ban do (node + moi o da thay).
lo_xy, hi_xy = xy.min(0), xy.max(0)
n_grids = 0
for _, em, ob in cells(a.db, pose):
n_grids += 1
for p in (em, ob):
if len(p):
lo_xy, hi_xy = np.minimum(lo_xy, p.min(0)), np.maximum(hi_xy, p.max(0))
if not n_grids:
raise SystemExit('DB khong co luoi cuc bo nao (obstacle_cells / empty_cells)')
x0, y0 = lo_xy - PAD
x1, y1 = hi_xy + PAD
# ---------------- Mat dat: Gauss quanh node, phu ca khung ----------------
TW = int(math.ceil((x1 - x0) / TRES)) + 1
TH = int(math.ceil((y1 - y0) / TRES)) + 1
gx = x0 + np.arange(TW) * TRES
gy = y0 + np.arange(TH) * TRES
Z = np.empty((TH, TW))
for j in range(TH): # tung hang: (TW x so node) -- vua bo nho
d2 = (gx[:, None] - xy[None, :, 0]) ** 2 + (gy[j] - xy[None, :, 1]) ** 2
dmin = d2.min(1, keepdims=True)
# Rong SIGMA sat node, rong dan khi xa (sigma^2 + (d/2)^2): xa duong di
# khong thanh bac o duong chia giua hai node khac z.
w = np.exp(-(d2 - dmin) / (2.0 * SIGMA ** 2 + 0.5 * dmin))
Z[j] = (w @ zz) / w.sum(1)
zt = bilinear(Z, x0, y0, TRES)
dzy, dzx = np.gradient(Z, TRES)
zn = zt(xy[:, 0], xy[:, 1])
gxn = bilinear(dzx, x0, y0, TRES)(xy[:, 0], xy[:, 1])
gyn = bilinear(dzy, x0, y0, TRES)(xy[:, 0], xy[:, 1])
steep = np.degrees(np.arctan(np.hypot(gxn, gyn))) > SLOPE_DEG
print('mat dat %dx%d o %.1f m, z %.2f .. %.2f m; %d node tren doc > %.0f do'
% (TW, TH, TRES, Z.min(), Z.max(), int(steep.sum()), SLOPE_DEG))
# ---------------- Luoi 2D: log-odds nhu slam.yaml, bo tia cham dat ----------------
gp = grid_params(a.root)
lh, lm = logit(gp['ProbHit']), logit(gp['ProbMiss'])
lo, hi = logit(gp['ProbClampingMin']), logit(gp['ProbClampingMax'])
W = int(math.ceil((x1 - x0) / RES))
H = int(math.ceil((y1 - y0) / RES))
L = np.zeros((H, W))
seen = np.zeros((H, W), bool)
ground = np.zeros((H, W), bool)
k_of = {nid: k for k, nid in enumerate(ids)}
n_obs = n_ground = 0
for nid, em, ob in cells(a.db, pose): # luot 2 qua DB
k = k_of[nid]
if len(ob):
# Tia ngang song song mat dat duoi robot, cao LIDAR_H: o nao mat dat
# nho len gan toi do la tia cham DAT, khong phai tuong.
plane = zn[k] + gxn[k] * (ob[:, 0] - xy[k, 0]) + gyn[k] * (ob[:, 1] - xy[k, 1])
g = zt(ob[:, 0], ob[:, 1]) - plane > LIDAR_H - GROUND_TOL
n_obs += len(ob)
if g.any():
n_ground += int(g.sum())
ground[((ob[g, 1] - y0) / RES).astype(int).clip(0, H - 1),
((ob[g, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
ob = ob[~g]
for pts, d in ((em, lm), (ob, lh)):
if not len(pts):
continue
flat = np.unique(((pts[:, 1] - y0) / RES).astype(int).clip(0, H - 1) * W
+ ((pts[:, 0] - x0) / RES).astype(int).clip(0, W - 1))
L.flat[flat] = np.clip(L.flat[flat] + d, lo, hi)
seen.flat[flat] = True
occ = seen & (L > 0)
ground &= ~occ # o con chiem nho node khac nhin thay that
n_log = int(occ.sum())
occ |= fill_gaps(occ) & ~ground
near = dilate(path_mask(xy, np.ones(len(xy), bool), x0, y0, H, W),
int(math.ceil((ROBOT_R + 0.05) / RES)))
cleared = occ & near
occ &= ~near
print('luoi %dx%d o %.2f m: %d o tuong (log-odds %d + lap khe %d - tren duong da di %d); '
'bo %d/%d lan thay la tia cham dat'
% (W, H, RES, int(occ.sum()), n_log, int((occ | cleared).sum()) - n_log,
int(cleared.sum()), n_ground, n_obs))
if steep.any():
sl = dilate(path_mask(xy, steep, x0, y0, H, W), int(round(0.6 / RES)))
print(' con %d o tuong cach duong DOC <= 0.6 m (tuong / lan can that, hoac tuong gia sot)'
% int((occ & sl).sum()))
# ---------------- Doan doc + diem dat robot ----------------
runs = slope_runs(xy, zz, steep)
for n, (k, e, dz, length) in enumerate(runs):
print('doc #%d: node %d..%d, dai %.1f m, z %.2f -> %.2f (chenh %.2f m, ~%.1f do)'
% (n, ids[k], ids[e], length, zz[k], zz[e], dz,
math.degrees(math.atan2(dz, max(length, 1e-6)))))
spawn = None
if runs:
k, e, _, _ = max(runs, key=lambda r: r[2])
top, step = (e, +1) if zz[e] > zz[k] else (k, -1)
s = walk_out(xy, top, step, 1.0) # lui ~1 m ra mat bang tren
spawn = (float(xy[s, 0]), float(xy[s, 1]), float(yaw[s]))
print('dat robot o DINH doc lon nhat (node %d, z %.2f m): --x %.2f --y %.2f --yaw %.3f'
% (ids[s], zz[s], spawn[0], spawn[1], spawn[2]))
else:
print('!! khong thay doan doc nao (chenh >= 0.2 m) -- --slope-test se bao khong co doc')
# ---------------- Ghi model + world + ban sao DB ----------------
tag = 'tu %s. Sinh boi tools/gen_world_from_db.py -- dung sua tay.' % os.path.basename(a.db)
w = base.Obj('Tuong (o chiem luoi 2D), cao %.1f m tren mat dat, %s Z-UP, met.' % (WALL_H, tag))
rects = wall_rects(occ)
for i0, j0, i1, j1 in rects:
bx0, bx1 = x0 + i0 * RES, x0 + (i1 + 1) * RES
by0, by1 = y0 + j0 * RES, y0 + (j1 + 1) * RES
f = zt(*np.meshgrid(np.linspace(bx0, bx1, max(2, int((bx1 - bx0) / TRES) + 2)),
np.linspace(by0, by1, max(2, int((by1 - by0) / TRES) + 2))))
w.box(bx0, by0, float(f.min()) - 0.05, bx1, by1, float(f.max()) + WALL_H)
print('tuong: %d hop' % len(rects))
models = os.path.join(out, 'models')
for mname, mesh, text, desc in (
(terrain, 'terrain.obj', terrain_obj('Mat dat (z node) %s Z-UP, met.' % tag, gx, gy, Z),
'Mat dat tu z node ban do that.'),
(walls, 'walls.obj', w.text(), 'Tuong tu luoi 2D ban do that.')):
base.write(os.path.join(models, mname, 'meshes', mesh), text)
base.write(os.path.join(models, mname, 'model.sdf'), base.SDF.format(name=mname, mesh=mesh))
base.write(os.path.join(models, mname, 'model.config'),
base.CONFIG.format(name=mname, desc=desc).replace('gen_slope_world', 'gen_world_from_db'))
hint = ('--x %.2f --y %.2f --yaw %.3f' % spawn) if spawn else '(khong co doc)'
world_path = os.path.join(out, name + '.world')
base.write(world_path, ''.join([
'<?xml version="1.0" ?>\n',
'<!-- World %s\n Frame world = frame ban do. Dinh doc lon nhat: %s -->\n' % (tag, hint),
'<sdf version="1.6">\n <world name="%s">\n' % name,
' <include><uri>model://ground_plane</uri></include>\n',
' <include><uri>model://sun</uri></include>\n',
base.include(terrain + '_1', terrain, 0, 0, 0, 0),
base.include(walls + '_1', walls, 0, 0, 0, 0),
' </world>\n</sdf>\n']))
# Ban sao DB: localization co the ghi vao DB, giu ban that nguyen ven. Chep
# lai moi khi ban sao khac ban goc (ca sau mot lan sim da ghi vao no).
db_copy = os.path.join(out, name + '.db')
st = os.stat(a.db)
if (not os.path.exists(db_copy) or os.stat(db_copy).st_size != st.st_size
or int(os.stat(db_copy).st_mtime) != int(st.st_mtime)):
shutil.copy2(a.db, db_copy)
print('chep DB ->', db_copy)
# DB tu Jetson (RTAB-Map 0.23) ma may nay link ban cu hon (0.21) thi RTAB-Map
# tu choi mo ("Opened database version ... is more recent"). Schema 0.23 =
# 0.21 + hai cot 0.21 khong doc (Admin.dictionary_index, Data.depth_confidence),
# nen ha chuoi version cua BAN SAO la du -- 08/10: rtabmap-info + vslam_node
# 0.21.13 nap va dinh vi lai binh thuong tren DB 0.23.12.
local = local_rtabmap_version(a.root)
con = sqlite3.connect(db_copy)
ver = con.execute('select version from Admin').fetchone()[0]
if local and vtuple(ver) > vtuple(local):
con.execute('update Admin set version = ?', (local,))
con.commit()
print('ban sao DB: version %s -> %s (RTAB-Map cua build nay)' % (ver, local))
con.close()
if a.preview:
preview(a.preview, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0)
root = os.path.abspath(a.root)
rel = lambda p: os.path.relpath(p, root) if p.startswith(root + os.sep) else p
maps = os.path.join(root, 'resources', 'maps')
db_arg = os.path.relpath(db_copy, maps) if db_copy.startswith(maps + os.sep) else db_copy
mp = rel(models) if os.path.isabs(rel(models)) else '$PWD/' + rel(models)
print('\nChay sim (tu goc repo; dinh vi lai CHI bang LiDAR -- anh sim khac anh that):\n'
' export GAZEBO_MODEL_PATH=$PWD/resources/models:%s\n'
' ./build/app/vslam_node --sim --sim-gl --world %s %s --token t --port 8092 \\\n'
' --slam --slam-db %s --slam-mode localization --slam-reloc --slam-reloc-auto \\\n'
' --slope-test 2>&1 | tee logs/sim_%s.log'
% (mp, rel(world_path), hint, db_arg, name))
if __name__ == '__main__':
main()