From 0a1b1b13f198e5a4253649bd90410f23c46ac5b4 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Wed, 23 Sep 2026 13:36:48 +0700 Subject: [PATCH] update --- CMakeLists.txt | 8 +- CMakePresets.json | 3 +- PROJECT_CONTEXT.md | 30 ++- README.md | 63 ++++- app/src/app_config.cc | 40 ++- app/src/app_config.h | 13 + app/src/runtime.cc | 139 +++++++++- app/src/runtime.h | 40 +++ app/src/wiring.cc | 24 ++ configuration_files/sensors.yaml | 34 ++- configuration_files/slam.yaml | 65 ++++- configuration_files/system.yaml | 19 ++ .../include/vslam/node_constants.h | 27 ++ .../vslam_common/include/vslam/vslam_common.h | 40 +++ libs/vslam_common/src/node_constants.cc | 72 +++++ libs/vslam_slam/CMakeLists.txt | 1 + .../include/vslam/occupancy_export.h | 5 + libs/vslam_slam/include/vslam/rtabmap_slam.h | 12 + libs/vslam_slam/include/vslam/voxel_export.h | 100 +++++++ libs/vslam_slam/src/occupancy_export.cc | 6 + libs/vslam_slam/src/rtabmap_params.cc | 36 +++ libs/vslam_slam/src/rtabmap_slam.cc | 58 ++++- libs/vslam_slam/src/voxel_export.cc | 246 ++++++++++++++++++ libs/vslam_web/include/vslam/binary_codec.h | 80 +++++- libs/vslam_web/include/vslam/web_config.h | 14 + libs/vslam_web/include/vslam/web_snapshot.h | 18 ++ libs/vslam_web/src/binary_codec.cc | 165 ++++++++---- libs/vslam_web/src/json_writer.cc | 7 +- libs/vslam_web/src/web_server.cc | 110 ++++++++ libs/vslam_web/www/app.js | 124 ++++++++- libs/vslam_web/www/app3d.js | 88 +++++++ libs/vslam_web/www/index.html | 4 + test/CMakeLists.txt | 10 + test/test_binary_codec.cc | 165 +++++++++--- test/test_map_path.cc | 118 +++++++++ test/test_slam.cc | 40 +++ test/test_voxel_export.cc | 210 +++++++++++++++ test/www/test_voxel_decode.js | 235 +++++++++++++++++ 38 files changed, 2331 insertions(+), 138 deletions(-) create mode 100644 libs/vslam_slam/include/vslam/voxel_export.h create mode 100644 libs/vslam_slam/src/voxel_export.cc create mode 100644 test/test_map_path.cc create mode 100644 test/test_voxel_export.cc create mode 100644 test/www/test_voxel_decode.js diff --git a/CMakeLists.txt b/CMakeLists.txt index 4534126..f52fc2d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -137,8 +137,14 @@ install(DIRECTORY configuration_files/ DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/vslam/configuration_files 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/ - 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) include(vslam_cpack) diff --git a/CMakePresets.json b/CMakePresets.json index 2b18f0f..f4434ca 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,8 +42,7 @@ "cacheVariables": { "CMAKE_BUILD_TYPE": "Release", "CMAKE_PREFIX_PATH": "/opt/vslam", - "CMAKE_INSTALL_PREFIX": "/opt/vslam", - "VSLAM_ENABLE_CPACK": "ON" + "CMAKE_INSTALL_PREFIX": "/opt/vslam" } } ], diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index 50a734c..6f70171 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -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 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`). -- 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) - 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). - 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` (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` (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; 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. - 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 - `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) - - `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 - - `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 + - `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, `camera_3d` (default false) is the 3D-voxel-map switch: true forces Grid/Sensor=2 + Grid/3D=true + height-threshold ground split + - `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) - 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. `/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): `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` - 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 - 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). - 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. -- 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 @@ -70,7 +71,7 @@ Use this file for verified target-repository facts only. Keep unknown values as - Model formats: N/A - 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). -- 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). ## Commands @@ -94,17 +95,20 @@ All commands below are transcribed from README.md / CMakePresets.json / docs — ## 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 -- 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: 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). 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). 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. 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). + 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 voxel map (`camera_3d: true`) has NOT been run on hardware yet. Three numbers in it are reasoned estimates, not measurements: `voxel.emit_size_m` 0.10, `voxel.delta_max_ratio` 0.35, and the 150k `max_cells` ceiling. 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). diff --git a/README.md b/README.md index c5e7f3f..3b317ff 100644 --- a/README.md +++ b/README.md @@ -192,20 +192,28 @@ source tools/dev_env.sh export VSLAM_CONFIG_DIR=$PWD/configuration_files export VSLAM_RESOURCE_DIR=$PWD/resources -DB=~/maps/hospital_$(date +%Y%m%d_%H%M).db -mkdir -p ~/maps - ./build/app/vslam_node --sim --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world \ --x 1.03 --y -25.07 --max-speed 1.5 \ - --slam --slam-db "$DB" --slam-mode mapping --token t \ + --slam --slam-db "hospital_{stamp}.db" --slam-mode mapping --token t \ 2>&1 | tee /tmp/quet_map.log ``` -Duong dan DB mang **dau thoi gian**, khong phai cho dep: moi lan quet BAT BUOC -la mot file moi -- xem canh bao ben duoi. +Duong dan DB o day la **tuong doi** va co **`{stamp}`**, ca hai deu co ly do: + +- Tuong doi -> giai theo `MapDir()` = `$VSLAM_RESOURCE_DIR/maps`, tuc ban do + nam trong chinh project o `resources/maps/` (da nam san trong `.gitignore`). + Thu muc cha duoc tao neu chua co. Duong dan tuyet doi van dung nguyen. +- `{stamp}` -> no ra `%Y%m%d_%H%M%S` luc khoi dong. Moi lan quet BAT BUOC la + mot file moi (xem canh bao ben duoi), va day la cach khong phai nho. + +Dong dau tien trong log noi ro no da giai ra duong dan nao: + +``` +slam: database_path "hospital_{stamp}.db" -> /home/.../resources/maps/hospital_20260923_103347.db +``` Mo **http://localhost:8080/?token=t**, bam **chia doi**, lai het khu vuc roi -**Ctrl-C**. Ban do duoc luu vao `$DB` luc thoat. +**Ctrl-C**. Ban do duoc luu luc thoat, vao dung duong dan in o dong tren. Khung trai cho biet ban dang o dau trong toa nha; khung phai cho biet SLAM da dung duoc bao nhieu. Cho nao khung phai con trong la cho chua quet. @@ -222,6 +230,10 @@ CHECK sai so vs ground truth 0.008 m (lon nhat 0.018) map_correction 0.011 m Dong thu ba phai **tang dan** khi lai. Dung yen o `0 bi chiem, 0 trong` nghia la SLAM khong nap duoc gi. +⚠️ Bon con so tren do voi `camera_3d: false` (mac dinh). Bat ban do 3D len +thi `Grid/Sensor` thanh 2 va camera bat dau nap vat can vao luoi -- so o bi +chiem se KHAC, va cao hon. Do lai truoc khi dung chung lam nguong. + Dong thu tu (5 giay mot lan, tim bang `grep CHECK`) mang ba so: sai so uoc luong so voi vi tri THAT, do lon phep nan cua SLAM, va so lan phat hien KE CAN. `ke can` phai TANG khi ban lai qua cho da di -- do la co che duy nhat cat duoc @@ -484,6 +496,43 @@ va thu tu uu tien ba nguon nhap (manual > joystick > phim) deu nam trong C++. goc** (`test/gen_teleop_vectors.py`), sai lech < 1e-9 -- do la cach duy nhat kiem duoc loi hua "logic giu NGUYEN VEN" cua ban port. +## Ban do 3D tren web + +MAC DINH TAT. Bat bang `camera_3d: true` trong `slam.yaml`, roi mo web, bam +**3D** va tick lop **voxel 3D**. + +Bat no len keo theo ba thu, tu dong: + +| | | +|---|---| +| `Grid/Sensor = 2` | RTAB-Map nap CA scan LiDAR lan depth vao luoi cuc bo | +| `Grid/3D = true` | luoi cuc bo cua tung node thanh ba chieu | +| nguong chieu cao | tach san/vat can bang 0.10 m va 2.0 m, khong bang phap tuyen (re hon nhieu, du cho robot 2.5D nay) | + +Ban do 3D duoc **dung lai tu dau** tu cac pose DA TOI UU moi lan do thi doi, +nen sau mot vong dong no tu nan theo -- khong co buoc "sua ban do" rieng nao. +Doi lai, luc do gan nhu moi voxel doi chi so, va server tu chuyen tu gui delta +sang gui lai ca tap (`voxel.delta_max_ratio`). + +Ba dieu can biet truoc khi bat: + +1. **No doi ca luoi 2D.** Vat can thap ma LiDAR khong thay (ban, bac thang) + tu nay hien tren ban do 2D. Do la y muon, nhung con so trong muc "dau hieu + chay dung" o tren se khac. +2. **Ton them RAM/CPU tren Jetson.** Ban xuat voxel chay CUNG ngan sach duty + 25% voi ban xuat luoi 2D (khong phai them mot ngan sach thu hai), nen no tu + gian nhip ra khi do thi lon -- nhung tong cong viec thi nhieu hon. +3. **Phai KHOP voi luc quet.** Mo ban do voxel tren mot DB quet phang chi ra + MOT lop ngang o cao do LiDAR. Node canh bao khi lech. + +Kiem nhanh ma khong phai mo khung 3D: khung JSON cua WebSocket mang ba truong +`slam.voxels_source` (`scan+depth` | `scan` | `off`), `slam.voxel_cells` va +`slam.voxel_epoch`. (KHONG phai `/api/status` -- endpoint do chi tra thong ke +cua web server: so client, frames_sent, frames_dropped.) + +`voxels_source: "scan"` trong khi ban tuong minh dang co depth nghia la camera +khong toi duoc SLAM. Do la cho can nhin dau tien, truoc khi nghi ban do hong. + ## Dieu khien bang tay cam Port 1-1 tu `base_kit/src/joy_control` -- Logitech F710/F310 o mode XInput. diff --git a/app/src/app_config.cc b/app/src/app_config.cc index f11d64f..d7e12a5 100644 --- a/app/src/app_config.cc +++ b/app/src/app_config.cc @@ -561,6 +561,38 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) { return StatusResponse::Error(StatusCode::kInvalidArgument, 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"}); + if (!r.ok()) return r; + + out->voxel.emit_size_m = v.get("emit_size_m", out->voxel.emit_size_m); + out->voxel.z_min = v.get("z_min", out->voxel.z_min); + out->voxel.z_max = v.get("z_max", out->voxel.z_max); + out->voxel.max_cells = static_cast( + v.get("max_cells", static_cast(out->voxel.max_cells))); + out->voxel.delta_max_ratio = + v.get("delta_max_ratio", out->voxel.delta_max_ratio); + + 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"); + } + } } #endif @@ -582,7 +614,8 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) { Reject(w, "system.yaml web", {"port", "bind", "auth_token", "asset_dir", "status_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; } out->web.port = static_cast(w.get("port", 8080)); @@ -597,6 +630,11 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) { static_cast(w.get("cloud_max_points", 4000)); out->slam_runtime.map_rebuild_rate_hz = w.get("map_rebuild_rate_hz", out->slam_runtime.map_rebuild_rate_hz); + out->web.voxel_chunk_bytes = static_cast( + w.get("voxel_chunk_bytes", static_cast(out->web.voxel_chunk_bytes))); + out->web.voxel_sync_chunks_per_tick = static_cast(w.get( + "voxel_sync_chunks_per_tick", + static_cast(out->web.voxel_sync_chunks_per_tick))); if (out->web.auth_token.empty()) { // Khong tu choi khoi dong: mot robot trong phong lab khong can token. diff --git a/app/src/app_config.h b/app/src/app_config.h index fe56ae1..a561522 100644 --- a/app/src/app_config.h +++ b/app/src/app_config.h @@ -47,6 +47,18 @@ struct SlamRuntimeConfig { 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; +}; + struct ThreadConfig { int safety_priority = 50; int driver_priority = 45; @@ -107,6 +119,7 @@ struct AppConfig { GamepadConfig gamepad; // system.yaml ThreadConfig threads; SlamRuntimeConfig slam_runtime; + VoxelConfig voxel; RecordConfig record; std::string log_level = "info"; diff --git a/app/src/runtime.cc b/app/src/runtime.cc index 295fcaf..791f18d 100644 --- a/app/src/runtime.cc +++ b/app/src/runtime.cc @@ -3,10 +3,12 @@ #include #include +#include #include #include #include +#include "vslam/binary_codec.h" #include "vslam/clock.h" #include "vslam/geometry.h" #include "vslam/log.h" @@ -361,6 +363,18 @@ StatusResponse Runtime::Start() { slam_enabled_ = true; slam_mode_ = sc.mode; + // Latch depth chi bat khi CO yeu cau ban do 3D. Tat thi duong nay khong + // ton mot lan copy con tro nao tren luong camera. + slam_use_depth_ = sc.camera_3d; + voxel_enabled_ = sc.camera_3d; + if (slam_use_depth_ && camera_ == nullptr) { + // KHONG tu choi: `--live` cho phep thieu camera co y (xem OpenSource). + // Ban do voxel khi do chi co mot lop ngang o cao do LiDAR -- kem, nhung + // van la mot ban do, va nguoi van hanh phai biet tai sao. + VSLAM_WARN("slam: camera_3d=true nhung khong co camera -- ban do 3D se " + "chi co mot lop ngang o cao do LiDAR."); + } + // Chi LUU o che do mapping va khi co duong dan that. // // ⚠️ `RtabmapSlam::~RtabmapSlam()` goi `Close(false)` -- VUT BO ban do. @@ -369,10 +383,12 @@ StatusResponse Runtime::Start() { // // O che do localization thi KHONG luu: ghi phien dinh vi vao ban do da // quet se lam ban do phinh dan moi lan chay, va khong ai co y do do. + // `slam_->database_path()` chu khong phai `sc.database_path`: Init() da + // giai tuong doi va no {stamp}, nen day moi la file that se duoc ghi. slam_should_save_ = - (sc.mode == SlamMode::kMapping) && !sc.database_path.empty(); + (sc.mode == SlamMode::kMapping) && !slam_->database_path().empty(); if (slam_should_save_) { - VSLAM_INFO("slam: che do mapping, se LUU vao " << sc.database_path + VSLAM_INFO("slam: che do mapping, se LUU vao " << slam_->database_path() << " khi thoat (Ctrl-C)."); } else if (sc.mode == SlamMode::kMapping) { VSLAM_WARN("slam: che do mapping nhung database_path de RONG -- ban do " @@ -889,6 +905,9 @@ void Runtime::SlamLoop() { // TAI THAT chu khong theo mot hang so -- xem khoi ben duoi. double map_export_cost_s_ = 0.0; constexpr double kMapExportDuty = 0.25; // toi da 25% luong slam + // Do lech stamp toi da con coi scan va depth la cung mot thoi diem. Bang + // mac dinh cua ApproxTimeSync; xem cho ghep ben duoi. + constexpr double kSlamDepthSlopSec = 0.05; auto last_map_build = std::chrono::steady_clock::time_point{}; while (!stop_.load()) { @@ -932,10 +951,36 @@ void Runtime::SlamLoop() { last_used = scan->header.stamp; have_last = true; + // --- Ghep depth gan nhat voi scan nay --- + // + // ⚠️ Ba shared_ptr duoi day PHAI con song qua `Process()`: + // `BuildSensorData` boc `cv::Mat` QUANH `Image::data` ma khong copy + // (sensor_data_builder.cc), va `rtabmap::SensorData` giu chinh cv::Mat do. + // Dung tach doan nay thanh mot helper tra ve con tro tho. + ImagePtr depth, infra1; + std::shared_ptr depth_info; + if (slam_use_depth_) { + std::lock_guard lk(depth_mu_); + // 50 ms = mac dinh cua ApproxTimeSync. Scan 25 Hz (40 ms) va depth 30 Hz + // (33 ms) nen latch khong bao gio cu hon mot khung -- nguong nay khop + // gan nhu moi vong, va khi no KHONG khop thi bo depth la dung: mot + // khung depth lac thoi diem lam ban do 3D nhoe ra. + if (have_depth_ && + std::fabs(SecondsBetween(scan->header.stamp, latest_depth_stamp_)) <= + kSlamDepthSlopSec) { + depth = latest_depth_; + infra1 = latest_infra1_; + depth_info = latest_depth_info_; + } + } + SlamInput in; in.stamp = scan->header.stamp; in.odom = odom; in.scan = scan.get(); + in.depth = depth.get(); + in.depth_info = depth_info.get(); + in.infra1 = infra1.get(); // --- KHONG MOT MUTEX NAO duoc giu qua dong nay --- const SlamOutput out = slam_->Process(in); @@ -1037,6 +1082,67 @@ void Runtime::SlamLoop() { } // Loi o day khong phai chuyen la: do thi co the chua co pose toi uu nao // o nhung khung dau. Khong log moi lan de khong lap day log. + + // ---- Ban do voxel 3D ---- + // + // Di CHUNG nhip voi luoi 2D: cung mot tin hieu (`map_version` doi), va + // quan trong hon, cung MOT ngan sach duty 25%. Hai ngan sach 25% doc lap + // deu ton trong "25%" ma cong lai la 50% luong slam trong truong hop + // xau -- chi phi cua ca hai lan xuat cong vao cung mot EWMA. + if (voxel_enabled_) { + VoxelExportOptions vo; + vo.emit_size_m = cfg_->voxel.emit_size_m; + vo.z_min = cfg_->voxel.z_min; + vo.z_max = cfg_->voxel.z_max; + vo.max_cells = cfg_->voxel.max_cells; + + VoxelGrid vg; + const auto t_vox = std::chrono::steady_clock::now(); + const StatusResponse vst = slam_->ExportVoxels(vo, &vg); + const double vcost = + std::chrono::duration(std::chrono::steady_clock::now() - t_vox) + .count(); + map_export_cost_s_ = 0.7 * map_export_cost_s_ + 0.3 * (cost + vcost); + + if (vst.ok()) { + std::vector added, removed; + DiffVoxelGrids(prev_voxel_cells_, vg.cells, &added, &removed); + + // Gui lai CA TAP khi phan doi qua lon. Sau mot lan toi uu do thi + // (dong vong) thi gan nhu moi o doi chi so, va khi do delta con to + // hon chinh ban do. Nguong tu phat hien ra dieu do -- khong dua vao + // `loop_closure_id`, vi ke can no lien tuc ma phan lon khong lam do + // thi dich di bao nhieu. + const size_t total = std::max(vg.cells.size(), 1); + const double change = + static_cast(added.size() + removed.size()) / + static_cast(total); + const bool full_resync = + prev_voxel_cells_.empty() || change > cfg_->voxel.delta_max_ratio; + + std::shared_ptr delta_buf; + if (full_resync) { + // Epoch moi: moi khung delta dang cho deu vo nghia, va client se + // duoc bom lai ca tap. + ++voxel_epoch_; + voxel_seq_ = 0; + } else if (!added.empty() || !removed.empty()) { + auto buf = std::make_shared(); + EncodeVoxelDelta(voxel_epoch_, ++voxel_seq_, added, removed, + clock_->Now(), buf.get()); + delta_buf = buf; + } + vg.epoch = voxel_epoch_; + + prev_voxel_cells_ = vg.cells; + auto vptr = std::make_shared(std::move(vg)); + { + std::lock_guard lk(slam_mu_); + slam_voxels_ = vptr; + slam_voxel_delta_ = delta_buf; + } + } + } } } #endif @@ -1184,6 +1290,21 @@ void Runtime::WebLoop() { // Khong co SLAM thi map_correction la dong nhat, tuc map == odom -- va // noi ro dieu do tren web (`slam.mode = "off"`) thay vi de nguoi xem // tuong dang nhin mot pose da duoc SLAM sua. + // Nguon THAT SU cua ban do 3D, khong phai y dinh. Mot ban do 3D dung tu + // scan trong khi nguoi dung tuong minh dang co depth la kieu hong im lang + // nhat o day. + // + // ⚠️ Doc `depth_mu_` TRUOC khi vao `slam_mu_`, khong long hai lock vao + // nhau: vong an toan khong dinh toi cho nay, nhung mot thu tu lock long + // nhau la thu chi phat hien duoc khi no da khoa that. +#ifdef VSLAM_HAVE_SLAM + const char* voxels_source = "off"; + if (voxel_enabled_) { + std::lock_guard dlk(depth_mu_); + voxels_source = have_depth_ ? "scan+depth" : "scan"; + } +#endif + { std::lock_guard lk(slam_mu_); if (slam_map_version_ > 0) { @@ -1195,6 +1316,20 @@ void Runtime::WebLoop() { snap.slam.process_ms = slam_process_ms_; #ifdef VSLAM_HAVE_SLAM snap.slam.mode = SlamModeName(slam_mode_); + snap.voxels = slam_voxels_; + // Delta TIEU THU DUNG MOT LAN. + // + // ⚠️ De no nam lai thi Publish() gui cung mot khung o moi tick: + // client thay so thu tu lap lai -> tuong hut khung -> xin dong bo lai + // moi giay, mai mai. `prev_voxel_cells_` o luong slam da tien len roi, + // nen khung nay chi dung DUNG mot lan. + snap.voxel_delta = slam_voxel_delta_; + slam_voxel_delta_.reset(); + if (slam_voxels_) { + snap.slam.voxel_cells = static_cast(slam_voxels_->cells.size()); + snap.slam.voxel_epoch = slam_voxels_->epoch; + } + snap.slam.voxels_source = voxels_source; #endif if (slam_map_) snap.map = slam_map_; } else { diff --git a/app/src/runtime.h b/app/src/runtime.h index 8900cf2..e441e36 100644 --- a/app/src/runtime.h +++ b/app/src/runtime.h @@ -49,6 +49,7 @@ #ifdef VSLAM_HAVE_SLAM #include "vslam/rtabmap_slam.h" +#include "vslam/voxel_export.h" #endif namespace vslam { @@ -192,6 +193,24 @@ class Runtime { bool have_cliff_ = false; 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 latest_depth_info_; + UnixTime latest_depth_stamp_; + bool have_depth_ = false; + // mcu_mu_: sieu am va bumper. // // Hai cam bien nay o tren MCU vi ca hai deu la cam bien MUC THAP phai toi @@ -252,9 +271,30 @@ class Runtime { int slam_prox_id_ = 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 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 prev_voxel_cells_; + uint32_t voxel_epoch_ = 0; + uint32_t voxel_seq_ = 0; +#endif + // Doc-only sau Start(), nen khong can mutex. bool slam_enabled_ = 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. double speed_limit_ = 0.35; // Gia toc thuc su dung. Bang robot.yaml, TRU khi `--max-speed` noi tran -- diff --git a/app/src/wiring.cc b/app/src/wiring.cc index 497f6e3..e89d03f 100644 --- a/app/src/wiring.cc +++ b/app/src/wiring.cc @@ -197,6 +197,30 @@ StatusResponse Runtime::Wire() { if (camera_ != nullptr) { camera_->SetCallback([this](const CameraFrame& f) { 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 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(f.depth_info); + latest_depth_stamp_ = f.header.stamp; + have_depth_ = true; + } + // Ca chuoi perception chay INLINE o day: depth -> cloud -> loc -> // can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong // camera. diff --git a/configuration_files/sensors.yaml b/configuration_files/sensors.yaml index f5b1926..93c73fb 100644 --- a/configuration_files/sensors.yaml +++ b/configuration_files/sensors.yaml @@ -222,19 +222,28 @@ mcu: # 4. Lan nay log PHAI bao ~0 ms. Neu van bao XX thi mo hinh tre sai, dung # tang dai -- doc lai truoc. # - # --- 0.08: DO DUOC, khong phai chinh tay --- - # May do bao 80 ms sau tam lan lien tiep (mau 3500 -> 6500) trong luc lai vao - # ra cua. Dat vao day roi chay lai thi no bao 0 ms -- phep tu kiem chung. + # --- 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 # - # 80 ms do KHONG nam o phia host, nen firmware dong dau som cach may cung + # 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. - imu_lag_sec: 0.08 + imu_lag_sec: 0.07 # Ban ghi encoder `E,,,` la MO RONG moi -- giao # thuc cu chi co I/B/P. @@ -268,11 +277,18 @@ base: # 0 = dung mac dinh 16384, suy tu 0x200E:01 = 4096 "wire" doc duoc tren # 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 - # "wire" va "count". Sai he so nay lam odometry sai dung 4 lan. + # He so x4: DA KIEM CHUNG tren robot that 2026-09-23 (khong phai bang + # 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 - # vong bang tay, doc lai. Hieu so chinh la count/vong that -- dat vao day. + # Bang chung: dong `wheel_odom/dbg` trong mot phien lai 3.5 phut cho + # 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 # candump can0,581:7FF -n 1 # diff --git a/configuration_files/slam.yaml b/configuration_files/slam.yaml index c5a35de..8640055 100644 --- a/configuration_files/slam.yaml +++ b/configuration_files/slam.yaml @@ -21,9 +21,20 @@ mode: localization # Bat buoc (require<>): khong co mac dinh. Mot mac dinh im lang se ghi ban do # vao cho khong ai tim thay. # +# Duong dan TUONG DOI duoc giai theo MapDir() = $VSLAM_RESOURCE_DIR/maps, tuc +# `/resources/maps/` khi chay tu cay nguon va +# /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, # 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 ============ # "0"=TORO "1"=g2o "2"=GTSAM "3"=Ceres @@ -49,8 +60,60 @@ optimizer_strategy: "1" # 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. visual_loop: false + +# Cong tac cua BAN DO VOXEL 3D tren web UI. +# +# Bat len keo theo ba thu, tu dong, khong sua tay trong khoi `rtabmap:` ben +# duoi (xem BuildRtabmapParams): +# Grid/Sensor = 2 scan + depth (truoc do chi scan) +# Grid/3D = true luoi cuc bo cua moi node thanh 3 chieu +# tach san/vat can bang nguong chieu cao (0.10 m san, 2.0 m tran) thay vi +# bang phap tuyen -- re hon nhieu va du cho robot 2.5D nay +# +# ⚠️ Doi CA noi dung luoi 2D: vat can thap ma LiDAR khong thay (ban, bac +# thang) tu nay hien tren ban do. Do la y muon, nhung no la mot thay doi that. +# +# ⚠️ Ton them RAM va CPU tren Jetson: moi node luu them o 3D, va ban xuat +# voxel chay cung ngan sach duty 25% voi ban xuat luoi 2D. +# +# ⚠️ Phai KHOP voi luc quet: mo ban do voxel tren mot DB quet phang chi ra +# mot lop ngang o cao do LiDAR. Init() canh bao khi lech. camera_3d: false +# ============ 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, doc lap voi Grid/CellSize (0.05) cua SLAM. Lam tho them + # mot bac cat so voxel di 8 lan (the tich) ma mat rat it hinh dang o muc + # "co cai ban o day". + emit_size_m: 0.10 + + # 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 cung. Cham tran thi ban do bi CAT BOT va co `truncated` bat len -- + # tinh ra o log va o /api/status, khong nuot im. + # + # Uoc luong: mot tang 30x30 m, tuong cao 2 m, o 0.10 m, chi be mat, la + # ~24k voxel; phong that co do dac vao khoang 40-80k. 150k la cho thua. + max_cells: 150000 + + # (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 + # ============ KHOI RTAB-MAP ============ # Ghi de len mac dinh cua du an (xem BuildRtabmapParams). De trong thi dung # mac dinh -- do la lua chon dung cho hau het truong hop. diff --git a/configuration_files/system.yaml b/configuration_files/system.yaml index 465bdd0..e9b5a0f 100644 --- a/configuration_files/system.yaml +++ b/configuration_files/system.yaml @@ -66,6 +66,25 @@ web: # Mot tan so CO DINH sai o ca hai dau. 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. 16 kB = 2722 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. 1 manh x 16 kB x 10 Hz = 160 kB/s. + # Mot ban do 60k o = 23 manh = 2.3 giay. + # Tuc la trong 2.3 giay dau cua MOI client moi vao, ngan sach bi vuot. Khung + # cloud drop duoc nen chung hap thu phan chenh. Muon em hon thi ha + # voxel_chunk_bytes, doi lai dong bo lau hon. + voxel_chunk_bytes: 16384 + voxel_sync_chunks_per_tick: 1 + # ============ 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. diff --git a/libs/vslam_common/include/vslam/node_constants.h b/libs/vslam_common/include/vslam/node_constants.h index 0004a9a..079dbb0 100644 --- a/libs/vslam_common/include/vslam/node_constants.h +++ b/libs/vslam_common/include/vslam/node_constants.h @@ -15,6 +15,9 @@ #include +#include "vslam/vslam_common.h" // StatusResponse. Khong vong: + // vslam_common.h chi keo unix_time.h + namespace vslam { // --- Duong dan mac dinh ---------------------------------------------------- @@ -93,6 +96,30 @@ std::string RecordDir(); // map_hospital.db ma khong phai copy 3.8 GB. 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 : tren GCC 9 (xem +// CMakeLists.txt:76-88) can link them -lstdc++fs, ma vslam_common +// la dep cua MOI target trong cay nay. +StatusResponse EnsureParentDir(const std::string& path); + } // namespace vslam #endif // VSLAM_NODE_CONSTANTS_H diff --git a/libs/vslam_common/include/vslam/vslam_common.h b/libs/vslam_common/include/vslam/vslam_common.h index 4294fe3..793428f 100644 --- a/libs/vslam_common/include/vslam/vslam_common.h +++ b/libs/vslam_common/include/vslam/vslam_common.h @@ -151,6 +151,46 @@ struct OccupancyGrid { std::vector 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` 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 cells; // DA SAP XEP theo khoa goi, khong trung +}; + +using VoxelGridPtr = std::shared_ptr; + // --------------------------------------------------------------------------- // sensor_msgs // --------------------------------------------------------------------------- diff --git a/libs/vslam_common/src/node_constants.cc b/libs/vslam_common/src/node_constants.cc index 2fe313a..edba69a 100644 --- a/libs/vslam_common/src/node_constants.cc +++ b/libs/vslam_common/src/node_constants.cc @@ -1,6 +1,11 @@ #include "vslam/node_constants.h" +#include + +#include #include +#include +#include namespace vslam { namespace { @@ -18,6 +23,19 @@ std::string Join(const std::string& dir, const std::string& 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 std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); } @@ -40,4 +58,58 @@ std::string CorpusDir() { 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 diff --git a/libs/vslam_slam/CMakeLists.txt b/libs/vslam_slam/CMakeLists.txt index 690e4c9..0b3bdc4 100644 --- a/libs/vslam_slam/CMakeLists.txt +++ b/libs/vslam_slam/CMakeLists.txt @@ -15,6 +15,7 @@ vslam_add_library(vslam_slam rtabmap_slam.h sensor_data_builder.h occupancy_export.h + voxel_export.h FIND_DEPS vslam_common RTABMap diff --git a/libs/vslam_slam/include/vslam/occupancy_export.h b/libs/vslam_slam/include/vslam/occupancy_export.h index fc62fb9..5963cd8 100644 --- a/libs/vslam_slam/include/vslam/occupancy_export.h +++ b/libs/vslam_slam/include/vslam/occupancy_export.h @@ -26,6 +26,11 @@ struct DbFacts { int nodes = 0; 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 + + // 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); diff --git a/libs/vslam_slam/include/vslam/rtabmap_slam.h b/libs/vslam_slam/include/vslam/rtabmap_slam.h index 438a3a0..08efe51 100644 --- a/libs/vslam_slam/include/vslam/rtabmap_slam.h +++ b/libs/vslam_slam/include/vslam/rtabmap_slam.h @@ -23,6 +23,7 @@ #include "vslam/rtabmap_params.h" #include "vslam/slam_types.h" +#include "vslam/voxel_export.h" #include "vslam/vslam_common.h" namespace vslam { @@ -75,11 +76,22 @@ class RtabmapSlam { // Xuat occupancy grid hien tai. Dat, goi khi map_version doi. 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); + StatusResponse Close(bool save_database); const SlamStats& stats() 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; + private: std::unique_ptr impl_; }; diff --git a/libs/vslam_slam/include/vslam/voxel_export.h b/libs/vslam_slam/include/vslam/voxel_export.h new file mode 100644 index 0000000..d18002e --- /dev/null +++ b/libs/vslam_slam/include/vslam/voxel_export.h @@ -0,0 +1,100 @@ +#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 phai lay o BI CHIEM o he cuc bo cua tung node roi +// tu bien doi bang pose DA TOI UU. +// +// ⚠️ 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 gridObstacleCellsRaw(). +// 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 +#include +#include + +#include "vslam/vslam_common.h" + +namespace rtabmap { +class Rtabmap; +} + +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 cung. Cham tran thi cat bot va bat `truncated` chu khong am tham + // nuot: mot ban do 3D thieu mot nua trong im lang la kieu hong te nhat. + 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; +}; + +// 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_; } + + private: + void Flush(); + + VoxelExportOptions opt_; + double inv_size_ = 10.0; + std::vector scratch_; + std::vector acc_; // luon o trang thai da sort+unique + size_t clamped_ = 0; + size_t z_rejected_ = 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, VoxelGrid* out); + +// 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& prev, + const std::vector& now, + std::vector* added, + std::vector* removed); + +} // namespace vslam + +#endif // VSLAM_VOXEL_EXPORT_H diff --git a/libs/vslam_slam/src/occupancy_export.cc b/libs/vslam_slam/src/occupancy_export.cc index 7c3c729..c8036c7 100644 --- a/libs/vslam_slam/src/occupancy_export.cc +++ b/libs/vslam_slam/src/occupancy_export.cc @@ -106,6 +106,12 @@ DbFacts InspectDatabase(const std::string& path) { auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy()); 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); return f; } diff --git a/libs/vslam_slam/src/rtabmap_params.cc b/libs/vslam_slam/src/rtabmap_params.cc index 9359454..171dad8 100644 --- a/libs/vslam_slam/src/rtabmap_params.cc +++ b/libs/vslam_slam/src/rtabmap_params.cc @@ -116,6 +116,42 @@ std::map BuildRtabmapParams( // Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh. out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1"; + // --- camera_3d: luoi cuc bo 3D de dung ban do voxel cho web --- + // + // Nam o muc 3 chu khong o `project_defaults`: slam.yaml dat THANG + // `Grid/Sensor: "0"` va `Grid/3D: "false"`, ma muc 2 (YAML) ghi de len muc + // 1. De o day thi ba key nay la HE QUA cua co, dung nhu Mem/IncrementalMemory + // la he qua cua mode. + if (cfg.camera_3d) { + // 0=scan 1=depth 2=ca hai. Can "2": LiDAR van la trong tai cho ICP, con + // depth la thu duy nhat co chieu cao. + out["Grid/Sensor"] = "2"; + out["Grid/3D"] = "true"; + + // Tach san/vat can bang NGUONG CHIEU CAO, khong bang phap tuyen. + // NormalsSegmentation mac dinh true va la duong DAT: no uoc luong phap + // tuyen (Grid/NormalK = 20 lang gieng) cho moi diem, moi khung. Robot nay + // la 2.5D (Reg/Force3DoF), san phang, nen mot nguong chieu cao la du. + // RTAB-Map cung noi thang: MaxGroundHeight "should be set if + // NormalsSegmentation is false". + out["Grid/NormalsSegmentation"] = "false"; + out["Grid/MaxGroundHeight"] = "0.10"; // duoi nguong = san + out["Grid/MaxObstacleHeight"] = "2.0"; // tren nguong = tran, vut di + + // ⚠️ Grid/RayTracing GIU NGUYEN "true" (mac dinh cua du an), khong tat. + // + // Tat no re hon that -- voi Grid/3D=true, ray tracing dien o KHONG GIAN + // chu khong phai mat phang, va ban do voxel chi doc o BI CHIEM nen o + // trong la chi phi thuan. Nhung no cung chinh la thu sinh ra o "trong" + // cua luoi 2D: do tren robot that 2026-09-23, mot phien 3.5 phut cho + // 84961 o trong / 5049 o bi chiem. Tat di thi khung ban do tren web gan + // nhu chi con mau "chua biet". + // + // Muon danh doi nguoc lai thi dat `Grid/RayTracing: "false"` trong khoi + // `rtabmap:` cua slam.yaml -- do la viec cua nguoi van hanh, khong phai + // mot he qua am tham cua camera_3d. + } + // Optimizer: dat TUONG MINH, luon luon. // // DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson diff --git a/libs/vslam_slam/src/rtabmap_slam.cc b/libs/vslam_slam/src/rtabmap_slam.cc index f912260..aa4e7c6 100644 --- a/libs/vslam_slam/src/rtabmap_slam.cc +++ b/libs/vslam_slam/src/rtabmap_slam.cc @@ -12,6 +12,7 @@ #include "vslam/geometry.h" #include "vslam/log.h" +#include "vslam/node_constants.h" #include "vslam/occupancy_export.h" #include "vslam/sensor_data_builder.h" @@ -69,6 +70,10 @@ void RtabmapSlam::SetExtrinsics(const Transform& laser_to_base, SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; } const SlamStats& RtabmapSlam::stats() const { return impl_->stats; } +const std::string& RtabmapSlam::database_path() const { + return impl_->cfg.database_path; +} + Pose2D RtabmapSlam::map_correction() const { std::lock_guard lk(impl_->out_mu); return impl_->map_correction; @@ -88,6 +93,27 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { } impl_->cfg = cfg; + // --- 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; // thong tin can thiet da co trong SlamOutput va stats. ULogger::setType(ULogger::kTypeNoLog); @@ -113,14 +139,14 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { return StatusResponse::Error(StatusCode::kInvalidArgument, msg); } - const DbFacts facts = InspectDatabase(cfg.database_path); + const DbFacts facts = InspectDatabase(db_path); if (cfg.mode == SlamMode::kLocalization) { // 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 // map->odom luon bang 0, trong nhu "SLAM dang chay tot". // // Duong dan rong = DB trong RAM = chac chan khong co ban do. - if (cfg.database_path.empty()) { + if (db_path.empty()) { return StatusResponse::Error( StatusCode::kFailedPrecondition, "che do localization nhung database_path de rong (DB trong RAM). " @@ -129,7 +155,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { if (!facts.exists || facts.nodes == 0) { return StatusResponse::Error( 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) { @@ -141,6 +167,11 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { "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."); } + if (cfg.camera_3d && facts.exists && !facts.grid_3d) { + VSLAM_WARN("slam: camera_3d=true nhung DB nay duoc quet voi Grid/3D=false " + "-- ban do voxel se chi co MOT lop ngang o cao do LiDAR. Quet " + "lai vao DB moi neu can ban do 3D that."); + } if (facts.exists && facts.optimizer_strategy != cfg.optimizer_strategy) { VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy << ", dang ep ve " << cfg.optimizer_strategy @@ -169,10 +200,19 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { " node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: " "Statistics.id' o MOI khung va khong dung duoc ban do nao.\n" " - Quet lai tu dau : --slam-db \n" + " - Dat ten tu dong : --slam-db \"map_{stamp}.db\"\n" " - Dung ban do nay : --slam-mode localization " "--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()); try { // loadDatabaseParameters = FALSE, luon luon. @@ -180,7 +220,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { // 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 // 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) { return StatusResponse::Error(StatusCode::kInternal, std::string("rtabmap init: ") + e.what()); @@ -205,7 +245,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) { impl_->map_version = 1; } 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 << " tu vung), optimizer " << cfg.optimizer_strategy); return StatusResponse::Ok(); @@ -307,6 +347,14 @@ StatusResponse RtabmapSlam::ExportMap(OccupancyGrid* out) { return ExportOccupancyGrid(impl_->rtabmap, out); } +StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt, + VoxelGrid* out) { + if (!impl_->inited) { + return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init"); + } + return ExportVoxelGrid(impl_->rtabmap, opt, out); +} + StatusResponse RtabmapSlam::Close(bool save_database) { if (!impl_->inited) return StatusResponse::Ok(); impl_->inited = false; diff --git a/libs/vslam_slam/src/voxel_export.cc b/libs/vslam_slam/src/voxel_export.cc new file mode 100644 index 0000000..ca8e467 --- /dev/null +++ b/libs/vslam_slam/src/voxel_export.cc @@ -0,0 +1,246 @@ +#include "vslam/voxel_export.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#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 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(static_cast(x + kIdxBias)) & 0x1FFFFFULL; + const uint64_t uy = static_cast(static_cast(y + kIdxBias)) & 0x1FFFFFULL; + const uint64_t uz = static_cast(static_cast(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((k >> 42) & 0x1FFFFFULL) - kIdxBias; + *y = static_cast((k >> 21) & 0x1FFFFFULL) - kIdxBias; + *z = static_cast(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); +} + +} // 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) { + if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) return; + if (z < opt_.z_min || z > opt_.z_max) { + ++z_rejected_; + return; + } + + 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) { + ++clamped_; + return; + } + const int32_t ix = static_cast(fx); + const int32_t iy = static_cast(fy); + const int32_t iz = static_cast(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)) { + ++clamped_; + return; + } + + scratch_.push_back(PackKey(ix, iy, iz)); + 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 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(opt_.emit_size_m); + out->origin_x = 0.0; + out->origin_y = 0.0; + out->origin_z = 0.0; + out->header.frame_id = kMapFrame; + out->truncated = acc_.size() > opt_.max_cells; + + const size_t n = std::min(acc_.size(), opt_.max_cells); + out->cells.clear(); + out->cells.reserve(n); + for (size_t i = 0; i < n; ++i) { + int32_t x = 0, y = 0, z = 0; + UnpackKey(acc_[i], &x, &y, &z); + VoxelIndex k; + k.x = static_cast(x); + k.y = static_cast(y); + k.z = static_cast(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. +} + +void DiffVoxelGrids(const std::vector& prev, + const std::vector& now, + std::vector* added, + std::vector* 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]); +} + +StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam, + const VoxelExportOptions& opt, VoxelGrid* out) { + const std::map& 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"); + } + + VoxelAccumulator acc(opt); + size_t nodes_with_grid = 0; + int channels_seen = 0; + + for (const auto& kv : poses) { + if (kv.second.isNull()) continue; + rtabmap::SensorData data = mem->getNodeData(kv.first, false, false, false, true); + // ⚠️ BAT BUOC. Thieu dong nay thi gridObstacleCellsRaw() tra ma tran RONG + // o moi node va ban do 3D im lang rong khong. + data.uncompressData(); + if (data.gridCellSize() <= 0.0f) continue; + + const cv::Mat& obs = data.gridObstacleCellsRaw(); + if (obs.empty()) continue; + if (obs.depth() != CV_32F) { + return StatusResponse::Error( + StatusCode::kInternal, + "o luoi cuc bo khong phai float32 (depth=" + + std::to_string(obs.depth()) + ") -- phien ban RTAB-Map la"); + } + + const int ch = obs.channels(); + if (ch < 2) { + return StatusResponse::Error( + StatusCode::kInternal, + "o luoi cuc bo co " + std::to_string(ch) + + " kenh, cho doi 2 (XY) hoac 3/4 (XYZ[+RGB])"); + } + if (channels_seen == 0) channels_seen = ch; + + // 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(); + + const int n = obs.cols * obs.rows; + const float* p = obs.ptr(); + for (int i = 0; i < n; ++i) { + const float px = p[0]; + const float py = p[1]; + // 2 kenh = luoi PHANG (DB quet voi Grid/3D=false). Van ve duoc, chi la + // ra mot lop ngang -- Init() da canh bao truong hop nay. + const float pz = (ch >= 3) ? p[2] : 0.0f; + p += ch; + + acc.AddPoint(r00 * px + r01 * py + r02 * pz + tx, + r10 * px + r11 * py + r12 * pz + ty, + r20 * px + r21 * py + r22 * pz + tz); + } + ++nodes_with_grid; + } + + if (nodes_with_grid == 0) { + return StatusResponse::Error( + StatusCode::kFailedPrecondition, + "khong node nao co luoi cuc bo -- RGBD/CreateOccupancyGrid tat, hoac " + "DB quet truoc khi bat camera_3d"); + } + + acc.Finish(out); + + // Mot dong, mot lan moi 30 giay: so kenh la thu duy nhat trong ca duong nay + // khong doc duoc tu header RTAB-Map, nen no phai hien ra o log that. + VSLAM_INFO_THROTTLE(30.0, "slam: voxel " << out->cells.size() << " o tu " + << nodes_with_grid << " node (" << channels_seen + << " kenh/o" << (out->truncated ? ", DA CAT BOT" : "") + << ")"); + if (acc.clamped() > 0) { + VSLAM_WARN_THROTTLE(30.0, "slam: " << acc.clamped() + << " diem ngoai dai chi so voxel -- bo qua"); + } + return StatusResponse::Ok(); +} + +} // namespace vslam diff --git a/libs/vslam_web/include/vslam/binary_codec.h b/libs/vslam_web/include/vslam/binary_codec.h index 591cd27..4139bed 100644 --- a/libs/vslam_web/include/vslam/binary_codec.h +++ b/libs/vslam_web/include/vslam/binary_codec.h @@ -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 // client. 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; @@ -72,10 +87,52 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, BinaryType type = BinaryType::kMapFull); -// Chi vung bao (bbox) cac o doi so voi `prev`. Tra false neu kich thuoc hai -// map khac nhau (khi do phai gui MAP_FULL) hoac khong co o nao doi. -bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev, - UnixTime stamp, std::string* out); +// (kMapPatch = 4 da bi BO. No noi duoc vao dau: cong per-session chi la mot +// atomic `acked_map_version_`, khong dien ta noi "session nay dang giu luoi +// NAO", va ban than no bail moi khi origin hay kich thuoc doi -- tuc gan nhu +// 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& added, + const std::vector& removed, UnixTime stamp, + std::string* out); // Thua hoa: chi giu diem cach diem truoc > min_step_m. void EncodePath(const std::vector& path, UnixTime stamp, double min_step_m, @@ -94,6 +151,21 @@ bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out); bool DecodeScan(const std::string& buf, LaserScan* out); bool DecodeMapFull(const std::string& buf, OccupancyGrid* out); +// 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* out); +bool DecodeVoxelDelta(const std::string& buf, uint32_t* epoch, uint32_t* seq, + std::vector* added, + std::vector* removed); + } // namespace vslam #endif // VSLAM_BINARY_CODEC_H diff --git a/libs/vslam_web/include/vslam/web_config.h b/libs/vslam_web/include/vslam/web_config.h index 43dfddd..5c60cef 100644 --- a/libs/vslam_web/include/vslam/web_config.h +++ b/libs/vslam_web/include/vslam/web_config.h @@ -31,11 +31,25 @@ struct WebConfig { double path_hz = 1.0; // 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 -------------------------------------------------- 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 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. // MAP khong bao gio bi drop -- thay vao do bat co map_pending. size_t max_queued_frames = 4; diff --git a/libs/vslam_web/include/vslam/web_snapshot.h b/libs/vslam_web/include/vslam/web_snapshot.h index 140b32f..b1cd5b7 100644 --- a/libs/vslam_web/include/vslam/web_snapshot.h +++ b/libs/vslam_web/include/vslam/web_snapshot.h @@ -45,6 +45,13 @@ struct SlamSnapshot { int proximity_total = 0; uint32_t map_version = 0; double process_ms = 0.0; + + // Ban do voxel 3D den tu dau: "scan+depth" | "scan" | "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; }; struct TeleopSnapshot { @@ -163,6 +170,17 @@ struct WebSnapshot { // that -- luc do khong co su that nao de doi chieu. OccupancyGridPtr world_map; std::vector 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 voxel_delta; }; } // namespace vslam diff --git a/libs/vslam_web/src/binary_codec.cc b/libs/vslam_web/src/binary_codec.cc index d2ff049..ac25a3f 100644 --- a/libs/vslam_web/src/binary_codec.cc +++ b/libs/vslam_web/src/binary_codec.cc @@ -171,66 +171,89 @@ void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, } } -bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev, - UnixTime stamp, std::string* out) { - // Kich thuoc doi -> khong vá duoc, phai gui full. - if (map.width != prev.width || map.height != prev.height || - map.data.size() != prev.data.size() || - std::abs(map.resolution - prev.resolution) > 1e-6f || - std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 || - std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) { - return false; +// --- Ban do voxel 3D ------------------------------------------------------- + +namespace { + +constexpr size_t kVoxelFullHeaderBytes = 32; // sau header chung 16 byte +constexpr size_t kVoxelCellBytes = 6; // i16 * 3 + +void PutCells(std::string* out, const VoxelIndex* cells, size_t n) { + 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. - int32_t x0 = static_cast(map.width); - int32_t y0 = static_cast(map.height); - int32_t x1 = -1, y1 = -1; - - for (uint32_t y = 0; y < map.height; ++y) { - const size_t row = static_cast(y) * map.width; - for (uint32_t x = 0; x < map.width; ++x) { - if (map.data[row + x] == prev.data[row + x]) continue; - const int32_t xi = static_cast(x); - const int32_t yi = static_cast(y); - if (xi < x0) x0 = xi; - 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 patch; - patch.reserve(static_cast(w) * static_cast(h)); - for (int32_t y = y0; y <= y1; ++y) { - const size_t row = static_cast(y) * map.width; - for (int32_t x = x0; x <= x1; ++x) { - patch.push_back(map.data[row + static_cast(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(runs); - for (int i = 0; i < 4; ++i) { - (*out)[run_count_off + static_cast(i)] = - static_cast((r32 >> (8 * i)) & 0xFF); +bool GetCells(const std::string& b, size_t off, size_t n, + std::vector* out) { + if (b.size() < off + n * kVoxelCellBytes) return false; + out->reserve(out->size() + n); + for (size_t i = 0; i < n; ++i) { + const size_t o = off + i * kVoxelCellBytes; + VoxelIndex k; + // Qua uint16 roi ep ve int16: ep thang tu char la noi dau am di lac. + k.x = static_cast(GetU16(b, o)); + k.y = static_cast(GetU16(b, o + 2)); + k.z = static_cast(GetU16(b, o + 4)); + out->push_back(k); } 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(std::min(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(grid.origin_x)); + PutF32(out, static_cast(grid.origin_y)); + PutF32(out, static_cast(grid.origin_z)); + PutU32(out, grid.epoch); + PutU32(out, static_cast(total)); + PutU16(out, chunk_index); + PutU16(out, chunk_count); + PutU32(out, static_cast(n)); + PutCells(out, grid.cells.data() + begin, n); +} + +void EncodeVoxelDelta(uint32_t epoch, uint32_t seq, + const std::vector& added, + const std::vector& removed, UnixTime stamp, + std::string* out) { + PutHeader(out, BinaryType::kVoxelDelta, stamp); + PutU32(out, epoch); + PutU32(out, seq); + PutU32(out, static_cast(added.size())); + PutU32(out, static_cast(removed.size())); + PutCells(out, added.data(), added.size()); + PutCells(out, removed.data(), removed.size()); +} + void EncodePath(const std::vector& path, UnixTime stamp, double min_step_m, std::string* out) { std::vector kept; @@ -332,4 +355,38 @@ bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) { return true; } +bool DecodeVoxelFull(const std::string& buf, VoxelChunkInfo* info, + std::vector* 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* added, + std::vector* 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(n_add) * 6, n_del, removed); +} + } // namespace vslam diff --git a/libs/vslam_web/src/json_writer.cc b/libs/vslam_web/src/json_writer.cc index 58c3283..35f18fd 100644 --- a/libs/vslam_web/src/json_writer.cc +++ b/libs/vslam_web/src/json_writer.cc @@ -188,7 +188,12 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) { Int("prox_id", s.slam.proximity_id, out); Comma(out); Int("prox_total", s.slam.proximity_total, out); Comma(out); Int("map_version", s.slam.map_version, out); Comma(out); - Num("process_ms", s.slam.process_ms, 1, out); + Num("process_ms", s.slam.process_ms, 1, out); Comma(out); + // Ban do 3D: nguon va so o. Mot ban do voxel RONG phai doc duoc tu day, chu + // khong phai bang cach mo khung 3D len roi doan. + Str("voxels_source", s.slam.voxels_source, out); Comma(out); + Int("voxel_cells", static_cast(s.slam.voxel_cells), out); Comma(out); + Int("voxel_epoch", static_cast(s.slam.voxel_epoch), out); out->push_back('}'); Comma(out); Key("teleop", out); diff --git a/libs/vslam_web/src/web_server.cc b/libs/vslam_web/src/web_server.cc index d50f670..556adf3 100644 --- a/libs/vslam_web/src/web_server.cc +++ b/libs/vslam_web/src/web_server.cc @@ -265,6 +265,20 @@ class WsSession : public std::enable_shared_from_this, void mark_world_map_sent() { world_map_sent_.store(true); } void set_acked_map_version(uint32_t v) { acked_map_version_.store(v); } + // --- Ban do voxel 3D --- + // `voxel_epoch_` = epoch client DA co du. 0 = chua co gi. + // `voxel_sync_from_` = da bom toi o thu may cua epoch dang dong bo. + uint32_t voxel_epoch() const { return voxel_epoch_.load(); } + void set_voxel_epoch(uint32_t v) { voxel_epoch_.store(v); } + bool voxel_resync() const { return voxel_resync_.load(); } + void set_voxel_resync(bool v) { voxel_resync_.store(v); } + uint32_t voxel_sync_epoch() const { return voxel_sync_epoch_.load(); } + size_t voxel_sync_from() const { return voxel_sync_from_.load(); } + void set_voxel_sync(uint32_t epoch, size_t from) { + voxel_sync_epoch_.store(epoch); + voxel_sync_from_.store(from); + } + void Close() override { auto self = shared_from_this(); asio::post(ws_.get_executor(), [self] { @@ -342,6 +356,23 @@ class WsSession : public std::enable_shared_from_this, } return; } + + // Client da rap du moi manh cua mot epoch voxel. + if (type == "ack_voxel") { + double v = 0.0; + if (JsonGetNumber(msg, "epoch", &v) && v >= 0.0) { + set_voxel_epoch(static_cast(v)); + set_voxel_resync(false); + } + return; + } + + // Client phat hien hut so thu tu delta hoac lech epoch -> xin ca tap. + if (type == "voxel_resync") { + set_voxel_resync(true); + set_voxel_epoch(0); + return; + } } void Enqueue(std::shared_ptr payload, bool is_binary, bool is_map) { @@ -401,6 +432,10 @@ class WsSession : public std::enable_shared_from_this, // Ban do the gioi la TINH trong mo phong -- gui mot lan la du, khong can // co che version/ACK nhu ban do SLAM. std::atomic world_map_sent_{false}; + std::atomic voxel_epoch_{0}; + std::atomic voxel_resync_{false}; + std::atomic voxel_sync_epoch_{0}; + std::atomic voxel_sync_from_{0}; }; // --------------------------------------------------------------------------- @@ -801,6 +836,81 @@ void WebServer::Publish(const WebSnapshot& snap) { s->set_acked_map_version(snap.slam.map_version); } } + + // --- BAN DO VOXEL 3D --- + // + // Hai duong, va chung KHONG doi xung: + // + // full-sync : client chua co epoch nay -> bom `voxel_sync_chunks_per_tick` + // manh moi lan Publish, cho toi het. KHONG danh dau is_map: + // `Enqueue` khong bao gio drop khung map, nen 23 manh voxel + // danh dau is_map se lam hang doi phinh vo han. Chung la + // khung THUONG, drop duoc; mat manh nao thi ACK khong bao gio + // toi va lan dong bo sau bat dau lai. + // + // delta : client dang giu dung epoch -> gui phan them/bot ngay khi co. + // Payload da duoc ma hoa san o luong slam va chi song MOT lan + // (WebLoop lay xong la xoa), nen khong co cong tan so nao o day. + if (snap.voxels) { + const uint32_t epoch = snap.voxels->epoch; + const size_t per = VoxelCellsPerChunk(impl_->cfg.voxel_chunk_bytes); + const uint16_t chunks = + VoxelChunkCount(*snap.voxels, impl_->cfg.voxel_chunk_bytes); + // KHONG gate theo tan so: delta chi sinh ra khi luong slam xuat ban do + // (<= map_rebuild_rate_hz, va da bi duty 25% ghim lai), nen nhip do CHINH + // la nhip tu nhien. Mot cong tan so o day chi co the LAM MAT khung. + + for (const auto& s : targets) { + const bool synced = !s->voxel_resync() && s->voxel_epoch() == epoch; + if (synced) { + // ⚠️ is_map=TRUE cho delta. Khong phai vi no la ban do 2D, ma vi + // `Enqueue` chi drop khung khong-map: mat mot delta la client giu mot + // ban do SAI vinh vien, y het mat mot khung MAP. Delta nho (vai tram + // byte) va toi da ~4 khung/giay nen giu chung lai la re. + if (snap.voxel_delta) s->Send(snap.voxel_delta, true, /*is_map=*/true); + continue; + } + + // Bat dau lai tu manh 0 khi epoch doi giua chung -- tron hai epoch la + // cach chac chan nhat de ra mot ban do sai ma khong ai biet. + size_t from = s->voxel_sync_from(); + if (s->voxel_sync_epoch() != epoch) from = 0; + + for (uint32_t k = 0; + k < impl_->cfg.voxel_sync_chunks_per_tick && + from < snap.voxels->cells.size(); + ++k) { + const uint16_t index = static_cast(from / per); + auto buf = std::make_shared(); + EncodeVoxelFull(*snap.voxels, snap.stamp, from, per, index, chunks, buf.get()); + s->Send(buf, true, /*is_map=*/false); + from += per; + } + + // Ban do RONG: van gui MOT manh rong, de client biet "gio khong con gi" + // thay vi giu mai tap cu. + if (snap.voxels->cells.empty()) { + auto buf = std::make_shared(); + EncodeVoxelFull(*snap.voxels, snap.stamp, 0, 0, 0, 1, buf.get()); + s->Send(buf, true, /*is_map=*/false); + } + + s->set_voxel_sync(epoch, from); + + // Da bom het -> danh dau DA DONG BO ngay, khong doi `ack_voxel`. + // + // ⚠️ Cho ACK o day la mot cho treo that: ACK mat thi server coi + // client van dang dong bo, ma `from` da toi cuoi nen vong tren khong gui + // gi nua, va delta cung khong duoc gui vi chua "synced" -- ban do 3D + // dung yen vinh vien ma khong mot loi nao. Danh dau lac quan o day va de + // client TU xin resync khi no phat hien hut so thu tu delta; do la cung + // khuon mau `set_acked_map_version` ngay sau khi xep hang o khoi MAP. + if (from >= snap.voxels->cells.size()) { + s->set_voxel_epoch(epoch); + s->set_voxel_resync(false); + } + } + } } size_t WebServer::client_count() const { diff --git a/libs/vslam_web/www/app.js b/libs/vslam_web/www/app.js index 662200c..5c2e43e 100644 --- a/libs/vslam_web/www/app.js +++ b/libs/vslam_web/www/app.js @@ -12,7 +12,7 @@ const MAGIC = 0x314C5356; // 'VSL1' little-endian // Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css. // Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con // cache ban cu". -const UI_VERSION = '2026-09-19g'; +const UI_VERSION = '2026-09-23a'; // ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau. // @@ -62,9 +62,12 @@ const PALETTE = { }, }; -const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_MAP_PATCH = 4, T_PATH = 5; +const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_PATH = 5; +// 4 = kMapPatch, DA BO o phia server. Giu lo trong, khong tai dung. // Ban do THE GIOI cua bo mo phong -- khung nhin "Gazebo". Tinh: gui mot lan. const T_WORLD_MAP = 6; +// Ban do voxel 3D: tap day du (chia manh) va phan them/bot. +const T_VOXEL_FULL = 7, T_VOXEL_DELTA = 8; // Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh. const R_NAN = 0xFFFF; // khong do duoc (duoi range_min) @@ -77,6 +80,14 @@ const state = { // anchorPose(). `scanDelta` den tu khung state, dung ngay khung scan ke tiep. cloudPose: null, scanPose: null, scanDelta: null, map: null, mapImage: null, mapVersion: 0, + // Ban do voxel 3D. `set` la Set CAC SO (khong phai chuoi): o 100k phan tu + // thi Set re hon han Set ca ve bo nho lan thoi gian. + // `dirty` = co gi doi ke tu lan dung lai hinh gan nhat. + voxels: { + epoch: 0, res: 0.1, ox: 0, oy: 0, oz: 0, + set: new Set(), total: 0, seq: 0, syncing: false, dirty: false, + }, + voxelResyncAt: 0, bytes: 0, lastBytes: 0, wireRate: 0, }; @@ -127,6 +138,32 @@ function setConn(ok) { // --- Khung nhi phan -------------------------------------------------------- +// Khoa voxel dang SO. Ba chi so i16 -> mot so nguyen <= 2^48, van chinh xac +// tuyet doi trong double. +function voxelKey(x, y, z) { + return ((x + 32768) * 65536 + (y + 32768)) * 65536 + (z + 32768); +} + +function voxelUnpack(k) { + const z = (k % 65536) - 32768; + k = (k - (z + 32768)) / 65536; + const y = (k % 65536) - 32768; + k = (k - (y + 32768)) / 65536; + return [k - 32768, y, z]; +} + +// Xin server gui lai ca tap. Ham han MOT lan moi giay: lech epoch thuong keo +// theo mot chum khung delta, va moi khung lai goi vao day. +function requestVoxelResync() { + const now = Date.now(); + if (now - state.voxelResyncAt < 1000) return; + state.voxelResyncAt = now; + state.voxels.seq = 0; + if (ws && ws.readyState === 1) { + ws.send(JSON.stringify({ t: 'voxel_resync' })); + } +} + function onBinary(dv) { if (dv.byteLength < 16 || dv.getUint32(0, true) !== MAGIC) return; const type = dv.getUint8(4); @@ -212,6 +249,84 @@ function onBinary(dv) { return; } + // --- Ban do voxel 3D --- + // + // Khoa la mot SO, khong phai chuoi: `((x+32768)*65536 + (y+32768))*65536 + + // (z+32768)` toi da 2^48, double bieu dien chinh xac tuyet doi. Set + // o 100k phan tu la mot con duong chac chan toi giat hinh. + if (type === T_VOXEL_FULL) { + const res = dv.getFloat32(off, true); + const ox = dv.getFloat32(off + 4, true); + const oy = dv.getFloat32(off + 8, true); + const oz = dv.getFloat32(off + 12, true); + const epoch = dv.getUint32(off + 16, true); + const total = dv.getUint32(off + 20, true); + const chunkIndex = dv.getUint16(off + 24, true); + const chunkCount = dv.getUint16(off + 26, true); + const n = dv.getUint32(off + 28, true); + + const v = state.voxels; + // Manh dau, hoac epoch la giua chung -> bo het lam lai. Tron hai epoch se + // ra mot ban do khong ton tai o dau ca. + if (chunkIndex === 0 || epoch !== v.epoch) { + v.set = new Set(); + v.epoch = epoch; + v.res = res; + v.ox = ox; v.oy = oy; v.oz = oz; + v.total = total; + v.seq = 0; + v.syncing = true; + } + for (let i = 0; i < n; i++) { + const b = off + 32 + i * 6; + v.set.add(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true), + dv.getInt16(b + 4, true))); + } + v.dirty = true; + + if (chunkIndex + 1 >= chunkCount) { + v.syncing = false; + // Dem lai truoc khi bao "xong": manh full-sync la khung THUONG, server + // drop duoc chung khi hang doi day. Thieu mot manh ma van ack thi ban do + // co mot lo hong khong bao gio duoc lap, va khong mot dau hieu nao. + if (v.set.size !== v.total) { + requestVoxelResync(); + } else if (ws && ws.readyState === 1) { + ws.send(JSON.stringify({ t: 'ack_voxel', epoch: v.epoch })); + } + } + return; + } + + if (type === T_VOXEL_DELTA) { + const epoch = dv.getUint32(off, true); + const seq = dv.getUint32(off + 4, true); + const nAdd = dv.getUint32(off + 8, true); + const nDel = dv.getUint32(off + 12, true); + + const v = state.voxels; + // Lech epoch = server da dung lai ban do (vong dong). Hut so thu tu = mat + // khung. Ca hai deu khong va duoc, phai xin lai ca tap. + if (epoch !== v.epoch || (v.seq !== 0 && seq !== v.seq + 1)) { + requestVoxelResync(); + return; + } + v.seq = seq; + + let b = off + 16; + for (let i = 0; i < nAdd; i++, b += 6) { + v.set.add(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true), + dv.getInt16(b + 4, true))); + } + for (let i = 0; i < nDel; i++, b += 6) { + v.set.delete(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true), + dv.getInt16(b + 4, true))); + } + v.total = v.set.size; + v.dirty = true; + return; + } + if (type === T_PATH) { const n = dv.getUint32(off, true); const pts = new Float32Array(n * 2); @@ -1069,6 +1184,11 @@ function draw3d() { // SLAM: lop phu tren san, hien DAN khi quet -- day la phan "RViz". O chua // quet trong suot nen tuong 3D van nhin xuyen qua. + // VOXEL: "cai gi dung tren san", bu cho tam phang cua v3dSetMap ("da quet + // toi dau"). Hai lop khong tranh nhau: tam phang o y = -0.002, voxel bat + // dau tu z_min = 0.05. + v3dSetVoxels(state.voxels, on('lyVoxel')); + if (state.map && on('lyMap')) { v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion }); } diff --git a/libs/vslam_web/www/app3d.js b/libs/vslam_web/www/app3d.js index 3c7df1a..5214d8b 100644 --- a/libs/vslam_web/www/app3d.js +++ b/libs/vslam_web/www/app3d.js @@ -24,6 +24,7 @@ const V3D = { ready: false, scene: null, camera: null, renderer: null, root: null, robotGroup: null, scanPts: null, cloudPts: null, mapMesh: null, + voxelMesh: null, voxelCap: 0, voxelEpoch: -1, worldMesh: null, worldKey: null, meshWorld: null, // nhom mesh THAT doc tu .world; co thi khong dung khoi hop gtGroup: null, pathLine: null, @@ -496,6 +497,93 @@ function v3dSetCloud(arr, pose) { V3D.cloudPts.geometry.setAttribute('color', new THREE.BufferAttribute(col, 3)); } +// --- Ban do voxel 3D ------------------------------------------------------- +// +// Nguon: SLAM, khong phai bo mo phong. Day la "cai gi dung tren san" do chinh +// robot do duoc, bu cho tam phang cua v3dSetMap ("da quet toi dau"). +// +// Ba cho CO Y khac v3dSetWorld va v3dSetCloud, moi cho vi mot ly do: +// +// 1. Dung lai theo NOI DUNG (`v.dirty`), khong theo kich thuoc. v3dSetWorld +// cache theo `w x h @ ox,oy` -- dung cho mot ban do TINH, sai hoan toan o +// day vi tap voxel doi lien tuc trong khi bao ngoai dung yen. +// +// 2. KHONG dispose/dung lai hinh moi khung nhu v3dSetCloud. InstancedMesh co +// so luong co dinh, nen cap phat du `capacity` roi chi doi `count`. O +// 100k the thi kieu cua cloud khong song noi. +// +// 3. KHONG do bong. v3dSetWorld bat ca castShadow lan receiveShadow; nem +// 100k the vao shadow map 2048^2 la mat frame rate. Dung "sua" lai. +function v3dSetVoxels(v, visible) { + if (!V3D.ready) return; + if (!v || !visible || v.set.size === 0) { + if (V3D.voxelMesh) V3D.voxelMesh.visible = false; + return; + } + + const n = v.set.size; + const needNew = !V3D.voxelMesh || n > V3D.voxelCap || + (V3D.voxelMesh && V3D.voxelRes !== v.res); + if (needNew) { + if (V3D.voxelMesh) { + V3D.root.remove(V3D.voxelMesh); + V3D.voxelMesh.geometry.dispose(); + V3D.voxelMesh.material.dispose(); + } + // Cap phat du de lon them mot doan ma khong phai cap phat lai moi khung. + let cap = 1024; + while (cap < Math.ceil(n * 1.5)) cap *= 2; + const geo = new THREE.BoxGeometry(v.res, v.res, v.res); + const mat = new THREE.MeshStandardMaterial({ roughness: 0.9, metalness: 0.0 }); + V3D.voxelMesh = new THREE.InstancedMesh(geo, mat, cap); + // Bounding sphere cua InstancedMesh lay tu hinh GOC (mot hop 0.1 m), nen + // de mac dinh thi three.js cull ca ban do ngay khi goc toa do ra khoi khung. + V3D.voxelMesh.frustumCulled = false; + V3D.voxelMesh.castShadow = false; + V3D.voxelMesh.receiveShadow = false; + V3D.voxelCap = cap; + V3D.voxelRes = v.res; + V3D.root.add(V3D.voxelMesh); + v.dirty = true; // hinh moi -> phai do lai du lieu + } + + V3D.voxelMesh.visible = true; + if (!v.dirty) return; + v.dirty = false; + + const m4 = new THREE.Matrix4(); + const col = new THREE.Color(); + const half = v.res * 0.5; + let i = 0; + for (const key of v.set) { + // Giai khoa tai cho: goi voxelUnpack() 100k lan moi lan dung lai la + // 100k mang tam. + const z = (key % 65536) - 32768; + const k1 = (key - (z + 32768)) / 65536; + const y = (k1 % 65536) - 32768; + const x = (k1 - (y + 32768)) / 65536 - 32768; + + // Tam o, khong phai goc o. ROS (x, y, z) -> three (x, z, -y) -- giong + // toScene(), nhung noi thang vao day: toScene() cap phat mot Vector3 moi + // lan goi, va 100k lan cap phat moi lan dung lai la mot con bao GC. + const wx = v.ox + x * v.res + half; + const wy = v.oy + y * v.res + half; + const wz = v.oz + z * v.res + half; + m4.makeTranslation(wx, wz, -wy); + V3D.voxelMesh.setMatrixAt(i, m4); + + // Cung thang mau voi point cloud, gian ra toi 2 m: hai lop phai doc nhu + // mot he, khong phai hai he mau canh nhau. + const t = Math.max(0, Math.min(1, wz / 2.0)); + col.setRGB((80 + 175 * t) / 255, (200 - 90 * t) / 255, (120 + 60 * t) / 255); + V3D.voxelMesh.setColorAt(i, col); + ++i; + } + V3D.voxelMesh.count = i; + V3D.voxelMesh.instanceMatrix.needsUpdate = true; + if (V3D.voxelMesh.instanceColor) V3D.voxelMesh.instanceColor.needsUpdate = true; +} + // The gioi 3D: o BI CHIEM -> hop, dung nhu Gazebo dung tuong tu ban do. // // ================== VI SAO INSTANCED ================== diff --git a/libs/vslam_web/www/index.html b/libs/vslam_web/www/index.html index 81aa918..5884b4a 100644 --- a/libs/vslam_web/www/index.html +++ b/libs/vslam_web/www/index.html @@ -11,6 +11,10 @@
+ + diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 2c3a8af..4e41104 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -43,6 +43,7 @@ if(VSLAM_BUILD_COMMON) # ctest -LE condvar set_tests_properties(test_channel PROPERTIES LABELS condvar) vslam_add_test(test_config LIBS vslam_common) + vslam_add_test(test_map_path LIBS vslam_common) vslam_add_test(test_approx_sync LIBS vslam_common) vslam_add_test(test_teleop_model LIBS vslam_common) vslam_add_test(test_robot_model LIBS vslam_common) @@ -94,6 +95,7 @@ endif() if(VSLAM_BUILD_SLAM) vslam_add_test(test_slam LIBS vslam_slam vslam_common) + vslam_add_test(test_voxel_export LIBS vslam_slam vslam_common) endif() if(VSLAM_BUILD_WEB) @@ -207,6 +209,14 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export) # Scan di qua day tren dinh dang POLAR trong frame LASER; trinh duyet doi # sang Descartes roi ap pose BASE. Quen khoang gan LiDAR lam ca vanh quet # lui 24 cm ma khong mot chi so van hanh nao doi. + # Ban do voxel 3D: khoa dang SO (khong phai chuoi), rap manh, va hai duong + # xin dong bo lai. Mot dau tru sai trong phep goi khoa lam nua ban do phia am + # gap len goc toa do -- van ve duoc, khong mot loi nao. + add_test(NAME www_voxel_decode + COMMAND ${VSLAM_NODE_EXE} + ${CMAKE_CURRENT_SOURCE_DIR}/www/test_voxel_decode.js) + set_tests_properties(www_voxel_decode PROPERTIES + PASS_REGULAR_EXPRESSION "=> DAT") add_test(NAME www_scan_frame COMMAND ${VSLAM_NODE_EXE} ${CMAKE_CURRENT_SOURCE_DIR}/www/test_scan_frame.js) diff --git a/test/test_binary_codec.cc b/test/test_binary_codec.cc index 71d5a1a..da767bb 100644 --- a/test/test_binary_codec.cc +++ b/test/test_binary_codec.cc @@ -129,53 +129,146 @@ TEST(BinaryCodec, MapFullNenTotTrenBanDoThua) { EXPECT_EQ(out.data, m.data); } -TEST(BinaryCodec, MapPatchChiGuiVungDoi) { - OccupancyGrid a; - a.width = 100; - a.height = 100; - a.resolution = 0.05f; - a.data.assign(10000u, -1); +// --- Ban do voxel 3D ------------------------------------------------------- - OccupancyGrid b = a; - for (uint32_t y = 50; y < 55; ++y) { - for (uint32_t x = 20; x < 30; ++x) b.data[y * b.width + x] = 100; +namespace { + +VoxelIndex VK(int x, int y, int z) { + VoxelIndex k; + k.x = static_cast(x); + k.y = static_cast(y); + k.z = static_cast(z); + return k; +} + +VoxelGrid MakeGrid(size_t n, uint32_t epoch = 7) { + VoxelGrid g; + g.resolution = 0.10f; + g.epoch = epoch; + for (size_t i = 0; i < n; ++i) { + g.cells.push_back(VK(static_cast(i), 0, 1)); } - - std::string patch; - ASSERT_TRUE(EncodeMapPatch(b, a, UnixTime::fromSec(1.0), &patch)); - - BinaryHeader h; - ASSERT_TRUE(DecodeHeader(patch, 0, &h)); - EXPECT_EQ(h.type, BinaryType::kMapPatch); - // Vung bao la 10x5 = 50 o, nen patch phai nho hon nhieu so voi full. - std::string full; - EncodeMapFull(b, UnixTime::fromSec(1.0), &full); - EXPECT_LT(patch.size(), full.size()); + return g; } -TEST(BinaryCodec, MapPatchTuChoiKhiKichThuocDoi) { - OccupancyGrid a; - a.width = 10; a.height = 10; a.resolution = 0.05f; - a.data.assign(100u, -1); +} // namespace - OccupancyGrid b = a; - b.width = 20; b.height = 10; - b.data.assign(200u, -1); +TEST(BinaryCodec, VoxelFullRoundTripMotManh) { + VoxelGrid g = MakeGrid(3); + g.cells[1] = VK(-5, -32768, 32767); // bien cua i16, ca hai dau - std::string patch; - // Kich thuoc doi -> khong va duoc, phai gui MAP_FULL. - EXPECT_FALSE(EncodeMapPatch(b, a, UnixTime::fromSec(1.0), &patch)); + std::string buf; + EncodeVoxelFull(g, UnixTime::fromSec(2.0), 0, g.cells.size(), 0, 1, &buf); + + VoxelChunkInfo info; + std::vector out; + ASSERT_TRUE(DecodeVoxelFull(buf, &info, &out)); + EXPECT_EQ(info.epoch, 7u); + EXPECT_EQ(info.total, 3u); + EXPECT_EQ(info.chunk_index, 0); + EXPECT_EQ(info.chunk_count, 1); + ASSERT_EQ(out.size(), 3u); + // Dau AM phai song sot qua duong truyen -- day la bug kinh dien cua i16. + EXPECT_EQ(out[1].x, -5); + EXPECT_EQ(out[1].y, -32768); + EXPECT_EQ(out[1].z, 32767); } -TEST(BinaryCodec, MapPatchTuChoiKhiKhongCoGiDoi) { - OccupancyGrid a; - a.width = 10; a.height = 10; a.resolution = 0.05f; - a.data.assign(100u, -1); +TEST(BinaryCodec, VoxelFullChiaManhVaRapLai) { + const VoxelGrid g = MakeGrid(1000); + // 64 byte/manh -> 32 byte con lai sau hai header -> 5 o moi manh. + const uint32_t chunk_bytes = 16 + 32 + 5 * 6; + const size_t per = VoxelCellsPerChunk(chunk_bytes); + ASSERT_EQ(per, 5u); + const uint16_t chunks = VoxelChunkCount(g, chunk_bytes); + EXPECT_EQ(chunks, 200); - std::string patch; - EXPECT_FALSE(EncodeMapPatch(a, a, UnixTime::fromSec(1.0), &patch)); + std::vector rap; + for (uint16_t i = 0; i < chunks; ++i) { + std::string buf; + EncodeVoxelFull(g, UnixTime::fromSec(1.0), static_cast(i) * per, per, + i, chunks, &buf); + VoxelChunkInfo info; + ASSERT_TRUE(DecodeVoxelFull(buf, &info, &rap)); + EXPECT_EQ(info.total, 1000u); + EXPECT_EQ(info.chunk_count, chunks); + } + ASSERT_EQ(rap.size(), 1000u); + for (size_t i = 0; i < rap.size(); ++i) EXPECT_EQ(rap[i].x, static_cast(i)); } +TEST(BinaryCodec, VoxelFullManhCuoiNganHon) { + const VoxelGrid g = MakeGrid(7); + const uint32_t chunk_bytes = 16 + 32 + 5 * 6; // 5 o/manh -> 5 + 2 + EXPECT_EQ(VoxelChunkCount(g, chunk_bytes), 2); + + std::string buf; + EncodeVoxelFull(g, UnixTime::fromSec(1.0), 5, 5, 1, 2, &buf); // xin 5, con 2 + VoxelChunkInfo info; + std::vector out; + ASSERT_TRUE(DecodeVoxelFull(buf, &info, &out)); + EXPECT_EQ(out.size(), 2u) << "khong duoc doc qua duoi mang"; + EXPECT_EQ(info.total, 7u); +} + +TEST(BinaryCodec, VoxelFullBanDoRongVanCoMotManh) { + // Client phai nhan duoc MOT khung de biet ban do gio rong, khong thi no giu + // mai tap cu. + const VoxelGrid g = MakeGrid(0); + EXPECT_EQ(VoxelChunkCount(g, 16384), 1); + + std::string buf; + EncodeVoxelFull(g, UnixTime::fromSec(1.0), 0, 0, 0, 1, &buf); + VoxelChunkInfo info; + std::vector out; + ASSERT_TRUE(DecodeVoxelFull(buf, &info, &out)); + EXPECT_EQ(info.total, 0u); + EXPECT_TRUE(out.empty()); +} + +TEST(BinaryCodec, VoxelDeltaRoundTrip) { + const std::vector added = {VK(1, 2, 3), VK(-1, -2, -3)}; + const std::vector removed = {VK(9, 9, 9)}; + + std::string buf; + EncodeVoxelDelta(7, 42, added, removed, UnixTime::fromSec(3.0), &buf); + EXPECT_EQ(buf.size(), 16u + 16u + 3u * 6u); + + uint32_t epoch = 0, seq = 0; + std::vector a, r; + ASSERT_TRUE(DecodeVoxelDelta(buf, &epoch, &seq, &a, &r)); + EXPECT_EQ(epoch, 7u); + EXPECT_EQ(seq, 42u); + ASSERT_EQ(a.size(), 2u); + EXPECT_EQ(a[1].x, -1); + EXPECT_EQ(a[1].z, -3); + ASSERT_EQ(r.size(), 1u); + EXPECT_EQ(r[0].y, 9); +} + +TEST(BinaryCodec, VoxelDeltaRongVanHopLe) { + std::string buf; + EncodeVoxelDelta(1, 0, {}, {}, UnixTime::fromSec(1.0), &buf); + uint32_t epoch = 0, seq = 0; + std::vector a, r; + ASSERT_TRUE(DecodeVoxelDelta(buf, &epoch, &seq, &a, &r)); + EXPECT_TRUE(a.empty()); + EXPECT_TRUE(r.empty()); +} + +TEST(BinaryCodec, VoxelKhungCutBiTuChoi) { + // Khung bi cat giua chung phai tra false chu khong doc qua duoi bo dem. + VoxelGrid g = MakeGrid(10); + std::string buf; + EncodeVoxelFull(g, UnixTime::fromSec(1.0), 0, 10, 0, 1, &buf); + buf.resize(buf.size() - 7); + + VoxelChunkInfo info; + std::vector out; + EXPECT_FALSE(DecodeVoxelFull(buf, &info, &out)); +} + + TEST(BinaryCodec, CloudGiamMauVaBoNaN) { PointCloudXYZ c; for (int i = 0; i < 10000; ++i) { diff --git a/test/test_map_path.cc b/test/test_map_path.cc new file mode 100644 index 0000000..55ab2d4 --- /dev/null +++ b/test/test_map_path.cc @@ -0,0 +1,118 @@ +// Giai duong dan ban do: tuong doi -> MapDir(), `{stamp}` -> dau thoi gian, +// va mkdir -p cho thu muc cha. +// +// Cac test nay TU dat $VSLAM_RESOURCE_DIR trong than test thay vi nho harness: +// ResolveMapPath doc env o MOI lan goi, nen dat tai cho la du, va khong ep +// moi test khac trong cay phai song chung mot bien moi truong. + +#include "vslam/node_constants.h" + +#include + +#include +#include + +#include +#include +#include + +using namespace vslam; + +namespace { + +// Thu muc tam rieng cho tung test, duoi $TMPDIR. Kem pid de hai lan chay song +// song khong dam nhau. +std::string TempRoot(const std::string& leaf) { + const char* t = std::getenv("TMPDIR"); + const std::string base = (t != nullptr && t[0] != '\0') ? std::string(t) : "/tmp"; + return base + "/vslam_test_" + leaf + "_" + std::to_string(::getpid()); +} + +void SetResourceDir(const std::string& dir) { + ::setenv(kResourceDirEnv, dir.c_str(), 1); +} + +} // namespace + +TEST(ResolveMapPath, RongThiGiuRong) { + // Rong = DB trong RAM. Bien no thanh mot duong dan la doi han y nghia cua + // `--slam-db ""`. + SetResourceDir("/tmp/khong-duoc-dung"); + EXPECT_EQ(ResolveMapPath(""), ""); +} + +TEST(ResolveMapPath, TuyetDoiGiuNguyen) { + SetResourceDir("/tmp/khong-duoc-dung"); + EXPECT_EQ(ResolveMapPath("/abs/duong/map.db"), "/abs/duong/map.db"); +} + +TEST(ResolveMapPath, TuongDoiGiaiTheoMapDir) { + SetResourceDir("/tmp/vslam_res"); + EXPECT_EQ(MapDir(), "/tmp/vslam_res/maps"); + EXPECT_EQ(ResolveMapPath("map.db"), "/tmp/vslam_res/maps/map.db"); + EXPECT_EQ(ResolveMapPath("tang3/map.db"), "/tmp/vslam_res/maps/tang3/map.db"); +} + +TEST(ResolveMapPath, StampNoRaVaDongNhatTrongCaChuoi) { + SetResourceDir("/tmp/vslam_res"); + const std::string out = ResolveMapPath("{stamp}/map_{stamp}.db"); + + // Khong con token nao sot lai. + EXPECT_EQ(out.find('{'), std::string::npos); + + // Hai lan xuat hien phai ra CUNG mot gia tri -- neu moi lan goi NowStamp() + // rieng thi ten thu muc va ten file lech nhau mot giay. + const std::string prefix = "/tmp/vslam_res/maps/"; + ASSERT_EQ(out.compare(0, prefix.size(), prefix), 0) << out; + const std::string rest = out.substr(prefix.size()); + const size_t slash = rest.find('/'); + ASSERT_NE(slash, std::string::npos) << out; + const std::string dir_stamp = rest.substr(0, slash); + EXPECT_EQ(dir_stamp.size(), 15u); // %Y%m%d_%H%M%S + EXPECT_EQ(rest.substr(slash + 1), "map_" + dir_stamp + ".db"); + + for (char c : dir_stamp) { + EXPECT_TRUE((c >= '0' && c <= '9') || c == '_') << dir_stamp; + } +} + +TEST(ResolveMapPath, Idempotent) { + SetResourceDir("/tmp/vslam_res"); + const std::string once = ResolveMapPath("map_{stamp}.db"); + EXPECT_EQ(ResolveMapPath(once), once); +} + +TEST(EnsureParentDir, TaoLongNhau) { + const std::string root = TempRoot("mkdir"); + const std::string db = root + "/a/b/c/map.db"; + const StatusResponse st = EnsureParentDir(db); + ASSERT_TRUE(st.ok()) << st.message; + + struct stat sb {}; + ASSERT_EQ(::stat((root + "/a/b/c").c_str(), &sb), 0); + EXPECT_TRUE(S_ISDIR(sb.st_mode)); + EXPECT_FALSE(::access(db.c_str(), F_OK) == 0) << "chi tao thu muc, khong tao file"; + + // Goi lai tren thu muc da co phai Ok, khong phai EEXIST. + EXPECT_TRUE(EnsureParentDir(db).ok()); +} + +TEST(EnsureParentDir, LoiKhiChaLaFileThuong) { + const std::string root = TempRoot("notdir"); + ASSERT_TRUE(EnsureParentDir(root + "/x").ok()); + { + std::ofstream f(root + "/tap-tin"); + ASSERT_TRUE(f.good()); + f << "khong phai thu muc\n"; + } + const StatusResponse st = EnsureParentDir(root + "/tap-tin/map.db"); + EXPECT_FALSE(st.ok()); + EXPECT_NE(st.message.find("khong phai thu muc"), std::string::npos) << st.message; +} + +TEST(EnsureParentDir, KhongCoThuMucChaThiBoQua) { + // "map.db" tran = thu muc hien tai; "/map.db" = ngay duoi root. Ca hai deu + // khong co gi de tao, va KHONG duoc di mkdir("/"). + EXPECT_TRUE(EnsureParentDir("map.db").ok()); + EXPECT_TRUE(EnsureParentDir("/map.db").ok()); +} diff --git a/test/test_slam.cc b/test/test_slam.cc index 60d3819..cc1ae26 100644 --- a/test/test_slam.cc +++ b/test/test_slam.cc @@ -87,6 +87,46 @@ TEST(RtabmapParams, CheDoGhiDeLenCaYaml) { << "localization ma khong nap het node -> vung chua tung den khong duoc xet"; } +TEST(RtabmapParams, Camera3dBatLuoiCucBo3D) { + // `camera_3d` la CONG TAC cua ban do voxel 3D tren web. No phai thang ca + // YAML: slam.yaml dat thang Grid/Sensor va Grid/3D, va mot file cu con hai + // dong do se am tham lam ban do 3D rong khong. + RtabmapConfig cfg; + cfg.camera_3d = true; + cfg.overrides["Grid/3D"] = "false"; // YAML co gang tat + cfg.overrides["Grid/Sensor"] = "0"; // YAML co gang bo depth + + std::vector unknown; + const auto p = BuildRtabmapParams(cfg, &unknown); + EXPECT_TRUE(unknown.empty()) << "ten key Grid/* phai dung y het RTAB-Map"; + + EXPECT_EQ(p.at("Grid/3D"), "true"); + EXPECT_EQ(p.at("Grid/Sensor"), "2") << "0=scan 1=depth 2=ca hai"; + EXPECT_EQ(p.at("Grid/NormalsSegmentation"), "false"); + EXPECT_EQ(p.at("Grid/MaxGroundHeight"), "0.10"); + EXPECT_EQ(p.at("Grid/MaxObstacleHeight"), "2.0"); + + // Ray tracing KHONG bi tat kem theo: no la thu sinh ra o "trong" cua luoi + // 2D (84961 o tren robot that), va ban do 3D khong duoc phep lam rong khung + // ban do 2D. + EXPECT_EQ(p.at("Grid/RayTracing"), "true"); + + // Khong them key la nao -- go sai ten Grid/* se lam bang nay phinh ra. + const auto def = rtabmap::Parameters::getDefaultParameters(); + EXPECT_EQ(p.size(), def.size()); +} + +TEST(RtabmapParams, MacDinhKhongDungToiLuoi3D) { + // Mac dinh PHAI la 2D: bat 3D len doi CA noi dung luoi 2D (o tu camera) lan + // RAM/CPU cua Jetson. Ai can thi bat tuong minh. + RtabmapConfig cfg; + EXPECT_FALSE(cfg.camera_3d); + std::vector unknown; + const auto p = BuildRtabmapParams(cfg, &unknown); + EXPECT_EQ(p.at("Grid/3D"), "false"); + EXPECT_EQ(p.at("Grid/Sensor"), "0"); +} + TEST(RtabmapParams, OptimizerLuonDuocEpTuongMinh) { // map_house.db luu Optimizer/Strategy=2 (GTSAM). Tren Jetson build // -DWITH_GTSAM=OFF ma de RTAB-Map doc tham so tu DB thi no chon GTSAM va diff --git a/test/test_voxel_export.cc b/test/test_voxel_export.cc new file mode 100644 index 0000000..f9a8b9e --- /dev/null +++ b/test/test_voxel_export.cc @@ -0,0 +1,210 @@ +// VoxelAccumulator va DiffVoxelGrids: phan THUAN cua duong xuat ban do 3D. +// +// Khong mot kieu nao cua RTAB-Map o day, va do la chu y: `ExportOccupancyGrid` +// den nay khong co unit test nao chinh vi no can mot `Rtabmap` dang chay. +// Phan tinh toan tach ra thi kiem duoc bang so. + +#include "vslam/voxel_export.h" + +#include + +#include +#include + +using namespace vslam; + +namespace { + +VoxelExportOptions Opt(double emit = 0.10) { + VoxelExportOptions o; + o.emit_size_m = emit; + o.z_min = 0.05; + o.z_max = 2.00; + return o; +} + +VoxelIndex K(int x, int y, int z) { + VoxelIndex k; + k.x = static_cast(x); + k.y = static_cast(y); + k.z = static_cast(z); + return k; +} + +bool Has(const std::vector& v, int x, int y, int z) { + for (const VoxelIndex& k : v) { + if (k.x == x && k.y == y && k.z == z) return true; + } + return false; +} + +// Cung thu tu ma Finish() hua: theo khoa goi, tuc (x, y, z) tu nhien. +bool DaSapXep(const std::vector& v) { + for (size_t i = 1; i < v.size(); ++i) { + const VoxelIndex& a = v[i - 1]; + const VoxelIndex& b = v[i]; + if (a.x != b.x) { if (a.x > b.x) return false; continue; } + if (a.y != b.y) { if (a.y > b.y) return false; continue; } + if (a.z >= b.z) return false; + } + return true; +} + +} // namespace + +TEST(VoxelAccumulator, GomDiemTrungVaoMotO) { + VoxelAccumulator acc(Opt(0.10)); + // Ba diem trong cung mot o 10 cm. + acc.AddPoint(1.01, 2.02, 0.51); + acc.AddPoint(1.09, 2.09, 0.59); + acc.AddPoint(1.05, 2.05, 0.55); + VoxelGrid g; + acc.Finish(&g); + + ASSERT_EQ(g.cells.size(), 1u); + EXPECT_TRUE(Has(g.cells, 10, 20, 5)); + EXPECT_FLOAT_EQ(g.resolution, 0.10f); + EXPECT_FALSE(g.truncated); +} + +TEST(VoxelAccumulator, ChiSoAmDungHuong) { + // floor(), khong phai cat ve 0: -0.05 m phai roi vao o -1 chu khong phai 0. + // Nham cho nay thi nua ban do phia am bi gap len goc toa do. + VoxelAccumulator acc(Opt(0.10)); + acc.AddPoint(-0.05, -1.25, 0.10); + VoxelGrid g; + acc.Finish(&g); + ASSERT_EQ(g.cells.size(), 1u); + EXPECT_EQ(g.cells[0].x, -1); + EXPECT_EQ(g.cells[0].y, -13); + EXPECT_EQ(g.cells[0].z, 1); +} + +TEST(VoxelAccumulator, CatSanVaTran) { + VoxelAccumulator acc(Opt(0.10)); + acc.AddPoint(0.0, 0.0, 0.00); // san -> bo (z < z_min) + acc.AddPoint(0.0, 0.0, 0.04); // van duoi nguong -> bo + acc.AddPoint(0.0, 0.0, 1.00); // giu + acc.AddPoint(0.0, 0.0, 2.50); // tran -> bo + VoxelGrid g; + acc.Finish(&g); + + ASSERT_EQ(g.cells.size(), 1u); + EXPECT_EQ(g.cells[0].z, 10); + EXPECT_EQ(acc.z_rejected(), 3u); +} + +TEST(VoxelAccumulator, DauRaDaSapXep) { + VoxelAccumulator acc(Opt(0.10)); + // Nhet vao theo thu tu lung tung. + const double pts[][3] = {{5.0, 1.0, 1.0}, {-3.0, 2.0, 0.5}, {5.0, 0.5, 1.0}, + {0.0, 0.0, 1.5}, {-3.0, 2.0, 1.5}}; + for (const auto& p : pts) acc.AddPoint(p[0], p[1], p[2]); + VoxelGrid g; + acc.Finish(&g); + + EXPECT_EQ(g.cells.size(), 5u); + EXPECT_TRUE(DaSapXep(g.cells)) << "DiffVoxelGrids dua vao dung tinh chat nay"; +} + +TEST(VoxelAccumulator, ChamTranThiCatVaBaoTruncated) { + VoxelExportOptions o = Opt(0.10); + o.max_cells = 4; + VoxelAccumulator acc(o); + for (int i = 0; i < 20; ++i) acc.AddPoint(i * 1.0, 0.0, 1.0); + VoxelGrid g; + acc.Finish(&g); + + EXPECT_EQ(g.cells.size(), 4u); + EXPECT_TRUE(g.truncated) << "cat bot ma khong bao la kieu hong te nhat"; +} + +TEST(VoxelAccumulator, FlushNhieuLanVanRaCungKetQua) { + // flush_every nho ep duong set_union chay nhieu lan; ket qua phai y het khi + // gom mot lan. + VoxelExportOptions o = Opt(0.10); + o.flush_every = 3; + VoxelAccumulator many(o); + VoxelAccumulator once(Opt(0.10)); + for (int i = 0; i < 25; ++i) { + const double x = (i % 7) * 0.31; + many.AddPoint(x, 0.0, 1.0); + once.AddPoint(x, 0.0, 1.0); + } + VoxelGrid a, b; + many.Finish(&a); + once.Finish(&b); + + ASSERT_EQ(a.cells.size(), b.cells.size()); + for (size_t i = 0; i < a.cells.size(); ++i) { + EXPECT_EQ(a.cells[i].x, b.cells[i].x); + EXPECT_EQ(a.cells[i].y, b.cells[i].y); + EXPECT_EQ(a.cells[i].z, b.cells[i].z); + } +} + +TEST(VoxelAccumulator, DiemNgoaiDaiBiBoChuKhongKep) { + // Kep se dan mot buc tuong gia o ria ban do. Bo la dung. + VoxelAccumulator acc(Opt(0.10)); + acc.AddPoint(1e9, 0.0, 1.0); + acc.AddPoint(0.0, 0.0, 1.0); + VoxelGrid g; + acc.Finish(&g); + + EXPECT_EQ(g.cells.size(), 1u); + EXPECT_EQ(acc.clamped(), 1u); +} + +TEST(DiffVoxelGrids, ThemVaBot) { + const std::vector prev = {K(0, 0, 1), K(1, 0, 1), K(2, 0, 1)}; + const std::vector now = {K(1, 0, 1), K(2, 0, 1), K(3, 0, 1)}; + std::vector added, removed; + DiffVoxelGrids(prev, now, &added, &removed); + + ASSERT_EQ(added.size(), 1u); + EXPECT_EQ(added[0].x, 3); + ASSERT_EQ(removed.size(), 1u); + EXPECT_EQ(removed[0].x, 0); +} + +TEST(DiffVoxelGrids, QuetTienThiChiCoThem) { + // Mapping binh thuong: tap moi la sieu tap -> khong co o nao bi bo, delta nho. + const std::vector prev = {K(0, 0, 1), K(1, 0, 1)}; + const std::vector now = {K(0, 0, 1), K(1, 0, 1), K(2, 0, 1)}; + std::vector added, removed; + DiffVoxelGrids(prev, now, &added, &removed); + + EXPECT_EQ(added.size(), 1u); + EXPECT_TRUE(removed.empty()); +} + +TEST(DiffVoxelGrids, TapRong) { + std::vector added, removed; + const std::vector some = {K(0, 0, 1)}; + + DiffVoxelGrids({}, some, &added, &removed); + EXPECT_EQ(added.size(), 1u); + EXPECT_TRUE(removed.empty()); + + DiffVoxelGrids(some, {}, &added, &removed); + EXPECT_TRUE(added.empty()); + EXPECT_EQ(removed.size(), 1u); +} + +TEST(DiffVoxelGrids, SauVongDongThiDoiGanHet) { + // Toi uu lai do thi dich moi pose -> phep tru van dung, chi la khong lon. + // Day la ca de nguoi goi phat hien va nhay sang gui lai ca tap (doi epoch). + std::vector prev, now; + for (int i = 0; i < 100; ++i) { + prev.push_back(K(i, 0, 1)); + now.push_back(K(i, 5, 1)); // ca ban do dich 0.5 m theo y + } + std::vector added, removed; + DiffVoxelGrids(prev, now, &added, &removed); + + EXPECT_EQ(added.size(), 100u); + EXPECT_EQ(removed.size(), 100u); + const double ratio = static_cast(added.size() + removed.size()) / + static_cast(now.size()); + EXPECT_GT(ratio, 0.35) << "vuot nguong -> nguoi goi phai doi epoch"; +} diff --git a/test/www/test_voxel_decode.js b/test/www/test_voxel_decode.js new file mode 100644 index 0000000..f39e41c --- /dev/null +++ b/test/www/test_voxel_decode.js @@ -0,0 +1,235 @@ +// Giai ma khung voxel o phia trinh duyet: goi/mo khoa, rap manh, va xu ly +// delta lac epoch. +// +// ================== VI SAO CAN BAI KIEM NAY ================== +// Khoa voxel trong app.js la mot SO chu khong phai chuoi, va phep goi +// `((x+32768)*65536 + (y+32768))*65536 + (z+32768)` khong doc duoc bang mat. +// Sai mot dau tru o day thi ban do 3D van hien -- chi la nua phia am bi gap +// len goc toa do, va khong mot loi nao. +// +// Bai kiem nay lay CHINH app.js (khong chep lai logic), dung mot WebSocket +// gia, va nhet vao no dung nhung byte ma binary_codec.cc sinh ra. + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const APP = path.join(__dirname, '..', '..', 'libs', 'vslam_web', 'www', 'app.js'); + +// --- DOM gia: du de app.js chay het phan khai bao --- +const el = () => ({ + textContent: '', className: '', value: '', checked: false, style: {}, + width: 0, height: 0, clientWidth: 800, clientHeight: 600, + addEventListener() {}, getContext: () => ctx2d(), classList: { toggle() {}, add() {}, remove() {} }, + appendChild() {}, querySelectorAll: () => [], getBoundingClientRect: () => + ({ left: 0, top: 0, width: 800, height: 600 }), +}); +const ctx2d = () => new Proxy({}, { + get: (t, k) => (k === 'canvas' ? el() : () => ({ data: new Uint8ClampedArray(4) })), +}); + +const sent = []; +const ws = { readyState: 1, send: (m) => sent.push(JSON.parse(m)) }; + +const sandbox = { + console, Date, Math, JSON, Set, Map, Number, String, Array, Object, + Float32Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + DataView, ArrayBuffer, isNaN, parseFloat, parseInt, + document: { + getElementById: () => el(), querySelectorAll: () => [], querySelector: () => el(), + addEventListener() {}, + createElement: () => el(), body: el(), documentElement: el(), + }, + window: { addEventListener() {}, devicePixelRatio: 1, location: { search: '', host: 'x' } }, + location: { search: '', host: 'x', protocol: 'http:' }, + navigator: { userAgent: 'node' }, + requestAnimationFrame: () => 0, + setInterval: () => 0, setTimeout: () => 0, clearTimeout: () => 0, + fetch: () => new Promise(() => {}), + URLSearchParams: class { constructor() {} get() { return null; } }, + WebSocket: function () { return ws; }, + performance: { now: () => 0 }, +}; +sandbox.globalThis = sandbox; +vm.createContext(sandbox); + +let bad = 0; +try { + vm.runInContext(fs.readFileSync(APP, 'utf8'), sandbox, { filename: 'app.js' }); +} catch (e) { + // app.js chay den phan gan su kien UI thi co the vap -- khong sao, mien la + // cac ham giai ma da duoc dinh nghia. + console.log(' (app.js dung som: ' + e.message + ')'); +} + +// `function f(){}` o muc goc cua mot script vm TRO THANH thuoc tinh cua global, +// nhung `const`/`let` thi KHONG -- chung nam trong moi truong tu vung cua +// context. Moi truong do duoc dung chung giua cac lan runInContext, nen lay +// chung ra bang mot cau lenh chay trong chinh context do. +const { onBinary, voxelKey } = sandbox; +let state = null; +try { + state = vm.runInContext('state', sandbox); + // `ws` la `let` trong app.js va chi duoc gan trong connect(). Gan thang o + // day de duong gui ack/resync chay that thay vi bi bo qua im lang. + vm.runInContext('ws = globalThis.__fakeWs', Object.assign(sandbox, { __fakeWs: ws })); +} catch (e) { + console.log(' khong lay duoc `state` tu app.js: ' + e.message); +} + +if (typeof onBinary !== 'function' || typeof voxelKey !== 'function' || !state) { + console.log(' KHONG lay duoc onBinary/state/voxelKey tu app.js'); + console.log('\n => HONG'); + process.exit(1); +} + +// --- Dung khung y het binary_codec.cc --- +function header(buf, type) { + const dv = new DataView(buf); + dv.setUint8(0, 0x56); dv.setUint8(1, 0x53); dv.setUint8(2, 0x4C); dv.setUint8(3, 0x31); + dv.setUint8(4, type); + dv.setUint8(5, 1); + return dv; +} + +function voxelFull(cells, { epoch = 1, total = null, index = 0, count = 1, res = 0.1 } = {}) { + const buf = new ArrayBuffer(16 + 32 + cells.length * 6); + const dv = header(buf, 7); + dv.setFloat32(16, res, true); + dv.setFloat32(20, 0, true); + dv.setFloat32(24, 0, true); + dv.setFloat32(28, 0, true); + dv.setUint32(32, epoch, true); + dv.setUint32(36, total === null ? cells.length : total, true); + dv.setUint16(40, index, true); + dv.setUint16(42, count, true); + dv.setUint32(44, cells.length, true); + cells.forEach((c, i) => { + dv.setInt16(48 + i * 6, c[0], true); + dv.setInt16(48 + i * 6 + 2, c[1], true); + dv.setInt16(48 + i * 6 + 4, c[2], true); + }); + return dv; +} + +function voxelDelta(epoch, seq, add, del) { + const buf = new ArrayBuffer(16 + 16 + (add.length + del.length) * 6); + const dv = header(buf, 8); + dv.setUint32(16, epoch, true); + dv.setUint32(20, seq, true); + dv.setUint32(24, add.length, true); + dv.setUint32(28, del.length, true); + let o = 32; + for (const c of add.concat(del)) { + dv.setInt16(o, c[0], true); + dv.setInt16(o + 2, c[1], true); + dv.setInt16(o + 4, c[2], true); + o += 6; + } + return dv; +} + +function check(name, cond, chiTiet) { + if (cond) return; + bad++; + console.log(` ${name}: HONG${chiTiet ? ' -- ' + chiTiet : ''}`); +} + +// --- 1. Khoa giu duoc so am --- +{ + const k = voxelKey(-5, -32768, 32767); + const z = (k % 65536) - 32768; + const k1 = (k - (z + 32768)) / 65536; + const y = (k1 % 65536) - 32768; + const x = (k1 - (y + 32768)) / 65536 - 32768; + check('khoa am', x === -5 && y === -32768 && z === 32767, `${x},${y},${z}`); + check('khoa nguyen', Number.isSafeInteger(k), String(k)); +} + +// --- 2. Mot manh: nap du va gui ack --- +{ + sent.length = 0; + onBinary(voxelFull([[1, 2, 3], [-1, -2, -3]], { epoch: 5 })); + const v = state.voxels; + check('mot manh: so o', v.set.size === 2, String(v.set.size)); + check('mot manh: epoch', v.epoch === 5, String(v.epoch)); + check('mot manh: het syncing', v.syncing === false); + check('mot manh: co o am', v.set.has(voxelKey(-1, -2, -3))); + const ack = sent.find((m) => m.t === 'ack_voxel'); + check('mot manh: gui ack_voxel', ack && ack.epoch === 5, JSON.stringify(sent)); +} + +// --- 3. Nhieu manh: rap lai du, chi ack o manh cuoi --- +{ + sent.length = 0; + onBinary(voxelFull([[0, 0, 1], [1, 0, 1]], { epoch: 6, total: 4, index: 0, count: 2 })); + check('nhieu manh: dang sync', state.voxels.syncing === true); + check('nhieu manh: chua ack', sent.filter((m) => m.t === 'ack_voxel').length === 0); + onBinary(voxelFull([[2, 0, 1], [3, 0, 1]], { epoch: 6, total: 4, index: 1, count: 2 })); + check('nhieu manh: du 4 o', state.voxels.set.size === 4, String(state.voxels.set.size)); + check('nhieu manh: ack mot lan', sent.filter((m) => m.t === 'ack_voxel').length === 1); +} + +// --- 4. Delta them/bot --- +{ + onBinary(voxelDelta(6, 1, [[9, 9, 9]], [[0, 0, 1]])); + const v = state.voxels; + check('delta: da them', v.set.has(voxelKey(9, 9, 9))); + check('delta: da bot', !v.set.has(voxelKey(0, 0, 1))); + check('delta: seq', v.seq === 1, String(v.seq)); +} + +// --- 5. Delta lac epoch -> xin resync, KHONG cham vao tap --- +{ + sent.length = 0; + state.voxelResyncAt = 0; + const truoc = state.voxels.set.size; + onBinary(voxelDelta(99, 2, [[7, 7, 7]], [])); + check('epoch la: khong nap', state.voxels.set.size === truoc); + check('epoch la: xin resync', sent.some((m) => m.t === 'voxel_resync'), JSON.stringify(sent)); +} + +// --- 6. Hut so thu tu -> cung xin resync --- +{ + sent.length = 0; + state.voxelResyncAt = 0; + onBinary(voxelFull([[0, 0, 1]], { epoch: 7 })); + onBinary(voxelDelta(7, 1, [[1, 1, 1]], [])); + sent.length = 0; + state.voxelResyncAt = 0; + onBinary(voxelDelta(7, 5, [[2, 2, 2]], [])); // nhay tu 1 sang 5 + check('hut seq: xin resync', sent.some((m) => m.t === 'voxel_resync')); + check('hut seq: khong nap', !state.voxels.set.has(voxelKey(2, 2, 2))); +} + +// --- 7. Ham han resync mot lan moi giay --- +{ + sent.length = 0; + state.voxelResyncAt = 0; + for (let i = 0; i < 5; i++) onBinary(voxelDelta(12345, i + 1, [[1, 1, 1]], [])); + const n = sent.filter((m) => m.t === 'voxel_resync').length; + check('ham han resync', n === 1, `${n} lan`); +} + +// --- 8. Manh dau cua epoch moi xoa sach tap cu --- +{ + onBinary(voxelFull([[0, 0, 1], [1, 0, 1]], { epoch: 20 })); + onBinary(voxelFull([[5, 5, 5]], { epoch: 21 })); + check('epoch moi: tap duoc thay', state.voxels.set.size === 1, String(state.voxels.set.size)); + check('epoch moi: dung o', state.voxels.set.has(voxelKey(5, 5, 5))); +} + +// --- 9. Mat mot manh -> KHONG ack, xin dong bo lai --- +{ + sent.length = 0; + state.voxelResyncAt = 0; + // Server hua total = 4 nhung chi hai o toi (mot manh bi drop). + onBinary(voxelFull([[0, 0, 1], [1, 0, 1]], { epoch: 30, total: 4, index: 0, count: 2 })); + onBinary(voxelFull([[2, 0, 1]], { epoch: 30, total: 4, index: 1, count: 2 })); + check('mat manh: khong ack', sent.filter((m) => m.t === 'ack_voxel').length === 0, + JSON.stringify(sent)); + check('mat manh: xin resync', sent.some((m) => m.t === 'voxel_resync')); +} + +console.log(bad ? '\n => HONG' : '\n => DAT'); +process.exit(bad ? 1 : 0);