Files
vslam_cpp/PROJECT_CONTEXT.md
trung09122002 d6f1afac31 update
2026-09-24 16:30:03 +07:00

115 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Project Context
Use this file for verified target-repository facts only. Keep unknown values as `Unknown / needs confirmation`.
## Project Identity
- Project name: `vslam` (CMakeLists.txt:2, version 0.1.0); repo dir `vslam_cpp`
- Robot or system: indoor service robot, differential drive, ZLAC8015D base (README.md:3, configuration_files/sensors.yaml `base:`)
- Primary use case: SLAM + localization for indoor service robot, pure C++, no ROS (README.md:3-4)
- Repository role: rewrite of `~/projects/vSLAM_ws` (ROS 1 Noetic + catkin). Old repo kept as reference and test corpus (README.md:6-7). `../vSLAM_ws` is NOT in this repo.
## Stack
- 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`). 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).
## Repository Layout
- ROS packages: none. Eight CMake libraries in `libs/`, gated by `VSLAM_BUILD_*` options (CMakeLists.txt:35-42):
- `vslam_common` (P0, ON) — config, log, clock, geometry, TransformTree, Channel, RobotModel, stats
- `vslam_web` (P1, ON) — Boost.Beast HTTP + WebSocket server, RLE, binary codec, embedded www assets
- `vslam_drivers` (P2, ON) — LakiBeam LiDAR, RealSense D410, MCU serial bridge, ZLAC base, record/replay I/O, ScanSanitizer, ClockSync
- `vslam_odometry` (P3, ON) — wheel odometry + EKF SE(2)
- `vslam_safety` (P4, ON) — SafetyMonitor FSM
- `vslam_perception` (P5, ON) — depth_to_cloud, depth_filter, gravity_align, cliff_detect, pipeline
- `vslam_slam` (P6, default **OFF**) — RTAB-Map wrapper, occupancy export, sensor data builder
- `vslam_sim` (ON) — Gazebo-world reader, occupancy map I/O, sim source
- Dependency graph and rationale: libs/CMakeLists.txt:1-13
- Launch/config locations: no launch files. Wiring is code: `app/src/wiring.cc` is the single place sources connect to stages (app/CMakeLists.txt:4-5, docs/RUNTIME.md). Runtime config: `configuration_files/` — `robot.yaml`, `sensors.yaml`, `pipeline.yaml`, `slam.yaml`, `safety.yaml`, `system.yaml`, plus `master.dcf` (CANopen, generated by `dcfgen`).
- Source locations: `libs/<lib>/{include/vslam,src}`, `app/src`, `tools/`, vendored SDKs in `libs/vslam_drivers/thirdparty/` (`lakibeam_sdk`, `lidar_core`, `zlac` — copied from `base_kit`, see thirdparty/PROVENANCE.md)
- Test locations: `test/` — GTest binaries, node-level config tests, JS tests in `test/www/`; fixtures in `test/data/`, tolerance baselines in `test/expected/` (12 scenario JSONs)
- Documentation locations: `README.md` (~1000 lines, operational guide), `docs/RUNTIME.md`, `docs/PERCEPTION.md`, `docs/SLAM.md`, `docs/REGRESSION.md`. Config files themselves carry extensive rationale comments — treat them as primary docs.
## Runtime Interfaces
- 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<T>` (libs/vslam_common/include/vslam/channel.h) replaces pub/sub. External surface is HTTP/WebSocket on port 8080 — e.g. `GET /api/world.bin` (README.md:133-135). Binary WS frame types: 1 scan, 2 cloud, 3 map_full, 4 **retired** (was map_patch, removed 2026-09-23), 5 path, 6 world_map, 7 voxel_full (chunked), 8 voxel_delta. Types 7/8 carry the accumulated 3D map as a voxel-hashed index set at 0.05 m; the browser renders it as a POINT CLOUD, not as boxes; token auth is asymmetric by design: engage e-stop needs no token, release e-stop / bumper reset require one (configuration_files/system.yaml `web.auth_token`).
- Services / Actions: none.
- 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.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` (code default false; slam.yaml currently true) is the 3D scanned-cloud switch: true sends depth into RTAB-Map (stored in the DB) and turns on the voxel map, but does NOT touch Grid/* — the grid stays 2D, LiDAR-only. The voxel map is built outside `process()` from each node's depth (cached per node id, max 40 new nodes per export). Changed 2026-09-24: the old Grid/Sensor=2 + Grid/3D=true path raised sim pose error vs ground truth from 0.009 m to 0.06-0.11 m
- `system.yaml`: web port 8080, status/scan 10 Hz, cloud 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. `<repo>/resources/maps/` from the source tree. `{stamp}` anywhere in the path expands to `%Y%m%d_%H%M%S` (one value per call). Absolute paths are used as-is; `""` still means a RAM-only DB. The parent directory is created for mapping runs only. All of this lives in `RtabmapSlam::Init`, deliberately NOT on the `--check` path.
- TF frames: own `TransformTree`, no tf2. Tree (node_constants.h:44-56, robot.yaml):
`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: 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: 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 **confirmed** by field data (2026-09-23, see Verification Notes).
## CV And AI
- Models: **no learned models in this repo.** No `.onnx`/`.pt`/`.trt`/`.engine`/`.tflite` files exist. `resources/model_colors.json` is a Gazebo *model* color lookup table (median texture color per mesh), generated by `tools/gen_model_colors.py` — not an ML model.
- 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.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
All commands below are transcribed from README.md / CMakePresets.json / docs — **not executed during onboarding**. Run them yourself before relying on the outcomes.
- Environment prerequisite (dev x86): `source tools/dev_env.sh` removes `/opt/MVS` from `LD_LIBRARY_PATH`. The Hikvision MVS SDK ships an old libusb missing `libusb_set_option`, which breaks any link against `libpcl_io`. CMakeLists.txt:59-88 turns this into a FATAL configure error when SLAM or perception is enabled. Also export `VSLAM_CONFIG_DIR=$PWD/configuration_files` and `VSLAM_RESOURCE_DIR=$PWD/resources` when running from the source tree.
- Build command: `cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVSLAM_BUILD_APP=ON -DVSLAM_BUILD_SLAM=ON` then `cmake --build build -j`. Presets: `cmake --preset dev|asan|tsan|jetson`. Optional: `-DVSLAM_WITH_REALSENSE=ON`, `-DVSLAM_WITH_CANOPEN=ON`. `-DVSLAM_BUILD_SLAM=OFF` still builds and runs everything else.
- Test command: `(cd build && ctest)` (README claims 37 tests); `./tools/regress.sh` (12 replay scenarios, README claims ~3 s); `./build/app/vslam_node --check` (config check only, then exit). ThreadSanitizer recipe in docs/RUNTIME.md; `ctest --test-dir build-tsan -LE condvar`.
- Lint command: Unknown / needs confirmation — no `.clang-format`, `.clang-tidy`, or CI configuration in the repo. `tools/pre-push` (install manually as a git hook) runs the regression suite, not a linter.
- Launch examples:
- `./build/app/vslam_node --sim --token t` then open `http://localhost:8080/?token=t`
- `./build/app/vslam_node --sim --world ../vSLAM_ws/src/robot_sim/worlds/hospital.world --x 1.03 --y -25.07 --token t` (that start pose has 4.75 m clearance; origin does not)
- `./build/app/vslam_node --sim --map test/data/maps/hospital.yaml --x -5.99 --y -2.91 --token t`
- Mapping: add `--slam --slam-db <NEW path> --slam-mode mapping`. The DB path must be new every run — mapping into an existing DB is refused at startup (RTAB-Map 0.21.13 throws `UNIQUE constraint failed: Statistics.id` every frame).
- `--live` requires a CANopen build; without it the node refuses to start with an actionable message (app/src/runtime.cc:137-146).
- Bag playback examples: no rosbag. Custom `.vsr` record format —
- record: `./build/tools/vslam_record ...` / `./tools/regress.sh --record`
- replay: `./build/app/vslam_node --replay FILE.vsr`, or `./build/tools/vslam_replay` for flat JSON output compared against `test/expected/` by tolerance
- `.vsr` files are gitignored (~55 MB), regenerated on demand
## Verification Notes
- 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 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` 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. (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 scanned cloud (`camera_3d: true`) produced frames in sim on 2026-09-24 with the OLD Grid/3D path; the depth-per-node path that replaced it is not yet run (sim or hardware). Not on hardware at all. Three numbers in it are reasoned estimates, not measurements: `voxel.emit_size_m` 0.05, `voxel.delta_max_ratio` 0.35, and the 300k `max_cells` ceiling. The full-sync burst (2 x 32 kB x 10 Hz = 655 kB/s) also exceeds the documented 120 kB/s UI budget for 1-3 s per joining client — deliberate, but unmeasured on Jetson WiFi. Also unmeasured: RAM/CPU cost of `Grid/3D=true` with ray tracing left ON (kept on deliberately — turning it off empties the 2D free-space map).