This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

75
tools/CMakeLists.txt Normal file
View File

@@ -0,0 +1,75 @@
# Cong cu chan doan va do dac. Thay cho 18 script Python trong slam_eval/.
# probe_rtabmap: kiem RUI RO R1 -- API dung occupancy grid cua RTAB-Map co
# dung la public va export day du khong. Chay o P0, TRUOC khi viet vslam_slam,
# vi neu khong thi phai doi sang duong du phong (tu dung grid tu
# getLocalOptimizedPoses() + scan luu trong DB).
option(VSLAM_BUILD_PROBE_RTABMAP "Build tools/probe_rtabmap (can RTAB-Map)" OFF)
if(VSLAM_BUILD_PROBE_RTABMAP)
find_package(RTABMap REQUIRED)
add_executable(probe_rtabmap probe_rtabmap.cc)
target_link_libraries(probe_rtabmap PRIVATE rtabmap::core vslam_common)
endif()
# vslam_web_demo: tieu chi nghiem thu P1. Chay web UI bang du lieu gia, khong
# can phan cung -- tach viec kiem chung tang hien thi khoi tang cam bien.
if(VSLAM_BUILD_WEB)
add_executable(vslam_web_demo vslam_web_demo.cc)
target_link_libraries(vslam_web_demo PRIVATE vslam_web vslam_common)
endif()
# vslam_sim_run: mo phong + web UI trong mot tien trinh. Thay cho
# `roslaunch robot_bringup sim.launch` + Gazebo GUI + RViz.
# Can ca vslam_odometry: mo phong chay DUONG ODOMETRY THAT (encoder ->
# wheel_odom -> EKF), khong phai hien thi ground truth.
if(VSLAM_BUILD_SIM AND VSLAM_BUILD_WEB AND VSLAM_BUILD_ODOMETRY
AND VSLAM_BUILD_SAFETY AND VSLAM_BUILD_PERCEPTION)
add_executable(vslam_sim_run vslam_sim_run.cc)
target_link_libraries(vslam_sim_run
PRIVATE vslam_sim vslam_web vslam_odometry vslam_safety vslam_perception
vslam_common)
endif()
# vslam_slam_bench: chay lai session trong DB RTAB-Map qua wrapper cua ta.
# Corpus `../vSLAM_ws/maps/*.db` dung duoc NGAY, truoc khi phan cung chay lan
# nao -- moi node co scan + odom + pose da toi uu.
if(VSLAM_BUILD_SLAM)
add_executable(vslam_slam_bench vslam_slam_bench.cc)
# vslam_sim chi de lay SaveOccupancyMap (PGM+YAML). No khong keo dep nang
# nao ngoai vslam_common, va nho no ban do xuat ra dung duoc NGAY voi
# `vslam_node --sim --map`.
target_link_libraries(vslam_slam_bench PRIVATE vslam_slam vslam_sim vslam_common)
endif()
# vslam_record: ghi .vsr tu bo mo phong theo kich ban co ten. Hat giong co
# dinh => cung kich ban cho cung file, byte giong byte -- dieu kien de
# regress.sh so ket qua duoc.
if(VSLAM_BUILD_SIM AND VSLAM_BUILD_DRIVERS)
add_executable(vslam_record vslam_record.cc)
target_link_libraries(vslam_record PRIVATE vslam_sim vslam_drivers vslam_common)
endif()
# vslam_replay: phat lai .vsr qua TOAN BO duong ong roi xuat JSON phang.
# `ReplaySource` implement chinh cac interface driver, nen khong co nhanh
# `if (replay)` nao trong logic -- day la loi ich lon nhat cua interface +
# factory.
if(VSLAM_BUILD_DRIVERS AND VSLAM_BUILD_ODOMETRY AND VSLAM_BUILD_SAFETY
AND VSLAM_BUILD_PERCEPTION)
add_executable(vslam_replay vslam_replay.cc)
target_link_libraries(vslam_replay
PRIVATE vslam_drivers vslam_odometry vslam_safety vslam_perception vslam_common)
endif()
# vslam_lidar_probe: nghe UDP va SUY RA cau truc goi cua LiDAR.
#
# Khong phu thuoc lib nao cua du an -- chi socket POSIX. Co y: no phai chay
# duoc tren mot may chi co mang toi LiDAR, khong can build ca cay.
add_executable(vslam_lidar_probe vslam_lidar_probe.cc)
# vslam_world_export: `.world` cua Gazebo -> luoi chiem dung .pgm + .yaml.
#
# Cho phep dung the gioi mo phong TU CHINH file world, thay vi tu mot .db da
# quet -- nho vay luoi, mesh 3D va tu the do dac deu o MOT he toa do.
add_executable(vslam_world_export vslam_world_export.cc)
target_link_libraries(vslam_world_export PRIVATE vslam_sim vslam_common)

54
tools/dev_env.sh Executable file
View File

@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Moi truong phat trien cho may dev x86 (Ubuntu 20.04).
#
# CHI can tren may dev nay. Jetson khong can -- no khong co /opt/MVS.
#
# source tools/dev_env.sh
#
# Viec duy nhat no lam: go /opt/MVS khoi LD_LIBRARY_PATH.
#
# Vi sao: SDK camera Hikvision MVS tu chen /opt/MVS/lib/64 vao LD_LIBRARY_PATH
# trong ca ~/.bashrc lan ~/.profile (hien co 6 lan trong bien do). Thu muc do
# chua mot ban libusb-1.0.so.0 CU thieu ky hieu libusb_set_option, trong khi
# libpcl_io cua he thong can ky hieu do.
#
# Trieu chung luc LINK:
# /usr/bin/ld: /usr/lib/x86_64-linux-gnu/libpcl_io.so:
# undefined reference to `libusb_set_option'
#
# Trieu chung luc CHAY (day la dang ma repo ROS cu gap):
# symbol lookup error: libpcl_io.so.1.10: undefined symbol: libusb_set_option
#
# Doi prepend thanh append KHONG cuu duoc: LD_LIBRARY_PATH luon duoc tim truoc
# cache ldconfig, nen chi can /opt/MVS con trong bien do la no van thang thu
# vien he thong. Phai go han.
#
# MVS van dung binh thuong o cac shell khac.
_vslam_strip_mvs() {
local out=""
local IFS=':'
for p in $LD_LIBRARY_PATH; do
case "$p" in
/opt/MVS/*) continue ;;
"") continue ;;
esac
# bo trung lap luon -- bien nay dang co 6 ban sao cua cung mot duong dan
case ":$out:" in
*":$p:"*) continue ;;
esac
out="${out:+$out:}$p"
done
export LD_LIBRARY_PATH="$out"
}
_vslam_strip_mvs
unset -f _vslam_strip_mvs
echo "dev_env: LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-<rong>}"
if [ -n "${LD_LIBRARY_PATH##*MVS*}" ] || [ -z "$LD_LIBRARY_PATH" ]; then
echo "dev_env: da go /opt/MVS -- link duoc libpcl_io"
else
echo "dev_env: CANH BAO /opt/MVS van con trong LD_LIBRARY_PATH" >&2
fi

75
tools/gen_model_colors.py Normal file
View File

@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Sinh bang mau cho tung model Gazebo tu chinh texture cua no.
VI SAO CAN: khung 3D khong tai duoc texture -- 149 file PNG cua bo model nay
tong cong 74 MB, gui qua LAN moi lan mo trang la khong chap nhan duoc. Nhung
mau thi PHAI dung, vi nguoi dung so sanh truc tiep voi Gazebo.
Mau khong lay tu `<diffuse>` cua DAE hay `Kd` cua MTL: ca hai deu tro toi
texture hoac tra ve 0.8 0.8 0.8 xam -- mau that nam TRONG anh.
Lay TRUNG VI chu khong phai trung binh: nhieu texture co vien alpha va vet
logo sam mau, trung binh bi keo lech; trung vi giu dung mau than vat the.
python3 tools/gen_model_colors.py ~/gazebo_models > resources/model_colors.json
"""
import json
import os
import sys
import numpy as np
from PIL import Image
SKIP = ("_normal", "_norm", "_spec", "_rough", "_metal", "_ao", "_occlusion")
def model_color(mesh_dir):
px = []
for fn in sorted(os.listdir(mesh_dir)):
low = fn.lower()
if not low.endswith(".png") or any(s in low for s in SKIP):
continue
try:
im = Image.open(os.path.join(mesh_dir, fn)).convert("RGBA")
except Exception:
continue
im = im.resize((32, 32), Image.BILINEAR)
a = np.asarray(im, dtype=np.int16).reshape(-1, 4)
px.append(a[a[:, 3] > 128][:, :3])
if not px:
return None
all_px = np.concatenate(px, axis=0)
if all_px.size == 0:
return None
return [int(v) for v in np.median(all_px, axis=0)]
def main():
roots = sys.argv[1:] or [os.path.expanduser("~/gazebo_models")]
out = {}
for root in roots:
for dirpath, dirnames, _ in os.walk(root):
base = os.path.basename(dirpath)
# Hai quy uoc cung ton tai trong bo nay: texture nam trong
# `meshes/` (kieu Fuel) hoac `materials/textures/` (kieu Gazebo
# co). `thumbnails/` PHAI bo qua -- do la anh chup ca model tren
# nen xam, lay mau tu do ra xam het.
if base == "meshes":
owner = os.path.dirname(dirpath)
elif base == "textures" and os.path.basename(
os.path.dirname(dirpath)) == "materials":
owner = os.path.dirname(os.path.dirname(dirpath))
else:
continue
dirnames[:] = []
name = os.path.basename(owner)
c = model_color(dirpath)
if c is not None and name not in out:
out[name] = c
json.dump(out, sys.stdout, indent=0, sort_keys=True)
sys.stdout.write("\n")
print("%d model co mau" % len(out), file=sys.stderr)
if __name__ == "__main__":
main()

28
tools/pre-push Executable file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Git pre-push hook: chay bo hoi quy truoc khi day.
#
# CAI DAT (khi repo da co .git):
# ln -s ../../tools/pre-push .git/hooks/pre-push
#
# Bo qua mot lan: git push --no-verify
#
# Hook nay CHI chay lai ban ghi co san; no khong ghi lai .vsr. Neu ban vua
# doi bo mo phong thi phai tu chay `tools/regress.sh --record --bless` va
# DOC ky hieu so thay doi truoc khi commit file ky vong moi.
set -e
ROOT=$(git rev-parse --show-toplevel)
cd "$ROOT"
if [ ! -x build/tools/vslam_replay ]; then
echo "pre-push: chua build vslam_replay -- bo qua bo hoi quy" >&2
exit 0
fi
# Ban ghi khong nam trong git (55 MB). Khong co thi sinh lai -- tat dinh.
if [ -z "$(ls test/data/vsr/*.vsr 2>/dev/null)" ]; then
echo "pre-push: chua co ban ghi, dang sinh lai..."
./tools/regress.sh --record >/dev/null || exit 1
fi
exec ./tools/regress.sh

188
tools/probe_rtabmap.cc Normal file
View File

@@ -0,0 +1,188 @@
// probe_rtabmap -- kiem RUI RO R1 va R2 truoc khi viet vslam_slam.
//
// R1: API dung occupancy grid cua RTAB-Map co public va export day du khong?
// Da xac nhan o muc HEADER rang bon thu sau deu public va mang
// RTABMAP_CORE_EXPORT:
// LocalGridCache::add(nodeId, ground, obstacles, empty, cellSize, viewPoint)
// OccupancyGrid(const LocalGridCache*, const ParametersMap&)
// GlobalMap::update(const std::map<int, Transform>& poses) -> bool
// OccupancyGrid::getMap(float& xMin, float& yMin) -> cv::Mat
// Chuong trinh nay xac nhan o muc LINK va RUNTIME: mo .db that, doc local
// grid tung node qua DBDriver::getNodeData(), dung grid, in kich thuoc.
//
// Neu that bai thi duong du phong la tu dung grid tu laser scan luu trong
// DB -- kha thi vi cau hinh hien tai dat Grid/Sensor=false, nghia la grid
// von da chi dung tu laser scan chu khong tu depth.
//
// R2: optimizer nao thuc su kha dung trong .so da cai. Quyet dinh bo GTSAM va
// dung g2o (Optimizer/Strategy=1) phu thuoc vao cau tra loi nay.
//
// Cach chay:
// ./probe_rtabmap ../vSLAM_ws/maps/map_house.db
#include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/LocalGrid.h>
#include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/global_map/OccupancyGrid.h>
#include <rtabmap/utilite/UStl.h>
#include <cstdio>
#include <map>
#include <set>
#include <string>
int main(int argc, char** argv) {
if (argc < 2) {
std::fprintf(stderr, "cach dung: %s <duong_dan.db> [so_node_toi_da]\n", argv[0]);
return 2;
}
const std::string db_path = argv[1];
const int max_nodes = argc > 2 ? std::atoi(argv[2]) : 0; // 0 = tat ca
// --- R2: optimizer kha dung -------------------------------------------
std::printf("optimizer kha dung trong librtabmap_core da cai:\n");
std::printf(" TORO =%d\n", rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeTORO) ? 1 : 0);
std::printf(" g2o =%d <- ke hoach dung cai nay (Optimizer/Strategy=1)\n",
rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeG2O) ? 1 : 0);
std::printf(" GTSAM=%d <- ke hoach BO cai nay (khong co apt arm64)\n",
rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeGTSAM) ? 1 : 0);
std::printf(" Ceres=%d\n", rtabmap::Optimizer::isAvailable(rtabmap::Optimizer::kTypeCeres) ? 1 : 0);
std::printf("\n");
// --- Mo DB -------------------------------------------------------------
rtabmap::DBDriver* driver = rtabmap::DBDriver::create();
if (driver == nullptr || !driver->openConnection(db_path)) {
std::fprintf(stderr, "khong mo duoc DB: %s\n", db_path.c_str());
delete driver;
return 1;
}
std::printf("mo DB OK: %s\n", db_path.c_str());
// --- Pose da toi uu ----------------------------------------------------
const std::map<int, rtabmap::Transform> poses = driver->loadOptimizedPoses();
std::printf("pose da toi uu: %zu\n", poses.size());
if (poses.empty()) {
std::fprintf(stderr, "DB khong co pose toi uu\n");
delete driver;
return 1;
}
// --- R1: nap local grid tu tung node -----------------------------------
rtabmap::LocalGridCache cache;
size_t with_grid = 0, without_grid = 0;
int n = 0;
for (const auto& kv : poses) {
if (max_nodes > 0 && n >= max_nodes) break;
++n;
rtabmap::SensorData data;
// Chi lay occupancy grid: images=false, scan=false, userData=false.
// Doc ca anh depth cua map_hospital.db (1.8 GB) se ngon het RAM.
driver->getNodeData(kv.first, data, /*images=*/false, /*scan=*/false,
/*userData=*/false, /*occupancyGrid=*/true);
// RTAB-Map luu du lieu DA NEN trong DB. gridGroundCellsRaw() tra ma tran
// RONG cho toi khi giai nen -- day la bay de mac phai va no im lang:
// khong loi, khong canh bao, chi la khong co du lieu.
//
// Dung uncompressDataConst voi ba con tro grid va de nullptr cho anh, de
// KHONG giai nen 119 MB anh depth ma minh khong can.
cv::Mat ground, obstacles, empty;
data.uncompressDataConst(/*imageRaw=*/nullptr, /*depthOrRightRaw=*/nullptr,
/*laserScanRaw=*/nullptr, /*userDataRaw=*/nullptr,
&ground, &obstacles, &empty);
if (ground.empty() && obstacles.empty() && empty.empty()) {
++without_grid;
continue;
}
cache.add(kv.first, ground, obstacles, empty, data.gridCellSize(),
data.gridViewPoint());
++with_grid;
}
std::printf("node co local grid: %zu / khong co: %zu (da quet %d)\n",
with_grid, without_grid, n);
std::printf("LocalGridCache::size() = %zu, bo nho = %lu byte\n", cache.size(),
cache.getMemoryUsed());
if (cache.empty()) {
std::fprintf(stderr,
"KHONG co local grid nao trong DB -- phai dung duong du phong "
"(tu dung grid tu laser scan)\n");
delete driver;
return 3;
}
// --- Dung OccupancyGrid ------------------------------------------------
// Tham so khop voi rtabmap.launch:330-334 cua repo cu.
rtabmap::ParametersMap params;
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridCellSize(), "0.05"));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGrid3D(), "false"));
params.insert(rtabmap::ParametersPair(rtabmap::Parameters::kGridRangeMax(), "12.0"));
rtabmap::OccupancyGrid grid(&cache, params);
const bool changed = grid.update(poses);
std::printf("OccupancyGrid::update() -> %s\n", changed ? "co doi" : "khong doi");
float x_min = 0.0f, y_min = 0.0f;
const cv::Mat map = grid.getMap(x_min, y_min);
if (map.empty()) {
std::fprintf(stderr, "getMap() tra ma tran rong\n");
delete driver;
return 4;
}
std::printf("getMap(): %dx%d, kieu=%d, origin=(%.3f, %.3f), cellSize=%.3f\n",
map.cols, map.rows, map.type(), x_min, y_min, grid.getCellSize());
// Dem o theo tung loai -- kiem quy uoc gia tri truoc khi viet occupancy_export.
// RTAB-Map dung -1 chua biet, 0 trong, 100 bi chiem (giong nav_msgs).
int unknown = 0, free_c = 0, occ = 0, other = 0;
for (int r = 0; r < map.rows; ++r) {
for (int c = 0; c < map.cols; ++c) {
const signed char v = map.at<signed char>(r, c);
if (v == -1) ++unknown;
else if (v == 0) ++free_c;
else if (v == 100) ++occ;
else ++other;
}
}
const double total = static_cast<double>(map.rows) * map.cols;
std::printf("o: chua biet=%d (%.1f%%) trong=%d bi chiem=%d khac=%d\n", unknown,
100.0 * unknown / total, free_c, occ, other);
// --- Do RLE that, phuc vu thiet ke binary codec cua web (P1) -----------
// Ma hoa hang-chinh, moi run la {u16 count, i8 value} = 3 byte.
// count la u16 nen run > 65535 phai tach.
size_t runs = 0;
{
signed char prev = 0;
bool first = true;
long run_len = 0;
for (int r = 0; r < map.rows; ++r) {
for (int c = 0; c < map.cols; ++c) {
const signed char v = map.at<signed char>(r, c);
if (first) { prev = v; run_len = 1; first = false; continue; }
if (v == prev && run_len < 65535) { ++run_len; continue; }
++runs;
prev = v;
run_len = 1;
}
}
if (!first) ++runs;
}
const size_t rle_bytes = runs * 3;
const size_t raw_bytes = static_cast<size_t>(map.rows) * map.cols;
std::printf("RLE: %zu run -> %zu byte (tho %zu byte, ti le %.2fx)\n", runs,
rle_bytes, raw_bytes,
rle_bytes > 0 ? static_cast<double>(raw_bytes) / rle_bytes : 0.0);
std::printf("-> mot lan gui MAP_FULL qua WebSocket: %.1f kB\n", rle_bytes / 1024.0);
delete driver;
std::printf("\nR1 DA GO: duong dung grid qua LocalGridCache + OccupancyGrid chay duoc.\n");
return 0;
}

113
tools/regress.sh Executable file
View File

@@ -0,0 +1,113 @@
#!/usr/bin/env bash
# Bo hoi quy: phat lai moi ban ghi .vsr qua toan bo duong ong, so ket qua voi
# file ky vong theo DUNG SAI.
#
# ============ VI SAO DUNG SAI CHU KHONG PHAI SO SANH VAN BAN ============
# So dem phai khop TUYET DOI -- lech mot khung nghia la duong di qua code da
# doi. Con pose thi khong bao gio khop bit-for-bit qua cac muc toi uu hoa hay
# cac phien ban libm. Dung sai theo tien to khoa nam trong vslam_replay.cc.
#
# ============ CACH DUNG ============
# tools/regress.sh chay va so voi ky vong
# tools/regress.sh --bless GHI DE ky vong bang ket qua hien tai
# tools/regress.sh --record ghi lai .vsr tu bo mo phong truoc khi chay
#
# --bless chi dung khi da DOC ky hieu so thay doi va xac nhan la dung. No xoa
# sach gia tri cua ca bo hoi quy.
set -u
cd "$(dirname "$0")/.."
ROOT=$(pwd)
BUILD=${VSLAM_BUILD_DIR:-build}
VSR_DIR=${VSLAM_VSR_DIR:-test/data/vsr}
EXP_DIR=${VSLAM_EXPECTED_DIR:-test/expected}
RECORD=0
BLESS=0
for a in "$@"; do
case "$a" in
--bless) BLESS=1 ;;
--record) RECORD=1 ;;
--help) sed -n '2,20p' "$0"; exit 0 ;;
*) echo "tham so la: $a" >&2; exit 2 ;;
esac
done
REPLAY="$BUILD/tools/vslam_replay"
RECORDER="$BUILD/tools/vslam_record"
if [ ! -x "$REPLAY" ]; then
echo "khong thay $REPLAY -- build truoc da" >&2
exit 2
fi
# /opt/MVS chen mot libusb cu thieu libusb_set_option vao LD_LIBRARY_PATH va
# lam hong moi lien ket toi libpcl_io. Xem tools/dev_env.sh.
# shellcheck disable=SC1091
[ -f tools/dev_env.sh ] && . tools/dev_env.sh >/dev/null 2>&1
# Chay tu CAY NGUON: lay config o day chu khong o /etc/vslam. Khong dat thi
# bo hoi quy chay voi config da CAI, tuc la no kiem mot phien ban khac voi
# cai dang sua.
export VSLAM_CONFIG_DIR=${VSLAM_CONFIG_DIR:-$ROOT/configuration_files}
if [ "$RECORD" = "1" ]; then
echo "== ghi lai ban ghi =="
mkdir -p "$VSR_DIR"
"$RECORDER" --scenario all --out-dir "$VSR_DIR" 2>&1 | grep -vE "INFO|WARN" || exit 1
echo
fi
mkdir -p "$EXP_DIR"
shopt -s nullglob
FILES=("$VSR_DIR"/*.vsr)
if [ ${#FILES[@]} -eq 0 ]; then
echo "khong co ban ghi nao trong $VSR_DIR -- chay voi --record" >&2
exit 2
fi
START=$(date +%s)
PASS=0
FAIL=0
FAILED_NAMES=""
for f in "${FILES[@]}"; do
name=$(basename "$f" .vsr)
exp="$EXP_DIR/$name.json"
if [ "$BLESS" = "1" ] || [ ! -f "$exp" ]; then
if "$REPLAY" --in "$f" --emit "$exp" --quiet 2>/dev/null; then
echo " GHI $name -> $exp"
PASS=$((PASS + 1))
else
echo " LOI $name (replay that bai)"
FAIL=$((FAIL + 1)); FAILED_NAMES="$FAILED_NAMES $name"
fi
continue
fi
if out=$("$REPLAY" --in "$f" --expect "$exp" --quiet 2>&1); then
echo " OK $name"
PASS=$((PASS + 1))
else
echo " HONG $name"
echo "$out" | sed 's/^/ /'
FAIL=$((FAIL + 1)); FAILED_NAMES="$FAILED_NAMES $name"
fi
done
ELAPSED=$(( $(date +%s) - START ))
echo
echo "== $PASS dat, $FAIL hong, $ELAPSED s =="
# Chi tieu P7: ca bo phai chay duoi 5 phut, neu khong khong ai gan vao
# pre-push va no chet dan.
if [ "$ELAPSED" -gt 300 ]; then
echo "CANH BAO: $ELAPSED s > 300 s -- qua cham de gan vao pre-push" >&2
fi
if [ "$FAIL" -gt 0 ]; then
echo "hong:$FAILED_NAMES" >&2
exit 1
fi
exit 0

75
tools/tsan_check.sh Executable file
View File

@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Chay vslam_node duoi ThreadSanitizer roi PHAN LOAI canh bao theo CHU SO HUU.
#
# ============ VI SAO CAN SCRIPT NAY ============
# Khi bat SLAM, RTAB-Map tu sinh luong rieng (`UThread::start()`) va cac luong
# do tranh chap tren du lieu cua CHINH NO. TSan bao het, va `called_from_lib:`
# khong bit duoc: no loc theo thu vien GOI, con day la race giua hai luong
# BEN TRONG thu vien tren heap ma thu vien tu cap phat.
#
# Nen thay vi giau chung, script nay TACH chung ra. Cau hoi duy nhat dang tra
# loi la: co canh bao nao cham vao mutex hay du lieu CUA TA khong?
#
# Quy tac song con dang duoc kiem:
# luong `safety` KHONG chia se mutex nao voi luong `slam`.
# `Rtabmap::process()` chan 100-600 ms; mot mutex chung la du de treo vong an
# toan trong ngan do. Trong ban ROS dieu nay duoc bao dam mien phi boi tien
# trinh rieng; o day chi TSan kiem duoc.
#
# Cach dung: tools/tsan_check.sh [giay] [them tham so cho vslam_node...]
set -u
cd "$(dirname "$0")/.."
ROOT=$(pwd)
SECS=${1:-30}
shift || true
BIN=build-tsan/app/vslam_node
if [ ! -x "$BIN" ]; then
echo "khong thay $BIN. Build truoc -- xem docs/RUNTIME.md muc ThreadSanitizer." >&2
exit 2
fi
# shellcheck disable=SC1091
[ -f tools/dev_env.sh ] && . tools/dev_env.sh >/dev/null 2>&1
export VSLAM_CONFIG_DIR=${VSLAM_CONFIG_DIR:-$ROOT/configuration_files}
export TSAN_OPTIONS="halt_on_error=0 history_size=7 suppressions=$ROOT/test/tsan_suppressions.txt"
LOG=$(mktemp /tmp/vslam_tsan.XXXXXX.log)
echo "== chay $SECS s, log: $LOG =="
"$BIN" --sim "$@" >"$LOG" 2>&1 &
PID=$!
sleep "$SECS"
kill -INT "$PID" 2>/dev/null
sleep 5
kill -9 "$PID" 2>/dev/null
wait "$PID" 2>/dev/null
TOTAL=$(grep -c "WARNING: ThreadSanitizer" "$LOG" || true)
# Mutex cua ta. Mot canh bao cham vao bat ky ten nao o day la LOI THAT.
OURS=$(grep -cE "scan_mu_|odom_mu_|safety_mu_|slam_mu_|perc_mu_|cmd_mu_|teleop_mu_|traj_mu_" "$LOG" || true)
# Du lieu do RTAB-Map cap phat, tranh chap boi luong cua chinh no.
THIRD=$(grep -cE "UThread::start|ULogger::|UMutex::|librtabmap|libsqlite3|cv::Mat" "$LOG" || true)
echo
echo " tong canh bao : $TOTAL"
echo " cham mutex CUA TA : $OURS <-- phai la 0"
echo " quy ve RTAB-Map/OpenCV : $THIRD"
echo
if [ "$OURS" -ne 0 ]; then
echo "HONG: co canh bao cham vao mutex cua ta." >&2
grep -nE "scan_mu_|odom_mu_|safety_mu_|slam_mu_|perc_mu_|cmd_mu_|teleop_mu_|traj_mu_" "$LOG" | head -20 >&2
exit 1
fi
if [ "$TOTAL" -gt 0 ]; then
echo "Con $TOTAL canh bao, tat ca thuoc ben thu ba. Kiem lai bang:"
echo " grep -E 'Location is' $LOG | sort -u"
echo " grep -E 'Thread T[0-9]+ .* created by' -A3 $LOG | grep UThread"
fi
echo "DAT: khong canh bao nao cham vao dong bo cua ta."
exit 0

341
tools/vslam_lidar_probe.cc Normal file
View File

@@ -0,0 +1,341 @@
// Nghe UDP tu LiDAR va SUY RA cau truc goi.
//
// ================== VI SAO CAN CONG CU NAY ==================
// Driver LakiBeam thieu dung MOT thu: byte layout cua goi UDP. Moi thu khac
// da biet tu `richbeam.launch` cua repo cu -- UDP, host 192.168.198.2, port
// 2368, tham so `inverted` va `angle_offset`.
//
// Doan byte layout la cach chac chan nhat de tao ra mot ban do sai ma khong
// ai biet. Cong cu nay khong doan: no DO.
//
// ================== NO SUY RA DUOC GI ==================
// * kich thuoc goi (co dinh hay khong) va tan so goi
// * truong AZIMUTH: tim uint16 tang DEU DAN va quay vong -- goc quet chi co
// the la thu duy nhat co hanh vi do
// * so goi moi vong quet, suy ra tu diem azimuth quay ve dau
// * truong co gia tri gan nhu KHONG DOI giua cac goi (header, magic, id)
// * vung co phuong sai cao, lien tuc -> nhieu kha nang la mang range
//
// ================== CACH DUNG ==================
// tools/../build/tools/vslam_lidar_probe --port 2368 --seconds 5
// tools/../build/tools/vslam_lidar_probe --pcap capture.pcap (chua ho tro)
//
// Neu may khong noi duoc voi LiDAR, dung tcpdump roi gui file:
// sudo tcpdump -i eth0 udp port 2368 -w lakibeam.pcap -c 2000
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
namespace {
constexpr size_t kMaxPacket = 2048;
uint16_t RdLe16(const uint8_t* p) { return static_cast<uint16_t>(p[0] | (p[1] << 8)); }
uint16_t RdBe16(const uint8_t* p) { return static_cast<uint16_t>((p[0] << 8) | p[1]); }
void HexDump(const uint8_t* d, size_t n, size_t limit) {
const size_t m = std::min(n, limit);
for (size_t i = 0; i < m; i += 16) {
std::printf(" %04zu: ", i);
for (size_t j = 0; j < 16; ++j) {
if (i + j < m) std::printf("%02x ", d[i + j]);
else std::printf(" ");
}
std::printf(" |");
for (size_t j = 0; j < 16 && i + j < m; ++j) {
const uint8_t c = d[i + j];
std::putchar((c >= 32 && c < 127) ? c : '.');
}
std::printf("|\n");
}
if (n > m) std::printf(" ... con %zu byte\n", n - m);
}
// Mot truong ung vien o offset `off`, doc theo endianness `be`.
struct FieldStat {
size_t off = 0;
bool be = false;
uint64_t increases = 0; // so lan tang so voi goi truoc
uint64_t wraps = 0; // so lan tut manh (quay vong)
uint16_t min_v = 0xFFFF, max_v = 0;
bool constant = true;
uint16_t first = 0;
};
} // namespace
int main(int argc, char** argv) {
int port = 2368;
double seconds = 5.0;
std::string bind_ip = "0.0.0.0";
bool dump_first = true;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--port") port = std::atoi(next().c_str());
else if (a == "--seconds") seconds = std::atof(next().c_str());
else if (a == "--bind") bind_ip = next();
else if (a == "--no-dump") dump_first = false;
else if (a == "--help") {
std::printf(
"cach dung: %s [--port 2368] [--seconds 5] [--bind 0.0.0.0]\n\n"
"Nghe UDP va suy ra cau truc goi cua LiDAR.\n"
"Neu may nay khong noi duoc voi LiDAR:\n"
" sudo tcpdump -i eth0 udp port %d -w lakibeam.pcap -c 2000\n",
argv[0], port);
return 0;
}
}
const int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
std::perror("socket");
return 1;
}
int one = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
addr.sin_addr.s_addr = inet_addr(bind_ip.c_str());
if (::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
std::perror("bind");
::close(fd);
return 1;
}
timeval tv{};
tv.tv_sec = 1;
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
std::printf("nghe UDP %s:%d trong %.1f s...\n", bind_ip.c_str(), port, seconds);
std::vector<uint8_t> buf(kMaxPacket);
std::vector<std::vector<uint8_t>> packets;
std::map<size_t, uint64_t> size_hist;
std::vector<double> arrival;
const auto t0 = std::chrono::steady_clock::now();
while (std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count() <
seconds) {
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
if (n <= 0) continue;
size_hist[static_cast<size_t>(n)]++;
arrival.push_back(
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
// Giu toi da 400 goi: du de suy ra cau truc, khong du de an het RAM.
if (packets.size() < 400) {
packets.emplace_back(buf.begin(), buf.begin() + n);
}
}
::close(fd);
if (packets.empty()) {
std::printf(
"\nKHONG NHAN DUOC GOI NAO.\n"
" - LiDAR co cam va cap nguon chua?\n"
" - May nay co cung dai mang voi LiDAR chua? richbeam.launch cua repo\n"
" cu ghi hostip 192.168.198.2 -- kiem `ip addr` va `ping`.\n"
" - Firewall: `sudo iptables -L -n | grep %d`\n"
" - Thu tcpdump de xem goi co toi card mang khong:\n"
" sudo tcpdump -i any udp port %d -c 5\n",
port, port);
return 2;
}
// ================== 1. Kich thuoc va nhip ==================
std::printf("\n=== KICH THUOC GOI ===\n");
for (const auto& kv : size_hist) {
std::printf(" %5zu byte : %llu goi\n", kv.first,
static_cast<unsigned long long>(kv.second));
}
uint64_t total = 0;
for (const auto& kv : size_hist) total += kv.second;
std::printf(" tong %llu goi trong %.1f s = %.1f goi/s\n",
static_cast<unsigned long long>(total), seconds, total / seconds);
if (size_hist.size() > 1) {
std::printf(" ⚠️ NHIEU kich thuoc khac nhau -- co the co ca goi du lieu lan\n"
" goi trang thai/telemetry. Phan tich duoi day gop chung lai.\n");
}
const size_t plen = packets[0].size();
size_t same_len = 0;
for (const auto& p : packets) same_len += (p.size() == plen) ? 1 : 0;
if (dump_first) {
std::printf("\n=== GOI DAU TIEN (%zu byte) ===\n", plen);
HexDump(packets[0].data(), plen, 256);
if (packets.size() > 1) {
std::printf("\n=== GOI THU HAI ===\n");
HexDump(packets[1].data(), packets[1].size(), 128);
}
}
// ================== 2. Truong KHONG DOI ==================
// Header, magic, model id -- nhung thu giong nhau o moi goi.
std::printf("\n=== BYTE KHONG DOI GIUA CAC GOI ===\n");
std::string runs;
size_t const_start = 0;
bool in_run = false;
for (size_t i = 0; i < plen; ++i) {
bool same = true;
for (const auto& p : packets) {
if (p.size() != plen || p[i] != packets[0][i]) { same = false; break; }
}
if (same && !in_run) { in_run = true; const_start = i; }
if (!same && in_run) {
in_run = false;
if (i - const_start >= 2) {
char b[128];
std::snprintf(b, sizeof(b), " [%zu..%zu] %zu byte: ", const_start, i - 1,
i - const_start);
runs += b;
for (size_t j = const_start; j < i && j < const_start + 8; ++j) {
std::snprintf(b, sizeof(b), "%02x ", packets[0][j]);
runs += b;
}
runs += "\n";
}
}
}
std::printf("%s", runs.empty() ? " (khong co day nao >= 2 byte)\n" : runs.c_str());
// ================== 3. Truong AZIMUTH ==================
//
// Goc quet la thu DUY NHAT trong goi co hanh vi: tang deu dan roi quay vong
// ve dau. Quet moi offset, ca little- lan big-endian, dem so lan tang va so
// lan tut manh.
std::printf("\n=== UNG VIEN TRUONG GOC (azimuth) ===\n");
std::vector<FieldStat> cands;
for (size_t off = 0; off + 1 < plen; ++off) {
for (int e = 0; e < 2; ++e) {
FieldStat fs;
fs.off = off;
fs.be = (e == 1);
uint16_t prev = 0;
bool first = true;
size_t n = 0;
for (const auto& p : packets) {
if (p.size() != plen) continue;
const uint16_t v = fs.be ? RdBe16(&p[off]) : RdLe16(&p[off]);
fs.min_v = std::min(fs.min_v, v);
fs.max_v = std::max(fs.max_v, v);
if (first) { fs.first = v; first = false; }
else {
if (v != prev) fs.constant = false;
if (v > prev) fs.increases++;
else if (prev - v > 1000) fs.wraps++;
}
prev = v;
n++;
}
if (n < 10 || fs.constant) continue;
// Goc quet: TANG o hau het cac buoc, va quay vong it nhat mot lan neu
// ta bat du mot vong.
const double up = static_cast<double>(fs.increases) / (n - 1);
if (up > 0.80 && fs.wraps >= 1) cands.push_back(fs);
}
}
if (cands.empty()) {
std::printf(" (khong tim thay truong nao tang deu roi quay vong --\n"
" co the ban ghi ngan hon mot vong quet. Thu --seconds 10)\n");
}
for (const FieldStat& f : cands) {
const double span = static_cast<double>(f.max_v) - f.min_v;
std::printf(" offset %3zu %s: tang %llu lan, quay vong %llu lan, dai [%u..%u]\n",
f.off, f.be ? "BE" : "LE",
static_cast<unsigned long long>(f.increases),
static_cast<unsigned long long>(f.wraps), f.min_v, f.max_v);
// Don vi thuong gap: 1/100 do (Velodyne) hoac 1/1000 do.
if (f.max_v > 30000 && f.max_v <= 36000) {
std::printf(" -> dai ~36000: nhieu kha nang don vi 1/100 DO (0..359.99)\n");
} else if (f.max_v > 3000 && f.max_v <= 3600) {
std::printf(" -> dai ~3600: nhieu kha nang don vi 1/10 DO\n");
} else if (span > 60000) {
std::printf(" -> dai ~65535: co the la bo dem goi, KHONG phai goc\n");
}
}
// ================== 4. Vung du lieu ==================
//
// Mang range co phuong sai cao va lien tuc. Do phuong sai theo tung byte roi
// tim doan dai nhat vuot nguong.
std::printf("\n=== VUNG PHUONG SAI CAO (nhieu kha nang la mang range) ===\n");
std::vector<double> var(plen, 0.0);
for (size_t i = 0; i < plen; ++i) {
double mean = 0;
size_t n = 0;
for (const auto& p : packets) {
if (p.size() != plen) continue;
mean += p[i]; n++;
}
if (n == 0) continue;
mean /= n;
double s = 0;
for (const auto& p : packets) {
if (p.size() != plen) continue;
s += (p[i] - mean) * (p[i] - mean);
}
var[i] = std::sqrt(s / n);
}
size_t best_start = 0, best_len = 0, cur_start = 0, cur_len = 0;
for (size_t i = 0; i < plen; ++i) {
if (var[i] > 8.0) {
if (cur_len == 0) cur_start = i;
cur_len++;
if (cur_len > best_len) { best_len = cur_len; best_start = cur_start; }
} else {
cur_len = 0;
}
}
if (best_len >= 8) {
std::printf(" [%zu..%zu] dai %zu byte\n", best_start, best_start + best_len - 1,
best_len);
std::printf(" -> neu moi tia la uint16 thi doan nay chua %zu tia\n", best_len / 2);
std::printf(" -> neu moi tia la uint16 range + uint8 intensity (3 byte): %zu tia\n",
best_len / 3);
} else {
std::printf(" (khong tim thay doan lien tuc >= 8 byte)\n");
}
// ================== 5. Nhip ==================
if (arrival.size() > 10) {
std::vector<double> dt;
for (size_t i = 1; i < arrival.size(); ++i) dt.push_back(arrival[i] - arrival[i - 1]);
std::sort(dt.begin(), dt.end());
std::printf("\n=== NHIP GOI ===\n");
std::printf(" p50 %.3f ms, p95 %.3f ms, max %.3f ms\n", dt[dt.size() / 2] * 1e3,
dt[static_cast<size_t>(0.95 * (dt.size() - 1))] * 1e3,
dt.back() * 1e3);
if (!cands.empty()) {
const uint64_t w = cands[0].wraps;
if (w > 0) {
std::printf(" %llu vong quet trong %.1f s = %.2f Hz\n",
static_cast<unsigned long long>(w), seconds, w / seconds);
std::printf(" %.1f goi moi vong quet\n",
static_cast<double>(total) / static_cast<double>(w));
}
}
}
std::printf("\n=== BUOC TIEP ===\n");
std::printf(" Gui ket qua nay lai. Voi offset goc + vung range + so goi moi\n");
std::printf(" vong, ham giai ma goi viet duoc ngay.\n");
std::printf(" Neu %zu/%zu goi cung kich thuoc thi cau truc la CO DINH, de nhat.\n",
same_len, packets.size());
return 0;
}

313
tools/vslam_record.cc Normal file
View File

@@ -0,0 +1,313 @@
// Ghi ban ghi `.vsr` tu bo mo phong, theo kich ban co ten.
//
// ================== VI SAO GHI TU SIM ==================
// Chua co phan cung. Nhung bo hoi quy can du lieu CO DINH, va bo mo phong voi
// hat giong co dinh cho ra dung the: cung kich ban => cung file, byte giong
// byte. Khi co phan cung that, `vslam_record --live` ghi cung dinh dang va
// `vslam_replay` khong phan biet duoc hai nguon -- do la ca ly do
// `SimSource` implement chinh cac interface driver.
//
// Kich ban duoc chon de moi cai cham vao MOT duong ma cac cai khac khong
// cham: thang -> tich phan odometry; vuong -> sai so goc; truot -> phat hien
// truot; vuc -> perception + safety; tuong -> chan theo LiDAR; xoay -> cong
// vat can cua cliff_detect.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "vslam/driver_interfaces.h"
#include "vslam/record_format.h"
#include "vslam/record_io.h"
#include "vslam/sim_source.h"
namespace {
struct Leg {
double vx = 0.0;
double wz = 0.0;
double seconds = 0.0;
};
struct Scenario {
const char* name;
const char* what; // duong nao duoc cham toi
std::vector<Leg> legs;
double slip = 0.0;
double diff_slip = 0.0;
bool cliff = false;
float cliff_z = -0.40f;
// Anh depth chiem ~96% kich thuoc ban ghi. Chi bat camera o kich ban thuc
// su cham vao perception; cac kich ban odometry/safety khong can.
bool camera = false;
double camera_hz = 10.0;
double glass_at = 0.0; // 0 = khong dat kinh
double us_dropout = 0.0; // 1.0 = day sieu am dut han
bool no_us = false; // khong LAP sieu am (khac han "dut")
double lidar_cut_at = 0.0; // giay thu may thi "rut day" LiDAR
double lidar_cut_for = 0.0;
double start_x = 0.0, start_y = 0.0, start_yaw = 0.0;
};
std::vector<Scenario> Scenarios() {
return {
{"straight", "tich phan odometry, EKF, ScanSanitizer",
{{0.35, 0.0, 8.0}, {0.0, 0.0, 1.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
// Hanh lang tong hop rong 1.6 m -- KHONG lot mot hinh vuong 4x4 m.
// Bai vuong UMBmark can san trong; o day thay bang di-va-ve, van do
// duoc sai so goc tich luy ma khong dam vao tuong (dam tuong thi phep
// do thanh phep do cua LOP AN TOAN, khong phai cua odometry).
{"outback", "sai so goc tich luy: di 3 m, quay 180 do, ve",
{{0.30, 0.0, 10.0}, {0.0, 0.7, 4.49}, {0.30, 0.0, 10.0}, {0.0, 0.7, 4.49}},
0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, -4.0, 0, 0},
// Truot VI SAI: gyro thay lech giua hai banh -> phat hien duoc.
{"slip_diff", "phat hien truot bang gyro, covariance cua wheel_odom",
{{0.35, 0.0, 10.0}}, 0.0, 0.25, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
// Truot DOI XUNG: ca hai banh truot deu -> gyro KHONG thay gi.
// Kich ban nay ton tai de khoa mot GIOI HAN da biet, khong phai de
// chung minh he chay dung.
{"slip_sym", "gioi han: truot doi xung khong phat hien duoc",
{{0.35, 0.0, 10.0}}, 0.25, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
{"cliff", "cliff_detect + nhanh CLIFF_STOP cua FSM",
{{0.30, 0.0, 8.0}}, 0.0, 0.0, true, -0.40f, true, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
// Bat dau cach tuong cuoi hanh lang ~3 m de tia truoc nhin thay no
// ngay tu khung dau. Bat dau xa qua thi robot chi chay tu do het ban
// ghi va nhanh chan KHONG BAO GIO chay -- da do: 598/598 khung OK.
// Bac NONG, sat nguong. Nguong no ra theo tam:
// thr = z_ref - (cliff_margin + r * tan(pitch_unc))
// = 0.089 m o r = 1.1, va 0.137 m o r = 2.5. Mot bac 0.12 m nam GIUA
// hai gia tri do, nen no chi bi phat hien khi robot lai du gan.
//
// Kich ban nay ton tai vi bai `cliff` (bac 0.40 m) cho hang tram diem
// va KHONG nhay cam voi nguong: da thu doi `min_cluster` 12 -> 20, ca
// bo hoi quy van xanh. Mot bo hoi quy chi chay xa nguong thi khong bat
// duoc truot nguong.
{"cliff_shallow", "sat nguong: bac 0.12 m, chi thay khi den gan",
{{0.25, 0.0, 12.0}}, 0.0, 0.0, true, -0.12f, true, 10.0, 0, 0, 0},
// KINH: LiDAR va depth XUYEN QUA, chi sieu am thay. Day la ly do
// nhanh US_BLOCKED cua FSM ton tai, va truoc kich ban nay no CHUA BAO
// GIO chay end-to-end -- chi co unit test.
{"glass", "US_BLOCKED: kinh vo hinh voi LiDAR",
{{0.35, 0.0, 14.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 3.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
// Sieu am CHET (moi dau do tra NaN). Phai ra US_TIMEOUT, KHONG duoc
// coi nhu "khong thay gi".
{"us_dead", "US_TIMEOUT: day sieu am dut",
{{0.35, 0.0, 8.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 1.0, false, 0.0, 0.0, 0, 0, 0},
// KINH + KHONG LAP sieu am. Day la kich ban AC MONG: khong cam bien
// nao thay duoc buc kinh, va robot dam vao. No la ly do DUY NHAT
// nhanh BUMPER ton tai, va la bang chung vi sao sieu am khong phai do
// trang tri.
//
// Khac han `us_dead`: o day KHONG CO cam bien nao (map rong -> FSM bo
// qua ca hai nhanh US), con `us_dead` la co cam bien nhung chung chet
// (-> US_TIMEOUT, robot dung an toan).
{"glass_blind", "BUMPER: kinh + khong lap sieu am",
{{0.35, 0.0, 16.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 3.0, 0.0, true, 0.0, 0.0, 0, 0, 0},
// RUT DAY LiDAR o giay thu 4, trong 3 giay. Tieu chi P4 ghi
// "SCAN_TIMEOUT < 1.1 s"; day la cach do duoc no ma khong phai rut day
// that.
{"lidar_cut", "SCAN_TIMEOUT: mat LiDAR giua chung",
{{0.30, 0.0, 10.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false,
4.0, 3.0, 0, 0, 0},
{"wall", "chan theo LiDAR: SCAN_SLOW roi SCAN_STOP",
{{0.35, 0.0, 14.0}}, 0.0, 0.0, false, -0.40f, false, 10.0, 0.0, 0.0, false, 0.0, 0.0, 8.5, 0, 0},
// Quay tai cho trong hanh lang 1.6 m: cong `max_obstructed_frac` cua
// cliff_detect phai kich, va KHONG duoc bao vuc.
{"spin", "cong vat can cua cliff_detect trong hanh lang hep",
{{0.0, 1.0, 7.0}}, 0.0, 0.0, false, -0.40f, true, 10.0, 0.0, 0.0, false, 0.0, 0.0, 0, 0, 0},
};
}
} // namespace
int main(int argc, char** argv) {
std::string name, out_dir = ".";
bool list = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--scenario") name = next();
else if (a == "--out-dir") out_dir = next();
else if (a == "--list") list = true;
else if (a == "--help") {
std::printf("cach dung: %s --scenario TEN --out-dir D\n"
" %s --list\n"
" %s --scenario all --out-dir D\n", argv[0], argv[0], argv[0]);
return 0;
}
}
const std::vector<Scenario> all = Scenarios();
if (list || name.empty()) {
std::printf("kich ban:\n");
for (const Scenario& s : all) std::printf(" %-12s %s\n", s.name, s.what);
return name.empty() && !list ? 2 : 0;
}
int written = 0;
for (const Scenario& s : all) {
if (name != "all" && name != s.name) continue;
vslam::SimConfig cfg;
cfg.seed = 1234; // co dinh: cung kich ban => cung file
cfg.start_x = s.start_x;
cfg.start_y = s.start_y;
cfg.start_yaw = s.start_yaw;
cfg.slip_factor = s.slip;
cfg.slip_differential = s.diff_slip;
cfg.enable_depth_camera = s.camera;
cfg.us_dropout_rate = s.us_dropout;
cfg.enable_ultrasonic = !s.no_us;
cfg.lidar_cut_at = s.lidar_cut_at;
cfg.lidar_cut_for = s.lidar_cut_for;
cfg.camera_rate_hz = s.camera_hz;
vslam::SimSource sim(cfg);
if (!sim.Open().ok()) {
std::fprintf(stderr, "%s: sim khong mo duoc\n", s.name);
return 1;
}
if (s.glass_at != 0.0) {
// Kinh phai la o BI CHIEM: no la vat can THAT, chi la vat can ma
// LiDAR va depth khong thay.
vslam::OccupancyGrid m = sim.map();
const double res = m.resolution;
const int gcx = static_cast<int>((s.glass_at - m.origin.position.x) / res);
for (int cy = 0; cy < static_cast<int>(m.height); ++cy) {
if (gcx < 0 || gcx >= static_cast<int>(m.width)) break;
const size_t i = static_cast<size_t>(cy) * m.width + gcx;
if (m.data[i] == 0) m.data[i] = 100;
}
sim.SetMapForTest(m);
sim.SetGlass(s.glass_at - res, -50.0, s.glass_at + res, 50.0, true);
}
if (s.cliff) {
// Bac hut xuong 0.40 m o 4 m phia truoc: nam ngoai vung mu 1.10 m nen
// detector phai thay truoc khi robot toi.
sim.SetFloorHeight(4.0, -3.0, 20.0, 3.0, s.cliff_z);
}
const std::string path = out_dir + "/" + s.name + ".vsr";
vslam::RecordWriterConfig wc;
wc.path = path;
wc.compress = false; // nen = khong tat dinh giua cac phien ban zstd
wc.config_json = std::string("{\"scenario\":\"") + s.name + "\",\"seed\":1234}";
vslam::RecordWriter w(wc);
const vslam::StatusResponse st = w.Open();
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", path.c_str(), st.message.c_str());
return 1;
}
// Ghi THO: scan TRUOC sanitizer, imu, encoder. Dung nguyen tac cua
// topics_to_record.yaml cu.
// MOI bo dem MOT stream, va CLEAR truoc moi lan ma hoa.
//
// `Encode*Payload` NOI THEM vao `out` (xem record_format.h). Dung chung
// mot bo dem va khong xoa thi moi ban ghi to hon ban truoc: da lam ra mot
// file 17 GB cho mot kich ban 9 giay truoc khi phat hien.
std::string b_scan, b_imu, b_enc, b_info, b_depth;
sim.lidar()->SetCallback([&](vslam::LaserScanPtr sc) {
b_scan.clear();
vslam::EncodeScanPayload(*sc, &b_scan);
w.Write(vslam::VsrStream::kScanRaw, sc->header.stamp, b_scan);
});
sim.mcu()->SetImuCallback([&](vslam::ImuPtr m) {
b_imu.clear();
vslam::EncodeImuPayload(*m, &b_imu);
w.Write(vslam::VsrStream::kImu, m->header.stamp, b_imu);
});
std::string b_us, b_bump;
sim.mcu()->SetUltrasonicCallback([&](const vslam::UltrasonicReading& u) {
b_us.clear();
vslam::EncodeUltrasonicPayload(u.range, u.count, &b_us);
w.Write(vslam::VsrStream::kUltrasonic, u.stamp, b_us);
});
sim.mcu()->SetBumperCallback([&](const vslam::BumperReading& bm) {
b_bump.clear();
vslam::EncodeBumperPayload(bm.mask, &b_bump);
w.Write(vslam::VsrStream::kBumper, bm.stamp, b_bump);
});
sim.base()->SetEncoderCallback([&](const vslam::EncoderReading& e) {
if (!e.valid) return;
b_enc.clear();
vslam::EncodeEncoderPayload(e.left_rad, e.right_rad, &b_enc);
w.Write(vslam::VsrStream::kEncoder, e.stamp, b_enc);
});
if (sim.camera() != nullptr) {
sim.camera()->SetCallback([&](const vslam::CameraFrame& f) {
if (!f.depth) return;
b_info.clear();
vslam::EncodeCameraInfoPayload(f.depth_info, &b_info);
w.Write(vslam::VsrStream::kCameraInfo, f.header.stamp, b_info);
b_depth.clear();
vslam::EncodeImagePayload(*f.depth, &b_depth);
w.Write(vslam::VsrStream::kDepth, f.header.stamp, b_depth);
});
sim.camera()->Open();
}
sim.lidar()->Open();
sim.mcu()->Open();
sim.base()->Open();
// Chay theo CHANG, chia thanh lat 50 ms va PHAT LAI lenh truoc moi lat.
//
// Base cua bo mo phong co watchdog: khong co lenh trong 0.3 s thi no tu
// dung robot -- dung nhu base that, va dung nhu nhanh NO_CMD cua FSM.
// Dat van toc MOT lan roi chay 8 giay thi robot chi di duoc 0.3 giay:
// da do 0.026 m thay vi 2.5 m, va khong co gi bao loi vi day la hanh vi
// DUNG cua base.
//
// Phat lai o 20 Hz cung la dung cai ma luong safety lam tren robot that.
constexpr double kSlice = 0.05;
double total = 0.0;
for (const Leg& leg : s.legs) {
double left = leg.seconds;
while (left > 1e-9) {
const double dt = std::min(kSlice, left);
sim.base()->SetVelocity(leg.vx, leg.wz);
sim.RunFor(dt);
left -= dt;
}
total += leg.seconds;
}
sim.base()->SetVelocity(0.0, 0.0);
w.Close();
const vslam::RecordWriterStats ws = w.Stats();
std::printf("%-12s %6.1f s %7llu chunk %8.2f MB drop %llu\n", s.name, total,
static_cast<unsigned long long>(ws.chunks_written),
ws.bytes_written / 1048576.0,
static_cast<unsigned long long>(ws.chunks_dropped));
if (ws.chunks_dropped > 0) {
std::fprintf(stderr, "%s: DROP %llu chunk -- ban ghi khong dung lam goc "
"hoi quy duoc\n", s.name,
static_cast<unsigned long long>(ws.chunks_dropped));
return 1;
}
written++;
}
if (written == 0) {
std::fprintf(stderr, "khong co kich ban ten '%s'\n", name.c_str());
return 2;
}
return 0;
}

410
tools/vslam_replay.cc Normal file
View File

@@ -0,0 +1,410 @@
// Phat lai mot ban ghi `.vsr` qua TOAN BO duong ong, roi xuat mot ban tom tat
// JSON PHANG. Tuy chon: so voi mot file ky vong theo dung sai.
//
// ================== VI SAO JSON PHANG ==================
// Chi khoa -> so vo huong. Khong long nhau, khong mang. Nho vay phep so sanh
// la mot vong lap 20 dong dung CHINH `JsonGetNumber` ma lop xac thuc web
// dung -- khong them thu vien JSON, khong them Python, va khong co cho nao de
// hai cach doc cung mot file lech nhau.
//
// ================== NGUON KHONG PHAN BIET DUOC ==================
// `ReplaySource` implement CHINH cac interface driver ma `SimSource` va phan
// cung that implement. Khong co nhanh `if (replay)` nao trong logic duoi day.
// Do la loi ich kien truc lon nhat cua interface + factory.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "vslam/ekf_se2.h"
#include "vslam/geometry.h"
#include "vslam/json_parse.h"
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
#include "vslam/perception_pipeline.h"
#include "vslam/replay_source.h"
#include "vslam/safety_monitor.h"
#include "vslam/wheel_odometry.h"
namespace {
// Ban tom tat: khoa -> so. Giu thu tu chen de file de doc.
class Summary {
public:
void Set(const std::string& k, double v) {
auto it = index_.find(k);
if (it == index_.end()) {
index_[k] = order_.size();
order_.emplace_back(k, v);
} else {
order_[it->second].second = v;
}
}
void Add(const std::string& k, double d) {
auto it = index_.find(k);
if (it == index_.end()) Set(k, d);
else order_[it->second].second += d;
}
const std::vector<std::pair<std::string, double>>& items() const { return order_; }
std::string ToJson(const std::string& scenario) const {
std::ostringstream o;
o << "{\n \"scenario\": \"" << scenario << "\"";
for (const auto& kv : order_) {
// %.6g giu du y nghia ma khong in ra rac cua dau phay dong. So sanh van
// theo dung sai chu khong theo van ban, nhung file phai doc duoc bang mat.
char buf[64];
std::snprintf(buf, sizeof(buf), "%.6g", kv.second);
o << ",\n \"" << kv.first << "\": " << buf;
}
o << "\n}\n";
return o.str();
}
private:
std::vector<std::pair<std::string, double>> order_;
std::map<std::string, size_t> index_;
};
// Dung sai theo TIEN TO khoa.
//
// Mot dung sai duy nhat cho moi thu la sai: so dem phai khop TUYET DOI (lech
// mot khung nghia la duong di qua code da doi), con pose thi khong bao gio
// khop bit-for-bit qua cac muc toi uu hay cac phien ban libm.
struct Tol {
const char* prefix;
double abs_tol;
double rel_tol;
};
const Tol kTolerances[] = {
{"n_", 0.0, 0.0}, // so dem: khop chinh xac
{"count_", 0.0, 0.0}, // so dem theo nhanh: khop chinh xac
{"pose_", 0.002, 0.0}, // met
{"dist_", 0.002, 0.0},
{"yaw_", 0.001, 0.0}, // rad
{"metric_", 0.01, 0.0},
{"", 0.005, 1e-6}, // con lai
};
const Tol& ToleranceFor(const std::string& key) {
for (const Tol& t : kTolerances) {
const size_t n = std::strlen(t.prefix);
if (n == 0) return t;
if (key.size() >= n && key.compare(0, n, t.prefix) == 0) return t;
}
return kTolerances[0];
}
std::string ReadFile(const std::string& path) {
std::ifstream f(path);
if (!f) return "";
std::ostringstream o;
o << f.rdbuf();
return o.str();
}
// Dem so khoa o muc goc cua mot JSON phang. Dung de phat hien khoa BIEN MAT:
// mot nhanh ngung chay cung la hoi quy, va so sanh theo tung khoa mot khong
// bat duoc dieu do.
size_t CountKeys(const std::string& json) {
size_t n = 0;
bool in_str = false;
for (size_t i = 0; i < json.size(); ++i) {
const char c = json[i];
if (c != '"') continue;
if (i > 0 && json[i - 1] == '\\') continue;
if (in_str) {
// Chuoi vua ket thuc: no la mot KHOA neu ky tu khong-trang tiep theo la
// dau hai cham.
const size_t j = json.find_first_not_of(" \t\r\n", i + 1);
if (j != std::string::npos && json[j] == ':') n++;
}
in_str = !in_str;
}
return n;
}
} // namespace
int main(int argc, char** argv) {
std::string in, expect, emit;
bool quiet = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--in") in = next();
else if (a == "--expect") expect = next();
else if (a == "--emit") emit = next();
else if (a == "--quiet") quiet = true;
else if (a == "--help") {
std::printf("cach dung: %s --in X.vsr [--expect X.json] [--emit X.json] [--quiet]\n",
argv[0]);
return 0;
}
}
if (in.empty()) {
std::fprintf(stderr, "can --in\n");
return 2;
}
// --- Nguon ---
vslam::ReplayConfig rc;
rc.path = in;
// TAT DINH: khong ngu theo dong ho tuong, xu ly dung thu tu stamp. Day la
// dieu kien de hai lan chay cho ra cung mot ket qua -- neu khong thi moi
// khac biet deu la nhieu va bo hoi quy vo dung.
rc.deterministic = true;
rc.apply_sanitizer = true;
constexpr double kPi = 3.14159265358979323846;
rc.sanitizer.range_min = 0.05;
rc.sanitizer.range_max = 40.0;
rc.sanitizer.sector_masks.push_back(vslam::SectorMask{118.0 * kPi / 180.0, kPi});
rc.sanitizer.sector_masks.push_back(vslam::SectorMask{-kPi, -118.0 * kPi / 180.0});
vslam::ReplaySource src(rc);
const vslam::StatusResponse st = src.Open();
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str());
return 1;
}
std::string scenario = "?";
vslam::JsonGetString(src.recorded_config_json(), "scenario", &scenario);
// --- Duong ong, DUNG cac lop se chay tren robot that ---
// Hinh hoc lay tu robot.yaml, KHONG go tay o day.
//
// Truoc khi co RobotModel, phep dung `cam_to_base` bi lap lai o bon file va
// `nominal_tz` da lech (0.803 vs 0.80). Gio no la HE QUA cua camera_link.z
// cong wheel_radius, doc tu mot nguon duy nhat.
vslam::RobotModel robot;
{
const vslam::StatusResponse rs =
robot.LoadFile(vslam::ConfigPath(vslam::kRobotConfigFile));
if (!rs.ok()) {
std::fprintf(stderr, "robot.yaml: %s\n", rs.message.c_str());
return 1;
}
}
vslam::Transform cam_to_base;
if (!robot.StaticTransform(vslam::kBaseLinkFrame,
vslam::kCameraDepthOpticalFrame, &cam_to_base)) {
std::fprintf(stderr, "robot.yaml: khong co duong camera -> base_link\n");
return 1;
}
vslam::PerceptionConfig pc;
pc.cliff.nominal_tz = robot.camera_height_above_floor();
pc.cliff.wheel_radius = robot.geometry().wheel_radius;
pc.gravity.wheel_radius = robot.geometry().wheel_radius;
pc.filter.max_rate = 0.0;
pc.enable_cloud = false; // hoi quy chi can co-vuc/khong, khong can cloud
vslam::PerceptionPipeline perception(pc, *src.clock());
perception.SetCameraExtrinsic(cam_to_base);
vslam::WheelOdometryConfig wo_cfg;
wo_cfg.wheel_radius = robot.geometry().wheel_radius;
wo_cfg.wheel_separation = robot.geometry().wheel_separation;
vslam::WheelOdometry wheel_odom(wo_cfg);
vslam::EkfSe2 ekf;
vslam::SafetyMonitor safety;
Summary s;
vslam::LaserScanPtr last_scan;
vslam::UnixTime last_scan_stamp;
bool cliff_flag = false;
vslam::UnixTime cliff_stamp;
bool have_cliff = false;
std::string cliff_detail = "judged";
double max_slip = 0.0;
src.lidar()->SetCallback([&](vslam::LaserScanPtr sc) {
last_scan = sc;
last_scan_stamp = sc->header.stamp;
s.Add("n_scan", 1);
});
std::map<std::string, double> us_map;
vslam::UnixTime us_stamp;
bool have_us = false;
bool bumper = false;
vslam::UnixTime bumper_stamp;
bool have_bumper = false;
src.mcu()->SetUltrasonicCallback([&](const vslam::UltrasonicReading& u) {
s.Add("n_ultrasonic", 1);
us_map.clear();
for (size_t i = 0; i < u.count; ++i) {
// GIU CA NaN -- FSM phan biet ba ngu nghia, day chi truyen nguyen ven.
// Loc NaN o day lam mot day cam bien DUT tro nen vo hinh.
us_map["us" + std::to_string(i)] = u.range[i];
}
us_stamp = u.stamp;
have_us = true;
});
src.mcu()->SetBumperCallback([&](const vslam::BumperReading& b) {
s.Add("n_bumper", 1);
bumper = b.any();
bumper_stamp = b.stamp;
have_bumper = true;
});
src.mcu()->SetImuCallback([&](vslam::ImuPtr m) {
s.Add("n_imu", 1);
perception.FeedImu(*m);
wheel_odom.FeedGyroZ(m->header.stamp, m->angular_velocity.z);
ekf.UpdateImuYawRate(m->header.stamp, m->angular_velocity.z, 2.4e-7);
});
src.base()->SetEncoderCallback([&](const vslam::EncoderReading& e) {
if (!e.valid) return;
s.Add("n_encoder", 1);
vslam::Odometry o;
if (!wheel_odom.Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
ekf.UpdateOdomTwist(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z,
o.twist.covariance[0], o.twist.covariance[35]);
perception.FeedOdom(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z);
max_slip = std::max(max_slip, wheel_odom.slip_metric());
// FSM chay o day vi ban ghi khong co dong ho doc lap. Tren robot that no
// la mot luong 20 Hz rieng -- xem vslam_sim_run.cc. Lenh dua vao la van
// toc DO DUOC, tuc la cau hoi "robot dang di the nay, co an toan khong".
vslam::SafetyInputs si;
si.now = e.stamp;
vslam::Twist cmd;
cmd.linear.x = o.twist.twist.linear.x;
cmd.angular.z = o.twist.twist.angular.z;
si.cmd = &cmd;
si.cmd_stamp = e.stamp;
if (last_scan) {
si.scan = last_scan.get();
si.scan_stamp = last_scan_stamp;
}
if (have_us) {
si.ultrasonic = us_map;
si.us_stamp = us_stamp;
}
if (have_bumper) {
si.have_bumper = true;
si.bumper = bumper;
si.bumper_stamp = bumper_stamp;
}
if (have_cliff) {
si.have_cliff = true;
si.cliff = cliff_flag;
si.cliff_stamp = cliff_stamp;
// Giong `Runtime`: FSM phan biet "THAY vuc" voi "mu nen gia dinh co
// vuc". Bo hoi quy phai di DUNG duong ma node di.
si.cliff_judged = (cliff_detail == "judged");
si.cliff_window_min = pc.cliff.min_dist;
}
const vslam::SafetyOutput so = safety.Step(si);
s.Add(std::string("count_state_") + vslam::SafetyStateName(so.state), 1);
s.Add("n_safety_step", 1);
});
if (src.camera() != nullptr) {
src.camera()->SetCallback([&](const vslam::CameraFrame& f) {
if (!f.depth) return;
s.Add("n_camera", 1);
const vslam::PerceptionOutput po = perception.Process(*f.depth, f.depth_info);
cliff_flag = po.cliff_detected;
cliff_stamp = po.stamp;
cliff_detail = po.cliff_detail;
have_cliff = true;
if (po.cliff_detected) s.Add("count_cliff_detected", 1);
if (po.cliff_detail == "judged") s.Add("count_cliff_judged", 1);
else s.Add("count_bail_" + po.cliff_detail, 1);
});
src.camera()->Open();
}
src.lidar()->Open();
src.mcu()->Open();
src.base()->Open();
src.Run();
// --- Ket qua ---
const vslam::ReplaySource::Stats rs = src.stats();
const vslam::Pose2D ekf_pose = ekf.pose();
const vslam::Pose2D wheel_pose = wheel_odom.pose();
s.Set("n_chunks", static_cast<double>(rs.chunks));
s.Set("n_truncated", rs.truncated ? 1.0 : 0.0);
s.Set("dist_duration_sec", rs.duration_sec);
s.Set("pose_ekf_x", ekf_pose.x);
s.Set("pose_ekf_y", ekf_pose.y);
s.Set("yaw_ekf", ekf_pose.theta);
s.Set("pose_wheel_x", wheel_pose.x);
s.Set("pose_wheel_y", wheel_pose.y);
s.Set("yaw_wheel", wheel_pose.theta);
s.Set("dist_ekf_vs_wheel", vslam::Distance2D(ekf_pose, wheel_pose));
s.Set("metric_slip_max", max_slip);
const std::string json = s.ToJson(scenario);
if (!quiet) std::fputs(json.c_str(), stdout);
if (!emit.empty()) {
std::ofstream f(emit);
if (!f) {
std::fprintf(stderr, "khong ghi duoc %s\n", emit.c_str());
return 1;
}
f << json;
}
if (expect.empty()) return 0;
// --- So voi ky vong ---
const std::string want = ReadFile(expect);
if (want.empty()) {
std::fprintf(stderr, "%s: khong doc duoc file ky vong\n", expect.c_str());
return 1;
}
int bad = 0;
for (const auto& kv : s.items()) {
double w = 0.0;
if (!vslam::JsonGetNumber(want, kv.first, &w)) {
std::fprintf(stderr, " MOI %-28s = %.6g (ky vong khong co khoa nay)\n",
kv.first.c_str(), kv.second);
bad++;
continue;
}
const Tol& t = ToleranceFor(kv.first);
const double limit = t.abs_tol + t.rel_tol * std::fabs(w);
const double d = std::fabs(kv.second - w);
if (d > limit) {
std::fprintf(stderr, " LECH %-28s co %.6g, ky vong %.6g (lech %.3g > %.3g)\n",
kv.first.c_str(), kv.second, w, d, limit);
bad++;
}
}
// Khoa CO trong ky vong ma KHONG con trong ket qua cung la hoi quy: no
// nghia la mot nhanh da ngung chay. So sanh theo tung khoa mot khong bat
// duoc dieu do, nen phai dem.
const size_t want_keys = CountKeys(want);
const size_t have_keys = s.items().size() + 1; // +1 cho "scenario"
if (want_keys != have_keys) {
std::fprintf(stderr,
" SO KHOA ky vong %zu, co %zu -- mot nhanh da ngung chay?\n",
want_keys, have_keys);
bad++;
}
if (bad > 0) {
std::fprintf(stderr, "%s: %d khac biet\n", scenario.c_str(), bad);
return 1;
}
if (!quiet) std::printf("%s: KHOP\n", scenario.c_str());
return 0;
}

547
tools/vslam_sim_run.cc Normal file
View File

@@ -0,0 +1,547 @@
// vslam_sim_run -- chay mo phong + web UI trong mot tien trinh.
//
// Thay cho `roslaunch robot_bringup sim.launch` + Gazebo GUI + RViz.
//
// ./vslam_sim_run [--map <map.yaml>] [--port 8080] [--token <chuoi>]
// [--slip 0.05] [--speed 1.0]
//
// Roi mo http://<may>:8080 va lai robot bang joypad tren trang.
//
// ================== DUONG DI CUA DU LIEU ==================
// SimSource -> LidarInterface -> ScanSanitizer -> web
// -> McuInterface -> (P3: EKF)
// -> BaseInterface <- lenh teleop tu web
//
// Chu y SimSource noi vao dung nhung interface ma phan cung that se noi vao.
// Khi cam LiDAR va base vao, chi doi hai dong o wiring, khong doi gi khac.
#include <atomic>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/json_parse.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
#include "vslam/occupancy_map_io.h"
#include "vslam/sim_source.h"
#include "vslam/ekf_se2.h"
#include "vslam/perception_pipeline.h"
#include "vslam/safety_monitor.h"
#include "vslam/teleop_model.h"
#include "vslam/wheel_odometry.h"
#include "vslam/web_server.h"
namespace {
std::atomic<bool> g_stop{false};
void OnSignal(int) { g_stop.store(true); }
} // namespace
int main(int argc, char** argv) {
vslam::SimConfig sim_cfg;
vslam::WebConfig web_cfg;
// Mo hinh teleop port tu robot_bringup/scripts/teleop_model.py (BSD-3-Clause,
// goc: virtual_joystick_teleop cua duongtd). Trang web chi gui truc joystick
// da chuan hoa; MOI phep quy ra van toc nam o day.
vslam::TeleopConfig tcfg;
tcfg.linear_speed = 0.30;
tcfg.angular_speed = 0.70;
tcfg.max_linear_speed = 0.35; // khop gioi han cua base
tcfg.max_angular_speed = 0.80;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--map") sim_cfg.map_yaml = next();
else if (a == "--port") web_cfg.port = static_cast<uint16_t>(std::atoi(next().c_str()));
else if (a == "--token") web_cfg.auth_token = next();
else if (a == "--assets") web_cfg.asset_dir = next();
else if (a == "--slip") sim_cfg.slip_factor = std::atof(next().c_str());
else if (a == "--speed") sim_cfg.speed = std::atof(next().c_str());
else if (a == "--x") sim_cfg.start_x = std::atof(next().c_str());
else if (a == "--y") sim_cfg.start_y = std::atof(next().c_str());
else if (a == "--yaw") sim_cfg.start_yaw = std::atof(next().c_str());
else if (a == "--help") {
std::printf(
"cach dung: %s [--map map.yaml] [--port N] [--token S]\n"
" [--x X] [--y Y] [--yaw RAD] [--slip F] [--speed F]\n\n"
"Khong co --map thi dung the gioi tong hop (hanh lang + phong).\n",
argv[0]);
return 0;
}
}
std::signal(SIGINT, OnSignal);
std::signal(SIGTERM, OnSignal);
// --- Hinh hoc robot ------------------------------------------------------
// MOT nguon duy nhat cho hinh hoc: robot.yaml. Bo mo phong cung lay tu day,
// neu khong thi "sim dung mot bo so, duong ong dung bo khac" va moi phep do
// deu do nham.
vslam::RobotModel robot;
{
const vslam::StatusResponse rs =
robot.LoadFile(vslam::ConfigPath(vslam::kRobotConfigFile));
if (!rs.ok()) {
std::fprintf(stderr, "robot.yaml: %s\n", rs.message.c_str());
return 1;
}
}
sim_cfg.wheel_radius = robot.geometry().wheel_radius;
sim_cfg.wheel_separation = robot.geometry().wheel_separation;
sim_cfg.robot_radius = robot.geometry().robot_radius;
sim_cfg.camera_z = robot.camera_height_above_floor();
sim_cfg.camera_pitch = robot.camera_pitch();
sim_cfg.max_linear = robot.base().max_linear;
sim_cfg.max_angular = robot.base().max_angular;
sim_cfg.accel_limit = robot.base().accel_limit;
{
vslam::Transform laser;
if (robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kLaserFrame, &laser)) {
sim_cfg.lidar_x = laser.translation.x;
}
vslam::Transform cam;
if (robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraFrame, &cam)) {
sim_cfg.camera_x = cam.translation.x;
}
}
// --- Mo phong ------------------------------------------------------------
vslam::SimSource sim(sim_cfg);
const vslam::StatusResponse st = sim.Open();
if (!st.ok()) {
std::fprintf(stderr, "sim: %s\n", st.message.c_str());
return 1;
}
// --- Ve sinh scan --------------------------------------------------------
// Dung CHINH ScanSanitizer ma phan cung that se dung. Sector mask +-118 do
// khop cau hinh cu: laser o x=0.24, than robot nua rong 0.17.
constexpr double kPi = 3.14159265358979323846;
vslam::ScanSanitizerConfig san_cfg;
san_cfg.range_min = 0.05;
san_cfg.range_max = 40.0;
san_cfg.sector_masks.push_back(vslam::SectorMask{118.0 * kPi / 180.0, kPi});
san_cfg.sector_masks.push_back(vslam::SectorMask{-kPi, -118.0 * kPi / 180.0});
vslam::ScanSanitizer sanitizer(san_cfg);
// --- Perception: depth -> cloud -> loc -> can trong luc -> phat hien vuc --
//
// Chay INLINE trong callback camera, dung mot luong. Do la cai thay cho ba
// nodelet chung mot manager cua ban ROS, va tot hon: thu tu buoc la thu tu
// dong lenh chu khong phu thuoc thu tu remap trong launch file.
vslam::PerceptionConfig perc_cfg;
perc_cfg.gravity.wheel_radius = robot.geometry().wheel_radius;
perc_cfg.cliff.wheel_radius = robot.geometry().wheel_radius;
// `nominal_tz` la HE QUA cua camera_link.z cong wheel_radius, khong phai
// mot so go tay. Go tay lan thu hai la cho no duoc phep lech -- va no DA
// lech that: 0.803 trong cliff_detect.h so voi 0.80 cua sim.
perc_cfg.cliff.nominal_tz = robot.camera_height_above_floor();
// camera_depth_optical_frame -> base_link, lay tu CAY FRAME cua robot.yaml.
//
// Truoc day phep dung nay duoc go tay o day, va o ba file khac nua. Bon ban
// chep cua cung mot chuoi QuaternionMultiply, va khong co gi bat duoc khi
// mot trong bon lech di.
vslam::Transform cam_to_base;
if (!robot.StaticTransform(vslam::kBaseLinkFrame,
vslam::kCameraDepthOpticalFrame, &cam_to_base)) {
std::fprintf(stderr, "robot.yaml: khong co duong camera -> base_link\n");
return 1;
}
vslam::PerceptionPipeline perception(perc_cfg, *sim.clock());
perception.SetCameraExtrinsic(cam_to_base);
std::mutex perc_mu;
vslam::PointCloudXYZPtr latest_cloud;
bool perc_cliff = false;
vslam::UnixTime perc_cliff_stamp;
bool have_perc = false;
std::string perc_detail;
// --- Trang thai chia se giua luong sim va luong web ----------------------
// --- Duong odometry that: encoder -> wheel_odom -> EKF ------------------
// Dung CHINH cac lop se chay tren robot that. SimSource day encoder va IMU
// vao dung nhung interface ma phan cung day vao.
vslam::WheelOdometryConfig wo_cfg;
wo_cfg.wheel_radius = robot.geometry().wheel_radius;
wo_cfg.wheel_separation = robot.geometry().wheel_separation;
vslam::WheelOdometry wheel_odom(wo_cfg);
vslam::EkfSe2 ekf;
std::mutex odom_mu;
vslam::Odometry latest_odom;
bool have_odom = false;
// --- Lop an toan that ---------------------------------------------------
// Thay cho chot e-stop tam thoi. FSM 10 nhanh, dung lop se chay tren robot
// that. Lenh teleop di QUA no truoc khi toi base.
vslam::SafetyMonitor safety;
std::mutex safety_mu;
vslam::SafetyOutput last_safety;
// Lenh teleop THO, chua qua lop an toan. Luong safety doc bien nay o 20 Hz.
std::mutex cmd_mu;
vslam::Twist raw_cmd;
vslam::UnixTime raw_cmd_stamp;
bool have_raw_cmd = false;
std::mutex mu;
vslam::TeleopModel teleop(tcfg);
std::mutex teleop_mu;
vslam::LaserScanPtr latest_scan;
std::vector<vslam::Pose2D> trajectory;
std::atomic<bool> estop{false};
sim.lidar()->SetCallback([&](vslam::LaserScanPtr s) {
auto copy = std::make_shared<vslam::LaserScan>(*s);
sanitizer.Apply(copy.get());
std::lock_guard<std::mutex> lk(mu);
latest_scan = copy;
});
// IMU -> gyro cho phat hien truot, VA -> EKF.
sim.mcu()->SetImuCallback([&](vslam::ImuPtr m) {
// Bo loc bu cua gravity_align an o day: 200 Hz, truoc moi thu khac.
perception.FeedImu(*m);
std::lock_guard<std::mutex> lk(odom_mu);
wheel_odom.FeedGyroZ(m->header.stamp, m->angular_velocity.z);
ekf.UpdateImuYawRate(m->header.stamp, m->angular_velocity.z,
m->angular_velocity_covariance[8] > 0.0
? m->angular_velocity_covariance[8]
: 2.4e-7);
});
// Encoder -> wheel_odom -> EKF.
//
// Chu y truyen THANG twist.covariance tu wheel_odom vao EKF: do chinh la
// cach wheel_odom bao "dang truot, dung tin toi". Thay bang hang so o day
// la vut bo toan bo co che phat hien truot.
sim.base()->SetEncoderCallback([&](const vslam::EncoderReading& e) {
if (!e.valid) return;
std::lock_guard<std::mutex> lk(odom_mu);
vslam::Odometry o;
if (!wheel_odom.Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
ekf.UpdateOdomTwist(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z,
o.twist.covariance[0], o.twist.covariance[35]);
latest_odom = o;
have_odom = true;
// gravity_align phai TRU gia toc rieng cua robot truoc khi coi phan con
// lai la trong luc. Khong co duong nay, moi lan tang toc bi hieu thanh
// mot cu nghieng -- dung loi da lam cliff_detect bao vuc gia 1625/1832
// mau trong repo cu.
perception.FeedOdom(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z);
});
// Camera -> perception. SimSource tra nullptr khi enable_depth_camera=false,
// khong tra mot camera khong co anh -- nen kiem nullptr o day la du.
if (sim.camera() != nullptr) {
sim.camera()->SetCallback([&](const vslam::CameraFrame& f) {
if (!f.depth) return;
vslam::PerceptionOutput po = perception.Process(*f.depth, f.depth_info);
std::lock_guard<std::mutex> lk(perc_mu);
latest_cloud = po.cloud_aligned;
perc_cliff = po.cliff_detected;
perc_cliff_stamp = po.stamp;
perc_detail = po.cliff_detail;
have_perc = true;
});
}
sim.lidar()->Open();
sim.mcu()->Open();
sim.base()->Open();
if (sim.camera() != nullptr) sim.camera()->Open();
// --- Web -----------------------------------------------------------------
vslam::WebServer web(
web_cfg,
[&](const std::string& cmd, const std::string& body) -> vslam::StatusResponse {
if (cmd == "safety/estop") {
bool on = false;
if (!vslam::JsonGetBool(body, "on", &on)) {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument,
"can truong bool \"on\"");
}
estop.store(on);
{
std::lock_guard<std::mutex> lk(safety_mu);
safety.SetEstop(on);
}
// Khong tu goi SetVelocity: luong safety se thay estop va zero lenh
// trong vong 50 ms. Mot duong duy nhat toi base.
return vslam::StatusResponse::Ok();
}
if (cmd == "safety/reset") {
estop.store(false);
std::lock_guard<std::mutex> lk(safety_mu);
safety.SetEstop(false);
safety.Reset();
return vslam::StatusResponse::Ok();
}
if (cmd == "teleop/adjust") {
// Doi scale van toc NGAY KHI DANG CHAY -- tinh nang cua
// teleop_model.py ma ban joystick viet voi khong co.
std::string axis;
double dir = 0.0;
if (!vslam::JsonGetString(body, "axis", &axis) ||
!vslam::JsonGetNumber(body, "dir", &dir)) {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument,
"can \"axis\" va \"dir\"");
}
std::lock_guard<std::mutex> lk(teleop_mu);
if (axis == "lin") {
teleop.AdjustLinearSpeed(dir);
} else if (axis == "ang") {
teleop.AdjustAngularSpeed(dir);
} else {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument,
"axis phai la \"lin\" hoac \"ang\"");
}
return vslam::StatusResponse::Ok();
}
return vslam::StatusResponse::Error(vslam::StatusCode::kNotFound, "lenh la");
},
[&](double vx_norm, double wz_norm) {
// E-stop chan lenh o day. Lop safety that (P4) se lam viec nay tu te
// hon -- co FSM, co timeout, co dem tia. Day chi la chan tam.
if (estop.load()) {
std::lock_guard<std::mutex> lk(teleop_mu);
teleop.ClearMotion();
sim.base()->SetVelocity(0.0, 0.0);
return;
}
// Truc joystick cua trang web dung quy uoc cua TeleopModel:
// vertical duong = keo XUONG = lui
// horizontal duong = keo PHAI = quay phai
// app.js gui vx/wz theo chieu nguoi lai (duong = tien/trai), nen doi
// dau o day. Doi dau o mot cho, khong rai rac hai phia.
std::pair<double, double> cmd;
{
std::lock_guard<std::mutex> lk(teleop_mu);
teleop.SetJoystick(-wz_norm, -vx_norm);
cmd = teleop.Command();
}
// CHI ghi lai lenh tho. Viec danh gia an toan do LUONG SAFETY lam,
// o 20 Hz tren dong ho cua no.
//
// Goi Step() ngay o day la sai: FSM se chi chay khi CO lenh teleop
// toi, ma NO_CMD / SCAN_TIMEOUT / cliff_hold ton tai chinh xac cho
// truong hop lenh NGUNG toi. Da mac loi nay mot lan.
std::lock_guard<std::mutex> lk(cmd_mu);
raw_cmd.linear.x = cmd.first;
raw_cmd.angular.z = cmd.second;
raw_cmd_stamp = sim.clock()->Now();
have_raw_cmd = true;
});
const vslam::StatusResponse wst = web.Start();
if (!wst.ok()) {
std::fprintf(stderr, "web: %s\n", wst.message.c_str());
return 1;
}
const vslam::OccupancyGrid& grid = sim.map();
auto map_ptr = std::make_shared<const vslam::OccupancyGrid>(grid);
std::printf("\n mo phong dang chay\n");
std::printf(" ban do : %ux%u @ %.3f m/o\n", grid.width, grid.height,
static_cast<double>(grid.resolution));
std::printf(" web UI : http://localhost:%u%s\n", web.port(),
web_cfg.auth_token.empty() ? "" : "/?token=<token>");
std::printf(" dieu khien: joypad tren trang web\n");
std::printf(" Ctrl-C de dung\n\n");
// --- Luong mo phong ------------------------------------------------------
std::thread sim_thread([&] { sim.Run(); });
// --- Luong an toan: 20 Hz, doc lap voi moi thu khac ----------------------
//
// Tren robot that luong nay chay SCHED_FIFO cao nhat va KHONG chia se mutex
// nao voi luong slam. O day chua co slam, nhung giu dung cau truc de khi
// them vao thi khong phai sua lai.
//
// No chay DEU DAN bat ke co lenh teleop hay khong -- do la dieu kien de
// NO_CMD, SCAN_TIMEOUT va cliff_hold co y nghia.
std::thread safety_thread([&] {
while (!g_stop.load()) {
vslam::SafetyInputs si;
si.now = sim.clock()->Now();
vslam::Twist cmd_copy;
{
std::lock_guard<std::mutex> lk(cmd_mu);
if (have_raw_cmd) {
cmd_copy = raw_cmd;
si.cmd = &cmd_copy;
si.cmd_stamp = raw_cmd_stamp;
}
}
vslam::LaserScanPtr scan_copy;
{
std::lock_guard<std::mutex> lk(mu);
scan_copy = latest_scan;
}
if (scan_copy) {
si.scan = scan_copy.get();
si.scan_stamp = scan_copy->header.stamp;
}
{
std::lock_guard<std::mutex> lk(perc_mu);
if (have_perc) {
si.have_cliff = true;
si.cliff = perc_cliff;
si.cliff_stamp = perc_cliff_stamp;
}
}
vslam::SafetyOutput so;
{
std::lock_guard<std::mutex> lk(safety_mu);
so = safety.Step(si);
last_safety = so;
}
// Day la duong DUY NHAT lenh toi duoc base. Khong co nhanh nao cho
// lenh di thang xuong, ke ca teleop.
sim.base()->SetVelocity(so.cmd.linear.x, so.cmd.angular.z);
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 20 Hz
}
});
// --- Vong phat len web ---------------------------------------------------
vslam::UnixTime last_traj;
while (!g_stop.load()) {
vslam::WebSnapshot snap;
snap.stamp = sim.clock()->Now();
const vslam::Pose2D gt = sim.ground_truth();
// Pose hien thi la dau ra cua ESTIMATOR, khong phai ground truth.
// Ground truth chi dung de DOI CHUNG -- dung vai tro cua
// /ground_truth/odom trong repo cu, noi ghi ro "khong estimator nao duoc
// subscribe".
vslam::Pose2D ekf_pose = ekf.pose();
vslam::Pose2D wheel_pose;
{
std::lock_guard<std::mutex> lk(odom_mu);
wheel_pose = wheel_odom.pose();
snap.slip_metric = wheel_odom.slip_metric();
if (have_odom) {
snap.vx = latest_odom.twist.twist.linear.x;
snap.vyaw = latest_odom.twist.twist.angular.z;
}
}
snap.pose_map = ekf_pose;
snap.pose_odom = wheel_pose;
// Sai so tich luy so voi ground truth -- day la con so ma bai L2 cua repo
// cu do duoc 1.04% trong sim va 18% tren robot that.
const double ate = vslam::Distance2D(ekf_pose, gt);
{
std::lock_guard<std::mutex> lk(mu);
snap.scan = latest_scan;
if (trajectory.empty() ||
vslam::Distance2D(trajectory.back(), gt) > 0.1) {
trajectory.push_back(gt);
if (trajectory.size() > 2000) {
trajectory.erase(trajectory.begin(), trajectory.begin() + 500);
}
}
snap.trajectory = trajectory;
}
snap.map = map_ptr;
snap.slam.map_version = 1;
snap.slam.mode = "sim";
snap.slam.localized = true;
snap.slam.score = 1.0;
const vslam::SimSource::Stats ss = sim.stats();
// So lieu an toan lay THANG tu FSM, khong tinh lai o day. Tinh lai la mo
// duong cho hai ban logic lech nhau -- dung loai bug da gap o lop xac
// thuc e-stop cua web.
{
std::lock_guard<std::mutex> lk(safety_mu);
snap.safety.state = vslam::SafetyStateName(last_safety.state);
snap.safety.detail = last_safety.detail;
snap.safety.min_front = last_safety.min_front;
snap.safety.front_rays = last_safety.front_rays;
snap.safety.front_blanked = last_safety.front_blanked;
snap.safety.front_usable = last_safety.front_usable;
snap.safety.estop = safety.estop();
snap.safety.bumper_latched = safety.bumper_latched();
}
{
std::lock_guard<std::mutex> lk(teleop_mu);
snap.teleop.linear_speed = teleop.linear_speed();
snap.teleop.angular_speed = teleop.angular_speed();
snap.teleop.max_linear_speed = teleop.max_linear_speed();
snap.teleop.max_angular_speed = teleop.max_angular_speed();
}
snap.health.lidar_hz = sim_cfg.lidar_rate_hz;
snap.health.imu_hz = sim_cfg.imu_rate_hz;
snap.health.ekf_hz = sim_cfg.encoder_rate_hz;
{
std::lock_guard<std::mutex> lk(perc_mu);
snap.cloud = latest_cloud;
snap.safety.cliff = perc_cliff;
if (!perc_detail.empty() && perc_detail != "judged") {
// "khong biet" khac han "khong co vuc" -- phai hien duoc tren web.
snap.safety.detail = "cliff:" + perc_detail;
}
}
snap.roll = perception.gravity().roll();
snap.pitch = perception.gravity().pitch();
snap.accel_ok = perception.gravity().accel_ok();
snap.health.camera_hz =
sim.camera() != nullptr ? sim_cfg.camera_rate_hz : 0.0;
snap.health.clock_skew = 1.0;
snap.health.drops = {{"collisions", ss.collisions},
{"slip_events", wheel_odom.stats().slip_events}};
// Hien sai so EKF vs ground truth ngay tren bang trang thai: con so nay
// la thu duy nhat noi duoc odometry co dung khong.
snap.slam.mode = "sim";
snap.slam.score = ss.distance_travelled > 0.1
? 1.0 - ate / ss.distance_travelled
: 1.0;
web.Publish(snap);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
sim.RequestStop();
if (safety_thread.joinable()) safety_thread.join();
if (sim_thread.joinable()) sim_thread.join();
web.Stop();
const vslam::SimSource::Stats s = sim.stats();
std::printf("\n thoi gian mo phong : %.1f s\n", s.sim_time_sec);
std::printf(" quang duong : %.2f m\n", s.distance_travelled);
std::printf(" scan / imu / enc : %lu / %lu / %lu\n",
static_cast<unsigned long>(s.scans), static_cast<unsigned long>(s.imu),
static_cast<unsigned long>(s.encoder));
std::printf(" va cham : %lu\n",
static_cast<unsigned long>(s.collisions));
return 0;
}

541
tools/vslam_slam_bench.cc Normal file
View File

@@ -0,0 +1,541 @@
// Chay lai mot session da ghi trong DB RTAB-Map qua wrapper cua ta, roi so
// pose voi pose da toi uu ma chinh DB do luu.
//
// ================== VI SAO BAI NAY DUNG DUOC NGAY HOM NAY ==================
// `map_house.db` DA LA mot dataset replay duoc, truoc khi phan cung chay lan
// nao. Moi node trong DB co scan, odom pose, va pose da toi uu. Doc lai chung
// theo dung thu tu la co mot phien chay day du.
//
// Day cung la cach kiem chung wrapper tu viet cho cung ket qua voi
// rtabmap_ros: neu ATE so voi pose toi uu trong DB nho, wrapper dang goi
// RTAB-Map dung cach.
//
// Ba che do:
// --db X.db chay lai session trong DB (mapping)
// --db X.db --localize chay lai o che do localization tren chinh DB do
// --db X.db --kidnap N,M tha robot lech N met / M do, do thoi gian hoi tu
#include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/LaserScan.h>
#include <rtabmap/core/SensorData.h>
#include <opencv2/core/core.hpp>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <string>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/occupancy_export.h"
#include "vslam/occupancy_map_io.h"
#include "vslam/rtabmap_slam.h"
#include "vslam/sensor_data_builder.h"
namespace {
struct Frame {
int id = 0;
double stamp = 0.0;
vslam::Pose2D odom; // pose odom goc (chua toi uu)
vslam::Pose2D optimized; // pose sau toi uu -- dong vai "su that"
bool has_optimized = false;
vslam::LaserScan scan;
bool has_scan = false;
// Anh, chi nap khi --with-images. Giu cv::Mat SONG vi Image POD chi tro
// vao du lieu chu khong so huu.
cv::Mat rgb, depth;
vslam::Image rgb_pod, depth_pod;
vslam::CameraInfo info;
bool has_image = false;
};
// cv::Mat -> Image POD. KHONG copy: `m` phai song qua het loi goi Process().
vslam::Image WrapMat(const cv::Mat& m) {
vslam::Image img;
img.width = static_cast<uint32_t>(m.cols);
img.height = static_cast<uint32_t>(m.rows);
img.step = static_cast<uint32_t>(m.step);
img.data = m.data;
if (m.type() == CV_16UC1) img.format = vslam::PixelFormat::kMono16;
else if (m.type() == CV_32FC1) img.format = vslam::PixelFormat::kFloat32;
else img.format = vslam::PixelFormat::kMono8;
return img;
}
// rtabmap::LaserScan (kXY hoac kXYZ) -> LaserScan POD.
//
// DB luu DIEM chu khong luu tia, nen phai dung lai cau truc tia. Dung dung
// angle_min/max/increment ma DB nho, roi do tia nao gan diem nao. Tia khong
// co diem nao -> inf (khong co phan xa), DUNG ngu nghia ta da dinh nghia.
bool ToPodScan(const rtabmap::LaserScan& in, vslam::LaserScan* out) {
if (in.isEmpty()) return false;
const int n = in.size();
float amin = in.angleMin(), amax = in.angleMax(), ainc = in.angleIncrement();
if (!(ainc > 0.0f)) {
// DB cu khong luu thong tin goc -> suy ra tu so diem, gia dinh quet deu
// 360 do. Tho, nhung chi anh huong toi cach dung lai tia, khong anh huong
// toi toa do diem ma ICP thuc su dung.
amin = -static_cast<float>(M_PI);
amax = static_cast<float>(M_PI);
ainc = (amax - amin) / static_cast<float>(std::max(n, 1));
}
const int nbeam = std::max(1, static_cast<int>(std::lround((amax - amin) / ainc)) + 1);
out->ranges.assign(static_cast<size_t>(nbeam),
std::numeric_limits<float>::infinity());
out->intensities.clear();
out->angle_min = amin;
out->angle_max = amax;
out->angle_increment = ainc;
out->range_min = in.rangeMin() > 0.0f ? in.rangeMin() : 0.05f;
out->range_max = in.rangeMax() > 0.0f ? in.rangeMax() : 40.0f;
out->scan_time = 0.04;
out->time_increment = out->scan_time / nbeam;
const cv::Mat& d = in.data();
for (int i = 0; i < n; ++i) {
const float* p = d.ptr<float>(0, i);
const float x = p[0], y = p[1];
if (!std::isfinite(x) || !std::isfinite(y)) continue;
const float r = std::sqrt(x * x + y * y);
if (r < out->range_min || r > out->range_max) continue;
const float a = std::atan2(y, x);
int k = static_cast<int>(std::lround((a - amin) / ainc));
if (k < 0 || k >= nbeam) continue;
// Nhieu diem co the roi vao cung mot tia (scan 3D ep xuong): giu diem
// GAN NHAT, giong cach mot LiDAR 2D that hanh xu.
if (!std::isfinite(out->ranges[k]) || r < out->ranges[k]) out->ranges[k] = r;
}
return true;
}
double Rmse(const std::vector<vslam::Pose2D>& a,
const std::vector<vslam::Pose2D>& b) {
double sum = 0.0;
const size_t n = std::min(a.size(), b.size());
if (n == 0) return -1.0;
for (size_t i = 0; i < n; ++i) {
const double dx = a[i].x - b[i].x, dy = a[i].y - b[i].y;
sum += dx * dx + dy * dy;
}
return std::sqrt(sum / static_cast<double>(n));
}
// ATE co CAN CHINH: tim phep quay + tinh tien SE(2) toi uu dua `est` ve `ref`
// (Umeyama 2D, khong co ti le) roi moi do sai so.
//
// Vi sao can: hai quy dao nam trong hai khung map KHAC NHAU. RTAB-Map dat goc
// map o node dau tien cua PHIEN DO, nen mot phien chay lai bat dau tu node
// khac -- hoac chi thay mot phan session -- se lech ca khung. Do truc tiep se
// tra ve khoang cach giua hai GOC TOA DO chu khong phai sai so quy dao.
//
// Bao cao CA HAI: neu tho lon ma can chinh nho thi loi la lech khung; neu ca
// hai cung lon thi la troi that.
double AteAligned(const std::vector<vslam::Pose2D>& est,
const std::vector<vslam::Pose2D>& ref) {
const size_t n = std::min(est.size(), ref.size());
if (n < 2) return -1.0;
double mex = 0, mey = 0, mrx = 0, mry = 0;
for (size_t i = 0; i < n; ++i) {
mex += est[i].x; mey += est[i].y;
mrx += ref[i].x; mry += ref[i].y;
}
mex /= n; mey /= n; mrx /= n; mry /= n;
double sxy = 0, sxx = 0;
for (size_t i = 0; i < n; ++i) {
const double ex = est[i].x - mex, ey = est[i].y - mey;
const double rx = ref[i].x - mrx, ry = ref[i].y - mry;
sxx += ex * rx + ey * ry; // phan doi xung -> cos
sxy += ex * ry - ey * rx; // phan phan doi xung -> sin
}
const double th = std::atan2(sxy, sxx);
const double c = std::cos(th), s = std::sin(th);
double sum = 0.0;
for (size_t i = 0; i < n; ++i) {
const double ex = est[i].x - mex, ey = est[i].y - mey;
const double ax = c * ex - s * ey + mrx;
const double ay = s * ex + c * ey + mry;
const double dx = ax - ref[i].x, dy = ay - ref[i].y;
sum += dx * dx + dy * dy;
}
return std::sqrt(sum / static_cast<double>(n));
}
} // namespace
int main(int argc, char** argv) {
std::string db;
bool localize = false;
double kid_m = 0.0, kid_deg = 0.0;
int limit = 0;
std::string optimizer = "1";
std::string export_map;
bool export_only = false;
bool visual_loop = false;
bool trace = false;
bool with_images = false;
std::string ref_db;
std::map<std::string, std::string> extra;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--db") db = next();
else if (a == "--localize") localize = true;
else if (a == "--limit") limit = std::atoi(next().c_str());
else if (a == "--optimizer") optimizer = next();
else if (a == "--export-map") export_map = next();
else if (a == "--export-only") export_only = true;
else if (a == "--visual-loop") visual_loop = true;
else if (a == "--trace") trace = true;
else if (a == "--with-images") with_images = true;
else if (a == "--ref-db") ref_db = next();
else if (a == "--param") {
// --param Key/Name=value. Di thang vao khoi overrides, tuc la CUNG
// duong ma slam.yaml di -- ke ca phep kiem ten key.
const std::string kv = next();
const size_t e = kv.find('=');
if (e != std::string::npos) extra[kv.substr(0, e)] = kv.substr(e + 1);
}
else if (a == "--kidnap") {
const std::string v = next();
const size_t c = v.find(',');
kid_m = std::atof(v.substr(0, c).c_str());
if (c != std::string::npos) kid_deg = std::atof(v.substr(c + 1).c_str());
localize = true;
} else if (a == "--help") {
std::printf(
"cach dung: %s --db X.db [--localize] [--kidnap M,DEG]\n"
" [--limit N] [--optimizer 0|1|2|3] [--export-map out.pgm]\n",
argv[0]);
return 0;
}
}
if (db.empty()) {
std::fprintf(stderr, "can --db\n");
return 2;
}
// --- Che do doi chung: so pose toi uu cua HAI DB ---
//
// Dung de doi chung wrapper voi `rtabmap-reprocess`, cong cu chinh thuc cua
// RTAB-Map. Neu reprocess chay cung tham so cung cho ATE ~ bang nhau so voi
// DB goc, thi chenh lech do la HE QUA CUA CAU HINH chu khong phai loi cua
// wrapper. Do la phep kiem quan trong nhat cua P6: no tach "wrapper goi sai
// API" ra khoi "scan-only thi khong dung bang scan+anh".
if (!ref_db.empty()) {
std::unique_ptr<rtabmap::DBDriver> d2(rtabmap::DBDriver::create());
if (d2 == nullptr || !d2->openConnection(ref_db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", ref_db.c_str());
return 1;
}
const std::map<int, rtabmap::Transform> opt2 = d2->loadOptimizedPoses();
d2->closeConnection(false);
std::unique_ptr<rtabmap::DBDriver> d1(rtabmap::DBDriver::create());
d1->openConnection(db, false);
const std::map<int, rtabmap::Transform> opt1 = d1->loadOptimizedPoses();
d1->closeConnection(false);
std::vector<vslam::Pose2D> a, b;
for (const auto& kv : opt1) {
auto it = opt2.find(kv.first);
if (it == opt2.end()) continue;
a.push_back(vslam::FromRtabmap(kv.second));
b.push_back(vslam::FromRtabmap(it->second));
}
std::printf("so hai DB: %zu vs %zu pose, %zu id chung\n", opt1.size(),
opt2.size(), a.size());
std::printf(" ATE RMSE (tho) : %.4f m\n", Rmse(a, b));
std::printf(" ATE RMSE (can chinh): %.4f m\n", AteAligned(a, b));
return 0;
}
// --- Doc session tu DB ---
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
if (driver == nullptr || !driver->openConnection(db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", db.c_str());
return 1;
}
const std::map<int, rtabmap::Transform> opt = driver->loadOptimizedPoses();
{
const vslam::DbFacts facts = vslam::InspectDatabase(db);
std::printf("DB goc: %d node, %d tu vung, Optimizer/Strategy=\"%s\"\n",
facts.nodes, facts.words,
facts.optimizer_strategy.empty() ? "(khong luu)"
: facts.optimizer_strategy.c_str());
}
std::set<int> ids;
driver->getAllNodeIds(ids);
vslam::Transform laser_to_base = vslam::TransformIdentity();
bool have_laser_tf = false;
std::vector<Frame> frames;
frames.reserve(ids.size());
for (int id : ids) {
if (limit > 0 && static_cast<int>(frames.size()) >= limit) break;
Frame f;
f.id = id;
rtabmap::Transform pose, gt;
int map_id = 0, weight = 0;
std::string label;
std::vector<float> vel;
rtabmap::GPS gps;
rtabmap::EnvSensors sensors;
if (!driver->getNodeInfo(id, pose, map_id, weight, label, f.stamp, gt, vel, gps,
sensors)) {
continue;
}
f.odom = vslam::FromRtabmap(pose);
// CHI node co trong tap pose toi uu moi dung lam tham chieu. DB co node
// nam ngoai do thi da toi uu (bi loai, hoac thuoc phien khac); lay pose
// odom cua chung lam "su that" la dang so uoc luong DA TOI UU cua ta voi
// odom THO -- do chinh la thu SLAM sinh ra de sua.
auto o = opt.find(id);
if (o != opt.end()) {
f.optimized = vslam::FromRtabmap(o->second);
f.has_optimized = true;
}
rtabmap::SensorData data;
driver->getNodeData(id, data, with_images, true, false, false);
data.uncompressData();
f.has_scan = ToPodScan(data.laserScanRaw(), &f.scan);
if (!f.has_scan) continue;
// Frame cuc bo cua laser nam TRONG scan cua DB, khong phai trong node
// info. Bo qua no la dat moi scan lech 24 cm so voi pose.
if (!data.laserScanRaw().localTransform().isNull()) {
laser_to_base = vslam::TransformFromRtabmap(data.laserScanRaw().localTransform());
have_laser_tf = true;
}
if (with_images && !data.imageRaw().empty() && !data.depthRaw().empty() &&
!data.cameraModels().empty()) {
f.rgb = data.imageRaw().clone();
f.depth = data.depthRaw().clone();
f.rgb_pod = WrapMat(f.rgb);
f.depth_pod = WrapMat(f.depth);
const rtabmap::CameraModel& cm = data.cameraModels()[0];
f.info.width = static_cast<uint32_t>(f.depth.cols);
f.info.height = static_cast<uint32_t>(f.depth.rows);
f.info.k[0] = cm.fx(); f.info.k[2] = cm.cx();
f.info.k[4] = cm.fy(); f.info.k[5] = cm.cy();
f.info.k[8] = 1.0;
f.has_image = true;
}
frames.push_back(std::move(f));
}
driver->closeConnection(false);
size_t with_img = 0;
for (const Frame& f : frames) with_img += f.has_image ? 1 : 0;
std::printf("DB %s: %zu node co scan (tong %zu), %zu pose toi uu, %zu co anh\n",
db.c_str(), frames.size(), ids.size(), opt.size(), with_img);
if (frames.empty()) return 1;
// --- Chay qua wrapper ---
// Ghi vao BAN SAO trong RAM: khong duoc sua corpus.
vslam::RtabmapConfig cfg;
cfg.mode = localize ? vslam::SlamMode::kLocalization : vslam::SlamMode::kMapping;
// O che do localization phai mo DB THAT. KHONG BAO GIO mo thang corpus:
// mot lan `Mem/IncrementalMemory` bi dat nham la ban do goc bi ghi de, va
// corpus khong co ban sao. Chep ra cho tam roi mo ban chep.
std::string work_db;
if (localize) {
work_db = db.substr(0, db.size() - 3) + "_bench_tmp.db"; // RTAB-Map doi duoi .db
std::ifstream src(db, std::ios::binary);
std::ofstream dst(work_db, std::ios::binary);
if (!src || !dst) {
std::fprintf(stderr, "khong chep duoc DB ra %s\n", work_db.c_str());
return 1;
}
dst << src.rdbuf();
dst.close();
std::printf("che do localization: dang dung ban chep %s\n", work_db.c_str());
}
cfg.database_path = work_db; // rong = DB trong RAM (che do mapping)
cfg.optimizer_strategy = optimizer;
cfg.visual_loop = visual_loop;
cfg.overrides = extra;
for (const auto& kv : extra) {
std::printf("param: %s = %s\n", kv.first.c_str(), kv.second.c_str());
}
vslam::RtabmapSlam slam;
slam.SetExtrinsics(laser_to_base, vslam::TransformIdentity());
std::printf("laser_to_base: %s(%.3f, %.3f, %.3f)\n",
have_laser_tf ? "" : "MAC DINH ", laser_to_base.translation.x,
laser_to_base.translation.y, laser_to_base.translation.z);
const vslam::StatusResponse st = slam.Init(cfg);
if (!st.ok()) {
std::fprintf(stderr, "init: %s\n", st.message.c_str());
return 1;
}
// --- Pose ban dau ---
//
// RTAB-Map KHONG dinh vi toan cuc duoc bang scan khong. Vong dong toan cuc
// di qua tui tu thi giac; con `RGBD/ProximityBySpace` chi tim trong mot ban
// kinh quanh uoc luong HIEN TAI. Khong co pose ban dau thi o che do
// localization no khong bao gio bat duoc vao ban do cu -- do duoc: ATE tho
// 9.80 m, 0 lien ket.
//
// He that giai quyet dung nhu vay: `dock_init.py` phat /initialpose tu dock.
// Robot LUON biet no bat dau o dau. Bai test phai mo phong dieu do, neu
// khong no dang do mot che do khong ai chay.
//
// Kidnap = pose ban dau SAI di N met / M do. Do la y nghia dung cua bai
// kidnapped-robot: robot TUONG no o mot cho khac.
if (localize) {
vslam::Pose2D init = frames.front().has_optimized ? frames.front().optimized
: frames.front().odom;
init.x += kid_m;
init.theta = vslam::NormalizeAngle(init.theta + kid_deg * M_PI / 180.0);
const vslam::StatusResponse ip = slam.SetInitialPose(init);
std::printf("pose ban dau: (%.3f, %.3f, %.1f do)%s%s\n", init.x, init.y,
init.theta * 180.0 / M_PI,
(kid_m != 0.0 || kid_deg != 0.0) ? " <-- KIDNAP " : "",
ip.ok() ? "" : " [LOI]");
}
// ============ XUAT NHANH ============
//
// `Init()` o che do localization da nap CA do thi va luoi tung node tu DB.
// Xuat ban do khong can phat lai mot khung nao.
//
// Phat lai ~1990 node cua map_hospital.db chi de xuat ban do mat hang chuc
// phut (p95 289 ms/khung) va khong them mot thong tin nao -- pose trong DB
// da la pose TOI UU.
if (export_only) {
if (export_map.empty()) {
std::fprintf(stderr, "--export-only can kem --export-map out.pgm\n");
return 2;
}
vslam::OccupancyGrid grid;
const vslam::StatusResponse e = slam.ExportMap(&grid);
if (!e.ok()) {
std::fprintf(stderr, "xuat ban do: %s\n", e.message.c_str());
return 1;
}
std::string yaml = export_map;
const size_t dot = yaml.rfind('.');
if (dot != std::string::npos) yaml = yaml.substr(0, dot);
yaml += ".yaml";
const vslam::StatusResponse w = vslam::SaveOccupancyMap(grid, yaml);
if (!w.ok()) {
std::fprintf(stderr, "ghi ban do: %s\n", w.message.c_str());
return 1;
}
std::printf("ban do: %ux%u @ %.3f m/o -> %s\n", grid.width, grid.height,
static_cast<double>(grid.resolution), yaml.c_str());
slam.Close(false);
if (!work_db.empty()) std::remove(work_db.c_str());
return 0;
}
const vslam::Pose2D kidnap_offset; // odom khong bi dong toi
std::vector<vslam::Pose2D> est, ref;
est.reserve(frames.size());
ref.reserve(frames.size());
int processed = 0, loops = 0, prox = 0;
double converge_s = -1.0;
const double t_start = frames.front().stamp;
for (const Frame& f : frames) {
vslam::SlamInput in;
in.stamp = vslam::UnixTime::fromSec(f.stamp);
in.odom = vslam::Pose2DCompose(kidnap_offset, f.odom);
in.scan = &f.scan;
if (f.has_image) {
in.depth = &f.depth_pod;
in.depth_info = &f.info;
in.infra1 = &f.rgb_pod;
}
const vslam::SlamOutput o = slam.Process(in);
if (!o.processed) continue;
processed++;
if (o.loop_closure_id > 0) loops++;
if (o.proximity_id > 0) prox++;
if (f.has_optimized) {
est.push_back(o.pose_map);
ref.push_back(f.optimized);
}
if (trace && (processed % 20 == 0)) {
std::printf(" [%4d] ms %7.1f wm %4d loop %d prox %d\n", processed,
o.process_ms, o.nodes_wm, o.loop_closure_id, o.proximity_id);
}
if (localize && converge_s < 0.0 && o.localized && f.has_optimized &&
vslam::Distance2D(o.pose_map, f.optimized) < 0.30) {
converge_s = f.stamp - t_start;
}
}
const vslam::SlamStats& s = slam.stats();
std::printf("\n=== ket qua ===\n");
std::printf(" khung vao / xu ly : %llu / %d\n",
static_cast<unsigned long long>(s.frames_in), processed);
std::printf(" vong dong / lan can: %d / %d\n", loops, prox);
std::printf(" process_ms : cuoi %.1f, max %.1f, p95 %.1f\n", s.last_ms,
s.max_ms, s.p95_ms);
std::printf(" cap so sanh : %zu (node co pose toi uu)\n", est.size());
const double ate_raw = Rmse(est, ref);
const double ate = AteAligned(est, ref);
std::printf(" ATE RMSE (tho) : %.4f m\n", ate_raw);
std::printf(" ATE RMSE (can chinh): %.4f m <-- chi tieu < 0.10\n", ate);
if (converge_s >= 0.0) std::printf(" hoi tu sau : %.2f s\n", converge_s);
else if (localize) std::printf(" hoi tu sau : KHONG hoi tu\n");
if (!export_map.empty()) {
vslam::OccupancyGrid grid;
const vslam::StatusResponse e = slam.ExportMap(&grid);
if (e.ok()) {
// ⚠️ Truoc day cho nay TINH luoi roi VUT DI: `--export-map` nhan duong
// dan, khong ghi gi, va van in dong "ban do xuat" nhu da thanh cong.
// Mot co dong lenh hua ra file ma khong ra file la kieu hong te nhat --
// nguoi dung di tim file trong thu muc trong.
//
// `SaveOccupancyMap` ghi CA .pgm lan .yaml (yaml tro toi pgm), tuc la
// dua thang vao duoc `vslam_node --sim --map`.
std::string yaml = export_map;
const size_t dot = yaml.rfind('.');
if (dot != std::string::npos) yaml = yaml.substr(0, dot);
yaml += ".yaml";
const vslam::StatusResponse w = vslam::SaveOccupancyMap(grid, yaml);
if (!w.ok()) {
std::printf(" ban do xuat : LOI GHI %s\n", w.message.c_str());
return 1;
}
std::printf(" ban do xuat : %ux%u @ %.3f m/o -> %s\n",
grid.width, grid.height,
static_cast<double>(grid.resolution), yaml.c_str());
} else {
std::printf(" ban do xuat : LOI %s\n", e.message.c_str());
}
}
slam.Close(false);
if (!work_db.empty()) std::remove(work_db.c_str());
return 0;
}

303
tools/vslam_web_demo.cc Normal file
View File

@@ -0,0 +1,303 @@
// vslam_web_demo -- tieu chi nghiem thu P1.
//
// Chay web UI bang DU LIEU GIA: khong can LiDAR, khong can camera, khong can
// RTAB-Map. Muc dich la tach viec kiem chung tang hien thi ra khoi viec kiem
// chung tang cam bien -- neu doi ca hai cung luc thi khi co gi sai se khong
// biet loi nam o dau.
//
// ./vslam_web_demo [--port 8080] [--token abc] [--assets <thu_muc>]
// [--map-w 2000] [--map-h 2000]
//
// Roi mo http://<may>:8080 tu laptop.
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <thread>
#include <vector>
#include "vslam/clock.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/json_parse.h"
#include "vslam/web_server.h"
namespace {
std::atomic<bool> g_stop{false};
void OnSignal(int) { g_stop.store(true); }
constexpr double kPi = 3.14159265358979323846;
// Ban do gia: mot hanh lang co phong hai ben. Du de kiem RLE va kiem render.
vslam::OccupancyGridPtr MakeFakeMap(uint32_t w, uint32_t h, float res) {
auto map = std::make_shared<vslam::OccupancyGrid>();
map->width = w;
map->height = h;
map->resolution = res;
map->origin.position.x = -static_cast<double>(w) * res / 2.0;
map->origin.position.y = -static_cast<double>(h) * res / 2.0;
map->data.assign(static_cast<size_t>(w) * h, -1);
auto put = [&](uint32_t x, uint32_t y, int8_t v) {
if (x < w && y < h) map->data[static_cast<size_t>(y) * w + x] = v;
};
const uint32_t cy = h / 2;
const uint32_t half = std::max<uint32_t>(6, h / 24);
// Hanh lang chinh chay theo truc x.
for (uint32_t x = w / 10; x < w - w / 10; ++x) {
for (uint32_t y = cy - half; y <= cy + half; ++y) put(x, y, 0);
put(x, cy - half - 1, 100);
put(x, cy + half + 1, 100);
}
// Phong hai ben, cach deu.
const uint32_t room = half * 3;
for (uint32_t rx = w / 6; rx + room < w - w / 10; rx += room + room / 2) {
for (int side = 0; side < 2; ++side) {
const uint32_t y0 = side == 0 ? cy + half + 2 : cy - half - 2 - room;
for (uint32_t x = rx; x < rx + room; ++x) {
for (uint32_t y = y0; y < y0 + room; ++y) put(x, y, 0);
}
for (uint32_t x = rx - 1; x <= rx + room; ++x) {
put(x, y0 - 1, 100);
put(x, y0 + room, 100);
}
for (uint32_t y = y0 - 1; y <= y0 + room; ++y) {
put(rx - 1, y, 100);
put(rx + room, y, 100);
}
// Cua thong ra hanh lang.
const uint32_t door = rx + room / 2;
for (uint32_t x = door - 2; x <= door + 2; ++x) {
put(x, side == 0 ? y0 - 1 : y0 + room, 0);
}
}
}
return map;
}
vslam::LaserScanPtr MakeFakeScan(double t) {
auto scan = std::make_shared<vslam::LaserScan>();
// Khop cau hinh LakiBeam 1L that: 270 do, 1081 tia, 25 Hz.
scan->angle_min = -2.356194f;
scan->angle_max = 2.356194f;
scan->angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
scan->range_min = 0.05f;
scan->range_max = 40.0f;
scan->scan_time = 0.04f;
scan->time_increment = scan->scan_time / 1081.0f;
scan->ranges.resize(1081);
static std::mt19937 rng(42);
std::normal_distribution<float> noise(0.0f, 0.01f);
for (size_t i = 0; i < scan->ranges.size(); ++i) {
const double a = scan->angle_min + static_cast<double>(i) * scan->angle_increment;
// Than robot che +-118 do: ScanSanitizer that se dat sentinel range_max+1.
// Tai lap o day de kiem client phan biet dung ba ngu nghia.
if (std::abs(a) > 118.0 * kPi / 180.0) {
scan->ranges[i] = scan->range_max + 1.0f;
continue;
}
double r = 3.0 + 1.5 * std::sin(a * 3.0 + t * 0.5);
if (i % 97 == 0) {
scan->ranges[i] = std::numeric_limits<float>::infinity(); // khong phan xa
continue;
}
if (i % 131 == 0) {
scan->ranges[i] = std::numeric_limits<float>::quiet_NaN(); // khong do duoc
continue;
}
scan->ranges[i] = static_cast<float>(r) + noise(rng);
}
return scan;
}
vslam::PointCloudXYZPtr MakeFakeCloud(double t) {
auto cloud = std::make_shared<vslam::PointCloudXYZ>();
cloud->points.reserve(4000);
static std::mt19937 rng(7);
std::uniform_real_distribution<float> u(-1.0f, 1.0f);
for (int i = 0; i < 4000; ++i) {
const double a = static_cast<double>(i) / 4000.0 * 2.0 * kPi;
const double r = 1.5 + 0.8 * std::sin(a * 5.0 + t);
vslam::PointXYZ p;
p.x = static_cast<float>(r * std::cos(a)) + u(rng) * 0.05f;
p.y = static_cast<float>(r * std::sin(a)) + u(rng) * 0.05f;
p.z = static_cast<float>(0.3 + 0.5 * std::sin(a * 2.0)) + u(rng) * 0.03f;
cloud->points.push_back(p);
}
return cloud;
}
} // namespace
int main(int argc, char** argv) {
vslam::WebConfig cfg;
uint32_t map_w = 600, map_h = 400;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--port") cfg.port = static_cast<uint16_t>(std::atoi(next().c_str()));
else if (a == "--token") cfg.auth_token = next();
else if (a == "--assets") cfg.asset_dir = next();
else if (a == "--map-w") map_w = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--map-h") map_h = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--help") {
std::printf("cach dung: %s [--port N] [--token S] [--assets DIR] "
"[--map-w N] [--map-h N]\n", argv[0]);
return 0;
}
}
std::signal(SIGINT, OnSignal);
std::signal(SIGTERM, OnSignal);
std::atomic<bool> estop{false};
vslam::WebServer server(
cfg,
[&estop](const std::string& cmd, const std::string& body) -> vslam::StatusResponse {
VSLAM_INFO("lenh: " << cmd << " body=" << body);
if (cmd == "safety/estop") {
// Dung CHINH ham parse ma lop xac thuc dung. Neu handler va lop xac
// thuc doc body theo hai cach khac nhau thi khoang cach giua hai
// cach do la mot lo hong -- da tung nhu vay o ban truoc, khi handler
// tim chuoi "true" con lop xac thuc goi JsonGetBool.
bool on = false;
if (!vslam::JsonGetBool(body, "on", &on)) {
return vslam::StatusResponse::Error(vslam::StatusCode::kInvalidArgument,
"can truong bool \"on\"");
}
estop.store(on);
return vslam::StatusResponse::Ok();
}
if (cmd == "safety/reset") {
estop.store(false);
return vslam::StatusResponse::Ok();
}
return vslam::StatusResponse::Error(vslam::StatusCode::kNotFound, "lenh la");
},
[](double vx, double wz) {
VSLAM_DEBUG_THROTTLE(1.0, "teleop vx=" << vx << " wz=" << wz);
});
const vslam::StatusResponse st = server.Start();
if (!st.ok()) {
std::fprintf(stderr, "khong khoi dong duoc web: %s\n", st.message.c_str());
return 1;
}
std::printf("mo http://localhost:%u (Ctrl-C de dung)\n", server.port());
const auto map = MakeFakeMap(map_w, map_h, 0.05f);
auto clock = vslam::MakeSystemClock();
const auto t0 = std::chrono::steady_clock::now();
int tick = 0;
while (!g_stop.load()) {
const double t =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
vslam::WebSnapshot snap;
snap.stamp = clock->Now();
// Robot chay vong quanh hanh lang.
const double R = static_cast<double>(map_w) * 0.05 * 0.25;
snap.pose_map.x = R * std::cos(t * 0.15);
snap.pose_map.y = R * 0.35 * std::sin(t * 0.30);
snap.pose_map.theta = vslam::NormalizeAngle(
std::atan2(R * 0.35 * 0.30 * std::cos(t * 0.30), -R * 0.15 * std::sin(t * 0.15)));
snap.pose_odom = snap.pose_map;
snap.vx = 0.32;
snap.vyaw = 0.10 * std::sin(t * 0.3);
snap.slip_metric = 0.02 + 0.01 * std::sin(t * 2.0);
snap.roll = 0.01 * std::sin(t);
snap.pitch = -0.02 * std::cos(t * 0.7);
snap.accel_ok = true;
const double min_front = 0.5 + 0.45 * (1.0 + std::sin(t * 0.4));
snap.safety.min_front = min_front;
snap.safety.front_rays = 141;
snap.safety.front_blanked = 4;
snap.safety.front_usable = 137;
snap.safety.estop = estop.load();
if (estop.load()) {
snap.safety.state = "ESTOP";
snap.safety.detail = "dung khan cap tu web";
} else if (min_front < 0.40) {
snap.safety.state = "SCAN_STOP";
snap.safety.detail = "vat can " + std::to_string(min_front).substr(0, 4) + " m";
} else if (min_front < 0.90) {
snap.safety.state = "SCAN_SLOW";
snap.safety.detail = "vat can " + std::to_string(min_front).substr(0, 4) + " m";
} else {
snap.safety.state = "OK";
}
snap.slam.mode = "localization";
snap.slam.localized = true;
snap.slam.score = 0.65 + 0.2 * std::sin(t * 0.5);
snap.slam.map_version = 1;
snap.slam.process_ms = 120.0 + 40.0 * std::sin(t);
snap.health.lidar_hz = 24.9;
snap.health.camera_hz = 29.7;
snap.health.imu_hz = 199.4;
snap.health.ekf_hz = 50.0;
snap.health.clock_skew = 1.0000031;
snap.health.cpu_pct = 38.0 + 8.0 * std::sin(t * 0.2);
snap.health.rss_mb = 812.0;
snap.health.drops = {{"scan", 0}, {"cloud", 3}, {"camera", 1}};
snap.map = map;
// Ton trong tan so trong WebConfig. Day la viec ma luong web_tx that se
// lam: mot Snapshot khong dien truong nao thi truong do khong duoc gui.
// De tat ca cung 10 Hz la lang phi bang thong -- do chinh la loi lan do
// dau tien, PATH chay 9.8 Hz thay vi 1 Hz va an het 30 kB/s.
const int scan_every = std::max(1, static_cast<int>(10.0 / cfg.scan_hz));
const int cloud_every = std::max(1, static_cast<int>(10.0 / cfg.cloud_hz));
const int path_every = std::max(1, static_cast<int>(10.0 / cfg.path_hz));
if (tick % scan_every == 0) snap.scan = MakeFakeScan(t);
if (tick % cloud_every == 0) snap.cloud = MakeFakeCloud(t);
if (tick % path_every == 0) {
snap.trajectory.reserve(400);
for (int k = 0; k < 400; ++k) {
const double tk = t - static_cast<double>(400 - k) * 0.1;
snap.trajectory.push_back(
vslam::Pose2D{R * std::cos(tk * 0.15), R * 0.35 * std::sin(tk * 0.30), 0.0});
}
}
server.Publish(snap);
++tick;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 10 Hz
}
const vslam::WebServer::Stats s = server.stats();
std::printf("\nket noi=%lu khung_gui=%lu khung_drop=%lu byte=%lu lenh=%lu\n",
static_cast<unsigned long>(s.connections_total),
static_cast<unsigned long>(s.frames_sent),
static_cast<unsigned long>(s.frames_dropped),
static_cast<unsigned long>(s.bytes_sent),
static_cast<unsigned long>(s.commands_handled));
server.Stop();
return 0;
}

163
tools/vslam_world_export.cc Normal file
View File

@@ -0,0 +1,163 @@
// Doc `.world` cua Gazebo, raster hoa mesh va cham thanh luoi chiem dung.
//
// Muc dich: dung the gioi mo phong TU CHINH file world, thay vi tu mot `.db`
// da quet. Nho vay luoi cho sim, mesh cho khung 3D va tu the do dac deu o MOT
// he toa do -- xem ghi chu trong `vslam/gazebo_world.h`.
//
// vslam_world_export --world X.world --out Y.pgm [--res 0.05]
// [--z-min 0.05] [--z-max 1.20] [--models DIR]
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "vslam/gazebo_world.h"
#include "vslam/occupancy_map_io.h"
int main(int argc, char** argv) {
std::string world, out;
std::vector<std::string> model_paths;
vslam::WorldRasterOptions opt;
bool list_only = false;
bool bbox = false;
std::string meshes_out, colors_json;
bool meshes_visual = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--world") world = next();
else if (a == "--out") out = next();
else if (a == "--res") opt.resolution = std::atof(next().c_str());
else if (a == "--z-min") opt.z_min = std::atof(next().c_str());
else if (a == "--z-max") opt.z_max = std::atof(next().c_str());
else if (a == "--models") model_paths.push_back(next());
else if (a == "--list") list_only = true;
else if (a == "--bbox") bbox = true;
else if (a == "--meshes") meshes_out = next();
else if (a == "--meshes-visual") meshes_visual = true;
else if (a == "--colors") colors_json = next();
else if (a == "--help") {
std::printf(
"cach dung: %s --world X.world --out Y.pgm [--res 0.05]\n"
" [--z-min 0.05] [--z-max 1.20] [--models DIR] [--list]\n"
"\n"
" --list chi liet ke model phan giai duoc roi thoat\n"
" --models co the lap lai; khong co thi dung $GAZEBO_MODEL_PATH\n"
" roi ~/.gazebo/models\n"
" --meshes F.bin xuat hinh hoc cho khung 3D thay vi luoi\n"
" --meshes-visual dung mesh HIEN THI thay vi mesh va cham\n"
" --colors F.json bang mau tu texture (gen_model_colors.py)\n",
argv[0]);
return 0;
} else {
std::fprintf(stderr, "tham so la: %s\n", a.c_str());
return 2;
}
}
if (world.empty()) {
std::fprintf(stderr, "can --world X.world\n");
return 2;
}
vslam::GazeboWorld gw;
size_t skipped = 0;
{
const vslam::StatusResponse st =
vslam::LoadGazeboWorld(world, model_paths, &gw, &skipped);
if (!st.ok()) {
std::fprintf(stderr, "%s\n", st.message.c_str());
return 1;
}
}
if (list_only) {
std::printf("%zu model, bo qua %zu\n", gw.models.size(), skipped);
for (const auto& m : gw.models) {
std::printf(" %-44s (%7.2f, %7.2f, %5.2f) yaw %6.2f %s\n",
m.model_name.c_str(), m.x, m.y, m.z, m.yaw,
m.collision_obj.empty() ? "KHONG MESH" : "");
}
return 0;
}
// --- Che do chan doan: bao loi TUNG model, de tim mesh van xa ---
//
// Mot mesh dat sai don vi hoac sai truc lam bao loi ca the gioi phinh ra
// hang tram met, va tu bao loi tong thi khong biet thu pham la ai.
if (bbox) {
for (const auto& m : gw.models) {
vslam::GazeboWorld one;
one.models.push_back(m);
vslam::OccupancyGrid g;
if (!vslam::RasterizeGazeboWorld(one, opt, &g).ok()) continue;
const double w = g.width * g.resolution, h = g.height * g.resolution;
if (w > 60.0 || h > 60.0) {
std::printf(" %-46s %7.1f x %7.1f m goc (%8.1f, %8.1f)\n",
m.model_name.c_str(), w, h,
g.origin.position.x, g.origin.position.y);
}
}
return 0;
}
if (!meshes_out.empty()) {
vslam::WorldMeshes wm;
const vslam::StatusResponse st =
vslam::ExportWorldMeshes(gw, meshes_visual, &wm);
if (!st.ok()) {
std::fprintf(stderr, "%s\n", st.message.c_str());
return 1;
}
size_t colored = 0;
if (!colors_json.empty()) {
colored = vslam::ApplyModelColors(colors_json, &wm);
}
std::string blob;
vslam::EncodeWorldMeshes(wm, &blob);
FILE* f = std::fopen(meshes_out.c_str(), "wb");
if (f == nullptr) {
std::fprintf(stderr, "khong ghi duoc %s\n", meshes_out.c_str());
return 1;
}
std::fwrite(blob.data(), 1, blob.size(), f);
std::fclose(f);
size_t ntri = 0;
for (const auto& g : wm.geoms) ntri += g.tri.size() / 9;
std::printf("mesh (%s): %zu hinh hoc (%zu co mau), %zu the hien, "
"%zu tam giac, %.2f MB -> %s\n",
meshes_visual ? "hien thi" : "va cham",
wm.geoms.size(), colored, wm.instances.size(), ntri,
blob.size() / 1048576.0, meshes_out.c_str());
return 0;
}
if (out.empty()) {
std::fprintf(stderr, "can --out Y.pgm (hoac dung --list)\n");
return 2;
}
vslam::OccupancyGrid grid;
{
const vslam::StatusResponse st = vslam::RasterizeGazeboWorld(gw, opt, &grid);
if (!st.ok()) {
std::fprintf(stderr, "%s\n", st.message.c_str());
return 1;
}
}
std::string yaml = out;
const size_t dot = yaml.rfind('.');
if (dot != std::string::npos) yaml = yaml.substr(0, dot);
yaml += ".yaml";
const vslam::StatusResponse w = vslam::SaveOccupancyMap(grid, yaml);
if (!w.ok()) {
std::fprintf(stderr, "ghi ban do: %s\n", w.message.c_str());
return 1;
}
std::printf("ban do: %ux%u @ %.3f m/o -> %s\n", grid.width, grid.height,
static_cast<double>(grid.resolution), yaml.c_str());
return 0;
}