Compare commits

...

93 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
trung09122002
f8049be038 web: chi lam muot HINH robot (truot 50 ms, bo du doan van toc 0.15 s lam vuot roi giat khi dung quay); scan + cloud neo theo pose THAT de dinh vao tuong -- neo theo pose muot thi lac quanh tuong moi khi xoay, roi mat 2026-10-07 16:21:10 +07:00
trung09122002
31f84eb082 map,lidar,web: ban do theo lan nhin MOI NHAT + scan dung gio. Luoi 2D: GridGlobal/* (3 lan nhin xuyen qua -> trong, truoc ~9; truoc 07/10 khong truyen vao bo ghep luoi); lop camera + 3D: xoa voxel ma >= 2 node sau nhin xuyen qua (VoxelCarver) -- nguoi dung roi di thi quay lai quet la mat. LiDAR: stamp_offset -55 ms + chinh meo theo chieu quet (do tren ban do that 28/09 + 01/10); web: robot troi muot 2026-10-07 16:04:28 +07:00
trung09122002
61c3a75fb1 slope: bu nghieng scan giu CA vong scan LakiBeam -- lidar_core phat goc [0, 2pi) (angle_min 0), LevelScan dua ve [-pi, pi) roi tru nen bo het nua -pi..0: ban do that tu 06/10 chi con nua scan (325 vs 620-730 diem); RayIndex lay goc theo vong tron + test scan LakiBeam; log slope/scan ti le tia giu 2026-10-07 14:57:49 +07:00
trung09122002
cc3df0ecb2 odom: goc quay EKF theo ENCODER mac dinh (pipeline.yaml ekf.gyro_yaw: false) -- WT61PC lech mot chieu khi chay: 07/10 gyro - encoder +0.11..+0.38 rad moi 30 s du quay trai hay phai (+71 do / 2.5 phut); log odom/yaw in hieu tuyet doi + nguon EKF 2026-10-07 14:42:00 +07:00
trung09122002
3935ffe0cc odom: goc quay EKF -- GyroYawFuser (gyro giu tong, encoder lap khoang chua ve) thay cua so 0.5-1.5 buoc roi vut: IMU 200 Hz toi theo cum lam ban do 07/10 dem thieu 9.9% moi goc quay; log odom/yaw 30 s 2026-10-07 13:25:51 +07:00
trung09122002
b5574a17b5 reloc: dung XIEN tren doc -- tu chay quay mat theo chieu doc (IMU) de camera nhan ra; bo loc nghieng + neo z noi suy giua hai lan cung mat doc (doc rong) -- sim doc rong quet 3 lan: 8/8 cho xien chot dung 0.5-4.4 cm, 6/8 bang camera (11-55 s) 2026-10-07 09:07:11 +07:00
trung09122002
35fef155f5 sim: slope_two_ramps -- hai doc rong het nha (8 m) thay hanh lang 2.4 m, giong doc ngoai troi; README 2026-10-06 15:27:49 +07:00
trung09122002
994edd1da3 reloc,web: chua chot thi ve robot tu cho bat dau quet (node dau ban do) thay vi goc map -- trong mo phong goc world thuong la goc nha 2026-10-06 15:12:00 +07:00
trung09122002
3f60ecf630 sim: world slope_two_ramps -- sanh giua + doc 10 do / 15 do len hai tang 1.5 m, khong doi xung, quet mot vong ~85 m (tools/gen_two_ramp_world.py); README 2026-10-06 14:40:37 +07:00
trung09122002
788c08c916 docs,config: README cho doc (gioi thieu, lenh quet / dinh vi lai sim + robot that, udev IMU, sao luu ban do, bang log dau) + slam.yaml slope.enabled mac dinh BAT 2026-10-06 11:08:47 +07:00
trung09122002
28f124275a config: imu_lag_sec 0.03 -- do tren robot 06/10 (115200 / 200 Hz): dat 0.01 thi wheel_odom/lag bao 20 ms on dinh 1000-5000 mau 2026-10-06 10:41:18 +07:00
trung09122002
25fc247cfb slam: height_map.h thieu #include <cstddef> (size_t) -- GCC 11 tren Jetson bao loi, GCC 9 may dev khong 2026-10-06 10:32:14 +07:00
trung09122002
f0c5ddb6b8 reloc,web: dinh vi lai TREN DOC (slope.enabled) -- loc gia thuyet bang do nghieng IMU vs do doc ban do, chan mu doc truc (ShiftScoreRatio), vong DUNG YEN khong xoay (ty le nho nhat >= 3 vong / hai cho cung pose), tu chay bo thang tren doc; camera VPR+PnP tren doc (>= 2 anh trung, khop nghieng, LiDAR khong phan doi, pose = trung binh camera) -- sim 10 cho chot dung 1.4-2.9 cm, 0 chot sai; web 3D: ban do uon theo san (FLH1), scan/quy dao theo z, het nen lung, sua ro GPU; CMake: TensorRT tren CMake < 3.17 2026-10-06 10:17:17 +07:00
trung09122002
b1ab04c51e drivers,tools: IMU WT61PC 115200 baud / 200 Hz -- mcu.baud 115200, imu_lag_sec 0.01 (uoc luong, can do lai bang wheel_odom/lag), FTDI low-latency 1 ms + log latency_timer, luat udev configuration_files/udev/99-imu.rules; tool vslam_imu_config (do / doi baud + tan so WT61PC bang lenh WitMotion); vslam_vo_bench --pitch-source sensor 2026-10-06 10:17:07 +07:00
trung09122002
6d552e231e slam: pose odometry DUNG LUC QUET cho SLAM (noi suy lich su EKF -- luc quay tai cho, ghep scan voi pose hien tai lam lech 0.7 do va xoay ca ban do) + vong dong xa (slam.yaml far_loops, mac dinh bat: node vua tao vs node cu cach >= 100 buoc trong 1 m, ICP xac nhan, addLink) -- sim vong doc 52 m: cuoi vong 17-22 cm -> 1.5 cm 2026-10-04 01:36:35 +07:00
trung09122002
f064dcf3ec slam,odometry,perception: di tren doc (G4, slam.yaml slope.enabled, mac dinh tat) -- z robot = tich -ds*sin(pitch IMU) kep phang < 1.5 do va neo vao ban do (HeightEstimator), odometry ngang, scan cho SLAM bu nghieng + bo tia cham san/doc theo ban do do cao tu depth (ScanLeveler, ElevationMap), z/roll/pitch luu vao node + do thi z 1-D + mat san theo node (height_map), voxel dat o z that va vat can tinh tu san cuc bo, xoa tuong gia LiDAR tren doc noi camera da thay mat san, web z uoc luong, --sim-imu-hz 2026-10-04 00:03:02 +07:00
trung09122002
6735b53423 tools: so nguon z tren doc (G3) -- vslam_vo_bench (F2M RTAB-Map tren IR+depth, hang tham chieu ds*sin(pitch) bang GravityAlign, num IMU Hz/bias/truot/nhieu IR), slope_eval/slope_fuse/slope_summary/slope_bakeoff.sh (3 muc giong that, DM-VIO ngoai repo); vslam_vsr_export them bias/nhieu IR; vslam_record --gl-headlight/--gl-ambient 2026-10-04 00:02:53 +07:00
trung09122002
213b5f23a6 tools: vslam_record kich ban doc (slope_loop, slope_lane5..30) lai theo waypoint khong qua FSM, --gl, --cam-decimate, nhieu IMU vao header; vslam_vsr_export doi .vsr sang dataset DM-VIO (mau IMU dung gio anh, T_cam_imu tu robot.yaml, su that IMU/camera/base, ha tan so/lech gio/nhieu IMU luc xuat) 2026-10-03 19:37:29 +07:00
trung09122002
f9fd18b5aa sim: camera ve bang GPU (lib tuy chon vslam_sim_gl, EGL + GLES3 + assimp) -- anh IR co texture that + depth khop tung pixel, vslam_node --sim-gl, tool vslam_render_preview 2026-10-03 19:13:50 +07:00
trung09122002
0dd2546ab1 drivers,sim: moi khung anh mot bo dem rieng (sua tranh chap voi SlamLoop o RealSense/sim/replay); sim: IMU dong hoc tu quy dao 6-DoF, tan so phat/tre/bias, ground truth vao .vsr, vslam_record --robot --gt 2026-10-03 18:55:55 +07:00
trung09122002
26ee1a3b72 sim: dia hinh 3D -- doc va san cao tu model vslam_terrain_*, robot di tren mat san, LiDAR tia 3D, ground truth 6-DoF, world slope_test (5 doc 5-30 do) 2026-10-03 18:31:13 +07:00
trung09122002
be2aa17e3e drivers: IMU WT61PC noi thang UART (mcu.protocol: wt61pc), bo ESP32 -- doc quyen cong, tach khung co resync, canh bao khi im 2026-10-02 14:01:19 +07:00
trung09122002
a8388102d8 docs: README -- dung them motor_control truoc khi chay robot, so do reloc camera tren robot that 2026-10-02 11:04:03 +07:00
trung09122002
5f47e83fd9 docs: README -- GAZEBO_MODEL_PATH cho mo phong, dinh vi lai bang camera (--slam-reloc-vpr), yaw bang rad 2026-10-01 11:37:33 +07:00
trung09122002
fed62c280a web: mo trang khong con lam dinh vi lai tu dong nhuong 5 s; vpr_encoder.h sua comment; reloc bench --refine-sigma 2026-10-01 11:21:28 +07:00
trung09122002
dbd508d910 reloc: gan lai camera (VPR + PnP) vao node -- chi bat khi co --slam-reloc-vpr; duong LiDAR giu nguyen ban 29/09
Code camera lay nguyen tu 1d3cb2f, giu hien thi yaw bang rad (153bb1b).
Kiem mo phong (co tuong, khong co co camera): vong 1 trung tung chu so voi ban 29/09
(1059 diem, ty le 1.16046 / 2.22805), chot sau 4 vong lech 0.042 m.
2026-10-01 11:17:03 +07:00
trung09122002
f4b45afead reloc: dong DA DINH VI / TIM THAY hien yaw bang rad, cung don vi voi o POSE tren web 2026-10-01 11:06:56 +07:00
trung09122002
e9be787948 reloc: tra node ve ban chieu 29/09 (2c6c839) -- tam go camera VPR khoi node
Mo phong lech tu 30/09 la do thieu GAZEBO_MODEL_PATH (khong nap tuong benh vien), khong phai do code.
Thu vien VPR / VisualVerifier van giu trong libs/, gan lai vao node sau khi chay on trong mo phong.
2026-10-01 10:53:00 +07:00
trung09122002
1d3cb2f037 reloc: --slam-reloc-vpr -- camera (VPR TensorRT + PnP) ket hop LiDAR, chot khi hai nguon trung 2026-09-30 15:24:31 +07:00
trung09122002
c6c42d177f reloc: VisualVerifier (ORB + PnP bang depth anh ban do) + vslam_pnp_eval -- trung khop ban Python 2430/2430 cap 2026-09-30 15:09:53 +07:00
trung09122002
2fc289db1c vslam_vpr_check: cham theo ty le TIM DUNG CHO (top-1/top-5) thay vi giong het PyTorch 2026-09-30 15:03:06 +07:00
trung09122002
1552ec2636 vpr: VprEncoder TensorRT (chi Jetson, -DVSLAM_WITH_TENSORRT=ON) + vslam_vpr_check + tools/vpr_export_onnx.py 2026-09-30 14:50:47 +07:00
trung09122002
cccc048eaf reloc eval: camera (VPR+PnP) ket hop LiDAR -- 25/09: 85->159, 28/09: 29->40, 0 chot sai ca hai ban 2026-09-30 14:27:02 +07:00
trung09122002
29d07e4db5 reloc bench: --gicp xac minh 3D bang depth; analyzer: luat trung khop 3D tai pose doan (R3: 137 -> 153 dung, 0 sai) 2026-09-30 13:55:44 +07:00
trung09122002
e7e38c0b48 docs: README gon lai -- mo ta, cong nghe, build (dev + Jetson), chay mapping va relocalization 2026-09-30 09:57:09 +07:00
trung09122002
2c6c839269 reloc: ban do 3D luc khoi dong nap du moi node (khong gioi han 40 node/lan) 2026-09-29 14:50:34 +07:00
trung09122002
0f3e46d83a web: hang 'ban do 3D' (nguon + so o); tu bat lop cloud da quet khi co voxel; ui 2026-09-29a 2026-09-29 14:44:09 +07:00
trung09122002
36db5126c2 reloc: web hien map DB (2D+3D) ngay luc khoi dong; robot o goc map toi khi chot roi nhay ve cho that 2026-09-29 14:32:14 +07:00
trung09122002
60853531aa reloc: --slam-reloc(-auto) tu dinh vi lai trong node (tu xoay/tu di, nguoi luon thang); web ve robot mo o vi tri doan; sieu am cho xoay; LocalMatch gioi han huong 2026-09-29 11:16:04 +07:00
trung09122002
399a46139e reloc: LocalMatch + bench --split-id/--vpr-csv + phan tich ghep VPR/LiDAR; robot that: 85 -> 108 chot dung, 0 sai 2026-09-29 10:26:00 +07:00
trung09122002
ca3b7854ea update 2026-09-29 10:00:22 +07:00
trung09122002
7258f15ab5 tools/vpr_eval.py: do VPR tren anh IR D410 -- CosPlace/EigenPlaces top-1 dung cho 88-89% 2026-09-29 09:59:51 +07:00
trung09122002
89ab2e7868 slam.yaml: profiles sim/real -- odom sigma va ICP ratio tach theo moi truong 2026-09-28 14:40:48 +07:00
trung09122002
c8c08223ed web: chi gui lenh khi dang lai -- het de len lenh tay cam 2026-09-28 11:13:56 +07:00
trung09122002
6edf5f6961 web 3D: lat hang lop ban do da quet -- het lat guong theo y 2026-09-28 10:58:16 +07:00
trung09122002
4baa38c12c zlac: doc 0x606C du phong boc try rieng -- khong terminate khi bus CAN nghen 2026-09-28 10:39:31 +07:00
trung09122002
720ae3d0d8 tools/render_map.py xuat anh bao cao; bo qua logs/ report/ 2026-09-28 10:22:37 +07:00
trung09122002
1dc4765b57 robot that: max_linear 0.5 m/s; stop 0.45, us_stop 0.40 2026-09-28 10:22:37 +07:00
trung09122002
f91d929a62 voxel: chi giu o >= 3 node thay; obstacle_z_min 0.15 2026-09-25 16:04:29 +07:00
trung09122002
ccd6d5954a voxel: chi giu o >= 3 node thay; obstacle_z_min 0.15 2026-09-25 15:57:22 +07:00
trung09122002
185814f0ec robot that: ICP ratio 0.05, odom sigma 0.1; khong dem goc gyro 2 lan khi IMU 10 Hz 2026-09-25 15:43:20 +07:00
trung09122002
08c9e1a3b8 vslam_slam: bo opencv_* khong co (aruco tren Jetson); bo __pycache__ 2026-09-25 14:56:35 +07:00
trung09122002
fe8b147c6a update 2026-09-25 14:07:58 +07:00
trung09122002
0093df0508 update 2026-09-25 09:04:37 +07:00
trung09122002
d6f1afac31 update 2026-09-24 16:30:03 +07:00
robotics
5e27c7cc41 update 2026-09-23 13:38:49 +07:00
trung09122002
0a1b1b13f1 update 2026-09-23 13:36:48 +07:00
trung09122002
dbcbf84dc3 update 2026-09-22 17:28:01 +07:00
trung09122002
f17dbdce2b update 2026-09-22 17:18:02 +07:00
trung09122002
caf080649f update 2026-09-22 17:10:03 +07:00
trung09122002
83e20a64d9 update 2026-09-22 16:04:42 +07:00
trung09122002
d8c96377c6 update 2026-09-22 15:52:31 +07:00
trung09122002
2ef18312a8 update 2026-09-22 15:42:14 +07:00
trung09122002
14ccf198d2 update 2026-09-22 10:42:14 +07:00
trung09122002
3107c4a28f update 2026-09-22 10:24:51 +07:00
trung09122002
58fae1778a update 2026-09-22 10:18:45 +07:00
trung09122002
3c6e02d9d8 update 2026-09-22 10:08:31 +07:00
trung09122002
ee82d64440 update 2026-09-22 10:02:27 +07:00
trung09122002
50f14a264d update 2026-09-22 09:53:33 +07:00
trung09122002
1efef2ef47 update 2026-09-22 09:31:16 +07:00
trung09122002
b5f0956b1d cliff: tat, kem toan bo ly do va duong sua that
Robot dang MU VUC, va do la quyet dinh co y sau khi di het duong phan
mem.

Nguyen nhan khong phai tham so sai ma la hinh hoc phan cung: camera dat
NGANG o 0.445 m nen chi vai hang pixel duoi cung cham san, o goc 14-21
do. Stereo nhin san phang khong van o goc luot do gan nhu khong tra ve
gi.

Do duoc, robot dung yen giua cho trong:
    n_cliff=49 (lo=55 hut=0, trong cua so=676)

`hut=0` la cho quyet dinh: khong co diem nao thap hon nguong that, toan
bo la LO. Ma cau thang toi cung cho ra lo, san khong van cung cho ra lo
-- detector khong phan biet duoc, nen chon phia an toan va fail_safe
chan robot lien tuc giua san phang.

Da thu het:
- chieu cao camera do lai bang thuoc: 0.3935 -> 0.445 m, z0 tu -0.098 ve
  -0.002
- min_dist 1.00 -> 1.15 (1.00 cu da roi vao trong vung mu 1.105 m),
  max_dist 1.50 -> 1.70
- tach log lo/hut -- chinh nho no moi biet hut=0

Duong sua that la chuc camera xuong 15-20 do. Da thu tren robot: dam may
diem CO san that, trai rong truoc mui thay vi vai cum roi rac.

Ghi vao file ca cai bay da mac: chuc camera ma quen dat pitch trong
robot.yaml thi TF van khai 0, detector chieu tia y nhu cu (`san thay o
1.215..`, `trong cua so=675` giong het den tung con so) va `lo` bung tu
150 len 516 -- te hon truoc khi chuc.
2026-09-21 17:08:31 +07:00
trung09122002
0e44588032 zlac: het crash luc tat -- nem tu trong catch, va join sai thu tu
Moi lan tat node deu abort kem core dump:

  [ZlacMotorDriver] Safely disabling motor hardware...
  terminate called after throwing an instance of 'lely::canopen::SdoError'
    what(): SubmitRead:01:6064:01: Resource not available: SDO connection

Hai loi chong nhau, va ca hai do phep doc 0x6064 toi them vao lo ra:

1. Phep doc SDO du phong nam BEN TRONG mot khoi `catch (...)`. Nem tu
   trong catch thi thoat thang ra ngoai, khong con ai bat -> terminate.
   Boc no bang mot `try` rieng.

2. disableHardware() gui NMT STOP TRUOC roi moi join luong telemetry,
   nen luong do chac chan gap ket noi SDO da chet. Chuyen join len dau
   ham; `hardware_ready_.exchange(false)` o tren da lam vong while thoat
   nen chi cho not mot chu ky 20 ms.

Ban goc khong lo vi no chi doc 0x606C, cung trong khoi catch do nhung
khong ai dung ket qua -- loi nam san day tu truoc, phep doc vi tri chi
lam no phat ra.

Ghi vao PROVENANCE.md: day la sua doi thu hai trong zlac/ so voi
base_kit, phai mang theo khi dong bo lai.
2026-09-21 16:53:25 +07:00
trung09122002
717ccd36c7 perception: tach LO khoi HUT trong log cliff
Log chi in n_cliff gop. Diem khong co so do do sau bi tinh la ung vien
vuc -- dung voi cau thang toi, nhung san phang KHONG VAN nhin o goc
luot cung cho ra y het nhu vay (pipeline.yaml da ghi ro: cang luot thi
stereo cang khong bat duoc gi tren san phang khong van).

Hai thu do can hai cach sua khac han nhau, ma gop lam mot con so thi
khong phan biet duoc tu log. In them n_hole, n_drop, n_inwin va dai
r_min..r_max de biet camera thuc su thay san o dau.
2026-09-21 16:49:19 +07:00
trung09122002
252ff2d5d7 robot: camera cao 0.445 m (do bang thuoc), khong phai 0.3935
cliff_detect bao VUC giua cho trong. Nhung lan nay khac lan truoc: no
khop mat san voi mad chi 2-5 mm -- tuc khop DUNG san, khong phai tuong
hay vat can nhu hoi robot dung sat tuong. Phep do dung, MOC sai.

Cac mau sach (doc ~ 0) bao z0 = -0.049 m deu dan: san thap hon du kien
5 cm, va theo dinh nghia do LA mot hut 5 cm.

Do bang thuoc tu san len tam hang ong kinh: 44.5 cm. Cau hinh khai
0.3935. Lech 5.15 cm, khop dung con so detector bao.

camera_link.z: 0.307 -> 0.3585 (+ wheel_radius 0.0865 = 0.445).

Hai gia tri SUY RA tu chieu cao phai doi theo, neu khong thi sua mot cho
lai hong cho khac:

  min_dist 1.00 -> 1.15. Vung mu hinh hoc la chieu_cao/tan(21.9 do);
  voi 0.445 m thi la 1.105 m, nen 1.00 roi VAO TRONG vung mu -- detector
  se soi vao cho khong the thay san roi bao vuc. Dung cai bay ma comment
  trong file da canh bao cho gia tri cu 0.55.

  max_dist 1.50 -> 1.70. Giu cung goc luot 14.7 do nhu truoc:
  0.445/tan(14.7) = 1.696. Camera cao hon thi tia bot luot, nen cua so
  rong ra 55 cm thay vi 50 cm -- mat loi duy nhat cua viec nay.

test_robot_model giu 0.3935 va fail dung nhu thiet ke: thong bao cua no
ghi thang "chieu cao camera doi -> min_dist va nominal_tz phai doi theo".
Cap nhat ky vong va ghi luon cong thuc cua hai gia tri suy ra, de lan
sau khoi phai tim lai.
2026-09-21 16:45:49 +07:00
trung09122002
21a3de5206 ekf: lech thu tu nho khong phai nhay lui; chot hai gia tri IMU da do
ekf_se2.cc gop hai chuyen khac han nhau vao mot nhanh `dt < 0`.

Sau khi dat mcu.imu_lag_sec = 80 ms thi dau thoi gian IMU LUON cu hon
encoder -- va do la dung: 80 ms la thoi diem do that (WT61PC loc noi bo
~50 ms, day 2 khung qua 9600 baud ~23 ms, ca hai truoc luc ESP32 dong
dau). Encoder chi bu `age`, co ms.

Nhanh `dt < 0` coi moi cu lui la "phat lai ban ghi" roi reset moc, nen
EKF tien 80 ms theo encoder roi bi IMU keo lui, MOI 100 ms mot lan:
nhieu qua trinh cong hai lan moi chu ky, cac phep cap nhat roi sai thoi
diem. Do duoc tren robot: `ekf: thoi gian lui` lap lien tuc -0.040 /
-0.054 / -0.045 / -0.059 / -0.073 s.

Lech duoi 0.25 s: ap phep do len trang thai hien tai, giu nguyen moc,
dem vao stats.out_of_order. Gan dung -- sai so chi la phan trang thai
doi trong 80 ms, voi mot phep do VAN TOC GOC thi khong dang ke.
Tren 0.25 s: giu nguyen hanh vi cu, do moi la replay/reset that.

Cach dung han la xep moi phep do vao hang doi theo dau thoi gian roi nap
theo thu tu voi tre co dinh ~150 ms. Chuan hon nhung dung ca runtime.cc
va them tre vao vong dieu khien. Ghi lai lam mon no.

sensors.yaml: chot expect_timestamps = true va imu_lag_sec = 0.08. Hai
gia tri nay da chay tren Jetson tu truoc nhung chi sua bang sed, chua
bao gio vao git -- mot lan `git checkout` la mat, va mat im lang: robot
van chay, chi quay ve trang thai tre 80 ms khong bu.
2026-09-21 16:10:56 +07:00
trung09122002
675f602c44 odom: omega cua so tinh tu HIEU VI TRI, khong trung binh cac ti so
Tren robot: omega encoder bao 0.0096 roi 0.4377 quanh gia tri that 0.22
-- mot khoang bo sot chuyen dong, khoang sau bu lai gap doi.

Nguyen nhan o zlac_motor_driver.cpp:328: vong telemetry chay 50 Hz, vong
doc cua ta cung 50 Hz, hai vong khong dong bo. Nhip thuc te do duoc la
43.6 Hz, tuc ~13% lan doc trung mau cu. `age` cua mau dao dong 0-20 ms
va di thang vao dau thoi gian roi vao `dt`. Trong omega = d_theta/dt thi
TU SO chinh xac tuyet doi (dem xung) con MAU SO nhieu +-20 ms tren nen
20 ms.

Trung binh cac ti so d_theta_i/dt_i khong khu duoc nhieu do: trung binh
cua ti so khac ti so cua trung binh, va con lech he thong. Lay
(theta(t1)-theta(t0))/(t1-t0) thi tu so la hieu hai so dem xung va moi
nhieu o cac moc GIUA cua so tu triet tieu -- chi con hai dau, tren nen
100 ms thay vi 20 ms.

Them nguong rieng cho nhanh so THO. Ban dau toi tat han bao truot o
nhanh do, nhung test YawRateSigmaBangSaiSoDaDo -- giu mot su kien truot
THAT do duoc tren robot, lech 2.258 rad/s -- fail ngay. Tat han la qua
tay: bo qua su kien do thi EKF nhan mot diem 11-sigma ma van tin.

Nhieu cua nhanh tho co chan tren DO DUOC (0.78 rad/s trong test jitter),
con truot that thi khong. Nen nguong nhanh tho = 8x nguong thuong: tren
chan nhieu, duoi su kien that.
2026-09-21 15:55:44 +07:00
trung09122002
29a8f66d5f mcu: bo dong cut dau tien, va LUON tien moc thoi gian MCU
Hai loi, ca hai deu do chinh commit truoc gay ra hoac lo ra.

1. Toi lap lai dung cai bug vua chua trong wheel_odometry. Ly le "dung
   lay mau rac lam moc" nghe hop ly nhung hau qua nguoc han: mot mau rac
   lam moc KET vinh vien, moi mau that sau do deu co buoc lon nen deu bi
   bo. Do tren robot: bo dem nhay 1 -> 101 -> 201 moi 10 giay, tuc 100%
   mau bi loai, va buoc bao cao lon dan dung bang thoi gian thuc
   (117 -> 127 -> 137 s). ClockSync khong nhan duoc mau nao ca phien.

   Luon tien moc: mot cu vap ton dung HAI mau roi tu khop lai.

2. Nguon cua mau rac dau tien: mo cong serial giua dong. Thiet bi phat
   lien tuc nen open() gan nhu luon roi vao GIUA mot dong, va '\n' dau
   tien gap duoc la ket thuc cua mot dong CUT.

   Dong cut van parse duoc -- do moi la van de. "I,117592345,..." bi cat
   dau thanh "I,5678,..." thi micros be di hang tram giay ma moi truong
   deu hop le. Buoc 117.587 s do duoc chinh la tuoi cua ESP32 luc do.

   Bo dong dau tien sau open(), ca hai nhanh.
2026-09-21 15:48:09 +07:00
trung09122002
e61a6abf37 mcu: loc mau MCU truoc khi nap vao ClockSync
Tren robot: ClockSync cho thoi diem lech 77 GIAY so voi luc nhan duoc
dong. Bo chan o dau ra bat duoc, nhung nguyen nhan thi nam o dau vao.

Dong text KHONG co checksum, nen mot byte hong lam `micros` thanh mot so
bat ky ma van parse duoc. Va mot mau rac duy nhat du de pha ca phep fit:
khi skew bi tu choi thi offset = trung_binh_host - trung_binh_mcu, nen
mot mau lech X giay keo offset di X/16. Lech 77 s ung voi mot mau sai
~1200 s -- vua dung co mot dong hong byte.

McuTimeUnwrapper khong phai thu pham: no chi bu tran khi gia tri lui hon
nua dai (2^31), da kiem.

Loc: buoc thoi gian MCU phai nam trong (0, 2] giay. O 10 Hz buoc that la
~0.1 s; 2 s de con chiu duoc cu vap cua USB hay scheduler. Mau ngoai
khoang do khong duoc nap vao ClockSync va khong duoc dung anh xa dong ho
MCU cho chinh no.

Khi bo mau thi KHONG cap nhat moc: lay mau rac lam moc se lam moi mau
tot ke tiep cung bi coi la rac.
2026-09-21 15:44:43 +07:00
trung09122002
9c438a6b27 mcu+odom: chan anh xa dong ho vo nghia; lui 1.5 chu ky de con kep duoc
Tren robot: TRUOT 24 -> 5, [tho:P] 17 -> 1, T do duoc = 0.1002 s. Hai
viec con lai, ca hai deu lo ra so cu the.

1. ClockSync cho thoi diem lech -29.1 GIAY so voi luc nhan duoc dong.
   Do khong phai sai so ma la vo nghia: mot mau vua den thi thoi diem
   cua no phai cach t_recv dung do tre mot chieu, tuc vai ms. ready()
   bat ngay khi co 2 mau, va fit tu 2 diem cach nhau mot chu ky IMU thi
   ra bat cu gi.

   Them kiem tinh hop ly truoc khi tin: lech qua 1 giay thi bo, dung
   dong ho host, va canh bao co in do lon. Nguong 1 s rat rong so voi
   vai ms that -- co y, no chi de bat cai vo nghia.

2. [tho:G] 9 lan: t_ref = stamp - T co tuoi dung bang T, trong khi mau
   gyro moi nhat co tuoi bat ky trong [0, T]. Mot mau den tre chut la
   t_ref roi ra SAU mau moi nhat va het kep duoc.

   Lui 1.5 chu ky thay vi 1: t_ref nam giua hai mau moi nhat trong moi
   truong hop binh thuong. Cai gia la phat hien truot tre them ~50 ms,
   khong dang ke voi mot tin hieu chi de nang covariance. Phep so van
   dung vi ca hai ben deu lay tai t_ref.
2026-09-21 15:41:07 +07:00
trung09122002
664c9a13c9 odom: cu nhay dau thoi gian gyro thi XOA lich su, khong bo mau
Ban truoc lam te hon: TRUOT tang tu 2 len 24 tren robot that.

Bo loc chong nhay LUI ma khong nghi toi cu nhay TIEN. Chi can MOT dau
thoi gian nhay len tuong lai la `prev.t` nam o tuong lai vinh vien, moi
mau sau deu "cu hon", deu bi bo, va lich su khong bao gio dung lai duoc.
Trieu chung do duoc: [tho:P] o 17 dong dbg -- tuc duoi 8 mau trong lich
su suot ca phien -- nen viec so cung bang thong khong chay lan nao.

Mot mau lech thu tu khong phai rac, no la dau hieu GOC THOI GIAN DA DOI.
Co it nhat mot cho chac chan sinh ra no: luc ClockSync chuyen tu "chua
san sang" (dong ho host) sang "san sang" (dong ho MCU), hai goc khac
nhau nen co mot buoc nhay va khong ai bao dam no nhay ve phia nao.

Xoa lich su roi dung lai tu mau do: mat ~1 s du lieu thay vi mat vinh
vien. Them canh bao co in ra DO LON cu nhay, va test hoi quy bom mot cu
nhay 5 giay roi doi lich su phai phuc hoi.

Dong dbg them "T=<chu ky>" de thay suc khoe lich su tu ben ngoai.
2026-09-21 15:36:47 +07:00
trung09122002
ecff9cf7b8 odom: noi ly do khi lui ve so tho, va bo mau gyro nhay lui
Tren robot: TRUOT 7 -> 2 sau khi so cung bang thong. Nhung "[tho]" hien
o 4/5 dong dbg cuoi -- viec so cung bang thong dang thuong xuyen khong
chay tren robot, trong khi trong test thi chay.

Mot chu "[tho]" tron khong du de truy: ba nhanh that bai can ba cach sua
khac han nhau. Gio in ro [tho:P] (chua do duoc chu ky gyro), [tho:E]
(thieu mau encoder trong cua so), [tho:G] (khong co mau gyro hai ben).

Va bit mot loi that: lich su gyro PHAI don dieu vi ca GyroAt() lan
GyroPeriodSec() gia dinh the, nhung khong ai bao dam dieu do.
mcu_bridge dung ClockSync, ma ClockSync fit lai sau MOI mau; voi
t_send = t_recv thi moi RTT bang 0 nen keep_best nhat bua 16 mau va
offset nhay vai ms moi lan fit -- du de dau thoi gian ke tiep roi LUI so
voi mau truoc. Mau lui lai lam phep tim cap kep that bai IM LANG roi lui
ve so tho, dung trieu chung dang thay.

Bo mau do khoi lich su va dem vao stats_.gyro_out_of_order. Dong dbg
hien "[lui]" khi bo dem khac 0, de lan chay toi noi duoc day co phai
nguyen nhan hay khong thay vi doan tiep.
2026-09-21 15:32:47 +07:00
trung09122002
f91b755776 odom: so gyro voi encoder cung BANG THONG, khong chi cung thoi diem
Sau khi dinh thoi da dung han (wheel_odom/lag bao 0 ms sau khi dat
mcu.imu_lag_sec = 0.08), tren robot van con 7 lan bao TRUOT BANH. Doc
dau thi khong phai truot: 5 trong 7 lan encoder doc IT hon gyro, ma
truot lam encoder doc NHIEU hon su that.

Nguyen nhan la khac biet bang thong. WT61PC o che do 10 Hz bao TRUNG
BINH tren cua so 100 ms; encoder bao tuc thoi tren 20 ms. Luc robot doi
toc do quay thi hai thu lech nhau ma khong ben nao sai, va dich dau thoi
gian khong chua duoc -- no can chinh TAM cua so, khong can chinh do rong.

Sua: lay trung binh encoder tren dung cua so cua gyro roi moi so. Chu ky
gyro DO tu lich su chu khong khai bao trong config -- no phu thuoc
firmware va che do cam bien, va da doi mot lan roi.

Cai gia: trung binh hoa lam mo truot that ngan hon mot chu ky gyro, va
lam viec phat hien tre them chung ay. Co test rieng cho chuyen do
(TruotTHATVanBatDuocSauKhiTrungBinhHoa) vi mot bo phat hien truot da bi
lam mo qua tay con te hon la khong co: no tao cam giac an toan.

Test con loi ra mot bug that trong GyroAt(): dieu kien bien dung `>=`
nen khi `t` TRUNG DUNG dau thoi gian cua mau bien thi require_bracket tu
choi -- trong khi do la truong hop tot nhat, gia tri co san chinh xac.
Gyro 10 Hz voi encoder 50 Hz thi cu 5 lan lai trung mot lan: do duoc
59/199 lan phai lui ve so tho, va chinh chung sinh ra bao dong gia
0.4667 rad/s = do doc nhan tron mot chu ky gyro.

Them stats_.slip_coarse_updates de con thay duoc chuyen do tu ben ngoai,
tren robot that chu khong chi trong test.
2026-09-21 15:27:39 +07:00
trung09122002
f2a17b8b3c clock_sync: doi goc truoc khi fit -- triet tieu lam skew ra 0.000318
Do tren robot that sau khi bat nhanh expect_timestamps:

  clock_sync: skew bat thuong (0.000318103, lech -999682 ppm)

Khong phai thach anh te. Fit hoi quy chay tren so THO, ma hai truc lech
nhau chin bac do lon: host_s la thoi gian Unix (~1.8e9) con mcu_s la
giay tu luc MCU khoi dong (~vai tram). Voi mau trai vai giay thi n*sxy
va sx*sy deu co do lon ~4e9 trong khi HIEU that chi ~1e-2 -- double giu
15-16 chu so nen phan tin hieu bi nuot trong phep tru.

Hau qua im lang: ClockSync tu choi moi ket qua fit (dung), ve skew = 1.0
va o nguyen day. Nhin tu ben ngoai thi "skew = 1.0 vi dong ho tot" va
"skew = 1.0 vi khong fit noi" y het nhau.

Doi goc ve trung binh: ket qua khong doi ve toan hoc, nhung phep tru
khong con triet tieu. Test moi cho 21 ppb -- gioi han cua double o do
lon 1.79e9, tot hon truoc 3e7 lan.

mcu_bridge: in skew dinh ky thay vi mot lan. ready() bat ngay khi co 2
mau (68 ms o 10 Hz), nen log mot lan la in dung con so vo nghia nhat roi
im -- da bao "skew 0 ppm" trong khi fit dang bi tu choi lien tuc.

Cap nhat khoi chu thich dau mcu_bridge.cc: no van mo ta firmware cu la
cai duy nhat ton tai.
2026-09-21 15:18:05 +07:00
trung09122002
9eef4fbe13 mcu: firmware phat dau thoi gian; host doc qua ClockSync
Do tre 80 ms cua IMU da truy ra goc trong firmware ESP32 cua base_kit:

- WT61PC noi ESP32 o 9600 baud. 33 byte moi mau = 34 ms tren day, va
  tran tan so la 960/33 = 29 Hz.
- main.c khong he goi modifyFrequency() nen cam bien chay o toc do luu
  san. Do duoc: 10 Hz (50 dong Gyro / 5 s). Tuoi mau trung binh 50 ms.
- 34 + 50 = 84 ms, khop voi 80 ms may do bao.

Phia host cua base_kit (imu_ros_node.cpp) dong dau bang dong ho ROS luc
doc duoc dong -- y het mcu_bridge cu, khong sua duoc gi. Nhung firmware
thi sua duoc.

firmware/imu_uart/ (moi, nhung tu base_kit):
- dong dau esp_timer_get_time() ngay khi khung gyro qua checksum
- phat `I,<micros>,...` theo mcu_protocol.h, rad/s va m/s^2
- 10 -> 20 Hz. Khong len nua: cam bien van gui ca 3 khung nen 9600 baud
  chi cho toi 29 Hz, va khong nang baud cam bien vi thanh ghi 0x04
  khong co trong thu vien DFRobot -- doan sai la cam bien cam han.
- bo khung Angle: khong ai doc imu.orientation trong libs/ va app/

Firmware vao repo nay chu khong o base_kit vi mcu_protocol.h tu nhan la
DAC TA ma firmware phai khop. Da thay cai gia cua viec de roi: base_kit
nam trong .gitignore, va ban tren may dev co src/hardware/IMU_uart con
ban tren Jetson thi khong -- hai may lech nhau tu luc nao khong ro.

mcu_bridge: nhanh expect_timestamps dung ParseMcuLine + McuTimeUnwrapper
+ ClockSync. Chua co ping/pong nen t_send = t_recv: offset lech dung do
tre mot chieu cua USB (co ms), con skew va viec khu jitter van dung vi
chung den tu fit tuyen tinh. Phan hang so con lai gop vao imu_lag_sec.

Nhanh text cu giu nguyen, mac dinh van la no.

Them test cho mối noi firmware <-> dac ta, trong do co bay doi don vi
hai lan: ban ghi I la rad/s san, nhanh text cu moi phai nhan deg2rad.
2026-09-21 14:36:05 +07:00
trung09122002
eb42f08e00 odom: so gyro voi encoder cung thoi diem; them may do do tre IMU
Canh bao TRUOT BANH khong phai truot. Bon lan bao deu roi dung luc robot
vao/ra cua, lech 0.20-0.22 rad/s = dung bang slip_threshold. Hai trong
bon lan encoder doc IT hon gyro, ma truot lam encoder doc NHIEU hon su
that -- truot khong tao ra duoc dau do.

Do la lech dau thoi gian. Update() so omega_encoder voi gyro_z_ MOI
NHAT, hai thoi diem vat ly khac nhau; luc robot doi toc do quay thi sai
so la alpha * lech_t.

Da loai hai gia thuyet kia bang so do: dung yen 3054 mau -> trung binh
-8.1e-06, gyro khong co bias. Quay deu omega 0.68 (gap doi luc bao
truot) -> lech chi +-0.02, nen 16384 count/vong dung trong 2%.

Sua:
- mcu_bridge tru mcu.imu_lag_sec vao stamp NGAY TAI NGUON, de EkfSe2
  cung duoc sua chu khong rieng wheel_odom.
- wheel_odom dem lich su gyro, noi suy ve dung stamp encoder.
- them estimated_imu_lag_sec(): khop tau lam phuong sai (enc - gyro)
  nho nhat, luoi -100..+200 ms.

May do danh gia LUI 0.3 s chu khong tai stamp: tai stamp thi gyro o
stamp+tau voi tau>0 nam o tuong lai cua lich su, khong kep duoc, va cuc
tieu luon roi ve phia am. Bom do tre 0/50/100 ms deu bao -10 ms cho toi
khi sua. Test moi tim lai duoc dung 0/50/100/-50 ms.

lidar: xac nhan 178.75 dung -- tam quat mu ve 180.0.
2026-09-21 10:50:37 +07:00
trung09122002
51a670b721 update 2026-09-21 10:32:41 +07:00
trung09122002
2264903ce3 odom: log lech omega khong loc nguong; lidar offset 178.75
Canh bao truot chi in khi |lech| > 0.20 nen moi dong log deu nam sat
nguong -- cum quanh 0.20 la do NGUONG, khong doc duoc gi. Them dong
INFO throttle 5 s in enc/gyro/lech va trung binh cong don, khong loc.

Tach duoc ba gia thuyet: counts_per_rev sai -> lech ti le omega; gyro
bias -> trung binh khac 0 khi robot dung yen; lech dau thoi gian ->
lech ti le dao ham omega (MCU khong phat timestamp nen kha nang that).

Hai mau do duoc: gyro doi 5 lan ma lech dung yen 0.2017/0.2044 -- lech
CONG chu khong phai ti le, nen 16384 count/vong nhieu kha nang dung.

lidar: ReportBlindSector bao tam quat mu o -178.75 do suot 6/6 lan,
rong 89.75-90.25 do. Ga lech 1.25 do = 11 cm o 5 m.
2026-09-21 10:30:59 +07:00
trung09122002
641db2e914 update 2026-09-21 10:23:51 +07:00
trung09122002
dea92c46d2 update 2026-09-21 10:13:32 +07:00
trung09122002
84369b7314 update 2026-09-21 10:02:33 +07:00
trung09122002
2b3bec37eb update 2026-09-21 09:53:31 +07:00
192 changed files with 45016 additions and 1300 deletions

8
.gitignore vendored
View File

@@ -17,9 +17,17 @@ resources/records/*
!resources/records/.keep !resources/records/.keep
resources/maps/* resources/maps/*
!resources/maps/.keep !resources/maps/.keep
# Mo hinh VPR: ONNX ~111 MB + engine TensorRT rieng tung may -- sinh bang tools/vpr_export_onnx.py
resources/vpr/*
!resources/vpr/.keep
test/data/*.vsr test/data/*.vsr
# Log chay + anh bao cao -- nang, rieng tung may, khong commit
logs/
report/
*.swp *.swp
__pycache__/
.vscode/ .vscode/
.idea/ .idea/
.DS_Store .DS_Store

View File

@@ -137,8 +137,14 @@ install(DIRECTORY configuration_files/
DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/vslam/configuration_files DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/vslam/configuration_files
FILES_MATCHING PATTERN "*.yaml" PATTERN "*.dcf") FILES_MATCHING PATTERN "*.yaml" PATTERN "*.dcf")
# ⚠️ *.db bi LOAI: tu khi `database_path` tuong doi giai ve resources/maps,
# thu muc nay chua ban do da quet (tram MB toi vai GB). `.keep` van duoc cai
# nen thu muc dich ton tai san va EnsureParentDir khong phai chay o ban cai.
install(DIRECTORY resources/ install(DIRECTORY resources/
DESTINATION ${CMAKE_INSTALL_LOCALSTATEDIR}/lib/vslam/resources) DESTINATION ${CMAKE_INSTALL_LOCALSTATEDIR}/lib/vslam/resources
PATTERN "*.db" EXCLUDE
PATTERN "*.db-journal" EXCLUDE
PATTERN "*.db-wal" EXCLUDE)
if(VSLAM_ENABLE_CPACK) if(VSLAM_ENABLE_CPACK)
include(vslam_cpack) include(vslam_cpack)

View File

@@ -42,8 +42,7 @@
"cacheVariables": { "cacheVariables": {
"CMAKE_BUILD_TYPE": "Release", "CMAKE_BUILD_TYPE": "Release",
"CMAKE_PREFIX_PATH": "/opt/vslam", "CMAKE_PREFIX_PATH": "/opt/vslam",
"CMAKE_INSTALL_PREFIX": "/opt/vslam", "CMAKE_INSTALL_PREFIX": "/opt/vslam"
"VSLAM_ENABLE_CPACK": "ON"
} }
} }
], ],

0
KHONG Normal file
View File

View File

@@ -14,7 +14,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
- ROS distribution: none. No `package.xml`, no `setup.py`, no ament/catkin anywhere. ROS only appears as data-format compatibility (map_server `.yaml`/`.pgm`, REP-103 frame conventions) and as the reference implementation being replaced. - ROS distribution: none. No `package.xml`, no `setup.py`, no ament/catkin anywhere. ROS only appears as data-format compatibility (map_server `.yaml`/`.pgm`, REP-103 frame conventions) and as the reference implementation being replaced.
- ROS variant: N/A - ROS variant: N/A
- Operating system: target Ubuntu 22.04 arm64 on Jetson AGX (README.md:4). Dev host is x86 (CMakeLists.txt:54-88, CMakePresets.json `dev`). - Operating system: target Ubuntu 22.04 arm64 on Jetson AGX (README.md:4). Dev host is x86 (CMakeLists.txt:54-88, CMakePresets.json `dev`).
- Build system: CMake >= 3.16, C++17, CMakePresets.json v3 (presets `dev`, `asan`, `tsan`, `jetson`). Optional CPack DEB via `VSLAM_ENABLE_CPACK` (cmake/vslam_cpack). - Build system: CMake >= 3.16, C++17, CMakePresets.json v3 (presets `dev`, `asan`, `tsan`, `jetson`). CPack is **not wired**: `VSLAM_ENABLE_CPACK` exists (default OFF) but `cmake/vslam_cpack.cmake` does not exist, so turning it on fails configure. The jetson preset no longer requests it (removed 2026-09-23).
- Main languages: C++17 (libs/, app/, tools/, test/), JavaScript (libs/vslam_web/www/, test/www/), Python 3 (tools/gen_model_colors.py, test/gen_teleop_vectors.py), Bash (tools/*.sh) - Main languages: C++17 (libs/, app/, tools/, test/), JavaScript (libs/vslam_web/www/, test/www/), Python 3 (tools/gen_model_colors.py, test/gen_teleop_vectors.py), Bash (tools/*.sh)
- Simulation stack: in-repo `vslam_sim` library — replaces Gazebo. Reads Gazebo `.world` files directly (mesh rasterized to occupancy grid + meshes shipped to 3D web view) or ROS map_server `.yaml` + `.pgm` (README.md:100-186). - Simulation stack: in-repo `vslam_sim` library — replaces Gazebo. Reads Gazebo `.world` files directly (mesh rasterized to occupancy grid + meshes shipped to 3D web view) or ROS map_server `.yaml` + `.pgm` (README.md:100-186).
@@ -39,30 +39,31 @@ Use this file for verified target-repository facts only. Keep unknown values as
- Main nodes: one process — `vslam_node` (`build/app/vslam_node`). Owns all threads and all Channels. Source must be chosen explicitly, no default: `--sim` | `--replay FILE` | `--live` | `--check` (app/src/main.cc:39-69, docs/RUNTIME.md:1-20). - Main nodes: one process — `vslam_node` (`build/app/vslam_node`). Owns all threads and all Channels. Source must be chosen explicitly, no default: `--sim` | `--replay FILE` | `--live` | `--check` (app/src/main.cc:39-69, docs/RUNTIME.md:1-20).
- Tools: `vslam_record`, `vslam_replay`, `vslam_sim_run`, `vslam_slam_bench`, `vslam_web_demo`, `vslam_world_export`, `vslam_lidar_probe`, `probe_rtabmap` - Tools: `vslam_record`, `vslam_replay`, `vslam_sim_run`, `vslam_slam_bench`, `vslam_web_demo`, `vslam_world_export`, `vslam_lidar_probe`, `probe_rtabmap`
- Topics: none (no middleware). In-process `Channel<T>` (libs/vslam_common/include/vslam/channel.h) replaces pub/sub. External surface is HTTP/WebSocket on port 8080 — e.g. `GET /api/world.bin` (README.md:133-135); token auth is asymmetric by design: engage e-stop needs no token, release e-stop / bumper reset require one (configuration_files/system.yaml `web.auth_token`). - Topics: none (no middleware). In-process `Channel<T>` (libs/vslam_common/include/vslam/channel.h) replaces pub/sub. External surface is HTTP/WebSocket on port 8080 — e.g. `GET /api/world.bin` (README.md:133-135). Binary WS frame types: 1 scan, 2 cloud, 3 map_full, 4 **retired** (was map_patch, removed 2026-09-23), 5 path, 6 world_map, 7 voxel_full (chunked), 8 voxel_delta. Types 7/8 carry the accumulated 3D map as a voxel-hashed index set at 0.05 m; the browser renders it as a POINT CLOUD, not as boxes; token auth is asymmetric by design: engage e-stop needs no token, release e-stop / bumper reset require one (configuration_files/system.yaml `web.auth_token`).
- Services / Actions: none. - Services / Actions: none.
- Parameters: YAML only, one file per library. Selected verified values — - Parameters: YAML only, one file per library. Selected verified values —
- `robot.yaml`: wheel_radius 0.0865 m, wheel_separation 0.400 m, robot_radius 0.24, max_linear 0.35 m/s, max_angular 0.80 rad/s, accel_limit 0.30 m/s², base.cmd_timeout 0.30 s - `robot.yaml`: wheel_radius 0.0865 m, wheel_separation 0.400 m, robot_radius 0.24, max_linear 0.35 m/s, max_angular 0.80 rad/s, accel_limit 0.30 m/s², base.cmd_timeout 0.30 s
- `safety.yaml`: scan stop_distance 0.35 m, slow_distance 0.80 m, front_angle 0.5 rad, min_front_rays 20, cliff_hold 3.0 s, sensor_timeout 1.0 s, cmd_timeout 0.5 s (must stay > base.cmd_timeout), bumper escape_linear 0.10 / escape_angular 0.4 - `safety.yaml`: scan stop_distance 0.35 m, slow_distance 0.80 m, front_angle 0.5 rad, min_front_rays 20, cliff_hold 3.0 s, sensor_timeout 1.0 s, cmd_timeout 0.5 s (must stay > base.cmd_timeout), bumper escape_linear 0.10 / escape_angular 0.4
- `pipeline.yaml`: depth_filter 0.22–4.0 m, voxel 0.03 m, 30 Hz in / 10 Hz out; cliff_detect window 1.00–1.50 m (geometric blind zone from level camera at 0.3935 m) - `pipeline.yaml`: depth_filter 0.22–4.0 m, voxel 0.03 m, 30 Hz in / 10 Hz out; cliff_detect window 1.15–1.70 m (geometric blind zone from level camera at 0.445 m), and `cliff_detect.enabled: false` — cliff detection is currently OFF (pipeline.yaml:100)
- `slam.yaml`: enabled false, mode localization, Reg/Strategy=1 (ICP), Reg/Force3DoF=true, Optimizer/Strategy=1 (g2o), RGBD/NeighborLinkRefining=false, RGBD/ProximityPathMaxNeighbors=30, Rtabmap/DetectionRate=3, Grid/CellSize 0.05 - `slam.yaml`: enabled false, mode localization, Reg/Strategy=1 (ICP), Reg/Force3DoF=true, Optimizer/Strategy=1 (g2o), RGBD/NeighborLinkRefining=false, RGBD/ProximityPathMaxNeighbors=30, Rtabmap/DetectionRate=3, Grid/CellSize 0.05, `camera_3d` (code default false; slam.yaml currently true) is the 3D scanned-cloud switch: true sends depth into RTAB-Map (stored in the DB) and turns on the voxel map, but does NOT touch Grid/* — the grid stays 2D, LiDAR-only. The voxel map is built outside `process()` from each node's depth (cached per node id, max 40 new nodes per export). Changed 2026-09-24: the old Grid/Sensor=2 + Grid/3D=true path raised sim pose error vs ground truth from 0.009 m to 0.06-0.11 m
- `system.yaml`: web port 8080, status/scan 10 Hz, cloud 2 Hz, path 1 Hz, map_rebuild_rate_hz 4.0; thread priorities safety 50 / driver 45 / estimator 40, safety_rate_hz 20 - `system.yaml`: web port 8080, status/scan 10 Hz, cloud 8 Hz, path 1 Hz, map_rebuild_rate_hz 4.0, voxel_chunk_bytes 16384 / voxel_sync_chunks_per_tick 1 (the voxel map has no send-rate knob by design); thread priorities safety 50 / driver 45 / estimator 40, safety_rate_hz 20
- Unknown RTAB-Map keys are a **startup refusal**, not a silent ignore (`BuildRtabmapParams`, slam.yaml:10-16) - Unknown RTAB-Map keys are a **startup refusal**, not a silent ignore (`BuildRtabmapParams`, slam.yaml:10-16)
- Config dir resolution: `$VSLAM_CONFIG_DIR`, else `/etc/vslam/configuration_files`; resources: `$VSLAM_RESOURCE_DIR`, else `/var/lib/vslam/resources` (libs/vslam_common/include/vslam/node_constants.h) - Config dir resolution: `$VSLAM_CONFIG_DIR`, else `/etc/vslam/configuration_files`; resources: `$VSLAM_RESOURCE_DIR`, else `/var/lib/vslam/resources` (libs/vslam_common/include/vslam/node_constants.h)
- Map path resolution (added 2026-09-23): a RELATIVE `slam.database_path` / `--slam-db` resolves against `MapDir()` = `$VSLAM_RESOURCE_DIR/maps`, i.e. `<repo>/resources/maps/` from the source tree. `{stamp}` anywhere in the path expands to `%Y%m%d_%H%M%S` (one value per call). Absolute paths are used as-is; `""` still means a RAM-only DB. The parent directory is created for mapping runs only. All of this lives in `RtabmapSlam::Init`, deliberately NOT on the `--check` path.
- TF frames: own `TransformTree`, no tf2. Tree (node_constants.h:44-56, robot.yaml): - TF frames: own `TransformTree`, no tf2. Tree (node_constants.h:44-56, robot.yaml):
`map -> odom -> base_footprint -> base_link -> {laser_link, imu_link, camera_link}`, `map -> odom -> base_footprint -> base_link -> {laser_link, imu_link, camera_link}`,
`camera_link -> camera_depth_optical_frame | camera_infra1_optical_frame | camera_infra2_optical_frame` `camera_link -> camera_depth_optical_frame | camera_infra1_optical_frame | camera_infra2_optical_frame`
- Three dynamic edges, one writer each: `map->odom` (slam, ~1 Hz), `odom->base_footprint` (EKF, 50 Hz), `base_footprint->base_link` (gravity_align, measured roll/pitch) - Three dynamic edges, one writer each: `map->odom` (slam, ~1 Hz), `odom->base_footprint` (EKF, 50 Hz), `base_footprint->base_link` (gravity_align, measured roll/pitch)
- Static: laser_link [0, 0, 0.13] rpy 0 (mount rotation compensated in driver via `angle_offset_deg: -180`, NOT in TF — do not "fix"); imu_link [0, 0, 0.06]; camera_link [0.095, 0, 0.307] rpy 0 (level, not tilted) = 0.3935 m above floor; optical frames rpy [-pi/2, 0, -pi/2] - Static: laser_link [0, 0, 0.13] rpy 0 (mount rotation compensated in driver via `angle_offset_deg: 178.75`, NOT in TF — do not "fix"); imu_link [0, 0, 0.06]; camera_link rpy 0 (level, not tilted) = **0.445 m** above floor (robot.yaml:100-101); optical frames rpy [-pi/2, 0, -pi/2]
## Sensors And Hardware ## Sensors And Hardware
- Cameras: RealSense D410 (depth + IR, **no RGB** — left IR doubles as the "rgb" channel for SLAM). 640x480 @ 30 fps, `decimate: 2` with CameraInfo still carrying full-res K (consumers must compensate). Driver `realsense_driver.cc`, built only with `-DVSLAM_WITH_REALSENSE=ON`; sensors.yaml states it is **not yet verified against real hardware**. - Cameras: RealSense D410 (depth + IR, **no RGB** — left IR doubles as the "rgb" channel for SLAM). 640x480 @ 30 fps, `decimate: 2` with CameraInfo still carrying full-res K (consumers must compensate). Driver `realsense_driver.cc`, built only with `-DVSLAM_WITH_REALSENSE=ON`; sensors.yaml states it is **not yet verified against real hardware**.
- LiDAR: LakiBeam 1L over UDP, bind 0.0.0.0:2368, expected 25 Hz, 270° FOV, range 0.05–40.0 m. Angle convention `theta = (flip ? -alpha : alpha) + angle_offset_deg` with `angle_offset_deg: -180`, `angle_flip: false` (derived twice independently in sensors.yaml:20-60). - LiDAR: LakiBeam 1L over UDP, bind 0.0.0.0:2368, expected 25 Hz, 270° FOV, range 0.05–40.0 m. Angle convention `theta = (flip ? -alpha : alpha) + angle_offset_deg` with `angle_offset_deg: 178.75`, `angle_flip: true` (sensors.yaml:52-53; the 1.25 deg off 180 is a MEASURED mount error, and the driver logs a suggestion line every 10 s that reads as a no-op when the value is already right).
- IMU: WT61PC behind an ESP32-S3 MCU on `/dev/ttyACM0` @ 115200 baud, expected 200 Hz. `ClockSync` fits MCU `micros()` to host clock; `McuTimeUnwrapper` is mandatory (uint32 wraps every 71.58 min). - IMU: WT61PC wired straight to a UART (USB-FTDI adapter, `/dev/imu`, `mcu.protocol: wt61pc`), 115200 baud / 200 Hz (stored in the sensor 2026-10-06; factory default 9600 baud / 10 Hz), FTDI latency_timer 1 ms via `configuration_files/udev/99-imu.rules`. Stamped from the host clock minus `imu_lag_sec` (no `ClockSync`). The older ESP32-S3 path (`mcu.protocol: esp`, `/dev/ttyACM0`, `ClockSync`, `McuTimeUnwrapper` for uint32 `micros()` wrap every 71.58 min) is still supported.
- Compute target: Jetson AGX (arm64); jetson preset uses `CMAKE_PREFIX_PATH=/opt/vslam` and `CMAKE_INSTALL_PREFIX=/opt/vslam`, deps built from source (tools/build_deps.sh referenced by CMakePresets.json:40 — **script not present in repo**). - Compute target: Jetson AGX (arm64); jetson preset uses `CMAKE_PREFIX_PATH=/opt/vslam` and `CMAKE_INSTALL_PREFIX=/opt/vslam`, deps built from source (tools/build_deps.sh referenced by CMakePresets.json:40 — **script not present in repo**).
- Accelerators: none used. No CUDA/TensorRT/OpenCL in the build; all processing is CPU. - Accelerators: none used. No CUDA/TensorRT/OpenCL in the build; all processing is CPU.
- Actuators or robot base: ZLAC8015D dual motor driver over **CANopen on `can0`, node id 1** (not serial), via `liblely-coapp`, gated by `-DVSLAM_WITH_CANOPEN=ON`. DCF at `configuration_files/master.dcf`, path resolved relative to the config dir. `encoder_counts_per_rev: 0` = fall back to 16384 (4096 "wire" x4); the x4 factor is flagged unverified. - Actuators or robot base: ZLAC8015D dual motor driver over **CANopen on `can0`, node id 1** (not serial), via `liblely-coapp`, gated by `-DVSLAM_WITH_CANOPEN=ON`. DCF at `configuration_files/master.dcf`, path resolved relative to the config dir. `encoder_counts_per_rev: 0` = fall back to 16384 (4096 "wire" x4); the x4 factor is **confirmed** by field data (2026-09-23, see Verification Notes).
## CV And AI ## CV And AI
@@ -70,7 +71,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
- Model formats: N/A - Model formats: N/A
- Inference runtimes: N/A. Geometric CV only: RTAB-Map (ICP/g2o) + OpenCV + PCL. - Inference runtimes: N/A. Geometric CV only: RTAB-Map (ICP/g2o) + OpenCV + PCL.
- Preprocessing: depth -> `depth_to_cloud` -> `depth_filter` (range gate 0.22–4.0 m, 0.03 m voxel, rate limit to 10 Hz) -> `gravity_align` (complementary filter alpha 0.98, own-acceleration subtraction from odometry) -> cloud in `base_footprint`. Runs inline on the camera thread, not as separate stages (docs/PERCEPTION.md). - Preprocessing: depth -> `depth_to_cloud` -> `depth_filter` (range gate 0.22–4.0 m, 0.03 m voxel, rate limit to 10 Hz) -> `gravity_align` (complementary filter alpha 0.98, own-acceleration subtraction from odometry) -> cloud in `base_footprint`. Runs inline on the camera thread, not as separate stages (docs/PERCEPTION.md).
- Postprocessing: `cliff_detect` (self-leveling ground fit, window 1.00–1.50 m, fail-safe after 1.0 s) -> cliff flags + edge cloud; SLAM outputs occupancy grid exported via `occupancy_export`, RLE-compressed for the web UI. - Postprocessing: `cliff_detect` (self-leveling ground fit, window 1.15–1.70 m, fail-safe after 1.0 s; **currently disabled** in pipeline.yaml) -> cliff flags + edge cloud; SLAM outputs occupancy grid exported via `occupancy_export`, RLE-compressed for the web UI.
- Calibration files: none in the repo. Camera intrinsics come from the device at runtime; `fx = 595.914 @ 640x480` appears only inside comments as the basis for FOV math. Extrinsics live in `robot.yaml` (there is no URDF — deliberately, robot.yaml:1-20). - Calibration files: none in the repo. Camera intrinsics come from the device at runtime; `fx = 595.914 @ 640x480` appears only inside comments as the basis for FOV math. Extrinsics live in `robot.yaml` (there is no URDF — deliberately, robot.yaml:1-20).
## Commands ## Commands
@@ -94,17 +95,20 @@ All commands below are transcribed from README.md / CMakePresets.json / docs —
## Verification Notes ## Verification Notes
- Last inspected by Claude Code: 2026-09-20, branch `master`, HEAD `4ea3268` - Last inspected by Claude Code: 2026-09-23, branch `master`, HEAD `dbcbf84` (plus the uncommitted 3D-voxel-map work)
- Verified files: CMakeLists.txt, CMakePresets.json, libs/CMakeLists.txt, app/CMakeLists.txt, all `libs/*/CMakeLists.txt` (dependency greps), test/CMakeLists.txt, tools/CMakeLists.txt, all six `configuration_files/*.yaml`, app/src/main.cc, app/src/runtime.cc (source-selection path), libs/vslam_common/include/vslam/node_constants.h, docs/RUNTIME.md, docs/PERCEPTION.md (head), docs/SLAM.md (head), docs/REGRESSION.md (head), README.md:1-260, tools/regress.sh (head), tools/pre-push, libs/vslam_drivers/thirdparty/PROVENANCE.md, .gitignore, build/CMakeCache.txt - Verified files: CMakeLists.txt, CMakePresets.json, libs/CMakeLists.txt, app/CMakeLists.txt, all `libs/*/CMakeLists.txt` (dependency greps), test/CMakeLists.txt, tools/CMakeLists.txt, all six `configuration_files/*.yaml`, app/src/main.cc, app/src/runtime.cc (source-selection path), libs/vslam_common/include/vslam/node_constants.h, docs/RUNTIME.md, docs/PERCEPTION.md (head), docs/SLAM.md (head), docs/REGRESSION.md (head), README.md:1-260, tools/regress.sh (head), tools/pre-push, libs/vslam_drivers/thirdparty/PROVENANCE.md, .gitignore, build/CMakeCache.txt
- Not verified: no build, test, or run command was executed. Test counts (37) and regression scenario counts (12) are README claims; `test/expected/` does contain 12 JSON baselines. - Not verified: no C++ build, ctest, or regression run was executed from this session (the repo forbids it — see CLAUDE.md build handoff). The JS tests under `test/www/` WERE run with node and pass. Test counts (37) and regression scenario counts (12) are README claims; `test/expected/` does contain 12 JSON baselines.
- Field data, 2026-09-23 live mapping run on the robot (gamepad + `--live --slam`): gamepad teleop, ClockSync, LiDAR blind-sector check and SLAM map growth all behaved; occupied cells 202 -> 8605 over 3.5 min.
- Open questions: - Open questions:
1. `sensors.yaml` `sector_masks` (+/-118 deg) lost their geometric basis when the LiDAR moved to `x = 0.0`. The file says they **must be re-measured before safety is enabled**. Still unresolved. 1. `sensors.yaml` `sector_masks` (+/-118 deg) lost their geometric basis when the LiDAR moved to `x = 0.0`. The file says they **must be re-measured before safety is enabled**. Still unresolved.
2. `encoder_counts_per_rev: 0` -> default 16384 assumes a x4 quadrature factor that `can_help.pdf` does not confirm. Wrong factor = odometry off by 4x. Two-minute measurement procedure is in sensors.yaml. 2. ~~`encoder_counts_per_rev` x4 factor~~ — **ANSWERED 2026-09-23.** On the real robot, encoder and gyro agree to 0.12% over 7671 samples (`enc 0.823336` vs `gyro 0.824332`, steady turn; mean bias -0.0015 rad/s). A wrong quadrature factor would show as a 4x or 0.25x ratio, so 16384 is right. The wheel-lift measurement in sensors.yaml is no longer needed.
3. All EKF and wheel-odometry covariances are datasheet estimates. UMBmark and allan_variance have not been run on this robot (robot.yaml, pipeline.yaml). 3. All EKF and wheel-odometry covariances are datasheet estimates. UMBmark and allan_variance have not been run on this robot (robot.yaml, pipeline.yaml).
4. No clock-synchronization path exists for the CANopen base: `EncoderReading` stamps are host-clock-at-SDO-read. `ClockSync` only bridges the serial MCU. 4. No clock-synchronization path exists for the CANopen base: `EncoderReading` stamps are host-clock-at-SDO-read. `ClockSync` only bridges the serial MCU.
5. RealSense driver unverified on real hardware; `RS2_OPTION_GLOBAL_TIME_ENABLED` on FW 5.17.0.10 unchecked (falls back to TIME_OF_ARRIVAL, a few ms worse). 5. RealSense driver unverified on real hardware; `RS2_OPTION_GLOBAL_TIME_ENABLED` on FW 5.17.0.10 unchecked (falls back to TIME_OF_ARRIVAL, a few ms worse).
6. `safety.yaml` cites `docs/HARDWARE.md` for the hardware motor-cut requirement, but that file does not exist in `docs/`. 6. `safety.yaml` cites `docs/HARDWARE.md` for the hardware motor-cut requirement, but that file does not exist in `docs/`.
7. `CMakePresets.json` jetson preset cites `tools/build_deps.sh`; that script is not in the repo. 7. `CMakePresets.json` jetson preset cites `tools/build_deps.sh`; that script is not in the repo. (The preset's `VSLAM_ENABLE_CPACK: ON` was removed 2026-09-23 — it pointed at a `cmake/vslam_cpack.cmake` that never existed and broke every Jetson configure.)
8. `docs/RUNTIME.md:8` says the `--live` driver is "CHUA viet" (not written), but `app/src/runtime.cc:137-191` wires live LiDAR, MCU, base, and camera behind `VSLAM_HAVE_CANOPEN`. One of the two is stale — likely the doc. 8. `docs/RUNTIME.md:8` says the `--live` driver is "CHUA viet" (not written), but `app/src/runtime.cc:137-191` wires live LiDAR, MCU, base, and camera behind `VSLAM_HAVE_CANOPEN`. One of the two is stale — likely the doc.
9. `RGBD/NeighborLinkRefining=false` was tuned against **simulated** odometry (exact to ground truth). Real-robot odometry drifts 1-2%, where ICP link refinement may help. Re-measure on hardware. 9. `RGBD/NeighborLinkRefining=false` was tuned against **simulated** odometry (exact to ground truth). Real-robot odometry drifts 1-2%, where ICP link refinement may help. Re-measure on hardware.
10. Real-hardware symmetric wheel slip is undetectable by the current `|omega_encoder - gyro_z|` test (0 events, 13.29% error in the `slip_sym` regression scenario). 10. Real-hardware symmetric wheel slip is undetectable by the current `|omega_encoder - gyro_z|` test (0 events, 13.29% error in the `slip_sym` regression scenario).
11. `imu_lag_sec` was re-measured 2026-09-23 and moved 0.08 -> 0.07 (estimator resolution is one 10 ms bin). The next live run must report `wheel_odom/lag: tot nhat ~0 ms`; if it still says -10 ms the model has bottomed out and must not be tuned further.
12. The 3D scanned cloud (`camera_3d: true`) produced frames in sim on 2026-09-24 with the OLD Grid/3D path; the depth-per-node path that replaced it is not yet run (sim or hardware). Not on hardware at all. Three numbers in it are reasoned estimates, not measurements: `voxel.emit_size_m` 0.05, `voxel.delta_max_ratio` 0.35, and the 300k `max_cells` ceiling. The full-sync burst (2 x 32 kB x 10 Hz = 655 kB/s) also exceeds the documented 120 kB/s UI budget for 1-3 s per joining client — deliberate, but unmeasured on Jetson WiFi. Also unmeasured: RAM/CPU cost of `Grid/3D=true` with ray tracing left ON (kept on deliberately — turning it off empties the 2D free-space map).

1038
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -38,6 +38,11 @@ endif()
if(VSLAM_WITH_REALSENSE) if(VSLAM_WITH_REALSENSE)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_REALSENSE=1)
endif() endif()
# Ve camera mo phong bang GPU (--sim-gl). Lib tuy chon, chi may dev co GPU.
if(TARGET vslam_sim_gl)
target_link_libraries(vslam_node PRIVATE vslam_sim_gl)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_SIM_GL=1)
endif()
if(VSLAM_WITH_CANOPEN) if(VSLAM_WITH_CANOPEN)
target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1) target_compile_definitions(vslam_node PRIVATE VSLAM_HAVE_CANOPEN=1)
endif() endif()

View File

@@ -69,7 +69,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
Reject(l, "sensors.yaml lidar", Reject(l, "sensors.yaml lidar",
{"host", "port", "expected_rate_hz", "range_min", "range_max", {"host", "port", "expected_rate_hz", "range_min", "range_max",
"stamp_mismatch_warn", "sector_masks", "stamp_mismatch_warn", "sector_masks",
"angle_offset_deg", "angle_flip"}); "angle_offset_deg", "angle_flip", "filters",
"stamp_offset_sec", "deskew"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->sanitizer.range_min = l.get<double>("range_min", 0.05); out->sanitizer.range_min = l.get<double>("range_min", 0.05);
@@ -94,6 +95,62 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg); l.get<double>("angle_offset_deg", out->lidar_driver.angle_offset_deg);
out->lidar_driver.inverted = out->lidar_driver.inverted =
l.get<bool>("angle_flip", out->lidar_driver.inverted); l.get<bool>("angle_flip", out->lidar_driver.inverted);
// Gio scan so voi odometry va chinh meo -- do tren ban do that, xem
// sensors.yaml.
out->lidar_driver.stamp_offset_sec =
l.get<double>("stamp_offset_sec", out->lidar_driver.stamp_offset_sec);
out->lidar_driver.deskew = l.get<bool>("deskew", out->lidar_driver.deskew);
// --- Bon bo loc scan ---
const ConfigNode ft = l["filters"];
{
const StatusResponse r =
Reject(ft, "sensors.yaml lidar.filters",
{"shadow_enabled", "shadow_min_angle_deg", "shadow_window",
"shadow_min_range_diff", "shadow_max_range",
"shadow_clear_start", "shadow_clear_neighbors",
"intensity_enabled", "intensity_min", "intensity_max",
"intensity_max_range",
"isolated_enabled", "isolated_min_cluster_points",
"isolated_max_range_jump", "isolated_max_range",
"box_enabled", "box_min_x", "box_max_x",
"box_min_y", "box_max_y"});
if (!r.ok()) return r;
}
{
LidarFilterConfig& f = out->lidar_driver.filter;
f.shadow_enabled = ft.get<bool>("shadow_enabled", f.shadow_enabled);
f.shadow_min_angle_deg =
ft.get<double>("shadow_min_angle_deg", f.shadow_min_angle_deg);
f.shadow_window = ft.get<int>("shadow_window", f.shadow_window);
f.shadow_min_range_diff =
ft.get<double>("shadow_min_range_diff", f.shadow_min_range_diff);
f.shadow_max_range = ft.get<double>("shadow_max_range", f.shadow_max_range);
f.shadow_clear_start =
ft.get<bool>("shadow_clear_start", f.shadow_clear_start);
f.shadow_clear_neighbors =
ft.get<int>("shadow_clear_neighbors", f.shadow_clear_neighbors);
f.intensity_enabled = ft.get<bool>("intensity_enabled", f.intensity_enabled);
f.intensity_min = ft.get<double>("intensity_min", f.intensity_min);
f.intensity_max = ft.get<double>("intensity_max", f.intensity_max);
f.intensity_max_range =
ft.get<double>("intensity_max_range", f.intensity_max_range);
f.isolated_enabled = ft.get<bool>("isolated_enabled", f.isolated_enabled);
f.isolated_min_cluster_points =
ft.get<int>("isolated_min_cluster_points", f.isolated_min_cluster_points);
f.isolated_max_range_jump =
ft.get<double>("isolated_max_range_jump", f.isolated_max_range_jump);
f.isolated_max_range =
ft.get<double>("isolated_max_range", f.isolated_max_range);
f.box_enabled = ft.get<bool>("box_enabled", f.box_enabled);
f.box_min_x = ft.get<double>("box_min_x", f.box_min_x);
f.box_max_x = ft.get<double>("box_max_x", f.box_max_x);
f.box_min_y = ft.get<double>("box_min_y", f.box_min_y);
f.box_max_y = ft.get<double>("box_max_y", f.box_max_y);
}
// Sector mask ghi bang DO trong YAML (doc duoc bang mat), dung bang RAD. // Sector mask ghi bang DO trong YAML (doc duoc bang mat), dung bang RAD.
// Doi mot lan o day, khong de moi noi tu doi. // Doi mot lan o day, khong de moi noi tu doi.
@@ -155,15 +212,48 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{ {
const StatusResponse r = const StatusResponse r =
Reject(mc, "sensors.yaml mcu", Reject(mc, "sensors.yaml mcu",
{"port", "baud", "sync_window", "max_skew_warn", {"protocol", "port", "baud", "sync_window", "max_skew_warn",
"expected_imu_rate_hz", "ticks_per_rev"}); "expected_imu_rate_hz", "ticks_per_rev", "imu_lag_sec",
"expect_timestamps"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0); out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0);
// esp = ESP32 + USB-CDC (cach cu). wt61pc = cam bien noi thang UART/USB-FTDI.
// Sai ten thi tu choi, khong doan: chon nham thi IMU im lang.
{
const std::string p = mc.get<std::string>("protocol", "esp");
if (p == "esp") {
out->mcu_driver.protocol = McuProtocol::kEspText;
} else if (p == "wt61pc") {
out->mcu_driver.protocol = McuProtocol::kWt61pc;
} else {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"sensors.yaml mcu.protocol = \"" + p + "\" khong biet. Chon: esp | wt61pc.");
}
}
out->mcu_driver.port = mc.get<std::string>("port", "/dev/ttyACM0"); out->mcu_driver.port = mc.get<std::string>("port", "/dev/ttyACM0");
out->mcu_driver.baud = static_cast<uint32_t>(mc.get<int>("baud", 115200)); out->mcu_driver.baud = static_cast<uint32_t>(mc.get<int>("baud", 115200));
out->mcu_driver.imu_frame_id = kImuFrame; out->mcu_driver.imu_frame_id = kImuFrame;
// true = firmware phat ban ghi theo mcu_protocol.h (co `micros()` cua MCU)
// -> mcu_bridge di nhanh ClockSync. false = ba dong text Acc/Gyro/Angle cu.
// Sai gia tri nay thi KHONG crash: parser cua nhanh kia tu choi moi dong va
// IMU im lang tat -- xem `mcu: khong co IMU moi` trong log wheel_odom.
out->mcu_driver.expect_timestamps = mc.get<bool>("expect_timestamps", false);
out->mcu_driver.imu_lag_sec = mc.get<double>("imu_lag_sec", 0.0);
// Chan tren 0.5 s: lon hon the thi lich su omega (128 mau ~2.5 s) van con
// du, nhung mot con so lon nhu vay chac chan la go nham don vi -- ms thay
// vi giay. Bu nham 200 s thi moi dau thoi gian IMU ve qua khu xa va bo loc
// im lang bo het, khong bao gi.
if (out->mcu_driver.imu_lag_sec < 0.0 ||
out->mcu_driver.imu_lag_sec > 0.5) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"sensors.yaml mcu.imu_lag_sec = " +
std::to_string(out->mcu_driver.imu_lag_sec) +
" nam ngoai [0, 0.5] giay. Don vi la GIAY, khong phai ms.");
}
// ---------- base ---------- // ---------- base ----------
// Muc nay MOI. Encoder va motor di qua CANopen tren can0, khong qua serial // Muc nay MOI. Encoder va motor di qua CANopen tren can0, khong qua serial
@@ -173,7 +263,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
const StatusResponse r = const StatusResponse r =
Reject(b, "sensors.yaml base", Reject(b, "sensors.yaml base",
{"can_channel", "can_node_id", "dcf_path", {"can_channel", "can_node_id", "dcf_path",
"encoder_counts_per_rev"}); "encoder_counts_per_rev", "accel_ramp_ms"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->base_driver.protocol = BaseProtocol::kZlacCanOpen; out->base_driver.protocol = BaseProtocol::kZlacCanOpen;
@@ -193,6 +283,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
} }
out->base_driver.encoder_counts_per_rev = out->base_driver.encoder_counts_per_rev =
static_cast<uint32_t>(b.get<int>("encoder_counts_per_rev", 0)); static_cast<uint32_t>(b.get<int>("encoder_counts_per_rev", 0));
out->base_driver.accel_ramp_ms =
static_cast<uint32_t>(b.get<int>("accel_ramp_ms", 1200));
// Hinh hoc va gioi han SAO tu robot.yaml, khong doc rieng. robot.yaml la // Hinh hoc va gioi han SAO tu robot.yaml, khong doc rieng. robot.yaml la
// nguon duy nhat; mot ban sao trong sensors.yaml se troi khoi no ma khong // nguon duy nhat; mot ban sao trong sensors.yaml se troi khoi no ma khong
@@ -220,7 +312,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{ {
const StatusResponse r = const StatusResponse r =
Reject(e, "pipeline.yaml ekf", Reject(e, "pipeline.yaml ekf",
{"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt"}); {"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt", "gyro_yaw"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x); out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x);
@@ -229,6 +321,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx); out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx);
out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw); out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw);
out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout); out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout);
out->ekf_gyro_yaw = e.get<bool>("gyro_yaw", out->ekf_gyro_yaw);
const ConfigNode d = root["depth_filter"]; const ConfigNode d = root["depth_filter"];
{ {
@@ -489,6 +582,125 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
return StatusResponse::Error(StatusCode::kInvalidArgument, return StatusResponse::Error(StatusCode::kInvalidArgument,
std::string("slam.yaml: ") + e.what()); std::string("slam.yaml: ") + e.what());
} }
// Khoi `voxel:` -- hinh hoc cua ban do 3D. Chi co nghia khi camera_3d bat,
// nhung van doc vo dieu kien de `--check` bat duoc gia tri sai tu truoc.
if (!root["voxel"].IsNull()) {
const ConfigNode v = root["voxel"];
const StatusResponse r =
Reject(v, "slam.yaml voxel",
{"emit_size_m", "z_min", "z_max", "max_cells", "delta_max_ratio",
"obstacle_z_min", "obstacle_z_max", "min_node_hits",
"clear_after_views"});
if (!r.ok()) return r;
out->voxel.emit_size_m = v.get<double>("emit_size_m", out->voxel.emit_size_m);
out->voxel.z_min = v.get<double>("z_min", out->voxel.z_min);
out->voxel.z_max = v.get<double>("z_max", out->voxel.z_max);
out->voxel.max_cells = static_cast<size_t>(
v.get<int>("max_cells", static_cast<int>(out->voxel.max_cells)));
out->voxel.delta_max_ratio =
v.get<double>("delta_max_ratio", out->voxel.delta_max_ratio);
out->voxel.obstacle_z_min =
v.get<double>("obstacle_z_min", out->voxel.obstacle_z_min);
out->voxel.obstacle_z_max =
v.get<double>("obstacle_z_max", out->voxel.obstacle_z_max);
const int hits = v.get<int>("min_node_hits",
static_cast<int>(out->voxel.min_node_hits));
if (hits < 1) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.min_node_hits phai >= 1");
}
out->voxel.min_node_hits = static_cast<size_t>(hits);
const int clear = v.get<int>("clear_after_views",
static_cast<int>(out->voxel.clear_after_views));
if (clear < 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.clear_after_views phai >= 0 (0 = tat)");
}
out->voxel.clear_after_views = static_cast<size_t>(clear);
if (out->voxel.emit_size_m <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.emit_size_m phai > 0");
}
if (out->voxel.z_min >= out->voxel.z_max) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml voxel: z_min phai nho hon z_max");
}
if (out->voxel.max_cells == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml voxel.max_cells phai > 0");
}
if (out->voxel.obstacle_z_min >= out->voxel.obstacle_z_max) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml voxel: obstacle_z_min phai nho hon obstacle_z_max");
}
}
// Khoi `far_loops:` -- vong dong xa luc quet. Vang mat = mac dinh.
if (!root["far_loops"].IsNull()) {
const ConfigNode v = root["far_loops"];
const StatusResponse r =
Reject(v, "slam.yaml far_loops",
{"enabled", "radius_m", "min_graph_gap", "max_corr_m", "max_corr_deg", "period_s"});
if (!r.ok()) return r;
FarLoopsConfig& c = out->far_loops;
c.enabled = v.get<bool>("enabled", c.enabled);
c.radius_m = v.get<double>("radius_m", c.radius_m);
c.min_graph_gap = v.get<int>("min_graph_gap", c.min_graph_gap);
c.max_corr_m = v.get<double>("max_corr_m", c.max_corr_m);
c.max_corr_deg = v.get<double>("max_corr_deg", c.max_corr_deg);
c.period_s = v.get<double>("period_s", c.period_s);
if (c.radius_m <= 0.0 || c.min_graph_gap < 10 || c.max_corr_m <= 0.0 ||
c.max_corr_deg <= 0.0 || c.period_s < 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml far_loops: radius_m > 0, min_graph_gap >= 10, max_corr_m/deg > 0, "
"period_s >= 0");
}
}
// Khoi `slope:` -- di tren doc. Vang mat = tat.
if (!root["slope"].IsNull()) {
const ConfigNode v = root["slope"];
const StatusResponse r = Reject(
v, "slam.yaml slope",
{"enabled", "clamp_deg", "sigma_rel", "sigma_flat", "sigma_anchor", "anchor_radius_m",
"horizontal_odom", "level_scan", "floor_margin_m", "below_ground_m",
"elevation_cell_m", "elevation_radius_m", "elevation_max_depth_m", "depth_stride"});
if (!r.ok()) return r;
SlopeConfig& c = out->slope;
c.enabled = v.get<bool>("enabled", c.enabled);
c.clamp_deg = v.get<double>("clamp_deg", c.clamp_deg);
c.sigma_rel = v.get<double>("sigma_rel", c.sigma_rel);
c.sigma_flat = v.get<double>("sigma_flat", c.sigma_flat);
c.sigma_anchor = v.get<double>("sigma_anchor", c.sigma_anchor);
c.anchor_radius_m = v.get<double>("anchor_radius_m", c.anchor_radius_m);
c.horizontal_odom = v.get<bool>("horizontal_odom", c.horizontal_odom);
c.level_scan = v.get<bool>("level_scan", c.level_scan);
c.floor_margin_m = v.get<double>("floor_margin_m", c.floor_margin_m);
c.below_ground_m = v.get<double>("below_ground_m", c.below_ground_m);
c.elevation_cell_m = v.get<double>("elevation_cell_m", c.elevation_cell_m);
c.elevation_radius_m = v.get<double>("elevation_radius_m", c.elevation_radius_m);
c.elevation_max_depth_m = v.get<double>("elevation_max_depth_m", c.elevation_max_depth_m);
c.depth_stride = v.get<int>("depth_stride", c.depth_stride);
if (c.clamp_deg < 0.0 || c.clamp_deg > 10.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope.clamp_deg phai trong [0, 10]");
}
if (c.sigma_rel < 0.0 || c.sigma_flat < 0.0 || c.sigma_anchor <= 0.0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"slam.yaml slope: sigma_rel/sigma_flat >= 0, sigma_anchor > 0");
}
if (c.elevation_cell_m <= 0.0 || c.elevation_radius_m <= 0.0 || c.depth_stride < 1) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml slope: elevation_cell_m, elevation_radius_m > 0, depth_stride >= 1");
}
}
} }
#endif #endif
@@ -500,7 +712,7 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
{ {
const StatusResponse r = const StatusResponse r =
Reject(root, "system.yaml", Reject(root, "system.yaml",
{"web", "logging", "record", "threads", "watchdog"}); {"web", "gamepad", "logging", "record", "threads", "watchdog"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
@@ -510,7 +722,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
Reject(w, "system.yaml web", Reject(w, "system.yaml web",
{"port", "bind", "auth_token", "asset_dir", "status_rate_hz", {"port", "bind", "auth_token", "asset_dir", "status_rate_hz",
"scan_rate_hz", "cloud_rate_hz", "path_rate_hz", "scan_rate_hz", "cloud_rate_hz", "path_rate_hz",
"cloud_max_points", "cloud_quant_m", "map_rebuild_rate_hz"}); "cloud_max_points", "cloud_quant_m", "map_rebuild_rate_hz",
"voxel_chunk_bytes", "voxel_sync_chunks_per_tick"});
if (!r.ok()) return r; if (!r.ok()) return r;
} }
out->web.port = static_cast<uint16_t>(w.get<int>("port", 8080)); out->web.port = static_cast<uint16_t>(w.get<int>("port", 8080));
@@ -525,6 +738,11 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
static_cast<uint32_t>(w.get<int>("cloud_max_points", 4000)); static_cast<uint32_t>(w.get<int>("cloud_max_points", 4000));
out->slam_runtime.map_rebuild_rate_hz = out->slam_runtime.map_rebuild_rate_hz =
w.get<double>("map_rebuild_rate_hz", out->slam_runtime.map_rebuild_rate_hz); w.get<double>("map_rebuild_rate_hz", out->slam_runtime.map_rebuild_rate_hz);
out->web.voxel_chunk_bytes = static_cast<uint32_t>(
w.get<int>("voxel_chunk_bytes", static_cast<int>(out->web.voxel_chunk_bytes)));
out->web.voxel_sync_chunks_per_tick = static_cast<uint32_t>(w.get<int>(
"voxel_sync_chunks_per_tick",
static_cast<int>(out->web.voxel_sync_chunks_per_tick)));
if (out->web.auth_token.empty()) { if (out->web.auth_token.empty()) {
// Khong tu choi khoi dong: mot robot trong phong lab khong can token. // Khong tu choi khoi dong: mot robot trong phong lab khong can token.
@@ -534,6 +752,125 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
"mang deu GO duoc e-stop va reset duoc bumper."); "mang deu GO duoc e-stop va reset duoc bumper.");
} }
// ---------- system.yaml gamepad ----------
//
// Port tu base_kit/src/joy_control. Ten khoa giu giong tham so cua node
// ROS ben do de doi chieu duoc hai ben.
const ConfigNode gp = root["gamepad"];
{
const StatusResponse r =
Reject(gp, "system.yaml gamepad",
{"enabled", "device", "publish_rate_hz", "max_linear_speed",
"max_angular_speed", "deadzone", "min_linear_kick",
"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", "button_test",
"button_turbo", "button_slow", "invert_linear",
"invert_angular", "lt_stop", "axis_lt", "lt_press_above"});
if (!r.ok()) return r;
}
out->gamepad.enabled = gp.get<bool>("enabled", false);
out->gamepad.device = gp.get<std::string>("device", out->gamepad.device);
out->gamepad.publish_rate_hz =
gp.get<double>("publish_rate_hz", out->gamepad.publish_rate_hz);
out->gamepad.max_linear_speed =
gp.get<double>("max_linear_speed", out->gamepad.max_linear_speed);
out->gamepad.max_angular_speed =
gp.get<double>("max_angular_speed", out->gamepad.max_angular_speed);
out->gamepad.deadzone = gp.get<double>("deadzone", out->gamepad.deadzone);
out->gamepad.min_linear_kick =
gp.get<double>("min_linear_kick", out->gamepad.min_linear_kick);
out->gamepad.min_angular_kick =
gp.get<double>("min_angular_kick", out->gamepad.min_angular_kick);
out->gamepad.idle_publish_sec =
gp.get<double>("idle_publish_sec", out->gamepad.idle_publish_sec);
out->gamepad.reopen_period_sec =
gp.get<double>("reopen_period_sec", out->gamepad.reopen_period_sec);
out->gamepad.turbo_linear =
gp.get<double>("turbo_linear", out->gamepad.turbo_linear);
out->gamepad.turbo_angular =
gp.get<double>("turbo_angular", out->gamepad.turbo_angular);
out->gamepad.slow_linear =
gp.get<double>("slow_linear", out->gamepad.slow_linear);
out->gamepad.slow_angular =
gp.get<double>("slow_angular", out->gamepad.slow_angular);
out->gamepad.axis_linear = gp.get<int>("axis_linear", out->gamepad.axis_linear);
out->gamepad.axis_linear_dpad =
gp.get<int>("axis_linear_dpad", out->gamepad.axis_linear_dpad);
out->gamepad.axis_angular =
gp.get<int>("axis_angular", out->gamepad.axis_angular);
out->gamepad.axis_angular_dpad =
gp.get<int>("axis_angular_dpad", out->gamepad.axis_angular_dpad);
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);
out->gamepad.lt_stop = gp.get<bool>("lt_stop", out->gamepad.lt_stop);
out->gamepad.axis_lt = gp.get<int>("axis_lt", out->gamepad.axis_lt);
out->gamepad.invert_linear =
gp.get<bool>("invert_linear", out->gamepad.invert_linear);
out->gamepad.invert_angular =
gp.get<bool>("invert_angular", out->gamepad.invert_angular);
out->gamepad.lt_press_above =
gp.get<double>("lt_press_above", out->gamepad.lt_press_above);
// Kiem CA KHI dang tat: `--gamepad` bat duoc no tu dong lenh, va luc do
// khong con cho nao de tu choi mot cau hinh sai nua.
{
if (out->gamepad.publish_rate_hz <= 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"system.yaml gamepad.publish_rate_hz phai > 0");
}
// ⚠️ KIEM CHEO VOI WATCHDOG CUA SAFETY.
//
// joydev chi gui event khi gia tri DOI, nen giu can gat dung yen la
// khong co event nao. Vong bom lenh phai DAY hon cmd_timeout, neu khong
// FSM ban NO_CMD va dung xe giua luc nguoi lai dang giu can. Lay mot nua
// de con cho jitter cua scheduler.
const double period = 1.0 / out->gamepad.publish_rate_hz;
if (period > 0.5 * out->safety.cmd_timeout) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"system.yaml gamepad.publish_rate_hz qua thua: chu ky " +
std::to_string(period) + " s, can <= mot nua safety.yaml "
"cmd_timeout (" + std::to_string(out->safety.cmd_timeout) +
" s) neu khong NO_CMD se dung xe khi dang giu can gat");
}
}
// Canh bao thi CHI khi tay cam dang bat -- khong lam on log cua mot lan
// chay khong dung toi no.
if (out->gamepad.enabled) {
// Tran cua tay cam KHONG duoc phep lam nguoi lai tuong minh co nhieu hon
// thuc te. Khong tu choi khoi dong -- base_kit dung 0.5/1.0 va ta giu
// nguyen so do de doi chieu duoc -- nhung phai noi ro no bi kep o dau.
if (out->gamepad.max_linear_speed > out->safety.max_linear) {
VSLAM_WARN("gamepad.max_linear_speed " << out->gamepad.max_linear_speed
<< " m/s CAO HON tran that " << out->safety.max_linear
<< " m/s (robot.yaml + safety.yaml). Lenh se bi kep o tran "
"that, turbo KHONG dat toi so da dat.");
}
if (out->gamepad.max_angular_speed > out->safety.max_angular) {
VSLAM_WARN("gamepad.max_angular_speed " << out->gamepad.max_angular_speed
<< " rad/s CAO HON tran that " << out->safety.max_angular
<< " rad/s -- se bi kep.");
}
// Cu kich toc do toi thieu tinh theo TRAN THAT, khong theo tran khai bao.
if (out->gamepad.min_linear_kick > 0.5 * out->safety.max_linear) {
VSLAM_WARN("gamepad.min_linear_kick " << out->gamepad.min_linear_kick
<< " m/s chiem qua nua tran that " << out->safety.max_linear
<< " m/s -- can gat se gan nhu thanh cong tac, mat dai bo "
"cham. base_kit dung 0.2 tren tran 0.5 (40%); tuong duong "
"o day la "
<< (0.4 * out->safety.max_linear) << ".");
}
}
const ConfigNode lg = root["logging"]; const ConfigNode lg = root["logging"];
{ {
const StatusResponse r = Reject(lg, "system.yaml logging", {"level"}); const StatusResponse r = Reject(lg, "system.yaml logging", {"level"});

View File

@@ -28,6 +28,7 @@
#include "vslam/gravity_align.h" #include "vslam/gravity_align.h"
#include "vslam/perception_pipeline.h" #include "vslam/perception_pipeline.h"
#include "vslam/driver_config.h" #include "vslam/driver_config.h"
#include "vslam/gamepad.h"
#include "vslam/robot_model.h" #include "vslam/robot_model.h"
#include "vslam/safety_monitor.h" #include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h" #include "vslam/scan_sanitizer.h"
@@ -46,6 +47,63 @@ struct SlamRuntimeConfig {
double map_rebuild_rate_hz = 0.5; double map_rebuild_rate_hz = 0.5;
}; };
// Hinh hoc cua ban do voxel 3D. Doc tu khoi `voxel:` trong slam.yaml -- cung
// file voi cai sinh ra no, khong phai system.yaml (o do chi co tham so TRUYEN).
struct VoxelConfig {
double emit_size_m = 0.10;
double z_min = 0.05;
double z_max = 2.00;
size_t max_cells = 150000;
// Ti le (them + bot) / tong vuot nguong nay thi gui lai CA TAP thay vi
// delta. Sau mot lan toi uu do thi thi gan nhu moi o doi chi so.
double delta_max_ratio = 0.35;
// Lop vat can tu camera gop vao luoi 2D: voxel co z trong khoang nay (tinh
// tu mat san) bi danh dau la tuong. Xem slam.yaml khoi `voxel:`.
double obstacle_z_min = 0.10;
double obstacle_z_max = 0.55;
// Voxel phai duoc it nhat bay nhieu node khac nhau thay moi giu -- ap cho ca
// ban do 3D lan lop vat can 2D. 1 = giu moi voxel.
size_t min_node_hits = 1;
// Xoa voxel ma bay nhieu node SAU lan thay cuoi nhin xuyen qua (vat da roi
// di). 0 = tat. Xem slam.yaml khoi `voxel:`.
size_t clear_after_views = 0;
};
// Di tren doc (G4). Doc tu khoi `slope:` trong slam.yaml. enabled = false thi
// moi duong cu giu nguyen tung byte -- xem slam.yaml.
struct SlopeConfig {
bool enabled = false;
// z = tich -ds*sin(pitch IMU); |pitch| < clamp -> coi la phang (dz = 0).
double clamp_deg = 1.5;
double sigma_rel = 0.05;
double sigma_flat = 0.005;
double sigma_anchor = 0.03;
// Neo z vao node ban do trong ban kinh nay (che do localization).
double anchor_radius_m = 0.6;
// Quang duong banh x cos(pitch) truoc khi vao EKF (doc 15 do: -3.4%).
bool horizontal_odom = true;
// Bu nghieng scan + bo tia cham san cho SLAM / dinh vi lai (KHONG cho an toan).
bool level_scan = true;
double floor_margin_m = 0.08;
double below_ground_m = 0.05;
// Ban do do cao san cuc bo tu depth camera.
double elevation_cell_m = 0.10;
double elevation_radius_m = 8.0;
double elevation_max_depth_m = 4.0;
int depth_stride = 4;
};
// Vong dong XA luc quet ban do (RtabmapSlam::TryFarLoopClosure). Doc tu khoi
// `far_loops:` trong slam.yaml.
struct FarLoopsConfig {
bool enabled = true;
double radius_m = 1.0; // node cu trong ban kinh nay (theo do thi)
int min_graph_gap = 100; // cach toi thieu bay nhieu node trong do thi
double max_corr_m = 0.5; // ICP chinh lon hon -> bo (sai cho)
double max_corr_deg = 10.0;
double period_s = 1.0; // toi da 1 lan thu moi chung nay giay
};
struct ThreadConfig { struct ThreadConfig {
int safety_priority = 50; int safety_priority = 50;
int driver_priority = 45; int driver_priority = 45;
@@ -95,6 +153,7 @@ struct AppConfig {
WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml
EkfSe2Config ekf; // pipeline.yaml EkfSe2Config ekf; // pipeline.yaml
bool ekf_gyro_yaw = false; // pipeline.yaml ekf.gyro_yaw: goc quay EKF theo gyro
PerceptionConfig perception; // pipeline.yaml + robot.yaml PerceptionConfig perception; // pipeline.yaml + robot.yaml
SafetyConfig safety; // safety.yaml SafetyConfig safety; // safety.yaml
@@ -103,8 +162,12 @@ struct AppConfig {
#endif #endif
WebConfig web; // system.yaml WebConfig web; // system.yaml
GamepadConfig gamepad; // system.yaml
ThreadConfig threads; ThreadConfig threads;
SlamRuntimeConfig slam_runtime; SlamRuntimeConfig slam_runtime;
VoxelConfig voxel;
SlopeConfig slope;
FarLoopsConfig far_loops;
RecordConfig record; RecordConfig record;
std::string log_level = "info"; std::string log_level = "info";

View File

@@ -53,6 +53,14 @@ void Usage(const char* argv0) {
" --x X --y Y --yaw R vi tri xuat phat cho --sim\n" " --x X --y Y --yaw R vi tri xuat phat cho --sim\n"
" --port N ghi de system.yaml web.port\n" " --port N ghi de system.yaml web.port\n"
" --token S ghi de system.yaml web.auth_token\n" " --token S ghi de system.yaml web.auth_token\n"
" --gamepad [DEV] bat tay cam (Logitech F710/F310), ghi de\n"
" system.yaml gamepad.enabled. DEV mac dinh lay\n"
" tu system.yaml (/dev/input/js0)\n"
" --no-gamepad tat tay cam du system.yaml co bat\n"
" --sim-gl ve camera mo phong bang GPU: depth + anh IR co\n"
" texture (can --world, build VSLAM_SIM_WITH_GL=ON)\n"
" --sim-imu-hz N IMU mo phong phat N Hz (mac dinh moi buoc vat ly,\n"
" 200 Hz). 100 = WT61PC sau khi doi 115200 baud.\n"
" --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n" " --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
" LiDAR/depth KHONG thay; chi sieu am + bumper.\n" " LiDAR/depth KHONG thay; chi sieu am + bumper.\n"
" --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n" " --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
@@ -65,6 +73,26 @@ void Usage(const char* argv0) {
" pose ban dau cho localization -- tuong duong\n" " pose ban dau cho localization -- tuong duong\n"
" /initialpose. BAT BUOC tren robot that: RTAB-Map\n" " /initialpose. BAT BUOC tren robot that: RTAB-Map\n"
" khong dinh vi toan cuc duoc bang scan khong.\n" " khong dinh vi toan cuc duoc bang scan khong.\n"
" --slam-reloc localization KHONG can pose ban dau: XOAY TAI CHO\n"
" ~300 do, node tu tim vi tri bang khop scan LiDAR\n"
" voi toan ban do. Khong di cung --slam-init-pose.\n"
" --slam-reloc-auto kem --slam-reloc: robot TU XOAY + TU DI (0.12 m/s,\n"
" 0.4 rad/s, toi da 6 vong / 12 m) toi khi chot.\n"
" Lenh van qua lop an toan; tay cam/web ra lenh\n"
" la tu chay nhuong ngay. THU TREN MO PHONG TRUOC.\n"
" --slam-reloc-vpr [ENGINE.plan]\n"
" 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", " --check nap va KIEM cau hinh roi thoat, khong chay gi\n",
argv0, vslam::ConfigDir().c_str()); argv0, vslam::ConfigDir().c_str());
} }
@@ -140,7 +168,16 @@ int main(int argc, char** argv) {
else if (a == "--port") else if (a == "--port")
opts.port_override = static_cast<uint16_t>(std::atoi(next().c_str())); opts.port_override = static_cast<uint16_t>(std::atoi(next().c_str()));
else if (a == "--token") opts.token_override = next(); else if (a == "--token") opts.token_override = next();
else if (a == "--gamepad") {
// Duong dan thiet bi la TUY CHON: `--gamepad` mot minh dung device trong
// system.yaml. Chi nuot tham so ke tiep khi no khong phai mot co khac.
opts.gamepad_override = 1;
if (i + 1 < argc && argv[i + 1][0] != '-') opts.gamepad_device = argv[++i];
}
else if (a == "--no-gamepad") opts.gamepad_override = -1;
else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str()); else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str());
else if (a == "--sim-gl") opts.sim_gl = true;
else if (a == "--sim-imu-hz") opts.sim_imu_hz = std::atof(next().c_str());
else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str()); else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
else if (a == "--slam") opts.force_slam = true; else if (a == "--slam") opts.force_slam = true;
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; } else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }
@@ -154,6 +191,34 @@ int main(int argc, char** argv) {
} }
opts.have_slam_init_pose = true; opts.have_slam_init_pose = true;
} }
else if (a == "--slam-reloc") opts.slam_reloc = true;
else if (a == "--slam-reloc-auto") opts.slam_reloc_auto = true;
else if (a == "--slam-reloc-vpr") {
// Duong dan engine la TUY CHON (giong --gamepad [DEV]).
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 == "--check") check_only = true;
else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; } else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; }
else { else {

File diff suppressed because it is too large Load Diff

View File

@@ -28,6 +28,8 @@
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstdio>
#include <deque>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <map> #include <map>
@@ -39,7 +41,13 @@
#include "app_config.h" #include "app_config.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
#include "vslam/ekf_se2.h" #include "vslam/ekf_se2.h"
#include "vslam/gyro_yaw_fuser.h"
#include "vslam/elevation_map.h"
#include "vslam/gamepad.h"
#include "vslam/geometry.h"
#include "vslam/height_estimator.h"
#include "vslam/perception_pipeline.h" #include "vslam/perception_pipeline.h"
#include "vslam/scan_leveler.h"
#include "vslam/safety_monitor.h" #include "vslam/safety_monitor.h"
#include "vslam/scan_sanitizer.h" #include "vslam/scan_sanitizer.h"
#include "vslam/teleop_model.h" #include "vslam/teleop_model.h"
@@ -47,7 +55,12 @@
#include "vslam/wheel_odometry.h" #include "vslam/wheel_odometry.h"
#ifdef VSLAM_HAVE_SLAM #ifdef VSLAM_HAVE_SLAM
#include "vslam/global_localizer.h"
#include "vslam/rtabmap_slam.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 #endif
namespace vslam { namespace vslam {
@@ -65,6 +78,11 @@ struct RuntimeOptions {
uint16_t port_override = 0; // 0 = dung system.yaml uint16_t port_override = 0; // 0 = dung system.yaml
std::string token_override; std::string token_override;
// Tay cam: 0 = theo system.yaml, 1 = --gamepad, -1 = --no-gamepad.
// Ba trang thai chu khong phai bool: "khong noi gi" khac han "noi la tat".
int gamepad_override = 0;
std::string gamepad_device; // rong = giu device trong system.yaml
// Tran toc do, GHI DE ca robot.yaml lan safety.yaml. 0 = khong ghi de. // Tran toc do, GHI DE ca robot.yaml lan safety.yaml. 0 = khong ghi de.
// //
// ⚠️ CHO MO PHONG. `robot.yaml base.max_linear = 0.35` la gioi han CO HOC // ⚠️ CHO MO PHONG. `robot.yaml base.max_linear = 0.35` la gioi han CO HOC
@@ -79,6 +97,11 @@ struct RuntimeOptions {
// Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh // Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh
// US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end. // US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end.
double sim_glass_at = 0.0; double sim_glass_at = 0.0;
// Ve camera mo phong bang GPU (vslam_sim_gl): depth + anh IR co texture.
// Can --world va node build voi -DVSLAM_SIM_WITH_GL=ON.
bool sim_gl = false;
// Tan so PHAT IMU cua sim (SimConfig::imu_output_hz). 0 = moi buoc vat ly.
double sim_imu_hz = 0.0;
bool force_slam = false; // --slam: ghi de slam.yaml enabled bool force_slam = false; // --slam: ghi de slam.yaml enabled
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
std::string slam_db; std::string slam_db;
@@ -87,6 +110,25 @@ struct RuntimeOptions {
// ROS, thu ma `dock_init.py` phat tu dock. // ROS, thu ma `dock_init.py` phat tu dock.
bool have_slam_init_pose = false; bool have_slam_init_pose = false;
Pose2D slam_init_pose; Pose2D slam_init_pose;
// --slam-reloc: localization KHONG pose ban dau -- tu dinh vi lai bang khop
// scan LiDAR toan ban do (vslam/global_localizer.h).
bool slam_reloc = false;
// --slam-reloc-auto: robot TU XOAY va TU DI de gom scan (reloc_exec cua ban
// ROS). Mac dinh TAT: robot tu chay khi CHUA biet minh o dau.
bool slam_reloc_auto = false;
// --slam-reloc-vpr [ENGINE]: CAMERA cung dinh vi lai -- VPR (TensorRT) goi y cho, PnP cho
// pose, chot khi TRUNG khop LiDAR. Can -DVSLAM_WITH_TENSORRT=ON; khong co thi canh bao
// 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 { class Runtime {
@@ -105,11 +147,18 @@ class Runtime {
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20 // wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
// file .launch cua ban ROS. // file .launch cua ban ROS.
StatusResponse Wire(); StatusResponse Wire();
// Di tren doc: mot khung depth -> ban do do cao san cuc bo (luong camera).
void AddDepthToElevation(const CameraFrame& f);
// runtime.cc // runtime.cc
StatusResponse OpenSource(); StatusResponse OpenSource();
void SafetyLoop(); void SafetyLoop();
// Bom lenh tay cam vao `raw_cmd_` o tan so co dinh. Xem ghi chu "bay cua
// joydev" trong gamepad.h: khong co vong nay thi giu can gat dung yen se bi
// hieu la MAT lenh.
void GamepadLoop();
// Do DO LECH giua dam may camera va scan LiDAR, bang so. // Do DO LECH giua dam may camera va scan LiDAR, bang so.
// //
// Hai cam bien nhin cung mot buc tuong. Neu ngoai lai cua camera trong // Hai cam bien nhin cung mot buc tuong. Neu ngoai lai cua camera trong
@@ -119,6 +168,62 @@ class Runtime {
void ReportCloudScanAlign(const PointCloudXYZ& cloud); void ReportCloudScanAlign(const PointCloudXYZ& cloud);
void WebLoop(); void WebLoop();
void SlamLoop(); void SlamLoop();
#ifdef VSLAM_HAVE_SLAM
// Dinh vi lai tu dong (--slam-reloc). CHI luong slam goi, TRUOC Process():
// gom scan theo goc da xoay, du thi khop toan cuc, chot thi SetInitialPose.
void RelocStep(const LaserScan& scan, const Pose2D& odom);
// Sau Process(): scan tai pose dang tin con khop ban do khong -- tut lau
// thi quay lai gom (nghi da lac).
void RelocWatch(const LaserScan& scan, const Pose2D& pose_map);
// Diem scan (frame laser) -> frame cua `pose` (odom hoac map), cat max_range.
std::vector<Point> ScanToFrame(const LaserScan& scan, const Pose2D& pose) const;
// `pending` = CHUA dinh vi xong: web khong ve robot theo pose uoc luong.
void SetRelocStatus(const std::string& s, bool pending);
// --- Tu chay (--slam-reloc-auto) ---
// Lenh di qua `raw_cmd_` NHU MOI NGUON KHAC -> van qua lop an toan.
void RelocCommand(double v, double w);
// Co ai KHAC ghi raw_cmd_ trong 0.5 s qua khong (tay cam, web).
bool RelocHumanCommanding();
// Chon huong thoang nhat trong scan, dat muc tieu QUAY + DI. false = khong
// co cho nao du rong.
bool RelocPlanDrive(const LaserScan& scan, const Pose2D& odom);
void RelocStartSweep();
void RelocHalt(const std::string& why);
// Dang dung tren doc (che do doc bat, nghieng than so voi trong luc qua
// nguong) -> vong dinh vi lai DUNG YEN, khong xoay robot. `deg`: goc nghieng.
bool RelocOnSlope(double* deg = nullptr) const;
// Khoang thoang PHIA TRUOC (+-15 do, frame base) theo scan; 0 = khong co tia
// nao trong quat do (khong biet -> khong di).
double RelocFrontClear(const LaserScan& scan) const;
// Che do doc: pose robot `p` (map) co hop khong -- dung tren o TRONG cua ban do, va
// do doc ban do tai do gay ra dung do nghieng IMU (roll/pitch) dang do.
bool RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p) const;
// Quyet dinh cho vong DUNG YEN: trung vi `static_rounds` vong lien tiep cung
// nguoi thang thay cho mot vong. `*along_axis` = bi chan vi mu doc truc.
RelocVerdict RelocStaticDecide(const RelocMatch& m, const Pose2D& odom, double shift_ratio,
bool use_shift, bool* along_axis, std::string* why);
// Sau khi CHOT: cho robot DUNG YEN, gom scan luc dung yen (khong nhoe do
// quay), khop cuc bo quanh pose vua chot roi moi dat pose ban dau.
void RelocSettle(const LaserScan& scan, const Pose2D& odom,
std::chrono::steady_clock::time_point now);
void RelocFinish(const Pose2D& map_from_odom, const Pose2D& odom, const LaserScan& scan,
const std::string& how);
// Bat dau pha dung yen + tinh chinh sau khi CHOT -- chung cho LiDAR va camera.
void RelocBeginSettle(const Pose2D& map_from_odom, double ratio, const Pose2D& odom,
std::chrono::steady_clock::time_point now, const std::string& src);
// Camera: cu 30 do xoay chup mot anh -> VPR top-5 -> PnP -> so voi LiDAR cuc bo quanh
// 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); void ApplyThreadPriority(std::thread* t, int prio, const char* name);
AppConfig* cfg_; AppConfig* cfg_;
@@ -143,6 +248,18 @@ class Runtime {
std::unique_ptr<SafetyMonitor> safety_; std::unique_ptr<SafetyMonitor> safety_;
std::unique_ptr<TeleopModel> teleop_; std::unique_ptr<TeleopModel> teleop_;
std::unique_ptr<WebServer> web_; std::unique_ptr<WebServer> web_;
// Tay cam. `gamepad_` doc thiet bi tren luong rieng; `gamepad_map_` bien
// trang thai tho thanh van toc va CHI luong `gamepad` cham vao.
//
// ⚠️ Tay cam KHONG di qua `teleop_`. Do la co y va giong base_kit: node joy
// ben do co tham so toc do rieng, doc lap voi ban phim. Nho vay hai nguon
// nhap khong tranh trang thai cua mot mo hinh chung -- chung chi gap nhau o
// `raw_cmd_`, va luat nhuong quyen la cua so idle 1.5 s.
std::unique_ptr<GamepadReader> gamepad_;
std::unique_ptr<GamepadMapper> gamepad_map_;
// Doc-only sau Wire(). Giu rieng vi `--gamepad` co the ghi de config.
double gamepad_rate_hz_ = 50.0;
#ifdef VSLAM_HAVE_SLAM #ifdef VSLAM_HAVE_SLAM
std::unique_ptr<RtabmapSlam> slam_; std::unique_ptr<RtabmapSlam> slam_;
#endif #endif
@@ -153,12 +270,26 @@ class Runtime {
// web_tx doc. // web_tx doc.
mutable std::mutex scan_mu_; mutable std::mutex scan_mu_;
LaserScanPtr latest_scan_; LaserScanPtr latest_scan_;
// Scan cho SLAM / dinh vi lai / canh lac: BU NGHIENG khi slope_on_ (xem
// ScanLeveler), con lai CHINH la latest_scan_. An toan + web dung ban tho.
LaserScanPtr latest_slam_scan_;
// odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong // odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
// kia chi doc ban sao pose. // kia chi doc ban sao pose.
mutable std::mutex odom_mu_; mutable std::mutex odom_mu_;
Odometry latest_odom_; Odometry latest_odom_;
bool have_odom_ = false; bool have_odom_ = false;
// Lich su pose EKF (moi buoc encoder, ~2 s) de SLAM lay pose DUNG LUC QUET.
// Ghep scan voi pose HIEN TAI thi luc quay tai cho 0.6 rad/s, tre 20 ms la
// lech 0.7 do -- lien ket ICP ke can o cho quay mang lech goc do vao do
// thi va xoay ca ban do (do trong sim doc 04/10: 0.56 do -> 0.2 m sau 20 m
// hanh lang).
struct OdomAt {
UnixTime stamp;
Pose2D pose;
double z = 0.0;
};
std::deque<OdomAt> odom_hist_;
// perc_mu_: ket qua perception. // perc_mu_: ket qua perception.
mutable std::mutex perc_mu_; mutable std::mutex perc_mu_;
@@ -169,6 +300,30 @@ class Runtime {
bool have_cliff_ = false; bool have_cliff_ = false;
std::string cliff_detail_; std::string cliff_detail_;
// depth_mu_: khung depth THO gan nhat, danh RIENG cho SLAM 3D.
//
// ⚠️ RIENG khoi `perc_mu_`, khong dung chung. Luong safety doc
// `cliff_flag_` duoi `perc_mu_`; cho luong slam cung cho vao do la dat mot
// vong lap 100-600 ms sau cung mot mutex voi vong an toan 20 Hz.
//
// ⚠️ Giu `ImagePtr` o day la GHIM mot khung cua librealsense:
// `Image::data` tro thang vao buffer cua SDK va `keep_alive` giu `rs2::frame`
// song. Nhieu nhat hai khung bi ghim cung luc (mot o day, mot dang bay trong
// SlamLoop) tren pool 16 -- do la ly do day la mot LATCH chu khong phai mot
// hang doi.
mutable std::mutex depth_mu_;
ImagePtr latest_depth_;
ImagePtr latest_infra1_;
std::shared_ptr<const CameraInfo> latest_depth_info_;
UnixTime latest_depth_stamp_;
bool have_depth_ = false;
// Nghieng (gravity_align) LUC chup khung depth tren -- xem
// SlamInput::camera_to_base.
double latest_depth_roll_ = 0.0;
double latest_depth_pitch_ = 0.0;
// base_link <- camera_depth_optical_frame, tinh. Doc-only sau Start().
Transform slam_cam_to_link_ = TransformIdentity();
// mcu_mu_: sieu am va bumper. // mcu_mu_: sieu am va bumper.
// //
// Hai cam bien nay o tren MCU vi ca hai deu la cam bien MUC THAP phai toi // Hai cam bien nay o tren MCU vi ca hai deu la cam bien MUC THAP phai toi
@@ -190,6 +345,9 @@ class Runtime {
Twist raw_cmd_; Twist raw_cmd_;
UnixTime raw_cmd_stamp_; UnixTime raw_cmd_stamp_;
bool have_raw_cmd_ = false; bool have_raw_cmd_ = false;
// Stamp cua lan GHI GAN NHAT boi dinh vi lai tu chay. raw_cmd_stamp_ moi hon
// cai nay nghia la NGUOI (tay cam/web) vua ra lenh -> tu chay nhuong.
UnixTime reloc_cmd_stamp_;
// teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay). // teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay).
mutable std::mutex teleop_mu_; mutable std::mutex teleop_mu_;
@@ -223,15 +381,151 @@ class Runtime {
size_t last_map_occ_ = 0; size_t last_map_occ_ = 0;
size_t last_map_free_ = 0; size_t last_map_free_ = 0;
OccupancyGridPtr slam_map_; OccupancyGridPtr slam_map_;
// Do cao san cua ban do (che do doc), cung phien ban voi slam_map_.
std::shared_ptr<const MapFloorGrid> slam_map_floor_;
double slam_process_ms_ = 0.0; double slam_process_ms_ = 0.0;
int slam_loops_ = 0; int slam_loops_ = 0;
// Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only. // Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only.
int slam_prox_id_ = 0; int slam_prox_id_ = 0;
uint64_t slam_prox_total_ = 0; uint64_t slam_prox_total_ = 0;
#ifdef VSLAM_HAVE_SLAM
// Duoi `slam_mu_`: tap voxel day du gan nhat va payload delta DA MA HOA.
// Ma hoa mot lan o luong slam roi dung chung cho moi session -- y het cach
// khung MAP_FULL dung chung mot bo dem.
VoxelGridPtr slam_voxels_;
std::shared_ptr<const std::string> slam_voxel_delta_;
// ⚠️ RIENG cua luong SlamLoop, KHONG duoi mutex nao: chi vong do doc va ghi.
// Dat chung vao `slam_mu_` la keo mot vector 150k phan tu vao trong lock ma
// WebLoop giu 10 lan moi giay.
std::vector<VoxelIndex> prev_voxel_cells_;
uint32_t voxel_epoch_ = 0;
uint32_t voxel_seq_ = 0;
// ⚠️ Dinh vi lai tu dong: RIENG cua luong SlamLoop, KHONG duoi mutex nao --
// tru `reloc_status_` (duoi slam_mu_, WebLoop doc).
std::unique_ptr<LikelihoodField> reloc_field_; // null = khong bat --slam-reloc
GlobalLocalizerConfig reloc_cfg_;
std::unique_ptr<HypothesisTracker> reloc_tracker_;
bool reloc_active_ = false; // dang gom/khop: CHUA dua gi cho RTAB-Map
std::vector<Point> reloc_pts_; // diem da gom, frame odom
double reloc_swept_ = 0.0; // rad da xoay trong vong gom nay
Pose2D reloc_prev_odom_;
bool reloc_have_prev_ = false;
// Vong gom nay DUNG YEN tren doc (chot luc dau vong, xem RelocOnSlope): khong
// xoay, gom scan tai cho vai giay roi khop -- bo khop da thu moi huong.
bool reloc_static_round_ = false;
// Do nghieng (do) va luc no doi qua nguong lan cuoi -- cho on dinh truoc vong dau.
double reloc_tilt_ref_deg_ = -1.0;
std::chrono::steady_clock::time_point reloc_tilt_ref_t_;
// Ket qua cac vong DUNG YEN lien tiep cung nguoi thang (xem DecideStatic),
// va tom tat cac CHO dung truoc (moi lan bo tren doc chot mot cho).
std::vector<StaticRound> reloc_static_hist_;
std::vector<StaticPlace> reloc_static_places_;
// Tu chay tren doc: so lan khop tai cho o CHO hien tai, quang da BO tren doc
// (tong, co tran), va pha DI hien tai co phai la mot lan BO khong.
int reloc_static_here_ = 0;
double reloc_slope_creep_ = 0.0;
bool reloc_creeping_ = false;
// Tu chay tren doc co camera: da quay mat theo chieu doc o CHO nay chua, va pha QUAY
// hien tai co phai lan quay theo chieu doc khong (chu tren web).
bool reloc_aligned_here_ = false;
bool reloc_aligning_ = false;
std::chrono::steady_clock::time_point reloc_t0_; // dau vong gom
std::chrono::steady_clock::time_point reloc_epoch_; // moc thoi gian cho tracker
// Truoc khi chot, web ve robot (mo) tu pose nay: node DAU TIEN cua ban do (cho bat dau
// quet). Robot that: trung goc map. Mo phong: ban do theo toa do world nen goc map la goc
// world (thuong la goc nha) -- ve o cho bat dau quet cho de nhin. Ghi trong Start() truoc
// khi luong web chay, sau do chi doc.
Pose2D reloc_view_origin_;
int reloc_cycle_ = 0;
double reloc_ref_score_ = -1.0; // diem luc chot -- moc cho canh "da lac"
bool reloc_lost_pending_ = false;
std::chrono::steady_clock::time_point reloc_lost_since_;
std::chrono::steady_clock::time_point reloc_watch_next_;
Transform slam_laser_to_base_ = TransformIdentity(); // doc-only sau Start()
std::string reloc_status_; // duoi slam_mu_
bool reloc_pending_ = false; // duoi slam_mu_: chua dinh vi xong
// Tu chay: XOAY (gom) -> khop -> chua chot thi QUAY ve cho thoang -> DI ->
// XOAY... Tran cung 6 vong / 12 m roi DUNG HAN goi nguoi (nhu ban ROS).
enum class RelocExec { kOff, kSweep, kTurn, kDrive, kHalted };
RelocExec reloc_exec_ = RelocExec::kOff;
double reloc_turn_target_ = 0.0; // huong odom can quay toi (rad)
Pose2D reloc_drive_start_;
double reloc_drive_len_ = 0.0; // quang duong du dinh cua pha DI
double reloc_total_drive_ = 0.0; // cong don cho mot lan dinh vi
int reloc_exec_cycles_ = 0;
std::chrono::steady_clock::time_point reloc_phase_t0_;
std::chrono::steady_clock::time_point reloc_yield_until_; // nguoi thang -> nhuong
// Pha "dung yen roi tinh chinh" (RelocSettle). Gom luc DANG QUAY lam dam
// diem nhoe 1-2 do moi scan (odom doc tre hon luc quet) -- mo phong
// 2026-09-29: chot lech 0.12 m va RTAB-Map khong sua vi robot dung ngay.
bool reloc_settle_ = false;
Pose2D reloc_settle_T_; // T_map_odom luc chot, chua tinh chinh
double reloc_settle_ratio_ = 0.0;
std::chrono::steady_clock::time_point reloc_settle_t0_;
std::chrono::steady_clock::time_point reloc_still_since_;
bool reloc_still_ = false;
Pose2D reloc_settle_prev_odom_;
std::vector<Point> reloc_settle_pts_;
int reloc_settle_scans_ = 0;
std::string reloc_settle_src_; // "LiDAR, ty le .." | "camera+LiDAR (..)" -- log/web
// --- Camera trong dinh vi lai (--slam-reloc-vpr). CHI luong slam cham. ---
std::unique_ptr<VprEncoder> vpr_; // null = khong dung camera
std::unique_ptr<VisualVerifier> vverif_;
std::vector<int> vpr_ids_; // node ban do co mo ta
std::vector<float> vpr_desc_; // vpr_ids_.size() x dim, da chuan hoa
struct MapShot {
VisualFrame f; // ORB + depth + K + T_base_optical
cv::Matx44d T_map_base;
};
std::map<int, MapShot> vpr_shots_; // node ban do, nap khi can roi giu
bool reloc_cam_have_last_ = false;
double reloc_cam_last_theta_ = 0.0; // odom.theta lan chup gan nhat
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. // Doc-only sau Start(), nen khong can mutex.
bool slam_enabled_ = false; bool slam_enabled_ = false;
bool slam_should_save_ = false; bool slam_should_save_ = false;
// slam.camera_3d VA co SLAM that. Quyet dinh co latch depth hay khong: tat
// thi ca duong nay khong ton mot lan copy con tro nao.
bool slam_use_depth_ = false;
// Ban do voxel 3D bat hay khong. Bang camera_3d, giu rieng de doc duoc o
// WebLoop ma khong phai cham vao cfg_->slam.
bool voxel_enabled_ = false;
// Tran toc do dang dung (m/s): tu robot.yaml, hoac --max-speed ghi de. // Tran toc do dang dung (m/s): tu robot.yaml, hoac --max-speed ghi de.
double speed_limit_ = 0.35; double speed_limit_ = 0.35;
// Gia toc thuc su dung. Bang robot.yaml, TRU khi `--max-speed` noi tran -- // Gia toc thuc su dung. Bang robot.yaml, TRU khi `--max-speed` noi tran --
@@ -249,12 +543,16 @@ class Runtime {
Pose2D prev_odom_; Pose2D prev_odom_;
UnixTime prev_odom_stamp_; UnixTime prev_odom_stamp_;
bool have_prev_odom_ = false; bool have_prev_odom_ = false;
double gyro_z_ = 0.0; // Goc quay cho EKF: gyro giu tong, encoder lap khoang gyro chua ve (xem
UnixTime gyro_stamp_; // gyro_yaw_fuser.h). Duoi `odom_mu_`.
// Tich phan gyro giua hai lan cap nhat odom, va tong thoi gian da phu. GyroYawFuser yaw_fuser_;
double gyro_dtheta_ = 0.0; // Chan doan goc quay 30 s mot lan (wiring.cc). Duoi `odom_mu_`.
double gyro_dt_ = 0.0; double yaw_diag_enc_ = 0.0;
bool have_gyro_ = false; double yaw_diag_enc_abs_ = 0.0;
double yaw_diag_fused_ = 0.0;
int yaw_diag_steps_ = 0;
int yaw_diag_gyro_ = 0;
UnixTime yaw_diag_t0_;
// Ground truth CHOT cung luc voi EKF, duoi `odom_mu_`. Doc tuoi luc chup // Ground truth CHOT cung luc voi EKF, duoi `odom_mu_`. Doc tuoi luc chup
// snapshot roi dem voi pose cu la do DO TRE chu khong phai sai so. // snapshot roi dem voi pose cu la do DO TRE chu khong phai sai so.
@@ -286,12 +584,47 @@ class Runtime {
std::atomic<double> tilt_roll_{0.0}; std::atomic<double> tilt_roll_{0.0};
std::atomic<double> tilt_pitch_{0.0}; std::atomic<double> tilt_pitch_{0.0};
std::atomic<bool> tilt_accel_ok_{false}; std::atomic<bool> tilt_accel_ok_{false};
// GravityAlign da khoi tao (co mau IMU) -- truoc do roll/pitch = 0 gia. Dinh
// vi lai tren doc CHO co nay roi moi quyet xoay hay dung yen.
std::atomic<bool> tilt_valid_{false};
// ---- Di tren doc (slam.yaml `slope:`) ----
// slope_on_ doc-only sau Start(). Tat thi KHONG doi tuong nao duoi day
// duoc tao, va moi duong cu giu nguyen.
bool slope_on_ = false;
// Duoi odom_mu_: luong encoder cong buoc, luong slam neo.
std::unique_ptr<HeightEstimator> height_;
// elev_mu_: ban do do cao san cuc bo + thong ke bu nghieng scan. THU TU
// KHOA: odom_mu_ roi moi elev_mu_, KHONG BAO GIO nguoc lai.
mutable std::mutex elev_mu_;
std::unique_ptr<ElevationMap> elev_;
ScanLevelerConfig level_cfg_;
ScanLevelStats level_stats_;
UnixTime elev_pruned_;
// Tinh, doc-only sau Start(): base_link <- laser_link / camera optical.
Transform laser_to_base_static_ = TransformIdentity();
Transform cam_to_base_static_ = TransformIdentity();
// Chinh meo scan (sensors.yaml `lidar.deskew`, CHI LiDAR that). Doc-only sau
// Start(); can laser_to_base_static_ o tren.
bool deskew_on_ = false;
SweepTiming sweep_;
bool have_cam_to_base_ = false;
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).
bool height_anchored_ = false;
// CHI luong slam: lan thu vong dong xa cuoi (far_loops).
std::chrono::steady_clock::time_point far_loops_at_{};
uint64_t far_loops_added_ = 0;
uint64_t heights_version_ = 0;
std::chrono::steady_clock::time_point heights_at_{};
std::atomic<bool> estop_{false}; std::atomic<bool> estop_{false};
std::atomic<bool> stop_{false}; std::atomic<bool> stop_{false};
std::thread source_thread_; std::thread source_thread_;
std::thread safety_thread_; std::thread safety_thread_;
std::thread gamepad_thread_;
std::thread web_thread_; std::thread web_thread_;
std::thread slam_thread_; std::thread slam_thread_;
}; };

View File

@@ -18,10 +18,14 @@
#include "runtime.h" #include "runtime.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/gravity_align.h"
#include "vslam/json_parse.h" #include "vslam/json_parse.h"
#include "vslam/log.h" #include "vslam/log.h"
#include <algorithm>
#include <cmath> #include <cmath>
#include <cstring>
#include <vector>
namespace vslam { namespace vslam {
@@ -36,8 +40,52 @@ StatusResponse Runtime::Wire() {
// rieng thi "cai nao chay truoc" la mot bay co that. // rieng thi "cai nao chay truoc" la mot bay co that.
auto copy = std::make_shared<LaserScan>(*s); auto copy = std::make_shared<LaserScan>(*s);
sanitizer_->Apply(copy.get()); sanitizer_->Apply(copy.get());
// Ban cho SLAM / dinh vi lai: CHINH MEO (LiDAR that) roi BU NGHIENG (doc).
// An toan va web giu ban tho. Tat ca hai thi hai con tro la MOT.
LaserScanPtr slam_scan = copy;
if (deskew_on_) {
// w ~ gyro 200 Hz qua EKF (lech 0.008 rad/s x 40 ms: khong dang ke),
// v theo encoder. Kep de mot mau van toc hong khong be cong scan.
double w = 0.0, v = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
w = std::max(-2.0, std::min(2.0, ekf_->vyaw()));
v = std::max(-1.0, std::min(1.0, ekf_->vx()));
}
auto dsk = std::make_shared<LaserScan>();
DeskewScan(*copy, laser_to_base_static_, sweep_, w, v, dsk.get());
slam_scan = dsk;
}
if (slope_on_ && cfg_->slope.level_scan) {
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
auto lv = std::make_shared<LaserScan>();
{
std::lock_guard<std::mutex> lk(elev_mu_);
LevelScan(*slam_scan, laser_to_base_static_, roll, pitch,
cfg_->robot.geometry().wheel_radius, od, z, elev_.get(), level_cfg_,
lv.get(), &level_stats_);
// Ti le tia giu lai (cong don tu luc chay) -- san phang phai ~100%.
// 07/10: nua scan bi bo tu 06/10 ma khong dong log nao bao.
const ScanLevelStats& ls = level_stats_;
VSLAM_INFO_THROTTLE(30.0, "slope/scan: giu " << ls.kept << "/" << ls.rays << " tia ("
<< (ls.rays > 0 ? 100 * ls.kept / ls.rays : 0) << "%), bo cham san "
<< ls.dropped_floor << ", duoi dat " << ls.dropped_below << ", ngoai goc "
<< ls.rays - ls.kept - ls.dropped_floor - ls.dropped_below);
}
slam_scan = lv;
}
std::lock_guard<std::mutex> lk(scan_mu_); std::lock_guard<std::mutex> lk(scan_mu_);
latest_scan_ = copy; latest_scan_ = copy;
latest_slam_scan_ = slam_scan;
}); });
} }
@@ -55,24 +103,14 @@ StatusResponse Runtime::Wire() {
tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed); tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed);
tilt_accel_ok_.store(perception_->gravity().accel_ok(), tilt_accel_ok_.store(perception_->gravity().accel_ok(),
std::memory_order_relaxed); std::memory_order_relaxed);
tilt_valid_.store(perception_->gravity().valid(), std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(odom_mu_); std::lock_guard<std::mutex> lk(odom_mu_);
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z); wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
// ⚠️ TICH PHAN gyro, khong lay mot mau. // Goc gyro (EKF dung khi `ekf.gyro_yaw: true`; log odom/yaw luon dung): TICH
// // PHAN theo DAU THOI GIAN mau (hinh thang), khong theo luc mau toi -- xem
// IMU chay 200 Hz con encoder 50 Hz, nen moi khoang odom co ~4 mau. // GyroYawFuser.
// Lay MOT mau roi nhan voi ca khoang 20 ms la phep hinh chu nhat tren yaw_fuser_.AddGyro(m->header.stamp, m->angular_velocity.z);
// mot tin hieu dang doi nhanh -- da do: sai goc 150 do sau mot lan xoay.
if (have_gyro_) {
const double dti = SecondsBetween(m->header.stamp, gyro_stamp_);
if (dti > 0.0 && dti < 0.1) {
gyro_dtheta_ += 0.5 * (gyro_z_ + m->angular_velocity.z) * dti;
gyro_dt_ += dti;
}
}
gyro_z_ = m->angular_velocity.z;
gyro_stamp_ = m->header.stamp;
have_gyro_ = true;
ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z, ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z,
m->angular_velocity_covariance[8] > 0.0 m->angular_velocity_covariance[8] > 0.0
? m->angular_velocity_covariance[8] ? m->angular_velocity_covariance[8]
@@ -108,6 +146,8 @@ StatusResponse Runtime::Wire() {
// ---------------- Encoder ---------------- // ---------------- Encoder ----------------
if (base_ != nullptr) { if (base_ != nullptr) {
VSLAM_INFO("odom: goc quay EKF theo " << (cfg_->ekf_gyro_yaw ? "GYRO" : "ENCODER")
<< " (pipeline.yaml ekf.gyro_yaw) -- gyro van so trong log odom/yaw");
base_->SetEncoderCallback([this](const EncoderReading& e) { base_->SetEncoderCallback([this](const EncoderReading& e) {
if (!e.valid) return; if (!e.valid) return;
Odometry o; Odometry o;
@@ -137,10 +177,25 @@ StatusResponse Runtime::Wire() {
double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta); double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta);
const double dt = SecondsBetween(e.stamp, prev_odom_stamp_); const double dt = SecondsBetween(e.stamp, prev_odom_stamp_);
// Gyro da duoc TICH PHAN trong callback IMU. Chi nhan neu no phu // Goc gyro cho buoc nay: GyroYawFuser -- gyro giu TONG, encoder chi lap
// gan het khoang odom -- thieu mau thi tich phan khong dai dien. // khoang gyro chua ve. Cach cu tich gyro theo luc mau TOI va chi nhan
const bool gyro_ok = gyro_dt_ > 0.5 * dt && dt > 0.0; // khi cua so dai 0.5-1.5 buoc encoder, ngoai do VUT: tren robot that
const double d_theta_gyro = gyro_ok ? gyro_dtheta_ : d_theta; // mau toi theo cum (log 07/10: cua so 40 ms / buoc 22.5 ms) -> ban do
// real_20261007_112455 dem THIEU 9.9% moi goc quay (cac cap node dung
// yen hai dau van 9.6%: loi ti le, khong phai lech gio). IMU cham
// (10 Hz) / het tuoi thi chi encoder, nhu truoc 06/10.
double d_theta_gyro = d_theta;
const bool gyro_step = dt > 0.0 && yaw_fuser_.Step(e.stamp, d_theta, &d_theta_gyro);
// EKF chi lay goc gyro khi pipeline.yaml `ekf.gyro_yaw: true`. Mac dinh
// TAT: WT61PC lech MOT CHIEU khi chay -- 07/10 14:27-14:29 gyro - encoder
// = +0.11..+0.38 rad moi 30 s du quay trai hay phai (+71 do trong 2.5
// phut), dung yen thi tra 0 nen khong thay. Ban do chi encoder (28/09,
// 01/10) thi dung. GyroYawFuser van chay de log `odom/yaw` so hai nguon.
const bool gyro_ok = gyro_step && cfg_->ekf_gyro_yaw;
if (cfg_->ekf_gyro_yaw && !gyro_step && yaw_fuser_.gyro_period() > 0.03) {
VSLAM_WARN_THROTTLE(60.0, "odom: IMU cham (chu ky " << yaw_fuser_.gyro_period() * 1e3
<< " ms) -- goc quay chi theo encoder. Can IMU >= 33 Hz de dung gyro.");
}
// Phuong sai: wheel_odom bao qua twist.covariance -- do chinh la // Phuong sai: wheel_odom bao qua twist.covariance -- do chinh la
// cho no noi "dang truot, dung tin toi". // cho no noi "dang truot, dung tin toi".
@@ -153,11 +208,54 @@ StatusResponse Runtime::Wire() {
gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9; gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9;
const double var_tr = std::max(o.twist.covariance[0] * dt * dt, 1e-12); const double var_tr = std::max(o.twist.covariance[0] * dt * dt, 1e-12);
ekf_->UpdateOdomDelta(e.stamp, d_trans, d_theta, d_theta_gyro, // Di tren doc: z cong tu quang duong DOC mat doc; EKF (SE(2)) nhan
// quang duong NGANG -- doc 15 do ma khong chieu thi ban do gian 3.4%.
double d_trans_ekf = d_trans;
if (slope_on_) {
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
height_->OnWheelStep(d_trans, pitch);
if (cfg_->slope.horizontal_odom) d_trans_ekf = d_trans * std::cos(pitch);
}
// Tat gyro thi EKF nhan DUNG goc encoder, khong phu thuoc ti le phuong sai.
ekf_->UpdateOdomDelta(e.stamp, d_trans_ekf, d_theta, gyro_ok ? d_theta_gyro : d_theta,
var_tr, var_th_enc, var_th_gyro); var_tr, var_th_enc, var_th_gyro);
// Chan doan 30 s mot lan: goc quay RONG theo encoder va theo gyro
// (GyroYawFuser), in HIEU tuyet doi -- lech mot chieu (07/10: gyro
// +0.11..+0.38 rad moi 30 s) doc theo % se tuong la loi ti le. Encoder
// sai ~2% (ban do 28/09, 01/10).
yaw_diag_enc_ += d_theta;
yaw_diag_enc_abs_ += std::fabs(d_theta);
yaw_diag_fused_ += gyro_step ? d_theta_gyro : d_theta;
++yaw_diag_steps_;
if (gyro_step) ++yaw_diag_gyro_;
if (yaw_diag_t0_.isZero()) yaw_diag_t0_ = e.stamp;
if (SecondsBetween(e.stamp, yaw_diag_t0_) >= 30.0) {
if (yaw_diag_enc_abs_ > 0.5) { // co quay, ke ca quay qua lai
VSLAM_INFO("odom/yaw: 30 s qua: quay rong encoder " << yaw_diag_enc_
<< " rad, gyro " << yaw_diag_fused_ << " rad (gyro - encoder "
<< yaw_diag_fused_ - yaw_diag_enc_ << " rad), tong |quay| "
<< yaw_diag_enc_abs_ << " rad, " << 100 * yaw_diag_gyro_ / yaw_diag_steps_
<< "% buoc co gyro (chu ky " << yaw_fuser_.gyro_period() * 1e3
<< " ms) -- EKF theo " << (cfg_->ekf_gyro_yaw ? "GYRO" : "ENCODER"));
}
yaw_diag_enc_ = yaw_diag_enc_abs_ = yaw_diag_fused_ = 0.0;
yaw_diag_steps_ = yaw_diag_gyro_ = 0;
yaw_diag_t0_ = e.stamp;
}
if (slope_on_) {
// Vet banh: san duoi robot o dung z robot. Thu tu khoa odom_mu_ ->
// elev_mu_ (xem runtime.h).
const Pose2D p = ekf_->pose();
std::lock_guard<std::mutex> lk2(elev_mu_);
elev_->AddFootprint(p.x, p.y, height_->z(), 0.15, e.stamp);
}
// Lich su pose cho SLAM (pose LUC QUET, xem runtime.h).
odom_hist_.push_back(OdomAt{e.stamp, ekf_->pose(), slope_on_ ? height_->z() : 0.0});
while (odom_hist_.size() > 2 &&
SecondsBetween(e.stamp, odom_hist_.front().stamp) > 2.0) {
odom_hist_.pop_front();
}
} }
gyro_dtheta_ = 0.0;
gyro_dt_ = 0.0;
prev_odom_ = now_pose; prev_odom_ = now_pose;
prev_odom_stamp_ = e.stamp; prev_odom_stamp_ = e.stamp;
have_prev_odom_ = true; have_prev_odom_ = true;
@@ -197,13 +295,54 @@ StatusResponse Runtime::Wire() {
if (camera_ != nullptr) { if (camera_ != nullptr) {
camera_->SetCallback([this](const CameraFrame& f) { camera_->SetCallback([this](const CameraFrame& f) {
if (!f.depth) return; if (!f.depth) return;
// --- Latch cho SLAM 3D, TRUOC chuoi perception ---
//
// Tap thang vao CameraFrame tho: `depth_filter` chan 30 Hz xuong 10 Hz,
// nhung RTAB-Map tu bo khung bang RGBD/LinearUpdate va Rtabmap/DetectionRate,
// nen cho no khung day du va de no tu chon.
//
// Khong dung `approx_sync.h` o day co y: queue_size mac dinh 30 se ghim
// 30 khung librealsense, va `Fire()` goi callback tren CHINH luong goi
// Add() -- tuc chay Rtabmap::process() (100-600 ms) tren luong camera.
// SlamLoop von da la vong pull "scan moi nhat + odom moi nhat"; them
// "depth moi nhat" la cung mot hinh. Khi nao depth that su can XEP HANG
// thi moi quay lai approx_sync.
if (slam_use_depth_) {
std::lock_guard<std::mutex> lk(depth_mu_);
latest_depth_ = f.depth;
latest_infra1_ = f.infra1;
// CameraInfo nam trong CameraFrame theo VALUE -> phai dong hop de
// SlamLoop cam duoc con tro ra ngoai lock.
latest_depth_info_ = std::make_shared<const CameraInfo>(f.depth_info);
latest_depth_stamp_ = f.header.stamp;
// Qua atomic, khong doc thang GravityAlign: tren --live camera va IMU
// chay tren HAI luong khac nhau.
latest_depth_roll_ = tilt_roll_.load(std::memory_order_relaxed);
latest_depth_pitch_ = tilt_pitch_.load(std::memory_order_relaxed);
have_depth_ = true;
}
// Di tren doc: depth -> ban do do cao san cuc bo (cho ScanLeveler).
if (slope_on_ && have_cam_to_base_) AddDepthToElevation(f);
// Ca chuoi perception chay INLINE o day: depth -> cloud -> loc -> // Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong // can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
// camera. // camera.
const PerceptionOutput po = perception_->Process(*f.depth, f.depth_info); const PerceptionOutput po = perception_->Process(*f.depth, f.depth_info);
std::lock_guard<std::mutex> lk(perc_mu_); std::lock_guard<std::mutex> lk(perc_mu_);
latest_cloud_ = po.cloud_aligned; // ⚠️ CHI ghi de khi CO cloud that. `po.cloud_aligned` la null o moi
// khung bi depth_filter chan (30 Hz vao, 10 Hz ra); gan null vao day la
// xoa mat dam may cuoi cung con dung.
//
// Da do: WebLoop chay 10 Hz, DUNG BANG nhip ra cua bo loc, nen hai ben
// khoa pha -- co luc WebLoop luon doc trung khoang null va web khong co
// cloud nao suot 14 giay lien (log "cloud: tuoi", trong tu 10:03:26 den
// 10:03:40). Man hinh giu dam may cu, nguoi lai thay "cloud tut sau
// scan". Do tre khong nam o duong ong -- duong ong cho ra cloud chi 25-50
// ms tuoi -- no nam o day.
if (po.cloud_aligned) latest_cloud_ = po.cloud_aligned;
latest_cliff_cloud_ = po.cloud_cliff; latest_cliff_cloud_ = po.cloud_cliff;
cliff_flag_ = po.cliff_detected; cliff_flag_ = po.cliff_detected;
cliff_stamp_ = po.stamp; cliff_stamp_ = po.stamp;
@@ -321,7 +460,91 @@ StatusResponse Runtime::Wire() {
have_raw_cmd_ = true; have_raw_cmd_ = true;
})); }));
// ---------------- Tay cam ----------------
//
// Duong thu hai cua LENH, va no di y het duong cua web: tinh ra van toc roi
// ghi `raw_cmd_`. KHONG co nhanh nao cho tay cam goi thang `SetVelocity` --
// lenh tu tay cam van phai qua FSM an toan nhu moi lenh khac.
//
// ⚠️ KHAC base_kit o day, va khac co y: ben do `/joy/cmd_vel` di thang toi
// `zlac_ros_node`, khong co lop an toan nao o giua. Hau qua thuc te: day can
// het co ma truoc mat co vat can trong `slow_distance` (0.80 m) thi xe VAN
// cham lai, trong `stop_distance` (0.35 m) thi VAN dung. Nguoi quen lai
// base_kit se thay "tay cam bi hut mat", va do la lop an toan dang lam viec.
//
// Viec bom lenh nam o `GamepadLoop()`, khong phai o day: joydev khong co
// nhip, nen khong co callback nao de treo vao.
{
GamepadConfig gc = cfg_->gamepad;
if (opts_.gamepad_override > 0) gc.enabled = true;
if (opts_.gamepad_override < 0) gc.enabled = false;
if (!opts_.gamepad_device.empty()) gc.device = opts_.gamepad_device;
if (gc.enabled) {
gamepad_.reset(new GamepadReader(gc, clock_));
gamepad_map_.reset(new GamepadMapper(gc));
gamepad_rate_hz_ = gc.publish_rate_hz;
}
}
return StatusResponse::Ok(); return StatusResponse::Ok();
} }
void Runtime::AddDepthToElevation(const CameraFrame& f) {
const Image& d = *f.depth;
if (d.data == nullptr || d.width == 0 || d.height == 0) return;
const CameraInfo& ci = f.depth_info;
const double fx = ci.fx_binned(), fy = ci.fy_binned();
const double cx = ci.cx_binned(), cy = ci.cy_binned();
if (fx <= 0.0 || fy <= 0.0) return;
Pose2D od;
double z = 0.0;
{
std::lock_guard<std::mutex> lk(odom_mu_);
od = ekf_->pose();
z = height_->z();
}
const double roll = tilt_roll_.load(std::memory_order_relaxed);
const double pitch = tilt_pitch_.load(std::memory_order_relaxed);
// base_footprint DA CAN <- optical: CHUNG TiltLift voi GravityAlign va
// ScanLeveler -- ba ban hinh hoc lech nhau la lop loi da co trong repo cu.
const Transform fp_from_cam = TransformCompose(
TiltLift(roll, pitch, cfg_->robot.geometry().wheel_radius), cam_to_base_static_);
const double c = std::cos(od.theta), s = std::sin(od.theta);
const int stride = std::max(1, cfg_->slope.depth_stride);
const double dmax = cfg_->slope.elevation_max_depth_m;
std::vector<PointXYZ> pts;
pts.reserve((d.width / stride + 1) * (d.height / stride + 1));
for (uint32_t v = 0; v < d.height; v += static_cast<uint32_t>(stride)) {
const uint8_t* row = d.data + static_cast<size_t>(v) * d.step;
for (uint32_t u = 0; u < d.width; u += static_cast<uint32_t>(stride)) {
double depth = 0.0;
if (d.format == PixelFormat::kMono16) {
uint16_t raw;
std::memcpy(&raw, row + 2 * u, 2);
depth = raw * static_cast<double>(d.depth_scale);
} else if (d.format == PixelFormat::kFloat32) {
float raw;
std::memcpy(&raw, row + 4 * u, 4);
depth = raw;
} else {
return;
}
if (!(depth > 0.2) || depth > dmax) continue;
const Point p = TransformPoint(
fp_from_cam, Point{(u - cx) / fx * depth, (v - cy) / fy * depth, depth});
pts.push_back(PointXYZ{static_cast<float>(od.x + c * p.x - s * p.y),
static_cast<float>(od.y + s * p.x + c * p.y),
static_cast<float>(z + p.z)});
}
}
std::lock_guard<std::mutex> lk(elev_mu_);
elev_->AddPoints(pts, f.header.stamp);
if (SecondsBetween(f.header.stamp, elev_pruned_) > 1.0) {
elev_->Prune(od.x, od.y, f.header.stamp);
elev_pruned_ = f.header.stamp;
}
}
} // namespace vslam } // namespace vslam

View File

@@ -14,6 +14,13 @@ ekf:
# Bo qua mau cach mau truoc qua lau: ban ghi bi cat, hoac cam bien vua cam # Bo qua mau cach mau truoc qua lau: ban ghi bi cat, hoac cam bien vua cam
# lai. Tich phan qua mot lo hong 2 giay la bia them sai so. # lai. Tich phan qua mot lo hong 2 giay la bia them sai so.
max_dt: 0.5 max_dt: 0.5
# Goc quay EKF: false = theo ENCODER (nhu truoc 06/10), true = theo gyro
# WT61PC (GyroYawFuser). 07/10 tren robot that: gyro - encoder = +0.11..+0.38
# rad moi 30 s, CA khi quay trai lan quay phai (+71 do trong 2.5 phut); dung
# yen thi WT61PC tra 0 nen khong thay. Ban do chi dung encoder (28/09, 01/10)
# thi dung. Chi bat lai khi da do/bu duoc lech gyro -- log `odom/yaw` van in
# gyro - encoder du tat hay bat.
gyro_yaw: false
# ============ depth -> cloud -> loc ============ # ============ depth -> cloud -> loc ============
depth_filter: depth_filter:
@@ -21,7 +28,14 @@ depth_filter:
# THAY GI -- do la vung mu ma bumper phai bit, # THAY GI -- do la vung mu ma bumper phai bit,
# khong phai vat can o khoang cach do. # khong phai vat can o khoang cach do.
max_range: 4.0 max_range: 4.0
voxel_size: 0.03 # 0.03 -> 0.05 de dam may xuong ~2000 diem NGAY TU NGUON.
#
# `web.cloud_max_points` cung giam mau, nhung bang BUOC DEU -- lay diem thu
# N roi vut phan con lai, nen hinh bi ro. Voxel 5 cm cho ra cung so diem ma
# phan bo deu trong khong gian. Cung mot ngan sach byte, hinh dep hon.
voxel_size: 0.05
# ⚠️ Day la TRAN tan so cua cloud tren web. `web.cloud_rate_hz` cao hon so
# nay chi lam gui lai dung mot dam may hai lan.
max_rate: 10.0 # Hz. 30 Hz vao, 10 Hz ra. max_rate: 10.0 # Hz. 30 Hz vao, 10 Hz ra.
enable_temporal: false enable_temporal: false
min_hits: 3 min_hits: 3
@@ -53,35 +67,77 @@ cliff_detect:
# ky cho hut nao. LiDAR khong thay xuong duoi mat phang quet cua no, va # ky cho hut nao. LiDAR khong thay xuong duoi mat phang quet cua no, va
# bumper chi bao SAU khi da cham. Chi lai o noi chac chan khong co mep roi, # bumper chi bao SAU khi da cham. Chi lai o noi chac chan khong co mep roi,
# va co nguoi dung canh. # va co nguoi dung canh.
# ⚠️ TAT CO Y -- ROBOT DANG MU VUC. Doc het truoc khi bat lai.
#
# Nguyen nhan KHONG phai tham so sai, ma la HINH HOC PHAN CUNG: camera dat
# NGANG o 0.445 m nen chi vai hang pixel duoi cung cham san, o goc 14-21 do.
# Stereo nhin san phang khong van o goc luot nhu vay gan nhu khong tra ve gi.
#
# Do duoc tren robot, robot dung yen giua cho trong:
# n_cliff=49 (lo=55 hut=0, trong cua so=676)
# `hut=0` la cho quyet dinh: KHONG co diem nao thap hon nguong that. Toan bo
# la LO -- cho le ra thay san ma khong co so do.
#
# Va detector khong the phan biet: cau thang toi cho ra lo, san khong van
# cung cho ra lo. No chon phia an toan, dung ve nguyen tac, sai ve thuc te
# o day -- fail_safe chan robot lien tuc giua san phang.
#
# ============ DA THU HET DUONG PHAN MEM ============
# - chieu cao camera: do lai bang thuoc, 0.3935 -> 0.445 m (lech 5.15 cm).
# z0 tu -0.098 ve -0.002. Dung huong nhung khong du.
# - min_dist 1.00 -> 1.15, max_dist 1.50 -> 1.70: tinh lai theo chieu cao
# moi. 1.00 cu da roi VAO TRONG vung mu hinh hoc (1.105 m).
# - tach log lo/hut: chinh nho no moi biet `hut=0`.
# Khong con gi sua duoc bang cau hinh voi hinh hoc nay.
#
# ============ DUONG SUA THAT ============
# CHUC CAMERA XUONG 15-20 do. Canh gan tu 1.15 m ve ~0.5 m, goc nhin san tu
# 14-21 do len 25-42 do -- du doc de stereo bat duoc san.
#
# Da thu tren robot: chuc xuong roi chup lai thi dam may diem CO san that,
# trai rong truoc mui robot thay vi vai cum roi rac. Huong dung.
#
# ⚠️ Khi chuc thi PHAI dat `camera_link.rpy` pitch trong robot.yaml cho khop.
# Da thu quen buoc do: TF van khai pitch = 0 nen detector chieu tia y nhu cu
# (`san thay o 1.215..` va `trong cua so=675` giong het den tung con so), va
# `lo` bung tu 150 len 516. Doi phan cung ma quen doi TF thi te hon truoc.
#
# Va tinh lai ca min_dist lan max_dist -- cong thuc doi han khi co goc chuc,
# khong dung lai `chieu_cao / tan(21.9 do)` duoc nua.
enabled: false enabled: false
# ⚠️ min_dist la VUNG MU HINH HOC, khong phai lua chon tuy y. # ⚠️ min_dist la VUNG MU HINH HOC, khong phai lua chon tuy y.
# #
# Camera DAT NGANG (robot.yaml: rpy pitch = 0), cao 0.3935 m so voi san. # Camera DAT NGANG (robot.yaml: rpy pitch = 0), cao 0.445 m so voi san.
# Nua FOV doc cua D410 = 21.9 do (suy tu fx = 595.914 tren anh 640x480). # Nua FOV doc cua D410 = 21.9 do (suy tu fx = 595.914 tren anh 640x480).
# Tia thap nhat vi the chi nghieng 21.9 do, cham san o: # Tia thap nhat vi the chi nghieng 21.9 do, cham san o:
# 0.3935 / tan(21.9 do) = 0.977 m # 0.445 / tan(21.9 do) = 1.105 m
# Cong bien -> 1.00. # Cong bien -> 1.15.
#
# ⚠️ Con so nay PHAI tinh lai moi khi doi chieu cao camera. Gia tri cu 1.00
# tinh cho 0.3935 m; sau khi do lai duoc 0.445 m thi 1.00 roi VAO TRONG vung
# mu, va detector se soi vao cho khong the thay san roi bao vuc.
# #
# ⚠️ Gia tri cu 0.55 duoc tinh khi con tuong camera chuc 15 do. Voi camera # ⚠️ Gia tri cu 0.55 duoc tinh khi con tuong camera chuc 15 do. Voi camera
# ngang thi 70% cua so nam trong VUNG MU -- detector soi vao cho khong the # ngang thi 70% cua so nam trong VUNG MU -- detector soi vao cho khong the
# co san, va bail lien tuc (few_samples / offset_large) roi fail_safe bao # co san, va bail lien tuc (few_samples / offset_large) roi fail_safe bao
# vuc. Do la nguyen nhan that cua "VUC phia truoc" khi truoc mat trong. # vuc. Do la nguyen nhan that cua "VUC phia truoc" khi truoc mat trong.
min_dist: 1.00 min_dist: 1.15
# Gioi han NHIEU DEPTH, khong phai hinh hoc: cang luot san thi stereo cang # Gioi han NHIEU DEPTH, khong phai hinh hoc: cang luot san thi stereo cang
# khong bat duoc gi tren san phang khong van. # khong bat duoc gi tren san phang khong van.
# 1.00 m -> 21.5 do 1.50 m -> 14.7 do # Voi camera o 0.445 m:
# 1.25 m -> 17.5 do 2.00 m -> 11.1 do # 1.15 m -> 21.2 do 1.70 m -> 14.7 do
# Thiet ke goc chap nhan toi 17.7 do (camera 0.80 m nhin 2.50 m). Giu dung # 1.50 m -> 16.5 do 2.00 m -> 12.5 do
# muc do thi max_dist = 1.23, tuc cua so chi rong 23 cm -- qua hep de on # Ban truoc (camera 0.3935 m) chap nhan toi 14.7 do o canh xa. Giu dung muc
# dinh. Lay 1.50 (14.7 do), long hon mot chut, doi lai cua so 50 cm. # do: 0.445 / tan(14.7 do) = 1.696 -> 1.70. Cua so rong 55 cm, hon ban truoc
# 5 cm -- camera cao hon thi tia bot luot, day la mat loi.
# #
# ⚠️ Camera dat NGANG o 0.39 m la hinh hoc kem cho viec do vuc: toan bo dai # ⚠️ Camera dat NGANG van la hinh hoc kem cho viec do vuc: canh gan bi day ra
# dung duoc deu luot hon truong hop XAU NHAT cua thiet ke goc. Chuc camera # 1.15 m, tuc robot khong thay duoc gi trong ban kinh do. Chuc camera xuong
# xuong 15-20 do se keo canh gan tu 0.98 m ve 0.52 m va lam cua so rong gap # 15-20 do se keo canh gan ve khoang 0.6 m va lam cua so rong gap ba. Neu
# ba. Neu phat hien vuc quan trong thi day la thay doi phan cung dang lam. # phat hien vuc quan trong thi day la thay doi phan cung dang lam.
max_dist: 1.50 max_dist: 1.70
cliff_margin: 0.05 cliff_margin: 0.05
pitch_uncertainty_deg: 2.0 pitch_uncertainty_deg: 2.0

View File

@@ -97,11 +97,20 @@ frames:
# D410 va LiDAR THANG HANG nhau: cung nam tren duong giua robot (y = 0), # D410 va LiDAR THANG HANG nhau: cung nam tren duong giua robot (y = 0),
# cach nhau 9.5 cm theo truc doc than va 17.7 cm theo chieu cao. # cach nhau 9.5 cm theo truc doc than va 17.7 cm theo chieu cao.
# #
# LiDAR o [0, 0, 0.13] => camera o [0.095, 0, 0.307] so voi tam truc # LiDAR o [0, 0, 0.13] => camera o [0.095, 0, 0.3585] so voi tam truc
# => 0.307 + wheel_radius 0.0865 = 0.3935 so voi SAN. # => 0.3585 + wheel_radius 0.0865 = 0.445 so voi SAN.
#
# ⚠️ 0.3585 la KET QUA DO BANG THUOC, thay cho 0.307 truoc day.
# Do tu san len tam hang ong kinh module depth: 44.5 cm.
#
# Gia tri cu lech 5.15 cm, va cliff_detect bat duoc dieu do truoc khi ai
# cam thuoc: no khop mat san voi mad chi 2-5 mm (tuc khop DUNG san, khong
# phai tuong hay vat can) nhung bao mat phang do nam o z0 = -0.049 m. San
# thap hon du kien 5 cm thi theo dinh nghia do LA mot hut 5 cm, nen no bao
# VUC giua cho trong. Phep do dung, MOC sai.
# `cliff_detect.nominal_tz` PHAI bang tong do; RobotModel tu tinh va kiem, # `cliff_detect.nominal_tz` PHAI bang tong do; RobotModel tu tinh va kiem,
# khong de nguoi dung go lai hai lan. # khong de nguoi dung go lai hai lan.
xyz: [0.095, 0.0, 0.307] xyz: [0.095, 0.0, 0.3585]
# rpy = [roll, pitch, yaw] -- camera DAT THANG, khong chuc, khong xoay. # rpy = [roll, pitch, yaw] -- camera DAT THANG, khong chuc, khong xoay.
# #
# ⚠️ Truoc day o day la pitch 0.2618 (chuc 15 do), thua ke tu cau hinh cu # ⚠️ Truoc day o day la pitch 0.2618 (chuc 15 do), thua ke tu cau hinh cu
@@ -151,7 +160,7 @@ frames:
# ============ BASE ============ # ============ BASE ============
base: base:
max_linear: 0.35 # m/s max_linear: 0.50 # m/s (2026-09-28)
max_angular: 0.80 # rad/s max_angular: 0.80 # rad/s
accel_limit: 0.30 # m/s^2 accel_limit: 0.30 # m/s^2
# Base tu dung robot neu khong co lenh trong ngan nay. Phai NGAN hon # Base tu dung robot neu khong co lenh trong ngan nay. Phai NGAN hon

View File

@@ -11,7 +11,8 @@
# ============ Quat truoc theo LiDAR ============ # ============ Quat truoc theo LiDAR ============
scan: scan:
# Duoi khoang cach nay thi chan TIEN han. # Duoi khoang cach nay thi chan TIEN han.
stop_distance: 0.35 # 0.5 m/s: ham ~0.16 m (0.079 m o 0.35, ti le v^2) + ~0.08 m phan ung
stop_distance: 0.45
# Trong dai [stop, slow] thi giam toc theo slow_factor. # Trong dai [stop, slow] thi giam toc theo slow_factor.
slow_distance: 0.80 slow_distance: 0.80
slow_factor: 0.4 slow_factor: 0.4
@@ -35,7 +36,7 @@ scan:
# ============ Cam bien khac ============ # ============ Cam bien khac ============
ultrasonic: ultrasonic:
us_stop_distance: 0.30 us_stop_distance: 0.40
cliff: cliff:
enable_cliff_stop: true enable_cliff_stop: true
@@ -80,5 +81,5 @@ bumper:
escape_angular: 0.4 escape_angular: 0.4
limits: limits:
max_linear: 0.35 max_linear: 0.50
max_angular: 0.8 max_angular: 0.8

View File

@@ -38,20 +38,110 @@ lidar:
# #
# KIEM LAI khi thay doi bat cu gi: dung ben TRAI robot, cham phai hien ben # KIEM LAI khi thay doi bat cu gi: dung ben TRAI robot, cham phai hien ben
# TRAI tren man hinh. # TRAI tren man hinh.
angle_offset_deg: 180.0 #
# --- 178.75 chu khong phai 180: lech GA DAT, do duoc ---
# ReportBlindSector bao tam quat mu o -178.75 do suot 6/6 lan doc, rong
# 89.75-90.25 do (dung 90 do nen tam tin duoc). Tuc LiDAR gan lech 1.25 do.
#
# 1.25 do nghe nho nhung o 5 m la 11 cm lech ngang -- du de lam nhoe tuong
# khi dung ban do. Sua o day chu khong sua rpy trong robot.yaml: ScanSanitizer
# va sector_masks doc THANG goc cua scan, chung khong di qua TF.
#
# ⚠️ Con so nay chi sua duoc phan XOAY. No khong noi gi ve lat guong -- xem
# canh bao tren.
angle_offset_deg: 178.75
angle_flip: true angle_flip: true
# --- Ve sinh scan --- # --- Ve sinh scan ---
# ScanSanitizer gop header-fix va sector mask lam MOT ham. Hai bo loc rieng # ScanSanitizer gop header-fix va sector mask lam MOT ham. Hai bo loc rieng
# thi thu tu chay giua chung la mot bay: mask truoc hay sua header truoc cho # thi thu tu chay giua chung la mot bay: mask truoc hay sua header truoc cho
# ra ket qua khac nhau. # ra ket qua khac nhau.
range_min: 0.05 # Lay y het lakibeam.yaml cua base_kit -- bo tham so da chinh tren robot nay.
range_max: 40.0 #
# ⚠️ range_min 0.19 chu khong phai 0.05. 5 cm nam trong chinh khung robot va
# duoi gioi han tin cay cua thiet bi: tia tra ve o khoang do la phan xa lech
# tu cot chong / khung ga -- dung loai rac ma bon bo loc ben duoi dang phai
# don. Chan ngay o day re hon loc sau.
#
# range_max 30 chu khong phai 40: datasheet LakiBeam1L ghi 40 m, nhung
# base_kit dung 30 -- bien 25% cho vung xa kem tin cay.
range_min: 0.19
range_max: 30.0
# Bo phat hien mat goi mien phi: canh bao neu # Bo phat hien mat goi mien phi: canh bao neu
# |(t_cuoi - t_dau) - scan_time| > nguong nay. # |(t_cuoi - t_dau) - scan_time| > nguong nay.
stamp_mismatch_warn: 0.005 stamp_mismatch_warn: 0.005
# --- Gio cua scan so voi odometry: DO tren ban do that ---
# Driver dong dau scan luc NHAN XONG vong quet. ICP scan luc robot dang QUAY
# voi scan gan do luc gan dung yen (ban do 28/09 + 01/10, 88 + 179 cap): scan
# tre +55..57 ms so voi odometry SAU khi chinh meo (+72..79 ms neu khong).
# Quay 0.8 rad/s ma khong bu -> moi scan lech 2.5-3.5 do, tuong dup sau moi
# lan quay. Doi phan cung / driver thi do lai.
stamp_offset_sec: -0.055
# Chinh meo: moi tia chup o mot thoi diem khac trong vong quet 40 ms (25 Hz);
# quay 0.8 rad/s thi tia dau va tia cuoi lech 1.8 do. Dua moi tia ve khung
# robot luc stamp theo w, v cua EKF. Chieu quet DO tren ban do that: goc GIAM
# theo thoi gian khi angle_flip: true (vong bat dau o angle_offset_deg, phia
# sau); chieu nguoc lai lam scan khop TE hon. Chi LiDAR that (--live,
# --replay) -- scan sim chup tuc thoi. Ban cho SLAM / dinh vi lai; an toan va
# web van dung scan tho.
deskew: true
# ============ BON BO LOC SCAN ============
# Chay TREN scan tho, truoc ScanSanitizer. Nguon: lakibeam.yaml cua
# base_kit -- bo tham so da duoc chinh tren chinh con robot nay.
#
# Vi sao can, ngoai ScanSanitizer: ScanSanitizer chi cat QUAT CO DINH. Rac
# sinh ra tu bon cot do hai tang tren khong nam gon trong quat nao -- no doi
# cho theo goc nhin va theo khoang cach vat the.
filters:
# --- Tia keo dai (shadow / grazing angle) ---
# Tia luot qua MEP mot vat (cot chong) ve ra mot dai diem cheo keo dai ra
# sau vat do, trong nhu mot buc tuong khong co that.
shadow_enabled: true
shadow_min_angle_deg: 12.0 # duoi goc nay coi la tia keo dai
shadow_window: 4 # so tia lan can de xet
shadow_min_range_diff: 0.05 # buoc nhay cu ly toi thieu, m
shadow_max_range: 2.0 # chi loc trong pham vi nay, m
shadow_clear_start: false # giu diem mep -- de khong an mat tuong that
shadow_clear_neighbors: 0 # 0 = khong lan sang diem tuong that
# --- Cuong do phan xa (RSSI 0-255) ---
# Tan xa yeu o gan thuong la bui hoac phan xa lech tu khung gan.
intensity_enabled: true
intensity_min: 30.0
intensity_max: 255.0
intensity_max_range: 1.0 # chi loc trong pham vi nay -- bao ve vat o xa
# --- Cum diem don le ---
isolated_enabled: true
isolated_min_cluster_points: 3 # cum nho hon nguong nay thi xoa
isolated_max_range_jump: 0.10 # hai tia lien tiep con coi la mot cum, m
isolated_max_range: 2.0 # 0 = ap dung toan scan
# --- Hop quanh than robot ---
#
# ⚠️ Day moi la thu THAY THE dung dan cho `sector_masks` ben duoi.
# sector_masks cat theo GOC, hop ly khi LiDAR nam o MEP truoc (x=0.24 nhu
# cau hinh cu). LiDAR gio o TAM robot (x=0), nen vung bi khung gan che
# khong con la mot quat goc ma la mot vung hinh HOP quanh goc toa do.
# ⚠️ box_max_y 0.25 chu KHONG phai 0.0 nhu lakibeam.yaml cua base_kit.
#
# base_kit de 0.0 nen hop chi phu nua ben y AM. Tren robot nay bon cot do
# nam doi xung o y = +-0.136, nen mot nua so cot lot ra ngoai hop va van
# bi quet vao -- do dung la hien tuong "mot chan cot bi quet, chan kia thi
# khong" quan sat duoc tren web.
#
# Day la cho ma chep y het base_kit lai SAI: bo tham so cua ho chinh cho
# mot khung ga khac, va cai bat doi xung do la co chu dich ben ho (comment
# goc: "de khong che tuong sau").
box_enabled: true
box_min_x: -0.25
box_max_x: 0.25
box_min_y: -0.25
box_max_y: 0.25
# Quat bi than robot che, don vi DO. # Quat bi than robot che, don vi DO.
# #
# ⚠️⚠️ HAI GIA TRI DUOI DAY DA MAT CAN CU -- PHAI DO LAI TRUOC KHI BAT SAFETY. # ⚠️⚠️ HAI GIA TRI DUOI DAY DA MAT CAN CU -- PHAI DO LAI TRUOC KHI BAT SAFETY.
@@ -93,11 +183,27 @@ camera:
# TIME_OF_ARRIVAL. Giu true van dung, duong lui da chay. # TIME_OF_ARRIVAL. Giu true van dung, duong lui da chay.
prefer_global_time: true prefer_global_time: true
# ============ MCU ============ # ============ MCU / IMU ============
mcu: mcu:
port: /dev/ttyACM0 # ============ NOI IMU VAO MAY ============
# 115200 theo firmware that (ESP32-S3 + WT61PC). Gia tri cu la 921600 -- doc # wt61pc = WT61PC noi THANG UART hoac cap USB-FTDI, khung nhi phan 0x55 cua
# sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang. # cam bien (wt61pc_protocol.h). Khong con ESP32, khong co ClockSync:
# stamp lay tu dong ho HOST, tru imu_lag_sec.
# esp = ESP32-S3 + WT61PC qua USB-CDC (cach cu, firmware/imu_uart/).
# Cac muc sync_window, max_skew_warn, expect_timestamps, ticks_per_rev ben
# duoi CHI co nghia voi `esp`.
protocol: wt61pc
# wt61pc: /dev/imu do luat udev tao (configuration_files/udev/99-imu.rules: cap
# FTDI 0403:6001 -> SYMLINK+="imu", latency_timer 1 ms). Cam bien DA DOI
# sang 115200 baud / 200 Hz (2026-10-06, luu trong cam bien; xuat xuong
# 9600 / 10 Hz). Day la baud HOST nghe, phai trung baud da luu trong cam
# bien: sai thi IMU im, log "checksum sai". Cong duoc KHOA DOC QUYEN:
# chuong trinh khac (imu_ros_node cua motor_control) mo cong sau se loi
# EBUSY.
# esp: /dev/ttyACM0 @ 115200 theo firmware that. Gia tri cu la 921600 --
# doc sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang.
port: /dev/imu
baud: 115200 baud: 115200
# ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh. # ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh.
@@ -110,6 +216,77 @@ mcu:
expected_imu_rate_hz: 200.0 expected_imu_rate_hz: 200.0
# ============ DINH DANG FIRMWARE ============
# false = firmware cu, ba dong text `Acc` / `Gyro` / `Angle`, khong co dau
# thoi gian. Stamp lay tu dong ho HOST luc doc duoc dong.
# true = firmware trong firmware/imu_uart/, phat ban ghi
# `I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az>` theo mcu_protocol.h.
# mcu_bridge dung ClockSync anh xa dong ho MCU sang dong ho host.
#
# ⚠️ Chi bat sau khi DA FLASH firmware moi. Sai gia tri nay khong lam crash:
# parser cua nhanh kia tu choi moi dong va IMU im lang tat -- trieu chung la
# `wheel_odom: khong co IMU moi -> Odometry dang chay 'mu'`.
#
# Da flash va da kiem: log bao `ClockSync skew -59 ppm` (dai thach anh that),
# va `wheel_odom/lag` bao 0 ms.
expect_timestamps: true
# ============ BU DO TRE IMU ============
# Firmware khong phat timestamp, nen stamp cua mot mau IMU la luc HOST doc
# duoc dong -- mau do thuc ra DO ROBOT SOM HON the. Tru con so nay vao stamp.
#
# Don vi GIAY. Sua o day chu khong sua trong wheel_odometry: dau thoi gian
# sinh ra o mcu_bridge, va EkfSe2 cung an no. Bu o mot cho tieu thu thi cho
# con lai van sai.
#
# --- Vi sao can: do duoc tren robot nay ---
# Bon lan `nghi TRUOT BANH` deu roi dung luc robot vao/ra cua, lech 0.20-0.22
# rad/s -- dung bang slip_threshold. Hai trong bon lan encoder doc IT hon
# gyro, ma truot banh lam encoder doc NHIEU hon su that: khong phai truot.
# Quay DEU o omega 0.68 (gap doi luc bao truot) thi lech chi +-0.02, nen
# counts_per_rev khong phai thu phao.
#
# --- Cach do ---
# 1. Chay --live, lai robot VAO RA CUA vai lan (dung yen hay quay deu thi
# khong do duoc gi: moi tau deu tot nhu nhau).
# 2. Doc log `wheel_odom/lag: tot nhat XX ms`.
# 3. Dat imu_lag_sec = XX/1000, chay lai.
# 4. Lan nay log PHAI bao ~0 ms. Neu van bao XX thi mo hinh tre sai, dung
# tang dai -- doc lai truoc.
#
# --- 0.07: DO DUOC, khong phai chinh tay ---
# Con so nay den tu may do o tren, khong phai suy ra tu ly thuyet:
# lan truoc 0.08 <- tam lan do bao 80 ms (mau 3500 -> 6500)
# 2026-09-23 0.07 <- do lai tren robot that, lai bang tay cam:
# `tot nhat -10 ms` on dinh tu mau 2000 den 7500,
# vao ra cua lien tuc
#
# Tuc 0.08 bu THUA dung MOT bin. Bin cua may do la 10 ms (kLagStepSec,
# wheel_odometry.h:176-178) nen 10 ms cung la DO PHAN GIAI: lan chay sau
# phai bao ~0 ms, con neu van bao -10 ms thi da cham day, dung chinh tiep.
#
# ~70 ms do KHONG nam o phia host, nen firmware dong dau som cach may cung
# khong bot duoc:
# ~50 ms WT61PC loc/trung binh noi bo o che do 10 Hz
# ~23 ms day 2 khung Acc+Gyro qua day 9600 baud
# Ca hai deu xay ra TRUOC luc ESP32 dong dau. Xem firmware/imu_uart/README.md.
# (Tong ly thuyet 73 ms nam GIUA hai bin 0.07 va 0.08 -- do la ly do con so
# nay nhay mot bin giua hai lan do, khong phai vi phan cung doi.)
#
# ⚠️ Phai do lai neu doi tan so cam bien hoac baud cua day UART1 -- ca hai so
# hang tren deu phu thuoc chung.
#
# ⚠️ 0.07 do duoc tren duong ESP32 + USB-CDC. Voi protocol: wt61pc (UART
# thang, khong ESP32) duong truyen khac, nen DO LAI bang quy trinh o tren
# truoc khi tin con so nay.
#
# --- 2026-10-06: 115200 baud / 200 Hz, DO tren robot that ---
# dat 0.01 (uoc luong) -> log `tot nhat 20 ms` on dinh tu mau 1000 den
# 5000, lai ra vao cua -> 0.01 + 0.02 = 0.03. Uoc luong ~2 ms day khung +
# ~1 ms USB nen loc noi bo cua cam bien ~27 ms, khong phai 3-10 ms.
# Lan chay sau phai bao ~0 ms (bin 10 ms). Giu 0.07 o 200 Hz la lech ~40 ms.
imu_lag_sec: 0.03
# Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao # Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao
# thuc cu chi co I/B/P. # thuc cu chi co I/B/P.
# #
@@ -142,11 +319,32 @@ base:
# 0 = dung mac dinh 16384, suy tu 0x200E:01 = 4096 "wire" doc duoc tren # 0 = dung mac dinh 16384, suy tu 0x200E:01 = 4096 "wire" doc duoc tren
# thiet bi, nhan 4 theo quy uoc cau phuong. # thiet bi, nhan 4 theo quy uoc cau phuong.
# #
# ⚠️ He so x4 CHUA KIEM CHUNG -- can_help.pdf khong cho nao noi quan he giua # He so x4: DA KIEM CHUNG tren robot that 2026-09-23 (khong phai bang
# "wire" va "count". Sai he so nay lam odometry sai dung 4 lan. # can_help.pdf -- tai lieu do khong noi gi ve quan he "wire" va "count").
# #
# Cach do (2 phut): ke banh len khoi san, doc 0x6064:01, quay banh dung MOT # Bang chung: dong `wheel_odom/dbg` trong mot phien lai 3.5 phut cho
# vong bang tay, doc lai. Hieu so chinh la count/vong that -- dat vao day. # enc 0.823336 gyro 0.824332 (lech 0.12%, quay deu)
# enc -0.750065 gyro -0.73921
# trung binh lech -0.0015 rad/s tren 7671 mau
# Sai he so cau phuong thi ti so enc/gyro phai la 4 hoac 0.25, khong phai
# 1.001. Nen 16384 la dung.
#
# Giu lai cach do truc tiep phong khi doi encoder: ke banh len khoi san, doc
# 0x6064:01, quay banh dung MOT vong bang tay, doc lai.
# cansend can0 601#40.64.60.01.00.00.00.00 # cansend can0 601#40.64.60.01.00.00.00.00
# candump can0,581:7FF -n 1 # candump can0,581:7FF -n 1
#
# ⚠️ base_kit KHONG tra loi duoc cau hoi nay. motor_params.yaml cua ho khong
# co tham so nao ve encoder, vi zlac_ros_node chi doc VAN TOC (0x606C, don vi
# rpm da co san) -- khong bao gio phai doi count sang radian. Chi du an nay
# doc 0x6064 nen chi du an nay can con so do.
encoder_counts_per_rev: 0 encoder_counts_per_rev: 0
# Thoi gian ramp tang/giam toc (0x6083 / 0x6084), ms tu 0 den toc do dinh
# muc. SO CANG LON CANG CHAM.
#
# 1200 lay tu base_kit/src/Zlac_ros/config/motor_params.yaml (acc_dec_val).
# Mac dinh cua ZlacMotorDriver la 500 -- tang toc nhanh gap 2.4 lan, du de
# banh truot that tren san tron. Day la tham so cua THIET BI va base_kit da
# chinh no tren chinh con robot nay, nen theo ho.
accel_ramp_ms: 500

View File

@@ -21,9 +21,20 @@ mode: localization
# Bat buoc (require<>): khong co mac dinh. Mot mac dinh im lang se ghi ban do # Bat buoc (require<>): khong co mac dinh. Mot mac dinh im lang se ghi ban do
# vao cho khong ai tim thay. # vao cho khong ai tim thay.
# #
# Duong dan TUONG DOI duoc giai theo MapDir() = $VSLAM_RESOURCE_DIR/maps, tuc
# `<repo>/resources/maps/` khi chay tu cay nguon va
# <localstatedir>/lib/vslam/resources/maps sau khi cai. Tuyet doi dung nguyen.
#
# De RONG ("") nghia la DB trong RAM -- dung khi quet thu voi bo mo phong, # De RONG ("") nghia la DB trong RAM -- dung khi quet thu voi bo mo phong,
# khong de lai gi tren dia. # khong de lai gi tren dia.
database_path: /var/lib/vslam/maps/map.db #
# ⚠️ `{stamp}` no ra %Y%m%d_%H%M%S. Quet ban do MOI thi dung
# `--slam-db "map_{stamp}.db"`: mapping vao mot DB da co node bi TU CHOI khoi
# dong (RTAB-Map 0.21.13 -- xem rtabmap_slam.cc).
#
# KHONG dat {stamp} lam mac dinh o day: mode mac dinh la localization, ma ten
# co dau thoi gian thi khong bao gio khop file nao.
database_path: map.db
# ============ OPTIMIZER ============ # ============ OPTIMIZER ============
# "0"=TORO "1"=g2o "2"=GTSAM "3"=Ceres # "0"=TORO "1"=g2o "2"=GTSAM "3"=Ceres
@@ -39,6 +50,22 @@ database_path: /var/lib/vslam/maps/map.db
# Do duoc tren map_house.db (240 node): xem docs/SLAM.md. # Do duoc tren map_house.db (240 node): xem docs/SLAM.md.
optimizer_strategy: "1" optimizer_strategy: "1"
# ============ DO CHAC CUA ODOM ============
# Sigma MOI LIEN KET giua hai node (~0.1-0.3 m di chuyen) gui RTAB-Map.
#
# Mac dinh cu (khong dat) la 10 cm / 5.7 do moi lien ket -- te hon ICP
# (1.1 do) ~5 lan, nen toi uu do thi nghe ICP. Moi lien ket ICP sai rat it
# (TB 0.7 cm / 0.15 do) nhung 37 phut quet co 2542 lien ket, cong don thanh
# xoay ~3 do va lech 0.25 m (do tren DB 2026-09-25).
#
# ⚠️ ROBOT THAT 2026-09-25: 0.01/0.005 lam ban do xoan -- odom that sai
# nhieu do/buoc (IMU 10 Hz dem goc hai lan), khai chac thi ICP khong nan
# duoc. Chay lai DB that: 0.01/0.005 van xoan; 0.1/0.1 hanh lang thang,
# phong vuong. (Mo phong thi 0.01/0.005 tot hon ~30% -- odom mo phong gan
# nhu hoan hao.)
#
# -> GIA TRI nam o `profiles:` cuoi file: mo phong va robot that khac nhau.
# ============ THI GIAC ============ # ============ THI GIAC ============
# Kp/MaxFeatures: -1 khi false, 400 khi true. # Kp/MaxFeatures: -1 khi false, 400 khi true.
# #
@@ -49,7 +76,173 @@ optimizer_strategy: "1"
# Da do tren robot nay: 42/43 vong dong thi giac bi loai voi 0/20 inlier -- # Da do tren robot nay: 42/43 vong dong thi giac bi loai voi 0/20 inlier --
# camera dong gop 0 cho dinh vi. Bat len chi ton CPU. # camera dong gop 0 cho dinh vi. Bat len chi ton CPU.
visual_loop: false visual_loop: false
camera_3d: false
# Cong tac cua BAN DO VOXEL 3D tren web UI.
#
# Bat len thi:
# * depth cua camera vao RTAB-Map cung scan, va duoc LUU trong DB;
# * ban do voxel 3D dung NGOAI process(): depth cua moi node chieu thanh
# diem MOT lan (cache theo node), roi ghep theo pose da toi uu.
# KHONG doi luoi: Grid/* van la 2D, chi tu LiDAR (xem BuildRtabmapParams).
#
# Vi sao khong de RTAB-Map dung luoi 3D (Grid/Sensor=2 + Grid/3D=true, cach
# cu truoc 2026-09-24): no keo pose lech. Do trong mo phong, hospital,
# 0.7 m/s, sai so vs ground truth luc dung yen:
# 2D thuan 0.009 m
# luoi 3D (cach cu) 0.06-0.11 m
# luoi 3D, tat Grid/RayTracing 0.035 m
# depth vao, luoi giu 2D 0.024 m <- cach hien tai
#
# ⚠️ Luoi 2D KHONG con vat can thap chi camera thay (mat ban, bac thang) --
# chung chi con trong ban do 3D. `Grid/Sensor: "2"` trong khoi `rtabmap:`
# se dua chung lai, nhung CHUA do xem no co keo pose lech khong.
#
# ⚠️ DB phai quet voi camera_3d: true thi moi co depth de dung ban do 3D.
# DB quet voi false van mo duoc, chi la ban do 3D rong.
camera_3d: true
# ============ BAN DO VOXEL 3D ============
# Hinh hoc cua ban do 3D gui len web. Chi duoc dung khi camera_3d: true.
#
# Tham so TRUYEN (nhip gui, kich thuoc manh) nam o system.yaml khoi `web` --
# mot ben la ban do, mot ben la duong day.
voxel:
# Kich thuoc o PHAT. Bang Grid/CellSize cua SLAM, co y.
#
# Day la buoc luoi de KHU TRUNG LAP, khong phai kich thuoc thu se ve ra: web
# ve tap nay bang DIEM chu khong bang hop. Lam tho len 0.10 cat duoc 8 lan so
# diem, nhung o tren man hinh no thanh mot khoi Minecraft chu khong con ra
# mot ban quet.
emit_size_m: 0.05
# Cat san va tran. z do tu mat san (base_footprint).
#
# z_min 0.05 chu khong phai 0: gravity_align chi bang phang san toi vai cm,
# va mot lop voxel mong tren khap san lam khung 3D khong doc duoc gi.
z_min: 0.05
# 2.0 m: cao hon dinh robot, thap hon tran nha. Vut tran di vi no che het
# khi nhin tu tren xuong.
z_max: 2.00
# Tran SO O PHAT (khong phai tran cua ban do).
#
# Cham tran thi ban do duoc GIAM MAU DEU -- giu nguyen hinh dang, chi thua
# di -- va log bao `GIAM MAU 1/k`. KHONG cat cut: cat cut mot danh sach da
# sort theo x nghia la mot canh cua toa nha bien mat, va do dung la loi da
# mac phai o ban dau.
#
# Nang so nay lam ban do min hon nhung lan dong bo dau nang hon theo ti le
# thang: moi o la 6 byte tren day.
#
# Uoc luong o 0.05 m: mot tang 30x30 m, tuong cao 2 m, chi be mat, la ~96k o;
# phong that co do dac vao khoang 150-250k. 300k la cho thua, KHONG phai
# muc tieu.
#
# ⚠️ Con so nay keo theo bang thong lan dong bo dau: 300k o x 6 byte =
# 1.8 MB. Xem phep tinh o system.yaml khoi `web`.
max_cells: 300000
# (them + bot) / tong vuot nguong nay thi gui lai CA TAP thay vi delta.
#
# Sau mot lan toi uu do thi (dong vong), pose dich cho nen gan nhu MOI voxel
# doi chi so -- delta khi do to hon ca ban do. Nguong nay tu phat hien ra
# dieu do ma khong can do xem co vong dong hay khong.
delta_max_ratio: 0.35
# Lop vat can tu camera gop vao luoi 2D: voxel co z trong khoang nay (tinh
# tu mat san) bi danh dau la tuong. Bat nhung thu LiDAR (0.2165 m) khong
# cat ngang: mat ghe, khung giuong, ke thap. Lam NGOAI RTAB-Map -- dua depth
# vao Grid/Sensor keo pose lech (do 2026-09-24: sai so TB 0.020 -> 0.052 m).
# 0.15: duoi day coi la san (nguong cua, day cap, nhieu depth + gravity_align)
# 0.55: noc robot ~0.46 m (mat ga camera 0.405 m tu san + camera) + ~9 cm
# du. ⚠️ Gan them do gi CAO hon camera len robot thi PHAI nang so nay.
# Chi THEM o bi chiem, khong xoa: vat bi doi di trong luc quet de lai vet.
#
# 0.15 (khong phai 0.10): san do tren robot that lech chuan 3.6 cm quanh 0
# (600 khung depth, 2026-09-25) -> 0.15 la ~4 sigma, nhieu san khong lot vao.
obstacle_z_min: 0.15
obstacle_z_max: 0.55
# Voxel phai duoc >= bay nhieu NODE khac nhau thay moi giu -- ap cho CA ban
# do 3D lan lop vat can 2D. Robot that 2026-09-25: camera gop 2048 o vat
# can, NHIEU HON 1379 o tuong cua LiDAR -- phan lon la diem bay o mep vat
# va nguoi di ngang, chi o 1-2 khung, ma lop nay khong bao gio xoa.
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# LAN NHIN MOI NHAT QUYET DINH (07/10). Truoc day lop nay CHI THEM: 3 nguoi
# dung tren duong luc quet thanh vat can vinh vien, quay lai quet van con.
# Gio: voxel ma >= bay nhieu node SAU lan thay cuoi nhin XUYEN qua (depth xa
# hon voxel + 0.10 + 0.03 z^2 m) va khong node nao trong do con thay -> XOA,
# ca khoi ban do 3D lan lop vat can 2D. Bi che (depth gan hon) thi khong tinh
# -- khong biet thi khong xoa. Ap ca luc quet lan luc mo ban do da luu.
# 0 = tat (chi them, nhu truoc).
clear_after_views: 2
# ============ VONG DONG XA (chi khi quet) ============
# Phat hien ke can cua RTAB-Map chi xet node trong 50 buoc do thi
# (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong DAI thi
# khong bao gio noi duoc -- sai so cuoi vong o lai trong ban do. Khoi nay: sau
# moi node, tim node CU (cach >= min_graph_gap buoc) trong ban kinh radius_m
# theo do thi, ICP giua hai scan (Icp/* cua chinh ban do), nhan neu chinh <
# max_corr, them lien ket.
#
# Do trong sim (slope_test, vong 52 m, 04/10):
# khong co (cu) cuoi vong lech 11.7 cm
# RGBD/ProximityMaxGraphDepth 0 van 0 lien ket ve dau vong
# detectMoreLoopClosures cua RTAB-Map TE HON: 33 cm -- them hang tram
# lien ket giua node CUNG luot trong hanh lang, ICP khong rang buoc doc
# truc keo ban do truot
# far_loops (khoi nay) 1.5 cm, 2 lien ket
#
# Ban kinh 1 m: chi ghep node ma do thi DA cho la cung cho -- khong tao vong
# giua hai noi khac nhau tru khi ban do da vo san. Tat: enabled: false.
far_loops:
enabled: true
radius_m: 1.0
min_graph_gap: 100 # ~10 m quang duong o RGBD/LinearUpdate 0.1
max_corr_m: 0.5
max_corr_deg: 10.0
period_s: 1.0
# ============ DI TREN DOC (G4) ============
# Pose SLAM van la SE(2) (Reg/Force3DoF). Khoi nay them, BEN CANH no:
# * z robot = tich -ds*sin(pitch IMU), kep ve 0 khi |pitch| < clamp_deg, neo
# vao z cua node ban do o che do localization;
# * z / roll / pitch luu vao MOI node (userData cua RTAB-Map) -> ban do 3D va
# lop vat can tinh theo SAN cuc bo, doc khong con bi coi la tuong;
# * quang duong banh x cos(pitch) truoc EKF (odometry NGANG);
# * scan cho SLAM / dinh vi lai duoc bu nghieng va bo tia cham san / mat doc
# (ban do do cao san cuc bo tu depth). Lop AN TOAN van dung scan tho.
#
# ⚠️ CAN IMU >= 100 Hz. Do trong sim (G3, 03/10): IMU 100 Hz -> sai dz qua doc
# 1.5 m trung vi 1.8 cm, max 8 cm; IMU 10 Hz (WT61PC mac dinh, 9600 baud) ->
# 19 cm, va khong chinh bo loc nao cuu duoc. WT61PC tren robot da o 115200 baud
# / 200 Hz (06/10/2026, sensors.yaml `mcu`).
#
# ⚠️ Gioi han NOI RO: doc that < clamp_deg bi coi la phang; tuong gia o chan
# doc LEN chi bo duoc khi camera da thay mat doc truoc do (re vao doc o goc
# hep thi con). Nhieu tang chong len nhau tai cung (x, y) KHONG ho tro.
#
# Mac dinh BAT tu 06/10/2026: robot di giua cac toa nha qua doc. San phang thi
# z kep ve 0, khong doi gi. Ban do quet truoc khi co che do doc (DB khong co z
# tung node) van mo duoc: khong co mat san -> bo loc nghieng cua dinh vi lai
# tu tat, chay nhu cu. enabled: false = moi duong cu giu nguyen.
slope:
enabled: true
clamp_deg: 1.5 # duoi nguong = mat bang (doc xe lan >= 2.9 do)
sigma_rel: 0.05 # sai he thong tren doc: 5% do cao da leo
sigma_flat: 0.005 # troi tren mat bang, m / sqrt(m)
sigma_anchor: 0.03 # sai z ban do dung de neo
anchor_radius_m: 0.6 # neo vao node trong ban kinh nay
horizontal_odom: true
level_scan: true
floor_margin_m: 0.08 # cao hon san da biet duoi nguong = cham san
below_ground_m: 0.05 # thap hon mat dat duoi robot = san duoi chan doc
elevation_cell_m: 0.10
elevation_radius_m: 8.0
elevation_max_depth_m: 4.0
depth_stride: 4 # lay 1/4 x 1/4 diem anh depth cho ban do do cao
# ============ KHOI RTAB-MAP ============ # ============ KHOI RTAB-MAP ============
# Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung # Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung
@@ -68,7 +261,7 @@ rtabmap:
Icp/MaxCorrespondenceDistance: "0.15" Icp/MaxCorrespondenceDistance: "0.15"
Icp/Iterations: "30" Icp/Iterations: "30"
Icp/Epsilon: "0.001" Icp/Epsilon: "0.001"
Icp/CorrespondenceRatio: "0.3" # Icp/CorrespondenceRatio -> `profiles:` cuoi file (sim va real khac nhau).
Icp/MaxTranslation: "0.5" Icp/MaxTranslation: "0.5"
# --- Vong dong va lien ket lan can --- # --- Vong dong va lien ket lan can ---
@@ -116,6 +309,16 @@ rtabmap:
Grid/CellSize: "0.05" Grid/CellSize: "0.05"
Grid/RangeMax: "12.0" Grid/RangeMax: "12.0"
Grid/RayTracing: "true" Grid/RayTracing: "true"
# Luoi 2D theo LAN NHIN MOI NHAT (07/10). Moi o cong log-odds: trung +0.85,
# truot (tia di xuyen qua) -0.62, kep trong [-1.39, +1.39]. Mac dinh RTAB-Map
# kep +3.5 va truot -0.41: o da chac chiem can ~9 lan nhin xuyen qua moi xoa
# -> nguoi dung lai roi di, quay lai quet van con tren ban do. Bo nay: 3 lan
# xuyen qua -> trong, 2 lan thay vat -> chiem. Doi lai: vat rat manh (chan
# ghe) co the chap chon khi tia luot sat ben canh.
GridGlobal/ProbHit: "0.7"
GridGlobal/ProbMiss: "0.35"
GridGlobal/ProbClampingMin: "0.2"
GridGlobal/ProbClampingMax: "0.8"
Grid/3D: "false" Grid/3D: "false"
Grid/DepthDecimation: "4" Grid/DepthDecimation: "4"
@@ -123,3 +326,41 @@ rtabmap:
Rtabmap/TimeThr: "0" Rtabmap/TimeThr: "0"
Rtabmap/MemoryThr: "0" Rtabmap/MemoryThr: "0"
Rtabmap/DetectionRate: "3" Rtabmap/DetectionRate: "3"
# --- Luu DB ---
# Khong luu cac khung RTAB-Map da bo qua (khong nam trong do thi). Mac dinh
# RTAB-Map la true: 37 phut quet ra 17723 node ma chi 3192 trong do thi --
# 79% (1.7 GB) cua DB 2.16 GB la khung thua.
# ⚠️ Doi lai: DB khong con MOI khung, nen vslam_slam_bench chay lai tu no
# se thua hon phien goc. Quet de lam du lieu phan tich thi dat "true".
Mem/NotLinkedNodesKept: "false"
# ============ THEO MOI TRUONG ============
# Mo phong va robot that can bo so KHAC nhau cho cung mot key. Chon TU DONG
# theo nguon: --sim -> sim; --live / --replay -> real (replay la du lieu
# robot that).
#
# Node TU CHOI khoi dong neu:
# - thieu mot trong hai khoi, hoac co khoi thu ba;
# - hai khoi KHONG cung tap key (sua mot ben quen ben kia);
# - mot key vua o day vua o phan chung phia tren (mot key, mot cho);
# - co key ngoai odom_sigma_m, odom_sigma_rad, rtabmap.
profiles:
sim:
# Odom mo phong gan nhu hoan hao, scan du 1440 tia. hospital_nam
# 2026-09-25 (run_N1): sai so vs ground truth 3-5 cm; cung ban do voi
# bo so `real` 2026-09-28: 8-12 cm sau 5 phut.
odom_sigma_m: 0.01
odom_sigma_rad: 0.005
rtabmap:
Icp/CorrespondenceRatio: "0.3"
real:
# 2026-09-25: 0.01/0.005 lam ban do xoan (odom that sai nhieu do/buoc);
# 0.1/0.1 hanh lang thang, phong vuong.
odom_sigma_m: 0.1
odom_sigma_rad: 0.1
rtabmap:
# Ti le khop that chi 0.05-0.1: RTAB-Map chia cho 1440 tia khai trong
# header trong khi LakiBeam chi ~655 diem hop le. DB that 2026-09-25:
# 0.3 -> 0 lien ket, 0.1 -> 18, 0.05 -> 325 (ban do dung).
Icp/CorrespondenceRatio: "0.05"

View File

@@ -20,12 +20,31 @@ web:
# Tan so phat. `web_tx` AP dat cac tan so nay; khong de moi nguon tu gui, # Tan so phat. `web_tx` AP dat cac tan so nay; khong de moi nguon tu gui,
# vi lan do dau tien da ra 109 kB/s chi vi PATH gui o 9.8 Hz thay vi 1 Hz. # vi lan do dau tien da ra 109 kB/s chi vi PATH gui o 9.8 Hz thay vi 1 Hz.
#
# ⚠️ Chung tung bi PARSE ma khong AP: `WebServer::Publish()` gui ca ba kenh
# o moi lan goi, tuc o status_rate_hz. Do duoc tren robot: 80 khung/s va
# ~300 kB/s cho 2 client, hang doi 4 khung day lien tuc, man hinh tut lai
# 1-2 giay. Gio Publish() co cong tan so that cho tung kenh.
status_rate_hz: 10.0 status_rate_hz: 10.0
scan_rate_hz: 10.0 scan_rate_hz: 10.0
cloud_rate_hz: 2.0 cloud_rate_hz: 8.0
path_rate_hz: 1.0 path_rate_hz: 1.0
cloud_max_points: 4000 # ⚠️ Hai so nay di CUNG NHAU: chung quyet dinh bang thong cua kenh nang
# nhat. Mot khung cloud = max_points * 6 byte + 36.
# 4000 diem @ 2 Hz = 48 kB/s
# 2500 diem @ 4 Hz = 60 kB/s
# 2000 diem @ 8 Hz = 96 kB/s (hien tai)
# Do duoc: phan KHONG phai cloud la 16 kB/s, ngan sach ca UI la 120 kB/s,
# nen cloud duoc tieu toi da ~104. Tang mot trong hai so thi tinh lai, dung
# doan.
#
# ⚠️ 96 kB/s la muc cho client xem TREN JETSON. Qua WiFi tu laptop da do
# duoc rot khung o muc thap hon the -- neu `frames_dropped` trong
# /api/status bat dau tang thi lui `cloud_rate_hz` ve 6.
#
# Tran tan so la `depth_filter.max_rate` (10 Hz), khong phai so nay.
cloud_max_points: 2000
cloud_quant_m: 0.01 cloud_quant_m: 0.01
# Tan so toi da DUNG lai ban do tu do thi SLAM. # Tan so toi da DUNG lai ban do tu do thi SLAM.
@@ -47,6 +66,138 @@ web:
# Mot tan so CO DINH sai o ca hai dau. # Mot tan so CO DINH sai o ca hai dau.
map_rebuild_rate_hz: 4.0 map_rebuild_rate_hz: 4.0
# --- Ban do voxel 3D (slam.yaml camera_3d: true) ---
#
# KHONG co tan so gui o day, co y: ca tap day du lan delta deu di theo SU
# KIEN (do thi doi), va nhip that da bi ngan sach duty 25% cua luong slam
# ghim lai. Them mot cong tan so nua chi co the LAM MAT khung delta -- ma
# mat mot delta la client giu ban do sai vinh vien.
#
# Mot manh cua lan dong bo day du. 32 kB = 5461 o.
#
# ⚠️ Phep tinh bang thong, de canh doan 120 kB/s o tren:
# manh full-sync KHONG di qua hang doi, moi lan Publish (10 Hz) bom
# `voxel_sync_chunks_per_tick` manh. 2 x 32 kB x 10 Hz = 655 kB/s.
# Mot ban do 150k o (0.05 m, mot tang) = 1.8 MB = 28 manh = 1.4 giay.
#
# Tuc la trong ~1-3 giay dau cua MOI client moi vao, ngan sach bi vuot NAM
# LAN. Chap nhan duoc vi no la mot dot, khong phai nhip thuong truc, va khung
# cloud (drop duoc) hap thu phan chenh. Nhung tren WiFi cua Jetson thi do
# `frames_dropped` trong /api/status ngay sau khi mo trang: neu no nhay thi
# ha `voxel_sync_chunks_per_tick` ve 1.
#
# Epoch doi (sau mot vong dong lon) lam MOI client dong bo lai tu dau -- do
# la ly do `voxel.delta_max_ratio` phai du cao de chuyen do hiem xay ra.
voxel_chunk_bytes: 32768
voxel_sync_chunks_per_tick: 2
# ============ Tay cam (Logitech F710/F310, mode XInput) ============
# Port 1-1 tu base_kit/src/joy_control -- ban dang chay that tren robot nay.
# Ten khoa giu giong tham so cua node ROS ben do de doi chieu duoc hai ben.
#
# ⚠️ MAC DINH TAT. Cam mot tay cam vao may khong duoc phep tu bien no thanh
# nguon lai: `--gamepad` hoac `enabled: true` la mot hanh dong co y.
#
# Bat tam thoi: vslam_node --live --gamepad
# Do index that: build/tools/vslam_joy_probe /dev/input/js0
gamepad:
enabled: false
device: /dev/input/js0
# = `autorepeat_rate: 50` cua joy_node trong teleop_all.launch.py.
#
# ⚠️ KHONG phai so cho vui. joydev CHI gui event khi gia tri DOI, nen giu can
# gat dung yen la khong co event nao. Node tu bom lai o tan so nay; qua thua
# thi `raw_cmd` cu dan va FSM ban NO_CMD (safety.yaml cmd_timeout 0.5 s) dung
# xe GIUA LUC nguoi lai dang giu can. Cau hinh bi TU CHOI neu chu ky > mot
# nua cmd_timeout.
publish_rate_hz: 50.0
# Tran cua RIENG tay cam, giong tham so node ROS. base_kit dung 0.5 / 1.0.
#
# ⚠️ Robot nay kep o 0.5 m/s (robot.yaml base.max_linear) va lan nua o
# safety.yaml max_linear, nen turbo BAO HOA o 0.5 chu khong len 1.0. Giu so
# cua base_kit de con doi chieu; log se WARN nhac lai chuyen bi kep.
max_linear_speed: 0.5
max_angular_speed: 1.0
deadzone: 0.05
# Ma sat tinh cua dong co: kich toc do toi thieu ngay khi nhich can gat, de
# tay cam "bat" giong ban phim thay vi bo tu 0.01 (joy_control_node.cpp:243).
#
# ⚠️ 0.2 tren tran 0.5 cua base_kit la 40% dai. Tren tran that 0.35 o day no
# chiem 57% -- can gat gan nhu thanh cong tac. Muon giu dung ti le thi dat
# 0.14. De 0.2 la de GIONG base_kit, khong phai vi no dung hon.
min_linear_kick: 0.2
min_angular_kick: 0.4
# Nha can gat -> gui 0 trong ngan nay roi IM HAN.
#
# Cai "im" moi la phan quan trong: no tra quyen lai cho joystick tren web
# (ben base_kit la tra cho ban phim). Bo di thi tay cam chiem `raw_cmd` vinh
# vien va trang web khong lai duoc nua.
idle_publish_sec: 1.5
# Mat tay cam -> thu mo lai moi ngan nay. Thay cho `exit(1)` + systemd
# Restart cua base_kit: o day vslam_node giu ca SLAM, EKF va vong an toan,
# nen rut day tay cam KHONG duoc phep giet tien trinh.
reopen_period_sec: 1.0
# He so khi VUA GIU nut VUA gat can (joy_control_node.cpp:212-218).
# Turbo giam toc do quay lai de khong gat khi dang chay nhanh.
turbo_linear: 2.0 # RB
turbo_angular: 0.5
slow_linear: 0.5 # LB
slow_angular: 0.5
# --- Index, layout F710/F310 XInput ---
# Sai index thi sua o day, KHONG sua code. Do bang vslam_joy_probe.
axis_linear: 1 # can trai Y (day len = tien)
axis_linear_dpad: 7 # D-pad Y
axis_angular: 3 # can phai X (trai = quay trai, REP-103)
axis_angular_dpad: 6 # D-pad X
button_enable: 7 # Start -- BAT/TAT dieu khien
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.
#
# joydev tra ve gia tri THO, va tren "Logitech Gamepad F710" qua xpad thi
# LEN va TRAI la AM. Chay khong dao dau: day can gat len -> banh quay LUI,
# gat can phai sang trai -> robot re PHAI. Dao ca hai truc moi dung.
#
# `joy_node` cua ROS dao dau san truoc khi publish, nen base_kit khong can
# co nay -- moi so trong file nay chep tu base_kit va vi the deu theo quy
# uoc DA DAO.
#
# Dau mong doi sau khi ap: day len = tien, gat trai = quay trai (REP-103).
# Bo tay cam khac co the khac chieu -- do bang vslam_joy_probe, dung suy tu
# log nhu lan truoc.
invert_linear: true
invert_angular: true
# Header cua base_kit hua "LT: EMERGENCY STOP (hold)" nhung code KHONG he doc
# truc do. Cai dat o day, mac dinh TAT dung bang hanh vi that cua base_kit.
#
# ⚠️ CHIEU CUA COC DO TREN CHINH TAY CAM NAY bang vslam_joy_probe:
# "Logitech Gamepad F710" -> axes[2] = -1.000 khi KHONG cham coc. Tuc coc
# nghi o -1.0 va bop len +1.0, nen nguong la "> lt_press_above".
#
# Nguong 0.5 chu khong phai 0.0: truoc mau dau tien truc co the doc ra 0.0,
# va 0.0 nam ngay sat nguong. Bo tay cam khac co the nghi o chieu nguoc lai
# -- do lai bang probe TRUOC khi bat `lt_stop`, neu khong thi coc dang nghi
# bi hieu la dang bop va robot dung cung vinh vien.
#
# Day la GIU DE DUNG, khong chot e-stop cua he thong: go e-stop bat buoc co
# token, nen mot cu va nham vao coc se khoa robot cho toi khi co nguoi mo
# trinh duyet.
lt_stop: false
axis_lt: 2
lt_press_above: 0.5
# ============ Log ============ # ============ Log ============
logging: logging:
level: info # debug | info | warn | error level: info # debug | info | warn | error

View File

@@ -0,0 +1,15 @@
# /dev/imu cho IMU WT61PC qua cap USB-FTDI (0403:6001) -- sensors.yaml `mcu.port`.
#
# latency_timer=1: cap FTDI day byte len host moi 1 ms thay vi 16 ms (mac dinh).
# O 200 Hz (5 ms/mau) 16 ms la ~3 mau den cung mot luc, stamp IMU giat.
# Wt61pcBridge log `imu: latency_timer cap FTDI = N ms` luc mo cong.
#
# Nguon: goi imu_uart cua namnc (ROS 2), 2026-10-06. Cai tren Jetson, mot lan:
# sudo cp configuration_files/udev/99-imu.rules /etc/udev/rules.d/
# sudo udevadm control --reload-rules && sudo udevadm trigger
# ls -l /dev/imu # -> ttyUSBn
# cat /sys/bus/usb-serial/devices/ttyUSB*/latency_timer # phai ra 1
#
# Luat khop MOI cap FTDI 0403:6001: cam them mot cap cung loai thi ca hai deu
# tranh ten /dev/imu.
KERNEL=="ttyUSB*", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0666", GROUP="robotics", SYMLINK+="imu", ATTR{latency_timer}="1", RUN+="/bin/chmod 777 /dev/%k"

View File

@@ -123,13 +123,31 @@ không cần nhãn.
## Một đường duy nhất tới motor ## Một đường duy nhất tới motor
``` ```
web → teleop → raw_cmd → [luồng safety] → base web → teleop → raw_cmd → [luồng safety] → base
tay cầm → mapper ↗
``` ```
Không nhánh nào cho lệnh đi thẳng xuống base. **Kể cả e-stop**: nó đặt cờ, rồi Không nhánh nào cho lệnh đi thẳng xuống base. **Kể cả e-stop**: nó đặt cờ, rồi
luồng safety thấy cờ và zero lệnh trong vòng một chu kỳ (50 ms). Hai đường luồng safety thấy cờ và zero lệnh trong vòng một chu kỳ (50 ms). Hai đường
nghĩa là hai chỗ để sai. nghĩa là hai chỗ để sai.
Tay cầm là nguồn lệnh thứ hai, **không** phải đường thứ hai: nó dừng ở
`raw_cmd` đúng như web. Hai điểm khác web, cả hai đều cố ý:
- **Không đi qua `TeleopModel`.** `GamepadMapper` tự quy ra vận tốc từ tham số
riêng của nó, giống node joy của `base_kit` có `max_linear_speed` riêng,
độc lập với bàn phím. Nhờ vậy hai nguồn nhập không tranh trạng thái của một
mô hình chung.
- **Nhường quyền bằng cửa sổ 1.5 s.** Thả cần gạt → gửi 0 trong 1.5 giây rồi
**im hẳn**, trả `raw_cmd` lại cho joystick trên web. Bỏ luật này thì tay cầm
chiếm `raw_cmd` vĩnh viễn và trang web không lái được nữa.
⚠️ `joydev` **chỉ** gửi event khi giá trị đổi, nên giữ cần gạt đứng yên là
không có event nào. Bản ROS che chuyện này bằng `joy_node autorepeat_rate: 50`;
ở đây `GamepadLoop()` tự bơm lại ở `gamepad.publish_rate_hz`. Thưa quá thì FSM
bắn `NO_CMD` và dừng xe **giữa lúc** người lái đang giữ cần — `LoadAppConfig`
từ chối cấu hình có chu kỳ bơm lớn hơn nửa `safety.cmd_timeout`.
FSM cũng **không** chạy trong callback teleop. Gọi `Step()` ở đó nghĩa là nó FSM cũng **không** chạy trong callback teleop. Gọi `Step()` ở đó nghĩa là nó
chỉ chạy khi *có* lệnh tới — mà `NO_CMD`, `SCAN_TIMEOUT` và `cliff_hold` tồn chỉ chạy khi *có* lệnh tới — mà `NO_CMD`, `SCAN_TIMEOUT` và `cliff_hold` tồn
tại chính xác cho trường hợp lệnh **ngừng** tới. Đã mắc lỗi này một lần. tại chính xác cho trường hợp lệnh **ngừng** tới. Đã mắc lỗi này một lần.
@@ -146,7 +164,7 @@ tại chính xác cho trường hợp lệnh **ngừng** tới. Đã mắc lỗi
| `pipeline.yaml` | EKF, depth_filter, gravity_align, cliff_detect | | `pipeline.yaml` | EKF, depth_filter, gravity_align, cliff_detect |
| `slam.yaml` | mode, DB, optimizer, **khối `rtabmap:` 26 key** | | `slam.yaml` | mode, DB, optimizer, **khối `rtabmap:` 26 key** |
| `safety.yaml` | FSM | | `safety.yaml` | FSM |
| `system.yaml` | web, log, ghi bản ghi, luồng | | `system.yaml` | web, **tay cầm**, log, ghi bản ghi, luồng |
### Không giá trị nào ở hai nơi ### Không giá trị nào ở hai nơi

View File

@@ -0,0 +1,4 @@
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(imu_uart)

101
firmware/imu_uart/README.md Normal file
View File

@@ -0,0 +1,101 @@
# Firmware IMU: WT61PC -> ESP32-S3 -> host
Cau noi mot chieu. WT61PC noi voi ESP32 qua UART1 9600 baud; ESP32 phat ra
console (UART0 + USB Serial/JTAG), host thay la `/dev/ttyACM0`.
## Vi sao firmware nam trong repo nay
`libs/vslam_drivers/include/vslam/mcu_protocol.h` tu nhan:
> PHAT HANH co y: file nay la DAC TA ma firmware phai khop.
Dac ta o mot repo, ban thuc thi o mot thu muc khong ai theo doi, thi hai cai
troi khoi nhau ma khong ai phat hien. Da xay ra that: `base_kit` bi liet trong
`.gitignore`, va ban tren may dev co `src/hardware/IMU_uart/` trong khi ban
tren Jetson KHONG co -- hai may da khac nhau tu luc nao khong ro.
De canh nhau thi `test/test_mcu_protocol.cc` la bai kiem cho ca hai phia.
## Sua gi so voi ban base_kit
Goc: `base_kit/src/hardware/IMU_uart/main/main.c`.
| | truoc | sau |
|---|---|---|
| dinh dang xuat | 3 dong text `Acc`/`Gyro`/`Angle` | mot dong `I,<micros>,...` |
| dau thoi gian | khong co | `esp_timer_get_time()` tai khung gyro |
| don vi gyro | do/s | rad/s (theo dac ta) |
| tan so | ~10 Hz (chua bao gio dat) | 20 Hz (`0xff 0xaa 0x03 0x07 0x00`) |
| khung Angle | doi va in | doc roi bo |
| hang so g | 9.8 | 9.80665 |
Dat `EMIT_LEGACY_TEXT 1` trong `main.c` de quay ve dinh dang cu.
### Vi sao 20 Hz chu khong cao hon
Cam bien van gui DU ca ba khung (Acc + Gyro + Angle = 33 byte) du firmware chi
dung hai khung dau. O 9600 baud 8N1 = 960 byte/s, tran la 960/33 = 29 Hz.
20 Hz = 660 byte/s = 69% bus, con bien. 25 Hz la 86% -- sat qua.
Muon cao hon thi phai nang baud cua cam bien (thanh ghi `0x04`), nhung thu vien
DFRobot khong expose thanh ghi do nen ma phai doan. Doan sai thi cam bien
chuyen sang baud khac va cam hoan toan. Chua lam.
### Do tre con lai
Cam bien lay mau roi moi day byte. Den luc khung gyro (khung thu hai) nhan
xong thi mau da gia ~23 ms:
2 khung x 11 byte x 10 bit / 9600 baud = 22.9 ms
Firmware KHONG tru san con so nay -- tru san la gia dinh cam bien phat ngay sau
khi lay mau, dieu chua kiem duoc. No la HANG SO va host DO DUOC: chay `--live`,
lai robot vao ra cua, doc dong `wheel_odom/lag`, dat ket qua vao
`mcu.imu_lag_sec` trong `configuration_files/sensors.yaml`. Chay lai thi dong
do phai bao ~0 ms -- do la phep tu kiem chung.
## Build va flash
Can ESP-IDF v5.x. Chua co thi:
sudo apt install -y git wget flex bison gperf python3-venv cmake ninja-build \
ccache libffi-dev libssl-dev dfu-util libusb-1.0-0
mkdir -p ~/esp && cd ~/esp
git clone -b v5.1.2 --recursive https://github.com/espressif/esp-idf.git
cd esp-idf && ./install.sh esp32s3
Roi:
. ~/esp/esp-idf/export.sh
cd firmware/imu_uart
idf.py set-target esp32s3
idf.py build
idf.py -p /dev/ttyACM0 flash
⚠️ **Tat `vslam_node` truoc khi flash.** ESP32-S3 dung chung `/dev/ttyACM0` cho
ca du lieu lan nap; `esptool` khong mo duoc cong neu node dang giu.
## Sao luu va khoi phuc
Truoc khi flash lan dau:
pip3 install --user esptool
~/.local/bin/esptool.py -p /dev/ttyACM0 read_flash 0x0 0x400000 ~/imu_firmware_backup.bin
Quay ve ban cu:
~/.local/bin/esptool.py -p /dev/ttyACM0 write_flash 0x0 ~/imu_firmware_backup.bin
## Kiem tra sau khi flash
sudo fuser -k /dev/ttyACM0
timeout 5 cat /dev/ttyACM0 > /tmp/imu.txt
grep -c '^I,' /tmp/imu.txt # chia 5 => Hz, mong doi ~20
head -3 /tmp/imu.txt
Mong doi:
I,12345678,0.00105,-0.00210,0.00000,0.069,-0.127,9.807
Roi bat nhanh co dau thoi gian o host: dat `mcu.expect_timestamps: true` trong
`configuration_files/sensors.yaml`.

View File

@@ -0,0 +1,2 @@
idf_component_register(SRCS "main.c"
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,179 @@
// Firmware ESP32-S3: cau noi WT61PC (UART) -> host (USB).
//
// ⚠️ File nay la BAN SUA cua base_kit/src/hardware/IMU_uart/main/main.c.
// Xem ../README.md muc "Sua gi so voi ban base_kit".
//
// Dinh dang xuat PHAI khop libs/vslam_drivers/include/vslam/mcu_protocol.h --
// file do tu nhan la DAC TA cho firmware. Do la ly do firmware nam trong repo
// nay chu khong nam trong base_kit: dac ta va ban thuc thi de canh nhau thi
// test_mcu_protocol.cc la bai kiem cho ca hai phia.
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_timer.h"
#define UART_PORT_NUM UART_NUM_1
#define UART_BAUD_RATE 9600
#define UART_TX_PIN 16
#define UART_RX_PIN 15
#define BUF_SIZE 1024
// Dat 1 de in lai ba dong text "Acc/Gyro/Angle" cu thay vi ban ghi I.
// Chi de lui ve khi can so sanh; host doc duoc ca hai (xem mcu_bridge.cc).
#define EMIT_LEGACY_TEXT 0
#define DEG2RAD 0.017453292519943295
// 9.80665 chu khong phai 9.8 nhu ban goc: lech 0.07%, sua mien phi.
#define G_MPS2 9.80665
static float acc_x, acc_y, acc_z; // m/s^2
static float gyro_x, gyro_y, gyro_z; // rad/s
static bool acc_updated = false;
#if EMIT_LEGACY_TEXT
static float angle_x, angle_y, angle_z;
static bool gyro_updated = false, angle_updated = false;
#endif
static uint8_t calculate_checksum(uint8_t *buf) {
uint8_t sum = 0;
for (int i = 0; i < 10; i++) sum += buf[i];
return sum;
}
// Doi tan so xuat cua WT61PC.
//
// Lenh {0xff,0xaa,0x03,<freq>,0x00} lay tu DFRobot_WT61PC::modifyFrequency().
// 0x07 = 20 Hz.
//
// ⚠️ KHONG dat cao hon. Cam bien van gui DU ca ba khung (Acc + Gyro + Angle =
// 33 byte) du firmware nay chi dung hai khung dau -- khong co cach tat khung
// Angle ma khong doan ma thanh ghi. O 9600 baud 8N1 = 960 byte/s thi tran la
// 960/33 = 29 Hz. 20 Hz = 660 byte/s = 69% bus, con bien. 25 Hz la 86%, sat
// qua: mot khung bi tre la keo theo ca chuoi.
//
// ⚠️ KHONG dung lenh doi baud (thanh ghi 0x04): thu vien DFRobot khong expose
// no nen ma phai doan, ma doan sai thi cam bien chuyen sang baud khac va CAM
// hoan toan -- phai thao ra noi lai moi cuu duoc.
static void set_output_rate_20hz(void) {
const uint8_t cmd[5] = {0xff, 0xaa, 0x03, 0x07, 0x00};
uart_write_bytes(UART_PORT_NUM, (const char *)cmd, sizeof(cmd));
vTaskDelay(pdMS_TO_TICKS(100)); // cho cam bien nhan lenh
}
static void uart_task(void *arg)
{
uart_config_t uart_config = {
.baud_rate = UART_BAUD_RATE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.source_clk = UART_SCLK_DEFAULT,
};
uart_driver_install(UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, 0);
uart_param_config(UART_PORT_NUM, &uart_config);
uart_set_pin(UART_PORT_NUM, UART_TX_PIN, UART_RX_PIN,
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
set_output_rate_20hz();
uint8_t data[11];
while (1) {
uint8_t ch;
int len = uart_read_bytes(UART_PORT_NUM, &ch, 1, portMAX_DELAY);
if (len != 1 || ch != 0x55) continue;
data[0] = 0x55;
len = uart_read_bytes(UART_PORT_NUM, &data[1], 10, 100 / portTICK_PERIOD_MS);
if (len != 10) continue;
if (calculate_checksum(data) != data[10]) continue;
int16_t x = (data[3] << 8) | data[2];
int16_t y = (data[5] << 8) | data[4];
int16_t z = (data[7] << 8) | data[6];
switch (data[1]) {
case 0x51: // Gia toc
acc_x = (x / 32768.0f) * 16.0f * G_MPS2;
acc_y = (y / 32768.0f) * 16.0f * G_MPS2;
acc_z = (z / 32768.0f) * 16.0f * G_MPS2;
acc_updated = true;
break;
case 0x52: { // Van toc goc
// ⚠️ Dong dau NGAY DAY, truoc moi xu ly khac. Day la thoi diem gan
// nhat voi luc DO ma firmware biet duoc.
//
// Van con lech: cam bien lay mau roi moi day byte, va den luc khung
// gyro (khung thu hai) nhan xong thi mau da gia ~23 ms o 9600 baud
// (2 khung x 11 byte x 10 bit / 9600). KHONG tru san o day -- tru
// san la gia dinh cam bien phat ngay sau khi lay mau, dieu chua
// kiem duoc. Phan du la HANG SO va host do duoc: xem
// `wheel_odom/lag` va `mcu.imu_lag_sec` trong sensors.yaml.
const int64_t t_us = esp_timer_get_time();
gyro_x = (x / 32768.0f) * 2000.0f * DEG2RAD;
gyro_y = (y / 32768.0f) * 2000.0f * DEG2RAD;
gyro_z = (z / 32768.0f) * 2000.0f * DEG2RAD;
#if EMIT_LEGACY_TEXT
gyro_updated = true;
#else
// Phat NGAY khi co du acc + gyro. KHONG doi khung 0x53 (Angle):
// khong co ai doc imu.orientation trong libs/ va app/, ma doi no
// ton them mot khung = 11.5 ms o 9600 baud.
//
// micros cat con 32 bit theo dung mcu_protocol.h -- no TRAN moi
// 71.58 phut va McuTimeUnwrapper phia host go tran.
if (acc_updated) {
printf("I,%" PRIu32 ",%.5f,%.5f,%.5f,%.3f,%.3f,%.3f\n",
(uint32_t)(t_us & 0xFFFFFFFF),
gyro_x, gyro_y, gyro_z, acc_x, acc_y, acc_z);
acc_updated = false;
}
#endif
break;
}
case 0x53: // Goc -- doc de khong lech khung, khong dung toi
#if EMIT_LEGACY_TEXT
angle_x = (x / 32768.0f) * 180.0f;
angle_y = (y / 32768.0f) * 180.0f;
angle_z = (z / 32768.0f) * 180.0f;
angle_updated = true;
#endif
break;
default:
break;
}
#if EMIT_LEGACY_TEXT
if (acc_updated && gyro_updated && angle_updated) {
printf("Acc\t%.2f\t%.2f\t%.2f\n", acc_x, acc_y, acc_z);
printf("Gyro\t%.2f\t%.2f\t%.2f\n",
gyro_x / (float)DEG2RAD, gyro_y / (float)DEG2RAD,
gyro_z / (float)DEG2RAD);
printf("Angle\t%.2f\t%.2f\t%.2f\n\n", angle_x, angle_y, angle_z);
acc_updated = gyro_updated = angle_updated = false;
}
#endif
}
}
void app_main(void)
{
// ⚠️ Dong nay KHONG toi duoc host qua USB Serial/JTAG: host chua kip nhan
// thiet bi luc app_main chay. Da mat mot buoi chan doan vi tuong firmware
// bi sai khi khong bat duoc banner. Giu lai vi no ra UART0.
printf("imu_uart: WT61PC -> ban ghi I, xem mcu_protocol.h\n");
xTaskCreate(uart_task, "uart_task", 4096, NULL, 5, NULL);
}

1951
firmware/imu_uart/sdkconfig Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
# Chi nhung gia tri KHAC mac dinh cua IDF va co anh huong that. Phan con lai
# de IDF tu sinh -- chep nguyen mot sdkconfig 2000 dong vao git thi moi lan
# doi phien ban IDF lai xung dot ca ngan dong.
CONFIG_IDF_TARGET="esp32s3"
# Console ra CA UART0 lan USB Serial/JTAG. /dev/ttyACM0 tren host chinh la
# duong USB nay. Giu UART0 lam console chinh de con cho doc luc board khoi
# dong (host chua kip nhan thiet bi USB o thoi diem do).
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y

View File

@@ -45,3 +45,11 @@ endif()
if(VSLAM_BUILD_SIM) if(VSLAM_BUILD_SIM)
add_subdirectory(vslam_sim) add_subdirectory(vslam_sim)
endif() endif()
# Ve anh camera mo phong bang GPU (anh IR + depth tu mesh co texture that).
# TUY CHON, chi may dev co GPU: sim van chay khong co no (depth raycast CPU,
# khong co anh IR).
option(VSLAM_SIM_WITH_GL "Ve camera mo phong bang GPU (EGL + GLES3 + assimp)" OFF)
if(VSLAM_BUILD_SIM AND VSLAM_SIM_WITH_GL)
add_subdirectory(vslam_sim_gl)
endif()

View File

@@ -15,6 +15,9 @@
#include <string> #include <string>
#include "vslam/vslam_common.h" // StatusResponse. Khong vong:
// vslam_common.h chi keo unix_time.h
namespace vslam { namespace vslam {
// --- Duong dan mac dinh ---------------------------------------------------- // --- Duong dan mac dinh ----------------------------------------------------
@@ -93,6 +96,30 @@ std::string RecordDir();
// map_hospital.db ma khong phai copy 3.8 GB. // map_hospital.db ma khong phai copy 3.8 GB.
std::string CorpusDir(); std::string CorpusDir();
// --- Duong dan ban do: giai tuong doi + no {stamp} -------------------------
// Giai database_path cua SLAM:
// "" -> "" (DB trong RAM -- giu nguyen nghia)
// "/abs/x.db" -> "/abs/x.db" (tuyet doi thi khong dung toi)
// "x.db" -> MapDir() + "/x.db" (tuong doi = nam trong project)
//
// `{stamp}` o bat ky dau bi thay bang dau thoi gian DIA PHUONG %Y%m%d_%H%M%S,
// tinh MOT lan cho ca chuoi (hai lan xuat hien ra cung mot gia tri).
//
// ⚠️ Dung dong ho TUONG (std::time), KHONG phai Clock cua he: replay 100x
// se duc ra ten trung nhau neu lay dong ho mo phong.
//
// Khong gian `~`: shell da lam roi, lam lai la lech voi doi so trong nhay.
// Idempotent: f(f(x)) == f(x).
std::string ResolveMapPath(const std::string& raw);
// mkdir -p cho thu muc CHA cua `path`. Ok neu da co.
//
// Dung mkdir() POSIX chu khong phai <filesystem>: tren GCC 9 (xem
// CMakeLists.txt:76-88) <filesystem> can link them -lstdc++fs, ma vslam_common
// la dep cua MOI target trong cay nay.
StatusResponse EnsureParentDir(const std::string& path);
} // namespace vslam } // namespace vslam
#endif // VSLAM_NODE_CONSTANTS_H #endif // VSLAM_NODE_CONSTANTS_H

View File

@@ -151,6 +151,46 @@ struct OccupancyGrid {
std::vector<int8_t> data; // size = width * height std::vector<int8_t> data; // size = width * height
}; };
// Ban do VOXEL: dang thua, chi nhung o BI CHIEM.
//
// Nam o vslam_common chu khong o vslam_slam vi `vslam_web` phai ma hoa duoc
// kieu nay ma no chi phu thuoc vslam_common -- y het ly do OccupancyGrid nam
// o day.
//
// Chi so la SO NGUYEN CO DAU quanh goc (0,0,0) cua frame map:
// index = floor(toa_do / resolution)
// Goc ghim vinh vien tai goc cua map frame, khong troi theo ban do, nho vay
// hai lan xuat khac nhau so sanh truc tiep duoc bang phep tru tap hop.
// int16 o 0.10 m = +-3276 m, thua cho moi toa nha trong nha.
//
// Ten la `VoxelIndex` chu khong phai `VoxelKey`: `vslam::VoxelKey` DA TON TAI
// la mot HAM trong depth_filter.h. C++ cho phep ham va lop trung ten trong
// cung mot scope, nhung ham CHE ten lop -- `std::vector<VoxelKey>` khi do bat
// phai cai ham va bao "expected a type". Da mac dung loi nay mot lan.
struct VoxelIndex {
int16_t x = 0;
int16_t y = 0;
int16_t z = 0;
};
struct VoxelGrid {
Header header; // frame_id = kMapFrame
float resolution = 0.10f; // kich thuoc o PHAT (khac Grid/CellSize cua SLAM)
double origin_x = 0.0; // luon 0 hien tai; giu tren day de doi sau nay
double origin_y = 0.0;
double origin_z = 0.0;
// Tang khi tap cu KHONG con dung nua (do thi vua duoc toi uu lai sau mot
// vong dong, hoac doi resolution). Client thay epoch la se tai lai tu dau
// thay vi ap delta.
uint32_t epoch = 0;
bool truncated = false; // cham tran max_cells -> ban do bi cat bot
std::vector<VoxelIndex> cells; // DA SAP XEP theo khoa goi, khong trung
};
using VoxelGridPtr = std::shared_ptr<const VoxelGrid>;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// sensor_msgs // sensor_msgs
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@@ -1,6 +1,11 @@
#include "vslam/node_constants.h" #include "vslam/node_constants.h"
#include <sys/stat.h>
#include <cerrno>
#include <cstdlib> #include <cstdlib>
#include <cstring>
#include <ctime>
namespace vslam { namespace vslam {
namespace { namespace {
@@ -18,6 +23,19 @@ std::string Join(const std::string& dir, const std::string& rel) {
return dir + "/" + rel; return dir + "/" + rel;
} }
constexpr char kStampToken[] = "{stamp}";
// Dau thoi gian DIA PHUONG. Sap xep duoc theo thu tu chu cai, va nguoi van
// hanh doc no bang `ls` tren chinh con robot -- do la ly do khong dung UTC.
std::string NowStamp() {
const std::time_t t = std::time(nullptr);
std::tm tm {};
localtime_r(&t, &tm);
char buf[32];
std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm);
return std::string(buf);
}
} // namespace } // namespace
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); } std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
@@ -40,4 +58,58 @@ std::string CorpusDir() {
return MapDir(); return MapDir();
} }
std::string ResolveMapPath(const std::string& raw) {
if (raw.empty()) return raw; // DB trong RAM -- giu nguyen
std::string p = raw;
if (p.find(kStampToken) != std::string::npos) {
// MOT dau thoi gian cho ca chuoi: hai lan xuat hien phai ra cung gia tri,
// khong thi ten file va ten thu muc lech nhau mot giay.
const std::string stamp = NowStamp();
std::string out;
out.reserve(p.size() + 16);
size_t i = 0;
for (;;) {
const size_t k = p.find(kStampToken, i);
if (k == std::string::npos) {
out.append(p, i, std::string::npos);
break;
}
out.append(p, i, k - i);
out += stamp;
i = k + sizeof(kStampToken) - 1;
}
p.swap(out);
}
// Cung khuon mau voi dcf_path o app_config.cc: tuyet doi thi dung nguyen,
// tuong doi thi giai theo thu muc cua chinh loai file do.
if (p.front() == '/') return p;
return Join(MapDir(), p);
}
StatusResponse EnsureParentDir(const std::string& path) {
const size_t slash = path.find_last_of('/');
// Khong co '/' = file o thu muc hien tai; slash == 0 = ngay duoi root.
if (slash == std::string::npos || slash == 0) return StatusResponse::Ok();
const std::string dir = path.substr(0, slash);
for (size_t i = 1; i <= dir.size(); ++i) {
if (i != dir.size() && dir[i] != '/') continue;
const std::string part = dir.substr(0, i);
if (::mkdir(part.c_str(), 0775) == 0) continue;
if (errno == EEXIST) {
// EEXIST chua phai tin tot: co the la mot FILE thuong trung ten.
struct stat st {};
if (::stat(part.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) continue;
return StatusResponse::Error(StatusCode::kInvalidArgument,
"khong phai thu muc: " + part);
}
return StatusResponse::Error(
StatusCode::kUnavailable,
"khong tao duoc thu muc " + part + ": " + std::strerror(errno));
}
return StatusResponse::Ok();
}
} // namespace vslam } // namespace vslam

View File

@@ -10,9 +10,11 @@ vslam_add_library(vslam_drivers
PUBLIC_HDRS PUBLIC_HDRS
driver_config.h driver_config.h
driver_interfaces.h driver_interfaces.h
gamepad.h
scan_sanitizer.h scan_sanitizer.h
clock_sync.h clock_sync.h
mcu_protocol.h mcu_protocol.h
wt61pc_protocol.h
record_format.h record_format.h
record_io.h record_io.h
replay_source.h replay_source.h
@@ -37,11 +39,13 @@ find_package(Boost REQUIRED COMPONENTS system thread)
target_sources(vslam_drivers PRIVATE target_sources(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp) ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_filter.cpp)
set_source_files_properties( set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_filter.cpp
PROPERTIES COMPILE_OPTIONS "-w") PROPERTIES COMPILE_OPTIONS "-w")
target_include_directories(vslam_drivers PRIVATE target_include_directories(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk ${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk

View File

@@ -19,6 +19,48 @@ enum class LidarStampMode {
kLastPacketMinusScanTime, kLastPacketMinusScanTime,
}; };
// Bon bo loc chay TREN scan tho, truoc khi ra khoi driver.
//
// Vi sao can: LiDAR gan giua robot, giua bon cot do hai tang tren. Tia dap
// vao cot va vao chinh khung gan sinh ra ba loai rac ma ScanSanitizer khong
// bat duoc -- no chi cat QUAT co dinh, ma o day rac khong nam gon trong mot
// quat nao.
struct LidarFilterConfig {
// --- Tia keo dai (shadow / grazing angle) ---
// Tia luot qua MEP mot vat (cot chong) ve ra mot dai diem cheo keo dai ra
// sau vat do -- trong nhu mot buc tuong khong co that.
bool shadow_enabled = true;
double shadow_min_angle_deg = 12.0; // duoi goc nay coi la tia keo dai
int shadow_window = 4; // so tia lan can de xet
double shadow_min_range_diff = 0.05; // buoc nhay cu ly toi thieu, m
double shadow_max_range = 2.0; // chi loc trong pham vi nay, m
bool shadow_clear_start = false; // false: giu diem mep de khong an mat tuong that
int shadow_clear_neighbors = 0; // 0: khong lan sang diem tuong that
// --- Cuong do phan xa (RSSI) ---
// Tan xa yeu o gan thuong la bui hoac phan xa lech tu khung gan.
bool intensity_enabled = true;
double intensity_min = 30.0; // RSSI 0-255
double intensity_max = 255.0;
double intensity_max_range = 1.0; // chi loc trong pham vi nay, m
// --- Cum diem don le ---
// Mot vai diem roi rac o gan, khong lien voi be mat nao.
bool isolated_enabled = true;
int isolated_min_cluster_points = 3; // cum nho hon nguong nay thi xoa
double isolated_max_range_jump = 0.10; // hai tia lien tiep con coi la mot cum, m
double isolated_max_range = 2.0; // 0 = ap dung toan scan
// --- Hop quanh than robot ---
// Thay cho `sector_masks` khi LiDAR nam o TAM robot: luc do vung bi che
// khong con la mot quat goc ma la mot vung hinh hop quanh goc toa do.
bool box_enabled = true;
double box_min_x = -0.25;
double box_max_x = 0.25;
double box_min_y = -0.25;
double box_max_y = 0.0;
};
struct LidarConfig { struct LidarConfig {
std::string host_ip = "0.0.0.0"; // dia chi de bind, KHONG phai IP cua LiDAR std::string host_ip = "0.0.0.0"; // dia chi de bind, KHONG phai IP cua LiDAR
uint16_t port = 2368; // UDP, theo datasheet uint16_t port = 2368; // UDP, theo datasheet
@@ -73,9 +115,14 @@ struct LidarConfig {
bool inverted = true; bool inverted = true;
LidarStampMode stamp_mode = LidarStampMode::kFirstPacket; LidarStampMode stamp_mode = LidarStampMode::kFirstPacket;
// Bu do tre da do duoc, cong vao stamp. Chua do -> 0. // Bu do tre da do duoc, cong vao stamp. Chua do -> 0. sensors.yaml
// `lidar.stamp_offset_sec` (07/10: -0.055, do tren ban do that).
double stamp_offset_sec = 0.0; double stamp_offset_sec = 0.0;
// Chinh meo scan trong vong quet (runtime lam, khong phai driver -- driver
// khong biet robot dang chuyen dong the nao). sensors.yaml `lidar.deskew`.
bool deskew = true;
// Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la // Canh bao neu do dai sweep lech qua nhieu so voi scan_time du kien. Day la
// bo phat hien mat goi UDP mien phi ma driver goc khong co. // bo phat hien mat goi UDP mien phi ma driver goc khong co.
double sweep_duration_tolerance_sec = 0.005; double sweep_duration_tolerance_sec = 0.005;
@@ -83,6 +130,17 @@ struct LidarConfig {
double recv_timeout_sec = 1.0; double recv_timeout_sec = 1.0;
ScanSanitizerConfig sanitizer; ScanSanitizerConfig sanitizer;
// --- Bon bo loc scan cua LakiBeam ---
//
// Guong cua `lidar_core::ScanFilterConfig` (thirdparty). Khai o day thay vi
// dung thang kieu kia vi driver_config.h la header CONG KHAI: keo kieu
// thirdparty vao se bat moi nguoi dung vslam_drivers phai co include path
// cua no.
//
// Gia tri mac dinh lay tu lakibeam.yaml cua base_kit -- bo da duoc chinh
// tren chinh con robot nay.
LidarFilterConfig filter;
}; };
// --- Camera RealSense D410 ------------------------------------------------- // --- Camera RealSense D410 -------------------------------------------------
@@ -122,7 +180,17 @@ struct CameraConfig {
// --- MCU: IMU + barometer -------------------------------------------------- // --- MCU: IMU + barometer --------------------------------------------------
// Cach IMU noi vao may.
enum class McuProtocol {
// ESP32-S3 + WT61PC, text qua USB-CDC (/dev/ttyACM0). Xem mcu_bridge.cc.
kEspText,
// WT61PC noi THANG UART hoac cap USB-FTDI (/dev/imu), khung nhi phan 0x55.
// Khong con ESP32, khong co ClockSync. Xem wt61pc_bridge.cc.
kWt61pc,
};
struct McuConfig { struct McuConfig {
McuProtocol protocol = McuProtocol::kEspText;
std::string port = "/dev/ttyACM0"; std::string port = "/dev/ttyACM0";
// 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la // 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la
// 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang. // 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang.
@@ -140,6 +208,23 @@ struct McuConfig {
// stamp_skew_ms trong DriverStats se luon la 0 vi khong co gi de so. // stamp_skew_ms trong DriverStats se luon la 0 vi khong co gi de so.
bool expect_timestamps = false; bool expect_timestamps = false;
// Bu do tre noi tren, giay. Mau IMU dong dau luc `t` thuc ra do robot tai
// `t - imu_lag_sec`, nen driver tru thang vao stamp.
//
// Sua o DAY chu khong sua trong wheel_odometry: dau thoi gian sinh ra o day,
// va EkfSe2 cung an no (`UpdateImuYawRate(stamp, ...)` dung stamp de
// Predict, `PredictFromWheel` tron d_theta_enc voi d_theta_gyro theo trong
// so nghich phuong sai). Bu o mot cho tieu thu thi cho con lai van sai.
//
// Hau qua khi de 0 va do tre that khac 0: moi lan vao cua, encoder va gyro
// duoc tron o hai thoi diem khac nhau. Do duoc tren robot nay: lech 0.20-0.22
// rad/s luc chuyen tiep -- dung bang slip_threshold, nen wheel_odom bao TRUOT
// ma san khong he tron.
//
// 0 = khong bu. Do bang log `wheel_odom/lag: tot nhat XX ms`; quy trinh o
// sensors.yaml muc mcu.
double imu_lag_sec = 0.0;
double ping_period_sec = 1.0; // chu ky ping de dong bo dong ho double ping_period_sec = 1.0; // chu ky ping de dong bo dong ho
// Datasheet ICM-42688-P / BMP390. TAT CA deu la doan tu datasheet cho toi // Datasheet ICM-42688-P / BMP390. TAT CA deu la doan tu datasheet cho toi
@@ -149,6 +234,10 @@ struct McuConfig {
double baro_variance = 9.0; double baro_variance = 9.0;
double read_timeout_sec = 1.0; double read_timeout_sec = 1.0;
// Chi cho kWt61pc: khong co khung hop le nao trong chung nay (giay) thi WARN
// kem goi y. Cam bien 10 Hz nen 2 s la mat ~20 khung, khong con la jitter.
double no_data_warn_sec = 2.0;
}; };
// --- Base: encoder + motor ------------------------------------------------- // --- Base: encoder + motor -------------------------------------------------
@@ -189,10 +278,23 @@ struct BaseConfig {
std::string dcf_path; std::string dcf_path;
// Encoder resolution cua ZLAC8015D, dem/vong SAU hop so, doc qua 0x6064. // Encoder resolution cua ZLAC8015D, dem/vong SAU hop so, doc qua 0x6064.
// 0 = doc tu thiet bi luc Open() (0x608F:1 Encoder Increments) thay vi tin //
// mot hang so chep tay. // ⚠️ 0 = dung mac dinh 16384 trong zlac_base.cc (4096 wire x 4 cau phuong),
// va con so do CHUA duoc kiem chung. base_kit KHONG giup duoc gi o day: ho
// chi doc van toc (0x606C, don vi rpm) nen khong bao gio can biet count/vong
// -- tham so nay khong ton tai trong motor_params.yaml cua ho.
// Cach do: quay banh tay dung mot vong, so hieu 0x6064:1 truoc/sau.
uint32_t encoder_counts_per_rev = 0; uint32_t encoder_counts_per_rev = 0;
// Thoi gian ramp gui xuong 0x6083/0x6084 (Profile acceleration/deceleration),
// don vi ms tu 0 den toc do dinh muc. SO CANG LON, RAMP CANG CHAM.
//
// 1200 la gia tri base_kit dung (motor_params.yaml: acc_dec_val). Mac dinh
// cua ZlacMotorDriver::enableHardware() la 500, tuc tang toc NHANH GAP 2.4
// LAN, du de banh truot that tren san tron. base_kit da chinh so nay tren
// chinh con robot nay nen no thang -- day la tham so cua THIET BI.
uint32_t accel_ramp_ms = 1200;
// --- Dung khi protocol = kVendorSerial --- // --- Dung khi protocol = kVendorSerial ---
std::string port = "/dev/ttyUSB0"; std::string port = "/dev/ttyUSB0";
uint32_t baud = 115200; uint32_t baud = 115200;

View File

@@ -0,0 +1,281 @@
#ifndef VSLAM_GAMEPAD_H
#define VSLAM_GAMEPAD_H
// Tay cam lai tay -- Logitech F710/F310 o mode XInput, qua joydev.
//
// ================== NGUON GOC ==================
// Port 1-1 tu `base_kit/src/joy_control/src/joy_control_node.cpp`, ban dang
// chay that tren chinh con robot nay. MOI hang so o day deu co mot dong tuong
// ung ben do, va cho nao lech thi duoc ghi ro la lech vi cai gi.
//
// GIU NGUYEN cam giac lai: he so turbo/slow, cach chon giua can gat va D-pad,
// cong thuc deadzone, cu kich toc do toi thieu de thang ma sat tinh, va luat
// "gui 0 trong 1.5 giay roi IM de nhuong nguon nhap khac". Bon thu do da duoc
// chinh tren robot that; viet lai cho "dep" la vut het cong chinh do di.
//
// ================== VI SAO KHONG NAM TRONG driver_interfaces.h ==================
// Cac interface ben do ton tai de ReplaySource thay the duoc driver that --
// do la diem tua cua chien luoc kiem chung. Tay cam KHONG thuoc nhom do: no la
// dau vao cua NGUOI VAN HANH, khong phai du lieu cam bien. Phat lai mot ban
// ghi ma trong do co ai do dang gat can la dieu KHONG duoc phep xay ra.
//
// ================== HAI LOP, TACH HAN ==================
// GamepadReader -- doc joydev tren luong rieng, CHI nuoi trang thai tho.
// GamepadMapper -- THUAN, khong I/O: trang thai tho -> van toc. Test duoc
// khong can tay cam, va do la noi toan bo logic nam.
//
// ================== BAY CUA joydev ==================
// joydev CHI gui event khi gia tri DOI. Giu can gat dung yen = khong co event
// nao suot ca phut. Ben ROS, `joy_node` che bay nay bang `autorepeat_rate: 50`
// (teleop_all.launch.py). O day khong co joy_node, nen NGUOI DOC phai tu bom
// lai: `GamepadLoop()` chay 50 Hz va ghi `raw_cmd_` moi vong. Khong lam vay
// thi `raw_cmd_stamp_` cu dan va SafetyMonitor ban NO_CMD (cmd_timeout 0.5 s)
// dung xe GIUA LUC nguoi lai dang giu can gat.
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "vslam/clock.h"
#include "vslam/vslam_common.h"
namespace vslam {
// Mac dinh lay tu teleop_all.launch.py + joy_control_node.cpp cua base_kit.
// Moi index deu la CAU HINH: bo tay cam khac tra ve layout khac, va sua mot
// dong YAML re hon build lai. Dung `vslam_joy_probe` de do index that.
struct GamepadConfig {
bool enabled = false;
std::string device = "/dev/input/js0";
// = `autorepeat_rate` cua joy_node. Xem bay joydev o dau file.
double publish_rate_hz = 50.0;
// ⚠️ Tran cua RIENG tay cam, giong tham so cua node ROS. robot.yaml
// (base.max_linear 0.35) va safety.yaml (max_linear 0.35) van kep lan nua o
// duoi, nen de 0.5 o day KHONG lam robot chay 0.5 -- turbo se bao hoa o
// 0.35. Giu nguyen so cua base_kit de con doi chieu duoc hai ben.
double max_linear_speed = 0.5;
double max_angular_speed = 1.0;
double deadzone = 0.05;
// --- Ma sat tinh cua dong co -- joy_control_node.cpp:240-250 ---
//
// Ban phim nhay thang len 0.5 nen xe chay ngay; can gat tang dan tu 0.01 nen
// dong co khong thang noi ma sat tinh va nguoi lai tuong tay cam bi tre.
// Cu kich nay lam can gat "bat" ngay khi nhich khoi vung chet.
//
// ⚠️ TREN ROBOT NAY TRAN THAP HON base_kit: 0.2 tren tran 0.5 la 40% dai,
// nhung tren tran 0.35 la 57% -- can gat gan nhu thanh cong tac, mat het
// dai bo cham. Muon giu dung ti le 40% thi dat 0.14.
double min_linear_kick = 0.2;
double min_angular_kick = 0.4;
// Gui 0 bao lau sau khi nha can, roi IM han. joy_control_node.cpp:259.
// "Im" la co y: no nhuong quyen lai cho nguon nhap khac (o base_kit la ban
// phim; o day la joystick tren web).
double idle_publish_sec = 1.5;
// Thay cho `exit(1)` + systemd Restart cua base_kit. Xem ghi chu o
// GamepadReader.
double reopen_period_sec = 1.0;
// He so khi giu RB / LB. joy_control_node.cpp:212-218.
double turbo_linear = 2.0;
double turbo_angular = 0.5; // quay CHAM lai khi chay nhanh, de khong gat
double slow_linear = 0.5;
double slow_angular = 0.5;
// --- Index, layout F710/F310 XInput ---
int axis_linear = 1; // can trai Y
int axis_linear_dpad = 7; // D-pad Y
int axis_angular = 3; // can phai X
int axis_angular_dpad = 6; // D-pad X
int button_enable = 7; // Start -- BAT/TAT dieu khien
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
// that, nen vong lap sua-thu phai re.
//
// Dau mong doi SAU khi ap hai co nay: day can len = duong = tien,
// gat trai = duong = quay trai (REP-103).
bool invert_linear = false;
bool invert_angular = false;
// Header cua base_kit hua "LT (axis 2): Emergency stop - HOLD to stop"
// nhung code KHONG he doc truc do. Cai dat o day, va de TAT mac dinh dung
// bang hanh vi that cua base_kit.
//
// ⚠️ CHIEU CUA COC DO DUOC TREN CHINH TAY CAM NAY, khong phai doan.
//
// `vslam_joy_probe` voi "Logitech Gamepad F710" tren may nay:
// axes[2] = -1.000 va axes[5] = -1.000 suot ca phien, khong cham coc
// Reader khong dao dau, nen mapper thay dung con so do: coc NGHI o -1.0 va
// bop len +1.0. Vi vay nguong la "> lt_press_above" = 0.5.
//
// Lay nguong am (vd "< 0") thi coc DANG NGHI thoa dieu kien va robot dung
// cung vinh vien, khong co dau hieu gi de doan ra.
//
// 0.5 con an toan cho truong hop driver chua gui mau dau tien va truc doc ra
// 0.0: 0.0 khong vuot 0.5.
//
// Bo tay cam khac co the nghi o chieu nguoc lai. DO LAI BANG PROBE truoc khi
// bat `lt_stop`.
//
// KHONG chot e-stop cua he thong: go e-stop bat buoc co token (xem
// system.yaml web), nen mot cu va nham vao coc se khoa robot lai cho toi khi
// co nguoi mo trinh duyet. Day chi la "giu de dung", dung nhu header hua.
bool lt_stop = false;
int axis_lt = 2;
double lt_press_above = 0.5;
};
// Doi mot gia tri truc THO cua joydev sang [-1, 1]. KHONG dao dau.
//
// ⚠️ PHEP DAO DAU NAM O CONFIG, KHONG O DAY -- va tren robot nay no PHAI bat.
//
// Do tren "Logitech Gamepad F710" qua xpad: joydev tra ve AM khi day can len
// va khi gat sang trai. Chay khong dao: day can len -> banh quay LUI, gat
// trai -> robot re PHAI. Vi vay `system.yaml` cua robot nay dat
// `invert_linear: true` va `invert_angular: true`.
//
// Vi sao khong dao thang trong ham nay: bo tay cam khac co the khac chieu, va
// chieu truc chi kiem duoc bang cach cam tay cam vao robot that roi nhin banh
// quay. Mot dong YAML re hon mot vong sua code + build + push + pull -- vong
// do da ton cua du an nay vai luot roi.
//
// De o header CHI de test khoa duoc quy uoc nay. `vslam_joy_probe` nhan ban
// lai phep tinh nay thay vi goi vao day: no co y khong phu thuoc lib nao.
double NormalizeJoydevAxis(int16_t raw);
// Anh chup trang thai tho. Index NGOAI KHOANG tra 0 / false thay vi doc ra
// ngoai vector.
//
// ⚠️ Day chinh la cho base_kit sap: `msg->buttons[7]` va `msg->axes[7]` duoc
// doc THANG, khong kiem `.size()` (joy_control_node.cpp:180, 223). Bo tay cam
// bao it truc/nut hon la doc ra ngoai vector -- UB, va tren tay PS thi so truc
// khac that.
struct GamepadState {
bool connected = false;
std::vector<float> axes;
std::vector<uint8_t> buttons;
double Axis(int i) const {
if (i < 0 || static_cast<size_t>(i) >= axes.size()) return 0.0;
return static_cast<double>(axes[i]);
}
bool Button(int i) const {
if (i < 0 || static_cast<size_t>(i) >= buttons.size()) return false;
return buttons[i] != 0;
}
};
struct GamepadCommand {
// Co nen GHI `raw_cmd_` vong nay khong. false = im, nhuong nguon khac.
bool publish = false;
double linear = 0.0;
double angular = 0.0;
bool enabled = false; // trang thai toggle cua nut Start
double linear_mult = 1.0; // de log, giong dong log cua base_kit
double angular_mult = 1.0;
// 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.
// Moc thoi gian do nguoi goi truyen vao, nen test lai duoc dung chuoi su kien.
class GamepadMapper {
public:
explicit GamepadMapper(const GamepadConfig& cfg);
// `now` chi dung cho cua so idle 1.5 s.
GamepadCommand Step(const GamepadState& s, UnixTime now);
bool enabled() const { return enabled_; }
// Cong thuc deadzone cua base_kit: cat o nguong roi GIAN LAI phan con lai ra
// ca dai [0, 1], de ngay sau vung chet khong bi nhay bac.
double ApplyDeadzone(double v) const;
private:
GamepadConfig cfg_;
bool enabled_ = false;
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_;
};
// Doc joydev tren luong rieng.
//
// ================== KHONG exit(1) ==================
// base_kit goi `exit(1)` khi mat tay cam (joy_control_node.cpp:145) va de
// systemd dung lai node. O do dieu do an toan: no la mot tien trinh ROS rieng.
//
// O day `vslam_node` la MOT tien trinh giu ca SLAM, EKF, web va luong safety.
// Rut day tay cam ma giet tien trinh nghia la robot mat vong an toan giua luc
// dang chay. Thay bang: danh dau mat ket noi, de GamepadMapper tat dieu khien
// (giong het hanh vi sau timeout cua base_kit -- phai bam Start lai), va thu
// mo lai thiet bi moi `reopen_period_sec`.
class GamepadReader {
public:
GamepadReader(const GamepadConfig& cfg, ClockPtr clock);
~GamepadReader();
GamepadReader(const GamepadReader&) = delete;
GamepadReader& operator=(const GamepadReader&) = delete;
// Bat luong doc. Chua cam tay cam KHONG phai la loi chet: tra ve
// kUnavailable de nguoi goi log WARN, nhung luong van chay va van thu mo
// lai. Tu choi khoi dong ca node vi thieu tay cam la sai.
StatusResponse Open();
void Close();
GamepadState Snapshot() const;
// Ten thiet bi + so truc/nut, lay luc mo duoc. Do la thu DUY NHAT noi cho
// nguoi van hanh biet layout index co khop config khong.
std::string DeviceInfo() const;
private:
void ReadLoop();
bool TryOpen();
void Drop(const std::string& why);
GamepadConfig cfg_;
ClockPtr clock_;
int fd_ = -1;
// atomic: Close() ghi tu luong goi, ReadLoop doc moi vong. Mot bool thuong o
// day la data race that, va ThreadSanitizer cua repo nay se bat dung no.
std::atomic<bool> running_{false};
std::thread thread_;
mutable std::mutex mu_;
GamepadState state_;
std::string info_;
bool warned_missing_ = false;
};
} // namespace vslam
#endif // VSLAM_GAMEPAD_H

View File

@@ -73,6 +73,10 @@ enum class VsrStream : uint8_t {
// bao "xanh" cho mot he da mat hai nhanh an toan. // bao "xanh" cho mot he da mat hai nhanh an toan.
kUltrasonic = 11, kUltrasonic = 11,
kBumper = 12, kBumper = 12,
// MO RONG: tu the THAT 6-DoF, CHI ban ghi tu bo mo phong. De cham diem
// offline (VO/VIO, z tren doc). Replay khong dua no vao duong ong nao --
// khong stage nao duoc doc su that.
kGroundTruth = 13,
}; };
const char* VsrStreamName(VsrStream s); const char* VsrStreamName(VsrStream s);
@@ -109,6 +113,11 @@ bool DecodeUltrasonicPayload(const std::string& buf, double* range, size_t* coun
void EncodeBumperPayload(uint32_t mask, std::string* out); void EncodeBumperPayload(uint32_t mask, std::string* out);
bool DecodeBumperPayload(const std::string& buf, uint32_t* mask); bool DecodeBumperPayload(const std::string& buf, uint32_t* mask);
// Ground truth 6-DoF: sau double x, y, z, roll, pitch, yaw cua base_footprint
// trong frame world (z = do cao san duoi robot; pitch duong = mui chuc xuong).
void EncodeGroundTruthPayload(const double pose6[6], std::string* out);
bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]);
void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out); void EncodeCameraInfoPayload(const CameraInfo& info, std::string* out);
bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out); bool DecodeCameraInfoPayload(const std::string& buf, CameraInfo* out);

View File

@@ -0,0 +1,81 @@
#ifndef VSLAM_WT61PC_PROTOCOL_H
#define VSLAM_WT61PC_PROTOCOL_H
// Khung nhi phan cua WT61PC (IMU 6 truc, WitMotion) khi cam THANG vao UART hoac
// cap USB-FTDI cua Jetson, khong qua ESP32.
//
// Khac mcu_protocol.h: day KHONG phai giao thuc cua du an. No la giao thuc cua
// cam bien, nen file nay GHI LAI dac ta cua nha san xuat; ben phai khop la
// cam bien, khong phai firmware.
//
// ================== KHUNG ==================
// 11 byte. Cam bien phat lien tuc, moi chu ky ba khung theo thu tu:
// 0x55 0x51 axL axH ayL ayH azL azH TL TH SUM gia toc
// 0x55 0x52 gxL gxH gyL gyH gzL gzH TL TH SUM van toc goc
// 0x55 0x53 rL rH pL pH yL yH TL TH SUM goc (roll, pitch, yaw)
// Moi truong la int16 little-endian. SUM = tong 10 byte dau, lay 8 bit thap.
//
// ================== DOI DON VI ==================
// gia toc : raw / 32768 * 16 g -> m/s^2 (g = 9.80665)
// van toc : raw / 32768 * 2000 do/s -> rad/s
// goc : raw / 32768 * 180 do -> rad
// Cung cong thuc voi firmware/imu_uart/main/main.c, nen truc va dau KHONG doi so
// voi ban ghi `I` cua ESP32: doi nguon IMU khong dong toi EKF hay gravity_align.
//
// ================== TAN SO ==================
// Mac dinh cua cam bien la 10 Hz o 9600 baud (do duoc: chu ky 0.1001 s). Moi
// chu ky 33 byte, nen 9600 baud tran o ~29 Hz. Muon cao hon phai doi baud CUA
// CAM BIEN (lenh cau hinh cua WitMotion), khong phai chi baud ben host.
#include <cstddef>
#include <cstdint>
namespace vslam {
constexpr size_t kWt61pcFrameBytes = 11;
constexpr uint8_t kWt61pcHeader = 0x55;
enum class Wt61pcType : uint8_t {
kAccel = 0x51, // m/s^2
kGyro = 0x52, // rad/s
kAngle = 0x53, // rad
};
struct Wt61pcFrame {
Wt61pcType type = Wt61pcType::kAccel;
// Da DOI DON VI theo `type`, xem tren.
double x = 0.0;
double y = 0.0;
double z = 0.0;
};
// Bo tach khung theo tung byte. Khong doc dong ho, khong goi he thong: chi la
// ham thuan tren chuoi byte, nen test duoc ma khong can cong serial.
class Wt61pcParser {
public:
// Nap mot byte. true khi byte nay hoan tat mot khung HOP LE loai
// kAccel/kGyro/kAngle (checksum dung) va *out da duoc dien.
bool Push(uint8_t byte, Wt61pcFrame* out);
void Reset();
uint64_t bad_checksum() const { return bad_checksum_; }
// Byte bi bo vi khong thuoc khung nao (rac, hoac mat dong bo).
uint64_t skipped_bytes() const { return skipped_bytes_; }
// Khung dung checksum nhung loai khac 0x51..0x53 (vd 0x54). WT61PC khong co
// tu ke nen binh thuong bang 0; dem de thay khi cam nham mot cam bien khac.
uint64_t other_frames() const { return other_frames_; }
private:
void Resync();
uint8_t buf_[kWt61pcFrameBytes] = {};
size_t n_ = 0;
uint64_t bad_checksum_ = 0;
uint64_t skipped_bytes_ = 0;
uint64_t other_frames_ = 0;
};
} // namespace vslam
#endif // VSLAM_WT61PC_PROTOCOL_H

View File

@@ -83,26 +83,50 @@ void ClockSync::Fit() {
if (best.size() < 2) return; if (best.size() < 2) return;
const double n = static_cast<double>(best.size()); const double n = static_cast<double>(best.size());
double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
// ⚠️ PHAI doi goc truoc khi fit. Cong thuc `(n*sxy - sx*sy) / (n*sxx - sx*sx)`
// tren so THO la mot cai bay so hoc o day, vi hai truc lech nhau chin bac do
// lon: `host_s` la thoi gian Unix (~1.8e9) con `mcu_s` la giay tu luc MCU
// khoi dong (~vai tram, ve 0 moi lan cam lai dien).
//
// Voi mau trai dai vai giay thi `n*sxy` va `sx*sy` deu co do lon ~4e9 trong
// khi HIEU that su cua chung chi co ~1e-2. double giu duoc 15-16 chu so co
// nghia, tuc o do lon 4e9 thi buoc nho nhat da la ~1e-6 -- phan tin hieu bi
// nuot gan het trong phep tru. Trieu triet tieu kinh dien.
//
// Da do tren robot that, KHONG phai lo ngai ly thuyet: fit dau tien cho
// skew = 0.000318103, tuc lech -999682 ppm. ClockSync tu choi ket qua do
// (dung), roi ve skew = 1.0 va o nguyen do -- nen chuoi dong ho MCU khong he
// chay du log noi "ClockSync san sang".
//
// Doi goc ve trung binh thi ca hai truc con lai bien thien that (co giay),
// phep tru khong con triet tieu, va ket qua khong doi ve mat toan hoc.
double mx = 0.0, my = 0.0;
for (const auto& s : best) { for (const auto& s : best) {
sx += s.mcu_s; mx += s.mcu_s;
sy += s.host_s; my += s.host_s;
sxx += s.mcu_s * s.mcu_s; }
sxy += s.mcu_s * s.host_s; mx /= n;
my /= n;
double sxx = 0.0, sxy = 0.0;
for (const auto& s : best) {
const double dx = s.mcu_s - mx;
sxx += dx * dx;
sxy += dx * (s.host_s - my);
} }
const double denom = n * sxx - sx * sx; if (!(sxx > 1e-12)) {
if (std::abs(denom) < 1e-12) {
// Cac mau qua gan nhau ve thoi gian -> chua uoc luong duoc skew, nhung // Cac mau qua gan nhau ve thoi gian -> chua uoc luong duoc skew, nhung
// offset thi van uoc luong duoc. // offset thi van uoc luong duoc.
offset_ = (sy - sx) / n; offset_ = my - mx;
skew_ = 1.0; skew_ = 1.0;
ready_ = true; ready_ = true;
return; return;
} }
const double skew = (n * sxy - sx * sy) / denom; const double skew = sxy / sxx;
const double offset = (sy - skew * sx) / n; const double offset = my - skew * mx;
// Skew phai rat gan 1.0 -- thach anh lech vai chuc ppm. Lech nhieu nghia la // Skew phai rat gan 1.0 -- thach anh lech vai chuc ppm. Lech nhieu nghia la
// du lieu rac (giao thuc sai, hoac micros() tran ma khong unwrap). // du lieu rac (giao thuc sai, hoac micros() tran ma khong unwrap).
@@ -113,7 +137,7 @@ void ClockSync::Fit() {
<< " ppm), bo qua ket qua fit. Kiem giao thuc MCU" << " ppm), bo qua ket qua fit. Kiem giao thuc MCU"
" va viec unwrap micros()."); " va viec unwrap micros().");
skew_ = 1.0; skew_ = 1.0;
offset_ = (sy - sx) / n; offset_ = my - mx;
ready_ = true; ready_ = true;
return; return;
} }

View File

@@ -0,0 +1,420 @@
// Tay cam lai tay. Xem gamepad.h truoc khi sua bat cu gi o day -- moi hang so
// deu co mot dong tuong ung trong base_kit/src/joy_control.
#include "vslam/gamepad.h"
#include <errno.h>
#include <fcntl.h>
#include <linux/joystick.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <utility>
#include "vslam/log.h"
namespace vslam {
namespace {
// Gia tri truc cua joydev la int16. Chia cho 32767 ra [-1, 1].
constexpr double kAxisScale = 1.0 / 32767.0;
// Cho poll() truoc khi ngo lai co running_. Du ngan de Close() khong treo,
// du dai de khong quay tit CPU.
constexpr int kPollTimeoutMs = 100;
// Chon trong hai truc cai nao dang duoc gat manh hon.
// joy_control_node.cpp:223 va :229 -- can gat va D-pad dung chung mot duong,
// khong cong vao nhau.
double PickLarger(double a, double b) {
return (std::abs(a) > std::abs(b)) ? a : b;
}
double Clamp(double v, double limit) {
const double l = std::abs(limit);
return std::max(-l, std::min(l, v));
}
// Nang do lon len toi thieu `floor`, giu nguyen dau. Khong dung khi v == 0:
// khong co dau nao de giu, va "dang dung yen" khong phai truong hop can thang
// ma sat tinh.
double LiftMagnitude(double v, double floor) {
if (floor <= 0.0 || v == 0.0) return v;
if (v > 0.0 && v < floor) return floor;
if (v < 0.0 && v > -floor) return -floor;
return v;
}
} // namespace
// Kep ve [-1, 1], KHONG dao dau. Phep dao nam o `invert_linear` /
// `invert_angular` trong config -- va tren robot nay ca hai deu PHAI bat.
// Xem gamepad.h.
//
// Kep can that: int16 nho nhat la -32768, chia 32767 ra -1.00003.
double NormalizeJoydevAxis(int16_t raw) {
const double v = static_cast<double>(raw) * kAxisScale;
return std::max(-1.0, std::min(1.0, v));
}
// ---------------------------------------------------------------------------
// GamepadMapper -- THUAN
// ---------------------------------------------------------------------------
GamepadMapper::GamepadMapper(const GamepadConfig& cfg) : cfg_(cfg) {}
double GamepadMapper::ApplyDeadzone(double value) const {
// joy_control_node.cpp:157-164, giu nguyen cong thuc.
if (std::abs(value) < cfg_.deadzone) return 0.0;
const double sign = (value > 0.0) ? 1.0 : -1.0;
const double span = 1.0 - cfg_.deadzone;
if (span <= 1e-9) return sign;
return sign * (std::abs(value) - cfg_.deadzone) / span;
}
GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
GamepadCommand out;
// --- Mat ket noi ---------------------------------------------------------
// Tuong duong nhanh timeout cua base_kit (joy_control_node.cpp:327-331): tat
// dieu khien, bat nguoi lai bam Start lai sau khi cam lai. KHAC mot cho:
// base_kit goi exit(1) o day, xem ghi chu trong gamepad.h.
if (!s.connected) {
if (was_connected_) {
out.connected_changed = true;
if (enabled_) out.enabled_changed = true;
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
// cung phai duoc don, chu khong de SafetyMonitor cho het NO_CMD.
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
out.publish = true;
} else {
have_active_ = false;
}
return out;
}
if (!was_connected_) {
was_connected_ = true;
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)) {
if (!enable_pressed_) {
enable_pressed_ = true;
enabled_ = !enabled_;
out.enabled_changed = true;
if (!enabled_) {
// ⚠️ LECH base_kit MOT CHUT, co y.
//
// Ben do, tat dieu khien xong thi node IM luon (dong publish bi comment
// lai de "nhuong ban phim"), va xe dung nho cmd_timeout 0.5 s cua
// Zlac. O day ta don lenh ve 0 trong cua so idle 1.5 s -- dung duong
// ma cu nha can gat da di. Chan hon, va van im sau 1.5 s nen joystick
// tren web khong bi cuop quyen.
last_active_ = now;
have_active_ = true;
}
}
} else {
enable_pressed_ = false;
}
out.enabled = enabled_;
// --- Nut B: ve 0 ngay ----------------------------------------------------
// joy_control_node.cpp:197-201. Chay BAT KE dang bat hay tat.
if (s.Button(cfg_.button_zero)) {
out.publish = true;
out.linear = 0.0;
out.angular = 0.0;
have_active_ = false;
return out;
}
// --- Coc LT: giu de dung -------------------------------------------------
// Thu ma header base_kit hua nhung code khong co. Mac dinh TAT.
// Do bang probe tren tay cam nay: coc nghi o -1.0, bop len +1.0. Xem
// gamepad.h truoc khi doi chieu so sanh nay.
if (cfg_.lt_stop && s.Axis(cfg_.axis_lt) > cfg_.lt_press_above) {
out.publish = true;
out.linear = 0.0;
out.angular = 0.0;
last_active_ = now;
have_active_ = true;
return out;
}
if (!enabled_) {
// joy_control_node.cpp:204-206: chua bat thi khong xu ly chuyen dong.
// Van con cua so idle de don not lenh cuoi.
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
out.publish = true;
} else {
have_active_ = false;
}
return out;
}
// --- He so turbo / slow --------------------------------------------------
// joy_control_node.cpp:208-218. Phai VUA GIU nut VUA gat can moi an.
double lin_mult = 1.0;
double ang_mult = 1.0;
if (s.Button(cfg_.button_turbo)) {
lin_mult = cfg_.turbo_linear;
ang_mult = cfg_.turbo_angular;
} else if (s.Button(cfg_.button_slow)) {
lin_mult = cfg_.slow_linear;
ang_mult = cfg_.slow_angular;
}
out.linear_mult = lin_mult;
out.angular_mult = ang_mult;
// --- Truc ----------------------------------------------------------------
double lin_axis =
PickLarger(s.Axis(cfg_.axis_linear), s.Axis(cfg_.axis_linear_dpad));
double ang_axis =
PickLarger(s.Axis(cfg_.axis_angular), s.Axis(cfg_.axis_angular_dpad));
// Dao dau o DAY, sau khi da chon giua can gat va D-pad: hai nguon do cung
// mot truc logic nen phai chiu cung mot phep dao.
if (cfg_.invert_linear) lin_axis = -lin_axis;
if (cfg_.invert_angular) ang_axis = -ang_axis;
double linear = ApplyDeadzone(lin_axis) * cfg_.max_linear_speed * lin_mult;
double angular = ApplyDeadzone(ang_axis) * cfg_.max_angular_speed * ang_mult;
// Kep theo tran DA NHAN he so, khong theo tran co ban: turbo duoc phep vuot
// nguong thuong. joy_control_node.cpp:236-238.
linear = Clamp(linear, cfg_.max_linear_speed * lin_mult);
angular = Clamp(angular, cfg_.max_angular_speed * ang_mult);
// --- Ma sat tinh ---------------------------------------------------------
// joy_control_node.cpp:243-250. Nguong xet la TRUC THO, khong phai van toc
// da tinh: nguoi lai nhich can la phai co luc, bat ke he so dang la bao nhieu.
if (std::abs(lin_axis) > cfg_.deadzone) {
linear = LiftMagnitude(linear, cfg_.min_linear_kick);
}
if (std::abs(ang_axis) > cfg_.deadzone) {
angular = LiftMagnitude(angular, cfg_.min_angular_kick);
}
// ⚠️ KEP LAI SAU CU KICH -- base_kit KHONG lam buoc nay.
//
// Ben do cu kich la lenh cuoi cung, nen no VUOT duoc tran vua kep o tren.
// Voi so cua base_kit dieu do khong bao gio lo ra: tran 0.5, che do cham con
// 0.25, van tren muc kich 0.2. Nhung dat `max_linear_speed: 0.35` cho khop
// tran that cua robot nay thi che do cham con 0.175 -- va cu kich day len
// 0.2, tuc nut LB "chay cham" lai NHANH HON tran cua chinh no.
//
// O moi cau hinh ma base_kit thuc su dung, hai ban cho ket qua giong het.
linear = Clamp(linear, cfg_.max_linear_speed * lin_mult);
angular = Clamp(angular, cfg_.max_angular_speed * ang_mult);
const bool idle = (linear == 0.0 && angular == 0.0);
if (!idle) {
last_active_ = now;
have_active_ = true;
out.publish = true;
out.linear = linear;
out.angular = angular;
return out;
}
// --- Idle: gui 0 trong 1.5 s roi IM --------------------------------------
// joy_control_node.cpp:255-267. Cai "im" moi la phan quan trong: no tra
// quyen lai cho nguon nhap khac (ben do la ban phim, o day la joystick web).
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
out.publish = true;
out.linear = 0.0;
out.angular = 0.0;
} else {
have_active_ = false;
}
return out;
}
// ---------------------------------------------------------------------------
// GamepadReader -- joydev
// ---------------------------------------------------------------------------
GamepadReader::GamepadReader(const GamepadConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
GamepadReader::~GamepadReader() { Close(); }
bool GamepadReader::TryOpen() {
const int fd = ::open(cfg_.device.c_str(), O_RDONLY | O_NONBLOCK);
if (fd < 0) {
if (!warned_missing_) {
// MOT lan thoi. Thu lai moi giay ma log moi giay thi log thanh vo dung.
VSLAM_WARN("gamepad: khong mo duoc " << cfg_.device << " ("
<< std::strerror(errno) << ") -- se thu lai moi "
<< cfg_.reopen_period_sec << " s");
warned_missing_ = true;
}
return false;
}
uint8_t n_axes = 0;
uint8_t n_buttons = 0;
char name[128] = {};
if (::ioctl(fd, JSIOCGAXES, &n_axes) < 0) n_axes = 0;
if (::ioctl(fd, JSIOCGBUTTONS, &n_buttons) < 0) n_buttons = 0;
if (::ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0) {
std::snprintf(name, sizeof(name), "(khong doc duoc ten)");
}
fd_ = fd;
warned_missing_ = false;
{
std::lock_guard<std::mutex> lk(mu_);
state_.axes.assign(n_axes, 0.0f);
state_.buttons.assign(n_buttons, 0);
state_.connected = true;
info_ = std::string(name) + ", " + std::to_string(n_axes) + " truc, " +
std::to_string(n_buttons) + " nut";
}
// In ra layout THAT. Config noi "can trai Y la axes[1]"; dong nay la cach
// duy nhat de nguoi van hanh doi chieu ma khong phai doan.
VSLAM_INFO("gamepad: mo " << cfg_.device << " -- " << info_
<< ". Kiem index bang `vslam_joy_probe` neu lai thay nguoc.");
return true;
}
void GamepadReader::Drop(const std::string& why) {
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
{
std::lock_guard<std::mutex> lk(mu_);
if (!state_.connected) return;
state_.connected = false;
// Xoa trang thai: giu lai gia tri cuoi cung cua mot tay cam da rut ra la
// cach de mot cu gat con sot lai "song day" sau khi cam lai.
std::fill(state_.axes.begin(), state_.axes.end(), 0.0f);
std::fill(state_.buttons.begin(), state_.buttons.end(), 0);
}
VSLAM_WARN("gamepad: MAT KET NOI (" << why << "). Dieu khien tat; cam lai "
"roi bam Start de bat lai.");
}
StatusResponse GamepadReader::Open() {
if (running_) return StatusResponse::Ok();
running_ = true;
const bool ok = TryOpen();
thread_ = std::thread([this] { ReadLoop(); });
if (!ok) {
return StatusResponse::Error(StatusCode::kUnavailable,
"chua mo duoc " + cfg_.device);
}
return StatusResponse::Ok();
}
void GamepadReader::Close() {
if (!running_) return;
running_ = false;
if (thread_.joinable()) thread_.join();
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
void GamepadReader::ReadLoop() {
const auto reopen_period = std::chrono::duration_cast<Clock::SteadyPoint::duration>(
std::chrono::duration<double>(cfg_.reopen_period_sec > 0.0
? cfg_.reopen_period_sec
: 1.0));
// Open() vua thu mot lan roi, nen lan thu tiep theo cach mot chu ky -- khong
// thu lai ngay o vong dau.
Clock::SteadyPoint next_try = clock_->Steady() + reopen_period;
while (running_) {
if (fd_ < 0) {
// Cam nong. KHONG exit(1) nhu base_kit -- xem ghi chu o gamepad.h.
if (clock_->Steady() < next_try) {
clock_->SleepFor(std::chrono::milliseconds(kPollTimeoutMs));
continue;
}
next_try = clock_->Steady() + reopen_period;
TryOpen();
continue;
}
pollfd pfd{};
pfd.fd = fd_;
pfd.events = POLLIN;
const int rc = ::poll(&pfd, 1, kPollTimeoutMs);
if (rc < 0) {
if (errno == EINTR) continue;
Drop(std::string("poll(): ") + std::strerror(errno));
next_try = clock_->Steady() + reopen_period;
continue;
}
if (rc == 0) continue; // khong co event -- binh thuong, xem bay joydev
if ((pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
Drop("thiet bi bien mat");
next_try = clock_->Steady() + reopen_period;
continue;
}
js_event ev{};
const ssize_t n = ::read(fd_, &ev, sizeof(ev));
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue;
Drop(std::string("read(): ") + std::strerror(errno));
next_try = clock_->Steady() + reopen_period;
continue;
}
if (n != static_cast<ssize_t>(sizeof(ev))) continue;
// Bo co JS_EVENT_INIT nhung VAN ap gia tri: cac event do la trang thai
// hien tai cua thiet bi luc vua mo, khong phai rac.
const uint8_t type = ev.type & ~JS_EVENT_INIT;
std::lock_guard<std::mutex> lk(mu_);
if (type == JS_EVENT_AXIS) {
if (ev.number < state_.axes.size()) {
state_.axes[ev.number] =
static_cast<float>(NormalizeJoydevAxis(ev.value));
}
} else if (type == JS_EVENT_BUTTON) {
if (ev.number < state_.buttons.size()) {
state_.buttons[ev.number] = ev.value ? 1 : 0;
}
}
}
}
GamepadState GamepadReader::Snapshot() const {
std::lock_guard<std::mutex> lk(mu_);
return state_;
}
std::string GamepadReader::DeviceInfo() const {
std::lock_guard<std::mutex> lk(mu_);
return info_;
}
} // namespace vslam

View File

@@ -33,6 +33,7 @@
#include <string> #include <string>
#include "lidar_core/lakibeam_driver.hpp" #include "lidar_core/lakibeam_driver.hpp"
#include "lidar_core/scan_filter.hpp"
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/driver_config.h" #include "vslam/driver_config.h"
@@ -86,6 +87,45 @@ class LakiBeamWrapper : public LidarInterface {
// biet cho nao cat no. // biet cho nao cat no.
lc.crop_fov = false; lc.crop_fov = false;
// Bon bo loc chay TREN scan tho, truoc khi doi sang kieu cua vslam.
//
// Chung xu ly loai rac ma ScanSanitizer khong bat duoc: ScanSanitizer chi
// cat QUAT CO DINH, con tia keo dai sau cot chong / tan xa yeu / cum diem
// don le thi khong nam gon trong quat nao.
//
// Box filter cung la thu thay the dung dan cho `sector_masks`: LiDAR nam
// o TAM robot nen vung bi khung gan che khong con la mot quat goc ma la
// mot vung hinh hop quanh goc toa do.
{
lidar_core::ScanFilterConfig fc;
const LidarFilterConfig& f = cfg_.filter;
fc.shadow_filter_enabled = f.shadow_enabled;
fc.shadow_min_angle_deg = f.shadow_min_angle_deg;
fc.shadow_window = f.shadow_window;
fc.shadow_min_range_diff = f.shadow_min_range_diff;
fc.shadow_max_range = f.shadow_max_range;
fc.shadow_clear_start = f.shadow_clear_start;
fc.shadow_clear_neighbors = f.shadow_clear_neighbors;
fc.intensity_filter_enabled = f.intensity_enabled;
fc.intensity_min = static_cast<float>(f.intensity_min);
fc.intensity_max = static_cast<float>(f.intensity_max);
fc.intensity_filter_max_range = static_cast<float>(f.intensity_max_range);
fc.isolated_filter_enabled = f.isolated_enabled;
fc.isolated_min_cluster_points = f.isolated_min_cluster_points;
fc.isolated_max_range_jump = f.isolated_max_range_jump;
fc.isolated_max_range = f.isolated_max_range;
fc.box_filter_enabled = f.box_enabled;
fc.box_min_x = f.box_min_x;
fc.box_max_x = f.box_max_x;
fc.box_min_y = f.box_min_y;
fc.box_max_y = f.box_max_y;
filter_ = std::make_unique<lidar_core::ScanFilter>(fc);
VSLAM_INFO("lidar: bo loc shadow=" << f.shadow_enabled
<< " intensity=" << f.intensity_enabled
<< " isolated=" << f.isolated_enabled
<< " box=" << f.box_enabled);
}
impl_ = std::make_unique<lidar_core::LakiBeamDriver>(lc); impl_ = std::make_unique<lidar_core::LakiBeamDriver>(lc);
impl_->setCallback([this](const lidar_core::LaserScan& s) { OnScan(s); }); impl_->setCallback([this](const lidar_core::LaserScan& s) { OnScan(s); });
@@ -110,6 +150,7 @@ class LakiBeamWrapper : public LidarInterface {
if (!impl_) return; if (!impl_) return;
impl_->stop(); impl_->stop();
impl_.reset(); impl_.reset();
filter_.reset();
} }
DriverStats Stats() const override { DriverStats Stats() const override {
@@ -118,7 +159,12 @@ class LakiBeamWrapper : public LidarInterface {
} }
private: private:
void OnScan(const lidar_core::LaserScan& in) { void OnScan(const lidar_core::LaserScan& raw) {
// Loc TRUOC khi doi kieu. ScanFilter thay diem rac bang +Inf, khong xoa
// phan tu, nen chi so tia va goc giu nguyen.
lidar_core::LaserScan in = raw;
if (filter_) filter_->filter(in);
auto out = std::make_shared<LaserScan>(); auto out = std::make_shared<LaserScan>();
out->header.seq = seq_++; out->header.seq = seq_++;
out->header.frame_id = cfg_.frame_id; out->header.frame_id = cfg_.frame_id;
@@ -218,6 +264,7 @@ class LakiBeamWrapper : public LidarInterface {
ClockPtr clock_; ClockPtr clock_;
ScanCallback cb_; ScanCallback cb_;
std::unique_ptr<lidar_core::LakiBeamDriver> impl_; std::unique_ptr<lidar_core::LakiBeamDriver> impl_;
std::unique_ptr<lidar_core::ScanFilter> filter_;
uint32_t seq_ = 0; uint32_t seq_ = 0;
mutable std::mutex mu_; mutable std::mutex mu_;

View File

@@ -1,43 +1,44 @@
// Cau noi toi MCU: IMU qua UART. // Cau noi toi MCU: IMU qua UART.
// //
// ================== KHONG KHOP DAC TA, VA VI SAO VAN VIET ================== // (Cach thu ba -- WT61PC noi THANG UART, khong ESP32 -- nam o wt61pc_bridge.cc;
// mcu_protocol.h la DAC TA ma firmware phai khop: // CreateMcuBridge() o cuoi file chon theo mcu.protocol.)
// I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az> //
// Firmware dang chay (base_kit/src/hardware/IMU_uart -- ESP32-S3 + DFRobot // ================== HAI NHANH, CHON BANG mcu.expect_timestamps ==================
// WT61PC) KHONG phat theo do. No phat text ba dong roi rac, tab/space: //
// `true` -- firmware trong firmware/imu_uart/ cua repo nay. Phat theo dung
// mcu_protocol.h:
// I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az> rad/s, m/s^2
// `micros` sinh TREN MCU ngay khi khung gyro qua checksum, va ClockSync anh xa
// dong ho MCU sang dong ho host. Jitter cua USB va cua scheduler bi phep fit
// loai bo thay vi doi thang vao stamp.
//
// `false` -- firmware cu (base_kit/src/hardware/IMU_uart). Phat text ba dong:
// Acc 0.05 -0.10 9.82 <- m/s^2 // Acc 0.05 -0.10 9.82 <- m/s^2
// Gyro 0.00 0.00 0.00 <- DO/s, khong phai rad/s // Gyro 0.00 0.00 0.00 <- DO/s, khong phai rad/s
// Angle -0.55 -0.34 -176.61 <- do // Angle -0.55 -0.34 -176.61 <- do
// Khong co dau thoi gian nen stamp lay luc HOST doc duoc dong, mang theo moi
// do tre cua USB-CDC va scheduler. Do duoc tren robot nay: 80 ms.
// //
// Driver nay doc DUNG cai firmware dang phat, va danh dau ro moi cho phai // Giu ca hai de con lui lai duoc khi firmware chua kip flash.
// chap nhan vi the. Viet theo dac ta roi cho firmware doi thi khong ai chay
// duoc gi hom nay; viet theo thuc te roi im lang thi no thanh no ky thuat
// khong ai thay. Nen: chay duoc, va noi to cai gia phai tra.
// //
// ================== BA CAI GIA, THEO MUC NGHIEM TRONG ================== // ================== CAI GIA CON LAI, CA HAI NHANH ==================
// //
// 1. KHONG CO TIMESTAMP -> ClockSync khong chay duoc. // 1. DO TRE HANG SO ~80 ms, nam TRUOC diem MCU dong dau.
// Dac ta yeu cau `micros()` cua MCU de ClockSync fit tuyen tinh dong ho // WT61PC o che do 10 Hz loc/trung binh noi bo (~50 ms), roi day 2 khung
// MCU <-> host. Firmware khong phat gi ca, nen stamp o day la luc HOST // Acc+Gyro qua day 9600 baud (~23 ms). Dong dau som cach may cung khong
// DOC DUOC DONG -- da qua bo dem USB-CDC, qua scheduler, qua ca do tre gom // cuu duoc phan do. No la HANG SO nen `mcu.imu_lag_sec` tru duoc -- do
// dong cua chinh driver nay. Do tre do KHONG do duoc va KHONG bu duoc. // bang log `wheel_odom/lag`, xem sensors.yaml.
// Hau qua thuc te: moi phep dong bo IMU voi LiDAR/camera deu mang mot sai
// so khong biet do lon. `stamp_skew_ms` trong DriverStats se luon la 0 --
// khong phai vi dong bo tot, ma vi KHONG CO GI DE SO.
// //
// 2. GYRO LAM TRON 2 CHU SO. // 2. GYRO LAM TRON.
// Firmware in "0.00" nghia la do phan giai 0.01 do/s ~ 0.17 mrad/s. Doc // Nhanh cu: firmware in "%.2f" do/s = 0.01 do/s ~ 0.17 mrad/s.
// duoc tren thiet bi dung yen: gyro_z = 0.00 o MOI mau. EKF yaw se khong // Nhanh moi: "%.5f" rad/s, min hon nhieu, nhung cam bien van tu ve 0 khi
// thay chuyen dong cham hon nguong do. // nghi -- doc duoc gyro = 0.00000 o moi mau luc dung yen.
// //
// 3. KHONG CO BARO / SIEU AM / BUMPER. // 3. KHONG CO BARO / SIEU AM / BUMPER.
// Dac ta co ban ghi B, U, K. Firmware khong co cai nao. Cac callback // Dac ta co ban ghi B, U, K. Ca hai firmware deu khong phat cai nao. Cac
// tuong ung KHONG BAO GIO duoc goi -- xem ghi chu tai cho dang ky. // callback tuong ung KHONG BAO GIO duoc goi -- xem ghi chu tai cho dang ky.
// Dac biet nguy hiem voi bumper: lop safety cho rang mat bumper la mot // Dac biet nguy hiem voi bumper: lop safety cho rang mat bumper la mot
// duong doc lap, o day no khong ton tai. // duong doc lap, o day no khong ton tai.
//
// Duong sua dung la firmware phat theo mcu_protocol.h. Khi do xoa file nay
// va dung duong `I/B/E/U/K/P` da co san trong mcu_protocol.cc.
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
@@ -55,10 +56,12 @@
#include <vector> #include <vector>
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/clock_sync.h"
#include "vslam/driver_config.h" #include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/mcu_protocol.h"
namespace vslam { namespace vslam {
namespace { namespace {
@@ -158,11 +161,22 @@ class McuBridge : public McuInterface {
} }
VSLAM_INFO("mcu: mo " << cfg_.port << " @" << cfg_.baud); VSLAM_INFO("mcu: mo " << cfg_.port << " @" << cfg_.baud);
if (!cfg_.expect_timestamps) { if (cfg_.expect_timestamps) {
VSLAM_INFO("mcu: doc ban ghi co dau thoi gian theo mcu_protocol.h. "
"ClockSync se anh xa dong ho MCU sang dong ho host; "
"imu_lag_sec = " << cfg_.imu_lag_sec * 1000.0 << " ms bu phan "
"hang so con lai (thoi gian truyen khung tren day cam bien).");
} else if (cfg_.imu_lag_sec > 0.0) {
VSLAM_INFO("mcu: firmware khong phat timestamp -- stamp lay tu dong ho "
"HOST, da tru bu imu_lag_sec = "
<< cfg_.imu_lag_sec * 1000.0
<< " ms. Kiem lai bang log `wheel_odom/lag`: phai bao ~0 ms.");
} else {
VSLAM_WARN( VSLAM_WARN(
"mcu: firmware khong phat timestamp -- stamp lay tu dong ho HOST luc " "mcu: firmware khong phat timestamp -- stamp lay tu dong ho HOST luc "
"doc duoc dong. Moi phep dong bo IMU voi LiDAR/camera mang mot do " "doc duoc dong, va imu_lag_sec = 0 nen KHONG bu gi. Moi phep dong bo "
"tre khong do duoc. Xem mcu_bridge.cc, muc 1."); "IMU voi LiDAR/camera mang mot do tre chua do. Chay lai co vao/ra cua "
"roi doc log `wheel_odom/lag`. Xem mcu_bridge.cc, muc 1.");
} }
running_ = true; running_ = true;
@@ -218,6 +232,158 @@ class McuBridge : public McuInterface {
void ProcessLine(const std::string& line) { void ProcessLine(const std::string& line) {
if (line.empty()) return; if (line.empty()) return;
// ⚠️ Bo dong DAU TIEN sau khi mo cong.
//
// Thiet bi dang phat lien tuc, nen `open()` gan nhu luon roi vao GIUA mot
// dong. Ky tu '\n' dau tien ta gap la ket thuc cua mot dong CUT.
//
// Dong cut van parse duoc, va do moi la van de: "I,117592345,..." bi cat
// dau thanh "I,5678,..." thi `micros` be di hang tram giay ma moi truong
// deu hop le. Da do tren robot: mau dau tien cho buoc 117.587 s -- dung
// bang tuoi cua ESP32 luc do.
if (!first_line_dropped_) {
first_line_dropped_ = true;
++unparsed_;
return;
}
if (cfg_.expect_timestamps) {
ProcessRecordLine(line);
return;
}
ProcessLegacyLine(line);
}
// Nhanh MOI: firmware phat theo mcu_protocol.h, co `micros()` cua chinh MCU.
//
// Khac biet that so voi nhanh cu KHONG phai o dinh dang ma o DONG HO. Nhanh
// cu dong dau bang dong ho host luc doc duoc dong, nen moi do tre cua UART,
// USB va scheduler deu chui vao stamp ma khong ai do duoc -- da do tren robot
// nay: 80 ms. O day `micros` sinh ra TREN MCU ngay khi nhan xong khung gyro,
// va ClockSync anh xa dong ho MCU sang dong ho host bang fit tuyen tinh, nen
// jitter cua duong truyen bi fit loai bo thay vi doi thang vao stamp.
void ProcessRecordLine(const std::string& line) {
const double t_recv = clock_->Now().toSec();
McuRecord rec;
if (!ParseMcuLine(line, &rec)) {
// Dong hong KHONG duoc coi la du lieu 0 -- dac ta noi ro. Firmware con
// in banner luc khoi dong nen vai dong dau khong doc duoc la binh thuong.
++unparsed_;
return;
}
// PHAI goi theo dung thu tu ban tin den: `micros` la uint32, tran moi 71.58
// phut, va McuTimeUnwrapper cong phan tran dua tren mau truoc do.
const double mcu_s = unwrap_.UnwrapSeconds(rec.micros);
// Chua co ping/pong nen khong do duoc RTT: dua t_send = t_recv. Hau qua la
// `offset` lech dung do tre MOT CHIEU cua USB Serial/JTAG (co ms), con
// `skew` va viec khu jitter thi khong anh huong -- chung den tu fit tuyen
// tinh tren nhieu mau. Phan lech hang so do gop chung vao `imu_lag_sec`,
// vay la mot nut duy nhat, do duoc, thay vi hai nut chong nhau.
// ⚠️ Loc mau truoc khi nap vao phep fit.
//
// Dong text KHONG co checksum, nen mot byte hong lam `micros` thanh mot so
// bat ky ma van parse duoc. Va mot mau rac duy nhat du de pha ca phep fit:
// khi `skew` bi tu choi thi `offset = trung_binh_host - trung_binh_mcu`,
// nen mot mau lech X giay keo offset di X/16. Do tren robot: ClockSync cho
// thoi diem lech 77 giay -- ung voi mot mau sai ~1200 s.
//
// O 10 Hz thi buoc that la ~0.1 s. Cho toi 2 s de con chiu duoc cu vap cua
// USB hay scheduler, nhung khong hon: ngoai khoang do thi khong phan biet
// duoc "gap that" voi "byte hong", ma doan sai o day thi hong ca dong ho.
bool mcu_step_ok = true;
if (have_prev_mcu_) {
const double step = mcu_s - prev_mcu_s_;
mcu_step_ok = (step > 0.0 && step < 2.0);
if (!mcu_step_ok) {
++mcu_step_rejected_;
VSLAM_WARN_THROTTLE(10.0,
"mcu: buoc thoi gian MCU = " << step
<< " s, ngoai khoang [0, 2] -- dong co the bi hong byte (text "
"khong co checksum). Bo mau nay khoi ClockSync va dung dong ho "
"host cho no. Lan thu " << mcu_step_rejected_ << ".");
}
}
if (mcu_step_ok) {
sync_.Add(mcu_s, t_recv, t_recv);
}
// ⚠️ LUON cap nhat moc, ke ca khi bo mau.
//
// Ban truoc giu nguyen moc voi ly le "dung lay mau rac lam moc". Nghe hop
// ly, hau qua thi nguoc han: mot mau rac lam moc KET vinh vien, va moi mau
// that sau do deu co buoc lon nen deu bi bo. Do duoc tren robot: bo dem
// nhay 1 -> 101 -> 201 moi 10 giay, tuc 100% mau bi loai, va buoc bao cao
// lon dan dung bang thoi gian thuc (117 -> 127 -> 137 s). ClockSync khong
// nhan duoc mau nao suot ca phien.
//
// Luon tien moc thi mot cu vap ton dung HAI mau: cu vap, roi cu nhay nguoc
// ve nhip that. Sau do tu khop lai.
prev_mcu_s_ = mcu_s;
have_prev_mcu_ = true;
double host_s = 0.0;
UnixTime stamp;
// ⚠️ KIEM tinh hop ly truoc khi tin. `ready()` cua ClockSync bat ngay khi
// co 2 mau, va fit tu 2 diem cach nhau mot chu ky IMU thi ra bat cu gi.
//
// Do duoc tren robot: lan chuyen tu dong ho host sang dong ho MCU lam dau
// thoi gian nhay LUI 29.1 GIAY. Do khong phai sai so, do la vo nghia -- mot
// mau vua den thi thoi diem do cua no phai cach `t_recv` dung do tre mot
// chieu cua duong truyen, tuc vai mili giay. Lech 29 s thi phep fit dang
// noi ve mot vu tru khac.
//
// 1 giay la nguong RAT rong so voi vai ms that su, co y: no chi de bat cai
// vo nghia, khong de tinh chinh.
const bool sane = mcu_step_ok && sync_.ToHost(mcu_s, &host_s) &&
std::fabs(host_s - t_recv) < 1.0;
if (!sane && sync_.ready()) {
++sync_rejected_;
VSLAM_WARN_THROTTLE(10.0,
"mcu: ClockSync cho thoi diem lech " << (host_s - t_recv)
<< " s so voi luc nhan duoc dong -- bo qua, dung dong ho host. "
"Lan thu " << sync_rejected_ << ".");
}
if (sane) {
stamp = UnixTime::fromSec(host_s);
// In DINH KY chu khong in mot lan.
//
// `ready()` bat ngay khi co 2 mau -- o 10 Hz la 68 ms sau khi mo cong,
// va fit tu 2 diem cach nhau 100 ms thi vo nghia. In mot lan tai thoi
// diem do la in dung con so te nhat roi im luon. Da mac loi do: log bao
// "skew 0 ppm" trong khi ClockSync dang tu choi moi ket qua fit va giu
// skew = 1.0 -- hai trang thai do nhin y het nhau tu ben ngoai.
VSLAM_INFO_THROTTLE(30.0, "mcu: ClockSync skew " << sync_.skew_ppm()
<< " ppm, stamp lay tu dong ho MCU.");
} else {
// Chua du mau de fit. Dung dong ho host nhu nhanh cu -- kem hon nhung
// van chay duoc, va chi keo dai vai giay dau.
stamp = clock_->Now();
VSLAM_INFO_THROTTLE(5.0, "mcu: ClockSync chua du mau, tam dung dong ho "
"host de dong dau.");
}
if (rec.type != McuRecordType::kImu) {
// B / E / U / K chua co nguoi dung o day. Dem de thay khi firmware bat
// dau phat chung, chu khong im lang bo di.
++unhandled_records_;
return;
}
// ⚠️ KHONG doi don vi o day. mcu_protocol.h dac ta ban ghi I la rad/s va
// m/s^2 SAN ROI; nhanh cu doi do/s -> rad/s vi firmware cu in do/s. Doi
// hai lan thi gyro nho di 57 lan va odometry van "chay binh thuong".
gx_ = rec.gx; gy_ = rec.gy; gz_ = rec.gz;
ax_ = rec.ax; ay_ = rec.ay; az_ = rec.az;
// Ban ghi I khong mang orientation. Khong ai doc imu.orientation trong
// libs/ va app/ (da kiem), nen de quaternion don vi.
roll_ = pitch_ = yaw_ = 0.0;
Publish(stamp - Duration::fromSec(cfg_.imu_lag_sec));
}
void ProcessLegacyLine(const std::string& line) {
std::istringstream iss(line); std::istringstream iss(line);
std::string type; std::string type;
double x = 0.0, y = 0.0, z = 0.0; double x = 0.0, y = 0.0, z = 0.0;
@@ -244,16 +410,20 @@ class McuBridge : public McuInterface {
} }
if (have_acc_ && have_gyro_ && have_angle_) { if (have_acc_ && have_gyro_ && have_angle_) {
Publish(); // ⚠️ Dong ho HOST, khong phai dong ho thiet bi -- xem dau file, muc 1.
// Tru do tre da do duoc: mau nay do robot SOM hon luc doc duoc no.
Publish(clock_->Now() - Duration::fromSec(cfg_.imu_lag_sec));
have_acc_ = have_gyro_ = have_angle_ = false; have_acc_ = have_gyro_ = have_angle_ = false;
} }
} }
void Publish() { void Publish(UnixTime stamp) {
auto imu = std::make_shared<Imu>(); auto imu = std::make_shared<Imu>();
imu->header.seq = seq_++; imu->header.seq = seq_++;
// ⚠️ Dong ho HOST, khong phai dong ho thiet bi -- xem dau file, muc 1. // Nguoi goi da tru `imu_lag_sec`. Hai nhanh dua stamp den tu hai nguon
imu->header.stamp = clock_->Now(); // khac han nhau -- dong ho host, hay dong ho MCU qua ClockSync -- nen viec
// chon nguon nam o cho goi, khong nam o day.
imu->header.stamp = stamp;
imu->header.frame_id = cfg_.imu_frame_id; imu->header.frame_id = cfg_.imu_frame_id;
imu->angular_velocity.x = gx_; imu->angular_velocity.x = gx_;
@@ -286,9 +456,14 @@ class McuBridge : public McuInterface {
if (dt > 0.0) stats_.hz = 1.0 / dt; if (dt > 0.0) stats_.hz = 1.0 / dt;
} }
last_pub_ = now; last_pub_ = now;
// KHONG co gi de so -> de 0. Xem dau file, muc 1. if (cfg_.expect_timestamps && sync_.ready()) {
stats_.stamp_skew_ms = 0.0; stats_.clock_skew_ppm = sync_.skew_ppm();
stats_.clock_skew_ppm = 0.0; stats_.stamp_skew_ms = (clock_->Now() - now).toSec() * 1e3;
} else {
// KHONG co gi de so -> de 0. Xem dau file, muc 1.
stats_.stamp_skew_ms = 0.0;
stats_.clock_skew_ppm = 0.0;
}
} }
if (imu_cb_) imu_cb_(imu); if (imu_cb_) imu_cb_(imu);
@@ -321,6 +496,20 @@ class McuBridge : public McuInterface {
double roll_ = 0.0, pitch_ = 0.0, yaw_ = 0.0; double roll_ = 0.0, pitch_ = 0.0, yaw_ = 0.0;
bool have_acc_ = false, have_gyro_ = false, have_angle_ = false; bool have_acc_ = false, have_gyro_ = false, have_angle_ = false;
uint64_t unparsed_ = 0; uint64_t unparsed_ = 0;
// Chi dung o nhanh expect_timestamps. Ca hai deu chi cham tu luong doc, nen
// khong can khoa.
McuTimeUnwrapper unwrap_;
ClockSync sync_;
uint64_t sync_rejected_ = 0; // lan ClockSync cho ket qua vo nghia
// Loc mau truoc khi nap vao ClockSync. Dong text khong co checksum nen mot
// byte hong lam `micros` thanh so bat ky ma van parse duoc.
double prev_mcu_s_ = 0.0;
bool have_prev_mcu_ = false;
uint64_t mcu_step_rejected_ = 0;
bool first_line_dropped_ = false; // dong dau sau open() luon la dong cut
uint64_t unhandled_records_ = 0; // B / E / U / K: chua co nguoi dung
uint32_t seq_ = 0; uint32_t seq_ = 0;
UnixTime last_pub_; UnixTime last_pub_;
@@ -330,8 +519,15 @@ class McuBridge : public McuInterface {
} // namespace } // namespace
// Dinh nghia o wt61pc_bridge.cc.
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
ClockPtr clock);
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg, std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg,
ClockPtr clock) { ClockPtr clock) {
if (cfg.protocol == McuProtocol::kWt61pc) {
return CreateWt61pcBridge(cfg, std::move(clock));
}
return std::make_unique<McuBridge>(cfg, std::move(clock)); return std::make_unique<McuBridge>(cfg, std::move(clock));
} }

View File

@@ -37,6 +37,7 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/driver_config.h" #include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
@@ -323,22 +324,30 @@ class RealSenseDriver : public CameraInterface {
depth_img->data = static_cast<const uint8_t*>(depth.get_data()); depth_img->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else { } else {
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), &depth_buf_, // MOI khung mot bo dem RIENG tu pool, anh giu no qua keep_alive.
//
// ⚠️ Truoc day la MOT bo dem dung chung, "hop le toi lan goi Loop()
// sau" -- du cho perception chay INLINE trong callback, nhung SlamLoop
// giu khung depth/IR moi nhat qua Rtabmap::process (100-600 ms) tren
// luong KHAC, va `BuildSensorData` boc cv::Mat quanh bo dem ma khong
// copy. Khung sau (33 ms) ghi de giua chung: anh luu vao DB co the la
// nua khung nay nua khung kia.
auto buf = buf_pool_->Acquire();
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), buf.get(),
&depth_img->width, &depth_img->height); &depth_img->width, &depth_img->height);
depth_img->step = depth_img->width * 2; depth_img->step = depth_img->width * 2;
depth_img->data = depth_buf_.data(); depth_img->data = buf->data();
// Bo dem cua ta: hop le toi lan goi Loop() sau. Consumer chay INLINE depth_img->keep_alive = buf;
// trong callback (xem PerceptionPipeline) nen dieu do la du.
} }
out.depth = depth_img; out.depth = depth_img;
if (cfg_.enable_infra1) { if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1); rs2::video_frame ir = fs.get_infrared_frame(1);
if (ir) out.infra1 = WrapIr(ir, out.header, keep, &ir1_buf_); if (ir) out.infra1 = WrapIr(ir, out.header, keep);
} }
if (cfg_.enable_infra2) { if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2); rs2::video_frame ir = fs.get_infrared_frame(2);
if (ir) out.infra2 = WrapIr(ir, out.header, keep, &ir2_buf_); if (ir) out.infra2 = WrapIr(ir, out.header, keep);
} }
out.depth_info = info_; out.depth_info = info_;
@@ -354,8 +363,7 @@ class RealSenseDriver : public CameraInterface {
} }
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr, ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep, const std::shared_ptr<FrameKeepAlive>& keep) {
std::vector<uint8_t>* buf) {
auto img = std::make_shared<Image>(); auto img = std::make_shared<Image>();
img->header = hdr; img->header = hdr;
img->format = PixelFormat::kMono8; img->format = PixelFormat::kMono8;
@@ -367,10 +375,13 @@ class RealSenseDriver : public CameraInterface {
img->data = static_cast<const uint8_t*>(ir.get_data()); img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep; img->keep_alive = keep;
} else { } else {
// Bo dem rieng moi khung, nhu depth o tren.
auto buf = buf_pool_->Acquire();
Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h, Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h,
static_cast<int>(cfg_.decimate), buf, &img->width, &img->height); static_cast<int>(cfg_.decimate), buf.get(), &img->width, &img->height);
img->step = img->width; img->step = img->width;
img->data = buf->data(); img->data = buf->data();
img->keep_alive = buf;
} }
return img; return img;
} }
@@ -384,7 +395,10 @@ class RealSenseDriver : public CameraInterface {
float depth_scale_ = 0.001f; float depth_scale_ = 0.001f;
CameraInfo info_; CameraInfo info_;
std::vector<uint8_t> depth_buf_, ir1_buf_, ir2_buf_; // Bo dem anh da decimate (depth + IR). Moi khung lay bo dem rieng va tra
// ve pool khi KHONG CON AI giu anh -- 0 malloc o trang thai on dinh.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> buf_pool_ =
BufferPool<std::vector<uint8_t>>::Create(12);
std::atomic<bool> running_{false}; std::atomic<bool> running_{false};
std::thread thread_; std::thread thread_;

View File

@@ -121,6 +121,7 @@ const char* VsrStreamName(VsrStream s) {
case VsrStream::kEvent: return "event"; case VsrStream::kEvent: return "event";
case VsrStream::kUltrasonic: return "ultrasonic"; case VsrStream::kUltrasonic: return "ultrasonic";
case VsrStream::kBumper: return "bumper"; case VsrStream::kBumper: return "bumper";
case VsrStream::kGroundTruth: return "ground_truth";
} }
return "?"; return "?";
} }
@@ -225,6 +226,15 @@ bool DecodeBumperPayload(const std::string& buf, uint32_t* mask) {
return r.ok; return r.ok;
} }
void EncodeGroundTruthPayload(const double pose6[6], std::string* o) {
for (int i = 0; i < 6; ++i) PutF64(o, pose6[i]);
}
bool DecodeGroundTruthPayload(const std::string& buf, double pose6[6]) {
Reader r(buf);
for (int i = 0; i < 6; ++i) pose6[i] = r.F64();
return r.ok;
}
void EncodeEncoderPayload(double l, double rr, std::string* o) { void EncodeEncoderPayload(double l, double rr, std::string* o) {
PutF64(o, l); PutF64(o, l);
PutF64(o, rr); PutF64(o, rr);

View File

@@ -7,6 +7,7 @@
#include <mutex> #include <mutex>
#include <vector> #include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/record_io.h" #include "vslam/record_io.h"
#include "vslam/scan_sanitizer.h" #include "vslam/scan_sanitizer.h"
@@ -163,9 +164,20 @@ struct ReplaySource::Impl {
// roi phat mot lan khi thay chunk depth ke tiep hoac khi het file. // roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
CameraFrame pending_frame; CameraFrame pending_frame;
bool have_pending = false; bool have_pending = false;
std::vector<uint8_t> depth_storage; // Kho nho cho anh giai ma. MOI anh mot kho rieng, giu qua keep_alive:
std::vector<uint8_t> infra1_storage; // SlamLoop giu khung moi nhat qua Rtabmap::process tren luong khac, va ba
std::vector<uint8_t> infra2_storage; // kho dung chung (nhu truoc day) bi khung sau ghi de giua chung.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> img_pool =
BufferPool<std::vector<uint8_t>>::Create(12);
// Giai ma mot anh vao kho rieng. null neu payload hong.
ImagePtr DecodeImage(const std::string& payload) {
auto img = std::make_shared<Image>();
auto storage = img_pool->Acquire();
if (!DecodeImagePayload(payload, img.get(), storage.get())) return nullptr;
img->keep_alive = storage;
return img;
}
CameraInfo last_info; CameraInfo last_info;
bool have_info = false; bool have_info = false;
@@ -360,22 +372,22 @@ void ReplaySource::Run() {
case VsrStream::kDepth: { case VsrStream::kDepth: {
// Chunk depth moi = khung truoc da day du -> phat khung truoc. // Chunk depth moi = khung truoc da day du -> phat khung truoc.
impl_->FlushCameraFrame(); impl_->FlushCameraFrame();
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break; if (!img) break;
impl_->pending_frame.header = img->header; impl_->pending_frame.header = img->header;
impl_->pending_frame.depth = img; impl_->pending_frame.depth = img;
impl_->have_pending = true; impl_->have_pending = true;
break; break;
} }
case VsrStream::kInfra1: { case VsrStream::kInfra1: {
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break; if (!img) break;
impl_->pending_frame.infra1 = img; impl_->pending_frame.infra1 = img;
break; break;
} }
case VsrStream::kInfra2: { case VsrStream::kInfra2: {
auto img = std::make_shared<Image>(); ImagePtr img = impl_->DecodeImage(payload);
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break; if (!img) break;
impl_->pending_frame.infra2 = img; impl_->pending_frame.infra2 = img;
break; break;
} }
@@ -385,6 +397,10 @@ void ReplaySource::Run() {
} }
break; break;
} }
case VsrStream::kGroundTruth:
// Su that tu bo mo phong: chi de cham diem offline. KHONG dua vao
// duong ong -- khong stage nao duoc doc no.
break;
case VsrStream::kCmdVel: case VsrStream::kCmdVel:
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra. // Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra.
// Replay khong tu dong ap chung: viec do do wiring quyet dinh. // Replay khong tu dong ap chung: viec do do wiring quyet dinh.

View File

@@ -0,0 +1,426 @@
// Cau noi toi IMU WT61PC noi THANG vao UART (cap USB-FTDI), khong qua ESP32.
//
// Chon bang `mcu.protocol: wt61pc` trong sensors.yaml. CreateMcuBridge() trong
// mcu_bridge.cc chuyen sang day; cach cu (ESP32 + USB-CDC) van o do.
//
// ================== KHAC McuBridge O DAU ==================
//
// 1. KHONG CO ClockSync.
// ESP32 dong dau bang micros() cua chinh no roi ClockSync anh xa sang dong
// ho host. O day khong co MCU, nen stamp lay tu dong ho HOST luc nhan xong
// khung gyro. De jitter khong chui thang vao stamp: cap USB-FTDI gom byte
// theo latency_timer (mac dinh 16 ms), nen mot lan read() co the mang nhieu
// khung. Driver bat ASYNC_LOW_LATENCY (ftdi_sio -> 1 ms) va luat udev
// configuration_files/udev/99-imu.rules dat san 1 ms: o 200 Hz (5 ms/mau)
// 16 ms la ~3 mau mot lan doc. Log luc mo cong bao gia tri that.
// Thoi diem cua mot khung duoc suy NGUOC tu luc read() tra ve, tru
// di thoi gian truyen cua cac byte toi sau no trong cung lan doc.
// Phan tre con lai (loc noi bo cua cam bien + thoi gian truyen khung) la
// HANG SO, tru bang `mcu.imu_lag_sec`. Con so 0.07 do duoc tren duong ESP32;
// sau khi doi sang UART thang PHAI do lai (log `wheel_odom/lag`).
//
// 2. PHAT NGAY KHI CO KHUNG GYRO, khong doi khung Angle.
// Mot chu ky la Acc -> Gyro -> Angle. Doi Angle them ~11.5 ms o 9600 baud,
// ma khong ai doc imu.orientation trong libs/ va app/ (firmware ESP32 cung
// lam vay, xem firmware/imu_uart/main/main.c). Gyro khong co Acc di truoc
// trong cung chu ky thi bo mau, khong ghep voi gia toc cu.
//
// 3. DOC QUYEN CONG (TIOCEXCL).
// Hai chuong trinh cung doc mot tty thi chia nhau luong byte: da gap tren
// robot nay khi imu_ros_node cua motor_control doc chung cong, IMU chi con
// mot nua so mau (chu ky 0.2 s thay vi 0.1 s) va khong bao loi nao. Co
// TIOCEXCL thi chuong trinh thu hai (khong phai root) mo cong se loi EBUSY
// ngay. Luu y: neu chuong trinh kia mo TRUOC thi khong chan duoc -- Open()
// van thanh cong; kiem bang `sudo fuser -v /dev/imu`.
//
// 4. KHONG IM LANG.
// Khong co khung hop le nao trong `no_data_warn_sec` -> WARN kem goi y. Cap
// bi rut -> read() loi, driver tu mo lai moi giay thay vi ket vinh vien.
//
// 5. KHONG CO BARO / SIEU AM / BUMPER. Ba callback do khong bao gio duoc goi,
// giong mcu_bridge.cc muc 3.
#include <errno.h>
#include <fcntl.h>
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/wt61pc_protocol.h"
namespace vslam {
namespace {
speed_t BaudConstant(uint32_t baud) {
switch (baud) {
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 921600: return B921600;
default: return 0;
}
}
// Cap FTDI gom byte latency_timer ms roi moi day len host (mac dinh 16 ms; o
// 200 Hz la ~3 mau mot lan). ASYNC_LOW_LATENCY -> ftdi_sio dat 1 ms. Cong khong
// phai FTDI (pty khi test) thi ioctl loi -> bo qua.
void SetLowLatency(int fd) {
serial_struct ss{};
if (::ioctl(fd, TIOCGSERIAL, &ss) != 0) return;
ss.flags |= ASYNC_LOW_LATENCY;
::ioctl(fd, TIOCSSERIAL, &ss);
}
// latency_timer (ms) cua cap FTDI sau `port` (/dev/imu -> ttyUSB0); -1 = khong
// doc duoc (khong phai FTDI, hoac khong co sysfs).
int FtdiLatencyMs(const std::string& port) {
char real[PATH_MAX];
if (::realpath(port.c_str(), real) == nullptr) return -1;
const char* name = std::strrchr(real, '/');
std::ifstream f(std::string("/sys/class/tty/") + (name != nullptr ? name + 1 : real) +
"/device/latency_timer");
int ms = -1;
return (f >> ms) ? ms : -1;
}
class Wt61pcBridge : public McuInterface {
public:
Wt61pcBridge(const McuConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~Wt61pcBridge() override { Close(); }
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
// WT61PC chi co IMU. Dac biet bumper: lop safety coi mat bumper la mot duong
// doc lap, o day no khong ton tai.
void SetBaroCallback(BaroCallback) override {}
void SetUltrasonicCallback(UltrasonicCallback) override {}
void SetBumperCallback(BumperCallback) override {}
StatusResponse Open() override {
if (running_) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"imu: da mo roi");
}
if (!clock_) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"imu: thieu clock");
}
if (BaudConstant(cfg_.baud) == 0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"imu: baud " + std::to_string(cfg_.baud) + " khong ho tro");
}
byte_s_ = 10.0 / static_cast<double>(cfg_.baud); // 1 start + 8 data + 1 stop
const StatusResponse st = OpenPort();
if (!st.ok()) return st;
VSLAM_INFO("imu: WT61PC o " << cfg_.port << " @" << cfg_.baud
<< ", doc quyen cong. Stamp lay tu dong ho HOST luc nhan xong "
"khung gyro, tru imu_lag_sec = " << cfg_.imu_lag_sec * 1000.0
<< " ms -- do lai bang log `wheel_odom/lag` sau khi doi nguon IMU.");
const int lat = FtdiLatencyMs(cfg_.port);
if (lat > 2) {
VSLAM_WARN("imu: latency_timer cap FTDI = " << lat << " ms -- moi lan doc gom nhieu "
"mau, stamp IMU giat. Cai configuration_files/udev/99-imu.rules (1 ms).");
} else if (lat >= 0) {
VSLAM_INFO("imu: latency_timer cap FTDI = " << lat << " ms");
}
if (cfg_.baud <= 9600) {
VSLAM_INFO("imu: 9600 baud chi du ~29 Hz (cam bien mac dinh 10 Hz). "
"wheel_odom bo gyro khi IMU cham hon encoder -- xem muc mcu "
"trong sensors.yaml.");
}
last_frame_ = std::chrono::steady_clock::now();
running_ = true;
thread_ = std::thread([this] { ReadLoop(); });
return StatusResponse::Ok();
}
void Close() override {
running_ = false;
// read() tra ve sau nhieu nhat 0.1 s (VTIME) nen join nhanh; dong fd SAU
// khi luong doc da thoat, khong dong duoi chan no.
if (thread_.joinable()) thread_.join();
CloseFd();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(stats_mu_);
return stats_;
}
private:
StatusResponse OpenPort() {
const int fd = ::open(cfg_.port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0) {
const int e = errno;
std::string hint;
if (e == EACCES) {
hint = " -- thieu quyen? kiem luat udev (MODE/GROUP) hoac them user vao "
"nhom dialout";
} else if (e == ENOENT) {
hint = " -- khong thay thiet bi: cap USB-UART da cam chua? luat udev "
"da cai chua (ls -l " + cfg_.port + ")?";
} else if (e == EBUSY) {
hint = " -- co chuong trinh khac dang giu cong (imu_ros_node cua "
"motor_control?): sudo fuser -v " + cfg_.port;
}
return StatusResponse::Error(
StatusCode::kUnavailable,
"imu: mo " + cfg_.port + " that bai: " + std::strerror(e) + hint);
}
termios tty{};
if (::tcgetattr(fd, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcgetattr that bai: " + err);
}
const speed_t speed = BaudConstant(cfg_.baud);
::cfsetospeed(&tty, speed);
::cfsetispeed(&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8 bit
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD); // khong parity
tty.c_cflag &= ~CSTOPB; // 1 stop bit
tty.c_cflag &= ~CRTSCTS; // khong flow control
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_oflag &= ~OPOST;
// VMIN=0 + VTIME=1: read() tra ve ngay khi co byte, hoac sau 0.1 s neu khong
// co. Du ngan de Close() va bo dem im lang chay deu.
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 1;
if (::tcsetattr(fd, TCSANOW, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcsetattr that bai: " + err);
}
if (::ioctl(fd, TIOCEXCL) != 0) {
VSLAM_WARN("imu: khong khoa duoc quyen doc cong " << cfg_.port << " ("
<< std::strerror(errno) << ") -- chuong trinh khac mo cong "
"sau se chia nhau luong byte.");
}
SetLowLatency(fd);
::tcflush(fd, TCIOFLUSH); // bo byte cu, tranh bat dau giua mot khung
fd_ = fd;
return StatusResponse::Ok();
}
void CloseFd() {
const int fd = fd_.exchange(-1);
if (fd >= 0) ::close(fd);
}
void ReadLoop() {
uint8_t buf[512];
Wt61pcFrame frame;
while (running_) {
const ssize_t n = ::read(fd_, buf, sizeof(buf));
const UnixTime t_read = clock_->Now(); // ngay sau khi read() tra ve
if (n < 0) {
if (!running_) break;
if (errno == EAGAIN || errno == EINTR) continue;
Fail(std::string("read() that bai: ") + std::strerror(errno) +
" -- cap bi rut? driver thu mo lai moi giay");
Reopen();
continue;
}
if (n > 0) {
bytes_ += static_cast<uint64_t>(n);
for (ssize_t i = 0; i < n; ++i) {
if (!parser_.Push(buf[i], &frame)) continue;
// Byte cuoi cua khung la byte thu i. (n - 1 - i) byte da toi SAU no
// trong cung lan doc, nen khung that ra som hon luc read() mot chut.
const UnixTime t_end =
t_read - Duration::fromSec(static_cast<double>(n - 1 - i) * byte_s_);
OnFrame(frame, t_end);
}
}
CheckSilence();
}
}
void OnFrame(const Wt61pcFrame& f, UnixTime t_end) {
last_frame_ = std::chrono::steady_clock::now();
switch (f.type) {
case Wt61pcType::kAccel:
ax_ = f.x; ay_ = f.y; az_ = f.z;
have_acc_ = true;
return;
case Wt61pcType::kAngle:
return; // khong dung, xem dau file muc 2
case Wt61pcType::kGyro:
break;
}
if (!have_acc_) {
++incomplete_; // mat khung gia toc cua chu ky nay
return;
}
have_acc_ = false;
Publish(f, t_end - Duration::fromSec(cfg_.imu_lag_sec));
}
void Publish(const Wt61pcFrame& gyro, UnixTime stamp) {
// Gom byte cua cap USB-FTDI co the khien thoi diem suy nguoc cua mot khung
// som hon khung truoc vai ms. Dau thoi gian khong duoc lui: wheel_odom chi
// chiu duoc lech thu tu nho.
if (have_pub_ && stamp < last_stamp_) {
stamp = last_stamp_;
++clamped_;
}
auto imu = std::make_shared<Imu>();
imu->header.seq = seq_++;
imu->header.stamp = stamp;
imu->header.frame_id = cfg_.imu_frame_id;
imu->angular_velocity.x = gyro.x;
imu->angular_velocity.y = gyro.y;
imu->angular_velocity.z = gyro.z;
imu->linear_acceleration.x = ax_;
imu->linear_acceleration.y = ay_;
imu->linear_acceleration.z = az_;
// Khong mang orientation (khung Angle khong duoc dung). [0] < 0 la quy uoc
// "khong co orientation", giong record_format.cc va sim_source.cc.
imu->orientation_covariance[0] = -1.0;
for (int i = 0; i < 3; ++i) {
imu->angular_velocity_covariance[i * 4] = cfg_.gyro_variance;
imu->linear_acceleration_covariance[i * 4] = cfg_.accel_variance;
}
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = true;
if (have_pub_) {
const double dt = (stamp - last_stamp_).toSec();
if (dt > 0.0) stats_.hz = 1.0 / dt;
}
// Khong co MCU de so dong ho -> hai so nay luon 0.
stats_.stamp_skew_ms = 0.0;
stats_.clock_skew_ppm = 0.0;
}
last_stamp_ = stamp;
have_pub_ = true;
if (imu_cb_) imu_cb_(imu);
}
// Goi sau moi lan read(), ke ca khi het thoi gian cho (n == 0).
void CheckSilence() {
const double quiet = std::chrono::duration<double>(
std::chrono::steady_clock::now() - last_frame_).count();
if (quiet < cfg_.no_data_warn_sec) return;
const std::string msg =
"khong co khung WT61PC hop le nao trong " + std::to_string(quiet) +
" s (nhan " + std::to_string(bytes_) + " byte, checksum sai " +
std::to_string(parser_.bad_checksum()) + ", byte bo " +
std::to_string(parser_.skipped_bytes()) + "). Kiem: day TX cua cam "
"bien -> RX cua cap USB-UART co long khong; cam bien co dang o baud "
"khac " + std::to_string(cfg_.baud) + " (co byte ma checksum sai "
"nhieu thi gan chac la sai baud); chuong trinh khac dang doc cong "
"(sudo fuser -v " + cfg_.port + ").";
{
std::lock_guard<std::mutex> lk(stats_mu_);
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
void Fail(const std::string& msg) {
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
// Cap bi rut roi cam lai: read() loi mai mai neu khong mo lai. Mo lai moi
// giay cho toi khi duoc hoac Close().
void Reopen() {
CloseFd();
parser_.Reset();
have_acc_ = false;
while (running_) {
for (int i = 0; i < 10 && running_; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (!running_) return;
const StatusResponse st = OpenPort();
if (st.ok()) {
VSLAM_INFO("imu: mo lai " << cfg_.port << " thanh cong");
last_frame_ = std::chrono::steady_clock::now();
return;
}
VSLAM_WARN_THROTTLE(5.0, st.message);
}
}
McuConfig cfg_;
ClockPtr clock_;
ImuCallback imu_cb_;
std::atomic<int> fd_{-1};
std::atomic<bool> running_{false};
std::thread thread_;
// Chi cham tu luong doc.
Wt61pcParser parser_;
double byte_s_ = 0.0;
uint64_t bytes_ = 0;
double ax_ = 0.0, ay_ = 0.0, az_ = 0.0;
bool have_acc_ = false;
uint64_t incomplete_ = 0; // gyro khong co acc di truoc trong chu ky
uint64_t clamped_ = 0; // stamp bi keo len de khong lui
uint32_t seq_ = 0;
UnixTime last_stamp_;
bool have_pub_ = false;
std::chrono::steady_clock::time_point last_frame_;
mutable std::mutex stats_mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
ClockPtr clock) {
return std::make_unique<Wt61pcBridge>(cfg, std::move(clock));
}
} // namespace vslam

View File

@@ -0,0 +1,100 @@
#include "vslam/wt61pc_protocol.h"
#include <cmath>
namespace vslam {
namespace {
constexpr double kWt61pcG = 9.80665;
constexpr double kDeg2Rad = M_PI / 180.0;
// Loai khung cua dong WitMotion nam trong 0x50..0x5A. 0x55 bi loai ra: no
// trung voi byte dau khung, nen "0x55 0x55" nghia la byte truoc la rac va byte
// nay moi la dau khung that.
bool IsFrameType(uint8_t b) {
return b >= 0x50 && b <= 0x5A && b != kWt61pcHeader;
}
double Int16LE(const uint8_t* p) {
return static_cast<double>(
static_cast<int16_t>(static_cast<uint16_t>(p[1]) << 8 | p[0]));
}
} // namespace
void Wt61pcParser::Reset() {
n_ = 0;
}
bool Wt61pcParser::Push(uint8_t byte, Wt61pcFrame* out) {
if (n_ == 0) {
if (byte == kWt61pcHeader) {
buf_[n_++] = byte;
} else {
++skipped_bytes_;
}
return false;
}
if (n_ == 1) {
if (IsFrameType(byte)) {
buf_[n_++] = byte;
} else {
++skipped_bytes_;
if (byte != kWt61pcHeader) n_ = 0; // 0x55 0x55: giu lai, byte nay la dau khung
}
return false;
}
buf_[n_++] = byte;
if (n_ < kWt61pcFrameBytes) return false;
uint8_t sum = 0;
for (size_t i = 0; i + 1 < kWt61pcFrameBytes; ++i) {
sum = static_cast<uint8_t>(sum + buf_[i]);
}
if (sum != buf_[kWt61pcFrameBytes - 1]) {
++bad_checksum_;
Resync();
return false;
}
const uint8_t type = buf_[1];
n_ = 0;
if (type != static_cast<uint8_t>(Wt61pcType::kAccel) &&
type != static_cast<uint8_t>(Wt61pcType::kGyro) &&
type != static_cast<uint8_t>(Wt61pcType::kAngle)) {
++other_frames_;
return false;
}
out->type = static_cast<Wt61pcType>(type);
double scale = 0.0;
switch (out->type) {
case Wt61pcType::kAccel: scale = 16.0 * kWt61pcG / 32768.0; break;
case Wt61pcType::kGyro: scale = 2000.0 * kDeg2Rad / 32768.0; break;
case Wt61pcType::kAngle: scale = 180.0 * kDeg2Rad / 32768.0; break;
}
out->x = Int16LE(buf_ + 2) * scale;
out->y = Int16LE(buf_ + 4) * scale;
out->z = Int16LE(buf_ + 6) * scale;
return true;
}
// Checksum sai co the la mat dong bo: dau khung that nam NGAY TRONG 10 byte sau
// dau gia. Bo ca 11 byte se nuot luon khung dung ngay sau, va o 10 Hz do la
// mat ca mot mau. Nen truot toi 0x55 ke tiep va nap lai phan con lai.
void Wt61pcParser::Resync() {
uint8_t keep[kWt61pcFrameBytes];
size_t m = 0;
size_t j = 1;
while (j < kWt61pcFrameBytes && buf_[j] != kWt61pcHeader) ++j;
skipped_bytes_ += j;
for (; j < kWt61pcFrameBytes; ++j) keep[m++] = buf_[j];
n_ = 0;
// Toi da 10 byte nen khong the ra mot khung moi (can 11), cung khong de quy
// vao Resync lan nua.
Wt61pcFrame unused;
for (size_t i = 0; i < m; ++i) Push(keep[i], &unused);
}
} // namespace vslam

View File

@@ -116,7 +116,7 @@ class ZlacWrapper : public BaseInterface {
"(systemctl status motor_control zlac_ros)" "(systemctl status motor_control zlac_ros)"
"\n - dcf_path: " + cfg_.dcf_path); "\n - dcf_path: " + cfg_.dcf_path);
} }
if (!impl_->enableHardware()) { if (!impl_->enableHardware(cfg_.accel_ramp_ms)) {
impl_.reset(); impl_.reset();
return StatusResponse::Error( return StatusResponse::Error(
StatusCode::kUnavailable, StatusCode::kUnavailable,
@@ -129,7 +129,8 @@ class ZlacWrapper : public BaseInterface {
VSLAM_INFO("base: ZLAC8015D tren " << cfg_.can_channel << " node " VSLAM_INFO("base: ZLAC8015D tren " << cfg_.can_channel << " node "
<< static_cast<int>(cfg_.can_node_id) << ", banh r=" << static_cast<int>(cfg_.can_node_id) << ", banh r="
<< cfg_.wheel_radius << " m cach nhau " << cfg_.wheel_separation << cfg_.wheel_radius << " m cach nhau " << cfg_.wheel_separation
<< " m, " << counts_per_rev_ << " count/vong"); << " m, " << counts_per_rev_ << " count/vong, ramp "
<< cfg_.accel_ramp_ms << " ms");
running_ = true; running_ = true;
poll_thread_ = std::thread([this] { PollLoop(); }); poll_thread_ = std::thread([this] { PollLoop(); });

View File

@@ -37,6 +37,16 @@ truoc khi chep de -- co mot cho da bi sua.
* `ZlacMotorDriver::getPositionCounts()` -- doc `0x6064` (Position actual * `ZlacMotorDriver::getPositionCounts()` -- doc `0x6064` (Position actual
value), cung cach telemetryLoop dang cache van toc. value), cung cach telemetryLoop dang cache van toc.
* `disableHardware()` join luong telemetry o DAU ham thay vi o cuoi, va phep
doc SDO du phong duoc boc mot `try` rieng.
Ban goc join SAU khi gui NMT STOP, tuc luong telemetry chac chan gap mot ket
noi SDO da chet. Khong lo vi no chi doc `0x606C` trong mot `catch(...)` rong.
Nhung phep doc `0x6064` them vao cung nam trong khoi `catch` do, ma nem tu
trong `catch` thi thoat thang ra ngoai -- `std::terminate`. Da do: node abort
kem core dump moi lan tat, voi
`SdoError: SubmitRead:01:6064:01: Resource not available: SDO connection`.
Ban goc chi co `getActualRPM()`, tuc chi co VAN TOC. `EncoderReading` cua du Ban goc chi co `getActualRPM()`, tuc chi co VAN TOC. `EncoderReading` cua du
an nay can GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la an nay can GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la
mat vinh vien mot doan quang duong va khong co cach nao phat hien -- xem mat vinh vien mot doan quang duong va khong co cach nao phat hien -- xem
@@ -51,3 +61,37 @@ lo mau khong mat gi.
Moi cho sua deu duoc danh dau bang `// [vslam]` trong nguon, de lan dong bo Moi cho sua deu duoc danh dau bang `// [vslam]` trong nguon, de lan dong bo
sau con tim lai duoc. sau con tim lai duoc.
## Khi nao theo base_kit, khi nao theo minh
Cau hoi nay se quay lai moi lan dong bo, nen ghi lai ranh gioi.
**Theo `base_kit`** voi nhung gi mo ta THIET BI. Chung dung voi moi con
LakiBeam / ZLAC, va bo tham so cua ho da chinh tren chinh con robot nay:
* `range_min` 0.19, `range_max` 30.0 -- gioi han tin cay cua cam bien
* 20 nguong loc shadow / intensity / isolated
* giai ma goi, don vi mm, quy uoc azimuth cua manual
**Theo minh** voi nhung gi mo ta CACH LAP con robot nay. `base_kit` chay tren
mot khung ga khac:
| Tham so | base_kit | o day | Vi sao |
|---|---|---|---|
| `angle_offset_deg` / `angle_flip` | 90 / false | 180 / true | phep thu: nguoi dung ben TRAI robot, man hinh phai hien ben TRAI |
| `acc_dec` (0x6083/84) | 1200 | 1200 | DA KEO VE. Mac dinh cua `enableHardware()` la 500 -- nhanh gap 2.4 lan |
| `box_min_y` / `box_max_y` | -0.25 / 0.0 | -0.25 / 0.25 | bon cot o day doi xung (y = +-0.136); hop mot ben bo sot hai cot |
| toan bo `robot.yaml` | -- | -- | vi tri banh / LiDAR / camera do tren robot nay |
Quy tac gon: **do duoc tren robot nay thi PHEP DO thang; khong do duoc thi
`base_kit` thang.**
⚠️ Va co loai thu ba: cai `base_kit` KHONG BIET. `encoder_counts_per_rev` la
mot -- `motor_params.yaml` khong co tham so encoder nao, vi `zlac_ros_node`
chi doc van toc (`0x606C`, don vi rpm da co san) nen khong bao gio phai doi
count sang radian. Chi du an nay doc `0x6064`, nen chi du an nay phai do.
Dung tim cau tra loi o ben do.
Moi lan lech khoi `base_kit` deu co mot phep do dung sau, khong lan nao la so
thich. Truoc khi keo mot gia tri cua ho ve, hoi: gia tri nay noi ve THIET BI
hay ve KHUNG GA?

View File

@@ -0,0 +1,80 @@
#ifndef LIDAR_CORE__SCAN_FILTER_HPP_
#define LIDAR_CORE__SCAN_FILTER_HPP_
#include <memory>
// [vslam] Chep tu base_kit/src/lidar/lakibeam_ros. Doi DUY NHAT: kieu
// sensor_msgs::msg::LaserScan -> lidar_core::LaserScan. Hai kieu co cung bo
// truong (lidar_core::LaserScan la ban sao thuan C++ cua sensor_msgs), va bo
// loc chi dung ranges/intensities/angle_*/range_*.
// Xem thirdparty/PROVENANCE.md.
#include "lidar_core/laser_scan.hpp"
namespace lidar_core
{
/// @brief Tham số cấu hình cho bộ lọc ScanFilter
struct ScanFilterConfig
{
// ---- Shadow / Trailing Beam Filter ----
bool shadow_filter_enabled = true; ///< Bật/tắt bộ lọc bóng/tia kéo dài
double shadow_min_angle_deg = 12.0; ///< Ngưỡng góc tới hạn [deg] (nhỏ hơn ngưỡng sẽ coi là tia kéo dài)
int shadow_window = 4; ///< Cửa sổ trượt kiểm tra (số tia lân cận)
double shadow_min_range_diff = 0.05; ///< Bước nhảy cự ly tối thiểu [m] để xét dải chéo
double shadow_max_range = 2.0; ///< Cự ly tối đa áp dụng lọc [m] (phạm vi quanh base robot)
bool shadow_clear_start = false; ///< Xóa cả điểm mép dải dốc (mặc định false để bảo vệ vật thể thật)
int shadow_clear_neighbors = 0; ///< Số tia lân cận xóa mở rộng (0 = không lấn sang tường thật)
// ---- Box / Footprint Filter (Khung robot base) ----
bool box_filter_enabled = false; ///< Bật/tắt lọc theo vùng hộp thân robot (mặc định tắt)
double box_min_x = -0.25; ///< Giới hạn X tối thiểu [m]
double box_max_x = 0.25; ///< Giới hạn X tối đa [m]
double box_min_y = -0.45; ///< Giới hạn Y tối thiểu [m]
double box_max_y = 0.0; ///< Giới hạn Y tối đa [m]
// ---- Intensity Filter (Lọc theo cường độ phản xạ RSSI) ----
bool intensity_filter_enabled = true; ///< Bật/tắt lọc theo cường độ phản xạ
float intensity_min = 25.0f; ///< Cường độ nhỏ nhất được chấp nhận (nhỏ hơn sẽ bị lọc)
float intensity_max = 255.0f; ///< Cường độ lớn nhất được chấp nhận
float intensity_filter_max_range = 1.0f; ///< Cự ly tối đa [m] áp dụng lọc cường độ (0 = toàn bộ scan)
// ---- Isolated Cluster Filter (Lọc cụm điểm đơn lẻ / nhiễu li ti) ----
bool isolated_filter_enabled = true; ///< Bật/tắt lọc cụm điểm đơn lẻ
int isolated_min_cluster_points = 3; ///< Lọc cụm có số điểm < ngưỡng này (3 = lọc điểm đơn và cụm 2 điểm)
double isolated_max_range_jump = 0.10; ///< Chênh lệch cự ly tối đa giữa 2 tia liên tiếp để tính cùng cụm [m]
double isolated_max_range = 2.0; ///< Chỉ lọc cụm đơn lẻ trong phạm vi này [m] (0 = toàn bộ scan)
};
/// @brief Interface cho bộ lọc LaserScan
class IScanFilter
{
public:
virtual ~IScanFilter() = default;
/// @brief Lọc trực tiếp trên bản tin LaserScan (thay các điểm rác bằng +Inf)
virtual void filter(LaserScan & scan) const = 0;
};
/// @brief Triển khai bộ lọc tia kéo dài (shadow / grazing angle filter)
class ScanFilter : public IScanFilter
{
public:
explicit ScanFilter(const ScanFilterConfig & config);
~ScanFilter() override = default;
ScanFilter(const ScanFilter &) = delete;
ScanFilter & operator=(const ScanFilter &) = delete;
void filter(LaserScan & scan) const override;
const ScanFilterConfig & config() const { return config_; }
private:
ScanFilterConfig config_;
double min_angle_rad_{0.0};
};
} // namespace lidar_core
#endif // LIDAR_CORE__SCAN_FILTER_HPP_

View File

@@ -0,0 +1,270 @@
#include "lidar_core/scan_filter.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
namespace lidar_core
{
namespace
{
constexpr double kDeg2Rad = 3.14159265358979323846 / 180.0;
constexpr double kTwoPi = 2.0 * 3.14159265358979323846;
inline bool isValidRange(float r, float range_min, float range_max)
{
return std::isfinite(r) && (r >= range_min) && (r <= range_max);
}
} // namespace
ScanFilter::ScanFilter(const ScanFilterConfig & config)
: config_(config),
min_angle_rad_(config.shadow_min_angle_deg * kDeg2Rad)
{
}
void ScanFilter::filter(LaserScan & scan) const
{
if ((!config_.shadow_filter_enabled && !config_.box_filter_enabled &&
!config_.intensity_filter_enabled && !config_.isolated_filter_enabled) ||
scan.ranges.empty()) {
return;
}
const size_t n = scan.ranges.size();
const float r_min = scan.range_min;
const float r_max = scan.range_max;
const double dtheta_base = std::abs(static_cast<double>(scan.angle_increment));
const double span = std::abs(static_cast<double>(scan.angle_max - scan.angle_min));
const bool is_360 = (span >= (kTwoPi - dtheta_base * 1.5));
const int window = std::max(1, config_.shadow_window);
const float min_range_diff = static_cast<float>(config_.shadow_min_range_diff);
const float max_range_threshold = static_cast<float>(config_.shadow_max_range);
const int clear_neighbors = std::max(0, config_.shadow_clear_neighbors);
std::vector<bool> to_filter(n, false);
// 1. Box / Footprint Filter: Lọc theo vùng hộp thân robot (tùy chọn)
if (config_.box_filter_enabled) {
for (size_t i = 0; i < n; ++i) {
const float r = scan.ranges[i];
if (!isValidRange(r, r_min, r_max)) {
continue;
}
const double theta = static_cast<double>(scan.angle_min) +
static_cast<double>(i) * static_cast<double>(scan.angle_increment);
const double x = static_cast<double>(r) * std::cos(theta);
const double y = static_cast<double>(r) * std::sin(theta);
if (x >= config_.box_min_x && x <= config_.box_max_x &&
y >= config_.box_min_y && y <= config_.box_max_y) {
to_filter[i] = true;
}
}
}
// 2. Shadow Filter: Lọc các dải dốc tia kéo dài (grazing angle)
if (config_.shadow_filter_enabled) {
for (size_t i = 0; i < n; ++i) {
const float r1 = scan.ranges[i];
if (!isValidRange(r1, r_min, r_max)) {
continue;
}
for (int k = 1; k <= window; ++k) {
const size_t j = is_360 ? ((i + static_cast<size_t>(k)) % n) : (i + static_cast<size_t>(k));
if (j >= n) {
break;
}
const float r2 = scan.ranges[j];
if (!isValidRange(r2, r_min, r_max)) {
continue;
}
// Giới hạn cự ly áp dụng lọc (chỉ lọc các dải xuất phát từ vùng gần robot)
if (max_range_threshold > 0.0f) {
const float nearer_dist = std::min(r1, r2);
if (nearer_dist > max_range_threshold) {
continue;
}
}
// Chênh lệch cự ly giữa 2 tia trong cửa sổ phải đủ lớn để cấu thành dải dốc
const float range_diff = std::abs(r2 - r1);
if (range_diff < min_range_diff) {
continue;
}
// Tính góc tới hạn alpha (grazing angle) tại điểm gần
const double dtheta = static_cast<double>(k) * dtheta_base;
const double d_perp = static_cast<double>(r2) * std::sin(dtheta);
const double d_para = std::abs(static_cast<double>(r2) * std::cos(dtheta) - static_cast<double>(r1));
const double alpha = std::atan2(d_perp, d_para);
if (alpha < min_angle_rad_) {
// Chỉ đánh dấu các điểm trung gian nằm trên dải dốc (r_low < r_m < r_high)
const float r_low = std::min(r1, r2);
const float r_high = std::max(r1, r2);
for (size_t m = 1; m < static_cast<size_t>(k); ++m) {
const size_t idx = (i + m) % n;
const float rm = scan.ranges[idx];
if (isValidRange(rm, r_min, r_max) && rm > (r_low + 0.005f) && rm < (r_high - 0.005f)) {
to_filter[idx] = true;
}
}
if (config_.shadow_clear_start) {
if (r1 < r2) {
to_filter[i] = true;
} else {
to_filter[j] = true;
}
}
// Xóa mở rộng thêm các tia lân cận ở 2 đầu nếu được cấu hình
for (int nb = 1; nb <= clear_neighbors; ++nb) {
const size_t s_nb = static_cast<size_t>(nb);
const size_t idx_before = is_360 ? ((i + n - s_nb) % n) : (i >= s_nb ? (i - s_nb) : 0);
const size_t idx_after = is_360 ? ((j + s_nb) % n) : (std::min(j + s_nb, n - 1));
to_filter[idx_before] = true;
to_filter[idx_after] = true;
}
}
}
}
}
// 3. Intensity Filter: Lọc theo cường độ phản xạ (RSSI)
if (config_.intensity_filter_enabled && !scan.intensities.empty()) {
const float int_min = config_.intensity_min;
const float int_max = config_.intensity_max;
const float int_max_range = static_cast<float>(config_.intensity_filter_max_range);
const size_t n_int = std::min(n, scan.intensities.size());
for (size_t i = 0; i < n_int; ++i) {
const float r = scan.ranges[i];
if (!isValidRange(r, r_min, r_max)) {
continue;
}
if (int_max_range > 0.0f && r > int_max_range) {
continue;
}
const float intensity = scan.intensities[i];
if (intensity < int_min || intensity > int_max) {
to_filter[i] = true;
}
}
}
// 4. Isolated Cluster Filter: Lọc cụm điểm đơn lẻ / nhiễu li ti
// Chia scan thành các cụm điểm liên tiếp (2 tia liền nhau thuộc cùng cụm nếu
// chênh lệch cự ly <= jump). Cụm có số điểm < min_cluster_points trong phạm vi
// max_range (cụm đơn lẻ gần robot — nhiễu li ti từ khung gắn) sẽ bị xóa.
// Tường/vật cản thật là cụm lớn nên được bảo toàn. Chạy sau cùng để các điểm
// đã bị bộ lọc khác xử lý (sẽ thành +Inf) không tính là điểm lân cận hỗ trợ.
if (config_.isolated_filter_enabled) {
const int min_pts = std::max(1, config_.isolated_min_cluster_points);
const float jump_thresh = static_cast<float>(config_.isolated_max_range_jump);
const float iso_max_range = static_cast<float>(config_.isolated_max_range);
// Điểm đã bị lọc (to_filter) coi như không hợp lệ vì sẽ bị gán +Inf
const auto is_valid_pt = [&](size_t idx) {
return !to_filter[idx] && isValidRange(scan.ranges[idx], r_min, r_max);
};
// Tìm mốc bắt đầu sao cho biên (start-1, start) là điểm ngăn cách cụm:
// ưu tiên điểm gap (không hợp lệ); nếu toàn bộ scan hợp lệ thì dùng vị trí
// break cự ly đầu tiên. Nhờ đó chia cụm theo vòng tròn không cần xử lý wrap.
size_t start = 0;
bool has_start = false;
for (size_t i = 0; i < n; ++i) {
if (!is_valid_pt(i)) {
has_start = true;
start = (i + 1) % n;
break;
}
}
if (!has_start) {
for (size_t i = 0; i < n; ++i) {
const size_t nxt = (i + 1) % n;
if (std::abs(scan.ranges[nxt] - scan.ranges[i]) > jump_thresh) {
has_start = true;
start = nxt;
break;
}
}
}
if (has_start) {
// Gán cluster id cho từng điểm hợp lệ (duyệt circular từ sau gap)
std::vector<int> cid(n, -1);
int cur_id = -1;
for (size_t off = 0; off < n; ++off) {
const size_t i = (start + off) % n;
if (!is_valid_pt(i)) {
continue;
}
const size_t prev = (i + n - 1) % n;
const bool new_cluster =
(cur_id < 0) || !is_valid_pt(prev) ||
(std::abs(scan.ranges[i] - scan.ranges[prev]) > jump_thresh);
if (new_cluster) {
++cur_id;
}
cid[i] = cur_id;
}
if (cur_id >= 0) {
// Đếm số điểm + cự ly gần nhất của từng cụm
std::vector<int> cluster_count(static_cast<size_t>(cur_id) + 1, 0);
std::vector<float> cluster_min_r(static_cast<size_t>(cur_id) + 1,
std::numeric_limits<float>::infinity());
for (size_t i = 0; i < n; ++i) {
if (cid[i] < 0) {
continue;
}
const size_t c = static_cast<size_t>(cid[i]);
++cluster_count[c];
cluster_min_r[c] = std::min(cluster_min_r[c], scan.ranges[i]);
}
// Lọc toàn bộ cụm nhỏ trong phạm vi max_range
for (size_t i = 0; i < n; ++i) {
if (cid[i] < 0) {
continue;
}
const size_t c = static_cast<size_t>(cid[i]);
if (cluster_count[c] >= min_pts) {
continue;
}
if (iso_max_range > 0.0f && cluster_min_r[c] > iso_max_range) {
continue;
}
to_filter[i] = true;
}
}
}
}
// Áp dụng gán +Inf cho các điểm bị lọc
const float inf = std::numeric_limits<float>::infinity();
const bool has_intensities = (scan.intensities.size() == n);
for (size_t i = 0; i < n; ++i) {
if (to_filter[i]) {
scan.ranges[i] = inf;
if (has_intensities) {
scan.intensities[i] = 0.0f;
}
}
}
}
} // namespace lidar_core

View File

@@ -152,6 +152,20 @@ void ZlacMotorDriver::disableHardware() {
std::cout << "[ZlacMotorDriver] Safely disabling motor hardware..." << std::endl; std::cout << "[ZlacMotorDriver] Safely disabling motor hardware..." << std::endl;
// [vslam] ⚠️ JOIN luong telemetry TRUOC khi dong bat cu thu gi.
//
// Ban goc join o cuoi, sau khi da gui NMT STOP -- nghia la luong telemetry
// chac chan gap mot ket noi SDO da chet va nem SdoError. Truoc day khong lo
// vi no chi doc 0x606C trong mot khoi catch(...) rong; tu khi them phep doc
// vi tri 0x6064 thi node abort kem core dump moi lan tat.
//
// `hardware_ready_.exchange(false)` o tren da lam vong `while` thoat, nen
// join o day chi cho not mot chu ky 20 ms.
hardware_ready_.store(false);
if (telemetry_thread_.joinable()) {
telemetry_thread_.join();
}
// 1. Send zero target velocity // 1. Send zero target velocity
setTargetRPM(0, 0); setTargetRPM(0, 0);
@@ -165,9 +179,7 @@ void ZlacMotorDriver::disableHardware() {
master_->Command(lely::canopen::NmtCommand::STOP, node_id_); master_->Command(lely::canopen::NmtCommand::STOP, node_id_);
} }
if (telemetry_thread_.joinable()) { // [vslam] Ban goc join o day. Da chuyen len DAU ham -- xem ghi chu o do.
telemetry_thread_.join();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
@@ -261,13 +273,22 @@ void ZlacMotorDriver::telemetryLoop() {
pdo_mapped_ = true; pdo_mapped_ = true;
} catch (...) { } catch (...) {
// Fallback to SDO synchronous read if PDO is not mapped yet // Fallback to SDO synchronous read if PDO is not mapped yet
auto left_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 1); //
auto right_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 2); // [vslam] try rieng, nhu 0x6064 ben duoi: nem tu trong catch ->
// std::terminate. Da xay ra GIUA phien chay 2026-09-28 khi bus CAN
// nghen ("49 write errors"): SdoError("SubmitRead:01:606C:01:
// Resource not available: SDO connection") va node abort.
try {
auto left_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 1);
auto right_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 2);
if (left_opt.has_value() && right_opt.has_value()) { if (left_opt.has_value() && right_opt.has_value()) {
cached_left_vel_raw_ = left_opt.value(); cached_left_vel_raw_ = left_opt.value();
cached_right_vel_raw_ = right_opt.value(); cached_right_vel_raw_ = right_opt.value();
cached_vel_valid_ = true; cached_vel_valid_ = true;
}
} catch (...) {
// Mat mot mau van toc; 20 ms sau doc lai.
} }
} }
} }
@@ -304,16 +325,27 @@ void ZlacMotorDriver::telemetryLoop() {
// Ben goi dung so nay de ngoai suy banh trai toi thoi diem cua banh // Ben goi dung so nay de ngoai suy banh trai toi thoi diem cua banh
// phai; khong bu thi cong thuc vi sai bien khoang lech do thanh quay // phai; khong bu thi cong thuc vi sai bien khoang lech do thanh quay
// gia. // gia.
const auto t0 = std::chrono::steady_clock::now(); //
auto lp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 1); // [vslam] ⚠️ try LONG BEN TRONG catch la BAT BUOC, khong phai thua.
auto rp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 2); // Nem tu trong mot khoi catch thi thoat thang ra ngoai, khong con ai
const auto t2 = std::chrono::steady_clock::now(); // bat nua -> std::terminate. Da xay ra that luc tat may: lely nem
if (lp.has_value() && rp.has_value()) { // SdoError("SubmitRead:01:6064:01: Resource not available: SDO
cached_left_pos_raw_ = lp.value(); // connection") vi disableHardware() da gui NMT STOP truoc khi join
cached_right_pos_raw_ = rp.value(); // luong nay, va node abort kem core dump.
cached_pos_skew_sec_ = try {
std::chrono::duration<double>(t2 - t0).count() / 2.0; const auto t0 = std::chrono::steady_clock::now();
pos_ok = true; auto lp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 1);
auto rp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 2);
const auto t2 = std::chrono::steady_clock::now();
if (lp.has_value() && rp.has_value()) {
cached_left_pos_raw_ = lp.value();
cached_right_pos_raw_ = rp.value();
cached_pos_skew_sec_ =
std::chrono::duration<double>(t2 - t0).count() / 2.0;
pos_ok = true;
}
} catch (...) {
// Mat mot mau vi tri. Ben goi nhan ra qua `seq` khong doi.
} }
} }
if (pos_ok) { if (pos_ok) {

View File

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

View File

@@ -74,6 +74,10 @@ struct EkfSe2Stats {
uint64_t imu_updates = 0; uint64_t imu_updates = 0;
uint64_t rejected_outliers = 0; uint64_t rejected_outliers = 0;
uint64_t time_resets = 0; uint64_t time_resets = 0;
// Phep do den KHONG dung thu tu, lech duoi kMaxOutOfOrderSec. Binh thuong
// voi nhieu cam bien: IMU duoc bu 80 ms nen dau thoi gian cua no luon cu hon
// encoder. Con so nay tang deu la DUNG. Tang vot moi dang nghi.
uint64_t out_of_order = 0;
double last_mahalanobis = 0.0; double last_mahalanobis = 0.0;
}; };

View File

@@ -0,0 +1,87 @@
#ifndef VSLAM_GYRO_YAW_FUSER_H
#define VSLAM_GYRO_YAW_FUSER_H
// Goc quay (yaw) cho EKF: GYRO giu TONG, encoder chi lap khoang gyro chua ve.
//
// ================== VI SAO ==================
// Cach cu tich gyro THEO LUC MAU TOI giua hai buoc encoder, roi chi nhan khi do
// dai cua so gyro nam trong 0.5-1.5 lan buoc encoder, ngoai do thi VUT. Tren
// robot that mau IMU toi THEO CUM (log 07/10: cua so 40 ms = 8 mau, buoc
// encoder 22.5 ms): cua so ngan (thieu) duoc nhan, cua so dai (mang phan bu)
// bi vut -> goc DEM THIEU mot chieu. Do tren ban do real_20261007_112455: ICP
// phai cong them 9.9% moi goc quay (ban do 28/09 va 01/10 dung encoder: 0% va
// -1.8%), trong khi chinh gyro van khop encoder 0.99 luc quay. Sim khong lo vi
// IMU va encoder toi deu.
//
// ================== CACH LAM ==================
// Goc tai buoc encoder t:
// Y(t) = Theta_gyro(b) + [theta_enc(t) - theta_enc(b)]
// b = dau thoi gian mau gyro MOI NHAT (da bu tre). Moi buoc tra ve
// Y(t_i) - Y(t_{i-1}): tong cong don lai triet tieu, nen ve lau dai goc theo
// DUNG gyro (khong mau nao bi vut), con khoang (b, t] -- vai chuc ms gyro chua
// toi -- lay tu encoder nen khong tre. Truot banh lam encoder sai trong khoang
// do thi buoc sau, khi gyro toi, phan lech duoc tra lai.
//
// IMU cham (chu ky > max_gyro_period, vd WT61PC 10 Hz) hoac het tuoi thi chi
// dung encoder -- nhu truoc 06/10. Gyro dut quang (khe > max_gap) thi dat lai
// moc, khong bu qua khe.
#include <deque>
#include "vslam/unix_time.h"
namespace vslam {
struct GyroYawFuserConfig {
double max_gyro_period = 0.03; // s; IMU cham hon -> chi encoder
double stale_sec = 0.2; // s; khong co mau gyro moi -> chi encoder
double max_gap = 0.1; // s; hai mau gyro cach hon -> khong tich phan qua khe
double enc_history_sec = 2.0; // s; lich su goc encoder de noi suy tai moc gyro
};
class GyroYawFuser {
public:
explicit GyroYawFuser(GyroYawFuserConfig cfg = GyroYawFuserConfig());
// Mot mau gyro z (rad/s), dau thoi gian DA bu tre IMU. Goi theo thu tu toi.
void AddGyro(UnixTime t, double wz);
// Mot buoc encoder ket thuc tai `t` voi goc encoder `d_theta_enc` (rad).
// `*d_theta` = goc da ghep cho buoc nay. Tra true neu co dung gyro.
bool Step(UnixTime t, double d_theta_enc, double* d_theta);
void Reset();
// Chu ky gyro uoc luong (s), 0 neu chua biet. De log.
double gyro_period() const { return period_; }
private:
struct EncSample {
UnixTime t;
double theta;
};
bool EncThetaAt(UnixTime t, double* out) const;
GyroYawFuserConfig cfg_;
// Gyro: goc tich luy (hinh thang) toi mau moi nhat.
bool have_g_ = false;
UnixTime g_t_;
double g_w_ = 0.0;
double g_theta_ = 0.0;
double period_ = 0.0;
// Encoder: goc tich luy theo thoi gian.
std::deque<EncSample> enc_;
double enc_theta_ = 0.0;
// Moc cua buoc truoc: thoi gian b, goc gyro va goc encoder tai b.
bool anchored_ = false;
UnixTime b_;
double g_at_b_ = 0.0;
double e_at_b_ = 0.0;
};
} // namespace vslam
#endif // VSLAM_GYRO_YAW_FUSER_H

View File

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

View File

@@ -62,6 +62,15 @@ struct WheelOdometryStats {
uint64_t slip_events = 0; uint64_t slip_events = 0;
uint64_t time_resets = 0; // dt <= 0: reset sim hoac replay nhay lui uint64_t time_resets = 0; // dt <= 0: reset sim hoac replay nhay lui
uint64_t no_imu_updates = 0; // chay "mu", khong phat hien duoc truot uint64_t no_imu_updates = 0; // chay "mu", khong phat hien duoc truot
// So lan phai lui ve so THO (omega tuc thoi vs gyro moi nhat) vi thieu lich
// su. Binh thuong chi xay ra vai chu ky dau va sau Reset(). Con so nay lon
// nghia la viec so cung bang thong khong chay -- va bao dong truot gia se
// quay lai ma khong co dau hieu nao khac.
uint64_t slip_coarse_updates = 0;
// Mau gyro den voi dau thoi gian KHONG moi hon mau truoc. Lich su noi suy
// phai don dieu nen chung bi bo. Khac 0 nghia la nguon dau thoi gian dang
// nhay lui -- nghi ClockSync fit lai qua thuong xuyen.
uint64_t gyro_out_of_order = 0;
double last_slip_metric = 0.0; double last_slip_metric = 0.0;
double total_distance = 0.0; double total_distance = 0.0;
}; };
@@ -83,6 +92,13 @@ class WheelOdometry {
double slip_metric() const { return slip_metric_; } double slip_metric() const { return slip_metric_; }
bool slipping() const { return slipping_; } bool slipping() const { return slipping_; }
// Do tre gyro uoc luong duoc, GIAY. Cong vao mcu.imu_lag_sec.
//
// NaN khi chua du mau. Va CHI CO NGHIA khi robot da tang/giam toc quay:
// dung yen hay quay deu thi moi tau deu khop tot nhu nhau va cuc tieu nam o
// dau cung duoc. Xem khoi "May do do tre" trong wheel_odometry.cc.
double estimated_imu_lag_sec() const;
Pose2D pose() const { return Pose2D{x_, y_, theta_}; } Pose2D pose() const { return Pose2D{x_, y_, theta_}; }
void SetPose(const Pose2D& p); void SetPose(const Pose2D& p);
void Reset(); void Reset();
@@ -105,6 +121,101 @@ class WheelOdometry {
double slip_metric_ = 0.0; double slip_metric_ = 0.0;
bool slipping_ = false; bool slipping_ = false;
// Chi de chan doan bring-up. Trung binh cong don cua (omega_enc - gyro_z).
double bias_sum_ = 0.0;
uint64_t bias_n_ = 0;
// ---- Lich su gyro ----
// Can vi dau thoi gian cua gyro va cua encoder KHONG BAO GIO trung khit.
// So gyro MOI NHAT voi encoder hien tai la so hai thoi diem khac nhau; luc
// robot dang doi toc do quay, chenh lech thuan tuy do lech dau thoi gian la
// alpha * lech_t, va no da do duoc 0.20 rad/s tren robot nay -- dung bang
// slip_omega_threshold.
//
// Dem GYRO chu khong dem encoder, va so o Update() chu khong o FeedGyroZ():
// stamp encoder da duoc keo LUI ve qua khu theo `age` (xem zlac_base.cc), nen
// tai luc Update(stamp) chay thi cac mau gyro hai ben `stamp` da co san. Lam
// nguoc lai -- dem encoder, so o FeedGyroZ() -- thi mau gyro moi nhat luon
// nam SAU mau encoder moi nhat, khong bao gio kep duoc, va viec phat hien
// truot im lang khong chay.
//
// Lich su PHAI don dieu; xem FeedGyroZ().
struct GyroSample {
UnixTime t;
double w = 0.0;
};
static constexpr size_t kGyroHist = 256; // 25 s o 10 Hz
GyroSample gyro_hist_[kGyroHist];
uint64_t gyro_n_ = 0; // tong so mau da ghi; chi so vong = % kGyroHist
// Noi suy tuyen tinh gyro tai `t`.
// require_bracket = true : chi tra ve khi `t` nam GIUA hai mau -> dung cho
// may do do tre, de khong nap gia tri kep bien vao phep khop.
// require_bracket = false: ngoai doan thi kep ve mau gan nhat -> dung cho
// phat hien truot, giu nguyen hanh vi cu khi chi co mot mau gyro.
bool GyroAt(UnixTime t, double* out, bool require_bracket) const;
// Chu ky lay mau gyro do tu chinh lich su, giay. 0 khi chua du mau.
//
// Do chu khong khai bao trong config: no phu thuoc firmware va che do cua
// cam bien, va da doi mot lan roi (10 Hz -> dinh 20 Hz nhung lenh khong an).
// Mot hang so trong config se troi khoi thuc te ma khong ai phat hien.
double GyroPeriodSec() const;
// Trung binh omega encoder tren [t0, t1]. Dung de so voi gyro tren CUNG mot
// cua so thoi gian -- xem khoi giai thich o cho goi.
bool OmegaEncoderMean(UnixTime t0, UnixTime t1, double* out) const;
// ---- May do do tre ----
// Mau gyro dong dau `s` do robot tai `s - L`, nen ung voi encoder tai `t` la
// mau gyro `t + L`. Tau nao lam phuong sai cua (omega_enc(t) - gyro(t + tau))
// nho nhat thi tau do la L. Chi co nghia khi robot CO tang/giam toc quay:
// dung yen hay quay deu thi moi tau deu tot nhu nhau.
//
// Luoi phu ca tau AM de con do duoc phan BU THUA sau khi dat mcu.imu_lag_sec.
static constexpr size_t kLagBins = 31; // -100 .. +200 ms
static constexpr size_t kLagZeroBin = 10; // bin cua tau = 0
static constexpr double kLagStepSec = 0.01;
// ⚠️ May do KHONG chay tai `stamp` ma lui lai ngan nay.
//
// Tai `stamp` thi gyro tai `stamp + tau` voi tau > 0 nam o TUONG LAI cua lich
// su gyro, khong kep duoc, nen cac bin tau duong khong bao gio nhan duoc mau
// va cuc tieu luon roi vao phia am. Da mac dung loi do: bom vao do tre 0 / 50
// / 100 ms thi may do bao -10 ms cho ca ba. Lui 0.3 s thi `t_ref + tau` nam
// tron trong [stamp-0.4, stamp-0.1], ca hai phia deu co du lieu.
//
// Chi ton them do tre bao cao, khong ton do chinh xac: day la phep do offline
// chay tren du lieu da qua.
static constexpr double kLagEvalDelaySec = 0.30;
// Lich su omega encoder -- CHI cho may do. Phat hien truot dung gyro_hist_.
struct OmegaSample {
UnixTime t;
double w = 0.0; // omega tuc thoi -- chi con may do do tre dung
double theta = 0.0; // goc quay TICH LUY tu encoder, radian
};
static constexpr size_t kOmegaHist = 128; // ~2.5 s o 50 Hz
OmegaSample omega_hist_[kOmegaHist];
uint64_t omega_n_ = 0;
bool OmegaEncoderAt(UnixTime t, double* out) const;
// Nhanh so THO dung nguong gap ngan nay. Xem khoi giai thich trong .cc:
// nhieu cua nhanh do co chan tren do duoc (0.78 rad/s) con truot that thi
// khong, nen nguong phai nam tren chan do.
static constexpr double kCoarseSlipFactor = 8.0;
// Noi suy goc quay tich luy tai `t`. Chi tra ve khi `t` nam GIUA hai mau.
bool EncThetaAt(UnixTime t, double* out) const;
// Goc quay tich luy tu encoder. Rieng voi `theta_`: `theta_` la pose va co
// the bi SetPose() ghi de tu ngoai, con day phai lien tuc.
double enc_theta_ = 0.0;
double lag_sse_[kLagBins] = {};
uint64_t lag_cnt_[kLagBins] = {};
uint64_t lag_n_ = 0;
WheelOdometryStats stats_; WheelOdometryStats stats_;
}; };

View File

@@ -134,6 +134,14 @@ struct EkfSe2::Impl {
EkfSe2::EkfSe2(EkfSe2Config cfg) : impl_(std::make_unique<Impl>(std::move(cfg))) {} EkfSe2::EkfSe2(EkfSe2Config cfg) : impl_(std::make_unique<Impl>(std::move(cfg))) {}
EkfSe2::~EkfSe2() = default; EkfSe2::~EkfSe2() = default;
// Lech thu tu duoi nguong nay coi la binh thuong; tren nguong coi la nhay lui
// that (reset mo phong, phat lai ban ghi).
//
// 0.25 s: rong hon nhieu so voi 80 ms cua IMU hien tai -- de con cho cam bien
// cham hon -- nhung hep hon han cu nhay hang giay cua replay. Nhanh `dt < 0`
// nguyen thuy viet cho truong hop sau, khong phai truong hop truoc.
constexpr double kMaxOutOfOrderSec = 0.25;
void EkfSe2::Predict(UnixTime now) { void EkfSe2::Predict(UnixTime now) {
std::lock_guard<std::mutex> lk(impl_->mu); std::lock_guard<std::mutex> lk(impl_->mu);
if (!impl_->have_time) { if (!impl_->have_time) {
@@ -143,7 +151,27 @@ void EkfSe2::Predict(UnixTime now) {
} }
const double dt = SecondsBetween(now, impl_->last_predict); const double dt = SecondsBetween(now, impl_->last_predict);
if (dt < 0.0) { if (dt < 0.0) {
// Thoi gian lui: reset mo phong hoac phat lai ban ghi. // ⚠️ HAI chuyen khac nhau, truoc day gop lam mot.
//
// LECH THU TU NHO -- binh thuong voi nhieu cam bien, khong phai loi.
// IMU duoc bu `mcu.imu_lag_sec` = 80 ms nen dau thoi gian cua no LUON cu
// hon encoder (encoder chi bu `age`, co ms). Do la DUNG: 80 ms do la thoi
// diem do that, WT61PC loc noi bo ~50 ms roi day 2 khung qua day 9600 baud
// ~23 ms, ca hai deu truoc luc ESP32 dong dau.
//
// Reset moc o day lam EKF tien 80 ms theo encoder roi bi IMU keo lui, moi
// 100 ms mot lan: nhieu qua trinh cong hai lan moi chu ky va cac phep cap
// nhat roi sai thoi diem. Do duoc tren robot: `ekf: thoi gian lui` lap lien
// tuc -0.040 / -0.054 / -0.045 / -0.059 / -0.073 s.
//
// Ap phep do len trang thai hien tai va GIU nguyen moc. Gan dung -- sai so
// chi la phan trang thai doi trong 80 ms, voi mot phep do VAN TOC GOC thi
// khong dang ke.
if (-dt < kMaxOutOfOrderSec) {
impl_->stats.out_of_order++;
return;
}
// NHAY LUI LON -- reset mo phong hoac phat lai ban ghi. Moc het nghia.
VSLAM_WARN("ekf: thoi gian lui " << dt << " s -- reset moc thoi gian"); VSLAM_WARN("ekf: thoi gian lui " << dt << " s -- reset moc thoi gian");
impl_->last_predict = now; impl_->last_predict = now;
impl_->stats.time_resets++; impl_->stats.time_resets++;

View File

@@ -0,0 +1,106 @@
#include "vslam/gyro_yaw_fuser.h"
#include <algorithm>
namespace vslam {
GyroYawFuser::GyroYawFuser(GyroYawFuserConfig cfg) : cfg_(cfg) {}
void GyroYawFuser::Reset() {
have_g_ = false;
g_w_ = 0.0;
g_theta_ = 0.0;
period_ = 0.0;
enc_.clear();
enc_theta_ = 0.0;
anchored_ = false;
}
void GyroYawFuser::AddGyro(UnixTime t, double wz) {
if (!have_g_) {
have_g_ = true;
g_t_ = t;
g_w_ = wz;
return;
}
const double dt = SecondsBetween(t, g_t_);
if (dt <= 0.0) {
// Dau thoi gian bang mau truoc (driver kep cho khong lui): khong co khoang
// nao de tich, mau sau se phu khoang nay. Giu toc do moi nhat.
g_w_ = wz;
return;
}
if (dt < cfg_.max_gap) {
g_theta_ += 0.5 * (g_w_ + wz) * dt;
period_ = period_ > 0.0 ? 0.9 * period_ + 0.1 * dt : dt;
} else {
// Dut quang: goc gyro khong biet trong khe -- dat lai moc, khong bu qua khe.
anchored_ = false;
}
g_t_ = t;
g_w_ = wz;
}
bool GyroYawFuser::EncThetaAt(UnixTime t, double* out) const {
if (enc_.empty()) return false;
if (SecondsBetween(t, enc_.back().t) >= 0.0) {
if (SecondsBetween(t, enc_.back().t) > 0.0) return false; // sau buoc moi nhat
*out = enc_.back().theta;
return true;
}
for (size_t k = enc_.size() - 1; k > 0; --k) {
const EncSample& hi = enc_[k];
const EncSample& lo = enc_[k - 1];
if (SecondsBetween(t, lo.t) < 0.0) continue;
const double span = SecondsBetween(hi.t, lo.t);
*out = span > 0.0 ? lo.theta + (hi.theta - lo.theta) * SecondsBetween(t, lo.t) / span
: hi.theta;
return true;
}
return false; // truoc mau encoder cu nhat
}
bool GyroYawFuser::Step(UnixTime t, double d_theta_enc, double* d_theta) {
*d_theta = d_theta_enc;
if (!enc_.empty() && SecondsBetween(t, enc_.back().t) <= 0.0) {
// Thoi gian encoder lui (reset mo phong, phat lai): bat dau lai.
Reset();
}
enc_theta_ += d_theta_enc;
enc_.push_back(EncSample{t, enc_theta_});
while (enc_.size() > 2 && SecondsBetween(t, enc_.front().t) > cfg_.enc_history_sec) {
enc_.pop_front();
}
const bool usable = have_g_ && period_ > 0.0 && period_ <= cfg_.max_gyro_period &&
SecondsBetween(t, g_t_) < cfg_.stale_sec;
if (!usable) {
anchored_ = false;
return false;
}
// Moc moi: mau gyro moi nhat, khong vuot buoc encoder nay.
const UnixTime b = SecondsBetween(g_t_, t) > 0.0 ? t : g_t_;
double e_b = 0.0;
if (!EncThetaAt(b, &e_b)) {
anchored_ = false;
return false;
}
// Gyro toi tre hon buoc encoder thi g_theta_ la goc tai g_t_; b = t chi khi
// gyro di truoc (it gap) -- khi do goc gyro tai t lay bang mau moi nhat.
if (!anchored_ || SecondsBetween(b, b_) < 0.0) {
anchored_ = true;
b_ = b;
g_at_b_ = g_theta_;
e_at_b_ = e_b;
return false;
}
// Goc tren khoang moc [b_, b]: gyro thay encoder.
const double corr = (g_theta_ - g_at_b_) - (e_b - e_at_b_);
*d_theta = d_theta_enc + corr;
b_ = b;
g_at_b_ = g_theta_;
e_at_b_ = e_b;
return true;
}
} // namespace vslam

View File

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

View File

@@ -2,6 +2,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <limits>
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
@@ -10,10 +11,185 @@ namespace vslam {
WheelOdometry::WheelOdometry(WheelOdometryConfig cfg) : cfg_(std::move(cfg)) {} WheelOdometry::WheelOdometry(WheelOdometryConfig cfg) : cfg_(std::move(cfg)) {}
bool WheelOdometry::GyroAt(UnixTime t, double* out, bool require_bracket) const {
const uint64_t have = gyro_n_ < kGyroHist ? gyro_n_ : kGyroHist;
if (have == 0) return false;
const uint64_t oldest = gyro_n_ - have; // chi so tuyet doi cua mau cu nhat
const GyroSample& newest = gyro_hist_[(gyro_n_ - 1) % kGyroHist];
const GyroSample& eldest = gyro_hist_[oldest % kGyroHist];
// ⚠️ `> 0.0` chu khong phai `>= 0.0`. Voi `>=`, truong hop `t` TRUNG DUNG dau
// thoi gian cua mau bien bi coi la "nam ngoai" va `require_bracket` tu choi
// -- trong khi do lai la truong hop TOT NHAT: gia tri co san chinh xac, khoi
// noi suy.
//
// Khong phai chuyen hiem. Gyro 10 Hz va encoder 50 Hz thi cu 5 lan cap nhat
// lai co mot lan `t_ref` roi dung vao mot mau gyro -- 20% so lan. Da do:
// 59/199 lan phai lui ve so tho, va chinh nhung lan do sinh ra bao dong truot
// gia 0.4667 rad/s = do doc nhan tron mot chu ky gyro.
if (SecondsBetween(t, newest.t) > 0.0) { // t moi hon moi mau dang giu
if (require_bracket) return false;
*out = newest.w;
return true;
}
if (SecondsBetween(eldest.t, t) > 0.0) { // t cu hon moi mau dang giu
if (require_bracket) return false;
*out = eldest.w;
return true;
}
// Duyet tu MOI ve CU: `t` thuong nam sat dau moi, nen vong nay ket thuc som.
for (uint64_t k = gyro_n_ - 1; k > oldest; --k) {
const GyroSample& hi = gyro_hist_[k % kGyroHist];
const GyroSample& lo = gyro_hist_[(k - 1) % kGyroHist];
if (SecondsBetween(t, lo.t) < 0.0 || SecondsBetween(hi.t, t) < 0.0) continue;
const double span = SecondsBetween(hi.t, lo.t);
if (!(span > 0.0)) {
*out = hi.w;
return true;
}
const double a = SecondsBetween(t, lo.t) / span;
*out = lo.w + a * (hi.w - lo.w);
return true;
}
return false;
}
bool WheelOdometry::OmegaEncoderAt(UnixTime t, double* out) const {
const uint64_t have = omega_n_ < kOmegaHist ? omega_n_ : kOmegaHist;
if (have < 2) return false;
const uint64_t oldest = omega_n_ - have;
for (uint64_t k = omega_n_ - 1; k > oldest; --k) {
const OmegaSample& hi = omega_hist_[k % kOmegaHist];
const OmegaSample& lo = omega_hist_[(k - 1) % kOmegaHist];
if (SecondsBetween(t, lo.t) < 0.0 || SecondsBetween(hi.t, t) < 0.0) continue;
const double span = SecondsBetween(hi.t, lo.t);
if (!(span > 0.0)) {
*out = hi.w;
return true;
}
const double a = SecondsBetween(t, lo.t) / span;
*out = lo.w + a * (hi.w - lo.w);
return true;
}
return false;
}
double WheelOdometry::GyroPeriodSec() const {
const uint64_t have = gyro_n_ < kGyroHist ? gyro_n_ : kGyroHist;
if (have < 8) return 0.0;
const GyroSample& newest = gyro_hist_[(gyro_n_ - 1) % kGyroHist];
const GyroSample& older = gyro_hist_[(gyro_n_ - 8) % kGyroHist];
const double span = SecondsBetween(newest.t, older.t);
if (!(span > 0.0)) return 0.0;
return span / 7.0;
}
bool WheelOdometry::EncThetaAt(UnixTime t, double* out) const {
const uint64_t have = omega_n_ < kOmegaHist ? omega_n_ : kOmegaHist;
if (have < 2) return false;
const uint64_t oldest = omega_n_ - have;
for (uint64_t k = omega_n_ - 1; k > oldest; --k) {
const OmegaSample& hi = omega_hist_[k % kOmegaHist];
const OmegaSample& lo = omega_hist_[(k - 1) % kOmegaHist];
if (SecondsBetween(t, lo.t) < 0.0 || SecondsBetween(hi.t, t) < 0.0) continue;
const double span = SecondsBetween(hi.t, lo.t);
if (!(span > 0.0)) {
*out = hi.theta;
return true;
}
const double a = SecondsBetween(t, lo.t) / span;
*out = lo.theta + a * (hi.theta - lo.theta);
return true;
}
return false;
}
bool WheelOdometry::OmegaEncoderMean(UnixTime t0, UnixTime t1,
double* out) const {
// ⚠️ Tinh tu HIEU VI TRI, khong phai trung binh cac omega tuc thoi.
//
// Hai vong 50 Hz khong dong bo (telemetry cua ZLAC va vong doc cua ta) lam
// `age` cua mau encoder dao dong 0-20 ms, va no di thang vao dau thoi gian
// roi vao `dt`. Trong `omega = d_theta / dt` thi TU SO chinh xac tuyet doi
// (dem xung) con MAU SO nhieu +-20 ms tren nen 20 ms.
//
// Trung binh cac ti so `d_theta_i / dt_i` KHONG khu duoc nhieu do -- trung
// binh cua ti so khac ti so cua trung binh, va con lech he thong. Do duoc
// tren robot: omega bao 0.0096 roi 0.4377 quanh gia tri that 0.22, tuc mot
// khoang bo sot chuyen dong va khoang sau bu lai gap doi.
//
// Lay `(theta(t1) - theta(t0)) / (t1 - t0)` thi tu so la hieu hai so dem
// xung -- chinh xac tuyet doi -- va moi nhieu o cac moc GIUA cua so tu triet
// tieu. Chi con nhieu o hai dau, tren nen 100 ms thay vi 20 ms: nho di 5 lan.
const double span = SecondsBetween(t1, t0);
if (!(span > 0.0)) return false;
double th0 = 0.0, th1 = 0.0;
if (!EncThetaAt(t0, &th0) || !EncThetaAt(t1, &th1)) return false;
*out = (th1 - th0) / span;
return true;
}
double WheelOdometry::estimated_imu_lag_sec() const {
size_t best = 0;
double best_mse = -1.0;
for (size_t i = 0; i < kLagBins; ++i) {
if (lag_cnt_[i] < 100) continue;
const double mse = lag_sse_[i] / static_cast<double>(lag_cnt_[i]);
if (best_mse < 0.0 || mse < best_mse) {
best_mse = mse;
best = i;
}
}
if (best_mse < 0.0) return std::numeric_limits<double>::quiet_NaN();
return kLagStepSec *
(static_cast<double>(best) - static_cast<double>(kLagZeroBin));
}
void WheelOdometry::FeedGyroZ(UnixTime stamp, double wz) { void WheelOdometry::FeedGyroZ(UnixTime stamp, double wz) {
gyro_z_ = wz; gyro_z_ = wz;
last_imu_time_ = stamp; last_imu_time_ = stamp;
have_imu_ = true; have_imu_ = true;
// Lich su PHAI don dieu: ca GyroAt() lan GyroPeriodSec() deu gia dinh the,
// va mot mau lech thu tu lam phep tim cap kep that bai IM LANG -> lui ve so
// tho -> bao dong truot gia quay lai.
//
// ⚠️ XOA lich su, KHONG bo mau.
//
// Ban truoc bo mau lech thu tu va giu lich su cu. Do la sai, va sai theo
// kieu khong hoi phuc duoc: chi can MOT dau thoi gian nhay len TUONG LAI la
// `prev.t` nam o tuong lai vinh vien, moi mau sau do deu "cu hon", deu bi bo,
// va lich su khong bao gio dung lai duoc. Do duoc tren robot: `[tho:P]` o 17
// dong dbg (tuc duoi 8 mau trong lich su suot ca phien) va TRUOT tang tu 2
// len 24. Bo loc chong nhay LUI ma khong nghi toi cu nhay TIEN.
//
// Mot mau lech thu tu khong phai rac: no la dau hieu GOC THOI GIAN DA DOI.
// Co it nhat mot cho chac chan sinh ra no -- luc ClockSync chuyen tu "chua
// san sang" (dong ho host) sang "san sang" (dong ho MCU), hai goc khac nhau
// nen co mot buoc nhay, va khong ai bao dam no nhay ve phia nao.
//
// Lich su cu luc do het so sanh duoc. Xoa va dung lai tu mau nay: mat ~1 s
// du lieu, thay vi mat vinh vien.
if (gyro_n_ > 0) {
const GyroSample& prev = gyro_hist_[(gyro_n_ - 1) % kGyroHist];
if (SecondsBetween(stamp, prev.t) <= 0.0) {
stats_.gyro_out_of_order++;
VSLAM_WARN_THROTTLE(10.0,
"wheel_odom: dau thoi gian gyro nhay "
<< SecondsBetween(stamp, prev.t) * 1e3 << " ms so voi mau truoc -- "
"xoa lich su va dung lai. Lan thu " << stats_.gyro_out_of_order
<< ". Nghi nguon dau thoi gian (ClockSync) khong on dinh.");
gyro_n_ = 0;
}
}
gyro_hist_[gyro_n_ % kGyroHist] = GyroSample{stamp, wz};
++gyro_n_;
} }
void WheelOdometry::SetPose(const Pose2D& p) { void WheelOdometry::SetPose(const Pose2D& p) {
@@ -27,6 +203,18 @@ void WheelOdometry::Reset() {
x_ = y_ = theta_ = 0.0; x_ = y_ = theta_ = 0.0;
slip_metric_ = 0.0; slip_metric_ = 0.0;
slipping_ = false; slipping_ = false;
// Lich su PHAI xoa: sau reset (nhay thoi gian, replay) cac mau cu tro thanh
// vo nghia, va noi suy tren chung cho ra mot so troi khong ai kiem duoc.
gyro_n_ = 0;
omega_n_ = 0;
enc_theta_ = 0.0;
bias_sum_ = 0.0;
bias_n_ = 0;
for (size_t i = 0; i < kLagBins; ++i) {
lag_sse_[i] = 0.0;
lag_cnt_[i] = 0;
}
lag_n_ = 0;
stats_ = WheelOdometryStats{}; stats_ = WheelOdometryStats{};
} }
@@ -63,19 +251,168 @@ bool WheelOdometry::Update(UnixTime stamp, double pos_l, double pos_r,
const double d_theta = (d_r - d_l) / cfg_.wheel_separation; const double d_theta = (d_r - d_l) / cfg_.wheel_separation;
// --------- Phat hien truot --------- // --------- Phat hien truot ---------
// So gyro voi encoder tai CUNG MOT THOI DIEM VAT LY, bang noi suy.
//
// Truoc day so thang `omega_encoder` voi `gyro_z_` moi nhat -- hai thoi diem
// khac nhau. Luc robot dang doi toc do quay, chenh lech thuan tuy do lech
// dau thoi gian la alpha * lech_t, va no da do duoc 0.20-0.22 rad/s tren
// robot nay: dung bang slip_omega_threshold, nen bao TRUOT ma san khong he
// tron. Bon lan bao truot deu roi vao luc chuyen tiep, va hai trong so do
// encoder doc IT hon gyro -- truot banh khong tao ra duoc dau do, truot lam
// encoder doc NHIEU hon su that.
const double omega_encoder = d_theta / dt; const double omega_encoder = d_theta / dt;
slip_metric_ = 0.0; slip_metric_ = 0.0;
slipping_ = false; slipping_ = false;
// ---- May do do tre ----
// Chay BAT KE mcu.imu_lag_sec da dat hay chua: sau khi bu dung, no phai bao
// ~0 ms. Do la cach TU KIEM CHUNG -- neu van bao XX ms nhu truoc khi bu thi
// mo hinh tre sai, biet ngay chu khong phai doan.
//
// Danh gia tai `t_ref` lui ve qua khu, KHONG tai `stamp` -- xem
// kLagEvalDelaySec trong header.
enc_theta_ += d_theta;
omega_hist_[omega_n_ % kOmegaHist] =
OmegaSample{stamp, omega_encoder, enc_theta_};
++omega_n_;
const UnixTime t_ref = stamp - Duration::fromSec(kLagEvalDelaySec);
double w_ref = 0.0;
if (OmegaEncoderAt(t_ref, &w_ref)) {
for (size_t i = 0; i < kLagBins; ++i) {
const double tau = kLagStepSec * (static_cast<double>(i) -
static_cast<double>(kLagZeroBin));
double g = 0.0;
if (!GyroAt(t_ref + Duration::fromSec(tau), &g, /*require_bracket=*/true)) {
continue;
}
const double e = w_ref - g;
lag_sse_[i] += e * e;
++lag_cnt_[i];
}
}
if (++lag_n_ % 500 == 0) {
const double lag = estimated_imu_lag_sec();
if (!std::isnan(lag)) {
VSLAM_INFO("wheel_odom/lag: tot nhat " << lag * 1000.0 << " ms tren "
<< lag_n_ << " mau. Cong vao mcu.imu_lag_sec roi chay lai -- "
"lan sau phai bao ~0 ms. Chi co nghia neu da lai VAO RA CUA.");
}
}
const bool imu_fresh = const bool imu_fresh =
have_imu_ && (SecondsBetween(stamp, last_imu_time_) < cfg_.imu_timeout); have_imu_ && (SecondsBetween(stamp, last_imu_time_) < cfg_.imu_timeout);
if (imu_fresh) { if (imu_fresh) {
slip_metric_ = std::fabs(omega_encoder - gyro_z_); // ---- So CUNG BANG THONG ----
slipping_ = slip_metric_ > cfg_.slip_omega_threshold; // Gyro 10 Hz bao TRUNG BINH tren 100 ms; encoder bao tuc thoi tren 20 ms.
// Luc robot doi toc do quay, hai thu nay lech chung ~alpha*T/2 ma KHONG
// ben nao sai ca -- do la khac biet bang thong, dich dau thoi gian khong
// chua duoc.
//
// Do duoc tren robot nay sau khi da sua xong dinh thoi (`wheel_odom/lag`
// bao 0 ms): van con 7 lan bao truot, lech deu ~0.21 = alpha 5 rad/s^2
// nhan T/2. Va 5 trong 7 lan encoder doc IT hon gyro, ma truot banh lam
// encoder doc NHIEU hon su that -- dau do loai truot.
//
// Danh gia lui mot chu ky gyro de co du lieu ca hai phia `t_ref`.
//
// ⚠️ Cai gia: trung binh hoa cung lam mo TRUOT THAT ngan hon mot chu ky
// gyro, va lam viec phat hien tre them chung ay. Truot tren san tron keo
// dai lau hon nhieu nen doi duoc, nhung day la danh doi co that.
const double period = GyroPeriodSec();
double w_enc = omega_encoder;
double g = gyro_z_;
// Lui 1.5 chu ky chu khong phai 1.
//
// Voi 1 chu ky thi `t_ref` co tuoi dung bang T, trong khi mau gyro moi nhat
// co tuoi bat ky trong [0, T]. Chi can mot mau gyro den tre chut la `t_ref`
// roi ra SAU mau moi nhat va het kep duoc. Do duoc: `[tho:G]` 9 lan, voi
// T = 0.1002 s.
//
// 1.5 chu ky cho `t_ref` nam giua mau moi nhat va mau ke truoc trong moi
// truong hop binh thuong. Cai gia la phat hien truot tre them nua chu ky
// (~50 ms) -- khong dang ke voi mot tin hieu chi de nang covariance.
//
// Phep so van dung: ca hai ben deu lay tai `t_ref`, chi la doc tre hon.
const UnixTime t_ref = stamp - Duration::fromSec(period * 1.5);
// Ghi ro LY DO khi phai lui ve so tho. Mot chu "[tho]" tron khong du: da
// mat mot vong do-sua-chay vi no chi noi "that bai" chu khong noi o dau,
// va ba nhanh duoi day can ba cach sua khac han nhau.
const char* why = "";
bool matched = false;
if (!(period > 0.0)) {
why = "[tho:P]"; // chua du 8 mau gyro de do chu ky
} else if (!OmegaEncoderMean(t_ref - Duration::fromSec(period * 0.5),
t_ref + Duration::fromSec(period * 0.5),
&w_enc)) {
why = "[tho:E]"; // thieu mau encoder trong cua so
} else if (!GyroAt(t_ref, &g, /*require_bracket=*/true)) {
why = "[tho:G]"; // khong co mau gyro hai ben t_ref
} else {
matched = true;
}
if (!matched) {
// Chua du lich su (vai chu ky dau, hoac sau Reset). Lui ve cach cu: kep
// gyro ve mau gan nhat va so voi omega tuc thoi.
stats_.slip_coarse_updates++;
w_enc = omega_encoder;
g = gyro_z_;
GyroAt(stamp, &g, /*require_bracket=*/false);
// ⚠️ So tho thi dung NGUONG CAO HON, khong phai tat han.
//
// Con so o nhanh nay khong dang tin: omega tuc thoi mang nguyen nhieu cua
// dau thoi gian encoder (+-20 ms tren nen 20 ms, xem OmegaEncoderMean),
// va gyro bi kep ve mau gan nhat, co the cu toi mot chu ky. Do duoc trong
// test: sai so len 0.78 rad/s ngay khi robot quay DEU.
//
// Nhung TAT han thi qua tay. Truot that co the rat lon -- da do tren robot
// mot su kien lech 2.258 rad/s (omega encoder -3.635 vs gyro -1.377), va
// bo qua no thi EKF nhan mot diem 11-sigma ma van tin.
//
// Nhieu cua nhanh tho co CHAN TREN do duoc (0.78), con truot that thi
// khong. Nen dat nguong cao hon han chan do: he so 8 cho 1.2 rad/s voi
// nguong 0.15 -- tren nhieu, duoi su kien that.
//
// Neu `[tho:*]` thanh thuong xuyen thi phat hien truot da gan nhu chet,
// nen canh bao.
const uint64_t upd = stats_.updates + 1;
if (upd > 200 && stats_.slip_coarse_updates * 4 > upd) {
VSLAM_WARN_THROTTLE(30.0,
"wheel_odom: so THO o " << stats_.slip_coarse_updates << "/" << upd
<< " lan cap nhat -- phat hien truot dang gan nhu khong chay. "
"Xem ma [tho:P/E/G] trong dong dbg.");
}
}
const double d_omega = w_enc - g;
slip_metric_ = std::fabs(d_omega);
const double thr = matched ? cfg_.slip_omega_threshold
: cfg_.slip_omega_threshold * kCoarseSlipFactor;
slipping_ = slip_metric_ > thr;
// So lieu chan doan, KHONG loc theo nguong. Canh bao truot ben duoi chi in
// khi vuot nguong, nen moi dong log deu nam sat nguong -- cum quanh 0.20 la
// do NGUONG, khong phai do vat ly, va khong doc duoc gi tu do.
bias_sum_ += d_omega;
++bias_n_;
// In `w_enc` chu khong phai `omega_encoder`: day la con so THUC SU duoc
// dem so, va no la trung binh tren cua so gyro. In gia tri tuc thoi thi
// `enc - gyro` khong ra `lech`, va nguoi doc log se di tim mot bug khong
// ton tai.
VSLAM_INFO_THROTTLE(5.0, "wheel_odom/dbg: enc " << w_enc << " gyro " << g
<< " lech " << d_omega << " T=" << period << " " << why
<< (stats_.gyro_out_of_order ? " [lui]" : "")
<< " | tb "
<< (bias_sum_ / static_cast<double>(bias_n_))
<< " tren " << bias_n_ << " mau");
if (slipping_) { if (slipping_) {
stats_.slip_events++; stats_.slip_events++;
VSLAM_WARN_THROTTLE(2.0, "wheel_odom: nghi TRUOT BANH -- omega encoder " VSLAM_WARN_THROTTLE(2.0, "wheel_odom: nghi TRUOT BANH -- omega encoder "
<< omega_encoder << " vs gyro " << gyro_z_ << w_enc << " vs gyro " << g
<< " rad/s (lech " << slip_metric_ << " rad/s (lech " << slip_metric_
<< "). Nang covariance."); << "). Nang covariance.");
} }

View File

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

View File

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

View File

@@ -0,0 +1,95 @@
#ifndef VSLAM_SCAN_LEVELER_H
#define VSLAM_SCAN_LEVELER_H
// Bu nghieng scan LiDAR cho SLAM 2D tren doc.
//
// ================== VAN DE ==================
// RTAB-Map 2D coi moi diem scan nam tren MOT mat phang ngang. Tren doc thi sai
// theo hai kieu:
// 1. Than nghieng -> tia nghieng: tuong cach 2 m tren doc 15 do doc ra
// 2 / cos(15) = 2.07 m, va goc cua tia lech di (tia 45 do -> 46 do).
// 2. Tia CHAM SAN / MAT DOC: dung tren san phang truoc doc len, tia cham
// mat doc o 0.2165 / tan(goc) (tuong gia co dinh tren the gioi); dang
// xuong doc (chuc mui), tia cham san duoi chan doc.
//
// ================== CACH LAM ==================
// Moi tia: diem cham -> frame base_link (ngoai lai tinh) -> base_footprint DA
// CAN trong luc (TiltLift, CHUNG ham voi GravityAlign / CliffDetect) -> do cao
// h so voi mat dat duoi robot, va do cao tuyet doi H = z_robot + h.
// * Biet do cao san tai do (ElevationMap) va H - san < floor_margin -> tia
// cham san/doc -> BO (NaN).
// * Khong biet san va h < -below_ground -> diem THAP hon cho robot dung, tuc
// san duoi chan doc khi dang xuong -> BO.
// * Con lai: chieu xuong mat phang ngang, tinh lai khoang cach va goc tu goc
// LiDAR (vi tri TINH trong base_link -- RTAB-Map dat lai diem dung cho do),
// xep vao o goc gan nhat, giu tia gan nhat moi o.
// Tia bo thanh NaN ("khong do duoc"), KHONG phai inf ("trong toi range_max"):
// inf se xoa trang ca vung sau mat doc tren luoi 2D.
//
// ⚠️ GIOI HAN: tuong gia khi tien toi chan doc LEN chi bo duoc neu camera da
// thay mat doc (ElevationMap co o do). Re vao chan doc o goc hep / camera bi
// che thi tuong gia van con.
//
// Chi cap cho SLAM / dinh vi lai / canh lac. Lop AN TOAN van dung scan THO:
// heuristic o day khong bao gio duoc xoa mot vat can that khoi luong dung xe.
#include <cstdint>
#include "vslam/elevation_map.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct ScanLevelerConfig {
// Diem cao hon san da biet duoi nguong nay = cham san / mat doc.
double floor_margin = 0.08;
// Khong biet san: diem thap hon mat dat duoi robot qua nguong nay = san duoi
// chan doc.
double below_ground = 0.05;
};
struct ScanLevelStats {
uint64_t scans = 0;
uint64_t rays = 0; // tia huu han vao
uint64_t kept = 0;
uint64_t dropped_floor = 0; // cham san theo ElevationMap
uint64_t dropped_below = 0; // thap hon mat dat duoi robot
uint64_t rebinned = 0; // doi sang o goc khac sau khi chieu
};
// laser_to_base: base_link <- laser_link (tinh). roll/pitch: nghieng than
// (GravityAlign). odom: base_footprint trong odom; z_robot: do cao robot
// (HeightEstimator). em co the null.
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats);
// ================== CHINH MEO SCAN (deskew) ==================
// LiDAR QUAY chup tung tia o mot thoi diem khac nhau trong vong quet, con
// stamp la MOT thoi diem (luc het vong). Robot dang quay w thi tia chup truoc
// stamp `lag` giay da lech w * lag -- 0.8 rad/s, vong 40 ms: tia dau va tia
// cuoi lech 1.8 do, o 5 m la 16 cm.
//
// Vong quet bat dau o goc `start_rad` (khung laser) va di theo chieu `dir`
// (+1: goc TANG theo thoi gian, -1: goc GIAM), het mot vong trong `period_s`.
// LakiBeam: theta = (flip ? -a : a) + angle_offset, azimuth a tang tu 0 ->
// start = angle_offset, dir = flip ? -1 : +1. Chieu nay DO tren ban do that
// 28/09 + 01/10: dir -1 lam scan khop tot hon, +1 te hon.
struct SweepTiming {
double start_rad = 0.0;
int dir = -1;
double period_s = 0.04;
};
// Dua moi tia ve khung robot LUC STAMP: robot da quay them w * lag va tien
// v * lag (w rad/s, v m/s theo truc x than) sau khi tia duoc chup. Xep lai vao
// o goc gan nhat, giu tia gan nhat moi o; o khong con tia nao -> NaN. Tia khong
// huu han va sentinel cua sector mask (> range_max) giu nguyen o cu, nhu
// LevelScan.
void DeskewScan(const LaserScan& in, const Transform& laser_to_base, const SweepTiming& tm,
double w, double v, LaserScan* out);
} // namespace vslam
#endif // VSLAM_SCAN_LEVELER_H

View File

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

View File

@@ -72,7 +72,16 @@ PerceptionOutput PerceptionPipeline::Process(const Image& depth, const CameraInf
"cliff: bao VUC, ly do=" << out.cliff_detail "cliff: bao VUC, ly do=" << out.cliff_detail
<< (cr.judged ? " (thay vuc THAT)" << (cr.judged ? " (thay vuc THAT)"
: " (KHONG phan xet duoc -> fail_safe)") : " (KHONG phan xet duoc -> fail_safe)")
<< " -- mu lien tuc " << cr.bail_held << " s, n_cliff=" << cr.n_cliff); << " -- mu lien tuc " << cr.bail_held << " s, n_cliff=" << cr.n_cliff
// Tach LO khoi HUT. Diem khong co so do do sau bi tinh la ung vien
// vuc (cliff_detect.cc: "le ra phai thay san o day ma khong co so do
// nao") -- dung voi cau thang toi, nhung san phang KHONG VAN nhin o
// goc luot cung cho ra y het nhu vay, va pipeline.yaml da ghi ro dieu
// do. Gop hai thu vao mot con so thi khong the phan biet tu log, ma
// chung can hai cach sua khac han nhau.
<< " (lo=" << cr.n_hole << " hut=" << cr.n_drop
<< ", trong cua so=" << cr.n_inwin
<< ", san thay o " << cr.r_min << ".." << cr.r_max << " m)");
// Mat phang san khop duoc, quy ve he base. Hai so nay CHINH LA sai so // Mat phang san khop duoc, quy ve he base. Hai so nay CHINH LA sai so
// ngoai lai cua camera, nen in kem ca hieu chinh suy ra tu chung: // ngoai lai cua camera, nen in kem ca hieu chinh suy ra tu chung:

View File

@@ -0,0 +1,160 @@
#include "vslam/scan_leveler.h"
#include <cmath>
#include <limits>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/gravity_align.h"
namespace vslam {
namespace {
// Chi so tia cua goc `a` (rad) BAT KE quy uoc goc cua scan: LakiBeam that phat
// [0, 2pi) (angle_min = 0, lidar_core scan_conversion.cpp), sim va test phat
// [-pi, pi). Lay hieu goc THEO VONG TRON roi moi chia; -1 = ngoai FOV.
//
// Truoc day NormalizeAngle(a) ve [-pi, pi) roi tru angle_min = 0: moi tia nua
// -pi..0 ra chi so AM va bi BO, khong log nao bao. Ban do robot that tu 06/10
// (doc BAT mac dinh) chi con nua scan (0..+120 do), 325 diem / scan thay vi
// 620-730 (28/09, 01/10) -- sim khong thay vi scan sim la [-135, 135] do.
long RayIndex(double a, double angle_min, double inc, size_t n) {
const double two_pi = 2.0 * M_PI;
double rel = std::fmod(a - angle_min, two_pi);
if (rel * inc < 0.0) rel += std::copysign(two_pi, inc); // cung chieu quet
long j = std::lround(rel / inc);
// Goc ~2pi: tia dau (scan tron vong) hoac ngay truoc angle_min.
if (j >= static_cast<long>(n)) j -= std::lround(two_pi / std::fabs(inc));
return (j >= 0 && j < static_cast<long>(n)) ? j : -1;
}
} // namespace
void LevelScan(const LaserScan& in, const Transform& laser_to_base, double roll,
double pitch, double wheel_radius, const Pose2D& odom, double z_robot,
const ElevationMap* em, const ScanLevelerConfig& cfg, LaserScan* out,
ScanLevelStats* stats) {
ScanLevelStats local;
ScanLevelStats& st = stats != nullptr ? *stats : local;
st.scans++;
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f) return;
const float nan = std::numeric_limits<float>::quiet_NaN();
out->ranges.assign(n, nan);
if (!out->intensities.empty()) out->intensities.assign(n, 0.0f);
// base_footprint (can trong luc) <- laser_link.
const Transform fp_from_laser =
TransformCompose(TiltLift(roll, pitch, wheel_radius), laser_to_base);
// Goc LiDAR TINH tren mat phang ngang (RTAB-Map dat diem bang ngoai lai
// tinh, nen tinh lai khoang cach/goc tu dung goc do).
const double lx0 = laser_to_base.translation.x, ly0 = laser_to_base.translation.y;
const double laser_yaw = YawFromQuaternion(laser_to_base.rotation);
const double c_th = std::cos(odom.theta), s_th = std::sin(odom.theta);
// Luot 1: tia KHONG huu han va sentinel cua sector mask giu nguyen o cu.
// Sentinel (> range_max) = than robot bi cat -- khong tia nao duoc de len.
std::vector<char> masked(n, 0);
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (std::isnan(r)) continue;
if (std::isinf(r)) {
out->ranges[i] = r;
} else if (r > in.range_max) {
out->ranges[i] = r;
masked[i] = 1;
}
}
// Luot 2: tia huu han -> chieu, loc, xep lai.
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
st.rays++;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
const Point p = TransformPoint(fp_from_laser, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double h = p.z;
const double wx = odom.x + c_th * p.x - s_th * p.y;
const double wy = odom.y + s_th * p.x + c_th * p.y;
double floor = 0.0;
if (em != nullptr && em->FloorAt(wx, wy, &floor)) {
if (z_robot + h - floor < cfg.floor_margin) {
st.dropped_floor++;
continue;
}
} else if (h < -cfg.below_ground) {
st.dropped_below++;
continue;
}
const double dx = p.x - lx0, dy = p.y - ly0;
const double rh = std::hypot(dx, dy);
const long j = RayIndex(std::atan2(dy, dx) - laser_yaw, in.angle_min, in.angle_increment, n);
if (j < 0 || masked[static_cast<size_t>(j)]) continue;
if (static_cast<size_t>(j) != i) st.rebinned++;
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rh < slot) {
slot = static_cast<float>(rh);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
st.kept++;
}
}
void DeskewScan(const LaserScan& in, const Transform& laser_to_base, const SweepTiming& tm,
double w, double v, LaserScan* out) {
*out = in;
const size_t n = in.ranges.size();
if (n == 0 || in.angle_increment == 0.0f || !(tm.period_s > 0.0)) return;
const float nan = std::numeric_limits<float>::quiet_NaN();
out->ranges.assign(n, nan);
if (!out->intensities.empty()) out->intensities.assign(n, 0.0f);
// Tia KHONG huu han va sentinel cua sector mask giu nguyen o cu (nhu LevelScan).
std::vector<char> masked(n, 0);
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (std::isnan(r)) continue;
if (std::isinf(r)) {
out->ranges[i] = r;
} else if (r > in.range_max) {
out->ranges[i] = r;
masked[i] = 1;
}
}
const Transform laser_from_base = TransformInverse(laser_to_base);
const double two_pi = 2.0 * M_PI;
for (size_t i = 0; i < n; ++i) {
const float r = in.ranges[i];
if (!std::isfinite(r) || r > in.range_max) continue;
const double a = in.angle_min + static_cast<double>(i) * in.angle_increment;
// Phan vong DA quet truoc tia nay -> tia chup truoc stamp `lag` giay.
double f = std::fmod(tm.dir > 0 ? a - tm.start_rad : tm.start_rad - a, two_pi);
if (f < 0.0) f += two_pi;
const double lag = tm.period_s * (1.0 - f / two_pi);
const double dth = w * lag, dx = v * lag;
// Diem trong khung base LUC CHUP -> khung base LUC STAMP: robot da tien dx
// roi quay dth, nen diem tinh lui dx va xoay -dth.
const Point pb = TransformPoint(laser_to_base, Point{r * std::cos(a), r * std::sin(a), 0.0});
const double c = std::cos(dth), s = std::sin(dth);
const double qx = pb.x - dx, qy = pb.y;
const Point pl = TransformPoint(laser_from_base, Point{c * qx + s * qy, -s * qx + c * qy, pb.z});
const long j = RayIndex(std::atan2(pl.y, pl.x), in.angle_min, in.angle_increment, n);
if (j < 0 || masked[static_cast<size_t>(j)]) continue;
const double rr = std::hypot(pl.x, pl.y);
float& slot = out->ranges[static_cast<size_t>(j)];
if (!std::isfinite(slot) || rr < slot) {
slot = static_cast<float>(rr);
if (!out->intensities.empty() && i < in.intensities.size()) {
out->intensities[static_cast<size_t>(j)] = in.intensities[i];
}
}
}
}
} // namespace vslam

View File

@@ -210,7 +210,15 @@ SafetyOutput SafetyMonitor::Step(const SafetyInputs& in) {
if (out.us_min < cfg_.us_stop_distance) { if (out.us_min < cfg_.us_stop_distance) {
VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< " VSLAM_WARN_THROTTLE(1.0, "safety: sieu am " << out.us_min << " m (< "
<< cfg_.us_stop_distance << cfg_.us_stop_distance
<< ") -- co the la KINH. Dung."); << ") -- co the la KINH. Chan tien/lui, "
"xoay tai cho de thoat.");
// Chan TINH TIEN (robot that chi co ten us0..usN, khong biet huong tung
// dau do) nhung GIU angular: xoay tai cho khong dua than robot lai gan vat.
// Chan ca xoay la be tac -- mo phong 2026-09-28: sieu am 0.31 m < 0.40,
// robot dung im, khong lenh nao ra duoc.
out.cmd = Twist{};
out.cmd.angular.z = std::max(-cfg_.max_angular,
std::min(cfg_.max_angular, in.cmd->angular.z));
return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh"); return finish(SafetyState::kUsBlocked, "sieu am chan -- co the la kinh");
} }

View File

@@ -9,6 +9,7 @@ find_package(yaml-cpp REQUIRED)
vslam_add_library(vslam_sim vslam_add_library(vslam_sim
PUBLIC_HDRS PUBLIC_HDRS
sim_source.h sim_source.h
sim_camera_renderer.h
occupancy_map_io.h occupancy_map_io.h
gazebo_world.h gazebo_world.h
PUBLIC_DEPS PUBLIC_DEPS

View File

@@ -57,8 +57,17 @@ struct WorldModel {
// `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu // `CGMClassic` mot minh ra bao loi 239 x 111 m, va ca the gioi phinh tu
// 25x51 m len 263x146 m. // 25x51 m len 263x146 m.
double sx = 1.0, sy = 1.0, sz = 1.0; double sx = 1.0, sy = 1.0, sz = 1.0;
// Model DIA HINH: mat robot di LEN duoc (san, doc, chieu nghi), khong phai
// vat can. Nhan bang TEN model (`kTerrainModelPrefix`), KHONG bang phap
// tuyen: mat ban, mat giuong, mat ghe cung huong len, va lay theo phap
// tuyen la cho robot leo len ban.
bool terrain = false;
}; };
// Model co ten bat dau bang chuoi nay la dia hinh. Xem `WorldModel::terrain`.
constexpr const char* kTerrainModelPrefix = "vslam_terrain_";
struct GazeboWorld { struct GazeboWorld {
std::string world_path; std::string world_path;
std::vector<WorldModel> models; std::vector<WorldModel> models;
@@ -80,9 +89,13 @@ StatusResponse LoadGazeboWorld(const std::string& world_path,
// Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D. // Raster hoa mesh VA CHAM cua world thanh luoi chiem dung 2D.
// //
// Chi lay tam giac nam trong dai do cao [z_min, z_max] so voi SAN: do la dai // Chi lay tam giac nam trong dai do cao [z_min, z_max] tinh tu MAT SAN CUC BO
// ma LiDAR 2D thuc su quet. Lay het moi do cao se bien ca mat san thanh vat // cua tung o: do la dai ma LiDAR 2D thuc su quet. Lay het moi do cao se bien
// can, va lay qua cao se bo lot ban ghe. // ca mat san thanh vat can, va lay qua cao se bo lot ban ghe.
//
// World khong co model dia hinh thi mat san o moi o la 0 -- dung y het truoc
// day. Co dia hinh (san cao, doc) thi dai z TRUOT theo san: mot cai tu dung
// tren san tang 2 cao 1.5 m van la vat can, va mat doc KHONG thanh tuong.
// //
// `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met. // `resolution` met/o. `pad` la vien trong them quanh bao loi, tinh bang met.
struct WorldRasterOptions { struct WorldRasterOptions {
@@ -92,10 +105,28 @@ struct WorldRasterOptions {
double pad = 1.0; double pad = 1.0;
}; };
// Dia hinh rut tu world, cung kich thuoc va goc voi luoi.
struct WorldTerrain {
// Do cao mat tren cua dia hinh tai TAM moi o (m, he world). O khong co dia
// hinh = 0. Nhieu tam giac chong nhau thi lay cao nhat (mat tren).
std::vector<float> floor_z;
// Dinh cua vat can cao nhat trong moi o bi chiem (m, he world); 0 = o
// trong. Cho phep raycast 3D biet tuong cao toi dau thay vi gia dinh mot
// chieu cao chung.
std::vector<float> wall_top;
size_t terrain_cells = 0; // so o co dia hinh; 0 = world phang
float floor_min = 0.0f, floor_max = 0.0f;
};
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world, StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
OccupancyGrid* out); OccupancyGrid* out);
// Nhu tren, va tra them dia hinh. `terrain` co the null.
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out, WorldTerrain* terrain);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Chi muc doan 2D, de raycast trung MAT TUONG chu khong trung bien o // Chi muc doan 2D, de raycast trung MAT TUONG chu khong trung bien o
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -135,10 +166,15 @@ struct WorldSegments {
// LiDAR do duoc phai la thu robot dam vao. Vai model trong bo nay co hull va // LiDAR do duoc phai la thu robot dam vao. Vai model trong bo nay co hull va
// cham don gian hoa khac han mesh hien thi (do duoc: PatientWheelChair, // cham don gian hoa khac han mesh hien thi (do duoc: PatientWheelChair,
// nursesstation_01), va Gazebo cung hanh xu y het. // nursesstation_01), va Gazebo cung hanh xu y het.
//
// Model dia hinh khong sinh doan nao (no la san, khong phai tuong). `floor_z`
// (tu `WorldTerrain`, cung kich thuoc `grid`) dua dai z ve mat san cuc bo;
// null = san phang o 0, y het truoc day.
StatusResponse BuildWorldSegments(const GazeboWorld& world, StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
const OccupancyGrid& grid, const OccupancyGrid& grid,
WorldSegments* out); WorldSegments* out,
const std::vector<float>* floor_z = nullptr);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D // Xuat hinh hoc cho khung 3D

View File

@@ -0,0 +1,51 @@
#ifndef VSLAM_SIM_CAMERA_RENDERER_H
#define VSLAM_SIM_CAMERA_RENDERER_H
// Ve anh camera cho bo mo phong.
//
// Interface nay KHONG phu thuoc do hoa: vslam_sim chi biet no, con cai dat GPU
// (EGL + OpenGL ES, texture that cua model) nam o lib TUY CHON vslam_sim_gl.
// Nho vay bo mo phong van build va chay tren Jetson / CI khong co GPU -- khi
// khong co renderer thi camera mo phong ve depth bang raycast CPU nhu cu va
// khong co anh IR.
#include <cstdint>
#include <string>
#include <vector>
namespace vslam {
// Tu the va noi suy cua MOT khung anh.
//
// Frame QUANG HOC theo quy uoc anh (giong RealSense va depth cua sim): +X
// phai, +Y xuong, +Z toi truoc. Pixel (u, v) co TAM tai toa do nguyen, kieu
// OpenCV: tia qua pixel u di theo ((u - cx) / fx, (v - cy) / fy, 1).
struct SimCameraView {
// Hang-chinh. Cot j la truc j cua frame quang hoc, viet trong world.
double R_wc[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
double t_wc[3] = {0, 0, 0}; // tam camera trong world, m
double fx = 0, fy = 0, cx = 0, cy = 0;
int width = 0, height = 0;
double near_m = 0.05, far_m = 30.0;
};
class SimCameraRenderer {
public:
virtual ~SimCameraRenderer() = default;
// Ve mot khung. `ir`: width*height byte, anh xam, HANG TREN CUNG TRUOC.
// `depth_z`: width*height float, Z-DEPTH (hinh chieu len truc quang) theo
// met; 0 = tia khong trung gi. Tra false neu khong ve duoc.
//
// ⚠️ Context GPU gan voi LUONG tao ra no: moi lan goi phai tren CUNG mot
// luong (luong vong mo phong).
virtual bool Render(const SimCameraView& view, std::vector<uint8_t>* ir,
std::vector<float>* depth_z) = 0;
// Mo ta ngan cho log, vd "NVIDIA GeForce RTX 4060 (EGL, GLES 3.2)".
virtual std::string Describe() const = 0;
};
} // namespace vslam
#endif // VSLAM_SIM_CAMERA_RENDERER_H

View File

@@ -35,12 +35,14 @@
// co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va // co ban do do cao san nen cliff_detect kiem duoc), nghieng than bac hai, va
// toan bo duong ong du lieu. // toan bo duong ong du lieu.
#include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include "vslam/clock.h" #include "vslam/clock.h"
#include "vslam/gazebo_world.h" #include "vslam/gazebo_world.h"
#include "vslam/sim_camera_renderer.h"
#include "vslam/driver_interfaces.h" #include "vslam/driver_interfaces.h"
#include "vslam/vslam_common.h" #include "vslam/vslam_common.h"
@@ -184,10 +186,37 @@ struct SimConfig {
// docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that". // docs/SIM_VS_REAL.md cu phai ghi "kinh phai kiem bang du lieu that".
double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan double glass_lidar_pass_rate = 1.0; // 1.0 = xuyen hoan toan
// Buoc VAT LY cua bo mo phong, va (mac dinh) tan so phat IMU.
double imu_rate_hz = 200.0; double imu_rate_hz = 200.0;
double gyro_noise_stddev = 4.9e-4; double gyro_noise_stddev = 4.9e-4;
double accel_noise_stddev = 6.9e-3; double accel_noise_stddev = 6.9e-3;
// ================== MO HINH IMU ==================
// kLegacy: cong thuc cu -- gia toc doc than + huong tam, gyro tu lo xo (va
// toc do doi nghieng do dia hinh). Giu nguyen tung byte ban ghi cu.
// kKinematic: gyro va gia toc ke tinh TU quy dao 6-DoF that cua DIEM DAT
// IMU (dao ham tu the, dao ham bac hai vi tri, cong trong luc). Tich phan
// IMU khop dung quy dao -- dieu kien toi thieu de thu VIO tren doc.
// kAuto: kKinematic khi dia hinh 3D bat, kLegacy khi khong.
enum class ImuModel { kAuto, kLegacy, kKinematic };
ImuModel imu_model = ImuModel::kAuto;
// Tan so PHAT IMU, Hz. 0 = moi buoc vat ly, nhu cu. Buoc vat ly van theo
// `imu_rate_hz`: ha tan so phat de giong WT61PC (10 Hz) khong keo ca dong
// hoc, LiDAR va camera xuong theo.
double imu_output_hz = 0.0;
// Mau phat ra la so do CU hon stamp bao nhieu giay (loc trong cam bien +
// truyen). Driver that tru `imu_lag_sec`; phan lech con lai la sai so dong
// bo camera-IMU ma VIO phai chiu.
double imu_delay_sec = 0.0;
// --- Chi mo hinh kKinematic (dung RNG RIENG, khong xao chuoi nhieu cu) ---
double gyro_bias_sigma = 0.0; // rad/s, sigma bias DAU moi truc
double accel_bias_sigma = 0.0; // m/s^2
double gyro_bias_rw = 0.0; // rad/s/sqrt(s), bias troi ngau nhien
double accel_bias_rw = 0.0; // m/s^2/sqrt(s)
double imu_lpf_hz = 0.0; // loc thong thap bac 1 trong cam bien; 0 = tat
// Vi tri diem dat IMU so voi base_link (robot.yaml: imu_link).
double imu_x = 0.0, imu_y = 0.0, imu_z = 0.06;
// ================== NGHIENG THAN ROBOT ================== // ================== NGHIENG THAN ROBOT ==================
// Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG, // Robot that co giam xoc: tang toc lam no NGOC LEN, phanh lam no CHUI XUONG,
// quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly // quay gap lam no NGHIENG ra ngoai. Gazebo mo phong dieu nay qua vat ly
@@ -210,6 +239,29 @@ struct SimConfig {
bool follow_terrain_slope = true; bool follow_terrain_slope = true;
double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc double wheelbase_for_slope = 0.44; // khoang cach truoc-sau de do doc
// ================== DIA HINH 3D (DOC, SAN NHIEU TANG) ==================
// Tat = hanh vi cu, giu NGUYEN tung byte: robot o z = 0, LiDAR quet mat
// phang ngang, camera o do cao co dinh. Do cao san chi de camera thay vuc.
//
// Bat thi robot di TREN mat san:
// * z = san duoi robot; roll/pitch theo dia hinh (truoc-sau, trai-phai);
// * lenh v la toc do BANH doc mat doc: di ngang v*cos(pitch), encoder
// dem quang duong doc doc;
// * LiDAR quet tia 3D nghieng theo than, cham doc/san/tuong that -- nen
// "tuong gia" o chan doc hien ra dung cho (0.2165 / tan(goc));
// * camera dat theo tu the 6-DoF; gyro thay toc do doi nghieng do dia hinh;
// * chenh san giua hai o ke nhau > max_step la vat can (mep bac, mep san
// cao) -- robot khong roi khoi mep doc.
//
// kAuto: bat khi world co model dia hinh (`vslam_terrain_*`).
enum class TerrainMode { kAuto, kOff, kOn };
TerrainMode terrain = TerrainMode::kAuto;
double max_step = 0.05; // m, chenh san toi da giua hai o ke nhau
// LiDAR nghieng theo CA lo xo giam xoc (mac dinh chi theo dia hinh). Than
// ngoc 2 do khi tang toc la tia cham san phang o ~6 m -- that, nhung lam
// nhieu moi bai do doc, nen de nut rieng.
bool lidar_follow_suspension = false;
double encoder_rate_hz = 50.0; double encoder_rate_hz = 50.0;
// ================== HAI LOAI TRUOT, RAT KHAC NHAU ================== // ================== HAI LOAI TRUOT, RAT KHAC NHAU ==================
@@ -251,6 +303,23 @@ struct SimConfig {
double speed = 1.0; double speed = 1.0;
}; };
// Tu the that 6-DoF cua robot (chi de danh gia).
//
// (x, y, z) la `base_footprint`: diem tren MAT SAN duoi tam robot, z la do
// cao san o do. roll/pitch la nghieng THAT cua than (dia hinh + lo xo), cung
// quy uoc voi `true_tilt` (pitch duong = mui chuc xuong).
struct SimPose3 {
double x = 0.0, y = 0.0, z = 0.0;
double roll = 0.0, pitch = 0.0, yaw = 0.0;
};
class RobotModel;
// Dien hinh hoc robot THAT (robot.yaml) vao cau hinh mo phong: banh, ban kinh
// than, vi tri LiDAR / camera / IMU. vslam_node va moi tool dung CHUNG ham
// nay -- sim va duong ong dung hai bo so khac nhau thi moi phep do deu do nham.
void SimConfigFromRobot(const RobotModel& robot, SimConfig* cfg);
// So huu ca bon nguon, y het ReplaySource. // So huu ca bon nguon, y het ReplaySource.
class SimSource { class SimSource {
public: public:
@@ -281,6 +350,29 @@ class SimSource {
// z am = bac hut xuong / cau thang di xuong. // z am = bac hut xuong / cau thang di xuong.
void SetFloorHeight(double x0, double y0, double x1, double y1, float z); void SetFloorHeight(double x0, double y0, double x1, double y1, float z);
// Doc TUYEN TINH theo x: san tang deu tu `z_at_x0` (o x0) toi `z_at_x1` (o
// x1), khong doi theo y. Cho bai kiem dia hinh 3D khong can file world.
void SetFloorRamp(double x0, double y0, double x1, double y1, float z_at_x0,
float z_at_x1);
// Dia hinh 3D dang bat chua (sau Open(); xem SimConfig::terrain).
bool terrain_active() const;
// Tu the that 6-DoF. CHI de danh gia, nhu `ground_truth()`.
SimPose3 ground_truth_3d() const;
// Goi lai voi tu the that moi `1 / rate_hz` giay mo phong (0 = moi buoc vat
// ly), tren luong chay Run()/RunFor(). Cho tool GHI su that vao ban ghi de
// cham diem offline -- KHONG duoc noi vao duong ong uoc luong.
using GroundTruthCallback = std::function<void(UnixTime, const SimPose3&)>;
void SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz = 0.0);
// Ve camera bang renderer ngoai (GPU, vslam_sim_gl): depth VA anh IR
// (`CameraFrame::infra1`) tu mesh co texture, thay raycast CPU. null = raycast
// CPU nhu cu, khong co anh IR. Goi truoc Run(); renderer duoc goi tren luong
// vong mo phong.
void SetCameraRenderer(std::shared_ptr<SimCameraRenderer> r);
// Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH. // Danh dau mot vung hinh chu nhat (toa do THE GIOI, met) la KINH.
// //
// O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can // O kinh phai la o BI CHIEM trong ban do (data >= 50) -- kinh la vat can

View File

@@ -155,6 +155,7 @@ StatusResponse LoadGazeboWorld(const std::string& world_path,
if (uri.empty()) { skip++; continue; } if (uri.empty()) { skip++; continue; }
m.model_name = uri.substr(uri.rfind('/') + 1); m.model_name = uri.substr(uri.rfind('/') + 1);
m.terrain = m.model_name.rfind(kTerrainModelPrefix, 0) == 0;
std::string root; std::string root;
const std::string dir = ResolveModelUri(uri, roots, &root); const std::string dir = ResolveModelUri(uri, roots, &root);
@@ -597,6 +598,12 @@ bool ReadObjTriangles(const std::string& path, std::vector<Tri>* out) {
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world, StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
OccupancyGrid* out) { OccupancyGrid* out) {
return RasterizeGazeboWorld(world, opt, out, nullptr);
}
StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out, WorldTerrain* terrain) {
if (!(opt.resolution > 0.0)) { if (!(opt.resolution > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument, return StatusResponse::Error(StatusCode::kInvalidArgument,
"resolution phai duong"); "resolution phai duong");
@@ -675,15 +682,70 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
// o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM. // o deu da biet -- cai chua duoc quet la chuyen cua ban do SLAM.
out->data.assign(static_cast<size_t>(w) * h, 0); out->data.assign(static_cast<size_t>(w) * h, 0);
// --- Luot 2: to tam giac trong dai do cao --- // --- Luot 1.5: dia hinh -> do cao san ---
//
// Do cao mat tren tai TAM o, noi suy trong tam giac. Tam giac dung thang
// (suy bien tren mat bang) la mat ben cua doc/bac, khong dinh nghia san nen
// bo qua. Chong nhau thi lay CAO NHAT: mot hop kin co ca mat day lan mat tren.
const size_t n_cells = static_cast<size_t>(w) * h;
std::vector<float> ground(n_cells, 0.0f);
std::vector<uint8_t> covered(n_cells, 0);
size_t n_terrain_models = 0, n_terrain_cells = 0;
for (const Loaded& L : loaded) {
if (!L.m->terrain) continue;
n_terrain_models++;
for (const Tri& t : L.tris) {
const double ax = t.x[0], ay = t.y[0];
const double bx = t.x[1], by = t.y[1];
const double cx = t.x[2], cy = t.y[2];
const double den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
if (std::fabs(den) < 1e-12) continue;
const int cx0 = std::max(0, static_cast<int>((std::min({ax, bx, cx}) - minx) / res));
const int cx1 = std::min(static_cast<int>(w) - 1,
static_cast<int>((std::max({ax, bx, cx}) - minx) / res));
const int cy0 = std::max(0, static_cast<int>((std::min({ay, by, cy}) - miny) / res));
const int cy1 = std::min(static_cast<int>(h) - 1,
static_cast<int>((std::max({ay, by, cy}) - miny) / res));
for (int gy = cy0; gy <= cy1; ++gy) {
for (int gx = cx0; gx <= cx1; ++gx) {
const double px = minx + (gx + 0.5) * res;
const double py = miny + (gy + 0.5) * res;
const double l1 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / den;
const double l2 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / den;
const double l3 = 1.0 - l1 - l2;
if (l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9) continue;
const float z = static_cast<float>(l1 * t.z[0] + l2 * t.z[1] + l3 * t.z[2]);
const size_t idx = static_cast<size_t>(gy) * w + gx;
if (!covered[idx]) {
covered[idx] = 1;
ground[idx] = z;
n_terrain_cells++;
} else if (z > ground[idx]) {
ground[idx] = z;
}
}
}
}
}
// O khong co dia hinh la san 0, nen min/max luon tinh ca 0. World phang:
// fmin = fmax = 0 va luot 2 duoi day y het truoc.
float fmin = 0.0f, fmax = 0.0f;
for (float f : ground) { fmin = std::min(fmin, f); fmax = std::max(fmax, f); }
// --- Luot 2: to tam giac VAT CAN trong dai do cao, tinh tu san cuc bo ---
std::vector<float> top(n_cells, 0.0f);
size_t n_used = 0; size_t n_used = 0;
for (const Loaded& L : loaded) { for (const Loaded& L : loaded) {
if (L.m->terrain) continue; // dia hinh la san, khong phai vat can
for (const Tri& t : L.tris) { for (const Tri& t : L.tris) {
// Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua: // Tam giac nam hoan toan ngoai dai thi bo. Cat dung tam giac la thua:
// mesh day dac nen mot tam giac bien bi bo van con hang xom phu. // mesh day dac nen mot tam giac bien bi bo van con hang xom phu.
//
// Day la phep loc THO theo dai cua ca ban do; dai dung cua tung o kiem
// ben duoi, theo san cua chinh o do.
const double tz0 = std::min({t.z[0], t.z[1], t.z[2]}); const double tz0 = std::min({t.z[0], t.z[1], t.z[2]});
const double tz1 = std::max({t.z[0], t.z[1], t.z[2]}); const double tz1 = std::max({t.z[0], t.z[1], t.z[2]});
if (tz1 < opt.z_min || tz0 > opt.z_max) continue; if (tz1 < fmin + opt.z_min || tz0 > fmax + opt.z_max) continue;
n_used++; n_used++;
// Bao loi cua tam giac, roi kiem tung o bang toa do trong tam. // Bao loi cua tam giac, roi kiem tung o bang toa do trong tam.
@@ -721,7 +783,13 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9; inside = l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9;
} }
if (inside) { if (inside) {
out->data[static_cast<size_t>(gy) * w + gx] = 100; const size_t idx = static_cast<size_t>(gy) * w + gx;
// Dai z cua RIENG o nay. World phang: san 0, trung phep loc tho
// o tren nen khong bo them o nao.
const double f = ground[idx];
if (tz1 < f + opt.z_min || tz0 > f + opt.z_max) continue;
out->data[idx] = 100;
if (tz1 > top[idx]) top[idx] = static_cast<float>(tz1);
} }
} }
} }
@@ -734,6 +802,18 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
<< minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri << minx << ", " << miny << "), " << n_mesh << " mesh, " << n_tri
<< " tam giac (" << n_used << " trong dai z [" << " tam giac (" << n_used << " trong dai z ["
<< opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem"); << opt.z_min << ", " << opt.z_max << "]), " << occ << " o bi chiem");
if (n_terrain_models > 0) {
VSLAM_INFO("world -> dia hinh: " << n_terrain_models << " model, "
<< n_terrain_cells << " o, san tu " << fmin << " den " << fmax
<< " m; dai z cua vat can tinh tu san cuc bo");
}
if (terrain != nullptr) {
terrain->floor_z = std::move(ground);
terrain->wall_top = std::move(top);
terrain->terrain_cells = n_terrain_cells;
terrain->floor_min = fmin;
terrain->floor_max = fmax;
}
return StatusResponse::Ok(); return StatusResponse::Ok();
} }
@@ -742,7 +822,8 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
StatusResponse BuildWorldSegments(const GazeboWorld& world, StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt, const WorldRasterOptions& opt,
const OccupancyGrid& grid, const OccupancyGrid& grid,
WorldSegments* out) { WorldSegments* out,
const std::vector<float>* floor_z) {
if (out == nullptr) { if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null"); return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
} }
@@ -759,6 +840,18 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
const double ox = out->origin_x, oy = out->origin_y; const double ox = out->origin_x, oy = out->origin_y;
const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height); const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height);
// San cuc bo tai mot diem, de dai z truot theo dia hinh. Khong co ban do
// san thi la 0 -- y het truoc.
const bool have_floor =
floor_z != nullptr && floor_z->size() == static_cast<size_t>(W) * H;
auto floor_at = [&](double x, double y) -> double {
if (!have_floor) return 0.0;
const int fx = static_cast<int>(std::floor((x - ox) / res));
const int fy = static_cast<int>(std::floor((y - oy) / res));
if (fx < 0 || fy < 0 || fx >= W || fy >= H) return 0.0;
return (*floor_z)[static_cast<size_t>(fy) * grid.width + fx];
};
// --- Gom doan tu canh cua tam giac trong dai z --- // --- Gom doan tu canh cua tam giac trong dai z ---
// //
// Lay CA BA canh cua moi tam giac. Canh nam trong long vat the (vd canh cua // Lay CA BA canh cua moi tam giac. Canh nam trong long vat the (vd canh cua
@@ -767,6 +860,7 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
std::map<std::string, std::vector<Tri>> cache; std::map<std::string, std::vector<Tri>> cache;
for (const WorldModel& m : world.models) { for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue; if (m.collision_obj.empty()) continue;
if (m.terrain) continue; // dia hinh la san: tia cham no o raycast 3D
auto it = cache.find(m.model_name); auto it = cache.find(m.model_name);
if (it == cache.end()) { if (it == cache.end()) {
std::vector<Tri> tris; std::vector<Tri> tris;
@@ -789,7 +883,8 @@ StatusResponse BuildWorldSegments(const GazeboWorld& world,
} }
const double zlo = std::min({Z[0], Z[1], Z[2]}); const double zlo = std::min({Z[0], Z[1], Z[2]});
const double zhi = std::max({Z[0], Z[1], Z[2]}); const double zhi = std::max({Z[0], Z[1], Z[2]});
if (zhi < opt.z_min || zlo > opt.z_max) continue; const double f = floor_at((X[0] + X[1] + X[2]) / 3.0, (Y[0] + Y[1] + Y[2]) / 3.0);
if (zhi < f + opt.z_min || zlo > f + opt.z_max) continue;
for (int e = 0; e < 3; ++e) { for (int e = 0; e < 3; ++e) {
const int a = e, b = (e + 1) % 3; const int a = e, b = (e + 1) % 3;
out->seg.push_back(static_cast<float>(X[a])); out->seg.push_back(static_cast<float>(X[a]));

View File

@@ -1,21 +1,54 @@
#include "vslam/sim_source.h" #include "vslam/sim_source.h"
#include <algorithm>
#include <atomic> #include <atomic>
#include <cmath> #include <cmath>
#include <deque>
#include <functional>
#include <mutex> #include <mutex>
#include <random> #include <random>
#include <thread> #include <thread>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/node_constants.h" #include "vslam/node_constants.h"
#include "vslam/occupancy_map_io.h" #include "vslam/occupancy_map_io.h"
#include "vslam/robot_model.h"
#include <limits> #include <limits>
namespace vslam { namespace vslam {
namespace { namespace {
// Raycast dia hinh 3D: chi noi suy san khi tia da xuong trong dai nay tren
// mat san cua o. Lon hon nhieu sai khac giua gia tri o va gia tri noi suy
// (o doc 30 do: < 1.5 cm), nho hon do cao LiDAR (0.2165 m).
constexpr double kSmoothFloorBand = 0.15;
// Ma tran xoay R = Rz(yaw) * Ry(pitch) * Rx(roll), REP-103: than -> the gioi.
// pitch DUONG = mui chuc xuong, roll DUONG = ben trai nhac len. Tinh MOT lan
// cho moi scan / moi khung anh, khong goi sin/cos cho tung tia.
struct Rot3 {
double m[9];
static Rot3 FromRPY(double roll, double pitch, double yaw) {
const double cr = std::cos(roll), sr = std::sin(roll);
const double cp = std::cos(pitch), sp = std::sin(pitch);
const double cy = std::cos(yaw), sy = std::sin(yaw);
Rot3 r;
r.m[0] = cy * cp; r.m[1] = cy * sp * sr - sy * cr; r.m[2] = cy * sp * cr + sy * sr;
r.m[3] = sy * cp; r.m[4] = sy * sp * sr + cy * cr; r.m[5] = sy * sp * cr - cy * sr;
r.m[6] = -sp; r.m[7] = cp * sr; r.m[8] = cp * cr;
return r;
}
void Apply(double x, double y, double z, double* ox, double* oy, double* oz) const {
*ox = m[0] * x + m[1] * y + m[2] * z;
*oy = m[3] * x + m[4] * y + m[5] * z;
*oz = m[6] * x + m[7] * y + m[8] * z;
}
};
// Bon lop nay la interface driver THAT, y het ReplaySource. vslam_node khong // Bon lop nay la interface driver THAT, y het ReplaySource. vslam_node khong
// phan biet duoc phan cung / file .vsr / mo phong. // phan biet duoc phan cung / file .vsr / mo phong.
@@ -185,10 +218,18 @@ struct SimSource::Impl {
double us_acc = 0.0, bump_acc = 0.0; double us_acc = 0.0, bump_acc = 0.0;
bool bumper_now = false; bool bumper_now = false;
// Bo dem anh depth, cap phat mot lan. Anh khong so huu bo nho (xem // Bo dem anh depth. Anh khong so huu bo nho (xem vslam_common.h), nen MOI
// vslam_common.h), nen bo dem nay phai song it nhat bang khung anh. // khung lay mot bo dem rieng tu pool va giu no qua keep_alive -- SlamLoop
std::vector<uint8_t> depth_buf; // giu khung moi nhat qua Rtabmap::process tren luong khac, va mot bo dem
uint32_t depth_w = 0, depth_h = 0; // dung chung se bi khung sau ghi de giua chung.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> depth_pool =
BufferPool<std::vector<uint8_t>>::Create(8);
// Renderer GPU tuy chon (SetCameraRenderer). null = raycast CPU, khong co IR.
std::shared_ptr<SimCameraRenderer> renderer;
std::vector<uint8_t> gl_ir;
std::vector<float> gl_depth;
bool gl_fail_logged = false;
std::shared_ptr<ReplayClock> clock; std::shared_ptr<ReplayClock> clock;
// Trang thai that cua robot. // Trang thai that cua robot.
@@ -204,6 +245,39 @@ struct SimSource::Impl {
double terrain_pitch = 0.0; // nghieng do DIA HINH, cong vao than double terrain_pitch = 0.0; // nghieng do DIA HINH, cong vao than
double last_accel = 0.0; double last_accel = 0.0;
// --- Dia hinh 3D (SimConfig::terrain). Tat thi khong truong nao duoi day
// duoc doc, va moi duong cu giu nguyen tung byte. ---
bool terrain_on = false; // chot o Open()
double ground_z = 0.0; // san duoi tam robot (base_footprint)
double terrain_roll = 0.0; // nghieng ngang do dia hinh
double terrain_pitch_rate = 0.0, terrain_roll_rate = 0.0;
// Goc dia hinh da co gia tri dau chua. Chua thi lan tinh dau KHONG sinh toc
// do goc -- neu khong, robot dat san tren doc se "quay" 10 do trong 5 ms.
bool terrain_ready = false;
bool steps_dirty = true; // san vua doi -> tinh lai mat na bac
std::vector<uint8_t> step_block; // o sat mep bac (chenh > max_step)
// Dinh vat can cao nhat moi o (he world, tu mesh). 0 = khong biet -> dung
// `wall_height` nhu cu.
std::vector<float> wall_top;
// --- IMU dong hoc (SimConfig::imu_model) va phat thua / tre ---
bool imu_kinematic = false; // chot o Open()
// RNG RIENG cho IMU dong hoc: dung chung `rng` se xao toan bo chuoi nhieu
// cua LiDAR/camera va moi ban ghi cu doi theo.
std::mt19937 imu_rng{1234};
Rot3 imu_R_prev{}; // tu the buoc truoc
double imu_p[3][3] = {}; // vi tri diem dat IMU: k-2, k-1, k
int imu_hist = 0; // so buoc da co lich su (toi da 3)
double imu_bg[3] = {0.0, 0.0, 0.0}, imu_ba[3] = {0.0, 0.0, 0.0};
bool imu_lpf_init = false;
double imu_lpf_w[3] = {0.0, 0.0, 0.0}, imu_lpf_f[3] = {0.0, 0.0, 0.0};
double imu_out_acc = 0.0;
std::deque<std::pair<double, ImuPtr>> imu_fifo; // (thoi diem DO, mau)
// --- Ground truth cho tool ghi ---
SimSource::GroundTruthCallback gt_cb;
double gt_period = 0.0, gt_acc = 0.0;
std::atomic<bool> stop{false}; std::atomic<bool> stop{false};
mutable std::mutex state_mu; mutable std::mutex state_mu;
Stats stats; Stats stats;
@@ -354,6 +428,82 @@ struct SimSource::Impl {
return inf; return inf;
} }
// Do cao san NOI SUY SONG TUYEN giua tam cac o (chi dia hinh 3D).
//
// Gia tri tung o la bac thang 5 cm: o doc 30 do moi o nhay 2.9 cm, va
// robot / tia doc san se thay rang cua thay vi mat doc. Ngoai ban do kep vao
// o bien -- robot khong ra duoc ngoai (va cham), con tia ra ngoai thi raycast
// da dung tu truoc.
double FloorAtSmooth(double wx, double wy) const {
if (floor_z.empty() || !std::isfinite(wx) || !std::isfinite(wy)) return 0.0;
const int W = static_cast<int>(map.width), H = static_cast<int>(map.height);
const double fx = std::min(
std::max((wx - map.origin.position.x) / map.resolution - 0.5, 0.0), W - 1.0);
const double fy = std::min(
std::max((wy - map.origin.position.y) / map.resolution - 0.5, 0.0), H - 1.0);
const int x0 = static_cast<int>(fx), y0 = static_cast<int>(fy);
const int x1 = std::min(x0 + 1, W - 1), y1 = std::min(y0 + 1, H - 1);
const double tx = fx - x0, ty = fy - y0;
auto at = [&](int cx, int cy) {
return static_cast<double>(
floor_z[static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx)]);
};
const double a = at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx;
const double b = at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx;
return a * (1.0 - ty) + b * ty;
}
// O nao sat mep bac -- chenh san voi mot o ke > max_step. Danh dau CA HAI
// phia mep, va CellBlocked() coi chung nhu tuong: robot khong leo duoc
// len bac, cung khong roi khoi mep san cao.
void RebuildStepMask() {
const uint32_t W = map.width, H = map.height;
step_block.assign(static_cast<size_t>(W) * H, 0);
const float lim = static_cast<float>(cfg.max_step);
size_t n = 0;
for (uint32_t cy = 0; cy < H; ++cy) {
for (uint32_t cx = 0; cx < W; ++cx) {
const size_t i = static_cast<size_t>(cy) * W + cx;
const float f = floor_z[i];
const bool step = (cx + 1 < W && std::fabs(floor_z[i + 1] - f) > lim) ||
(cx > 0 && std::fabs(floor_z[i - 1] - f) > lim) ||
(cy + 1 < H && std::fabs(floor_z[i + W] - f) > lim) ||
(cy > 0 && std::fabs(floor_z[i - W] - f) > lim);
if (step) { step_block[i] = 1; n++; }
}
}
steps_dirty = false;
VSLAM_DEBUG("sim: mat na bac: " << n << " o chenh > " << cfg.max_step << " m");
}
// z, pitch, roll do DIA HINH tai tu the hien tai, va toc do doi cua chung
// (cho gyro). Bon diem do: truoc/sau cach nhau `wheelbase_for_slope`,
// trai/phai cach nhau `wheel_separation`.
void UpdateTerrainPose(double dt) {
const double hl = cfg.wheelbase_for_slope / 2.0;
const double hw = cfg.wheel_separation / 2.0;
const double c = std::cos(yaw), s = std::sin(yaw);
const double ff = FloorAtSmooth(x + hl * c, y + hl * s);
const double fb = FloorAtSmooth(x - hl * c, y - hl * s);
const double fl = FloorAtSmooth(x - hw * s, y + hw * c);
const double fr = FloorAtSmooth(x + hw * s, y - hw * c);
// Doc len phia truoc -> mui ngoc len -> pitch AM (quy uoc cu). Ben TRAI
// cao hon -> roll DUONG (quay quanh +X dua +Y len).
const double np = -std::atan2(ff - fb, 2.0 * hl);
const double nr = std::atan2(fl - fr, 2.0 * hw);
if (terrain_ready && dt > 0.0) {
terrain_pitch_rate = (np - terrain_pitch) / dt;
terrain_roll_rate = (nr - terrain_roll) / dt;
} else {
terrain_pitch_rate = 0.0;
terrain_roll_rate = 0.0;
terrain_ready = true;
}
terrain_pitch = np;
terrain_roll = nr;
ground_z = FloorAtSmooth(x, y);
}
// Do cao san tai mot diem the gioi. Ngoai ban do coi nhu phang. // Do cao san tai mot diem the gioi. Ngoai ban do coi nhu phang.
float FloorAt(double wx, double wy) const { float FloorAt(double wx, double wy) const {
const int cx = static_cast<int>( const int cx = static_cast<int>(
@@ -567,7 +717,13 @@ struct SimSource::Impl {
// depth camera. Mot robot dich vu di vao cua kinh la truong hop that, // depth camera. Mot robot dich vu di vao cua kinh la truong hop that,
// va no la ly do nhanh US_BLOCKED cua FSM ton tai. // va no la ly do nhanh US_BLOCKED cua FSM ton tai.
if (map.data[idx] >= 50 && !(idx < glass.size() && glass[idx])) { if (map.data[idx] >= 50 && !(idx < glass.size() && glass[idx])) {
const double lo = fz, hi = fz + cfg.wall_height; const double lo = fz;
double hi = fz + cfg.wall_height;
// Dia hinh 3D: vat can cao dung bang mesh cua no. Tuong 4 m ben doc
// khong duoc thanh tuong 2 m chi vi san o day bang 0.
if (terrain_on && idx < wall_top.size() && wall_top[idx] > lo) {
hi = wall_top[idx];
}
if ((z_enter >= lo && z_enter <= hi) || (z_exit >= lo && z_exit <= hi) || if ((z_enter >= lo && z_enter <= hi) || (z_exit >= lo && z_exit <= hi) ||
(z_enter > hi && z_exit < lo) || (z_enter < lo && z_exit > hi)) { (z_enter > hi && z_exit < lo) || (z_enter < lo && z_exit > hi)) {
// Chi tinh chinh theo mat phang XY: tuong trong dai z la thang dung, // Chi tinh chinh theo mat phang XY: tuong trong dai z la thang dung,
@@ -581,8 +737,18 @@ struct SimSource::Impl {
// Cham san: tia tut xuong duoi mat san trong o nay. Noi suy tuyen tinh // Cham san: tia tut xuong duoi mat san trong o nay. Noi suy tuyen tinh
// giua hai dau o de khong luong tu hoa khoang cach theo kich thuoc o. // giua hai dau o de khong luong tu hoa khoang cach theo kich thuoc o.
const double gap_enter = z_enter - fz; //
const double gap_exit = z_exit - fz; // Dia hinh 3D: san tai hai dau o lay NOI SUY, de mat doc la mat phang
// chu khong phai bac thang. Chi tinh khi tia da xuong gan san -- tia
// LiDAR cach san 0.22 m bay qua hang tram o, va noi suy o moi o la
// phi.
double f_in = fz, f_out = fz;
if (terrain_on && std::min(z_enter, z_exit) < fz + kSmoothFloorBand) {
f_in = FloorAtSmooth(ox + dx * t_enter * res, oy + dy * t_enter * res);
f_out = FloorAtSmooth(ox + dx * t_exit * res, oy + dy * t_exit * res);
}
const double gap_enter = z_enter - f_in;
const double gap_exit = z_exit - f_out;
if (gap_enter > 0.0 && gap_exit <= 0.0) { if (gap_enter > 0.0 && gap_exit <= 0.0) {
const double frac = gap_enter / (gap_enter - gap_exit); const double frac = gap_enter / (gap_enter - gap_exit);
return (t_enter + frac * (t_exit - t_enter)) * res; return (t_enter + frac * (t_exit - t_enter)) * res;
@@ -614,8 +780,10 @@ struct SimSource::Impl {
cy >= static_cast<int>(map.height)) { cy >= static_cast<int>(map.height)) {
return true; return true;
} }
return map.data[static_cast<size_t>(cy) * map.width + const size_t idx = static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx);
static_cast<size_t>(cx)] >= 50; if (map.data[idx] >= 50) return true;
// Dia hinh 3D: mep bac / mep san cao cung chan nhu tuong.
return terrain_on && idx < step_block.size() && step_block[idx] != 0;
} }
// Kiem va cham: lay 8 diem tren vanh robot. // Kiem va cham: lay 8 diem tren vanh robot.
@@ -649,11 +817,24 @@ struct SimSource::Impl {
prev_v = v; prev_v = v;
// Tich phan pose THAT. // Tich phan pose THAT.
const double nx = x + v * std::cos(yaw) * dt; double nx, ny, nyaw;
const double ny = y + v * std::sin(yaw) * dt; if (terrain_on) {
const double nyaw = NormalizeAngle(yaw + w * dt); // Lenh v la toc do BANH, doc mat san: di NGANG v*cos(pitch). Than quay
// quanh truc z CUA NO (dang nghieng), nen huong tren mat bang doi
// w*cos(roll)/cos(pitch) -- bo qua thi sai 15% o doc 30 do.
const double ct = std::cos(terrain_pitch);
const double cr = std::cos(terrain_roll);
nx = x + v * ct * std::cos(yaw) * dt;
ny = y + v * ct * std::sin(yaw) * dt;
nyaw = NormalizeAngle(yaw + w * cr / std::max(ct, 0.1) * dt);
} else {
nx = x + v * std::cos(yaw) * dt;
ny = y + v * std::sin(yaw) * dt;
nyaw = NormalizeAngle(yaw + w * dt);
}
std::lock_guard<std::mutex> lk(state_mu); std::lock_guard<std::mutex> lk(state_mu);
if (terrain_on && steps_dirty) RebuildStepMask();
if (Collides(nx, ny)) { if (Collides(nx, ny)) {
// Dung tai cho. Robot that se truot va quay, nhung "dung han" la mo // Dung tai cho. Robot that se truot va quay, nhung "dung han" la mo
// hinh trung thuc hon voi mot robot dich vu co bumper cat nguon. // hinh trung thuc hon voi mot robot dich vu co bumper cat nguon.
@@ -690,7 +871,10 @@ struct SimSource::Impl {
roll += roll_rate * dt; roll += roll_rate * dt;
// Nghieng do DIA HINH: do chenh lech do cao san giua truoc va sau robot. // Nghieng do DIA HINH: do chenh lech do cao san giua truoc va sau robot.
if (cfg.follow_terrain_slope) { if (terrain_on) {
// Ca z, pitch va roll, voi toc do doi cho gyro.
UpdateTerrainPose(dt);
} else if (cfg.follow_terrain_slope) {
const double half = cfg.wheelbase_for_slope / 2.0; const double half = cfg.wheelbase_for_slope / 2.0;
const double fz = FloorAt(x + half * std::cos(yaw), y + half * std::sin(yaw)); const double fz = FloorAt(x + half * std::cos(yaw), y + half * std::sin(yaw));
const double bz = FloorAt(x - half * std::cos(yaw), y - half * std::sin(yaw)); const double bz = FloorAt(x - half * std::cos(yaw), y - half * std::sin(yaw));
@@ -728,6 +912,45 @@ struct SimSource::Impl {
right_rad += vr / cfg.wheel_radius * dt; right_rad += vr / cfg.wheel_radius * dt;
} }
// LiDAR tren dia hinh 3D: MOT mat phang quet gan cung vao than, nghieng
// theo dia hinh (va theo lo xo neu `lidar_follow_suspension`). Moi tia la
// tia 3D, cham tuong / vat can / MAT SAN that.
//
// Day la thu cho thay loi cua SLAM 2D tren doc: dung o san phang nhin vao
// chan doc goc t, tia ngang cham mat doc o 0.2165 / tan(t) -- mot "tuong"
// khong co that, va no lui dan khi robot tien len.
void FillScan3D(LaserScan* s) {
double rx, ry, rz, ryaw, rroll, rpitch;
{
std::lock_guard<std::mutex> lk(state_mu);
rx = x; ry = y; rz = ground_z; ryaw = yaw;
rroll = terrain_roll;
rpitch = terrain_pitch;
if (cfg.lidar_follow_suspension) { rroll += roll; rpitch += pitch; }
}
const Rot3 R = Rot3::FromRPY(rroll, rpitch, ryaw);
// Goc tia: base_footprint (tren san) + R * (lidar_x, 0, r_banh + lidar_z).
// `lidar_z` do tu TAM TRUC banh, nhu laser_link trong robot.yaml.
double ox, oy, oz;
R.Apply(cfg.lidar_x, 0.0, cfg.wheel_radius + cfg.lidar_z, &ox, &oy, &oz);
ox += rx; oy += ry; oz += rz;
std::normal_distribution<double> noise(0.0, cfg.lidar_noise_stddev);
for (uint32_t i = 0; i < cfg.lidar_samples; ++i) {
const double a = s->angle_min + i * s->angle_increment;
double dx, dy, dz;
R.Apply(std::cos(a), std::sin(a), 0.0, &dx, &dy, &dz);
const double r = RaycastDepth(ox, oy, oz, dx, dy, dz, cfg.lidar_range_max);
if (std::isinf(r)) {
s->ranges[i] = std::numeric_limits<float>::infinity();
} else {
const double rn = r + noise(rng);
s->ranges[i] = static_cast<float>(
rn < cfg.lidar_range_min ? cfg.lidar_range_min : rn);
}
}
}
LaserScanPtr MakeScan(UnixTime stamp) { LaserScanPtr MakeScan(UnixTime stamp) {
auto s = std::make_shared<LaserScan>(); auto s = std::make_shared<LaserScan>();
s->header.stamp = stamp; s->header.stamp = stamp;
@@ -742,6 +965,11 @@ struct SimSource::Impl {
s->range_max = static_cast<float>(cfg.lidar_range_max); s->range_max = static_cast<float>(cfg.lidar_range_max);
s->ranges.resize(cfg.lidar_samples); s->ranges.resize(cfg.lidar_samples);
if (terrain_on) {
FillScan3D(s.get());
return s;
}
double rx, ry, ryaw; double rx, ry, ryaw;
{ {
std::lock_guard<std::mutex> lk(state_mu); std::lock_guard<std::mutex> lk(state_mu);
@@ -776,24 +1004,25 @@ struct SimSource::Impl {
const uint32_t w = cfg.depth_width / dec; const uint32_t w = cfg.depth_width / dec;
const uint32_t h = cfg.depth_height / dec; const uint32_t h = cfg.depth_height / dec;
if (depth_w != w || depth_h != h) { // 16UC1. Vong lap ben duoi ghi MOI diem anh, nen khong can xoa truoc.
depth_w = w; auto buf = depth_pool->Acquire();
depth_h = h; buf->resize(static_cast<size_t>(w) * h * 2);
depth_buf.assign(static_cast<size_t>(w) * h * 2, 0); // 16UC1 std::vector<uint8_t>& depth_buf = *buf;
}
double rx, ry, ryaw; double rx, ry, rz, ryaw;
{ {
std::lock_guard<std::mutex> lk(state_mu); std::lock_guard<std::mutex> lk(state_mu);
rx = x; rx = x;
ry = y; ry = y;
rz = ground_z;
ryaw = yaw; ryaw = yaw;
} }
// Vi tri camera trong the gioi. // Vi tri camera trong the gioi. Dia hinh 3D tinh lai ben duoi, theo tu the
const double cx_w = rx + cfg.camera_x * std::cos(ryaw); // 6-DoF cua than.
const double cy_w = ry + cfg.camera_x * std::sin(ryaw); double cx_w = rx + cfg.camera_x * std::cos(ryaw);
const double cz_w = cfg.camera_z; double cy_w = ry + cfg.camera_x * std::sin(ryaw);
double cz_w = cfg.camera_z;
// Noi suy tu HFOV. Anh da decimate nen fx/fy tinh theo kich thuoc DA // Noi suy tu HFOV. Anh da decimate nen fx/fy tinh theo kich thuoc DA
// giam; binning trong CameraInfo bao cho consumer biet dieu do. // giam; binning trong CameraInfo bao cho consumer biet dieu do.
@@ -810,12 +1039,80 @@ struct SimSource::Impl {
std::lock_guard<std::mutex> lk(state_mu); std::lock_guard<std::mutex> lk(state_mu);
body_roll = roll; body_roll = roll;
body_pitch = pitch + terrain_pitch; body_pitch = pitch + terrain_pitch;
if (terrain_on) body_roll += terrain_roll;
} }
const double total_pitch = cfg.camera_pitch + body_pitch; const double total_pitch = cfg.camera_pitch + body_pitch;
const double cp = std::cos(total_pitch), sp = std::sin(total_pitch); const double cp = std::cos(total_pitch), sp = std::sin(total_pitch);
const double cr_b = std::cos(body_roll), sr_b = std::sin(body_roll); const double cr_b = std::cos(body_roll), sr_b = std::sin(body_roll);
const double cy_r = std::cos(ryaw), sy_r = std::sin(ryaw); const double cy_r = std::cos(ryaw), sy_r = std::sin(ryaw);
// Dia hinh 3D: than xoay du ba goc, camera chuc `camera_pitch` TREN than.
// (Duong cu cong camera_pitch vao pitch cua than va xoay roll truoc --
// chi dung khi roll = 0, du cho san phang.)
const Rot3 R_body = Rot3::FromRPY(body_roll, body_pitch, ryaw);
const double ccp = std::cos(cfg.camera_pitch), csp = std::sin(cfg.camera_pitch);
if (terrain_on) {
R_body.Apply(cfg.camera_x, 0.0, cfg.camera_z, &cx_w, &cy_w, &cz_w);
cx_w += rx;
cy_w += ry;
cz_w += rz;
}
// Huong (don vi) trong THE GIOI cua mot huong trong frame quang hoc.
// Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than,
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo than.
// Raycast CPU va renderer GPU dung CHUNG ham nay, nen tia cua hai duong
// trung nhau tung pixel.
auto to_world = [&](double bx0, double by0, double bz0, double* wx, double* wy,
double* wz) {
if (terrain_on) {
// Chuc camera tren than (quanh y than), roi xoay theo than.
const double mx = bx0 * ccp + bz0 * csp;
const double mz = -bx0 * csp + bz0 * ccp;
R_body.Apply(mx, by0, mz, wx, wy, wz);
} else {
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch).
const double by1 = by0 * cr_b - bz0 * sr_b;
const double bz1 = by0 * sr_b + bz0 * cr_b;
const double px = bx0 * cp + bz1 * sp;
*wz = -bx0 * sp + bz1 * cp;
const double py = by1;
*wx = px * cy_r - py * sy_r;
*wy = px * sy_r + py * cy_r;
}
};
// Renderer GPU: ve CA khung mot lan (depth + IR), vong lap ben duoi chi
// ap nhieu. Ve hong thi khung nay quay ve raycast CPU.
bool use_gl = false;
if (renderer) {
SimCameraView view;
// Cot j cua R_wc = truc j cua frame quang hoc trong world.
double ax[3][3];
to_world(0.0, -1.0, 0.0, &ax[0][0], &ax[0][1], &ax[0][2]); // +X quang
to_world(0.0, 0.0, -1.0, &ax[1][0], &ax[1][1], &ax[1][2]); // +Y quang
to_world(1.0, 0.0, 0.0, &ax[2][0], &ax[2][1], &ax[2][2]); // +Z quang
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) view.R_wc[i * 3 + j] = ax[j][i];
}
view.t_wc[0] = cx_w;
view.t_wc[1] = cy_w;
view.t_wc[2] = cz_w;
view.fx = fx;
view.fy = fy;
view.cx = ppx;
view.cy = ppy;
view.width = static_cast<int>(w);
view.height = static_cast<int>(h);
view.far_m = std::max(cfg.depth_far, 1.0) + 1.0;
use_gl = renderer->Render(view, &gl_ir, &gl_depth);
if (!use_gl && !gl_fail_logged) {
gl_fail_logged = true;
VSLAM_WARN("sim: renderer GPU ve hong -- camera quay ve raycast CPU, KHONG co anh IR");
}
}
// Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG // Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG
// CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap. // CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap.
std::uniform_real_distribution<double> uni01(0.0, 1.0); std::uniform_real_distribution<double> uni01(0.0, 1.0);
@@ -828,20 +1125,16 @@ struct SimSource::Impl {
const double oz = 1.0; const double oz = 1.0;
const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz); const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz);
// Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than, double d;
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo yaw. if (use_gl) {
const double bx0 = oz * inv, by0 = -ox * inv, bz0 = -oy * inv; // GPU tra thang Z-DEPTH; 0 = khong trung gi.
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch). const float zg = gl_depth[static_cast<size_t>(v) * w + u];
const double by1 = by0 * cr_b - bz0 * sr_b; d = zg > 0.0f ? static_cast<double>(zg) : std::numeric_limits<double>::infinity();
const double bz1 = by0 * sr_b + bz0 * cr_b; } else {
const double px = bx0 * cp + bz1 * sp; double wx, wy, pz;
const double pz = -bx0 * sp + bz1 * cp; to_world(oz * inv, -ox * inv, -oy * inv, &wx, &wy, &pz);
const double py = by1; d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
}
const double wx = px * cy_r - py * sy_r;
const double wy = px * sy_r + py * cy_r;
double d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense
// Depth dropout: D410 that mat diem o be mat toi, be mat bong, va o // Depth dropout: D410 that mat diem o be mat toi, be mat bong, va o
@@ -866,7 +1159,9 @@ struct SimSource::Impl {
// dung ra phang o z=0 bi cliff_detect khop thanh z0 = -0.254 m, // dung ra phang o z=0 bi cliff_detect khop thanh z0 = -0.254 m,
// doc +0.114 -- va 87/1903 tia trong cua so roi duoi nguong, tuc // doc +0.114 -- va 87/1903 tia trong cua so roi duoi nguong, tuc
// BAO VUC GIA tren san hoan toan phang, MAD 0.037 van lot cong. // BAO VUC GIA tren san hoan toan phang, MAD 0.037 van lot cong.
d *= inv; //
// GPU da tra Z-depth roi -- nhan them la sai lan nua.
if (!use_gl) d *= inv;
// Nhieu depth theo MO HINH STEREO, khong phai hang so. // Nhieu depth theo MO HINH STEREO, khong phai hang so.
// //
@@ -928,6 +1223,22 @@ struct SimSource::Impl {
img->format = PixelFormat::kMono16; img->format = PixelFormat::kMono16;
img->depth_scale = 0.001f; img->depth_scale = 0.001f;
img->data = depth_buf.data(); img->data = depth_buf.data();
img->keep_alive = buf;
if (use_gl) {
// Anh IR cung kich thuoc, cung K va cung stamp voi depth -- giong
// RealSense: hai anh IR va depth thang hang tung pixel.
auto ibuf = depth_pool->Acquire();
ibuf->assign(gl_ir.begin(), gl_ir.end());
auto ir = std::make_shared<Image>();
ir->header = img->header;
ir->width = w;
ir->height = h;
ir->step = w;
ir->format = PixelFormat::kMono8;
ir->data = ibuf->data();
ir->keep_alive = ibuf;
out->infra1 = ir;
}
out->header = img->header; out->header = img->header;
out->depth = img; out->depth = img;
@@ -966,6 +1277,14 @@ struct SimSource::Impl {
cur_rr = roll_rate; cur_rr = roll_rate;
cur_pr = pitch_rate; cur_pr = pitch_rate;
cur_accel = last_accel; cur_accel = last_accel;
if (terrain_on) {
// Than nghieng theo dia hinh thi gyro PHAI thay luc no nghieng --
// khong thi gia toc ke bao "dang tren doc" con gyro bao "chua he xoay",
// va moi bo loc (gravity_align, VIO) bi hai cam bien cai nhau.
cur_roll += terrain_roll;
cur_rr += terrain_roll_rate;
cur_pr += terrain_pitch_rate;
}
} }
// Con quay do van toc goc THAT tren ca ba truc. // Con quay do van toc goc THAT tren ca ba truc.
@@ -1005,6 +1324,169 @@ struct SimSource::Impl {
m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0]; m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0];
return m; return m;
} }
// IMU tinh TU quy dao that (SimConfig::ImuModel::kKinematic). Goi sau
// StepPhysics, MOI buoc vat ly -- lich su vi tri can deu buoc.
//
// gyro = Log(R_truoc^T R) / dt (van toc goc trong he THAN)
// accel = R^T (a + (0, 0, g)), a = sai phan lui bac hai vi tri diem dat IMU
//
// Tich phan nguoc (xoay gia toc ve the gioi bang tu the that, tru trong
// luc, tich phan hai lan) ra DUNG quy dao, sai so chi o muc lam tron. Mo
// hinh cu chi xap xi: thieu gia toc theo phuong dung khi len doc, thieu
// canh tay don cua diem dat IMU khi than nghieng.
// Tu the THAT va vi tri diem dat IMU o trang thai hien tai:
// base_footprint + R * (imu_x, imu_y, r_banh + imu_z).
void ImuTruth(Rot3* R, double p[3]) {
double rx, ry, rz, ryaw, rroll, rpitch;
{
std::lock_guard<std::mutex> lk(state_mu);
rx = x; ry = y; ryaw = yaw;
rz = terrain_on ? ground_z : 0.0;
rroll = roll + (terrain_on ? terrain_roll : 0.0);
rpitch = pitch + terrain_pitch;
}
*R = Rot3::FromRPY(rroll, rpitch, ryaw);
R->Apply(cfg.imu_x, cfg.imu_y, cfg.wheel_radius + cfg.imu_z, &p[0], &p[1], &p[2]);
p[0] += rx; p[1] += ry; p[2] += rz;
}
// Gieo lich su IMU tai tu the hien tai, robot coi nhu dang dung yen. Goi
// o Open(): mau dau tien phai mang CA chuyen dong cua buoc vat ly dau tien,
// khong thi tich phan IMU lech su that ngay tu dau.
void SeedImuHistory() {
double p[3];
ImuTruth(&imu_R_prev, p);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = p[j];
}
imu_hist = 1;
}
ImuPtr MakeImuKinematic(UnixTime stamp, double dt) {
Rot3 R;
double pnow[3];
ImuTruth(&R, pnow);
if (imu_hist == 0) SeedImuHistory();
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) imu_p[i][j] = imu_p[i + 1][j];
}
for (int j = 0; j < 3; ++j) imu_p[2][j] = pnow[j];
imu_hist = std::min(imu_hist + 1, 3);
double w[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
// Rr = R_truoc^T * R, roi Log() ve vector quay.
double Rr[9];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Rr[i * 3 + j] = imu_R_prev.m[0 * 3 + i] * R.m[0 * 3 + j] +
imu_R_prev.m[1 * 3 + i] * R.m[1 * 3 + j] +
imu_R_prev.m[2 * 3 + i] * R.m[2 * 3 + j];
}
}
const double c = std::max(-1.0, std::min(1.0, (Rr[0] + Rr[4] + Rr[8] - 1.0) / 2.0));
const double th = std::acos(c);
const double k = th < 1e-9 ? 0.5 : th / (2.0 * std::sin(th));
w[0] = k * (Rr[7] - Rr[5]) / dt;
w[1] = k * (Rr[2] - Rr[6]) / dt;
w[2] = k * (Rr[3] - Rr[1]) / dt;
}
imu_R_prev = R;
double a[3] = {0.0, 0.0, 0.0};
if (dt > 0.0) {
for (int j = 0; j < 3; ++j) {
a[j] = (imu_p[2][j] - 2.0 * imu_p[1][j] + imu_p[0][j]) / (dt * dt);
}
}
const double aw[3] = {a[0], a[1], a[2] + kGravity};
double f[3];
for (int i = 0; i < 3; ++i) {
f[i] = R.m[0 * 3 + i] * aw[0] + R.m[1 * 3 + i] * aw[1] + R.m[2 * 3 + i] * aw[2];
}
// Bias troi + nhieu trang.
std::normal_distribution<double> n01(0.0, 1.0);
const double sq = std::sqrt(std::max(dt, 0.0));
for (int i = 0; i < 3; ++i) {
if (cfg.gyro_bias_rw > 0.0) imu_bg[i] += cfg.gyro_bias_rw * sq * n01(imu_rng);
if (cfg.accel_bias_rw > 0.0) imu_ba[i] += cfg.accel_bias_rw * sq * n01(imu_rng);
w[i] += imu_bg[i];
f[i] += imu_ba[i];
if (cfg.gyro_noise_stddev > 0.0) w[i] += cfg.gyro_noise_stddev * n01(imu_rng);
if (cfg.accel_noise_stddev > 0.0) f[i] += cfg.accel_noise_stddev * n01(imu_rng);
}
// Loc trong cam bien (WT61PC co loc noi): lam tre va lam mem tin hieu.
if (cfg.imu_lpf_hz > 0.0 && dt > 0.0) {
const double al = dt / (dt + 1.0 / (2.0 * M_PI * cfg.imu_lpf_hz));
if (!imu_lpf_init) {
for (int i = 0; i < 3; ++i) { imu_lpf_w[i] = w[i]; imu_lpf_f[i] = f[i]; }
imu_lpf_init = true;
}
for (int i = 0; i < 3; ++i) {
imu_lpf_w[i] += al * (w[i] - imu_lpf_w[i]);
imu_lpf_f[i] += al * (f[i] - imu_lpf_f[i]);
w[i] = imu_lpf_w[i];
f[i] = imu_lpf_f[i];
}
}
auto m = std::make_shared<Imu>();
m->header.stamp = stamp;
m->header.frame_id = kImuFrame;
m->angular_velocity.x = w[0];
m->angular_velocity.y = w[1];
m->angular_velocity.z = w[2];
m->linear_acceleration.x = f[0];
m->linear_acceleration.y = f[1];
m->linear_acceleration.z = f[2];
m->orientation_covariance[0] = -1.0; // khong co orientation
const double gv = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev;
const double av = cfg.accel_noise_stddev * cfg.accel_noise_stddev;
m->angular_velocity_covariance[0] = gv;
m->angular_velocity_covariance[4] = gv;
m->angular_velocity_covariance[8] = gv;
m->linear_acceleration_covariance[0] = av;
m->linear_acceleration_covariance[4] = av;
m->linear_acceleration_covariance[8] = av;
return m;
}
// Phat mau IMU theo tan so phat va do tre. Tra true neu da phat.
//
// Mac dinh (imu_output_hz = 0, imu_delay_sec = 0): phat MOI mau ngay khi do,
// y het truoc. Co tre: mau phat luc `now` la mau DO tai `now - delay`, mang
// stamp `now` -- dung cai driver that thay khi dong dau bang gio nhan.
bool EmitImu(UnixTime now, ImuPtr meas, double dt) {
if (cfg.imu_output_hz <= 0.0 && cfg.imu_delay_sec <= 0.0) {
mcu.PushImu(std::move(meas));
return true;
}
const double t = sim_elapsed;
imu_fifo.emplace_back(t, std::move(meas));
imu_out_acc += dt;
const double period = cfg.imu_output_hz > 0.0 ? 1.0 / cfg.imu_output_hz : dt;
if (imu_out_acc + 1e-9 < period) {
// Khong de hang doi phinh khi tan so phat thap: giu toi da 2 s.
while (imu_fifo.size() > 1 && imu_fifo.front().first < t - cfg.imu_delay_sec - 2.0) {
imu_fifo.pop_front();
}
return false;
}
imu_out_acc -= period;
ImuPtr pick;
const double want = t - cfg.imu_delay_sec;
while (!imu_fifo.empty() && imu_fifo.front().first <= want + 1e-9) {
pick = imu_fifo.front().second;
imu_fifo.pop_front();
}
if (!pick) return false; // vua khoi dong, chua du tre
auto out = std::make_shared<Imu>(*pick);
out->header.stamp = now;
mcu.PushImu(std::move(out));
return true;
}
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -1017,18 +1499,21 @@ StatusResponse SimSource::Open() {
// chuoi do phai giong nhau giua hai lan ghi cung mot kich ban. // chuoi do phai giong nhau giua hai lan ghi cung mot kich ban.
impl_->rng.seed(impl_->cfg.seed); impl_->rng.seed(impl_->cfg.seed);
WorldTerrain terr;
if (!impl_->cfg.world_path.empty()) { if (!impl_->cfg.world_path.empty()) {
const StatusResponse st = LoadGazeboWorld( const StatusResponse st = LoadGazeboWorld(
impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world); impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world);
if (!st.ok()) return st; if (!st.ok()) return st;
WorldRasterOptions wo; WorldRasterOptions wo;
const StatusResponse rs = RasterizeGazeboWorld(impl_->world, wo, &impl_->map); const StatusResponse rs =
RasterizeGazeboWorld(impl_->world, wo, &impl_->map, &terr);
if (!rs.ok()) return rs; if (!rs.ok()) return rs;
// Chi muc doan 2D, de khoang cach tra ve trung MAT TUONG chu khong trung // Chi muc doan 2D, de khoang cach tra ve trung MAT TUONG chu khong trung
// bien o. Khong dung duoc thi van chay -- chi la moi tia dung som toi mot // bien o. Khong dung duoc thi van chay -- chi la moi tia dung som toi mot
// o, y nhu truoc day. // o, y nhu truoc day.
const StatusResponse ss = const StatusResponse ss = BuildWorldSegments(
BuildWorldSegments(impl_->world, wo, impl_->map, &impl_->segments); impl_->world, wo, impl_->map, &impl_->segments,
terr.terrain_cells > 0 ? &terr.floor_z : nullptr);
if (!ss.ok()) { if (!ss.ok()) {
VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message
<< ") -- raycast se luong tu hoa theo o " << ") -- raycast se luong tu hoa theo o "
@@ -1048,13 +1533,63 @@ StatusResponse SimSource::Open() {
} }
// San phang mac dinh. SetFloorHeight() tao bac hut xuong. // San phang mac dinh. SetFloorHeight() tao bac hut xuong.
impl_->floor_z.assign(static_cast<size_t>(impl_->map.width) * impl_->map.height, 0.0f); const size_t n_cells = static_cast<size_t>(impl_->map.width) * impl_->map.height;
impl_->glass.assign(static_cast<size_t>(impl_->map.width) * impl_->map.height, 0); impl_->floor_z.assign(n_cells, 0.0f);
impl_->glass.assign(n_cells, 0);
impl_->wall_top.clear();
impl_->step_block.clear();
// World co dia hinh (san cao, doc): san lay tu mesh dia hinh.
if (terr.terrain_cells > 0 && terr.floor_z.size() == n_cells) {
impl_->floor_z = terr.floor_z;
}
if (terr.wall_top.size() == n_cells) impl_->wall_top = terr.wall_top;
const SimConfig::TerrainMode tm = impl_->cfg.terrain;
impl_->terrain_on = tm == SimConfig::TerrainMode::kOn ||
(tm == SimConfig::TerrainMode::kAuto && terr.terrain_cells > 0);
if (impl_->terrain_on) {
VSLAM_INFO("sim: dia hinh 3D BAT -- " << terr.terrain_cells << " o dia hinh, san tu "
<< terr.floor_min << " den " << terr.floor_max
<< " m. Robot di tren mat san, LiDAR quet tia 3D, chenh san > "
<< impl_->cfg.max_step << " m la vat can.");
}
impl_->x = impl_->cfg.start_x; impl_->x = impl_->cfg.start_x;
impl_->y = impl_->cfg.start_y; impl_->y = impl_->cfg.start_y;
impl_->yaw = impl_->cfg.start_yaw; impl_->yaw = impl_->cfg.start_yaw;
if (impl_->terrain_on) {
impl_->RebuildStepMask();
impl_->terrain_ready = false;
impl_->UpdateTerrainPose(0.0);
}
// Mo hinh IMU. RNG rieng, gieo tu seed: cung kich ban => cung chuoi nhieu.
const SimConfig::ImuModel im = impl_->cfg.imu_model;
impl_->imu_kinematic = im == SimConfig::ImuModel::kKinematic ||
(im == SimConfig::ImuModel::kAuto && impl_->terrain_on);
impl_->imu_rng.seed(impl_->cfg.seed + 101u);
impl_->imu_hist = 0;
if (impl_->imu_kinematic) impl_->SeedImuHistory();
impl_->imu_lpf_init = false;
impl_->imu_fifo.clear();
impl_->imu_out_acc = 0.0;
for (int i = 0; i < 3; ++i) { impl_->imu_bg[i] = 0.0; impl_->imu_ba[i] = 0.0; }
if (impl_->imu_kinematic) {
std::normal_distribution<double> n01(0.0, 1.0);
for (int i = 0; i < 3; ++i) {
impl_->imu_bg[i] = impl_->cfg.gyro_bias_sigma * n01(impl_->imu_rng);
impl_->imu_ba[i] = impl_->cfg.accel_bias_sigma * n01(impl_->imu_rng);
}
VSLAM_INFO("sim: IMU dong hoc -- tinh tu quy dao 6-DoF that"
<< (impl_->cfg.imu_output_hz > 0.0
? ", phat " + std::to_string(impl_->cfg.imu_output_hz) + " Hz"
: std::string(""))
<< (impl_->cfg.imu_delay_sec > 0.0
? ", tre " + std::to_string(impl_->cfg.imu_delay_sec) + " s"
: std::string("")));
}
if (impl_->Collides(impl_->x, impl_->y)) { if (impl_->Collides(impl_->x, impl_->y)) {
// Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi // Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi
// doan tai sao no khong nhuc nhich. // doan tai sao no khong nhuc nhich.
@@ -1093,6 +1628,10 @@ void SimSource::SetMapForTest(const OccupancyGrid& m) {
impl_->map = m; impl_->map = m;
impl_->floor_z.assign(static_cast<size_t>(m.width) * m.height, 0.0f); impl_->floor_z.assign(static_cast<size_t>(m.width) * m.height, 0.0f);
impl_->glass.assign(static_cast<size_t>(m.width) * m.height, 0); impl_->glass.assign(static_cast<size_t>(m.width) * m.height, 0);
impl_->wall_top.clear();
impl_->step_block.clear();
impl_->steps_dirty = true;
impl_->terrain_ready = false;
} }
bool SimSource::true_bumper() const { return impl_->bumper_now; } bool SimSource::true_bumper() const { return impl_->bumper_now; }
@@ -1143,16 +1682,102 @@ void SimSource::SetFloorHeight(double x0, double y0, double x1, double y1, float
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] = z; impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] = z;
} }
} }
// Dia hinh 3D: mat na bac tinh lai o buoc vat ly sau, va goc dia hinh lay
// lai tu dau (khong sinh toc do goc gia).
impl_->steps_dirty = true;
impl_->terrain_ready = false;
VSLAM_INFO("sim: dat do cao san " << z << " m cho vung (" << x0 << ", " << y0 VSLAM_INFO("sim: dat do cao san " << z << " m cho vung (" << x0 << ", " << y0
<< ") - (" << x1 << ", " << y1 << ")"); << ") - (" << x1 << ", " << y1 << ")");
} }
void SimSource::SetFloorRamp(double x0, double y0, double x1, double y1,
float z_at_x0, float z_at_x1) {
const OccupancyGrid& m = impl_->map;
if (x1 == x0) return;
auto to_cell = [&](double w, double origin) {
return static_cast<int>(std::floor((w - origin) / m.resolution));
};
const int cx0 = std::max(0, to_cell(std::min(x0, x1), m.origin.position.x));
const int cy0 = std::max(0, to_cell(std::min(y0, y1), m.origin.position.y));
const int cx1 = std::min<int>(static_cast<int>(m.width) - 1,
to_cell(std::max(x0, x1), m.origin.position.x));
const int cy1 = std::min<int>(static_cast<int>(m.height) - 1,
to_cell(std::max(y0, y1), m.origin.position.y));
std::lock_guard<std::mutex> lk(impl_->state_mu);
for (int cy = cy0; cy <= cy1; ++cy) {
for (int cx = cx0; cx <= cx1; ++cx) {
// Do cao tai TAM o, cung quy uoc voi raster dia hinh tu world.
const double wx = m.origin.position.x + (cx + 0.5) * m.resolution;
const double t = std::min(1.0, std::max(0.0, (wx - x0) / (x1 - x0)));
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] =
static_cast<float>(z_at_x0 + t * (z_at_x1 - z_at_x0));
}
}
impl_->steps_dirty = true;
impl_->terrain_ready = false;
VSLAM_INFO("sim: doc tu x = " << x0 << " (" << z_at_x0 << " m) toi x = " << x1
<< " (" << z_at_x1 << " m)");
}
bool SimSource::terrain_active() const { return impl_->terrain_on; }
void SimSource::SetCameraRenderer(std::shared_ptr<SimCameraRenderer> r) {
impl_->renderer = std::move(r);
impl_->gl_fail_logged = false;
}
void SimSource::SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz) {
impl_->gt_cb = std::move(cb);
impl_->gt_period = rate_hz > 0.0 ? 1.0 / rate_hz : 0.0;
impl_->gt_acc = 0.0;
}
void SimConfigFromRobot(const RobotModel& robot, SimConfig* c) {
const RobotGeometry& g = robot.geometry();
c->wheel_radius = g.wheel_radius;
c->wheel_separation = g.wheel_separation;
c->robot_radius = g.robot_radius;
c->camera_z = robot.camera_height_above_floor();
c->camera_pitch = robot.camera_pitch();
Transform t;
if (robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
c->lidar_x = t.translation.x;
// Do cao LiDAR tren TAM TRUC. Duong 2D cu khong dung; dia hinh 3D thi
// can de tia o dung 0.2165 m tren san.
c->lidar_z = t.translation.z;
}
if (robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
c->camera_x = t.translation.x;
}
if (robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t)) {
c->imu_x = t.translation.x;
c->imu_y = t.translation.y;
c->imu_z = t.translation.z;
}
}
void SimSource::true_tilt(double* roll_out, double* pitch_out) const { void SimSource::true_tilt(double* roll_out, double* pitch_out) const {
std::lock_guard<std::mutex> lk(impl_->state_mu); std::lock_guard<std::mutex> lk(impl_->state_mu);
*roll_out = impl_->roll; // Tat dia hinh 3D thi KHONG cong (ke ca 0.0): giu dung tung bit nhu cu.
*roll_out = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
*pitch_out = impl_->pitch + impl_->terrain_pitch; *pitch_out = impl_->pitch + impl_->terrain_pitch;
} }
SimPose3 SimSource::ground_truth_3d() const {
std::lock_guard<std::mutex> lk(impl_->state_mu);
SimPose3 p;
p.x = impl_->x;
p.y = impl_->y;
p.yaw = impl_->yaw;
// Tat dia hinh 3D thi robot luon o z = 0, ke ca khi SetFloorHeight tao vuc:
// do cao san luc do chi de camera NHIN thay, robot khong di len no.
p.z = impl_->terrain_on ? impl_->ground_z : 0.0;
p.roll = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
p.pitch = impl_->pitch + impl_->terrain_pitch;
return p;
}
Pose2D SimSource::ground_truth() const { Pose2D SimSource::ground_truth() const {
std::lock_guard<std::mutex> lk(impl_->state_mu); std::lock_guard<std::mutex> lk(impl_->state_mu);
return Pose2D{impl_->x, impl_->y, impl_->yaw}; return Pose2D{impl_->x, impl_->y, impl_->yaw};
@@ -1207,13 +1832,24 @@ void SimSource::RunFor(double seconds) {
impl_->StepPhysics(dt); impl_->StepPhysics(dt);
impl_->sim_elapsed += dt; impl_->sim_elapsed += dt;
impl_->mcu.PushImu(impl_->MakeImu(now)); ImuPtr meas = impl_->imu_kinematic ? impl_->MakeImuKinematic(now, dt)
: impl_->MakeImu(now);
const bool imu_out = impl_->EmitImu(now, std::move(meas), dt);
{ {
std::lock_guard<std::mutex> lk(impl_->state_mu); std::lock_guard<std::mutex> lk(impl_->state_mu);
impl_->stats.imu++; if (imu_out) impl_->stats.imu++;
impl_->stats.sim_time_sec += dt; impl_->stats.sim_time_sec += dt;
} }
// Su that cho tool ghi (SetGroundTruthCallback). Khong stage nao doc no.
if (impl_->gt_cb) {
impl_->gt_acc += dt;
if (impl_->gt_period <= 0.0 || impl_->gt_acc + 1e-9 >= impl_->gt_period) {
if (impl_->gt_period > 0.0) impl_->gt_acc -= impl_->gt_period;
impl_->gt_cb(now, ground_truth_3d());
}
}
enc_acc += dt; enc_acc += dt;
if (enc_acc >= enc_period) { if (enc_acc >= enc_period) {
enc_acc -= enc_period; enc_acc -= enc_period;

View File

@@ -0,0 +1,38 @@
# Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh hien
# thi va texture THAT cua model (assimp), anh tu OpenCV.
#
# TUY CHON (-DVSLAM_SIM_WITH_GL=ON), chi cho may dev co GPU: vslam_sim KHONG
# phu thuoc lib nay -- no chi biet interface SimCameraRenderer
# (vslam/sim_camera_renderer.h). Jetson va CI van build sim nhu cu.
#
# Khong dung find_package(assimp): goi libassimp-dev 5.0.1 cua Ubuntu 20.04
# co file cmake tro sai ten thu vien. Tim thang thu vien va header thi chac.
find_package(OpenCV REQUIRED COMPONENTS core imgproc imgcodecs)
find_library(VSLAM_EGL_LIB EGL)
find_library(VSLAM_GLES_LIB GLESv2)
find_library(VSLAM_ASSIMP_LIB assimp)
find_path(VSLAM_EGL_INC EGL/egl.h)
find_path(VSLAM_GLES_INC GLES3/gl3.h)
find_path(VSLAM_ASSIMP_INC assimp/scene.h)
foreach(v VSLAM_EGL_LIB VSLAM_GLES_LIB VSLAM_ASSIMP_LIB VSLAM_EGL_INC VSLAM_GLES_INC VSLAM_ASSIMP_INC)
if(NOT ${v})
message(FATAL_ERROR "VSLAM_SIM_WITH_GL=ON nhung thieu ${v}. Ubuntu: "
"apt install libegl-dev libgles-dev libassimp-dev")
endif()
endforeach()
vslam_add_library(vslam_sim_gl
PUBLIC_HDRS
sim_gl_renderer.h
PUBLIC_DEPS
vslam_sim
vslam_common
FIND_DEPS
vslam_sim
vslam_common
)
target_include_directories(vslam_sim_gl SYSTEM PRIVATE
${VSLAM_EGL_INC} ${VSLAM_GLES_INC} ${VSLAM_ASSIMP_INC} ${OpenCV_INCLUDE_DIRS})
target_link_libraries(vslam_sim_gl PRIVATE
${VSLAM_EGL_LIB} ${VSLAM_GLES_LIB} ${VSLAM_ASSIMP_LIB} ${OpenCV_LIBS})

View File

@@ -0,0 +1,69 @@
#ifndef VSLAM_SIM_GL_RENDERER_H
#define VSLAM_SIM_GL_RENDERER_H
// Ve anh camera mo phong bang GPU: EGL KHONG man hinh + OpenGL ES 3, mesh
// HIEN THI cua world voi texture THAT cua model (assimp: OBJ/MTL, COLLADA).
//
// ================== VI SAO CAN ==================
// Raycast CPU cua bo mo phong chi ra DEPTH, tren tuong ep tu luoi 2D: khong co
// anh, va hinh hoc chi la 2.5D. VO/VIO (F2M, DM-VIO) can ANH co van that de
// bam diem, va can depth KHOP voi anh do. Ve ca hai tu CUNG mot mesh trong
// MOT luot GPU thi chung khop tung pixel.
//
// ================== GIOI HAN (noi ro) ==================
// * Anh "IR" la do sang texture * chieu sang don gian (ambient + den chieu
// theo huong camera), emitter TAT: khong co cham laser, khong rolling
// shutter, khong nhoe chuyen dong, khong tu dong phoi sang. Anh sach hon
// camera that -- ket qua VO trong sim LAC QUAN.
// * Model khong co texture (tuong/san tu sinh) duoc phu mot texture anh
// that theo toa do the gioi (triplanar). Van that, nhung khong dung nghia.
// * Chi xet yaw cua model (giong bo doc world): do doc phai nam san trong
// dinh mesh.
//
// ⚠️ Context GPU tao LUOI o lan Render() dau tien, tren luong goi, va moi lan
// goi sau phai tren CUNG luong do (luong vong mo phong).
#include <memory>
#include <string>
#include "vslam/gazebo_world.h"
#include "vslam/sim_camera_renderer.h"
namespace vslam {
struct GlRendererConfig {
// Texture cho model KHONG co texture: dia hinh (`vslam_terrain_*`) va vat
// khac. Phu theo toa do THE GIOI (triplanar), moi lan lap `texture_tile_m`
// met. Rong = mau dac (khong co van -- VO se khong bam duoc).
std::string fallback_floor_texture;
std::string fallback_wall_texture;
double texture_tile_m = 2.0;
// Chieu sang anh IR: ambient + den chieu dat tai camera (emitter TAT).
double ambient = 0.55;
double headlight = 0.45;
// Cho phep renderer PHAN MEM (Mesa llvmpipe). Mac dinh tu choi: may co ca
// driver Mesa, va chon nham thiet bi la cham ~100 lan ma khong bao loi.
bool allow_software = false;
};
// Cau hinh mac dinh: texture cho model khong co texture lay tu bo model AWS
// tren may (~/gazebo_models/aws_hospital): san/doc = anh THAM that, vat khac =
// anh VAI rem that -- ca hai lap duoc, co van cho VO bam. Bien moi truong
// VSLAM_SIM_FLOOR_TEXTURE / VSLAM_SIM_WALL_TEXTURE ghi de (duong dan anh).
// Khong tim thay anh nao thi de rong (mau dac) va log canh bao.
GlRendererConfig DefaultGlRendererConfig();
// Nap mesh + texture cua `world` NGAY (CPU), dua len GPU o lan Render() dau.
// Tra nullptr va dien `error` neu khong nap duoc mesh nao.
std::shared_ptr<SimCameraRenderer> CreateGlCameraRenderer(const GazeboWorld& world,
const GlRendererConfig& cfg,
std::string* error);
// Hop bao he WORLD cua mesh HIEN THI cua mot model, doc bang assimp voi CUNG
// quy uoc nhu renderer (ti le `<scale>`, yaw, tinh tien). Cho bai kiem so voi
// bo doc world cua vslam_sim. false neu khong doc duoc.
bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]);
} // namespace vslam
#endif // VSLAM_SIM_GL_RENDERER_H

View File

@@ -0,0 +1,704 @@
#include "vslam/sim_gl_renderer.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <assimp/Importer.hpp>
#include <assimp/config.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <sys/stat.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "vslam/log.h"
namespace vslam {
namespace {
// ---------------------------------------------------------------------------
// Du lieu phia CPU: nap mot lan luc tao, khong can context GPU.
// ---------------------------------------------------------------------------
struct CpuTexture {
int w = 0, h = 0;
std::vector<uint8_t> rgba; // hang DUOI cung truoc -- quy uoc texture GL
};
struct CpuMesh {
std::vector<float> v; // moi dinh: x y z nx ny nz u v, he WORLD
std::vector<uint32_t> idx;
int tex = -1; // chi so CpuTexture; -1 = mau dac
bool triplanar = false; // phu texture theo toa do world (model khong UV)
float color[3] = {0.7f, 0.7f, 0.7f};
};
std::string DirOf(const std::string& p) {
const size_t s = p.rfind('/');
return s == std::string::npos ? std::string(".") : p.substr(0, s);
}
// Nap anh texture. Lat DOC: OBJ va COLLADA dat v = 0 o DAY anh, con anh doc
// tu file thi hang tren cung truoc.
int LoadTexture(const std::string& path, std::map<std::string, int>* cache,
std::vector<CpuTexture>* out) {
auto it = cache->find(path);
if (it != cache->end()) return it->second;
cv::Mat img = cv::imread(path, cv::IMREAD_COLOR);
if (img.empty()) {
VSLAM_WARN("sim_gl: khong doc duoc texture " << path << " -- dung mau dac");
(*cache)[path] = -1;
return -1;
}
// 2048 la du cho anh 640x480 nhin vat cach vai met; texture 8K cua vai
// model chi ton bo nho GPU va thoi gian nap.
const int kMax = 2048;
if (img.cols > kMax || img.rows > kMax) {
const double s = static_cast<double>(kMax) / std::max(img.cols, img.rows);
cv::resize(img, img, cv::Size(), s, s, cv::INTER_AREA);
}
cv::Mat rgba;
cv::cvtColor(img, rgba, cv::COLOR_BGR2RGBA);
cv::flip(rgba, rgba, 0);
CpuTexture t;
t.w = rgba.cols;
t.h = rgba.rows;
t.rgba.assign(rgba.data, rgba.data + rgba.total() * 4);
out->push_back(std::move(t));
const int id = static_cast<int>(out->size()) - 1;
(*cache)[path] = id;
return id;
}
// Doc mesh HIEN THI cua mot model bang assimp, bien doi sang world theo CUNG
// thu tu voi bo doc world (gazebo_world.cc): ti le `<scale>` -> yaw -> tinh tien.
// `meshes`/`textures` co the null (chi lay hop bao).
bool LoadModel(const WorldModel& m, const GlRendererConfig* cfg,
std::map<std::string, int>* tex_cache, std::vector<CpuTexture>* textures,
std::vector<CpuMesh>* meshes, double mn[3], double mx[3]) {
const std::string& path = !m.visual_obj.empty() ? m.visual_obj : m.collision_obj;
if (path.empty()) return false;
Assimp::Importer imp;
// Bo <up_axis> cua COLLADA, y nhu bo doc world: file cua bo model AWS khai
// Y_UP nhung du lieu (hoac node goc) DA la Z-up. Don vi <unit> va bien doi
// node thi giu -- PreTransformVertices nuong ca hai vao dinh.
imp.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);
const aiScene* sc =
imp.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals |
aiProcess_PreTransformVertices |
aiProcess_JoinIdenticalVertices);
if (sc == nullptr || sc->mRootNode == nullptr) {
VSLAM_WARN("sim_gl: assimp khong doc duoc " << path << ": " << imp.GetErrorString());
return false;
}
const double cyw = std::cos(m.yaw), syw = std::sin(m.yaw);
const std::string dir = DirOf(path);
for (int k = 0; k < 3; ++k) { mn[k] = 1e18; mx[k] = -1e18; }
bool any = false;
for (unsigned mi = 0; mi < sc->mNumMeshes; ++mi) {
const aiMesh* am = sc->mMeshes[mi];
if (am->mNumVertices == 0 || am->mNumFaces == 0) continue;
CpuMesh cm;
if (meshes != nullptr && am->mMaterialIndex < sc->mNumMaterials) {
const aiMaterial* mat = sc->mMaterials[am->mMaterialIndex];
aiColor3D kd(0.7f, 0.7f, 0.7f);
if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, kd) == AI_SUCCESS) {
cm.color[0] = kd.r; cm.color[1] = kd.g; cm.color[2] = kd.b;
}
aiString tp;
if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0 &&
mat->GetTexture(aiTextureType_DIFFUSE, 0, &tp) == AI_SUCCESS) {
std::string t = tp.C_Str();
// '*' dau = texture nhung trong file -- bo model nay khong dung.
if (!t.empty() && t[0] != '*') {
std::replace(t.begin(), t.end(), '\\', '/');
cm.tex = LoadTexture(t[0] == '/' ? t : dir + "/" + t, tex_cache, textures);
}
}
}
const bool has_uv = am->HasTextureCoords(0);
if (meshes != nullptr && cfg != nullptr && (cm.tex < 0 || !has_uv)) {
// Khong co texture (tuong/san tu sinh): phu anh that theo toa do world.
const std::string& fb = m.terrain ? cfg->fallback_floor_texture
: cfg->fallback_wall_texture;
if (!fb.empty()) {
cm.tex = LoadTexture(fb, tex_cache, textures);
cm.triplanar = cm.tex >= 0;
}
}
cm.v.reserve(static_cast<size_t>(am->mNumVertices) * 8);
for (unsigned k = 0; k < am->mNumVertices; ++k) {
const aiVector3D& p = am->mVertices[k];
const double px = p.x * m.sx, py = p.y * m.sy, pz = p.z * m.sz;
const double wx = px * cyw - py * syw + m.x;
const double wy = px * syw + py * cyw + m.y;
const double wz = pz + m.z;
double nx = 0.0, ny = 0.0, nz = 1.0;
if (am->HasNormals()) {
// Ti le KHONG deu: phap tuyen chia (khong nhan) cho ti le, roi chuan hoa.
const double ax = am->mNormals[k].x / m.sx;
const double ay = am->mNormals[k].y / m.sy;
const double az = am->mNormals[k].z / m.sz;
const double rx = ax * cyw - ay * syw, ry = ax * syw + ay * cyw;
const double n = std::sqrt(rx * rx + ry * ry + az * az);
if (n > 1e-12) { nx = rx / n; ny = ry / n; nz = az / n; }
}
const float u = has_uv ? am->mTextureCoords[0][k].x : 0.0f;
const float w = has_uv ? am->mTextureCoords[0][k].y : 0.0f;
const float vals[8] = {static_cast<float>(wx), static_cast<float>(wy),
static_cast<float>(wz), static_cast<float>(nx),
static_cast<float>(ny), static_cast<float>(nz), u, w};
cm.v.insert(cm.v.end(), vals, vals + 8);
mn[0] = std::min(mn[0], wx); mx[0] = std::max(mx[0], wx);
mn[1] = std::min(mn[1], wy); mx[1] = std::max(mx[1], wy);
mn[2] = std::min(mn[2], wz); mx[2] = std::max(mx[2], wz);
any = true;
}
for (unsigned f = 0; f < am->mNumFaces; ++f) {
const aiFace& face = am->mFaces[f];
if (face.mNumIndices != 3) continue; // diem / doan sau Triangulate
cm.idx.push_back(face.mIndices[0]);
cm.idx.push_back(face.mIndices[1]);
cm.idx.push_back(face.mIndices[2]);
}
if (meshes != nullptr && !cm.idx.empty()) meshes->push_back(std::move(cm));
}
return any;
}
// ---------------------------------------------------------------------------
// Shader. Mot luot ve ra HAI anh: do sang IR (attachment 0) va Z-depth
// (attachment 1, float) -- cung mesh, cung pixel, nen khop tung diem.
// ---------------------------------------------------------------------------
const char* kVertex = R"(#version 300 es
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNrm;
layout(location = 2) in vec2 aUv;
uniform mat4 uProj;
uniform mat4 uView;
out vec3 vWorld;
out vec3 vNrm;
out vec2 vUv;
out float vZ;
void main() {
vWorld = aPos;
vNrm = aNrm;
vUv = aUv;
vec4 pc = uView * vec4(aPos, 1.0);
vZ = -pc.z; // Z-depth: camera GL nhin theo -z
gl_Position = uProj * pc;
}
)";
const char* kFragment = R"(#version 300 es
precision highp float;
in vec3 vWorld;
in vec3 vNrm;
in vec2 vUv;
in float vZ;
uniform sampler2D uTex;
uniform int uHasTex;
uniform int uTriplanar;
uniform float uTriScale;
uniform vec3 uColor;
uniform vec3 uCamPos;
uniform float uAmbient;
uniform float uHeadlight;
layout(location = 0) out vec4 oIr;
layout(location = 1) out vec4 oDepth;
vec3 Tri(vec3 p, vec3 n) {
vec3 w = abs(n);
w /= (w.x + w.y + w.z + 1e-6);
vec3 a = texture(uTex, p.yz * uTriScale).rgb;
vec3 b = texture(uTex, p.xz * uTriScale).rgb;
vec3 c = texture(uTex, p.xy * uTriScale).rgb;
return a * w.x + b * w.y + c * w.z;
}
void main() {
vec3 n = normalize(vNrm);
vec3 base = uColor;
if (uHasTex == 1) {
base = (uTriplanar == 1) ? Tri(vWorld, n) : texture(uTex, vUv).rgb;
}
// Den chieu dat tai camera; abs() vi vai mesh co phap tuyen nguoc.
vec3 l = normalize(uCamPos - vWorld);
float lit = uAmbient + uHeadlight * abs(dot(n, l));
float g = clamp(dot(base, vec3(0.299, 0.587, 0.114)) * lit, 0.0, 1.0);
oIr = vec4(g, g, g, 1.0);
oDepth = vec4(vZ, 0.0, 0.0, 1.0);
}
)";
GLuint Compile(GLenum type, const char* src, std::string* err) {
const GLuint s = glCreateShader(type);
glShaderSource(s, 1, &src, nullptr);
glCompileShader(s);
GLint ok = 0;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048] = {0};
glGetShaderInfoLog(s, sizeof(log), nullptr, log);
*err = log;
glDeleteShader(s);
return 0;
}
return s;
}
bool IsSoftware(const char* renderer) {
if (renderer == nullptr) return true;
const std::string r = renderer;
return r.find("llvmpipe") != std::string::npos ||
r.find("softpipe") != std::string::npos ||
r.find("SwiftShader") != std::string::npos;
}
// Ma tran 4x4 COT-chinh (quy uoc GL).
struct Mat4 {
float m[16];
};
class GlCameraRenderer : public SimCameraRenderer {
public:
GlCameraRenderer(std::vector<CpuMesh> meshes, std::vector<CpuTexture> textures,
GlRendererConfig cfg)
: meshes_(std::move(meshes)), textures_(std::move(textures)), cfg_(std::move(cfg)) {}
~GlCameraRenderer() override {
// Tren luong khac thi chi huy context: tai nguyen GL di theo no. KHONG
// eglTerminate -- display cua thiet bi dung chung giua cac renderer.
if (ctx_ != EGL_NO_CONTEXT && std::this_thread::get_id() == thread_) {
eglMakeCurrent(dpy_, surf_, surf_, ctx_);
for (const Gpu& g : gpu_) {
glDeleteVertexArrays(1, &g.vao);
glDeleteBuffers(1, &g.vbo);
glDeleteBuffers(1, &g.ibo);
}
if (!gl_tex_.empty()) glDeleteTextures(static_cast<GLsizei>(gl_tex_.size()), gl_tex_.data());
DropFbo();
if (prog_ != 0) glDeleteProgram(prog_);
eglMakeCurrent(dpy_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
if (ctx_ != EGL_NO_CONTEXT) eglDestroyContext(dpy_, ctx_);
if (surf_ != EGL_NO_SURFACE) eglDestroySurface(dpy_, surf_);
}
bool Render(const SimCameraView& view, std::vector<uint8_t>* ir,
std::vector<float>* depth_z) override {
if (!init_tried_) {
init_tried_ = true;
thread_ = std::this_thread::get_id();
ok_ = InitGpu();
// Du lieu CPU khong can nua: GPU da giu ban sao.
meshes_.clear();
meshes_.shrink_to_fit();
textures_.clear();
textures_.shrink_to_fit();
}
if (!ok_) return false;
if (std::this_thread::get_id() != thread_) {
VSLAM_ERROR("sim_gl: Render() goi tu luong khac luong tao context -- bo khung");
return false;
}
if (view.width <= 0 || view.height <= 0) return false;
if (eglGetCurrentContext() != ctx_) eglMakeCurrent(dpy_, surf_, surf_, ctx_);
if (!EnsureFbo(view.width, view.height)) return false;
const int w = view.width, h = view.height;
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glViewport(0, 0, w, h);
const GLenum bufs[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, bufs);
const float c0[4] = {0.0f, 0.0f, 0.0f, 1.0f};
const float c1[4] = {0.0f, 0.0f, 0.0f, 0.0f};
const float one = 1.0f;
glClearBufferfv(GL_COLOR, 0, c0);
glClearBufferfv(GL_COLOR, 1, c1);
glClearBufferfv(GL_DEPTH, 0, &one);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE); // vai mesh quay mat nguoc, ve ca hai mat
Mat4 proj, viewm;
Projection(view, &proj);
ViewMatrix(view, &viewm);
glUseProgram(prog_);
glUniformMatrix4fv(loc_proj_, 1, GL_FALSE, proj.m);
glUniformMatrix4fv(loc_view_, 1, GL_FALSE, viewm.m);
glUniform3f(loc_campos_, static_cast<float>(view.t_wc[0]),
static_cast<float>(view.t_wc[1]), static_cast<float>(view.t_wc[2]));
glUniform1f(loc_amb_, static_cast<float>(cfg_.ambient));
glUniform1f(loc_head_, static_cast<float>(cfg_.headlight));
glUniform1f(loc_triscale_, static_cast<float>(1.0 / std::max(0.05, cfg_.texture_tile_m)));
glUniform1i(loc_tex_, 0);
glActiveTexture(GL_TEXTURE0);
for (const Gpu& g : gpu_) {
glUniform3f(loc_color_, g.color[0], g.color[1], g.color[2]);
glUniform1i(loc_hastex_, g.tex >= 0 ? 1 : 0);
glUniform1i(loc_tri_, g.triplanar ? 1 : 0);
if (g.tex >= 0) glBindTexture(GL_TEXTURE_2D, gl_tex_[static_cast<size_t>(g.tex)]);
glBindVertexArray(g.vao);
glDrawElements(GL_TRIANGLES, g.count, GL_UNSIGNED_INT, nullptr);
}
glBindVertexArray(0);
rgba_.resize(static_cast<size_t>(w) * h * 4);
rgbaf_.resize(static_cast<size_t>(w) * h * 4);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba_.data());
glReadBuffer(GL_COLOR_ATTACHMENT1);
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, rgbaf_.data());
const GLenum e = glGetError();
if (e != GL_NO_ERROR) {
VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi ve");
return false;
}
// glReadPixels tra hang DUOI cung truoc; anh thi hang TREN truoc.
ir->resize(static_cast<size_t>(w) * h);
depth_z->resize(static_cast<size_t>(w) * h);
for (int r = 0; r < h; ++r) {
const size_t src = static_cast<size_t>(h - 1 - r) * w;
const size_t dst = static_cast<size_t>(r) * w;
for (int c = 0; c < w; ++c) {
(*ir)[dst + c] = rgba_[(src + c) * 4];
(*depth_z)[dst + c] = rgbaf_[(src + c) * 4];
}
}
return true;
}
std::string Describe() const override { return describe_; }
private:
struct Gpu {
GLuint vao = 0, vbo = 0, ibo = 0;
GLsizei count = 0;
int tex = -1;
bool triplanar = false;
float color[3] = {0.7f, 0.7f, 0.7f};
};
bool InitGpu() {
auto query_devices =
reinterpret_cast<PFNEGLQUERYDEVICESEXTPROC>(eglGetProcAddress("eglQueryDevicesEXT"));
auto get_display = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (query_devices == nullptr || get_display == nullptr) {
VSLAM_ERROR("sim_gl: EGL thieu EGL_EXT_device_enumeration / platform_device");
return false;
}
EGLDeviceEXT devs[16];
EGLint n = 0;
if (!query_devices(16, devs, &n) || n <= 0) {
VSLAM_ERROR("sim_gl: khong co thiet bi EGL nao");
return false;
}
std::string rejected;
for (EGLint i = 0; i < n; ++i) {
EGLDisplay d = get_display(EGL_PLATFORM_DEVICE_EXT, devs[i], nullptr);
EGLint maj = 0, min = 0;
if (d == EGL_NO_DISPLAY || !eglInitialize(d, &maj, &min)) continue;
if (!eglBindAPI(EGL_OPENGL_ES_API)) continue;
const EGLint cattr[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES3_BIT, EGL_NONE};
EGLConfig conf;
EGLint nc = 0;
if (!eglChooseConfig(d, cattr, &conf, 1, &nc) || nc < 1) continue;
const EGLint xattr[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
EGLContext c = eglCreateContext(d, conf, EGL_NO_CONTEXT, xattr);
if (c == EGL_NO_CONTEXT) continue;
const EGLint pattr[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE};
EGLSurface s = eglCreatePbufferSurface(d, conf, pattr);
if (s == EGL_NO_SURFACE || !eglMakeCurrent(d, s, s, c)) {
if (s != EGL_NO_SURFACE) eglDestroySurface(d, s);
eglDestroyContext(d, c);
continue;
}
const char* rend = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
const char* ext = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
const bool soft = IsSoftware(rend);
const bool fbuf = ext != nullptr && std::strstr(ext, "GL_EXT_color_buffer_float") != nullptr;
if ((soft && !cfg_.allow_software) || !fbuf) {
rejected += std::string(rend ? rend : "?") + (soft ? " (phan mem)" : " (thieu float FBO)") + "; ";
eglMakeCurrent(d, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroySurface(d, s);
eglDestroyContext(d, c);
continue;
}
dpy_ = d;
ctx_ = c;
surf_ = s;
describe_ = std::string(rend ? rend : "?") + " (EGL, " +
reinterpret_cast<const char*>(glGetString(GL_VERSION)) + ")";
break;
}
if (ctx_ == EGL_NO_CONTEXT) {
VSLAM_ERROR("sim_gl: khong co GPU dung duoc. Da bo: " << rejected
<< "(allow_software = true de chay CHAM tren CPU)");
return false;
}
std::string err;
const GLuint vs = Compile(GL_VERTEX_SHADER, kVertex, &err);
if (vs == 0) { VSLAM_ERROR("sim_gl: vertex shader: " << err); return false; }
const GLuint fs = Compile(GL_FRAGMENT_SHADER, kFragment, &err);
if (fs == 0) { VSLAM_ERROR("sim_gl: fragment shader: " << err); return false; }
prog_ = glCreateProgram();
glAttachShader(prog_, vs);
glAttachShader(prog_, fs);
glLinkProgram(prog_);
glDeleteShader(vs);
glDeleteShader(fs);
GLint linked = 0;
glGetProgramiv(prog_, GL_LINK_STATUS, &linked);
if (!linked) {
char log[2048] = {0};
glGetProgramInfoLog(prog_, sizeof(log), nullptr, log);
VSLAM_ERROR("sim_gl: link shader: " << log);
return false;
}
loc_proj_ = glGetUniformLocation(prog_, "uProj");
loc_view_ = glGetUniformLocation(prog_, "uView");
loc_tex_ = glGetUniformLocation(prog_, "uTex");
loc_hastex_ = glGetUniformLocation(prog_, "uHasTex");
loc_tri_ = glGetUniformLocation(prog_, "uTriplanar");
loc_triscale_ = glGetUniformLocation(prog_, "uTriScale");
loc_color_ = glGetUniformLocation(prog_, "uColor");
loc_campos_ = glGetUniformLocation(prog_, "uCamPos");
loc_amb_ = glGetUniformLocation(prog_, "uAmbient");
loc_head_ = glGetUniformLocation(prog_, "uHeadlight");
// Texture.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
gl_tex_.resize(textures_.size(), 0);
if (!gl_tex_.empty()) glGenTextures(static_cast<GLsizei>(gl_tex_.size()), gl_tex_.data());
for (size_t i = 0; i < textures_.size(); ++i) {
glBindTexture(GL_TEXTURE_2D, gl_tex_[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, textures_[i].w, textures_[i].h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, textures_[i].rgba.data());
glGenerateMipmap(GL_TEXTURE_2D);
// Mipmap + loc tuyen tinh: van o xa khong nhap nhay (aliasing) -- mot
// nguon "dac trung" gia ma VO se bam vao.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
// Mesh.
size_t tris = 0;
for (const CpuMesh& cm : meshes_) {
Gpu g;
g.tex = cm.tex;
g.triplanar = cm.triplanar;
std::copy(cm.color, cm.color + 3, g.color);
g.count = static_cast<GLsizei>(cm.idx.size());
glGenVertexArrays(1, &g.vao);
glBindVertexArray(g.vao);
glGenBuffers(1, &g.vbo);
glBindBuffer(GL_ARRAY_BUFFER, g.vbo);
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(cm.v.size() * sizeof(float)),
cm.v.data(), GL_STATIC_DRAW);
glGenBuffers(1, &g.ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g.ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(cm.idx.size() * sizeof(uint32_t)), cm.idx.data(),
GL_STATIC_DRAW);
const GLsizei stride = 8 * sizeof(float);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride,
reinterpret_cast<const void*>(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
reinterpret_cast<const void*>(6 * sizeof(float)));
glBindVertexArray(0);
gpu_.push_back(g);
tris += cm.idx.size() / 3;
}
const GLenum e = glGetError();
if (e != GL_NO_ERROR) {
VSLAM_ERROR("sim_gl: loi GL 0x" << std::hex << e << std::dec << " khi nap mesh");
return false;
}
VSLAM_INFO("sim_gl: ve camera bang " << describe_ << " -- " << gpu_.size() << " mesh, "
<< tris << " tam giac, " << gl_tex_.size() << " texture");
return true;
}
void DropFbo() {
if (fbo_ != 0) glDeleteFramebuffers(1, &fbo_);
if (rb_ir_ != 0) glDeleteRenderbuffers(1, &rb_ir_);
if (rb_depth_ != 0) glDeleteRenderbuffers(1, &rb_depth_);
if (rb_z_ != 0) glDeleteRenderbuffers(1, &rb_z_);
fbo_ = rb_ir_ = rb_depth_ = rb_z_ = 0;
fbo_w_ = fbo_h_ = 0;
}
bool EnsureFbo(int w, int h) {
if (fbo_ != 0 && fbo_w_ == w && fbo_h_ == h) return true;
DropFbo();
glGenFramebuffers(1, &fbo_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glGenRenderbuffers(1, &rb_ir_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_ir_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb_ir_);
glGenRenderbuffers(1, &rb_depth_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_depth_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA32F, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, rb_depth_);
glGenRenderbuffers(1, &rb_z_);
glBindRenderbuffer(GL_RENDERBUFFER, rb_z_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb_z_);
const GLenum st = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (st != GL_FRAMEBUFFER_COMPLETE) {
VSLAM_ERROR("sim_gl: framebuffer khong day du (0x" << std::hex << st << std::dec << ")");
DropFbo();
return false;
}
fbo_w_ = w;
fbo_h_ = h;
return true;
}
// Phep chieu tu noi suy pinhole. Tam pixel o toa do NGUYEN (kieu OpenCV),
// con GL lay mau o x + 0.5: cong 0.5 vao cx, cy de tia qua pixel u cua GL
// trung tia qua pixel u cua raycast CPU.
static void Projection(const SimCameraView& v, Mat4* P) {
const double W = v.width, H = v.height, n = v.near_m, f = v.far_m;
const double cx = v.cx + 0.5, cy = v.cy + 0.5;
std::fill(P->m, P->m + 16, 0.0f);
P->m[0] = static_cast<float>(2.0 * v.fx / W);
P->m[5] = static_cast<float>(2.0 * v.fy / H);
P->m[8] = static_cast<float>(1.0 - 2.0 * cx / W);
P->m[9] = static_cast<float>(2.0 * cy / H - 1.0);
P->m[10] = static_cast<float>(-(f + n) / (f - n));
P->m[11] = -1.0f;
P->m[14] = static_cast<float>(-2.0 * f * n / (f - n));
}
// World -> camera GL (x phai, y LEN, nhin theo -z). Frame quang hoc (y
// XUONG, z truoc) doi sang GL bang diag(1, -1, -1).
static void ViewMatrix(const SimCameraView& v, Mat4* V) {
// R_gl_w = diag(1,-1,-1) * R_wc^T. Hang i cua R_wc^T = cot i cua R_wc.
double R[9];
for (int i = 0; i < 3; ++i) {
const double s = i == 0 ? 1.0 : -1.0;
for (int j = 0; j < 3; ++j) R[i * 3 + j] = s * v.R_wc[j * 3 + i];
}
double t[3];
for (int i = 0; i < 3; ++i) {
t[i] = -(R[i * 3 + 0] * v.t_wc[0] + R[i * 3 + 1] * v.t_wc[1] + R[i * 3 + 2] * v.t_wc[2]);
}
std::fill(V->m, V->m + 16, 0.0f);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) V->m[j * 4 + i] = static_cast<float>(R[i * 3 + j]);
V->m[12 + i] = static_cast<float>(t[i]);
}
V->m[15] = 1.0f;
}
std::vector<CpuMesh> meshes_;
std::vector<CpuTexture> textures_;
GlRendererConfig cfg_;
bool init_tried_ = false, ok_ = false;
std::thread::id thread_;
EGLDisplay dpy_ = EGL_NO_DISPLAY;
EGLContext ctx_ = EGL_NO_CONTEXT;
EGLSurface surf_ = EGL_NO_SURFACE;
GLuint prog_ = 0;
GLint loc_proj_ = -1, loc_view_ = -1, loc_tex_ = -1, loc_hastex_ = -1, loc_tri_ = -1;
GLint loc_triscale_ = -1, loc_color_ = -1, loc_campos_ = -1, loc_amb_ = -1, loc_head_ = -1;
std::vector<Gpu> gpu_;
std::vector<GLuint> gl_tex_;
GLuint fbo_ = 0, rb_ir_ = 0, rb_depth_ = 0, rb_z_ = 0;
int fbo_w_ = 0, fbo_h_ = 0;
std::vector<uint8_t> rgba_;
std::vector<float> rgbaf_;
std::string describe_ = "sim_gl (chua khoi tao)";
};
} // namespace
namespace {
std::string TexturePath(const char* env, const char* home_rel) {
if (const char* e = std::getenv(env)) {
if (*e != '\0') return e;
}
const char* home = std::getenv("HOME");
if (home == nullptr) return "";
const std::string p = std::string(home) + "/gazebo_models/" + home_rel;
struct stat st;
if (::stat(p.c_str(), &st) != 0) {
VSLAM_WARN("sim_gl: khong thay texture " << p << " (dat " << env
<< ") -- model khong co texture se la MAU DAC, VO khong bam duoc");
return "";
}
return p;
}
} // namespace
GlRendererConfig DefaultGlRendererConfig() {
GlRendererConfig c;
c.fallback_floor_texture = TexturePath(
"VSLAM_SIM_FLOOR_TEXTURE",
"aws_hospital/aws_robomaker_residential_Carpet_01/materials/textures/aws_Carpet_01.png");
c.fallback_wall_texture = TexturePath(
"VSLAM_SIM_WALL_TEXTURE",
"aws_hospital/aws_robomaker_hospital_curtain_open_01/meshes/"
"aws_robomaker_hospital_curtain_open_01_visual.png");
return c;
}
std::shared_ptr<SimCameraRenderer> CreateGlCameraRenderer(const GazeboWorld& world,
const GlRendererConfig& cfg,
std::string* error) {
std::vector<CpuMesh> meshes;
std::vector<CpuTexture> textures;
std::map<std::string, int> cache;
size_t loaded = 0, failed = 0;
for (const WorldModel& m : world.models) {
double mn[3], mx[3];
if (LoadModel(m, &cfg, &cache, &textures, &meshes, mn, mx)) {
loaded++;
} else {
failed++;
}
}
if (meshes.empty()) {
if (error != nullptr) *error = "khong nap duoc mesh hien thi nao tu world";
return nullptr;
}
VSLAM_INFO("sim_gl: nap " << loaded << " model (" << failed << " khong doc duoc), "
<< meshes.size() << " mesh, " << textures.size() << " texture");
return std::make_shared<GlCameraRenderer>(std::move(meshes), std::move(textures), cfg);
}
bool AssimpModelBounds(const WorldModel& m, double mn[3], double mx[3]) {
return LoadModel(m, nullptr, nullptr, nullptr, nullptr, mn, mx);
}
} // namespace vslam

View File

@@ -8,6 +8,28 @@
find_package(RTABMap REQUIRED) find_package(RTABMap REQUIRED)
find_package(OpenCV REQUIRED) find_package(OpenCV REQUIRED)
# rtabmap::core ghi san ten tran `opencv_*` cua ban OpenCV ma RTAB-Map duoc
# build cung. Tren Jetson do la ban CO aruco, con OpenCV 4.8 cua JetPack thi
# KHONG -> link ra `-lopencv_aruco` va hong (2026-09-25). Bo moi `opencv_*`
# khong co trong OpenCV dang dung, va noi ro ra.
get_target_property(_rtab_iface rtabmap::core INTERFACE_LINK_LIBRARIES)
set(_rtab_kept "")
set(_rtab_dropped "")
foreach(_l IN LISTS _rtab_iface)
if(_l MATCHES "^opencv_" AND NOT TARGET ${_l})
list(APPEND _rtab_dropped ${_l})
else()
list(APPEND _rtab_kept ${_l})
endif()
endforeach()
if(_rtab_dropped)
message(WARNING "vslam_slam: bo ${_rtab_dropped} khoi rtabmap::core -- "
"OpenCV ${OpenCV_VERSION} khong co. Neu librtabmap_core.so THAT SU "
"can chung thi se hong khi link vslam_node hoac khi chay: kiem bang "
"`ldd build/jetson/app/vslam_node | grep -E 'opencv|not found'`.")
set_target_properties(rtabmap::core PROPERTIES INTERFACE_LINK_LIBRARIES "${_rtab_kept}")
endif()
vslam_add_library(vslam_slam vslam_add_library(vslam_slam
PUBLIC_HDRS PUBLIC_HDRS
slam_types.h slam_types.h
@@ -15,6 +37,12 @@ vslam_add_library(vslam_slam
rtabmap_slam.h rtabmap_slam.h
sensor_data_builder.h sensor_data_builder.h
occupancy_export.h occupancy_export.h
voxel_export.h
slope_test.h
height_map.h
global_localizer.h
vpr_encoder.h
visual_verifier.h
FIND_DEPS FIND_DEPS
vslam_common vslam_common
RTABMap RTABMap
@@ -23,3 +51,43 @@ vslam_add_library(vslam_slam
target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS}) target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS})
target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS}) target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS})
# VPR bang TensorRT -- CHI Jetson (JetPack 6: TensorRT 10 + CUDA). Giong RealSense/CANopen o
# vslam_drivers: GLOB_RECURSE gom het src/ nen phai loai vpr_tensorrt.cc khi tat, neu khong
# `#include <NvInfer.h>` lam hong build tren may khong co TensorRT. Tat thi
# CreateVprEncoder() (vpr_encoder.cc) tra Unavailable va dinh vi lai chay bang LiDAR.
option(VSLAM_WITH_TENSORRT "VPR (EigenPlaces) bang TensorRT -- chi Jetson" OFF)
get_target_property(_vslam_slam_srcs vslam_slam SOURCES)
list(FILTER _vslam_slam_srcs EXCLUDE REGEX "vpr_tensorrt\\.cc$")
set_target_properties(vslam_slam PROPERTIES SOURCES "${_vslam_slam_srcs}")
if(VSLAM_WITH_TENSORRT)
if(NOT DEFINED CUDAToolkit_ROOT AND EXISTS /usr/local/cuda)
set(CUDAToolkit_ROOT /usr/local/cuda)
endif()
# FindCUDAToolkit chi co tu CMake 3.17 (JetPack 6: 3.22). May dev Ubuntu 20.04 co CMake
# 3.16 nhung van co TensorRT + CUDA (chay VPR trong mo phong) -> tim tay cudart.
if(CMAKE_VERSION VERSION_LESS 3.17)
find_path(VSLAM_CUDA_INCLUDE_DIR cuda_runtime_api.h HINTS ${CUDAToolkit_ROOT}/include)
find_library(VSLAM_CUDART cudart HINTS ${CUDAToolkit_ROOT}/lib64)
if(NOT VSLAM_CUDA_INCLUDE_DIR OR NOT VSLAM_CUDART)
message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay CUDA runtime trong "
"${CUDAToolkit_ROOT}")
endif()
set(_vslam_cudart ${VSLAM_CUDART})
set(_vslam_cuda_inc ${VSLAM_CUDA_INCLUDE_DIR})
else()
find_package(CUDAToolkit REQUIRED)
set(_vslam_cudart CUDA::cudart)
set(_vslam_cuda_inc "")
endif()
find_path(TENSORRT_INCLUDE_DIR NvInfer.h PATH_SUFFIXES aarch64-linux-gnu x86_64-linux-gnu)
find_library(TENSORRT_NVINFER nvinfer)
if(NOT TENSORRT_INCLUDE_DIR OR NOT TENSORRT_NVINFER)
message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay NvInfer.h / libnvinfer "
"(JetPack: goi libnvinfer-dev)")
endif()
target_sources(vslam_slam PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/vpr_tensorrt.cc)
target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR} ${_vslam_cuda_inc})
target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} ${_vslam_cudart})
target_compile_definitions(vslam_slam PRIVATE VSLAM_HAVE_TENSORRT=1)
endif()

View File

@@ -0,0 +1,322 @@
#ifndef VSLAM_GLOBAL_LOCALIZER_H
#define VSLAM_GLOBAL_LOCALIZER_H
// Dinh vi TOAN CUC bang khop scan LiDAR voi luoi chiem dung -- port tu
// vSLAM_ws/src/localization_ops/scripts/global_scan_init.py (ban ROS).
//
// ============ BAI TOAN ============
// Tha robot xuong mot cho bat ky tren ban do da quet, KHONG cho biet dang o
// dau. Robot xoay tai cho gom scan. Phai suy ra pose trong ban do -- roi dua
// cho RTAB-Map lam pose ban dau (no chi bat duoc khi lech < ~0.3 m / 5 do, xem
// docs/SLAM.md).
//
// ============ VI SAO KHOP SCAN, KHONG TUI TU ============
// Ban ROS do tren hospital: 194 lan tui tu de xuat, 186 lan co DUNG 0 inlier
// (D410 chi co anh IR, hanh lang giong nhau). Khop scan tinh diem MOI gia
// thuyet (x, y, theta) cung luc nen SO SANH duoc cac ung vien -- hai hanh lang
// giong nhau cho hai diem gan bang nhau -> biet la nhap nhang va IM LANG thay
// vi chon bua.
//
// ============ ⚠️ DA DO BEN ROS, KHONG DUOC QUEN ============
// - Xac minh bang depth QUANH mot gia thuyet (GICP) bi bac: pose SAI 22.4 m
// duoc cham TOT hon pose dung. Xac minh cuc bo khong bat duoc nham lan
// toan cuc.
// - Tren phan cung that da CHOT SAI mot lan (22.5 m, lat 180 do) du qua ca
// hai cong ty le. Ty le mot lan khop KHONG tach duoc dung/sai o dai
// 1.31-1.39 -> moi co cong nhieu vong (`min_ratio_fast`, `min_cycles`).
//
// Module nay KHONG goi RTAB-Map, khong co luong, khong doc dong ho: chi la
// ham thuan tren (luoi, diem). Viec gom scan khi xoay va dat pose ban dau la
// cua ben goi.
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// So lay NGUYEN tu ban ROS (global_scan_init.py). Doi so nao thi ghi ly do va
// so do o ben canh -- ban ROS da hai lan rut ket luan tu 2 mau roi mau thu
// ba lat nguoc.
struct GlobalLocalizerConfig {
// Do rong truong likelihood exp(-d^2 / 2 sigma^2). 0.15 m ~ 3 o luoi 0.05:
// chiu duoc sai so luoi ma khong lam nhoe het dac trung.
double sigma = 0.15;
// = Grid/RangeMax: ban do chi dung tu tia <= 12 m. Dung tia xa hon la khop
// vao vung chua tung ghi.
double max_range = 12.0;
// --- Tim tho ---
double coarse_res = 0.80; // m
double angle_step_deg = 5.0;
int top_k = 24; // dinh tho xet de gom ung vien
int max_candidates = 8; // ung vien (da khu trung) dem tinh chinh
size_t max_points = 1500; // sau khi gop diem ve o luoi
// --- Doi thu ---
// Doi thu VI TRI phai cach nguoi thang it nhat ngan nay.
double reject_radius = 2.0;
// Doi thu HUONG: CUNG cho (trong reject_radius) nhung lech it nhat ngan nay.
// Ban ROS do: dam may 360 do doi xung quay -> vi tri dung, huong sai 40-160
// do ma ty le vi tri van 1.6.
double min_angle_sep_deg = 25.0;
// --- Cong ---
double min_ratio = 1.30; // s1 / s2 (vi tri)
double min_ratio_yaw = 1.30; // s1 / s2_yaw (huong)
// Tren nguong nay chot ngay. Duoi thi phai dung dau `min_cycles` vong lien
// tiep. Ban ROS: 7 ca DUNG 1.315-1.581, 3 ca SAI 1.31-1.39.
double min_ratio_fast = 1.60;
int min_cycles = 2;
double assoc_radius = 0.8; // m, ghep gia thuyet giua hai vong
// Chi tinh mot vong vao streak khi robot DA DI it nhat ngan nay: ban sao doi
// xung 180 do cung lap lai y het khi dung yen.
double acc_min_move = 0.20;
double acc_timeout = 120.0; // s
// --- Canh "da lac" ---
double lost_score_ratio = 0.55; // diem tut duoi ty le nay so voi luc khop
double lost_hold = 3.0; // s, phai tut lien tuc ngan nay
// --- Do nghieng IMU vs do doc ban do (che do doc, xem GlobalMatch) ---
// Gia thuyet ma mat san o do gay ra do nghieng lech qua nguong nay so voi
// IMU thi bi loai. 3.5 do: tach duoc doc 5 do khoi san phang (5 do) va cac
// lan 5/10/15/20/30 do khoi nhau, van chiu sai IMU + sai do nghieng node
// ~1-2 do.
double tilt_tol_deg = 3.5;
// Chi tin do doc cua node trong ban kinh nay; xa hon = khong biet san o do
// (khong loai).
double tilt_node_radius = 1.5; // m
// Xa hon tilt_node_radius nhung NAM GIUA hai lan cung mot mat doc (node gan nhat
// hai phia doi dien, lech gradient <= tilt_agree_deg) thi dung do doc chung do --
// xem FloorGradientBetween. Sim 06/10, doc rong 8 m quet hai lan sat tuong: giua
// doc cach node 2-2.5 m, doi thu lat 180 do o doc kia lot bo loc, 8/8 cho xien
// khong chot.
double tilt_between_radius = 4.0; // m
double tilt_agree_deg = 2.5;
// Chot NHO do nghieng (tilt_used) con phai qua kiem suy bien doc truc: dich
// pose `tilt_shift_m` theo 8 huong ma diem LiDAR van >= ty le nay so voi
// pose chot -> hanh lang / doc deu, vi tri doc truc khong quan sat duoc ->
// KHONG chot. Xem ShiftScoreRatio. Do sim 2026-10-05 (dich 1 m): giua lan doc
// MU = 100% (5 ca, mot ca da chot lech 0.77 m); gan dinh doc 5 do thay tuong
// sanh tren cach 10 m = 90-92% (8/8 vong dung cho, lech 7 cm); sanh 62-65%.
double tilt_shift_m = 1.0;
double tilt_max_shift_ratio = 0.95;
// --- Vong DUNG YEN tren doc (runtime: khong xoay robot) ---
// Dung yen thi cac vong nhin GAN NHU Y HET: streak (can di >= 0.2 m) khong
// ap dung, va thu mai roi chot o vong vot qua cong la "dao nhieu". Sim
// 2026-10-05, cung mot cho: ty le NHAY hai muc -- ~1.44 khi tim thay doi thu
// that (12 m doc cung lan), ~1.63 khi vong do bo sot no; trung vi 3 vong van
// lot (1.63 / 1.40 / 1.64). Nen quyet bang ty le NHO NHAT qua moi vong lien
// tiep CUNG nguoi thang (doi thu tung hien ra = co that), can >= `static_rounds`
// vong. Nguong mac dinh = min_ratio_fast (chuan mot goc nhin).
int static_rounds = 3;
double static_min_ratio = 1.60;
double static_agree_m = 0.3;
double static_agree_deg = 5.0;
};
// Truong likelihood tren luoi chiem dung. Dung chung cho khop toan cuc VA cho
// canh "da lac" -- cung mot thang do.
class LikelihoodField {
public:
// o >= 50 la tuong, o == 0 la trong (robot chi co the dung o day), -1 chua
// biet. Khoang cach bang EDT chinh xac (Felzenszwalb-Huttenlocher).
static LikelihoodField FromGrid(const OccupancyGrid& g, double sigma);
bool empty() const { return width_ == 0 || height_ == 0; }
int width() const { return width_; }
int height() const { return height_; }
double resolution() const { return res_; }
double origin_x() const { return ox_; }
double origin_y() const { return oy_; }
// Gia tri tai o (r, c); 0 ngoai luoi.
float At(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return 0.0f;
return lf_[static_cast<size_t>(r) * width_ + c];
}
bool Free(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return false;
return free_[static_cast<size_t>(r) * width_ + c] != 0;
}
// Diem TRUNG BINH moi diem (frame map). Diem ngoai luoi khong tinh; tra -1
// neu it hon `min_points` diem roi vao luoi.
double MeanScore(const std::vector<Point>& pts_map, size_t min_points = 50) const;
private:
int width_ = 0, height_ = 0;
double res_ = 0.05, ox_ = 0.0, oy_ = 0.0;
std::vector<float> lf_;
std::vector<uint8_t> free_;
};
struct RelocHypothesis {
Pose2D map_from_odom; // T_map_odom
double score = 0.0; // diem sau tinh chinh
};
struct RelocMatch {
bool ok = false;
Pose2D map_from_odom; // nguoi thang
double s1 = 0.0; // diem nguoi thang
double s2 = 0.0; // doi thu VI TRI tot nhat (> reject_radius)
double s2_yaw = 0.0; // doi thu HUONG tot nhat (cung cho)
// T_map_odom cua hai doi thu tren (de log "nhap nhang voi cho nao").
Pose2D s2_from_odom;
Pose2D s2_yaw_from_odom;
size_t points = 0; // so diem da dung sau khi gop
std::vector<RelocHypothesis> hyps; // da tinh chinh, [0] = nguoi thang
// Loc bang bang chung ngoai LiDAR (`admit` cua GlobalMatch):
bool tilt_used = false; // ket qua tren DA loai it nhat mot gia thuyet
int tilt_rejected = 0; // so gia thuyet mau thuan bi loai (ung vien + doi thu)
// LiDAR CHAC CHAN o mot cho ma bang chung noi khong the -> bo loc, giu ket
// qua LiDAR nhu cu (khong te hon truoc), nhung phai biet.
bool tilt_conflict = false;
double ratio() const { return s1 / (s2 > 1e-9 ? s2 : 1e-9); }
double ratio_yaw() const { return s1 / (s2_yaw > 1e-9 ? s2_yaw : 1e-9); }
};
// Bang chung DOC LAP voi LiDAR cho mot gia thuyet T_map_odom: false = mau
// thuan (vd do nghieng IMU khac do doc ban do tai cho do). Xem GlobalMatch.
using RelocAdmit = std::function<bool(const Pose2D& map_from_odom)>;
// Gop diem ve o luoi `res` roi rut con toi `max_points` (giu thu tu).
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points);
// Khop TOAN CUC. `pts_odom`: diem da gom trong frame ODOM (co dinh trong luc
// xoay), da cat theo max_range. Tra ok=false neu khong co dinh nao > 0.
//
// `admit` (tuy chon) chi PHAN XU giua cac gia thuyet LiDAR KHONG phan biet
// duoc: gia thuyet bi loai khong duoc thang va khong tinh la doi thu. Nguoi
// thang hop le phai co diem >= s_tot_nhat / min_ratio (trong dai ma LiDAR mot
// minh cung nhap nhang) -- khong bao gio day mot khop LiDAR KEM ro len thang.
// Khong co gia thuyet hop le nao trong dai do -> giu ket qua LiDAR nhu cu,
// danh dau `tilt_conflict`.
//
// ⚠️ Vi sao can (sim 2026-10-05, slope_test.world): robot dat giua doc 5/10/15
// do, 6 vong x 3 doc deu NHAP NHANG (ty le ~1.00). LiDAR nghieng theo doc chi
// thay hai tuong lan; ban sao doi xung (cho phang o dau kia lan, mui nguoc)
// khop y het. IMU biet robot dang chuc 15 do -- ban sao do o san phang.
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg,
const RelocAdmit& admit = nullptr);
// Suy bien DOC TRUC: diem trung binh cua dam diem tai pose dich `shift_m` theo
// 8 huong (giu huong xoay), chia cho diem tai chinh pose -- lon nhat trong 8.
// ~1 = co mot huong dich ma khop khong xau di (hanh lang, doc deu): vi tri doc
// huong do KHONG quan sat duoc. -1 neu khong tinh duoc.
//
// ⚠️ Cong ty le chi so voi doi thu XA hon reject_radius (2 m). Sim 2026-10-05:
// robot DUNG YEN giua doc 30 do, bo loc nghieng loai het doi thu xa (lan khac,
// cho phang) -> ty le 2.17 -> chot lech 0.77 m DOC lan, cong khong thay.
double ShiftScoreRatio(const LikelihoodField& field, const std::vector<Point>& pts_odom,
const Pose2D& map_from_odom, double shift_m,
size_t max_points = 1500);
// Khop CUC BO: robot phai nam trong `radius` quanh `center` (frame map). De
// XAC MINH ung vien tu nguon khac (VPR). `odom_now`: pose robot trong frame
// odom luc gom -- rang buoc dat tren vi tri ROBOT, khong phai tam dam diem (o
// hanh lang tam lech robot nhieu met). score = -1 neu khong khop.
//
// `yaw_center` (rad, huong ROBOT trong map) + `yaw_window`: chi xet huong
// trong cua so do. Mac dinh (NAN) = moi huong.
//
// ⚠️ VI SAO CAN GIOI HAN HUONG: robot that 2026-09-29, 113/249 lan hoi LiDAR
// NHAP NHANG HUONG (mot scan LakiBeam ~270 do). Khop cuc bo MOI huong quanh
// ung vien VPR dung cho van truot sang huong LON cung voi LiDAR toan cuc (4
// lan chot sai, lech 105-177 do) -- vi no van dung LiDAR de chon huong. Anh
// VPR biet camera nhin ve dau: de NO chon huong, LiDAR chi chinh chinh xac.
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
const GlobalLocalizerConfig& cfg,
double yaw_center = NAN, double yaw_window = M_PI);
// Tich luy gia thuyet qua nhieu vong, truyen bang ODOM (pose toan cuc chua
// biet). "Streak" = so vong LIEN TIEP mot gia thuyet dung dau.
class HypothesisTracker {
public:
explicit HypothesisTracker(const GlobalLocalizerConfig& cfg) : cfg_(cfg) {}
// `odom_now`: pose odom->base luc vong nay ket thuc. `now_s`: giay, don dieu.
void Add(const RelocMatch& m, const Pose2D& odom_now, double now_s);
// Streak cua gia thuyet gan `map_from_odom` nhat (trong assoc_radius).
int Streak(const Pose2D& map_from_odom) const;
size_t size() const { return acc_.size(); }
void Clear() { acc_.clear(); have_odom_ = false; }
private:
struct Entry {
Pose2D map_from_odom;
int streak = 0;
double t_last = 0.0;
};
GlobalLocalizerConfig cfg_;
std::vector<Entry> acc_;
Pose2D odom_mark_; // odom luc streak duoc cong lan cuoi
Pose2D last_odom_; // odom luc Add() gan nhat -- de so vi tri
bool have_odom_ = false;
double t_prev_ = 0.0;
};
enum class RelocVerdict {
kAccept, // qua het cong -> dat pose ban dau
kNeedCycles, // ty le o dai bien, chua du so vong lien tiep
kAmbiguous, // ty le vi tri < min_ratio (hanh lang lap)
kAmbiguousYaw, // vi tri co the dung, HUONG khong tin duoc
kFailed, // khong khop duoc gi
};
const char* RelocVerdictName(RelocVerdict v);
// Thu tu cong nhu ban ROS: huong truoc, roi vi tri, roi dai bien + streak.
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg);
// --- Vong DUNG YEN (robot khong xoay, vd tren doc) ---
struct StaticRound {
Pose2D robot; // pose robot trong map theo nguoi thang vong do
Pose2D map_from_odom; // T_map_odom cua nguoi thang (bat bien khi robot di)
double ratio = 0.0;
double ratio_yaw = 0.0;
double shift = -1.0; // ShiftScoreRatio; < 0 = khong tinh
};
// Tom tat cac vong o MOT cho dung (goi khi roi cho do).
struct StaticPlace {
Pose2D map_from_odom;
size_t rounds = 0;
double min_ratio = 0.0;
double min_yaw = 0.0;
double max_shift = -1.0;
};
StaticPlace SummarizePlace(const std::vector<StaticRound>& hist);
// Them `r` vao `hist` (xoa truoc neu nguoi thang KHAC vong truoc qua
// static_agree_m / static_agree_deg) roi quyet. Chot khi MOT trong hai:
// 1. MOT cho: >= static_rounds vong, ty le NHO NHAT >= static_min_ratio;
// 2. HAI cho khac nhau (`prev`, truoc khi bo): MOI cho >= static_rounds vong
// voi ty le NHO NHAT >= min_ratio, CUNG T_map_odom (static_agree_*).
// Ca hai: ty le huong nho nhat >= min_ratio_yaw, shift lon nhat < nguong (neu
// `use_shift`).
//
// ⚠️ Vi sao KHONG dung streak cua HypothesisTracker o day: sim 2026-10-05, bo
// xuong chan doc 10 / 15 do, nguoi thang SAI on dinh (cao hon 2 m doc lan),
// streak len 4-6 qua cac lan bo trong khi ty le 1.0-1.2; mot vong nhay 1.32 /
// 1.34 -> chot sai 2.0 / 1.5 m. Ty le NHO NHAT moi cho chan duoc kieu do.
RelocVerdict DecideStatic(std::vector<StaticRound>* hist, const StaticRound& r,
const std::vector<StaticPlace>& prev, const GlobalLocalizerConfig& cfg,
bool use_shift, bool* along_axis, std::string* why);
} // namespace vslam
#endif // VSLAM_GLOBAL_LOCALIZER_H

View File

@@ -0,0 +1,131 @@
#ifndef VSLAM_HEIGHT_MAP_H
#define VSLAM_HEIGHT_MAP_H
// z cua ban do khi pose SLAM la SE(2): do cao tung node va mat san quanh no.
//
// ================== NGUON ==================
// Moi node mang z / roll / pitch DO luc tao (HeightEstimator + GravityAlign),
// luu trong userData cua RTAB-Map. z do co troi (truot banh, sai pitch), va
// do thi SE(2) cua RTAB-Map khong biet gi ve no.
//
// ================== DO THI z 1-D ==================
// Sau moi lan toi uu cua RTAB-Map, giai lai z bang binh phuong toi thieu:
// * lien ket LANG GIENG (node lien tiep): z_j - z_i = z_do_j - z_do_i,
// sigma = min + rel * |dz| (sai he thong ti le voi do cao leo);
// * lien ket VONG / lan can (cung cho, hai lan qua): z_j - z_i = mat phang
// doc cua node i keo toi node j. Ca hai node PHANG (|pitch| < clamp) ->
// 0, chat (3 cm). Tren doc -> theo pitch, long hon (hai node cach 1 m tren
// doc 30 do lech 0.58 m -- dz = 0 o day la SAI);
// * node dau tien neo o z do cua no; moi node co mot prior rat long ve z do
// de do thi khong lien thong van giai duoc.
// Nho vay khi robot quay ve cho cu sau mot vong co doc, sai z don ra deu
// tren vong thay vi don het vao mot cho.
//
// ================== MAT SAN ==================
// FloorModel: do cao san tai (x, y) = MAT PHANG cua node GAN NHAT (z, pitch,
// roll cua no) keo toi do. Dung cho: cat voxel theo do cao TREN san, lop vat
// can tinh theo san cuc bo (doc khong con la tuong), va neo z robot luc dinh
// vi. Node gan nhat chu khong trung binh: canh dinh doc, trung binh hai mat
// phang (doc + chieu nghi) cho ra mot san khong co that.
//
// Khong phu thuoc RTAB-Map -- test duoc rieng.
#include <cstddef>
#include <map>
#include <vector>
namespace vslam {
struct NodeHeight {
double z = 0.0; // do cao base_footprint (mat san duoi robot), m
double roll = 0.0; // nghieng than luc tao node (ROS: duong = trai len)
double pitch = 0.0; // duong = mui chuc xuong
};
struct ZGraphLink {
int from = 0;
int to = 0;
bool neighbor = false; // lien tiep (odometry) hay vong / lan can
// Vi tri node `to` trong frame node `from` (mat phang ngang), m.
double dx = 0.0;
double dy = 0.0;
};
struct ZGraphConfig {
double clamp_rad = 0.0261799; // 1.5 do: duoi nguong = phang
double sigma_neighbor = 0.01;
double sigma_rel = 0.05;
double sigma_loop_flat = 0.03;
double sigma_loop_slope = 0.10;
double sigma_first = 0.01;
double sigma_prior = 2.0; // prior long ve z do cua MOI node
};
// Tra z da toi uu cho moi node trong `meas`. Lien ket toi node khong co trong
// `meas` bi bo qua.
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg = {});
struct FloorNode {
double x = 0.0, y = 0.0, theta = 0.0; // pose (da toi uu) trong frame map
double z = 0.0, roll = 0.0, pitch = 0.0;
};
class FloorModel {
public:
// radius: chi dung node trong ban kinh nay (camera thay toi ~4 m).
void Build(const std::vector<FloorNode>& nodes, double radius = 4.0, double cell = 0.25);
// Do cao san tai (x, y) theo mat phang node gan nhat; false neu khong node
// nao trong ban kinh. `dist`: khoang cach toi node do.
bool FloorAt(double x, double y, double* z, double* dist = nullptr) const;
// Node gan nhat (trong ban kinh) cua (x, y); false neu khong co.
bool NearestNode(double x, double y, FloorNode* node, double* dist = nullptr) const;
bool empty() const { return nodes_.empty(); }
size_t size() const { return nodes_.size(); }
const std::vector<FloorNode>& nodes() const { return nodes_; }
private:
std::vector<FloorNode> nodes_;
double radius_ = 4.0, cell_ = 0.25, x0_ = 0.0, y0_ = 0.0;
int w_ = 0, h_ = 0;
std::vector<int> nearest_; // moi o: chi so node gan nhat, -1 = khong co
};
// Do cao mat phang cua node n tai (x, y).
double PlaneZ(const FloorNode& n, double x, double y);
// Do doc SAN tai (x, y): gradient (dz/dx, dz/dy, frame map) cua mat phang node
// gan nhat. false neu node gan nhat xa hon `max_dist` (khong biet san o do).
bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx,
double* gy);
// Do doc SAN GIUA HAI LAN da quet: node gan nhat va node gan nhat o PHIA DOI DIEN
// (huong lech >= 120 do), ca hai trong `max_dist`, cung mot gradient (lech <= `agree`,
// don vi tan) -> tra gradient trung binh. Doc rong quet theo vai lan thi giua hai
// lan khong co node gan (FloorGradientAt false) nhung van la mot mat doc -- NOI SUY
// thi tin duoc, NGOAI SUY (chi mot phia, vd ngoai chan doc) thi khong: false.
bool FloorGradientBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double* gx, double* gy);
// Do cao SAN giua hai lan, cung cach chon node nhu FloorGradientBetween: hai mat phang
// node cung gradient (lech <= `agree`) va du doan z tai (x, y) lech <= `agree_z` (m) ->
// trung binh. Neo z sau dinh vi lai o giua doc rong (node gan nhat xa hon 2 m).
bool FloorZBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double agree_z, double* z);
// Do lech giua do nghieng than DO DUOC (roll, pitch -- ROS, tu IMU) va do
// nghieng ma mat san gradient (gx, gy) GAY RA cho robot mui huong `yaw` (frame
// map). Don vi: do doc (tan) -- 0.087 ~ 5 do. Dinh vi lai dung no de loai gia
// thuyet mau thuan voi IMU: quay nguoc 180 do tren doc, doc o cho phang, doc
// sai goc.
double TiltResidual(double roll, double pitch, double yaw, double gx, double gy);
// Goc can quay (rad, duong = trai) de mui nhin DOC theo doc -- LEN hoac XUONG, phia
// gan hon (bang nhau thi LEN) -- chi tu do nghieng than (roll, pitch -- ROS, IMU),
// khong can biet pose. `misalign`: |goc quay|. San phang: 0.
double SlopeAlignTurn(double roll, double pitch, double* misalign = nullptr);
} // namespace vslam
#endif // VSLAM_HEIGHT_MAP_H

View File

@@ -9,6 +9,8 @@
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do // canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o". // `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
#include <map>
#include <set>
#include <string> #include <string>
#include "vslam/vslam_common.h" #include "vslam/vslam_common.h"
@@ -26,6 +28,11 @@ struct DbFacts {
int nodes = 0; int nodes = 0;
int words = 0; // 0 = ban do quet KHONG co tu vung int words = 0; // 0 = ban do quet KHONG co tu vung
std::string optimizer_strategy; // tham so DB nho, co the khac cai ta ep std::string optimizer_strategy; // tham so DB nho, co the khac cai ta ep
// DB nay duoc quet voi luoi cuc bo 3D hay khong. Quet phang roi mo ban do
// voxel len thi chi thay MOT lop ngang o cao do LiDAR -- canh bao duoc, chu
// khong phai loi.
bool grid_3d = false;
}; };
DbFacts InspectDatabase(const std::string& path); DbFacts InspectDatabase(const std::string& path);
@@ -34,9 +41,17 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
// Doc thang tu DB, khong can Rtabmap dang chay. Dung cho // Doc thang tu DB, khong can Rtabmap dang chay. Dung cho
// `tools/vslam_slam_bench` va cho viec doi DB cu sang PGM. // `tools/vslam_slam_bench` va cho viec doi DB cu sang PGM.
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path, //
double cell_size, double range_max, // `only_ids`: chi dung cac node co id trong tap nay (nullptr = moi node). De
OccupancyGrid* out); // do relocalization CONG BANG tren mot phien: ban do tu nua dau, hoi bang nua
// sau -- scan dung de hoi khong duoc gop vao ban do.
//
// `grid_params`: tham so RTAB-Map dang chay -- lay GridGlobal/* (cach cap nhat
// o) tu day. nullptr = theo tham so DB da luu luc quet.
StatusResponse ExportOccupancyGridFromDb(
const std::string& db_path, double cell_size, double range_max, OccupancyGrid* out,
const std::set<int>* only_ids = nullptr,
const std::map<std::string, std::string>* grid_params = nullptr);
} // namespace vslam } // namespace vslam

View File

@@ -23,6 +23,13 @@
namespace vslam { namespace vslam {
// Ghi de theo MOI TRUONG -- khoi `profiles:` cua slam.yaml. Chi chua nhung
// key KHAC nhau giua mo phong va robot that; phan con lai dung chung.
struct SlamProfile {
std::map<std::string, double> numbers; // odom_sigma_m, odom_sigma_rad
std::map<std::string, std::string> rtabmap; // key RTAB-Map
};
struct RtabmapConfig { struct RtabmapConfig {
// TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc // TAT mac dinh: tren may chua build RTAB-Map thi node van phai chay duoc
// day du phan con lai. // day du phan con lai.
@@ -36,7 +43,12 @@ struct RtabmapConfig {
// Reg/Strategy=1 (ICP tren LiDAR) van la thu TINH phep bien doi. Nen bat // Reg/Strategy=1 (ICP tren LiDAR) van la thu TINH phep bien doi. Nen bat
// thi giac khong danh doi do chinh xac. // thi giac khong danh doi do chinh xac.
bool visual_loop = false; bool visual_loop = false;
// Gui depth vao RTAB-Map (luu trong DB) va bat ban do voxel 3D. KHONG doi
// luoi -- xem ghi chu trong BuildRtabmapParams.
bool camera_3d = false; bool camera_3d = false;
// Do chac cua odom MOI LIEN KET gui RTAB-Map. Xem slam.yaml.
double odom_sigma_m = 0.01;
double odom_sigma_rad = 0.005;
// Optimizer. "1" = g2o. KHONG dung "2" (GTSAM): apt jammy arm64 khong co // Optimizer. "1" = g2o. KHONG dung "2" (GTSAM): apt jammy arm64 khong co
// GTSAM va PPA borglab khong publish arm64. // GTSAM va PPA borglab khong publish arm64.
@@ -45,6 +57,11 @@ struct RtabmapConfig {
// Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac // Cac key RTAB-Map doc tu khoi `rtabmap:` cua slam.yaml. Ghi de len mac
// dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren. // dinh, va bi ghi de boi cac suy dien tu mode/visual_loop o tren.
std::map<std::string, std::string> overrides; std::map<std::string, std::string> overrides;
// "sim" va "real" tu khoi `profiles:`. CHUA ap: LoadRtabmapConfig chi doc
// va kiem, ben goi chon mot cai bang ApplySlamProfile() vi chi no biet dang
// chay mo phong hay robot that.
std::map<std::string, SlamProfile> profiles;
}; };
// Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang // Tra ve tap tham so day du. `unknown` nhan ten cac key khong co trong bang
@@ -53,9 +70,14 @@ struct RtabmapConfig {
std::map<std::string, std::string> BuildRtabmapParams( std::map<std::string, std::string> BuildRtabmapParams(
const RtabmapConfig& cfg, std::vector<std::string>* unknown); const RtabmapConfig& cfg, std::vector<std::string>* unknown);
// Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode. // Doc khoi `rtabmap:` + cac key cap cao tu ConfigNode. Nem neu khoi
// `profiles:` sai luat (xem slam.yaml).
RtabmapConfig LoadRtabmapConfig(const ConfigNode& node); RtabmapConfig LoadRtabmapConfig(const ConfigNode& node);
// Ap `profiles.<name>` len cfg: sigma odom va cac key RTAB-Map cua profile.
// Loi neu khong co profile do -- KHONG lang le chay bang mac dinh cua struct.
StatusResponse ApplySlamProfile(const std::string& name, RtabmapConfig* cfg);
// Tra ve true neu RTAB-Map duoc build kem optimizer nay. // Tra ve true neu RTAB-Map duoc build kem optimizer nay.
bool OptimizerAvailable(const std::string& strategy); bool OptimizerAvailable(const std::string& strategy);

View File

@@ -19,10 +19,16 @@
// `init(params, db, loadDatabaseParameters=false)` VA assert sau do. // `init(params, db, loadDatabaseParameters=false)` VA assert sau do.
#include <memory> #include <memory>
#include <map>
#include <string> #include <string>
#include <vector>
#include <opencv2/core.hpp>
#include "vslam/height_map.h"
#include "vslam/rtabmap_params.h" #include "vslam/rtabmap_params.h"
#include "vslam/slam_types.h" #include "vslam/slam_types.h"
#include "vslam/voxel_export.h"
#include "vslam/vslam_common.h" #include "vslam/vslam_common.h"
namespace vslam { namespace vslam {
@@ -31,6 +37,15 @@ class RtabmapSlamImpl; // o namespace scope, KHONG long trong class
// (pimpl long private khong goi duoc tu .cc -- da // (pimpl long private khong goi duoc tu .cc -- da
// mac loi nay o ConfigNode va WebServer) // mac loi nay o ConfigNode va WebServer)
// Anh cua mot node ban do, cho dinh vi lai bang camera (vslam/visual_verifier.h).
struct NodeView {
cv::Mat gray; // anh IR (kenh "rgb" luc quet), 8 bit
cv::Mat depth; // CV_16UC1 (mm); rong neu with_depth = false
cv::Matx33d K; // DA bu binning -- dung nhu luc luu
cv::Matx44d T_base_optical; // base (z tu san, gom nghieng luc chup) <- optical
cv::Matx44d T_map_base; // pose TOI UU cua node
};
class RtabmapSlam { class RtabmapSlam {
public: public:
RtabmapSlam(); RtabmapSlam();
@@ -75,11 +90,60 @@ class RtabmapSlam {
// Xuat occupancy grid hien tai. Dat, goi khi map_version doi. // Xuat occupancy grid hien tai. Dat, goi khi map_version doi.
StatusResponse ExportMap(OccupancyGrid* out); StatusResponse ExportMap(OccupancyGrid* out);
// Xuat ban do VOXEL 3D. Dat hon ExportMap: no quet lai o bi chiem cua moi
// node. Goi cung nhip va cung ngan sach voi ExportMap -- xem Runtime::SlamLoop.
//
// `out->epoch` khong duoc dat o day: vong doi epoch la viec cua nguoi goi,
// chi ho moi biet tap truoc do la gi.
StatusResponse ExportVoxels(const VoxelExportOptions& opt, VoxelGrid* out);
// Node co pose toi uu (ban do dang dung), va anh + hinh hoc camera cua mot node -- DUNG
// nhu RTAB-Map da luu (K da bu binning, T gom nghieng luc chup). CHI luong slam goi (cung
// luong Process()): doc thang Memory cua RTAB-Map.
std::vector<int> MapNodeIds() const;
StatusResponse GetNodeView(int id, bool with_depth, NodeView* out);
// ---- z ban do khi di tren doc (height_map.h) ----
// Giai lai do thi z tu z DO cua node (userData) va lien ket cua do thi,
// dung lai mat san. Node chua co z do thi nap tu DB (ban do quet truoc).
// CHI luong slam goi. `nodes_out`: so node co z.
StatusResponse UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out = nullptr);
// Do cao san tai (x, y) frame map theo mat phang node gan nhat, chi khi
// node do trong `radius`. false neu khong co. CHI luong slam goi.
bool HeightAt(double x, double y, double radius, double* z) const;
const FloorModel& floor_model() const;
// Bat dung z node + mat san cho ban do voxel (sau UpdateHeights).
void SetUseHeights(bool on);
// O 2D noi camera thay mat san trong lan ExportVoxels cuoi (che do doc).
const std::vector<uint64_t>& floor_cells() const;
// Vong dong XA: node vua tao vs node CU (cach >= min_graph_gap buoc trong do
// thi) nam trong ban kinh `radius_m` theo do thi da toi uu -- tuc lan di
// TRUOC qua cung cho. Dang ky ICP giua hai scan (tham so Icp/* cua chinh ban
// do); nhan neu ICP dat va chinh so voi do thi < max_corr; them lien ket.
//
// KHONG ghep node cung mot luot di: lien ket ICP trong hanh lang khong rang
// buoc doc truc va keo ban do truot (do trong sim 04/10: detectMoreLoopClosures
// cua RTAB-Map them hang tram lien ket nhu vay, sai 12 cm -> 33 cm).
// Tra 1 = da them, 0 = khong co ung vien / ICP khong dat, -1 = loi. `detail`:
// ly do. CHI luong slam, CHI che do mapping.
int TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail);
StatusResponse Close(bool save_database); StatusResponse Close(bool save_database);
const SlamStats& stats() const; const SlamStats& stats() const;
SlamMode mode() const; SlamMode mode() const;
// Duong dan DB DA GIAI (tuong doi -> MapDir(), {stamp} da no).
// Rong = DB trong RAM. Chi co nghia sau Init().
const std::string& database_path() const;
// Tham so RTAB-Map DANG CHAY (slam.yaml + mac dinh). Dung lai GridGlobal/*
// khi dung luoi tu DB (ExportOccupancyGridFromDb) cho cung cach cap nhat o
// voi ban do dang hien.
std::map<std::string, std::string> rtabmap_parameters() const;
private: private:
std::unique_ptr<RtabmapSlamImpl> impl_; std::unique_ptr<RtabmapSlamImpl> impl_;
}; };

View File

@@ -29,8 +29,12 @@ struct SlamInput {
// odom -> base_footprint. Day la dau vao BAT BUOC: RTAB-Map o che do nay // odom -> base_footprint. Day la dau vao BAT BUOC: RTAB-Map o che do nay
// khong tu tinh odometry, no chinh odometry cua ta. // khong tu tinh odometry, no chinh odometry cua ta.
Pose2D odom; Pose2D odom;
double odom_linear_var = 0.01; // Phuong sai odom MOI LIEN KET. <= 0 = lay tu slam.yaml (odom_sigma_*).
double odom_angular_var = 0.01; // Mac dinh cu 0.01 / 0.01 (sigma 10 cm / 5.7 do) lam RTAB-Map tin ICP hon
// odom ~27 lan ve goc; 2542 lien ket ICP sai TB 0.15 do cong don thanh
// troi 0.25 m sau 37 phut quet (do tren DB 2026-09-25).
double odom_linear_var = -1.0;
double odom_angular_var = -1.0;
// Scan DA VE SINH (qua ScanSanitizer), trong frame laser. // Scan DA VE SINH (qua ScanSanitizer), trong frame laser.
const LaserScan* scan = nullptr; const LaserScan* scan = nullptr;
@@ -39,6 +43,21 @@ struct SlamInput {
const Image* depth = nullptr; const Image* depth = nullptr;
const CameraInfo* depth_info = nullptr; const CameraInfo* depth_info = nullptr;
const Image* infra1 = nullptr; // D410 KHONG co RGB -> dung IR trai lam "rgb" const Image* infra1 = nullptr; // D410 KHONG co RGB -> dung IR trai lam "rgb"
// base_footprint <- camera_depth_optical_frame TAI luc chup depth, DA gom
// nghieng do duoc (TiltLift). Null = dung ngoai lai tinh trong SetExtrinsics
// (camera coi nhu luon nam ngang).
//
// Than robot chuc len/xuong khi tang/giam toc. Coi camera nam ngang thi san
// o 3 m bi day len ~0.2 m va thanh vat can gia trong ban do 3D.
const Transform* camera_to_base = nullptr;
// Di tren doc (slam.yaml `slope:`): do cao base_footprint va nghieng than
// luc nay. Co thi luu vao node (userData cua RTAB-Map) -- xem height_map.h.
bool has_height = false;
double z = 0.0;
double roll = 0.0;
double pitch = 0.0;
}; };
struct SlamOutput { struct SlamOutput {

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,65 @@
#ifndef VSLAM_VISUAL_VERIFIER_H
#define VSLAM_VISUAL_VERIFIER_H
// Xac minh ung vien VPR bang ANH: so khop diem dac trung (ORB) giua anh hoi va anh ban do,
// nang diem ban do len 3D bang depth cua chinh anh do, roi PnP RANSAC -> pose robot.
//
// Ban C++ cua tools/reloc_pnp_eval.py -- CUNG tham so. Do 2026-09-30 (camera + LiDAR, chot
// khi pose PnP trung khop LiDAR cuc bo quanh node anh VPR): 25/09 85 -> 159 dung, 28/09
// 29 -> 40 dung, 0 chot SAI ca hai. Diem dac trung nho (goc cua, poster) nhin NGUOC lai thi
// khac han -> pha duoc doi xung hanh lang ma LiDAR va hinh khoi depth deu bi lua.
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
namespace vslam {
struct VisualVerifierConfig {
int orb_features = 1500;
int fast_threshold = 7;
double clahe_clip = 3.0; // anh IR toi: CLAHE cho x2.7 diem ORB
int clahe_grid = 8;
double ratio = 0.8; // ratio test Lowe
double depth_min_m = 0.3;
double depth_max_m = 5.0;
int ransac_iters = 300;
double reproj_px = 4.0;
double confidence = 0.999;
int min_points = 8;
};
// Mot anh da trich dac trung, kem hinh hoc camera.
struct VisualFrame {
std::vector<cv::KeyPoint> kp;
cv::Mat des;
cv::Mat depth; // CV_16UC1 (mm) hoac CV_32FC1 (m); rong neu khong can
cv::Matx33d K;
cv::Matx44d T_base_optical; // base (z tinh tu san) <- optical
};
struct PnpResult {
int matches = 0; // cap qua ratio test
int inliers = 0; // inlier PnP RANSAC; 0 = khong ra nghiem
double x = 0.0, y = 0.0, yaw = 0.0; // base cua anh hoi trong map
double dz = 0.0, tilt_deg = 0.0; // robot tren san: phai ~0 (lech = nghiem suy bien)
};
class VisualVerifier {
public:
explicit VisualVerifier(const VisualVerifierConfig& cfg = VisualVerifierConfig());
// CLAHE + ORB. `depth`, `K`, `T_base_optical` nguoi goi dien sau.
VisualFrame Extract(const cv::Mat& gray) const;
// Pose base cua anh hoi `q` trong map, tu diem khop voi anh ban do `m` (can depth) co pose
// map <- base `T_map_base_m`.
PnpResult Solve(const VisualFrame& q, const VisualFrame& m, const cv::Matx44d& T_map_base_m) const;
private:
VisualVerifierConfig cfg_;
cv::Ptr<cv::ORB> orb_;
};
} // namespace vslam
#endif // VSLAM_VISUAL_VERIFIER_H

View File

@@ -0,0 +1,293 @@
#ifndef VSLAM_VOXEL_EXPORT_H
#define VSLAM_VOXEL_EXPORT_H
// Xuat BAN DO VOXEL 3D tu do thi RTAB-Map, cho khung 3D cua web UI.
//
// Khac occupancy_export.cc o mot cho ban le: o day KHONG dung
// rtabmap::OccupancyGrid. `BuildFromCache` ep Grid/3D="false" ngay trong ham
// (occupancy_export.cc) va do la dung cho duong 2D -- no chieu moi thu xuong
// mot mat phang. Ban do 3D lay DEPTH cua tung node, chieu thanh diem MOT lan
// (cache theo id node), roi moi lan xuat chi bien doi cac diem do bang pose
// DA TOI UU. Khong dung luoi cuc bo 3D cua RTAB-Map: dung no trong process()
// keo pose lech (xem BuildRtabmapParams).
//
// ⚠️ Chinh vi dung pose da toi uu ma ban do 3D tu NAN lai sau moi vong dong:
// khong co buoc "sua ban do" nao ca, ta dung lai tu dau tu do thi moi. Doi
// lai, sau mot lan toi uu thi gan nhu MOI voxel doi chi so -- xem `epoch`
// trong VoxelGrid va luat 35% o phia web.
//
// ⚠️ `data.uncompressData()` la BAT BUOC truoc khi doc depthOrRightRaw().
// Quen no thi moi node tra ve ma tran RONG, va trieu chung la "1990 node, 0 o"
// -- y het cai bay da co trong occupancy_export.h.
#include <cstddef>
#include <cstdint>
#include <map>
#include <unordered_map>
#include <vector>
#include "vslam/height_map.h"
#include "vslam/vslam_common.h"
namespace rtabmap {
class Rtabmap;
class SensorData;
}
namespace vslam {
struct VoxelExportOptions {
// Kich thuoc o PHAT. Doc lap voi Grid/CellSize (0.05) cua SLAM: lam tho
// them mot bac cat bon lan so voxel ma mat rat it hinh dang.
double emit_size_m = 0.10;
// Cat san va tran. z do tu base_footprint = mat san.
double z_min = 0.05;
double z_max = 2.00;
// Tran SO O PHAT. Cham tran thi GIAM MAU DEU (buoc `stride`), khong cat cut
// -- ban do giu nguyen hinh dang, chi thua di. Xem Finish().
size_t max_cells = 150000;
// Gom bao nhieu khoa thi sort+unique mot lan. Doi bo nho dinh lay so lan
// tron: 2M khoa = 16 MB tam thoi.
size_t flush_every = 2000000;
// Chieu depth cua node thanh diem. Cung dai voi depth_filter (pipeline.yaml
// 0.22-4.0 m): xa hon 4 m nhieu cua D410 tang theo binh phuong.
double depth_min_m = 0.22;
double depth_max_m = 4.0;
// Bang Grid/DepthDecimation (4) ma luoi 3D cu da dung.
int depth_decimation = 4;
// So node MOI toi da doi depth -> diem trong MOT lan xuat. Localization nap
// ca nghin node mot luc; khong gioi han thi lan xuat dau chan luong slam
// hang chuc giay. Ban do day dan qua cac lan xuat.
size_t max_new_nodes = 40;
// Voxel phai duoc it nhat bay nhieu NODE KHAC NHAU thay moi giu. Diem bay,
// nhieu depth va nguoi di ngang chi o 1-2 khung; tuong, ban ghe dung yen
// thi nhieu node thay. 1 = giu moi voxel (hanh vi cu).
size_t min_node_hits = 1;
// Di tren doc: z cua tung node (do thi z) + mat san. Co ca hai thi diem dat
// o z THAT (z node + z cuc bo), va dai z_min..z_max tinh tu SAN tai cho diem
// do (mat doc khong lot vao ban do nhu vat can). Null = duong cu (moi node
// o z = 0, dai tinh tu san duoi node).
const std::map<int, double>* node_z = nullptr;
const FloorModel* floor = nullptr;
// Che do doc: thu cac o 2D (kich thuoc emit_size_m, khoa PackFloorCell) noi
// camera THAY MAT SAN (|cao - san| <= floor_band). Dung cho
// ClearLidarOnSeenRamps. Null = khong thu.
std::vector<uint64_t>* floor_cells = nullptr;
double floor_band = 0.05;
// "Lan nhin MOI NHAT quyet dinh" (07/10): voxel ma >= clear_after_views node
// SAU lan thay cuoi nhin XUYEN qua no (depth xa hon voxel + sai so depth),
// va khong node nao trong so do con thay -> XOA. Nguoi dung tren duong luc
// quet roi di -> quay lai quet la mat. 0 = tat: chi them, khong bao gio xoa
// (hanh vi truoc 07/10). Can min_node_hits >= 1 bat ky -- tu bat dem node.
size_t clear_after_views = 0;
// Chi hoi node co camera trong ban kinh nay (m): xa hon depth nhieu.
double clear_range_m = 3.5;
};
// Khoa o 2D (ix, iy) cua floor_cells.
inline uint64_t PackFloorCell(int32_t ix, int32_t iy) {
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) << 32) | static_cast<uint32_t>(iy);
}
// Diem cua tung node, o frame CUA NODE, da gom voxel. Tinh MOT lan roi giu:
// depth cua node khong doi, chi pose cua no doi sau moi lan toi uu.
// CHI luong slam cham vao.
//
// Anh depth NHO cua mot node + camera cua no, de hoi "node nay co nhin XUYEN
// qua diem X khong" (VoxelCarver). Moi o lay depth NHO NHAT cua khoi pixel:
// than trong -- mot chan nguoi chiem vai pixel van lam o do "thay vat", khong
// thanh "xuyen qua".
struct NodeDepthView {
int w = 0, h = 0;
float fx = 0.0f, fy = 0.0f, cx = 0.0f, cy = 0.0f; // theo anh NHO
float cam[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}; // base <- optical, 3x4 theo hang
std::vector<uint16_t> depth_mm; // 0 = khong do duoc
bool empty() const { return depth_mm.empty(); }
};
struct VoxelNodeCache {
struct Node {
std::vector<float> pts; // x,y,z,x,y,z... frame node, da gom voxel
NodeDepthView view; // chi khi clear_after_views > 0
};
std::unordered_map<int, Node> nodes;
// Diem node da cat theo dai z RONG (che do doc). Doi che do thi xoa cache.
bool wide = false;
// Cache co anh depth nho cua node chua. Doi tuy chon thi xoa cache.
bool views = false;
};
// Anh depth nho cua node tu SensorData (depth + camera model dau tien).
// `block`: canh khoi pixel. Khong co depth -> `out` rong.
void NodeDepthViewFromSensorData(const rtabmap::SensorData& data, int block,
NodeDepthView* out);
// "Nhin xuyen qua" (07/10): hoi cac node SAU lan cuoi mot voxel duoc thay xem
// vat do CON khong. Xet node MOI NHAT truoc -- lan nhin moi nhat quyet dinh:
// depth tai cho voxel ~ khoang cach toi voxel -> van con, GIU;
// depth XA hon voxel + sai so -> nhin xuyen qua;
// depth GAN hon -> bi che, khong biet, bo qua.
// Khong chua kieu RTAB-Map -- test duoc nhu VoxelAccumulator.
class VoxelCarver {
public:
VoxelCarver(double range_m, size_t need_views);
// `order` TANG dan theo thoi gian. base_to_map: pose node da toi uu, 3x4 theo
// hang (z da cong z node neu co). `view` phai song toi khi xong Gone().
void AddView(int order, const float base_to_map[12], const NodeDepthView* view);
// true = vat da roi di: >= need lan xuyen qua tu cac node sau `last_order`
// truoc khi gap mot node con thay no.
bool Gone(double x, double y, double z, int last_order);
size_t views() const { return views_.size(); }
private:
struct View {
int order;
float r[9]; // map <- optical, theo hang
float t[3];
const NodeDepthView* v;
};
const std::vector<int>& Near(int32_t cx, int32_t cy);
double range_;
size_t need_;
std::vector<View> views_;
std::unordered_map<uint64_t, std::vector<int>> cells_; // o 1 m -> chi so view
std::unordered_map<uint64_t, std::vector<int>> near_; // cache Near()
};
// Gom diem -> tap voxel. KHONG chua kieu nao cua RTAB-Map, nen test duoc ma
// khong can mot Rtabmap dang chay -- do la ly do no tach rieng khoi
// ExportVoxelGrid.
class VoxelAccumulator {
public:
explicit VoxelAccumulator(const VoxelExportOptions& opt);
// Toa do trong frame MAP, met.
void AddPoint(double x, double y, double z);
// Sort + unique lan cuoi roi do ra `out`. `out->cells` da sap xep.
void Finish(VoxelGrid* out);
// So diem bi bo vi ra ngoai dai int16. Khac 0 nghia la ban do vuot +-3 km
// hoac resolution bi dat sai.
size_t clamped() const { return clamped_; }
// So diem bi cat vi nam ngoai [z_min, z_max].
size_t z_rejected() const { return z_rejected_; }
// Buoc giam mau da dung o lan Finish() gan nhat. 1 = khong giam.
size_t stride() const { return stride_; }
private:
void Flush();
VoxelExportOptions opt_;
double inv_size_ = 10.0;
std::vector<uint64_t> scratch_;
std::vector<uint64_t> acc_; // luon o trang thai da sort+unique
size_t clamped_ = 0;
size_t z_rejected_ = 0;
size_t stride_ = 1;
};
// Dem so node KHAC NHAU thay moi voxel. Moi node dong gop mot voxel toi da
// MOT lan, du co bao nhieu diem roi vao do. Khong chua kieu RTAB-Map nao --
// test duoc nhu VoxelAccumulator.
class VoxelHitCounter {
public:
explicit VoxelHitCounter(const VoxelExportOptions& opt);
// `order`: thu tu thoi gian cua node (tang dan) -- VoxelCarver hoi cac node
// SAU lan cuoi voxel duoc thay. Am = tu dem.
void BeginNode(int order = -1);
// Toa do trong frame MAP, met. Cung luat cat z / dai chi so voi
// VoxelAccumulator::AddPoint.
void AddPoint(double x, double y, double z);
void EndNode();
// Voxel co >= min_node_hits node -> dua qua VoxelAccumulator: giu nguyen
// luat giam mau khi cham tran, dau ra da sort. `carver` khac null: bo them
// voxel ma cac node sau lan thay cuoi nhin xuyen qua.
void Finish(VoxelGrid* out, VoxelCarver* carver = nullptr);
size_t clamped() const { return clamped_; }
size_t stride() const { return stride_; }
size_t carved() const { return carved_; }
private:
struct Hit {
uint64_t key;
int32_t order;
bool operator<(const Hit& o) const { return key != o.key ? key < o.key : order < o.order; }
};
VoxelExportOptions opt_;
double inv_size_ = 10.0;
int order_ = -1;
std::vector<uint64_t> node_; // khoa cua node dang gom
std::vector<Hit> all_; // khoa DA khu trung theo node, cua moi node
size_t clamped_ = 0;
size_t stride_ = 1;
size_t carved_ = 0;
};
// Quet toan bo pose da toi uu va dung lai tap voxel tu dau.
//
// `out->epoch` KHONG duoc dat o day -- nguoi goi quan ly vong doi epoch, vi
// chi ho moi biet tap truoc do la gi.
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const VoxelExportOptions& opt,
VoxelNodeCache* cache, VoxelGrid* out);
// Depth trong `data` (da uncompressData) -> diem o frame base cua node, cat
// theo depth_min/max va z_min/z_max, gom theo emit_size_m. Rong neu node
// khong co depth. Tach rieng de test duoc ma khong can Rtabmap.
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out);
// Danh dau o 2D bi chiem duoi moi voxel co tam trong [z_min, z_max] (tinh tu
// mat san). La LOP VAT CAN tu camera cho nhung thu LiDAR (0.22 m) khong cat
// ngang: mat ghe, khung giuong, ke thap. Chi THEM o bi chiem, khong xoa.
// Tra ve so o moi danh dau (truoc do trong/chua biet).
//
// `floor` (di tren doc): do cao tinh tu SAN TAI CHO voxel (FloorModel) thay vi
// tu z = 0 -- mat doc va san tang tren khong con bi danh la tuong. Null =
// duong cu.
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid, const FloorModel* floor = nullptr);
// Di tren doc: TREN DOC, lop LiDAR nhuong cho camera.
//
// LiDAR ngang thay mat doc len tu xa (> 4 m, ngoai tam depth) nhu mot buc
// tuong -- tuong gia vao node TRUOC khi camera kip thay mat doc, va cac scan
// sau BO tia cham doc (NaN) nen khong tia nao xoa duoc no. O day: o LiDAR bi
// chiem ma (1) node ban do gan nhat (trong `max_node_dist`) dang TREN DOC
// (|pitch| >= clamp) va (2) camera da THAY MAT SAN o do (floor_cells) -> tra
// ve trong. Vat can THAT tren doc van duoc MarkVoxelObstacles danh lai (goi
// SAU ham nay). Camera chua thay thi giu nguyen -- khong co bang chung.
// Tra ve so o da xoa.
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist);
// Hieu hai tap DA SAP XEP: `added` co trong `now` ma khong co trong `prev`,
// `removed` thi nguoc lai. O(n + m), mot luot.
//
// Tach ra de test duoc va de nguoi goi quyet dinh gui delta hay gui lai ca
// tap dua tren ti le thay doi.
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
const std::vector<VoxelIndex>& now,
std::vector<VoxelIndex>* added,
std::vector<VoxelIndex>* removed);
} // namespace vslam
#endif // VSLAM_VOXEL_EXPORT_H

View File

@@ -0,0 +1,52 @@
#ifndef VSLAM_VPR_ENCODER_H
#define VSLAM_VPR_ENCODER_H
// Nhan dien NOI CHON bang anh (VPR): anh IR -> mo ta 2048 chieu da chuan hoa L2.
// Hai anh chup cung mot cho co tich vo huong (cosine) cao.
//
// Mo hinh: EigenPlaces ResNet50, xuat ONNX bang tools/vpr_export_onnx.py. Chay bang
// TensorRT tren Jetson -- do 2026-09-30 (JetPack 6.1): fp16 6.5 ms/anh, OpenCV CPU
// 299 ms/anh. Build khong co -DVSLAM_WITH_TENSORRT=ON thi CreateVprEncoder() tra
// Unavailable: dinh vi lai van chay bang LiDAR nhu cu.
//
// Engine TensorRT (.plan) RIENG tung may + phien ban TensorRT. Dung MOT lan tren may do
// (lenh viet tren MOT dong):
// /usr/src/tensorrt/bin/trtexec --onnx=resources/vpr/eigenplaces_r50_2048_384x512.onnx
// --fp16 --saveEngine=resources/vpr/eigenplaces_r50_fp16.plan
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include "vslam/vslam_common.h"
namespace vslam {
// Tien xu ly PHAI giong tools/vpr_export_onnx.py (noi da do 88-89% top-1 tren anh IR).
struct VprConfig {
std::string engine_path; // .plan cua TensorRT
int width = 512;
int height = 384;
double clahe_clip = 2.0;
int clahe_grid = 8;
};
class VprEncoder {
public:
virtual ~VprEncoder() = default;
// Anh IR xam 8 bit, kich thuoc bat ky -> mo ta dim() so, da chuan hoa L2.
virtual StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) = 0;
virtual int dim() const = 0;
};
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out);
// Anh xam -> tensor (3, height, width) float32 hang CHW: CLAHE -> resize INTER_LINEAR ->
// /255 -> lap 3 kenh -> chuan hoa ImageNet. Tach rieng de dung/test khong can TensorRT.
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw);
} // namespace vslam
#endif // VSLAM_VPR_ENCODER_H

View File

@@ -0,0 +1,832 @@
#include "vslam/global_localizer.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
#include <unordered_set>
#include "vslam/geometry.h"
namespace vslam {
namespace {
constexpr double kDegToRad = M_PI / 180.0;
// EDT 1D (Felzenszwalb-Huttenlocher): d[i] = min_j (f[j] + (i-j)^2).
// Phan tu f = inf (khong co tuong) KHONG BAO GIO nam tren duong bao duoi, nen
// bo qua han -- de nguyen trong cong thuc giao diem thi ra inf - inf = NaN.
void Edt1d(const std::vector<float>& f, std::vector<float>* d,
std::vector<int>* v, std::vector<double>* z) {
const int n = static_cast<int>(f.size());
const float inf = std::numeric_limits<float>::infinity();
int k = -1;
for (int q = 0; q < n; ++q) {
if (f[q] == inf) continue;
if (k < 0) {
k = 0;
(*v)[0] = q;
(*z)[0] = -std::numeric_limits<double>::infinity();
(*z)[1] = std::numeric_limits<double>::infinity();
continue;
}
double s;
while (true) {
const int p = (*v)[k];
s = ((f[q] + static_cast<double>(q) * q) - (f[p] + static_cast<double>(p) * p)) /
(2.0 * (q - p));
// z[0] = -inf nen k khong bao gio xuong duoi 0.
if (s <= (*z)[k]) { --k; continue; }
break;
}
++k;
(*v)[k] = q;
(*z)[k] = s;
(*z)[k + 1] = std::numeric_limits<double>::infinity();
}
if (k < 0) { // ca hang/cot khong co tuong
for (int q = 0; q < n; ++q) (*d)[q] = inf;
return;
}
k = 0;
for (int q = 0; q < n; ++q) {
while ((*z)[k + 1] < q) ++k;
const int p = (*v)[k];
(*d)[q] = static_cast<float>((q - p) * static_cast<double>(q - p) + f[p]);
}
}
struct Refined {
double score = -1.0;
double x = 0.0, y = 0.0, th = 0.0; // (x, y) tuong doi goc luoi, met
};
// Mot luot luoi (x, y, theta) quanh (x0, y0, th0): x, y trong +-n_xy buoc
// dxy, theta trong +-n_a buoc da. Tinh truc tiep, khong FFT.
Refined SearchGrid(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, int n_xy, double dxy,
int n_a, double da) {
const double res = f.resolution();
Refined best;
std::vector<double> qx(P.size()), qy(P.size());
for (int ia = -n_a; ia <= n_a; ++ia) {
const double th = th0 + ia * da;
const double ct = std::cos(th), st = std::sin(th);
for (size_t i = 0; i < P.size(); ++i) {
qx[i] = ct * P[i].x - st * P[i].y;
qy[i] = st * P[i].x + ct * P[i].y;
}
for (int ix = -n_xy; ix <= n_xy; ++ix) {
const double x = x0 + ix * dxy;
for (int iy = -n_xy; iy <= n_xy; ++iy) {
const double y = y0 + iy * dxy;
double s = 0.0;
for (size_t i = 0; i < P.size(); ++i) {
const int c = static_cast<int>(std::lround((qx[i] + x) / res));
const int r = static_cast<int>(std::lround((qy[i] + y) / res));
s += f.At(r, c);
}
if (s > best.score) best = Refined{s, x, y, th};
}
}
}
return best;
}
// Tinh chinh mot ung vien o do phan giai ban do.
Refined Refine(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, double rc,
const GlobalLocalizerConfig& cfg) {
const double res = f.resolution();
const double step = cfg.angle_step_deg * kDegToRad;
// Luot 1 = ban ROS: +-nua o tho buoc 2*res, +-mot buoc goc buoc (buoc / 5).
const int n_xy = std::max(1, static_cast<int>(std::lround((rc / 2.0) / (2.0 * res))));
const Refined r1 = SearchGrid(f, P, x0, y0, th0, n_xy, 2.0 * res, 5, step / 5.0);
if (r1.score < 0.0) return r1;
// [vslam] Luot 2 min hon: +-0.1 m buoc res/2, +-(buoc / 5) buoc (buoc / 25).
// Lech 1.5 do o 7 m la 0.19 m ~ 1.3 sigma -- keo diem pose DUNG xuong va lam
// ty le kem tach bach (test tong hop 2026-09-29: sai 1.57 do). Ap cho MOI
// ung vien -- ca doi thu -- de so diem cong bang.
return SearchGrid(f, P, r1.x, r1.y, r1.th, 4, res / 2.0, 5, step / 25.0);
}
} // namespace
// ---------------------------------------------------------------------------
// LikelihoodField
// ---------------------------------------------------------------------------
LikelihoodField LikelihoodField::FromGrid(const OccupancyGrid& g, double sigma) {
LikelihoodField out;
out.width_ = static_cast<int>(g.width);
out.height_ = static_cast<int>(g.height);
out.res_ = g.resolution;
out.ox_ = g.origin.position.x;
out.oy_ = g.origin.position.y;
const size_t n = static_cast<size_t>(out.width_) * out.height_;
out.lf_.assign(n, 0.0f);
out.free_.assign(n, 0);
if (n == 0 || g.data.size() != n) return out;
const float inf = std::numeric_limits<float>::infinity();
std::vector<float> d2(n, inf);
bool any_occ = false;
for (size_t i = 0; i < n; ++i) {
if (g.data[i] >= 50) { d2[i] = 0.0f; any_occ = true; }
out.free_[i] = (g.data[i] == 0) ? 1 : 0;
}
if (!any_occ) return out;
// EDT tach duoc: cot roi hang, don vi o^2.
const int W = out.width_, H = out.height_;
const int m = std::max(W, H);
std::vector<float> f(m), d(m);
std::vector<double> z(m + 1);
std::vector<int> v(m);
for (int c = 0; c < W; ++c) {
f.resize(H); d.resize(H);
for (int r = 0; r < H; ++r) f[r] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int r = 0; r < H; ++r) d2[static_cast<size_t>(r) * W + c] = d[r];
}
for (int r = 0; r < H; ++r) {
f.resize(W); d.resize(W);
for (int c = 0; c < W; ++c) f[c] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int c = 0; c < W; ++c) d2[static_cast<size_t>(r) * W + c] = d[c];
}
const double k = (out.res_ * out.res_) / (2.0 * sigma * sigma);
for (size_t i = 0; i < n; ++i) {
out.lf_[i] = static_cast<float>(std::exp(-d2[i] * k));
}
return out;
}
double LikelihoodField::MeanScore(const std::vector<Point>& pts_map,
size_t min_points) const {
double s = 0.0;
size_t cnt = 0;
for (const Point& p : pts_map) {
const int c = static_cast<int>(std::lround((p.x - ox_) / res_));
const int r = static_cast<int>(std::lround((p.y - oy_) / res_));
if (r < 0 || c < 0 || r >= height_ || c >= width_) continue;
s += lf_[static_cast<size_t>(r) * width_ + c];
++cnt;
}
if (cnt < min_points || cnt == 0) return -1.0;
return s / static_cast<double>(cnt);
}
// ---------------------------------------------------------------------------
// Khop toan cuc
// ---------------------------------------------------------------------------
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points) {
// Nhieu tia roi vao mot o thi khong them thong tin, chi lam cham.
std::vector<Point> out;
out.reserve(pts.size());
std::unordered_set<uint64_t> seen;
seen.reserve(pts.size() * 2);
for (const Point& p : pts) {
const int64_t kx = static_cast<int64_t>(std::llround(p.x / res));
const int64_t ky = static_cast<int64_t>(std::llround(p.y / res));
const uint64_t key = (static_cast<uint64_t>(kx) << 32) ^
static_cast<uint32_t>(ky);
if (seen.insert(key).second) out.push_back(p);
}
if (max_points > 0 && out.size() > max_points) {
const size_t step = (out.size() + max_points - 1) / max_points;
std::vector<Point> thin;
thin.reserve(out.size() / step + 1);
for (size_t i = 0; i < out.size(); i += step) thin.push_back(out[i]);
out.swap(thin);
}
return out;
}
namespace {
// Luoi tho + dam diem da can tam -- dung chung cho GlobalMatch va LocalMatch.
struct Coarse {
double res = 0.05;
int k = 1; // o tho = k x k o min
double rc = 0.8; // canh o tho, met
int Wc = 0, Hc = 0;
std::vector<float> Lc; // max-pool truong likelihood
std::vector<uint8_t> Fc; // o tho co it nhat mot o min TRONG
Point cen; // tam dam diem (frame odom)
std::vector<Point> P; // diem da tru tam
double step = 0.0; // buoc goc, rad
int n_ang = 0;
int R = 0; // ban kinh histogram do lech, o tho
// Tam cua khoi tho b, met tuong doi goc luoi. O min i co tam i*res.
double BlockCenter(int b) const { return (b * k + (k - 1) / 2.0) * res; }
bool FreeCell(int r, int c) const { return Fc[static_cast<size_t>(r) * Wc + c] != 0; }
};
Coarse PrepareCoarse(const LikelihoodField& field, const std::vector<Point>& pts,
const GlobalLocalizerConfig& cfg) {
Coarse cz;
cz.res = field.resolution();
// Phai la MAX chu khong phai trung binh: muc tho de SANG LOC, bo sot mot
// dinh that o day thi khong con co hoi tinh chinh no nua.
cz.k = std::max(1, static_cast<int>(std::lround(cfg.coarse_res / cz.res)));
cz.rc = cz.res * cz.k;
const int W = field.width(), H = field.height();
cz.Wc = (W + cz.k - 1) / cz.k;
cz.Hc = (H + cz.k - 1) / cz.k;
cz.Lc.assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
cz.Fc.assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0);
for (int r = 0; r < H; ++r) {
for (int c = 0; c < W; ++c) {
const size_t ci = static_cast<size_t>(r / cz.k) * cz.Wc + (c / cz.k);
cz.Lc[ci] = std::max(cz.Lc[ci], field.At(r, c));
if (field.Free(r, c)) cz.Fc[ci] = 1;
}
}
// Xoay quanh TAM dam diem cho on dinh so hoc.
for (const Point& p : pts) { cz.cen.x += p.x; cz.cen.y += p.y; }
cz.cen.x /= static_cast<double>(pts.size());
cz.cen.y /= static_cast<double>(pts.size());
cz.P.resize(pts.size());
double maxn = 0.0;
for (size_t i = 0; i < pts.size(); ++i) {
cz.P[i].x = pts[i].x - cz.cen.x;
cz.P[i].y = pts[i].y - cz.cen.y;
maxn = std::max(maxn, std::hypot(cz.P[i].x, cz.P[i].y));
}
cz.step = cfg.angle_step_deg * kDegToRad;
cz.n_ang = std::max(1, static_cast<int>(std::lround(2.0 * M_PI / cz.step)));
cz.R = static_cast<int>(std::ceil(maxn / cz.rc)) + 1;
return cz;
}
struct AnglePeak { double score; int r, c; double th; };
// Diem THO cua goc thu `ia` tai moi o `allowed(r, c)` (o khac = 0).
//
// Ban ROS dung FFT; o day cong truc tiep tren cac do lech DA GOP (histogram do
// lech o tho) -- cung ket qua (khong cuon vong), khong can FFT.
template <class Allowed>
AnglePeak ScoreAngle(const Coarse& cz, int ia, Allowed allowed, std::vector<float>* sc) {
struct Off { int dr, dc; float n; };
const double th = ia * cz.step;
const double ct = std::cos(th), st = std::sin(th);
const int HW = 2 * cz.R + 1;
std::vector<float> hist(static_cast<size_t>(HW) * HW, 0.0f);
for (const Point& p : cz.P) {
const int dc = static_cast<int>(std::lround((ct * p.x - st * p.y) / cz.rc));
const int dr = static_cast<int>(std::lround((st * p.x + ct * p.y) / cz.rc));
hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)] += 1.0f;
}
std::vector<Off> offs;
for (int dr = -cz.R; dr <= cz.R; ++dr) {
for (int dc = -cz.R; dc <= cz.R; ++dc) {
const float n = hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)];
if (n > 0.0f) offs.push_back({dr, dc, n});
}
}
sc->assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
AnglePeak pk{-1.0, 0, 0, th};
for (int r = 0; r < cz.Hc; ++r) {
for (int c = 0; c < cz.Wc; ++c) {
if (!allowed(r, c)) continue;
double s = 0.0;
for (const Off& o : offs) {
const int rr = r + o.dr, cc = c + o.dc;
if (rr < 0 || cc < 0 || rr >= cz.Hc || cc >= cz.Wc) continue;
s += o.n * cz.Lc[static_cast<size_t>(rr) * cz.Wc + cc];
}
(*sc)[static_cast<size_t>(r) * cz.Wc + c] = static_cast<float>(s);
if (s > pk.score) pk = AnglePeak{s, r, c, th};
}
}
return pk;
}
// (x, y, th) dat TAM dam diem vao cho nao tren luoi. Doi sang T_map_odom:
// p_map = R(th) * p_odom + t, t = (x, y) + goc_luoi - R(th) * tam
Pose2D ToMap(const Refined& rf, const Point& cen, const LikelihoodField& f) {
const double ct = std::cos(rf.th), st = std::sin(rf.th);
return Pose2D{rf.x + f.origin_x() - (ct * cen.x - st * cen.y),
rf.y + f.origin_y() - (st * cen.x + ct * cen.y),
NormalizeAngle(rf.th)};
}
} // namespace
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg,
const RelocAdmit& admit) {
RelocMatch out;
if (field.empty() || pts_odom.empty()) return out;
const double res = field.resolution();
const std::vector<Point> pts = DownsamplePoints(pts_odom, res, cfg.max_points);
out.points = pts.size();
if (pts.empty()) return out;
const Coarse cz = PrepareCoarse(field, pts, cfg);
const int k = cz.k;
const double rc = cz.rc;
const int Wc = cz.Wc, Hc = cz.Hc;
const std::vector<Point>& P = cz.P;
const double step = cz.step;
const int n_ang = cz.n_ang;
auto block_center = [&](int b) { return cz.BlockCenter(b); };
// --- Quet tho: MOI goc x MOI o trong ---
// ⚠️ Rang buoc "o trong" dat tren TAM dam diem, dung nhu ban ROS
// (`sc[~Fc] = 0` tren luoi dat tam). Dam may 300 do quanh robot co tam gan
// robot nen gan nhu tuong duong.
std::vector<std::vector<float>> scores(n_ang);
std::vector<AnglePeak> peaks;
peaks.reserve(n_ang);
for (int ia = 0; ia < n_ang; ++ia) {
peaks.push_back(ScoreAngle(cz, ia, [&](int r, int c) { return cz.FreeCell(r, c); },
&scores[ia]));
}
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
if (peaks.empty() || peaks[0].score <= 0.0) return out;
// T_map_odom cua mot o tho: TAM dam diem dat vao tam khoi (r, c), xoay th.
auto coarse_map = [&](int r, int c, double th) {
Refined q;
q.x = block_center(c);
q.y = block_center(r);
q.th = th;
return ToMap(q, cz.cen, field);
};
// --- Gom TOP-K dinh tho, khu trung trong reject_radius ---
// Xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool nen rat
// rong rai, thu tu o day chua chac dung.
const double rad_c = cfg.reject_radius / rc;
std::vector<AnglePeak> cand;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(peaks.size())); ++i) {
const AnglePeak& p = peaks[i];
bool dup = false;
for (const AnglePeak& q : cand) {
const double dr = p.r - q.r, dc = p.c - q.c;
if (dr * dr + dc * dc <= rad_c * rad_c) { dup = true; break; }
}
if (!dup) cand.push_back(p);
if (static_cast<int>(cand.size()) >= cfg.max_candidates) break;
}
// Co bang chung ngoai: them dinh TOT NHAT HOP LE cua moi goc. Dinh tho cao
// nhat moi goc co the deu la ban sao doi xung bi loai, va khi do cho that
// khong bao gio duoc tinh chinh. Chi goi `admit` khi o vuot dinh hien tai.
std::vector<AnglePeak> acand;
if (admit) {
std::vector<AnglePeak> apeaks;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
const std::vector<float>& sc = scores[ia];
AnglePeak bp{0.0, -1, -1, th};
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > bp.score && admit(coarse_map(r, c, th))) bp = AnglePeak{v, r, c, th};
}
}
if (bp.r >= 0) apeaks.push_back(bp);
}
std::sort(apeaks.begin(), apeaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(apeaks.size())); ++i) {
const AnglePeak& p = apeaks[i];
bool dup = false;
auto near = [&](const AnglePeak& q) {
const double dr = p.r - q.r, dc = p.c - q.c;
return dr * dr + dc * dc <= rad_c * rad_c;
};
// Dinh LiDAR goc o CUNG cho nhung lat huong la ung vien KHAC han.
for (const AnglePeak& q : cand) {
if (near(q) && std::fabs(AngleDiff(p.th, q.th)) < min_sep) { dup = true; break; }
}
for (const AnglePeak& q : acand) {
if (!dup && near(q)) { dup = true; break; }
}
if (!dup) acand.push_back(p);
if (static_cast<int>(acand.size()) >= cfg.max_candidates) break;
}
}
// ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. So o muc tho (co
// max-pool) thi gan nhu moi cho canh tuong deu diem cao -- ban ROS do duoc
// tot/xau chi cach nhau 1.18 lan, cong chan loai ca ca DUNG.
auto refine_all = [&](const std::vector<AnglePeak>& src, std::vector<Refined>* dst) {
for (const AnglePeak& p : src) {
const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg);
if (rf.score >= 0.0) dst->push_back(rf);
}
std::sort(dst->begin(), dst->end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
};
std::vector<Refined> refined;
refine_all(cand, &refined);
if (refined.empty()) return out;
// --- Loc bang bang chung ngoai LiDAR (xem global_localizer.h) ---
// Nguoi thang hop le phai nam trong dai LiDAR mot minh cung nhap nhang
// (>= s_tot_nhat / min_ratio). Ngoai dai do = LiDAR CHAC o cho bang chung noi
// khong the -> giu nguyen ket qua LiDAR (y het khong co `admit`: ung vien them
// tu `acand` khong duoc dung), chi danh dau.
bool filt = false;
if (admit) {
std::vector<Refined> keep;
refine_all(acand, &keep); // dinh hop le them -- da hop le o muc tho
keep.erase(std::remove_if(keep.begin(), keep.end(),
[&](const Refined& rf) { return !admit(ToMap(rf, cz.cen, field)); }),
keep.end());
for (const Refined& rf : refined) {
if (admit(ToMap(rf, cz.cen, field))) {
keep.push_back(rf);
} else {
++out.tilt_rejected;
}
}
std::sort(keep.begin(), keep.end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
if (!keep.empty() && keep[0].score >= refined[0].score / cfg.min_ratio) {
refined.swap(keep);
filt = true;
} else {
out.tilt_conflict = true;
}
}
// Doi thu cung phai hop le: gia thuyet bang chung noi khong the thi khong
// canh tranh. ⚠️ Ke ca khi KHONG ung vien nao bi loai: ban lat 180 do o CUNG
// cho khong nam trong danh sach tinh chinh (gom theo vi tri) ma chi hien o
// doi thu HUONG -- dung ca lan doc. Xung dot thi moi thu nhu cu.
auto rival_ok = [&](int r, int c, double th) {
if (!filt || admit(coarse_map(r, c, th))) return true;
++out.tilt_rejected;
return false;
};
const Refined& best = refined[0];
// --- Doi thu VI TRI ---
// ⚠️ Phai LUON tim duoc, ke ca ngoai top-K. Ban ROS: tren ban do nho ca 8
// ung vien nam gon trong 2 m cua nhau -> s2 = 0 -> ty le len vo cuc va node
// chot bua (9.3% duong tinh gia, sai 9-13 m). Nen quet lai diem THO o vung xa.
double s2 = 0.0;
for (size_t i = 1; i < refined.size(); ++i) {
if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius &&
refined[i].score > s2) {
s2 = refined[i].score;
out.s2_from_odom = ToMap(refined[i], cz.cen, field);
}
}
const int rw = static_cast<int>(std::lround(best.y / res)) / k;
const int cw = static_cast<int>(std::lround(best.x / res)) / k;
auto is_far = [&](int r, int c) {
const double dr = r - rw, dc = c - cw;
return dr * dr + dc * dc > rad_c * rad_c;
};
{
double fv = -1.0;
int fr = -1, fc = -1;
double fth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > fv && is_far(r, c) && rival_ok(r, c, ia * step)) {
fv = v; fr = r; fc = c; fth = ia * step;
}
}
}
}
if (fr >= 0 && fv > 0.0) {
const Refined alt = Refine(field, P, block_center(fc), block_center(fr), fth, rc, cfg);
if (alt.score > s2) {
s2 = alt.score;
out.s2_from_odom = ToMap(alt, cz.cen, field);
}
}
}
// --- Doi thu HUONG: CUNG cho, KHAC huong ---
double s2_yaw = 0.0;
{
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
double gv = -1.0;
int gr = -1, gc = -1;
double gth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
if (std::fabs(AngleDiff(th, best.th)) < min_sep) continue;
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > gv && !is_far(r, c) && rival_ok(r, c, th)) { gv = v; gr = r; gc = c; gth = th; }
}
}
}
if (gr >= 0 && gv > 0.0) {
const Refined alt = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg);
s2_yaw = alt.score;
out.s2_yaw_from_odom = ToMap(alt, cz.cen, field);
}
}
out.tilt_used = filt && out.tilt_rejected > 0;
for (const Refined& rf : refined) out.hyps.push_back({ToMap(rf, cz.cen, field), rf.score});
out.map_from_odom = out.hyps[0].map_from_odom;
out.s1 = best.score;
out.s2 = s2;
out.s2_yaw = s2_yaw;
out.ok = true;
return out;
}
double ShiftScoreRatio(const LikelihoodField& field, const std::vector<Point>& pts_odom,
const Pose2D& map_from_odom, double shift_m, size_t max_points) {
if (field.empty() || pts_odom.empty()) return -1.0;
const std::vector<Point> pts = DownsamplePoints(pts_odom, field.resolution(), max_points);
auto score = [&](const Pose2D& T) {
const double c = std::cos(T.theta), s = std::sin(T.theta);
std::vector<Point> m(pts.size());
for (size_t i = 0; i < pts.size(); ++i) {
m[i].x = T.x + c * pts[i].x - s * pts[i].y;
m[i].y = T.y + s * pts[i].x + c * pts[i].y;
}
return field.MeanScore(m);
};
const double s0 = score(map_from_odom);
if (s0 <= 0.0) return -1.0;
double best = 0.0;
for (int k = 0; k < 8; ++k) {
const double a = k * M_PI / 4.0;
Pose2D t = map_from_odom;
t.x += shift_m * std::cos(a);
t.y += shift_m * std::sin(a);
best = std::max(best, score(t));
}
return best / s0;
}
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
const GlobalLocalizerConfig& cfg,
double yaw_center, double yaw_window) {
RelocHypothesis out;
out.score = -1.0;
if (field.empty() || pts_odom.empty()) return out;
const std::vector<Point> pts =
DownsamplePoints(pts_odom, field.resolution(), cfg.max_points);
if (pts.empty()) return out;
const Coarse cz = PrepareCoarse(field, pts, cfg);
// Rang buoc dat tren vi tri ROBOT, khong phai tam dam diem: o hanh lang tam
// lech robot nhieu met. Voi goc th, robot roi dung `center` khi tam dat tai
// center - R(th) * (robot_odom - tam)
// (met tuong doi goc luoi). Nua o tho cong them de khong cat hut o bien.
const double bx = odom_now.x - cz.cen.x, by = odom_now.y - cz.cen.y;
const double cx = center.x - field.origin_x(), cy = center.y - field.origin_y();
const double r2 = (radius + 0.5 * cz.rc) * (radius + 0.5 * cz.rc);
std::vector<AnglePeak> peaks;
std::vector<float> sc;
for (int ia = 0; ia < cz.n_ang; ++ia) {
const double th = ia * cz.step;
// Huong ROBOT trong map ung voi goc th: th + odom_now.theta. Cong mot buoc
// goc de khong cat hut goc tho sat bien cua so (tinh chinh +-1 buoc).
if (std::isfinite(yaw_center) &&
std::fabs(AngleDiff(th + odom_now.theta, yaw_center)) > yaw_window + cz.step) {
continue;
}
const double ct = std::cos(th), st = std::sin(th);
const double px = cx - (ct * bx - st * by), py = cy - (st * bx + ct * by);
const AnglePeak pk = ScoreAngle(
cz, ia,
[&](int r, int c) {
if (!cz.FreeCell(r, c)) return false;
const double dx = cz.BlockCenter(c) - px, dy = cz.BlockCenter(r) - py;
return dx * dx + dy * dy <= r2;
},
&sc);
if (pk.score > 0.0) peaks.push_back(pk);
}
if (peaks.empty()) return out;
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
// Tinh chinh vai dinh dau (cung ly do nhu GlobalMatch: so o muc tho la sai).
Refined best;
for (size_t i = 0; i < peaks.size() && i < 3; ++i) {
const Refined rf = Refine(field, cz.P, cz.BlockCenter(peaks[i].c),
cz.BlockCenter(peaks[i].r), peaks[i].th, cz.rc, cfg);
if (rf.score > best.score) best = rf;
}
if (best.score < 0.0) return out;
out.map_from_odom = ToMap(best, cz.cen, field);
out.score = best.score;
return out;
}
// ---------------------------------------------------------------------------
// Tich luy qua nhieu vong
// ---------------------------------------------------------------------------
//
// Luu T_map_odom chu khong luu pose robot: T_map_odom KHONG doi khi robot di
// (frame odom co dinh), nen khong phai truyen tung gia thuyet theo delta odom
// nhu ban ROS -- chi can ghep voi odom HIEN TAI khi so sanh vi tri.
//
// ⚠️ Khac ban ROS mot cho, co chu y: ban ROS dat lai moc odom MOI vong, ke ca
// vong chua du `acc_min_move` -- nen di cham (moi vong < 0.2 m) thi KHONG bao
// gio cong duoc streak. O day moc chi dat lai khi DA cong: quang duong duoc
// cong don cho toi khi du.
void HypothesisTracker::Add(const RelocMatch& m, const Pose2D& odom_now, double now_s) {
if (!m.ok || m.hyps.empty()) return;
if (!acc_.empty() && now_s - t_prev_ > cfg_.acc_timeout) acc_.clear();
t_prev_ = now_s;
last_odom_ = odom_now;
if (acc_.empty() || !have_odom_) {
acc_.clear();
for (size_t i = 0; i < m.hyps.size(); ++i) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
}
odom_mark_ = odom_now;
have_odom_ = true;
return;
}
// Cung cho -> streak KHONG duoc cong: ban sao doi xung cung lap lai y het.
if (std::hypot(odom_now.x - odom_mark_.x, odom_now.y - odom_mark_.y) < cfg_.acc_min_move) {
for (Entry& e : acc_) e.t_last = now_s;
return;
}
odom_mark_ = odom_now;
const double r2 = cfg_.assoc_radius * cfg_.assoc_radius;
for (size_t i = 0; i < m.hyps.size(); ++i) {
const Pose2D ph = Pose2DCompose(m.hyps[i].map_from_odom, odom_now);
Entry* hit = nullptr;
double bd = r2;
for (Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, odom_now);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; hit = &e; }
}
if (hit == nullptr) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
continue;
}
hit->map_from_odom = m.hyps[i].map_from_odom; // bam theo do do moi nhat
hit->t_last = now_s;
hit->streak = (i == 0) ? hit->streak + 1 : 0;
}
// Bo gia thuyet khong xuat hien lai o vong nay.
acc_.erase(std::remove_if(acc_.begin(), acc_.end(),
[&](const Entry& e) { return e.t_last < now_s; }),
acc_.end());
}
int HypothesisTracker::Streak(const Pose2D& map_from_odom) const {
const Pose2D ph = Pose2DCompose(map_from_odom, last_odom_);
int best = 0;
double bd = cfg_.assoc_radius * cfg_.assoc_radius;
for (const Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, last_odom_);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; best = e.streak; }
}
return best;
}
// ---------------------------------------------------------------------------
// Cong
// ---------------------------------------------------------------------------
const char* RelocVerdictName(RelocVerdict v) {
switch (v) {
case RelocVerdict::kAccept: return "CHOT";
case RelocVerdict::kNeedCycles: return "DAI_BIEN_CHO_VONG";
case RelocVerdict::kAmbiguous: return "NHAP_NHANG";
case RelocVerdict::kAmbiguousYaw: return "NHAP_NHANG_HUONG";
case RelocVerdict::kFailed: return "THAT_BAI";
}
return "?";
}
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg) {
if (!m.ok) return RelocVerdict::kFailed;
// Huong truoc: khong co cong nay thi vi tri dung, huong sai 40-160 do ma ty
// le vi tri van 1.6 (ban ROS).
if (m.ratio_yaw() < cfg.min_ratio_yaw) return RelocVerdict::kAmbiguousYaw;
// Hanh lang lap: tra loi sai tu tin te hon nhieu so voi im lang.
if (m.ratio() < cfg.min_ratio) return RelocVerdict::kAmbiguous;
// Dai bien: ty le mot lan khop khong tach duoc dung/sai o day.
if (m.ratio() < cfg.min_ratio_fast && streak < cfg.min_cycles) {
return RelocVerdict::kNeedCycles;
}
return RelocVerdict::kAccept;
}
StaticPlace SummarizePlace(const std::vector<StaticRound>& hist) {
StaticPlace p;
if (hist.empty()) return p;
p.map_from_odom = hist.back().map_from_odom;
p.rounds = hist.size();
p.min_ratio = 1e9;
p.min_yaw = 1e9;
p.max_shift = -1.0;
for (const StaticRound& h : hist) {
p.min_ratio = std::min(p.min_ratio, h.ratio);
p.min_yaw = std::min(p.min_yaw, h.ratio_yaw);
p.max_shift = std::max(p.max_shift, h.shift);
}
return p;
}
RelocVerdict DecideStatic(std::vector<StaticRound>* hist, const StaticRound& r,
const std::vector<StaticPlace>& prev, const GlobalLocalizerConfig& cfg,
bool use_shift, bool* along_axis, std::string* why) {
*along_axis = false;
// Robot dung yen -> nguoi thang cac vong phai la CUNG mot pose robot.
if (!hist->empty()) {
const Pose2D& b = hist->back().robot;
if (std::hypot(r.robot.x - b.x, r.robot.y - b.y) > cfg.static_agree_m ||
std::fabs(AngleDiff(r.robot.theta, b.theta)) > cfg.static_agree_deg * kDegToRad) {
hist->clear();
}
}
hist->push_back(r);
// Giu MOI vong lien tiep cung cho (chan tren de khong phinh): doi thu tung
// hien ra o bat ky vong nao deu tinh.
constexpr size_t kMaxHist = 30;
while (hist->size() > kMaxHist) hist->erase(hist->begin());
const size_t k = static_cast<size_t>(std::max(1, cfg.static_rounds));
const StaticPlace cur = SummarizePlace(*hist);
const size_t n = cur.rounds;
char b[200];
if (cur.min_yaw < cfg.min_ratio_yaw) {
std::snprintf(b, sizeof(b), "ty le huong nho nhat %zu vong %.2f < %.2f", n, cur.min_yaw,
cfg.min_ratio_yaw);
*why = b;
return RelocVerdict::kAmbiguousYaw;
}
if (cur.min_ratio < cfg.min_ratio) {
std::snprintf(b, sizeof(b), "ty le nho nhat %zu vong %.2f < %.2f", n, cur.min_ratio, cfg.min_ratio);
*why = b;
return RelocVerdict::kAmbiguous;
}
if (use_shift && cur.max_shift >= cfg.tilt_max_shift_ratio) {
*along_axis = true;
std::snprintf(b, sizeof(b), "dich %.1f m van giu %.0f%% diem", cfg.tilt_shift_m,
100.0 * cur.max_shift);
*why = b;
return RelocVerdict::kAmbiguous;
}
if (n < k) {
std::snprintf(b, sizeof(b), "cho %zu vong lien tiep cung cho (%zu/%zu), ty le nho nhat %.2f", k, n,
k, cur.min_ratio);
*why = b;
return RelocVerdict::kNeedCycles;
}
// 1. Mot cho, chuan mot goc nhin.
if (cur.min_ratio >= cfg.static_min_ratio) {
std::snprintf(b, sizeof(b), "%zu vong cung cho: ty le nho nhat %.2f / huong %.2f", n, cur.min_ratio,
cur.min_yaw);
*why = b;
return RelocVerdict::kAccept;
}
// 2. Hai cho khac nhau, MOI cho deu qua min_ratio o moi vong cua no, cung gia thuyet.
for (const StaticPlace& p : prev) {
if (p.rounds < k || p.min_ratio < cfg.min_ratio || p.min_yaw < cfg.min_ratio_yaw) continue;
if (use_shift && p.max_shift >= cfg.tilt_max_shift_ratio) continue;
if (std::hypot(p.map_from_odom.x - cur.map_from_odom.x, p.map_from_odom.y - cur.map_from_odom.y) >
cfg.static_agree_m ||
std::fabs(AngleDiff(p.map_from_odom.theta, cur.map_from_odom.theta)) >
cfg.static_agree_deg * kDegToRad) {
continue;
}
std::snprintf(b, sizeof(b),
"hai cho cung pose: ty le nho nhat %.2f (cho nay, %zu vong) / %.2f (cho truoc, %zu vong)",
cur.min_ratio, n, p.min_ratio, p.rounds);
*why = b;
return RelocVerdict::kAccept;
}
std::snprintf(b, sizeof(b),
"ty le nho nhat %zu vong %.2f < %.2f -- can them mot cho khac (sau khi bo) cung pose",
n, cur.min_ratio, cfg.static_min_ratio);
*why = b;
return RelocVerdict::kNeedCycles;
}
} // namespace vslam

View File

@@ -0,0 +1,256 @@
#include "vslam/height_map.h"
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <algorithm>
#include <cmath>
#include <limits>
namespace vslam {
std::map<int, double> SolveZGraph(const std::map<int, NodeHeight>& meas,
const std::vector<ZGraphLink>& links,
const ZGraphConfig& cfg) {
std::map<int, double> out;
if (meas.empty()) return out;
std::map<int, int> index;
for (const auto& kv : meas) {
const int k = static_cast<int>(index.size());
index[kv.first] = k;
}
const int n = static_cast<int>(index.size());
// Phuong trinh chuan H z = g, H = sum w a a^T.
std::vector<Eigen::Triplet<double>> trip;
Eigen::VectorXd g = Eigen::VectorXd::Zero(n);
auto add_rel = [&](int i, int j, double dz, double sigma) {
// z_j - z_i = dz
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
trip.emplace_back(j, j, w);
trip.emplace_back(i, j, -w);
trip.emplace_back(j, i, -w);
g(i) -= w * dz;
g(j) += w * dz;
};
auto add_abs = [&](int i, double z, double sigma) {
const double w = 1.0 / (sigma * sigma);
trip.emplace_back(i, i, w);
g(i) += w * z;
};
for (const auto& kv : meas) add_abs(index[kv.first], kv.second.z, cfg.sigma_prior);
add_abs(index[meas.begin()->first], meas.begin()->second.z, cfg.sigma_first);
for (const ZGraphLink& l : links) {
auto a = meas.find(l.from), b = meas.find(l.to);
if (a == meas.end() || b == meas.end() || l.from == l.to) continue;
const int i = index[l.from], j = index[l.to];
if (l.neighbor) {
const double dz = b->second.z - a->second.z;
add_rel(i, j, dz, cfg.sigma_neighbor + cfg.sigma_rel * std::fabs(dz));
continue;
}
const bool flat_a = std::fabs(a->second.pitch) < cfg.clamp_rad;
const bool flat_b = std::fabs(b->second.pitch) < cfg.clamp_rad;
if (flat_a && flat_b) {
add_rel(i, j, 0.0, cfg.sigma_loop_flat);
} else {
// Mat phang doc cua node `from`, keo toi `to`.
FloorNode fa;
fa.roll = a->second.roll;
fa.pitch = a->second.pitch;
const double dz = PlaneZ(fa, l.dx, l.dy);
add_rel(i, j, dz, cfg.sigma_loop_slope + cfg.sigma_rel * std::fabs(dz));
}
}
Eigen::SparseMatrix<double> H(n, n);
H.setFromTriplets(trip.begin(), trip.end());
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(H);
if (solver.info() != Eigen::Success) {
for (const auto& kv : meas) out[kv.first] = kv.second.z;
return out;
}
const Eigen::VectorXd z = solver.solve(g);
for (const auto& kv : index) out[kv.first] = z(kv.second);
return out;
}
double PlaneZ(const FloorNode& n, double x, double y) {
const double dx = x - n.x, dy = y - n.y;
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double fwd = c * dx + s * dy;
const double left = -s * dx + c * dy;
// Ry(pitch): +x chuc xuong khi pitch duong; Rx(roll): +y len khi roll duong.
return n.z - fwd * std::tan(n.pitch) + left * std::tan(n.roll);
}
void FloorModel::Build(const std::vector<FloorNode>& nodes, double radius, double cell) {
nodes_ = nodes;
radius_ = radius;
cell_ = cell;
nearest_.clear();
w_ = h_ = 0;
if (nodes_.empty()) return;
double xmin = std::numeric_limits<double>::max(), ymin = xmin;
double xmax = std::numeric_limits<double>::lowest(), ymax = xmax;
for (const FloorNode& f : nodes_) {
xmin = std::min(xmin, f.x);
xmax = std::max(xmax, f.x);
ymin = std::min(ymin, f.y);
ymax = std::max(ymax, f.y);
}
x0_ = xmin - radius - cell;
y0_ = ymin - radius - cell;
w_ = static_cast<int>(std::ceil((xmax - xmin + 2 * radius + 2 * cell) / cell));
h_ = static_cast<int>(std::ceil((ymax - ymin + 2 * radius + 2 * cell) / cell));
nearest_.assign(static_cast<size_t>(w_) * h_, -1);
std::vector<float> best(nearest_.size(), std::numeric_limits<float>::max());
const int rc = static_cast<int>(std::ceil(radius / cell));
const double r2 = radius * radius;
for (size_t k = 0; k < nodes_.size(); ++k) {
const FloorNode& f = nodes_[k];
const int cx = static_cast<int>((f.x - x0_) / cell), cy = static_cast<int>((f.y - y0_) / cell);
for (int iy = std::max(0, cy - rc); iy <= std::min(h_ - 1, cy + rc); ++iy) {
for (int ix = std::max(0, cx - rc); ix <= std::min(w_ - 1, cx + rc); ++ix) {
const double px = x0_ + (ix + 0.5) * cell, py = y0_ + (iy + 0.5) * cell;
const double d2 = (px - f.x) * (px - f.x) + (py - f.y) * (py - f.y);
if (d2 > r2) continue;
const size_t i = static_cast<size_t>(iy) * w_ + ix;
if (d2 < best[i]) {
best[i] = static_cast<float>(d2);
nearest_[i] = static_cast<int>(k);
}
}
}
}
}
bool FloorModel::NearestNode(double x, double y, FloorNode* node, double* dist) const {
if (nodes_.empty()) return false;
const int ix = static_cast<int>(std::floor((x - x0_) / cell_));
const int iy = static_cast<int>(std::floor((y - y0_) / cell_));
if (ix < 0 || iy < 0 || ix >= w_ || iy >= h_) return false;
const int k = nearest_[static_cast<size_t>(iy) * w_ + ix];
if (k < 0) return false;
*node = nodes_[static_cast<size_t>(k)];
if (dist != nullptr) *dist = std::hypot(x - node->x, y - node->y);
return true;
}
bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const {
FloorNode f;
if (!NearestNode(x, y, &f, dist)) return false;
*z = PlaneZ(f, x, y);
return true;
}
namespace {
// Dao ham cua PlaneZ: z = z_n - fwd * tan(pitch) + left * tan(roll).
void NodeGradient(const FloorNode& n, double* gx, double* gy) {
const double c = std::cos(n.theta), s = std::sin(n.theta);
const double tp = std::tan(n.pitch), tr = std::tan(n.roll);
*gx = -tp * c - tr * s;
*gy = -tp * s + tr * c;
}
} // namespace
bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx,
double* gy) {
FloorNode n;
double d = 0.0;
if (!fm.NearestNode(x, y, &n, &d) || d > max_dist) return false;
NodeGradient(n, gx, gy);
return true;
}
namespace {
// Node gan nhat va node gan nhat o PHIA DOI DIEN (huong lech >= 120 do), ca hai trong
// max_dist. false neu thieu mot trong hai.
bool OppositePair(const FloorModel& fm, double x, double y, double max_dist, FloorNode* a,
FloorNode* b) {
const std::vector<FloorNode>& nodes = fm.nodes();
int i1 = -1;
double d1 = max_dist;
for (size_t i = 0; i < nodes.size(); ++i) {
const double d = std::hypot(nodes[i].x - x, nodes[i].y - y);
if (d <= d1) {
d1 = d;
i1 = static_cast<int>(i);
}
}
if (i1 < 0 || d1 < 1e-6) return false;
const double ux = (nodes[i1].x - x) / d1, uy = (nodes[i1].y - y) / d1;
constexpr double kOpposite = -0.5; // cos(120 do)
int i2 = -1;
double d2 = max_dist;
for (size_t i = 0; i < nodes.size(); ++i) {
const double dx = nodes[i].x - x, dy = nodes[i].y - y;
const double d = std::hypot(dx, dy);
if (d > d2 || d < 1e-6 || (dx * ux + dy * uy) / d > kOpposite) continue;
d2 = d;
i2 = static_cast<int>(i);
}
if (i2 < 0) return false;
*a = nodes[static_cast<size_t>(i1)];
*b = nodes[static_cast<size_t>(i2)];
return true;
}
} // namespace
bool FloorGradientBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double* gx, double* gy) {
FloorNode a, b;
if (!OppositePair(fm, x, y, max_dist, &a, &b)) return false;
double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
NodeGradient(a, &ax, &ay);
NodeGradient(b, &bx, &by);
if (std::hypot(ax - bx, ay - by) > agree) return false;
*gx = 0.5 * (ax + bx);
*gy = 0.5 * (ay + by);
return true;
}
bool FloorZBetween(const FloorModel& fm, double x, double y, double max_dist, double agree,
double agree_z, double* z) {
FloorNode a, b;
if (!OppositePair(fm, x, y, max_dist, &a, &b)) return false;
double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
NodeGradient(a, &ax, &ay);
NodeGradient(b, &bx, &by);
const double za = PlaneZ(a, x, y), zb = PlaneZ(b, x, y);
if (std::hypot(ax - bx, ay - by) > agree || std::fabs(za - zb) > agree_z) return false;
*z = 0.5 * (za + zb);
return true;
}
double TiltResidual(double roll, double pitch, double yaw, double gx, double gy) {
const double c = std::cos(yaw), s = std::sin(yaw);
const double sf = gx * c + gy * s; // doc theo huong mui (len = duong)
const double sl = -gx * s + gy * c; // doc sang trai
// Than nam tren mat do, R = Rz(yaw) Ry(pitch) Rx(roll): truc x than nam trong
// mat -> tan(pitch) = -sf; truc y than nam trong mat -> tan(roll) = sl * cos(pitch).
const double mf = -std::tan(pitch);
const double ml = std::tan(roll) / std::max(1e-6, std::cos(pitch));
return std::hypot(mf - sf, ml - sl);
}
double SlopeAlignTurn(double roll, double pitch, double* misalign) {
// Huong LEN doc trong frame than, cung quy uoc TiltResidual: mf doc theo mui,
// ml doc sang trai.
const double mf = -std::tan(pitch);
const double ml = std::tan(roll) / std::max(1e-6, std::cos(pitch));
const double up = std::atan2(ml, mf);
const double down = up > 0.0 ? up - M_PI : up + M_PI;
const double turn = std::fabs(up) <= std::fabs(down) ? up : down;
if (misalign != nullptr) *misalign = std::fabs(turn);
return turn;
}
} // namespace vslam

View File

@@ -39,17 +39,23 @@ void CopyGrid(const cv::Mat& m, OccupancyGrid* out) {
StatusResponse BuildFromCache(rtabmap::LocalGridCache& cache, StatusResponse BuildFromCache(rtabmap::LocalGridCache& cache,
const std::map<int, rtabmap::Transform>& poses, const std::map<int, rtabmap::Transform>& poses,
double cell_size, double range_max, double cell_size, double range_max,
const rtabmap::ParametersMap& slam_params,
OccupancyGrid* out) { OccupancyGrid* out) {
if (poses.empty()) { if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, return StatusResponse::Error(StatusCode::kFailedPrecondition,
"khong co pose nao de dung grid"); "khong co pose nao de dung grid");
} }
rtabmap::ParametersMap params; rtabmap::ParametersMap params;
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridCellSize(), // Cach cap nhat o (GridGlobal/*: xac suat trung / truot / kep) THEO RTAB-Map
std::to_string(cell_size))); // dang chay (slam.yaml). Truoc 07/10 khong truyen -> luon mac dinh RTAB-Map:
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGrid3D(), "false")); // o da chac chiem can ~9 lan nhin xuyen qua moi xoa, nen nguoi dung lai roi
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridRangeMax(), // di van nam tren ban do sau khi quay lai quet.
std::to_string(range_max))); for (const auto& kv : slam_params) {
if (kv.first.rfind("GridGlobal/", 0) == 0) params.insert(kv);
}
params[rtabmap::Parameters::kGridCellSize()] = std::to_string(cell_size);
params[rtabmap::Parameters::kGrid3D()] = "false";
params[rtabmap::Parameters::kGridRangeMax()] = std::to_string(range_max);
rtabmap::OccupancyGrid grid(&cache, params); rtabmap::OccupancyGrid grid(&cache, params);
grid.update(poses); grid.update(poses);
@@ -106,6 +112,12 @@ DbFacts InspectDatabase(const std::string& path) {
auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy()); auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy());
if (it != db_params.end()) f.optimizer_strategy = it->second; if (it != db_params.end()) f.optimizer_strategy = it->second;
// Cung co che: doc lai tham so DB da luu. "true"/"1" deu tinh la bat.
auto it3d = db_params.find(rtabmap::Parameters::kGrid3D());
if (it3d != db_params.end()) {
f.grid_3d = (it3d->second == "true" || it3d->second == "1");
}
driver->closeConnection(false); driver->closeConnection(false);
return f; return f;
} }
@@ -129,12 +141,14 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out) {
cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(), cache.add(kv.first, data.gridGroundCellsRaw(), data.gridObstacleCellsRaw(),
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint()); data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
} }
return BuildFromCache(cache, poses, 0.05, 12.0, out); return BuildFromCache(cache, poses, 0.05, 12.0, slam.getParameters(), out);
} }
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path, StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max, double cell_size, double range_max,
OccupancyGrid* out) { OccupancyGrid* out,
const std::set<int>* only_ids,
const std::map<std::string, std::string>* grid_params) {
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create()); std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
bool opened = false; bool opened = false;
try { try {
@@ -147,7 +161,13 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc DB: " + db_path); return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc DB: " + db_path);
} }
const std::map<int, rtabmap::Transform> poses = driver->loadOptimizedPoses(); const std::map<int, rtabmap::Transform> all_poses = driver->loadOptimizedPoses();
// Chi node DA DUNG moi duoc dua vao update(): pose thua khong co luoi trong
// cache thi vo hai, nhung de ro rang la ban do dung tu tap nao.
std::map<int, rtabmap::Transform> poses;
for (const auto& kv : all_poses) {
if (only_ids == nullptr || only_ids->count(kv.first) != 0) poses.insert(kv);
}
rtabmap::LocalGridCache cache; rtabmap::LocalGridCache cache;
int with_grid = 0; int with_grid = 0;
@@ -162,6 +182,10 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint()); data.gridEmptyCellsRaw(), data.gridCellSize(), data.gridViewPoint());
with_grid++; with_grid++;
} }
// Cach cap nhat o: theo nguoi goi (tham so dang chay), khong thi theo tham
// so DB da luu luc quet.
const rtabmap::ParametersMap slam_params =
grid_params != nullptr ? *grid_params : driver->getLastParameters();
driver->closeConnection(false); driver->closeConnection(false);
if (with_grid == 0) { if (with_grid == 0) {
@@ -169,7 +193,7 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
StatusCode::kFailedPrecondition, StatusCode::kFailedPrecondition,
"khong node nao co local grid -- ban do quet voi Grid/FromDepth sai?"); "khong node nao co local grid -- ban do quet voi Grid/FromDepth sai?");
} }
return BuildFromCache(cache, poses, cell_size, range_max, out); return BuildFromCache(cache, poses, cell_size, range_max, slam_params, out);
} }
} // namespace vslam } // namespace vslam

View File

@@ -3,10 +3,82 @@
#include <rtabmap/core/Optimizer.h> #include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h> #include <rtabmap/core/Parameters.h>
#include <set>
#include "vslam/log.h" #include "vslam/log.h"
namespace vslam { namespace vslam {
namespace {
const char* const kProfileNames[] = {"sim", "real"};
// Doc va KIEM khoi `profiles:`. Ba luat de hai moi truong khong bao gio dung
// nhau hay lech nhau:
// 1. Dung hai khoi `sim` va `real`, du ca hai.
// 2. Hai khoi CUNG tap key -- sua mot ben quen ben kia la loi khoi dong,
// khong phai mot lan chay sai tren robot.
// 3. Key trong profiles KHONG nam o phan chung -- mot key, mot cho. Neu
// khong, doc file se khong biet gia tri nao dang chay.
void LoadProfiles(const ConfigNode& node, const ConfigNode& block, RtabmapConfig* cfg) {
for (const std::string& k : block.Keys()) {
if (k != "sim" && k != "real") {
throw ConfigError("profiles: khoi la '" + k + "' -- chi co sim va real");
}
}
std::set<std::string> keys[2];
for (int i = 0; i < 2; ++i) {
const std::string name = kProfileNames[i];
const ConfigNode p = block[name];
if (p.IsNull()) {
throw ConfigError("profiles: thieu khoi '" + name + "' -- can ca sim va real");
}
SlamProfile sp;
for (const std::string& k : p.Keys()) {
if (k == "odom_sigma_m" || k == "odom_sigma_rad") {
if (!node[k].IsNull()) {
throw ConfigError(k + " vua o phan chung vua o profiles." + name +
" -- mot key chi duoc o mot cho");
}
const double v = p.get<double>(k, 0.0);
if (!(v > 0.0)) {
throw ConfigError("profiles." + name + "." + k + " phai > 0");
}
sp.numbers[k] = v;
keys[i].insert(k);
} else if (k == "rtabmap") {
for (const auto& kv : p["rtabmap"].AsStringMap()) {
if (cfg->overrides.count(kv.first) != 0) {
throw ConfigError("rtabmap " + kv.first + " vua o khoi rtabmap chung vua o "
"profiles." + name + " -- mot key chi duoc o mot cho");
}
sp.rtabmap[kv.first] = kv.second;
keys[i].insert("rtabmap." + kv.first);
}
} else {
throw ConfigError("profiles." + name + ": khoa la '" + k +
"' -- chi co odom_sigma_m, odom_sigma_rad, rtabmap");
}
}
cfg->profiles[name] = sp;
}
if (keys[0] != keys[1]) {
std::string diff;
for (int i = 0; i < 2; ++i) {
for (const std::string& k : keys[i]) {
if (keys[1 - i].count(k) == 0) {
diff += " " + k + " (chi co o " + kProfileNames[i] + ")";
}
}
}
throw ConfigError("profiles: sim va real phai co CUNG tap key, lech:" + diff);
}
}
} // namespace
const char* SlamModeName(SlamMode m) { const char* SlamModeName(SlamMode m) {
switch (m) { switch (m) {
case SlamMode::kMapping: return "mapping"; case SlamMode::kMapping: return "mapping";
@@ -116,6 +188,17 @@ std::map<std::string, std::string> BuildRtabmapParams(
// Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh. // Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh.
out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1"; out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1";
// --- camera_3d KHONG dung vao Grid/* ---
//
// Truoc 2026-09-24 camera_3d ep Grid/Sensor=2 + Grid/3D=true de RTAB-Map
// dung luoi cuc bo 3D TRONG process(). Do trong mo phong (hospital, 0.7 m/s,
// sai so vs ground truth luc dung yen): 2D 0.009 m; luoi 3D 0.06-0.11 m;
// luoi 3D tat ray tracing 0.035 m; depth vao nhung luoi 2D 0.024 m. Luoi 3D
// trong process() keo pose lech -- co che ben trong RTAB-Map CHUA ro.
//
// Nen luoi giu 2D, depth van vao SensorData (luu trong DB), va ban do 3D
// dung NGOAI process() tu depth cua tung node -- xem voxel_export.h.
// Optimizer: dat TUONG MINH, luon luon. // Optimizer: dat TUONG MINH, luon luon.
// //
// DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson // DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson
@@ -144,6 +227,8 @@ RtabmapConfig LoadRtabmapConfig(const ConfigNode& node) {
cfg.visual_loop = node.get<bool>("visual_loop", false); cfg.visual_loop = node.get<bool>("visual_loop", false);
cfg.camera_3d = node.get<bool>("camera_3d", false); cfg.camera_3d = node.get<bool>("camera_3d", false);
cfg.odom_sigma_m = node.get<double>("odom_sigma_m", cfg.odom_sigma_m);
cfg.odom_sigma_rad = node.get<double>("odom_sigma_rad", cfg.odom_sigma_rad);
cfg.optimizer_strategy = node.get<std::string>("optimizer_strategy", "1"); cfg.optimizer_strategy = node.get<std::string>("optimizer_strategy", "1");
// Khoi `rtabmap:` di thang vao ParametersMap, giu nguyen van. Khong kiem // Khoi `rtabmap:` di thang vao ParametersMap, giu nguyen van. Khong kiem
@@ -153,7 +238,29 @@ RtabmapConfig LoadRtabmapConfig(const ConfigNode& node) {
if (!block.IsNull()) { if (!block.IsNull()) {
for (const auto& kv : block.AsStringMap()) cfg.overrides[kv.first] = kv.second; for (const auto& kv : block.AsStringMap()) cfg.overrides[kv.first] = kv.second;
} }
// SAU khoi rtabmap chung: luat "mot key, mot cho" can biet phan chung co gi.
const ConfigNode profiles = node["profiles"];
if (!profiles.IsNull()) LoadProfiles(node, profiles, &cfg);
return cfg; return cfg;
} }
StatusResponse ApplySlamProfile(const std::string& name, RtabmapConfig* cfg) {
const auto it = cfg->profiles.find(name);
if (it == cfg->profiles.end()) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml: khong co profiles." + name + " -- can khoi `profiles:` voi ca sim "
"va real, neu khong sigma odom va ICP chay bang mac dinh cua code");
}
for (const auto& kv : it->second.numbers) {
if (kv.first == "odom_sigma_m") cfg->odom_sigma_m = kv.second;
else if (kv.first == "odom_sigma_rad") cfg->odom_sigma_rad = kv.second;
}
// Ten key RTAB-Map duoc kiem o BuildRtabmapParams, nhu moi key trong
// overrides.
for (const auto& kv : it->second.rtabmap) cfg->overrides[kv.first] = kv.second;
return StatusResponse::Ok();
}
} // namespace vslam } // namespace vslam

View File

@@ -1,17 +1,23 @@
#include "vslam/rtabmap_slam.h" #include "vslam/rtabmap_slam.h"
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Optimizer.h> #include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h> #include <rtabmap/core/Parameters.h>
#include <rtabmap/core/RegistrationIcp.h>
#include <rtabmap/core/Rtabmap.h> #include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Statistics.h> #include <rtabmap/core/Statistics.h>
#include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/ULogger.h>
#include <algorithm> #include <algorithm>
#include <cmath>
#include <chrono> #include <chrono>
#include <mutex> #include <mutex>
#include <set>
#include "vslam/geometry.h" #include "vslam/geometry.h"
#include "vslam/log.h" #include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/occupancy_export.h" #include "vslam/occupancy_export.h"
#include "vslam/sensor_data_builder.h" #include "vslam/sensor_data_builder.h"
@@ -39,6 +45,17 @@ class RtabmapSlamImpl {
SlamStats stats; SlamStats stats;
// Diem depth theo node cho ban do voxel. Chi ExportVoxels (luong slam) cham.
VoxelNodeCache voxel_cache;
// ---- z ban do (di tren doc). CHI luong slam cham. ----
std::map<int, NodeHeight> node_meas; // z DO luc tao node
std::set<int> node_no_height; // node DB khong co userData z
std::map<int, double> node_z; // z sau do thi z
FloorModel floor;
bool use_heights = false;
std::vector<uint64_t> floor_cells;
void RecordMs(double ms) { void RecordMs(double ms) {
stats.last_ms = ms; stats.last_ms = ms;
stats.max_ms = std::max(stats.max_ms, ms); stats.max_ms = std::max(stats.max_ms, ms);
@@ -69,6 +86,14 @@ void RtabmapSlam::SetExtrinsics(const Transform& laser_to_base,
SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; } SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; }
const SlamStats& RtabmapSlam::stats() const { return impl_->stats; } const SlamStats& RtabmapSlam::stats() const { return impl_->stats; }
const std::string& RtabmapSlam::database_path() const {
return impl_->cfg.database_path;
}
std::map<std::string, std::string> RtabmapSlam::rtabmap_parameters() const {
return impl_->rtabmap.getParameters();
}
Pose2D RtabmapSlam::map_correction() const { Pose2D RtabmapSlam::map_correction() const {
std::lock_guard<std::mutex> lk(impl_->out_mu); std::lock_guard<std::mutex> lk(impl_->out_mu);
return impl_->map_correction; return impl_->map_correction;
@@ -88,6 +113,33 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
} }
impl_->cfg = cfg; impl_->cfg = cfg;
if (cfg.odom_sigma_m <= 0.0 || cfg.odom_sigma_rad <= 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml: odom_sigma_m / odom_sigma_rad phai > 0");
}
// --- Giai duong dan DB: tuong doi -> MapDir(), no {stamp} ---
//
// Lam o DAY chu khong o app_config: duong `--check` khong dung toi
// RtabmapSlam, nen cau hinh van kiem duoc tren may khong co quyen ghi vao
// /var/lib -- bon test badconfig chay dung kieu do.
impl_->cfg.database_path = ResolveMapPath(cfg.database_path);
const std::string& db_path = impl_->cfg.database_path;
if (db_path != cfg.database_path) {
VSLAM_INFO("slam: database_path \"" << cfg.database_path << "\" -> " << db_path);
}
// {stamp} o che do localization la mot loi logic, khong phai tuy chon: ten
// sinh moi lan chay thi khong bao gio khop ban do da quet.
if (cfg.mode == SlamMode::kLocalization &&
cfg.database_path.find("{stamp}") != std::string::npos) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"localization voi {stamp} trong database_path: ten sinh moi lan chay "
"thi khong bao gio tim thay ban do da quet.");
}
// ULogger cua RTAB-Map mac dinh in thang ra stdout va rat on. Day ve ERROR; // ULogger cua RTAB-Map mac dinh in thang ra stdout va rat on. Day ve ERROR;
// thong tin can thiet da co trong SlamOutput va stats. // thong tin can thiet da co trong SlamOutput va stats.
ULogger::setType(ULogger::kTypeNoLog); ULogger::setType(ULogger::kTypeNoLog);
@@ -113,14 +165,14 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
return StatusResponse::Error(StatusCode::kInvalidArgument, msg); return StatusResponse::Error(StatusCode::kInvalidArgument, msg);
} }
const DbFacts facts = InspectDatabase(cfg.database_path); const DbFacts facts = InspectDatabase(db_path);
if (cfg.mode == SlamMode::kLocalization) { if (cfg.mode == SlamMode::kLocalization) {
// Localization can mot ban do DA CO. Khong co thi no chay im lang ma // Localization can mot ban do DA CO. Khong co thi no chay im lang ma
// khong bao gio dinh vi duoc vao dau -- da do: process_ms 0.3-2.4 ms va // khong bao gio dinh vi duoc vao dau -- da do: process_ms 0.3-2.4 ms va
// map->odom luon bang 0, trong nhu "SLAM dang chay tot". // map->odom luon bang 0, trong nhu "SLAM dang chay tot".
// //
// Duong dan rong = DB trong RAM = chac chan khong co ban do. // Duong dan rong = DB trong RAM = chac chan khong co ban do.
if (cfg.database_path.empty()) { if (db_path.empty()) {
return StatusResponse::Error( return StatusResponse::Error(
StatusCode::kFailedPrecondition, StatusCode::kFailedPrecondition,
"che do localization nhung database_path de rong (DB trong RAM). " "che do localization nhung database_path de rong (DB trong RAM). "
@@ -129,7 +181,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
if (!facts.exists || facts.nodes == 0) { if (!facts.exists || facts.nodes == 0) {
return StatusResponse::Error( return StatusResponse::Error(
StatusCode::kFailedPrecondition, StatusCode::kFailedPrecondition,
"che do localization nhung DB khong co node nao: " + cfg.database_path); "che do localization nhung DB khong co node nao: " + db_path);
} }
} }
if (cfg.visual_loop && facts.exists && facts.words == 0) { if (cfg.visual_loop && facts.exists && facts.words == 0) {
@@ -141,7 +193,15 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
"visual_loop=true nhung DB khong co tu vung (Word = 0). Ban do nay " "visual_loop=true nhung DB khong co tu vung (Word = 0). Ban do nay "
"duoc quet voi visual_loop=false; hai co phai khop nhau."); "duoc quet voi visual_loop=false; hai co phai khop nhau.");
} }
if (facts.exists && facts.optimizer_strategy != cfg.optimizer_strategy) { // ⚠️ Canh bao duoi day hoi `nodes > 0`, khong chi `exists`.
//
// `facts.exists` nghia la MO DUOC, khong phai CO BAN DO: sqlite tao file
// ngay khi `InspectDatabase` mo no, nen mot duong dan moi tinh cung ra
// exists=true voi nodes=0 va moi tham so rong. Chi kiem `exists` thi moi lan
// quet moi deu keu "DB nay quet voi Grid/3D=false" va "DB luu
// Optimizer/Strategy=" (gia tri rong) -- do dung la cai da in ra o lan chay
// dau tien cua ban do 3D.
if (facts.nodes > 0 && facts.optimizer_strategy != cfg.optimizer_strategy) {
VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy
<< ", dang ep ve " << cfg.optimizer_strategy << ", dang ep ve " << cfg.optimizer_strategy
<< " (loadDatabaseParameters=false)"); << " (loadDatabaseParameters=false)");
@@ -169,10 +229,19 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
" node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: " " node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: "
"Statistics.id' o MOI khung va khong dung duoc ban do nao.\n" "Statistics.id' o MOI khung va khong dung duoc ban do nao.\n"
" - Quet lai tu dau : --slam-db <duong dan MOI>\n" " - Quet lai tu dau : --slam-db <duong dan MOI>\n"
" - Dat ten tu dong : --slam-db \"map_{stamp}.db\"\n"
" - Dung ban do nay : --slam-mode localization " " - Dung ban do nay : --slam-mode localization "
"--slam-init-pose x,y,yaw"); "--slam-init-pose x,y,yaw");
} }
// rtabmap.init() tao FILE, khong tao THU MUC -- thieu thu muc cha thi no
// nem tu trong ruot sqlite. Chi can o mapping; localization thi DB bat buoc
// da ton tai va da qua phep kiem ben tren.
if (cfg.mode == SlamMode::kMapping && !db_path.empty()) {
const StatusResponse mk = EnsureParentDir(db_path);
if (!mk.ok()) return mk;
}
rtabmap::ParametersMap pm(params.begin(), params.end()); rtabmap::ParametersMap pm(params.begin(), params.end());
try { try {
// loadDatabaseParameters = FALSE, luon luon. // loadDatabaseParameters = FALSE, luon luon.
@@ -180,7 +249,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
// map_house.db luu Optimizer/Strategy=2 (GTSAM). Neu de RTAB-Map doc lai // map_house.db luu Optimizer/Strategy=2 (GTSAM). Neu de RTAB-Map doc lai
// tham so tu DB thi tren Jetson build -DWITH_GTSAM=OFF no se chon GTSAM // tham so tu DB thi tren Jetson build -DWITH_GTSAM=OFF no se chon GTSAM
// va crash thieu symbol. // va crash thieu symbol.
impl_->rtabmap.init(pm, cfg.database_path, /*loadDatabaseParameters=*/false); impl_->rtabmap.init(pm, db_path, /*loadDatabaseParameters=*/false);
} catch (const std::exception& e) { } catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInternal, return StatusResponse::Error(StatusCode::kInternal,
std::string("rtabmap init: ") + e.what()); std::string("rtabmap init: ") + e.what());
@@ -205,7 +274,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
impl_->map_version = 1; impl_->map_version = 1;
} }
VSLAM_INFO("slam: " << SlamModeName(cfg.mode) << ", DB " VSLAM_INFO("slam: " << SlamModeName(cfg.mode) << ", DB "
<< (cfg.database_path.empty() ? "(RAM)" : cfg.database_path) << (db_path.empty() ? "(RAM)" : db_path)
<< " (" << facts.nodes << " node, " << facts.words << " (" << facts.nodes << " node, " << facts.words
<< " tu vung), optimizer " << cfg.optimizer_strategy); << " tu vung), optimizer " << cfg.optimizer_strategy);
return StatusResponse::Ok(); return StatusResponse::Ok();
@@ -224,13 +293,33 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
const auto t0 = std::chrono::steady_clock::now(); const auto t0 = std::chrono::steady_clock::now();
rtabmap::SensorData data = rtabmap::SensorData data =
BuildSensorData(in, impl_->laser_to_base, impl_->camera_to_base, impl_->next_id++); BuildSensorData(in, impl_->laser_to_base,
in.camera_to_base != nullptr ? *in.camera_to_base
: impl_->camera_to_base,
impl_->next_id++);
if (in.has_height) {
// z / roll / pitch DO cua node -> DB (userData). Ban do quet xong mo lai
// o localization van co z.
cv::Mat ud(1, 3, CV_64FC1);
ud.at<double>(0) = in.z;
ud.at<double>(1) = in.roll;
ud.at<double>(2) = in.pitch;
data.setUserData(ud);
}
// Phuong sai odom: nguoi goi dat thi dung, khong thi lay tu slam.yaml.
const double lin_var = in.odom_linear_var > 0.0
? in.odom_linear_var
: impl_->cfg.odom_sigma_m * impl_->cfg.odom_sigma_m;
const double ang_var = in.odom_angular_var > 0.0
? in.odom_angular_var
: impl_->cfg.odom_sigma_rad * impl_->cfg.odom_sigma_rad;
bool ok = false; bool ok = false;
try { try {
ok = impl_->rtabmap.process(data, ToRtabmap(in.odom), ok = impl_->rtabmap.process(data, ToRtabmap(in.odom),
static_cast<float>(in.odom_linear_var), static_cast<float>(lin_var),
static_cast<float>(in.odom_angular_var)); static_cast<float>(ang_var));
} catch (const std::exception& e) { } catch (const std::exception& e) {
VSLAM_ERROR("slam: process nem: " << e.what()); VSLAM_ERROR("slam: process nem: " << e.what());
return out; return out;
@@ -254,6 +343,12 @@ SlamOutput RtabmapSlam::Process(const SlamInput& in) {
} }
impl_->stats.frames_processed++; impl_->stats.frames_processed++;
if (in.has_height && impl_->cfg.mode == SlamMode::kMapping) {
// RTAB-Map tu sinh id node (Mem/GenerateIds) -- id cua SensorData chi la
// goi y. Node vua them la node cuoi cua bo nho.
const int id = impl_->rtabmap.getLastLocationId();
if (id > 0) impl_->node_meas[id] = NodeHeight{in.z, in.roll, in.pitch};
}
out.loop_closure_id = impl_->rtabmap.getLoopClosureId(); out.loop_closure_id = impl_->rtabmap.getLoopClosureId();
const rtabmap::Statistics& st = impl_->rtabmap.getStatistics(); const rtabmap::Statistics& st = impl_->rtabmap.getStatistics();
auto stat = [&](const std::string& k, double dflt) { auto stat = [&](const std::string& k, double dflt) {
@@ -307,6 +402,242 @@ StatusResponse RtabmapSlam::ExportMap(OccupancyGrid* out) {
return ExportOccupancyGrid(impl_->rtabmap, out); return ExportOccupancyGrid(impl_->rtabmap, out);
} }
StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
VoxelGrid* out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
if (impl_->use_heights && !impl_->node_z.empty()) {
VoxelExportOptions o = opt;
o.node_z = &impl_->node_z;
o.floor = &impl_->floor;
impl_->floor_cells.clear();
o.floor_cells = &impl_->floor_cells;
return ExportVoxelGrid(impl_->rtabmap, o, &impl_->voxel_cache, out);
}
return ExportVoxelGrid(impl_->rtabmap, opt, &impl_->voxel_cache, out);
}
void RtabmapSlam::SetUseHeights(bool on) { impl_->use_heights = on; }
const std::vector<uint64_t>& RtabmapSlam::floor_cells() const { return impl_->floor_cells; }
int RtabmapSlam::TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail) {
if (!impl_->inited || impl_->cfg.mode != SlamMode::kMapping) return 0;
const int cur = impl_->rtabmap.getLastLocationId();
const std::map<int, rtabmap::Transform>& poses = impl_->rtabmap.getLocalOptimizedPoses();
const auto itc = poses.find(cur);
if (cur <= 0 || itc == poses.end() || itc->second.isNull()) return 0;
// Ung vien: node CU (thu tu id = thu tu thoi gian), gan nhat trong ban kinh.
std::vector<int> ids;
ids.reserve(poses.size());
for (const auto& kv : poses) ids.push_back(kv.first);
const long ci = std::lower_bound(ids.begin(), ids.end(), cur) - ids.begin();
int cand = 0;
double best = radius_m;
for (long i = 0; i + min_graph_gap < ci; ++i) {
const rtabmap::Transform& p = poses.at(ids[static_cast<size_t>(i)]);
if (p.isNull()) continue;
const double d = std::hypot(p.x() - itc->second.x(), p.y() - itc->second.y());
if (d <= best) {
best = d;
cand = ids[static_cast<size_t>(i)];
}
}
if (cand == 0) return 0;
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
if (mem == nullptr) return -1;
const std::multimap<int, rtabmap::Link> links = mem->getLinks(cur);
if (links.find(cand) != links.end()) return 0; // da noi roi
try {
rtabmap::SensorData a = mem->getNodeData(cur, false, true, false, false);
rtabmap::SensorData b = mem->getNodeData(cand, false, true, false, false);
a.uncompressData();
b.uncompressData();
if (a.laserScanRaw().isEmpty() || b.laserScanRaw().isEmpty()) {
if (detail != nullptr) *detail = "node khong co scan";
return 0;
}
const rtabmap::Transform guess = itc->second.inverse() * poses.at(cand);
rtabmap::RegistrationIcp reg(impl_->rtabmap.getParameters());
rtabmap::RegistrationInfo info;
const rtabmap::Transform t = reg.computeTransformation(a, b, guess, &info);
if (t.isNull()) {
if (detail != nullptr) *detail = "ICP tu choi: " + info.rejectedMsg;
return 0;
}
const rtabmap::Transform corr = guess.inverse() * t;
const double ct = std::hypot(corr.x(), corr.y());
const double cr = std::fabs(corr.theta());
if (ct > max_corr_m || cr > max_corr_rad) {
if (detail != nullptr) {
*detail = "chinh qua lon (" + std::to_string(ct) + " m, " + std::to_string(cr) + " rad)";
}
return 0;
}
// Thong tin = nghich dao hiep phuong sai ICP, chan duoi phuong sai de
// khong co truc nao "chac tuyet doi".
cv::Mat inf = cv::Mat::eye(6, 6, CV_64FC1);
for (int k = 0; k < 6; ++k) {
const double v = info.covariance.empty() ? 1e-4 : info.covariance.at<double>(k, k);
inf.at<double>(k, k) = 1.0 / std::max(v, 1e-6);
}
if (!impl_->rtabmap.addLink(rtabmap::Link(cur, cand, rtabmap::Link::kUserClosure, t, inf))) {
if (detail != nullptr) *detail = "addLink tu choi";
return 0;
}
if (detail != nullptr) {
*detail = "noi " + std::to_string(cur) + " -> " + std::to_string(cand) + " (cach " +
std::to_string(ci - (std::lower_bound(ids.begin(), ids.end(), cand) - ids.begin())) +
" node, " + std::to_string(best) + " m), chinh " + std::to_string(ct) + " m / " +
std::to_string(cr * 180.0 / M_PI) + " do, ti le khop " +
std::to_string(info.icpInliersRatio);
}
} catch (const std::exception& e) {
if (detail != nullptr) *detail = std::string("nem: ") + e.what();
return -1;
}
std::lock_guard<std::mutex> lk(impl_->out_mu);
impl_->map_correction = FromRtabmap(impl_->rtabmap.getMapCorrection());
impl_->map_version++;
impl_->stats.loop_closures++;
return 1;
}
const FloorModel& RtabmapSlam::floor_model() const { return impl_->floor; }
StatusResponse RtabmapSlam::UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
std::map<int, rtabmap::Transform> poses;
std::multimap<int, rtabmap::Link> links;
impl_->rtabmap.getGraph(poses, links, /*optimized=*/true, /*global=*/false);
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "do thi rong");
}
// Node chua co z do: nap userData tu DB (ban do quet o phien truoc). Node
// DB khong co (quet truoc khi co che do doc) thi nho lai, khong hoi mai.
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
for (const auto& kv : poses) {
const int id = kv.first;
if (id <= 0 || impl_->node_meas.count(id) || impl_->node_no_height.count(id)) continue;
if (mem == nullptr) break;
const rtabmap::SensorData d = mem->getNodeData(id, false, false, true, false);
cv::Mat ud;
d.uncompressDataConst(nullptr, nullptr, nullptr, &ud);
if (ud.type() == CV_64FC1 && ud.total() == 3) {
impl_->node_meas[id] = NodeHeight{ud.at<double>(0), ud.at<double>(1), ud.at<double>(2)};
} else {
impl_->node_no_height.insert(id);
}
}
std::map<int, NodeHeight> meas;
for (const auto& kv : poses) {
auto it = impl_->node_meas.find(kv.first);
if (it != impl_->node_meas.end()) meas[kv.first] = it->second;
}
std::vector<ZGraphLink> zl;
for (const auto& kv : links) {
const rtabmap::Link& l = kv.second;
ZGraphLink z;
z.from = l.from();
z.to = l.to();
switch (l.type()) {
case rtabmap::Link::kNeighbor:
case rtabmap::Link::kNeighborMerged:
z.neighbor = true;
break;
case rtabmap::Link::kGlobalClosure:
case rtabmap::Link::kLocalSpaceClosure:
case rtabmap::Link::kLocalTimeClosure:
case rtabmap::Link::kUserClosure:
z.neighbor = false;
break;
default:
continue;
}
if (l.transform().isNull()) continue;
z.dx = l.transform().x();
z.dy = l.transform().y();
zl.push_back(z);
}
impl_->node_z = SolveZGraph(meas, zl, cfg);
std::vector<FloorNode> fn;
fn.reserve(impl_->node_z.size());
for (const auto& kv : impl_->node_z) {
const auto p = poses.find(kv.first);
if (p == poses.end() || p->second.isNull()) continue;
const NodeHeight& m = meas[kv.first];
FloorNode f;
f.x = p->second.x();
f.y = p->second.y();
f.theta = p->second.theta();
f.z = kv.second;
f.roll = m.roll;
f.pitch = m.pitch;
fn.push_back(f);
}
impl_->floor.Build(fn);
if (nodes_out != nullptr) *nodes_out = impl_->node_z.size();
return StatusResponse::Ok();
}
bool RtabmapSlam::HeightAt(double x, double y, double radius, double* z) const {
double d = 0.0;
if (!impl_->floor.FloorAt(x, y, z, &d)) return false;
return d <= radius;
}
namespace {
cv::Matx44d ToMatx44(const rtabmap::Transform& t) {
return cv::Matx44d(t.r11(), t.r12(), t.r13(), t.x(), t.r21(), t.r22(), t.r23(), t.y(),
t.r31(), t.r32(), t.r33(), t.z(), 0, 0, 0, 1);
}
} // namespace
std::vector<int> RtabmapSlam::MapNodeIds() const {
std::vector<int> out;
if (!impl_->inited) return out;
for (const auto& kv : impl_->rtabmap.getLocalOptimizedPoses()) out.push_back(kv.first);
return out;
}
StatusResponse RtabmapSlam::GetNodeView(int id, bool with_depth, NodeView* out) {
if (!impl_->inited) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
}
const std::map<int, rtabmap::Transform>& poses = impl_->rtabmap.getLocalOptimizedPoses();
const auto it = poses.find(id);
if (it == poses.end() || it->second.isNull()) {
return StatusResponse::Error(StatusCode::kNotFound, "node khong co pose toi uu");
}
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
if (mem == nullptr) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "rtabmap chua co Memory");
}
rtabmap::SensorData d = mem->getNodeData(id, true, false, false, false);
cv::Mat img, depth;
d.uncompressData(&img, with_depth ? &depth : nullptr); // du lieu trong DB la du lieu NEN
if (img.empty() || d.cameraModels().empty()) {
return StatusResponse::Error(StatusCode::kNotFound, "node khong co anh");
}
const rtabmap::CameraModel& cm = d.cameraModels()[0];
out->gray = img;
out->depth = depth;
out->K = cv::Matx33d(cm.fx(), 0, cm.cx(), 0, cm.fy(), cm.cy(), 0, 0, 1);
out->T_base_optical = ToMatx44(cm.localTransform());
out->T_map_base = ToMatx44(it->second);
return StatusResponse::Ok();
}
StatusResponse RtabmapSlam::Close(bool save_database) { StatusResponse RtabmapSlam::Close(bool save_database) {
if (!impl_->inited) return StatusResponse::Ok(); if (!impl_->inited) return StatusResponse::Ok();
impl_->inited = false; impl_->inited = false;

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

@@ -0,0 +1,75 @@
#include "vslam/visual_verifier.h"
#include <algorithm>
#include <cmath>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
namespace vslam {
VisualVerifier::VisualVerifier(const VisualVerifierConfig& cfg)
: cfg_(cfg),
orb_(cv::ORB::create(cfg.orb_features, 1.2f, 8, 31, 0, 2, cv::ORB::HARRIS_SCORE, 31,
cfg.fast_threshold)) {}
VisualFrame VisualVerifier::Extract(const cv::Mat& gray) const {
VisualFrame f;
cv::Mat g = gray, eq;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::createCLAHE(cfg_.clahe_clip, cv::Size(cfg_.clahe_grid, cfg_.clahe_grid))->apply(g, eq);
orb_->detectAndCompute(eq, cv::noArray(), f.kp, f.des);
return f;
}
PnpResult VisualVerifier::Solve(const VisualFrame& q, const VisualFrame& m,
const cv::Matx44d& T_map_base_m) const {
PnpResult r;
if (q.des.empty() || m.des.empty() || q.kp.size() < 8 || m.kp.size() < 8 || m.depth.empty()) {
return r;
}
std::vector<std::vector<cv::DMatch>> knn;
cv::BFMatcher(cv::NORM_HAMMING).knnMatch(q.des, m.des, knn, 2);
const cv::Matx44d Twm = T_map_base_m * m.T_base_optical; // map <- optical cua anh ban do
const double fx = m.K(0, 0), fy = m.K(1, 1), cx = m.K(0, 2), cy = m.K(1, 2);
std::vector<cv::Point3d> obj;
std::vector<cv::Point2d> img;
for (const auto& p : knn) {
if (p.size() < 2 || p[0].distance >= cfg_.ratio * p[1].distance) continue;
++r.matches;
const cv::Point2f uv = m.kp[p[0].trainIdx].pt;
const int row = static_cast<int>(std::lround(uv.y)), col = static_cast<int>(std::lround(uv.x));
if (row < 0 || col < 0 || row >= m.depth.rows || col >= m.depth.cols) continue;
const double z = m.depth.type() == CV_16UC1 ? m.depth.at<uint16_t>(row, col) * 0.001
: static_cast<double>(m.depth.at<float>(row, col));
if (!(z > cfg_.depth_min_m && z < cfg_.depth_max_m)) continue;
const cv::Vec4d pc((uv.x - cx) * z / fx, (uv.y - cy) * z / fy, z, 1.0);
const cv::Vec4d pw = Twm * pc;
obj.emplace_back(pw[0], pw[1], pw[2]);
img.emplace_back(q.kp[p[0].queryIdx].pt);
}
if (static_cast<int>(obj.size()) < cfg_.min_points) return r;
cv::Mat rvec, tvec;
std::vector<int> inl;
const bool ok = cv::solvePnPRansac(obj, img, cv::Mat(q.K), cv::noArray(), rvec, tvec, false,
cfg_.ransac_iters, static_cast<float>(cfg_.reproj_px),
cfg_.confidence, inl, cv::SOLVEPNP_EPNP);
if (!ok || inl.empty()) return r;
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Matx44d Tcw = cv::Matx44d::eye(); // optical <- map
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) Tcw(i, j) = R.at<double>(i, j);
Tcw(i, 3) = tvec.at<double>(i);
}
const cv::Matx44d Twb = Tcw.inv() * q.T_base_optical.inv(); // map <- base cua anh hoi
r.inliers = static_cast<int>(inl.size());
r.x = Twb(0, 3);
r.y = Twb(1, 3);
r.yaw = std::atan2(Twb(1, 0), Twb(0, 0));
r.dz = Twb(2, 3);
r.tilt_deg = std::acos(std::max(-1.0, std::min(1.0, Twb(2, 2)))) * 180.0 / M_PI;
return r;
}
} // namespace vslam

View File

@@ -0,0 +1,635 @@
#include "vslam/voxel_export.h"
#include <rtabmap/core/CameraModel.h>
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Transform.h>
#include <rtabmap/core/util3d.h>
#include <opencv2/core.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iterator>
#include <map>
#include <string>
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Goi chi so co dau vao 63 bit: 21 bit moi truc, lech +2^20 de so am van sap
// xep dung thu tu khi so sanh uint64.
//
// Vi sao vector<uint64> da sort chu khong phai hash set hay octree: tap nay
// duoc dung LAI TU DAU moi lan xuat (pose toi uu dich cho, cau truc tang dan
// vo nghia), va nguoi tieu thu can dau ra DA SAP XEP de lam phep tru tap hop
// O(n). Mot vector phang sort cache tot hon han hash 2 trieu phan tu.
constexpr int32_t kIdxBias = 1 << 20;
constexpr int32_t kIdxMin = -kIdxBias;
constexpr int32_t kIdxMax = kIdxBias - 1;
inline uint64_t PackKey(int32_t x, int32_t y, int32_t z) {
const uint64_t ux = static_cast<uint64_t>(static_cast<uint32_t>(x + kIdxBias)) & 0x1FFFFFULL;
const uint64_t uy = static_cast<uint64_t>(static_cast<uint32_t>(y + kIdxBias)) & 0x1FFFFFULL;
const uint64_t uz = static_cast<uint64_t>(static_cast<uint32_t>(z + kIdxBias)) & 0x1FFFFFULL;
return (ux << 42) | (uy << 21) | uz;
}
inline void UnpackKey(uint64_t k, int32_t* x, int32_t* y, int32_t* z) {
*x = static_cast<int32_t>((k >> 42) & 0x1FFFFFULL) - kIdxBias;
*y = static_cast<int32_t>((k >> 21) & 0x1FFFFFULL) - kIdxBias;
*z = static_cast<int32_t>(k & 0x1FFFFFULL) - kIdxBias;
}
inline bool FitsInt16(int32_t v) {
return v >= -32768 && v <= 32767;
}
inline uint64_t KeyOf(const VoxelIndex& k) {
return PackKey(k.x, k.y, k.z);
}
// Diem frame map -> khoa voxel. Dung CHUNG cho VoxelAccumulator va
// VoxelHitCounter, de hai noi luong tu hoa y het nhau.
// 0 = nhan, -1 = khong huu han, 1 = ngoai dai z, 2 = ngoai dai chi so.
inline int KeyForPoint(const VoxelExportOptions& opt, double inv_size,
double x, double y, double z, uint64_t* key) {
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) return -1;
if (z < opt.z_min || z > opt.z_max) return 1;
const double fx = std::floor(x * inv_size);
const double fy = std::floor(y * inv_size);
const double fz = std::floor(z * inv_size);
// Kiem TRUOC khi ep kieu: ep mot double khong lot int32 la hanh vi khong
// xac dinh, va o day no den tu du lieu cam bien chu khong tu hang so.
if (fx < kIdxMin || fx > kIdxMax || fy < kIdxMin || fy > kIdxMax ||
fz < kIdxMin || fz > kIdxMax) {
return 2;
}
const int32_t ix = static_cast<int32_t>(fx);
const int32_t iy = static_cast<int32_t>(fy);
const int32_t iz = static_cast<int32_t>(fz);
// Dang truyen la int16 -> chi so ngoai dai do la bo, khong phai kep: kep se
// dan mot buc tuong gia o ria ban do.
if (!FitsInt16(ix) || !FitsInt16(iy) || !FitsInt16(iz)) return 2;
*key = PackKey(ix, iy, iz);
return 0;
}
} // namespace
VoxelAccumulator::VoxelAccumulator(const VoxelExportOptions& opt) : opt_(opt) {
if (opt_.emit_size_m <= 0.0) opt_.emit_size_m = 0.10;
inv_size_ = 1.0 / opt_.emit_size_m;
scratch_.reserve(1 << 16);
}
void VoxelAccumulator::AddPoint(double x, double y, double z) {
uint64_t key = 0;
switch (KeyForPoint(opt_, inv_size_, x, y, z, &key)) {
case 0: break;
case 1: ++z_rejected_; return;
case 2: ++clamped_; return;
default: return;
}
scratch_.push_back(key);
if (scratch_.size() >= opt_.flush_every) Flush();
}
void VoxelAccumulator::Flush() {
if (scratch_.empty()) return;
std::sort(scratch_.begin(), scratch_.end());
scratch_.erase(std::unique(scratch_.begin(), scratch_.end()), scratch_.end());
if (acc_.empty()) {
acc_.swap(scratch_);
} else {
std::vector<uint64_t> merged;
merged.reserve(acc_.size() + scratch_.size());
std::set_union(acc_.begin(), acc_.end(), scratch_.begin(), scratch_.end(),
std::back_inserter(merged));
acc_.swap(merged);
}
scratch_.clear();
}
void VoxelAccumulator::Finish(VoxelGrid* out) {
Flush();
out->resolution = static_cast<float>(opt_.emit_size_m);
out->origin_x = 0.0;
out->origin_y = 0.0;
out->origin_z = 0.0;
out->header.frame_id = kMapFrame;
// ⚠️ Cham tran thi GIAM MAU DEU, tuyet doi khong cat cut danh sach.
//
// `acc_` sort theo khoa goi, ma khoa goi sort theo x truoc -- nen lay
// `max_cells` phan tu DAU la chat mot lat khong gian: nguyen mot canh cua
// toa nha bien mat khoi ban do trong khi phan con lai van day du. Da mac
// dung loi nay: nguoi dung bao "goc tren ben trai quet roi ma gio mat".
//
// Giam mau deu thi ban do GIU NGUYEN hinh dang, chi thua di. Cung khuon mau
// ma EncodeCloud dung cho `cloud_max_points` (binary_codec.cc) -- buoc deu,
// khong cat duoi.
const size_t total = acc_.size();
stride_ = 1;
if (opt_.max_cells > 0 && total > opt_.max_cells) {
stride_ = (total + opt_.max_cells - 1) / opt_.max_cells;
}
out->truncated = stride_ > 1;
out->cells.clear();
out->cells.reserve(total / stride_ + 1);
for (size_t i = 0; i < total; i += stride_) {
int32_t x = 0, y = 0, z = 0;
UnpackKey(acc_[i], &x, &y, &z);
VoxelIndex k;
k.x = static_cast<int16_t>(x);
k.y = static_cast<int16_t>(y);
k.z = static_cast<int16_t>(z);
out->cells.push_back(k);
}
// `acc_` da sort theo khoa goi, va khoa goi giu dung thu tu tu nhien cua
// (x, y, z) nho phep lech +2^20 -- nen out->cells cung da sap xep.
}
VoxelHitCounter::VoxelHitCounter(const VoxelExportOptions& opt) : opt_(opt) {
if (opt_.emit_size_m <= 0.0) opt_.emit_size_m = 0.10;
inv_size_ = 1.0 / opt_.emit_size_m;
}
void VoxelHitCounter::BeginNode(int order) {
node_.clear();
order_ = order >= 0 ? order : order_ + 1;
}
void VoxelHitCounter::AddPoint(double x, double y, double z) {
uint64_t key = 0;
const int r = KeyForPoint(opt_, inv_size_, x, y, z, &key);
if (r == 0) node_.push_back(key);
else if (r == 2) ++clamped_;
}
void VoxelHitCounter::EndNode() {
// Khu trung TRONG node: nhieu diem cua cung mot node roi vao mot voxel chi
// la mot lan "thay".
std::sort(node_.begin(), node_.end());
node_.erase(std::unique(node_.begin(), node_.end()), node_.end());
for (const uint64_t k : node_) all_.push_back(Hit{k, order_});
node_.clear();
}
void VoxelHitCounter::Finish(VoxelGrid* out, VoxelCarver* carver) {
// Sort theo (khoa, order): moi khoa mot doan, phan tu CUOI doan la node
// cuoi cung thay voxel do.
std::sort(all_.begin(), all_.end());
// Cat z da lam o AddPoint. Tat no o day: tam voxel co the roi ra ngoai
// [z_min, z_max] khi z_min khong trung bien voxel, va voxel se mat oan.
VoxelExportOptions o = opt_;
o.z_min = -1e9;
o.z_max = 1e9;
VoxelAccumulator acc(o);
const size_t need = std::max<size_t>(opt_.min_node_hits, 1);
const double s = opt_.emit_size_m;
carved_ = 0;
for (size_t i = 0; i < all_.size();) {
size_t j = i + 1;
while (j < all_.size() && all_[j].key == all_[i].key) ++j;
if (j - i >= need) {
int32_t x = 0, y = 0, z = 0;
UnpackKey(all_[i].key, &x, &y, &z);
// Tam voxel -> luong tu hoa lai ra DUNG chi so do.
const double cx = (x + 0.5) * s, cy = (y + 0.5) * s, cz = (z + 0.5) * s;
if (carver != nullptr && carver->Gone(cx, cy, cz, all_[j - 1].order)) {
++carved_;
} else {
acc.AddPoint(cx, cy, cz);
}
}
i = j;
}
acc.Finish(out);
stride_ = acc.stride();
}
// ---------------- Nhin xuyen qua ----------------
namespace {
// Khoa o 1 m cho chi so node theo vi tri camera.
inline uint64_t CellKey(int32_t cx, int32_t cy) {
return (static_cast<uint64_t>(static_cast<uint32_t>(cx)) << 32) | static_cast<uint32_t>(cy);
}
} // namespace
VoxelCarver::VoxelCarver(double range_m, size_t need_views)
: range_(range_m > 0.0 ? range_m : 3.5), need_(std::max<size_t>(need_views, 1)) {}
void VoxelCarver::AddView(int order, const float b[12], const NodeDepthView* view) {
if (view == nullptr || view->empty()) return;
// map <- optical = (map <- base) * (base <- optical).
const float* c = view->cam;
View w;
w.order = order;
w.v = view;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
w.r[i * 3 + j] = b[i * 4 + 0] * c[0 * 4 + j] + b[i * 4 + 1] * c[1 * 4 + j] +
b[i * 4 + 2] * c[2 * 4 + j];
}
w.t[i] = b[i * 4 + 0] * c[3] + b[i * 4 + 1] * c[7] + b[i * 4 + 2] * c[11] + b[i * 4 + 3];
}
const int idx = static_cast<int>(views_.size());
views_.push_back(w);
cells_[CellKey(static_cast<int32_t>(std::floor(w.t[0])),
static_cast<int32_t>(std::floor(w.t[1])))].push_back(idx);
near_.clear();
}
const std::vector<int>& VoxelCarver::Near(int32_t cx, int32_t cy) {
const uint64_t key = CellKey(cx, cy);
auto it = near_.find(key);
if (it != near_.end()) return it->second;
std::vector<int> v;
const int32_t r = static_cast<int32_t>(std::ceil(range_));
for (int32_t dx = -r; dx <= r; ++dx) {
for (int32_t dy = -r; dy <= r; ++dy) {
auto c = cells_.find(CellKey(cx + dx, cy + dy));
if (c != cells_.end()) v.insert(v.end(), c->second.begin(), c->second.end());
}
}
// Chi so view tang cung order (AddView theo thu tu thoi gian).
std::sort(v.begin(), v.end());
return near_.emplace(key, std::move(v)).first->second;
}
bool VoxelCarver::Gone(double x, double y, double z, int last_order) {
const std::vector<int>& cand =
Near(static_cast<int32_t>(std::floor(x)), static_cast<int32_t>(std::floor(y)));
size_t through = 0;
// MOI NHAT truoc; dung khi toi lan voxel duoc thay cuoi.
for (auto it = cand.rbegin(); it != cand.rend(); ++it) {
const View& w = views_[static_cast<size_t>(*it)];
if (w.order <= last_order) break;
const float qx = static_cast<float>(x) - w.t[0];
const float qy = static_cast<float>(y) - w.t[1];
const float qz = static_cast<float>(z) - w.t[2];
// optical = R^T * q
const float zc = w.r[2] * qx + w.r[5] * qy + w.r[8] * qz;
if (zc < 0.25f || zc > range_) continue;
const float xc = w.r[0] * qx + w.r[3] * qy + w.r[6] * qz;
const float yc = w.r[1] * qx + w.r[4] * qy + w.r[7] * qz;
const NodeDepthView& v = *w.v;
const float u = v.fx * xc / zc + v.cx;
const float vv = v.fy * yc / zc + v.cy;
if (!(u >= 0.0f) || !(vv >= 0.0f) || u >= static_cast<float>(v.w) ||
vv >= static_cast<float>(v.h)) {
continue; // ngoai khung nhin
}
const uint16_t dmm = v.depth_mm[static_cast<size_t>(vv) * static_cast<size_t>(v.w) +
static_cast<size_t>(u)];
if (dmm == 0) continue;
const float d = static_cast<float>(dmm) * 0.001f;
// Sai so depth stereo tang theo z^2 (D410: ~2 cm o 2 m, ~9 cm o 4 m) +
// nua voxel + sai pose.
const float margin = 0.10f + 0.03f * zc * zc;
if (d > zc + margin) {
if (++through >= need_) return true; // nhin xuyen qua: vat da di
} else if (d >= zc - margin) {
return false; // van thay: GIU
}
// Gan hon: bi vat khac che, khong biet.
}
return false;
}
void NodeDepthViewFromSensorData(const rtabmap::SensorData& data, int block,
NodeDepthView* out) {
out->depth_mm.clear();
const cv::Mat& d = data.depthOrRightRaw();
if (d.empty() || data.cameraModels().empty() || block < 1) return;
if (d.type() != CV_16UC1 && d.type() != CV_32FC1) return;
const rtabmap::CameraModel& m = data.cameraModels()[0];
if (m.fx() <= 0.0 || m.fy() <= 0.0) return;
// Mo hinh camera co the theo anh khac co (depth da giam mau): quy ve co depth.
const double sx = m.imageWidth() > 0 ? static_cast<double>(d.cols) / m.imageWidth() : 1.0;
const double sy = m.imageHeight() > 0 ? static_cast<double>(d.rows) / m.imageHeight() : 1.0;
out->w = d.cols / block;
out->h = d.rows / block;
if (out->w <= 0 || out->h <= 0) return;
out->fx = static_cast<float>(m.fx() * sx / block);
out->fy = static_cast<float>(m.fy() * sy / block);
out->cx = static_cast<float>((m.cx() * sx + 0.5) / block - 0.5);
out->cy = static_cast<float>((m.cy() * sy + 0.5) / block - 0.5);
const rtabmap::Transform& L = m.localTransform(); // base <- optical
const float c[12] = {L.r11(), L.r12(), L.r13(), L.x(), L.r21(), L.r22(), L.r23(), L.y(),
L.r31(), L.r32(), L.r33(), L.z()};
std::copy(c, c + 12, out->cam);
out->depth_mm.assign(static_cast<size_t>(out->w) * out->h, 0);
for (int by = 0; by < out->h; ++by) {
for (int bx = 0; bx < out->w; ++bx) {
// NHO NHAT cua khoi: than trong cho viec xoa.
uint32_t best = 0;
for (int y = by * block; y < (by + 1) * block; ++y) {
for (int x = bx * block; x < (bx + 1) * block; ++x) {
uint32_t mm = 0;
if (d.type() == CV_16UC1) {
mm = d.at<uint16_t>(y, x);
} else {
const float f = d.at<float>(y, x);
if (std::isfinite(f) && f > 0.0f) mm = static_cast<uint32_t>(f * 1000.0f + 0.5f);
}
if (mm > 0 && (best == 0 || mm < best)) best = mm;
}
}
out->depth_mm[static_cast<size_t>(by) * out->w + bx] =
static_cast<uint16_t>(std::min<uint32_t>(best, 65535u));
}
}
}
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
const std::vector<VoxelIndex>& now,
std::vector<VoxelIndex>* added,
std::vector<VoxelIndex>* removed) {
added->clear();
removed->clear();
size_t i = 0, j = 0;
while (i < prev.size() && j < now.size()) {
const uint64_t a = KeyOf(prev[i]);
const uint64_t b = KeyOf(now[j]);
if (a == b) {
++i;
++j;
} else if (a < b) {
removed->push_back(prev[i++]);
} else {
added->push_back(now[j++]);
}
}
for (; i < prev.size(); ++i) removed->push_back(prev[i]);
for (; j < now.size(); ++j) added->push_back(now[j]);
}
size_t MarkVoxelObstacles(const VoxelGrid& vg, double z_min, double z_max,
OccupancyGrid* grid, const FloorModel* floor) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f) return 0;
const double r = vg.resolution;
const double inv = 1.0 / grid->resolution;
size_t marked = 0;
for (const VoxelIndex& k : vg.cells) {
double z = vg.origin_z + (k.z + 0.5) * r;
if (floor != nullptr) {
double f = 0.0;
if (floor->FloorAt(vg.origin_x + (k.x + 0.5) * r, vg.origin_y + (k.y + 0.5) * r, &f)) z -= f;
}
if (z < z_min || z > z_max) continue;
// Luoi 2D khong xoay (occupancy_export dat orientation = dong nhat), va
// hang 0 la ymin -- cung quy uoc voi RTAB-Map/map_server.
const double fx =
std::floor((vg.origin_x + (k.x + 0.5) * r - grid->origin.position.x) * inv);
const double fy =
std::floor((vg.origin_y + (k.y + 0.5) * r - grid->origin.position.y) * inv);
if (fx < 0.0 || fy < 0.0 || fx >= grid->width || fy >= grid->height) continue;
int8_t& c = grid->data[static_cast<size_t>(fy) * grid->width +
static_cast<size_t>(fx)];
if (c < 50) {
c = 100;
++marked;
}
}
return marked;
}
size_t ClearLidarOnSeenRamps(OccupancyGrid* grid, const std::vector<uint64_t>& floor_cells,
double cell_size, const FloorModel& floor, double clamp_rad,
double max_node_dist) {
if (grid->width == 0 || grid->height == 0 || grid->resolution <= 0.0f || floor_cells.empty()) {
return 0;
}
std::vector<uint64_t> seen(floor_cells);
std::sort(seen.begin(), seen.end());
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
const double res = grid->resolution;
const double inv = 1.0 / cell_size;
size_t cleared = 0;
for (uint32_t r = 0; r < grid->height; ++r) {
for (uint32_t c = 0; c < grid->width; ++c) {
int8_t& v = grid->data[static_cast<size_t>(r) * grid->width + c];
if (v < 50) continue;
const double x = grid->origin.position.x + (c + 0.5) * res;
const double y = grid->origin.position.y + (r + 0.5) * res;
FloorNode n;
double d = 0.0;
if (!floor.NearestNode(x, y, &n, &d) || d > max_node_dist) continue;
if (std::fabs(n.pitch) < clamp_rad) continue;
const uint64_t k = PackFloorCell(static_cast<int32_t>(std::floor(x * inv)),
static_cast<int32_t>(std::floor(y * inv)));
if (!std::binary_search(seen.begin(), seen.end(), k)) continue;
v = 0;
++cleared;
}
}
return cleared;
}
void NodeCloudFromSensorData(const rtabmap::SensorData& data,
const VoxelExportOptions& opt,
std::vector<float>* out) {
out->clear();
if (data.depthOrRightRaw().empty() || data.cameraModels().empty()) return;
// cloudFromSensorData ap localTransform cua camera (base <- optical), nen
// diem ra o frame base cua node -- cung frame voi pose cua no.
const auto cloud = rtabmap::util3d::cloudFromSensorData(
data, opt.depth_decimation, static_cast<float>(opt.depth_max_m),
static_cast<float>(opt.depth_min_m));
if (!cloud) return;
VoxelAccumulator acc(opt);
for (const auto& p : cloud->points) acc.AddPoint(p.x, p.y, p.z);
VoxelGrid vg;
acc.Finish(&vg);
const double s = opt.emit_size_m;
out->reserve(vg.cells.size() * 3);
for (const VoxelIndex& k : vg.cells) {
out->push_back(static_cast<float>((k.x + 0.5) * s));
out->push_back(static_cast<float>((k.y + 0.5) * s));
out->push_back(static_cast<float>((k.z + 0.5) * s));
}
}
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
const VoxelExportOptions& opt,
VoxelNodeCache* cache, VoxelGrid* out) {
const std::map<int, rtabmap::Transform>& poses = slam.getLocalOptimizedPoses();
if (poses.empty()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"khong co pose nao de dung ban do voxel");
}
const rtabmap::Memory* mem = slam.getMemory();
if (mem == nullptr) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"rtabmap chua co Memory");
}
// Bo node khong con trong do thi (bi gop/xoa) -- khong thi cache phinh mai.
for (auto it = cache->nodes.begin(); it != cache->nodes.end();) {
it = poses.count(it->first) ? std::next(it) : cache->nodes.erase(it);
}
// Di tren doc: diem dat o z THAT, va dai z cat theo SAN tai cho diem -- ca
// hai viec lam O DAY, nen bo gom nhan moi z. Cache diem cua node giu dai
// rong hon (mat doc xuong phia truoc o z am so voi node).
const bool use_floor = opt.node_z != nullptr && opt.floor != nullptr;
VoxelExportOptions acc_opt = opt;
if (use_floor) {
acc_opt.z_min = -1e9;
acc_opt.z_max = 1e9;
}
VoxelExportOptions node_opt = opt;
if (use_floor) {
node_opt.z_min = opt.z_min - 3.0;
node_opt.z_max = opt.z_max + 3.0;
}
const bool carve = opt.clear_after_views > 0;
if (cache->wide != use_floor || cache->views != carve) {
cache->nodes.clear();
cache->wide = use_floor;
cache->views = carve;
}
// min_node_hits > 1: dem so node thay moi voxel (loc diem bay, nguoi di
// ngang). Xoa vat da roi di cung can dem (biet node CUOI thay voxel). Con
// lai: duong cu, re hon.
const bool count_hits = opt.min_node_hits > 1 || carve;
VoxelAccumulator acc(acc_opt);
VoxelHitCounter hits(acc_opt);
VoxelCarver carver(opt.clear_range_m, opt.clear_after_views);
size_t nodes_used = 0, fetched = 0, pending = 0, no_points = 0;
int order = 0; // thu tu thoi gian: id node RTAB-Map tang theo thoi gian
for (const auto& kv : poses) {
if (kv.second.isNull()) continue;
auto it = cache->nodes.find(kv.first);
if (it == cache->nodes.end()) {
if (fetched >= opt.max_new_nodes) {
++pending;
continue;
}
++fetched;
// images=true, con lai false: chi can depth + camera model.
rtabmap::SensorData data = mem->getNodeData(kv.first, true, false, false, false);
// ⚠️ BAT BUOC. Thieu dong nay thi depthOrRightRaw() tra ma tran RONG o
// moi node va ban do 3D im lang rong khong.
data.uncompressData();
VoxelNodeCache::Node n;
NodeCloudFromSensorData(data, node_opt, &n.pts);
// Khoi 4x4 tren depth 320x240 -> 80x60 (~10 KB/node): ~0.9 do moi o,
// 4.5 cm o 3 m -- co voxel 5 cm.
if (carve) NodeDepthViewFromSensorData(data, 4, &n.view);
it = cache->nodes.emplace(kv.first, std::move(n)).first;
}
const std::vector<float>& pts = it->second.pts;
const int node_order = order++;
if (pts.empty()) {
++no_points;
continue;
}
// Pose da toi uu: node -> map. Dung ma tran 3x4 dung san, 12 phep nhan
// cho moi diem, thay vi dung mot rtabmap::Transform cho tung diem.
const rtabmap::Transform& T = kv.second;
const float r00 = T.r11(), r01 = T.r12(), r02 = T.r13(), tx = T.x();
const float r10 = T.r21(), r11 = T.r22(), r12 = T.r23(), ty = T.y();
const float r20 = T.r31(), r21 = T.r32(), r22 = T.r33(), tz = T.z();
double z_off = 0.0;
if (use_floor) {
const auto zi = opt.node_z->find(kv.first);
if (zi != opt.node_z->end()) z_off = zi->second;
}
if (carve) {
// Camera cua node nay de hoi "nhin xuyen qua" -- cung pose (va z node)
// voi diem cua no.
const float b[12] = {r00, r01, r02, tx, r10, r11, r12, ty,
r20, r21, r22, static_cast<float>(tz + z_off)};
carver.AddView(node_order, b, &it->second.view);
}
if (count_hits) hits.BeginNode(node_order);
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
const float px = pts[i], py = pts[i + 1], pz = pts[i + 2];
const double wx = r00 * px + r01 * py + r02 * pz + tx;
const double wy = r10 * px + r11 * py + r12 * pz + ty;
double wz = r20 * px + r21 * py + r22 * pz + tz;
if (use_floor) {
wz += z_off;
double f = z_off;
opt.floor->FloorAt(wx, wy, &f);
const double h = wz - f;
if (opt.floor_cells != nullptr && std::fabs(h) <= opt.floor_band) {
const double inv = 1.0 / opt.emit_size_m;
opt.floor_cells->push_back(
PackFloorCell(static_cast<int32_t>(std::floor(wx * inv)),
static_cast<int32_t>(std::floor(wy * inv))));
}
if (h < opt.z_min || h > opt.z_max) continue;
}
if (count_hits) hits.AddPoint(wx, wy, wz);
else acc.AddPoint(wx, wy, wz);
}
if (count_hits) hits.EndNode();
++nodes_used;
}
if (nodes_used == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
pending > 0 ? "dang nap depth cua node"
: "khong node nao co depth -- DB quet voi camera_3d=false, "
"hoac khong co camera");
}
const auto t_fin = std::chrono::steady_clock::now();
if (count_hits) hits.Finish(out, carve ? &carver : nullptr);
else acc.Finish(out);
const size_t stride = count_hits ? hits.stride() : acc.stride();
const size_t clamped = count_hits ? hits.clamped() : acc.clamped();
if (carve) {
const double ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_fin)
.count();
VSLAM_INFO_THROTTLE(30.0, "slam: xoa " << hits.carved()
<< " voxel vat da roi di (>= " << opt.clear_after_views
<< " node sau nhin xuyen qua, " << carver.views() << " node co depth, "
<< ms << " ms)");
}
// Mot dong, mot lan moi 30 giay. `khong co diem` cao bat thuong nghia la
// getNodeData khong tra depth -- thu dau tien can nhin khi ban do 3D rong.
VSLAM_INFO_THROTTLE(30.0, "slam: voxel " << out->cells.size() << " o tu "
<< nodes_used << " node (dang nap " << pending << ", "
<< no_points << " node khong co diem"
<< (count_hits ? ", loc >= " + std::to_string(opt.min_node_hits) +
" node thay"
: std::string())
<< (out->truncated
? ", GIAM MAU 1/" + std::to_string(stride) +
" -- cham tran max_cells"
: std::string())
<< ")");
if (clamped > 0) {
VSLAM_WARN_THROTTLE(30.0, "slam: " << clamped
<< " diem ngoai dai chi so voxel -- bo qua");
}
return StatusResponse::Ok();
}
} // namespace vslam

View File

@@ -0,0 +1,36 @@
#include "vslam/vpr_encoder.h"
#include <opencv2/imgproc.hpp>
namespace vslam {
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw) {
static const float kMean[3] = {0.485f, 0.456f, 0.406f};
static const float kStd[3] = {0.229f, 0.224f, 0.225f};
cv::Mat g = gray;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::Mat eq, rs;
cv::createCLAHE(cfg.clahe_clip, cv::Size(cfg.clahe_grid, cfg.clahe_grid))->apply(g, eq);
cv::resize(eq, rs, cv::Size(cfg.width, cfg.height), 0, 0, cv::INTER_LINEAR);
const size_t plane = static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
chw->resize(3 * plane);
for (int c = 0; c < 3; ++c) {
float* dst = chw->data() + c * plane;
for (int y = 0; y < cfg.height; ++y) {
const uint8_t* src = rs.ptr<uint8_t>(y);
for (int x = 0; x < cfg.width; ++x) {
dst[static_cast<size_t>(y) * cfg.width + x] = (src[x] / 255.0f - kMean[c]) / kStd[c];
}
}
}
}
#ifndef VSLAM_HAVE_TENSORRT
StatusResponse CreateVprEncoder(const VprConfig&, std::unique_ptr<VprEncoder>* out) {
out->reset();
return StatusResponse::Error(StatusCode::kUnavailable,
"VPR can build voi -DVSLAM_WITH_TENSORRT=ON (chi Jetson)");
}
#endif
} // namespace vslam

View File

@@ -0,0 +1,150 @@
// CHI bien dich voi -DVSLAM_WITH_TENSORRT=ON (xem CMakeLists.txt).
#include "vslam/vpr_encoder.h"
#include <NvInfer.h>
#include <cuda_runtime_api.h>
#include <cmath>
#include <fstream>
#include <iterator>
#include <mutex>
#include "vslam/log.h"
namespace vslam {
namespace {
class TrtLogger : public nvinfer1::ILogger {
public:
void log(Severity s, const char* msg) noexcept override {
if (s <= Severity::kWARNING) VSLAM_WARN("tensorrt: " << msg);
}
};
// IRuntime giu tham chieu toi logger suot doi -> logger tinh.
TrtLogger& Logger() {
static TrtLogger l;
return l;
}
size_t Volume(const nvinfer1::Dims& d) {
size_t v = 1;
for (int i = 0; i < d.nbDims; ++i) v *= static_cast<size_t>(d.d[i]);
return v;
}
class TrtVprEncoder : public VprEncoder {
public:
~TrtVprEncoder() override {
if (d_in_ != nullptr) cudaFree(d_in_);
if (d_out_ != nullptr) cudaFree(d_out_);
if (stream_ != nullptr) cudaStreamDestroy(stream_);
// ctx_ -> engine_ -> runtime_ huy theo thu tu nguoc khai bao: dung thu tu TensorRT can.
}
StatusResponse Init(const VprConfig& cfg) {
cfg_ = cfg;
std::ifstream f(cfg.engine_path, std::ios::binary);
if (!f) {
return StatusResponse::Error(StatusCode::kNotFound,
"vpr: khong mo duoc engine " + cfg.engine_path +
" -- dung bang trtexec (xem vpr_encoder.h)");
}
const std::vector<char> blob((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
runtime_.reset(nvinfer1::createInferRuntime(Logger()));
if (!runtime_) return Err("createInferRuntime");
engine_.reset(runtime_->deserializeCudaEngine(blob.data(), blob.size()));
if (!engine_) return Err("deserializeCudaEngine -- engine dung cho may/TensorRT khac?");
ctx_.reset(engine_->createExecutionContext());
if (!ctx_) return Err("createExecutionContext");
for (int i = 0; i < engine_->getNbIOTensors(); ++i) {
const char* name = engine_->getIOTensorName(i);
if (engine_->getTensorDataType(name) != nvinfer1::DataType::kFLOAT) {
return Err(std::string("tensor ") + name + " khong phai float32");
}
const size_t n = Volume(engine_->getTensorShape(name));
if (engine_->getTensorIOMode(name) == nvinfer1::TensorIOMode::kINPUT) {
in_name_ = name;
in_elems_ = n;
} else {
out_name_ = name;
out_elems_ = n;
}
}
const size_t want = 3u * static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
if (in_name_.empty() || out_name_.empty() || in_elems_ != want) {
return Err("engine co dau vao " + std::to_string(in_elems_) + " so, can " +
std::to_string(want) + " (3x" + std::to_string(cfg.height) + "x" +
std::to_string(cfg.width) + ")");
}
if (cudaStreamCreate(&stream_) != cudaSuccess ||
cudaMalloc(&d_in_, in_elems_ * sizeof(float)) != cudaSuccess ||
cudaMalloc(&d_out_, out_elems_ * sizeof(float)) != cudaSuccess) {
return Err("cap phat bo nho GPU");
}
if (!ctx_->setTensorAddress(in_name_.c_str(), d_in_) ||
!ctx_->setTensorAddress(out_name_.c_str(), d_out_)) {
return Err("setTensorAddress");
}
VSLAM_INFO("vpr: TensorRT engine " << cfg.engine_path << " -- vao " << in_name_ << " ("
<< in_elems_ << " so), ra " << out_name_ << " (" << out_elems_ << " chieu)");
return StatusResponse::Ok();
}
StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) override {
if (gray.empty()) return StatusResponse::Error(StatusCode::kInvalidArgument, "vpr: anh rong");
std::lock_guard<std::mutex> lk(mu_);
VprPreprocess(gray, cfg_, &host_in_);
desc->resize(out_elems_);
if (cudaMemcpyAsync(d_in_, host_in_.data(), in_elems_ * sizeof(float),
cudaMemcpyHostToDevice, stream_) != cudaSuccess ||
!ctx_->enqueueV3(stream_) ||
cudaMemcpyAsync(desc->data(), d_out_, out_elems_ * sizeof(float),
cudaMemcpyDeviceToHost, stream_) != cudaSuccess ||
cudaStreamSynchronize(stream_) != cudaSuccess) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: suy luan TensorRT loi");
}
// Mo hinh da L2 o lop cuoi, nhung fp16 lam lech chuan chut it -> chuan hoa lai.
double n2 = 0.0;
for (float v : *desc) n2 += static_cast<double>(v) * v;
const float inv = n2 > 0.0 ? static_cast<float>(1.0 / std::sqrt(n2)) : 0.0f;
for (float& v : *desc) v *= inv;
return StatusResponse::Ok();
}
int dim() const override { return static_cast<int>(out_elems_); }
private:
static StatusResponse Err(const std::string& m) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: " + m);
}
VprConfig cfg_;
std::unique_ptr<nvinfer1::IRuntime> runtime_;
std::unique_ptr<nvinfer1::ICudaEngine> engine_;
std::unique_ptr<nvinfer1::IExecutionContext> ctx_;
std::string in_name_, out_name_;
size_t in_elems_ = 0, out_elems_ = 0;
void* d_in_ = nullptr;
void* d_out_ = nullptr;
cudaStream_t stream_ = nullptr;
std::vector<float> host_in_;
std::mutex mu_;
};
} // namespace
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out) {
std::unique_ptr<TrtVprEncoder> e(new TrtVprEncoder);
const StatusResponse st = e->Init(cfg);
if (!st.ok()) {
out->reset();
return st;
}
*out = std::move(e);
return StatusResponse::Ok();
}
} // namespace vslam

View File

@@ -40,6 +40,21 @@ enum class BinaryType : uint8_t {
// TINH: trong mo phong no khong bao gio doi, nen chi gui MOT lan cho moi // TINH: trong mo phong no khong bao gio doi, nen chi gui MOT lan cho moi
// client. // client.
kWorldMap = 6, kWorldMap = 6,
// --- Ban do voxel 3D ---
//
// kVoxelFull di theo TUNG MANH: mot ban do 60k o la ~360 kB, gui mot cuc se
// nghen ca hang doi 4 khung cua session. Moi manh tu mo ta (epoch,
// chunk_index, chunk_count) nen client rap lai duoc ma khong can trang thai
// ngoai.
//
// kVoxelDelta chi mang phan THEM/BOT so voi epoch client dang giu. Quet
// tien binh thuong thi n_del = 0 va khung chi vai tram byte.
//
// ⚠️ KHONG tai dung so 4 (kMapPatch, da bo): mot trinh duyet con cache
// app.js cu se giai khung voxel thanh map patch va ve rac len ban do.
kVoxelFull = 7,
kVoxelDelta = 8,
}; };
constexpr size_t kBinaryHeaderSize = 16; constexpr size_t kBinaryHeaderSize = 16;
@@ -58,20 +73,85 @@ void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out);
// Giam mau xuong `max_points` bang cach lay buoc deu, roi luong tu hoa theo // Giam mau xuong `max_points` bang cach lay buoc deu, roi luong tu hoa theo
// `quant_m`. Bo diem NaN. // `quant_m`. Bo diem NaN.
//
// `delta` quy diem ve he base_footprint HIEN TAI truoc khi ma hoa. Ap o day
// chu khong tren ca dam may vi o day da qua buoc deu: quy 40 k diem roi vut
// di 36 k la lang phi thuan tuy. Dong nhat = khong bu.
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points, void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, std::string* out); float quant_m, const Pose2D& delta, std::string* out);
// Do cao SAN cua ban do (slam.yaml slope.enabled): luoi THO, mm, kFloorUnknown
// = chua biet. Web uon mat phang ban do 2D theo luoi nay -- khong co no thi
// mat doc va san tang tren duoc ve o z = 0, nam DUOI tuong voxel (o z that)
// va trong nhu san bi thung.
constexpr int16_t kFloorUnknown = -32768;
struct MapFloorGrid {
float resolution = 0.2f;
uint32_t width = 0;
uint32_t height = 0;
float origin_x = 0.0f;
float origin_y = 0.0f;
std::vector<int16_t> mm; // hang chinh, hang 0 = y nho nhat (nhu OccupancyGrid)
};
// RLE hang-chinh. Xem rle.h. // RLE hang-chinh. Xem rle.h.
// `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do // `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do
// THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y // THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y
// nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang. // nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang.
//
// `floor_grid` (tuy chon): khoi do cao san NOI SAU phan RLE -- magic "FLH1", f32
// res, i32 w, i32 h, f32 ox, f32 oy, roi w*h int16 (mm). Khong co thi khung y
// het cu.
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type = BinaryType::kMapFull); BinaryType type = BinaryType::kMapFull,
const MapFloorGrid* floor_grid = nullptr);
// Chi vung bao (bbox) cac o doi so voi `prev`. Tra false neu kich thuoc hai // (kMapPatch = 4 da bi BO. No noi duoc vao dau: cong per-session chi la mot
// map khac nhau (khi do phai gui MAP_FULL) hoac khong co o nao doi. // atomic `acked_map_version_`, khong dien ta noi "session nay dang giu luoi
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev, // NAO", va ban than no bail moi khi origin hay kich thuoc doi -- tuc gan nhu
UnixTime stamp, std::string* out); // luon bail dung luc mapping. Viec nen delta thuc su co lai nam o ban do
// voxel, xem EncodeVoxelDelta.)
// --- Ban do voxel 3D -------------------------------------------------------
// Mot manh cua ban do day du. `cells` phai DA SAP XEP; ham nay khong sap lai.
//
// Bo cuc payload (sau header 16 byte):
// 0 f32 resolution kich thuoc o, m
// 4 f32 origin_x
// 8 f32 origin_y
// 12 f32 origin_z
// 16 u32 epoch
// 20 u32 total tong so o cua CA epoch (khong phai cua manh nay)
// 24 u16 chunk_index 0-based
// 26 u16 chunk_count
// 28 u32 n so o trong manh nay
// 32 n * (i16 x, i16 y, i16 z)
//
// Khong luong tu hoa them: chi so voxel CHINH LA du lieu, khac kCloud von
// phai chia cho quant_m.
void EncodeVoxelFull(const VoxelGrid& grid, UnixTime stamp, size_t first,
size_t count, uint16_t chunk_index, uint16_t chunk_count,
std::string* out);
// So manh can de gui het `grid` voi tran `chunk_bytes` moi manh. Luon >= 1,
// ke ca khi ban do rong -- client can mot khung de biet "ban do gio rong".
uint16_t VoxelChunkCount(const VoxelGrid& grid, uint32_t chunk_bytes);
size_t VoxelCellsPerChunk(uint32_t chunk_bytes);
// Phan THEM/BOT so voi epoch client dang giu.
//
// Bo cuc payload:
// 0 u32 epoch phai khop epoch client dang giu, khong thi client xin sync lai
// 4 u32 seq tang dan moi delta; hut so = mat khung -> xin sync lai
// 8 u32 n_add
// 12 u32 n_del
// 16 n_add * (i16 x, i16 y, i16 z)
// .. n_del * (i16 x, i16 y, i16 z)
void EncodeVoxelDelta(uint32_t epoch, uint32_t seq,
const std::vector<VoxelIndex>& added,
const std::vector<VoxelIndex>& removed, UnixTime stamp,
std::string* out);
// Thua hoa: chi giu diem cach diem truoc > min_step_m. // Thua hoa: chi giu diem cach diem truoc > min_step_m.
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m, void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
@@ -88,7 +168,24 @@ struct BinaryHeader {
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out); bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
bool DecodeScan(const std::string& buf, LaserScan* out); bool DecodeScan(const std::string& buf, LaserScan* out);
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out); // `floor_grid` (tuy chon) nhan khoi do cao san neu khung co; khong co thi width = 0.
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out,
MapFloorGrid* floor_grid = nullptr);
// Giai mot manh. `out` duoc NOI THEM, khong xoa -- rap nhieu manh bang cach
// goi lien tiep. `total`/`chunk_index`/`chunk_count`/`epoch` tra qua con tro
// de test kiem duoc phan dieu phoi.
struct VoxelChunkInfo {
uint32_t epoch = 0;
uint32_t total = 0;
uint16_t chunk_index = 0;
uint16_t chunk_count = 0;
};
bool DecodeVoxelFull(const std::string& buf, VoxelChunkInfo* info,
std::vector<VoxelIndex>* out);
bool DecodeVoxelDelta(const std::string& buf, uint32_t* epoch, uint32_t* seq,
std::vector<VoxelIndex>* added,
std::vector<VoxelIndex>* removed);
} // namespace vslam } // namespace vslam

View File

@@ -31,11 +31,25 @@ struct WebConfig {
double path_hz = 1.0; double path_hz = 1.0;
// MAP khong co tan so: chi gui khi map_version doi. // MAP khong co tan so: chi gui khi map_version doi.
// Ban do voxel khong co tan so gui, ca tap day du lan delta: chung di theo
// SU KIEN (epoch doi / do thi doi), giong MAP. Nhip that do duty 25% cua
// luong slam quyet dinh -- xem Runtime::SlamLoop.
// --- Giam bang thong -------------------------------------------------- // --- Giam bang thong --------------------------------------------------
uint32_t cloud_max_points = 4000; // voxel-stride truoc khi ma hoa uint32_t cloud_max_points = 4000; // voxel-stride truoc khi ma hoa
float cloud_quant_m = 0.01f; // luong tu hoa i16 -> dai +-327 m float cloud_quant_m = 0.01f; // luong tu hoa i16 -> dai +-327 m
double path_min_step_m = 0.1; // thua hoa quy dao double path_min_step_m = 0.1; // thua hoa quy dao
// Mot manh cua ban do voxel day du. 16 kB = 2722 o.
//
// ⚠️ Manh full-sync KHONG di qua hang doi (xem Publish): chung duoc bom
// `voxel_sync_chunks_per_tick` manh moi lan Publish. O 10 Hz va 16 kB thi
// mot dot dong bo la 160 kB/s -- vuot ngan sach 120 kB/s, nhung CHI trong
// vai giay dau va chi voi client vua vao. Khung cloud (drop duoc) hap thu
// phan chenh.
uint32_t voxel_chunk_bytes = 16384;
uint32_t voxel_sync_chunks_per_tick = 1;
// Hang doi gui moi phien. Day thi drop khung CU NHAT khong phai MAP. // Hang doi gui moi phien. Day thi drop khung CU NHAT khong phai MAP.
// MAP khong bao gio bi drop -- thay vao do bat co map_pending. // MAP khong bao gio bi drop -- thay vao do bat co map_pending.
size_t max_queued_frames = 4; size_t max_queued_frames = 4;

View File

@@ -13,6 +13,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "vslam/binary_codec.h"
#include "vslam/stats.h" #include "vslam/stats.h"
#include "vslam/vslam_common.h" #include "vslam/vslam_common.h"
@@ -45,6 +46,20 @@ struct SlamSnapshot {
int proximity_total = 0; int proximity_total = 0;
uint32_t map_version = 0; uint32_t map_version = 0;
double process_ms = 0.0; double process_ms = 0.0;
// Ban do voxel 3D den tu dau: "depth" | "thieu depth" | "off".
// Hien trong JSON status de mot ban do 3D RONG doc duoc ma khong phai mo
// khung 3D len xem -- cung ly do voi dong dem o/trong/chua-biet cua luoi 2D.
std::string voxels_source = "off";
uint32_t voxel_cells = 0;
uint32_t voxel_epoch = 0;
// Trang thai dinh vi lai tu dong (--slam-reloc): "XOAY TAI CHO 120/300 do",
// "NHAP NHANG ... di chuyen roi xoay tiep", "DA DINH VI ...". Rong = khong bat.
std::string reloc;
// CHUA dinh vi xong: `pose` chi la vi tri DOAN (ung vien so 1 cua vong khop
// gan nhat, hoac odom tu 0 truoc vong dau) -> web ve robot MO + dong chu.
bool reloc_pending = false;
}; };
struct TeleopSnapshot { struct TeleopSnapshot {
@@ -124,6 +139,13 @@ struct WebSnapshot {
double pitch = 0.0; double pitch = 0.0;
bool accel_ok = true; bool accel_ok = true;
// Di tren doc (slam.yaml `slope:`): z UOC LUONG cua robot. Chi xuat khi bat
// -- 0 khi tat la noi doi, client khong phan biet duoc "o san" voi "khong biet".
bool have_height = false;
double height_z = 0.0;
double height_sigma = 0.0;
bool on_slope = false;
// ============ GROUND TRUTH ============ // ============ GROUND TRUTH ============
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong // CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong
// repo cu, noi ghi ro "khong estimator nao duoc subscribe". // repo cu, noi ghi ro "khong estimator nao duoc subscribe".
@@ -137,6 +159,7 @@ struct WebSnapshot {
Pose2D ground_truth; Pose2D ground_truth;
double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align
double gt_pitch = 0.0; double gt_pitch = 0.0;
double gt_z = 0.0; // do cao san THAT duoi robot (world co doc)
SafetySnapshot safety; SafetySnapshot safety;
SlamSnapshot slam; SlamSnapshot slam;
@@ -144,12 +167,38 @@ struct WebSnapshot {
TeleopSnapshot teleop; TeleopSnapshot teleop;
LaserScanPtr scan; LaserScanPtr scan;
// Phep bien doi quy scan tu he laser LUC QUET ve pose HIEN TAI. Khac
// `cloud_delta` o cho no KHONG duoc ap o server: scan la du lieu cuc
// (range, goc) va mot phep doi SE(2) khong ap thang len do duoc. Gui len
// trinh duyet, noi scan da thanh diem Descartes.
Pose2D scan_delta;
bool have_scan_delta = false;
PointCloudXYZPtr cloud; PointCloudXYZPtr cloud;
// Phep bien doi quy cloud tu he base_footprint LUC CHUP ve he
// base_footprint HIEN TAI. Trinh duyet ve cloud bang pose moi nhat, nen
// mot dam may 0.5 s tuoi se bi dat lech dung `v * 0.5 s` neu khong bu.
// Dong nhat khi khong biet pose luc chup -- xem Runtime::WebLoop.
Pose2D cloud_delta;
bool have_cloud_delta = false;
OccupancyGridPtr map; // ban do SLAM dung OccupancyGridPtr map; // ban do SLAM dung
// Do cao SAN cua ban do (che do doc), gui kem khung map. Null = phang.
std::shared_ptr<const MapFloorGrid> map_floor;
// Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay // Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay
// that -- luc do khong co su that nao de doi chieu. // that -- luc do khong co su that nao de doi chieu.
OccupancyGridPtr world_map; OccupancyGridPtr world_map;
std::vector<Pose2D> trajectory; std::vector<Pose2D> trajectory;
// --- Ban do voxel 3D ---
//
// `voxels` la TAP DAY DU hien tai (da sap xep). WebServer chia manh va gui
// cho session nao chua co epoch nay.
//
// `voxel_delta` la payload DA MA HOA san cua phan them/bot so voi epoch
// truoc -- ma hoa MOT lan o luong slam roi dung chung cho moi session, y het
// cach khung MAP_FULL dung chung mot `buf`. Null khi khong co gi doi.
VoxelGridPtr voxels;
std::shared_ptr<const std::string> voxel_delta;
}; };
} // namespace vslam } // namespace vslam

View File

@@ -101,7 +101,7 @@ void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out) {
} }
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points, void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
float quant_m, std::string* out) { float quant_m, const Pose2D& delta, std::string* out) {
if (quant_m <= 0.0f) quant_m = 0.01f; if (quant_m <= 0.0f) quant_m = 0.01f;
// Lay buoc deu thay vi cat duoi: cat duoi lam mat ca mot vung khong gian, // Lay buoc deu thay vi cat duoi: cat duoi lam mat ca mot vung khong gian,
@@ -118,22 +118,27 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points
} }
PutHeader(out, BinaryType::kCloud, stamp); PutHeader(out, BinaryType::kCloud, stamp);
// Goc = (0,0,0): cloud da o frame base_footprint sau gravity_align. // Goc = (0,0,0): sau khi ap `delta` o vong duoi, diem nam trong he
// base_footprint HIEN TAI -- dung he ma trinh duyet ve.
PutF32(out, 0.0f); PutF32(out, 0.0f);
PutF32(out, 0.0f); PutF32(out, 0.0f);
PutF32(out, 0.0f); PutF32(out, 0.0f);
PutF32(out, quant_m); PutF32(out, quant_m);
PutU32(out, n_out); PutU32(out, n_out);
const double dc = std::cos(delta.theta), ds = std::sin(delta.theta);
const float inv = 1.0f / quant_m; const float inv = 1.0f / quant_m;
constexpr float kLim = 32767.0f; constexpr float kLim = 32767.0f;
for (size_t i = 0; i < n_in; i += stride) { for (size_t i = 0; i < n_in; i += stride) {
const PointXYZ& p = cloud.points[i]; const PointXYZ& p = cloud.points[i];
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue; if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
// z khong doi: `delta` la SE(2), robot khong di chuyen theo phuong dung.
const double bx = delta.x + dc * p.x - ds * p.y;
const double by = delta.y + ds * p.x + dc * p.y;
// Kep vao dai i16. Voi quant 0.01 m thi dai la +-327 m -- khong bao gio // Kep vao dai i16. Voi quant 0.01 m thi dai la +-327 m -- khong bao gio
// cham toi trong nha, nhung kep van re hon la de tran am tham. // cham toi trong nha, nhung kep van re hon la de tran am tham.
const float qx = std::max(-kLim, std::min(kLim, p.x * inv)); const float qx = std::max(-kLim, std::min(kLim, static_cast<float>(bx) * inv));
const float qy = std::max(-kLim, std::min(kLim, p.y * inv)); const float qy = std::max(-kLim, std::min(kLim, static_cast<float>(by) * inv));
const float qz = std::max(-kLim, std::min(kLim, p.z * inv)); const float qz = std::max(-kLim, std::min(kLim, p.z * inv));
PutI16(out, static_cast<int16_t>(std::lround(qx))); PutI16(out, static_cast<int16_t>(std::lround(qx)));
PutI16(out, static_cast<int16_t>(std::lround(qy))); PutI16(out, static_cast<int16_t>(std::lround(qy)));
@@ -142,7 +147,7 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points
} }
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
BinaryType type) { BinaryType type, const MapFloorGrid* floor_grid) {
PutHeader(out, type, stamp); PutHeader(out, type, stamp);
PutF32(out, map.resolution); PutF32(out, map.resolution);
PutI32(out, static_cast<int32_t>(map.width)); PutI32(out, static_cast<int32_t>(map.width));
@@ -164,68 +169,104 @@ void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
(*out)[run_count_off + static_cast<size_t>(i)] = (*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF); static_cast<char>((r32 >> (8 * i)) & 0xFF);
} }
// Khoi do cao san (che do doc), NOI SAU phan RLE -- xem binary_codec.h.
const MapFloorGrid* fg = floor_grid;
if (fg != nullptr && fg->width > 0 && fg->height > 0 &&
fg->mm.size() == static_cast<size_t>(fg->width) * fg->height) {
out->append("FLH1", 4);
PutF32(out, fg->resolution);
PutI32(out, static_cast<int32_t>(fg->width));
PutI32(out, static_cast<int32_t>(fg->height));
PutF32(out, fg->origin_x);
PutF32(out, fg->origin_y);
for (int16_t v : fg->mm) PutI16(out, v);
}
} }
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev, // --- Ban do voxel 3D -------------------------------------------------------
UnixTime stamp, std::string* out) {
// Kich thuoc doi -> khong vá duoc, phai gui full. namespace {
if (map.width != prev.width || map.height != prev.height ||
map.data.size() != prev.data.size() || constexpr size_t kVoxelFullHeaderBytes = 32; // sau header chung 16 byte
std::abs(map.resolution - prev.resolution) > 1e-6f || constexpr size_t kVoxelCellBytes = 6; // i16 * 3
std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 ||
std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) { void PutCells(std::string* out, const VoxelIndex* cells, size_t n) {
return false; for (size_t i = 0; i < n; ++i) {
PutI16(out, cells[i].x);
PutI16(out, cells[i].y);
PutI16(out, cells[i].z);
} }
}
// Vung bao cac o doi. bool GetCells(const std::string& b, size_t off, size_t n,
int32_t x0 = static_cast<int32_t>(map.width); std::vector<VoxelIndex>* out) {
int32_t y0 = static_cast<int32_t>(map.height); if (b.size() < off + n * kVoxelCellBytes) return false;
int32_t x1 = -1, y1 = -1; out->reserve(out->size() + n);
for (size_t i = 0; i < n; ++i) {
for (uint32_t y = 0; y < map.height; ++y) { const size_t o = off + i * kVoxelCellBytes;
const size_t row = static_cast<size_t>(y) * map.width; VoxelIndex k;
for (uint32_t x = 0; x < map.width; ++x) { // Qua uint16 roi ep ve int16: ep thang tu char la noi dau am di lac.
if (map.data[row + x] == prev.data[row + x]) continue; k.x = static_cast<int16_t>(GetU16(b, o));
const int32_t xi = static_cast<int32_t>(x); k.y = static_cast<int16_t>(GetU16(b, o + 2));
const int32_t yi = static_cast<int32_t>(y); k.z = static_cast<int16_t>(GetU16(b, o + 4));
if (xi < x0) x0 = xi; out->push_back(k);
if (yi < y0) y0 = yi;
if (xi > x1) x1 = xi;
if (yi > y1) y1 = yi;
}
}
if (x1 < 0) return false; // khong o nao doi
const int32_t w = x1 - x0 + 1;
const int32_t h = y1 - y0 + 1;
std::vector<int8_t> patch;
patch.reserve(static_cast<size_t>(w) * static_cast<size_t>(h));
for (int32_t y = y0; y <= y1; ++y) {
const size_t row = static_cast<size_t>(y) * map.width;
for (int32_t x = x0; x <= x1; ++x) {
patch.push_back(map.data[row + static_cast<size_t>(x)]);
}
}
PutHeader(out, BinaryType::kMapPatch, stamp);
PutI32(out, x0);
PutI32(out, y0);
PutI32(out, w);
PutI32(out, h);
const size_t run_count_off = out->size();
PutU32(out, 0);
const size_t runs = RleEncode(patch, out);
const uint32_t r32 = static_cast<uint32_t>(runs);
for (int i = 0; i < 4; ++i) {
(*out)[run_count_off + static_cast<size_t>(i)] =
static_cast<char>((r32 >> (8 * i)) & 0xFF);
} }
return true; return true;
} }
} // namespace
size_t VoxelCellsPerChunk(uint32_t chunk_bytes) {
const size_t usable = chunk_bytes > (kBinaryHeaderSize + kVoxelFullHeaderBytes)
? chunk_bytes - kBinaryHeaderSize - kVoxelFullHeaderBytes
: 0;
const size_t n = usable / kVoxelCellBytes;
return n > 0 ? n : 1; // khong bao gio 0: se lap vo han khi chia manh
}
uint16_t VoxelChunkCount(const VoxelGrid& grid, uint32_t chunk_bytes) {
const size_t per = VoxelCellsPerChunk(chunk_bytes);
// Ban do RONG van phai co MOT manh: do la cach client biet "gio khong con
// gi" thay vi giu mai tap cu.
if (grid.cells.empty()) return 1;
const size_t n = (grid.cells.size() + per - 1) / per;
return static_cast<uint16_t>(std::min<size_t>(n, 65535));
}
void EncodeVoxelFull(const VoxelGrid& grid, UnixTime stamp, size_t first,
size_t count, uint16_t chunk_index, uint16_t chunk_count,
std::string* out) {
const size_t total = grid.cells.size();
const size_t begin = std::min(first, total);
const size_t n = std::min(count, total - begin);
PutHeader(out, BinaryType::kVoxelFull, stamp);
PutF32(out, grid.resolution);
PutF32(out, static_cast<float>(grid.origin_x));
PutF32(out, static_cast<float>(grid.origin_y));
PutF32(out, static_cast<float>(grid.origin_z));
PutU32(out, grid.epoch);
PutU32(out, static_cast<uint32_t>(total));
PutU16(out, chunk_index);
PutU16(out, chunk_count);
PutU32(out, static_cast<uint32_t>(n));
PutCells(out, grid.cells.data() + begin, n);
}
void EncodeVoxelDelta(uint32_t epoch, uint32_t seq,
const std::vector<VoxelIndex>& added,
const std::vector<VoxelIndex>& removed, UnixTime stamp,
std::string* out) {
PutHeader(out, BinaryType::kVoxelDelta, stamp);
PutU32(out, epoch);
PutU32(out, seq);
PutU32(out, static_cast<uint32_t>(added.size()));
PutU32(out, static_cast<uint32_t>(removed.size()));
PutCells(out, added.data(), added.size());
PutCells(out, removed.data(), removed.size());
}
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m, void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
std::string* out) { std::string* out) {
std::vector<const Pose2D*> kept; std::vector<const Pose2D*> kept;
@@ -305,9 +346,10 @@ bool DecodeScan(const std::string& buf, LaserScan* out) {
return true; return true;
} }
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) { bool DecodeMapFull(const std::string& buf, OccupancyGrid* out, MapFloorGrid* floor_grid) {
BinaryHeader h; BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false; if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
if (floor_grid != nullptr) *floor_grid = MapFloorGrid{};
size_t o = kBinaryHeaderSize; size_t o = kBinaryHeaderSize;
if (buf.size() < o + 28) return false; if (buf.size() < o + 28) return false;
@@ -323,8 +365,61 @@ bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
const size_t expected = static_cast<size_t>(out->width) * out->height; const size_t expected = static_cast<size_t>(out->width) * out->height;
if (!RleDecode(buf, o, runs, expected, &out->data)) return false; if (!RleDecode(buf, o, runs, expected, &out->data)) return false;
// Khoi do cao san tuy chon, ngay sau RLE (3 byte moi run).
o += static_cast<size_t>(runs) * 3;
if (floor_grid != nullptr && buf.size() >= o + 24 && buf.compare(o, 4, "FLH1") == 0) {
MapFloorGrid f;
f.resolution = GetF32(buf, o + 4);
f.width = static_cast<uint32_t>(GetI32(buf, o + 8));
f.height = static_cast<uint32_t>(GetI32(buf, o + 12));
f.origin_x = GetF32(buf, o + 16);
f.origin_y = GetF32(buf, o + 20);
const size_t n = static_cast<size_t>(f.width) * f.height;
if (buf.size() >= o + 24 + 2 * n) {
f.mm.resize(n);
for (size_t i = 0; i < n; ++i) {
f.mm[i] = static_cast<int16_t>(GetU16(buf, o + 24 + 2 * i));
}
*floor_grid = std::move(f);
}
}
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns)); out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
return true; return true;
} }
bool DecodeVoxelFull(const std::string& buf, VoxelChunkInfo* info,
std::vector<VoxelIndex>* out) {
BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kVoxelFull) return false;
if (buf.size() < kBinaryHeaderSize + 32) return false;
const size_t o = kBinaryHeaderSize;
info->epoch = GetU32(buf, o + 16);
info->total = GetU32(buf, o + 20);
info->chunk_index = GetU16(buf, o + 24);
info->chunk_count = GetU16(buf, o + 26);
const uint32_t n = GetU32(buf, o + 28);
return GetCells(buf, o + 32, n, out);
}
bool DecodeVoxelDelta(const std::string& buf, uint32_t* epoch, uint32_t* seq,
std::vector<VoxelIndex>* added,
std::vector<VoxelIndex>* removed) {
BinaryHeader h;
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kVoxelDelta) return false;
if (buf.size() < kBinaryHeaderSize + 16) return false;
const size_t o = kBinaryHeaderSize;
*epoch = GetU32(buf, o);
*seq = GetU32(buf, o + 4);
const uint32_t n_add = GetU32(buf, o + 8);
const uint32_t n_del = GetU32(buf, o + 12);
added->clear();
removed->clear();
if (!GetCells(buf, o + 16, n_add, added)) return false;
return GetCells(buf, o + 16 + static_cast<size_t>(n_add) * 6, n_del, removed);
}
} // namespace vslam } // namespace vslam

Some files were not shown because too many files have changed in this diff Show More