reloc,web: dinh vi lai TREN DOC (slope.enabled) -- loc gia thuyet bang do nghieng IMU vs do doc ban do, chan mu doc truc (ShiftScoreRatio), vong DUNG YEN khong xoay (ty le nho nhat >= 3 vong / hai cho cung pose), tu chay bo thang tren doc; camera VPR+PnP tren doc (>= 2 anh trung, khop nghieng, LiDAR khong phan doi, pose = trung binh camera) -- sim 10 cho chot dung 1.4-2.9 cm, 0 chot sai; web 3D: ban do uon theo san (FLH1), scan/quy dao theo z, het nen lung, sua ro GPU; CMake: TensorRT tren CMake < 3.17

This commit is contained in:
trung09122002
2026-10-06 10:17:17 +07:00
parent b1ab04c51e
commit f0c5ddb6b8
19 changed files with 1947 additions and 68 deletions

View File

@@ -260,6 +260,15 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export)
${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js)
set_tests_properties(www_orbit_camera PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
# Do cao san (che do doc): khoi FLH1 sau RLE, mat phang ban do uon theo san,
# scan/cloud/quy dao nang theo z. Sai dau o phep doi truc -> doc nghieng
# nguoc, van ve duoc. Kem: mat san the gioi KHONG dung lai moi khung (ban
# cu ro ~1 geometry GPU moi khung khi chay tu `.world`).
add_test(NAME www_map_floor
COMMAND ${VSLAM_NODE_EXE}
${CMAKE_CURRENT_SOURCE_DIR}/www/test_map_floor.js)
set_tests_properties(www_map_floor PROPERTIES
PASS_REGULAR_EXPRESSION "=> DAT")
else()
message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend")
endif()

View File

@@ -129,6 +129,60 @@ TEST(BinaryCodec, MapFullNenTotTrenBanDoThua) {
EXPECT_EQ(out.data, m.data);
}
// Che do doc: khoi do cao san noi sau RLE. Phan luoi 2D phai giai y het khung
// khong co khoi (client cu bo qua duoi khung), va khoi giu dung tung o, ke ca
// o CHUA BIET va gia tri am (tang ham).
TEST(BinaryCodec, MapFullKhoiDoCaoSan) {
OccupancyGrid m;
m.width = 40;
m.height = 30;
m.resolution = 0.05f;
m.origin.position.x = -1.25;
m.origin.position.y = -2.5;
m.data.assign(static_cast<size_t>(m.width) * m.height, -1);
for (uint32_t x = 5; x < 35; ++x) m.data[10 * m.width + x] = 100;
MapFloorGrid f;
f.resolution = 0.2f;
f.width = 10;
f.height = 8;
f.origin_x = -1.25f;
f.origin_y = -2.5f;
f.mm.assign(80, kFloorUnknown);
f.mm[0] = 0;
f.mm[17] = 1500;
f.mm[79] = -320;
std::string plain, with_floor;
EncodeMapFull(m, UnixTime::fromSec(2.0), &plain);
EncodeMapFull(m, UnixTime::fromSec(2.0), &with_floor, BinaryType::kMapFull, &f);
ASSERT_EQ(with_floor.size(), plain.size() + 24 + 80 * 2);
EXPECT_EQ(with_floor.compare(0, plain.size(), plain), 0);
OccupancyGrid out;
MapFloorGrid fout;
ASSERT_TRUE(DecodeMapFull(with_floor, &out, &fout));
EXPECT_EQ(out.data, m.data);
EXPECT_EQ(fout.width, f.width);
EXPECT_EQ(fout.height, f.height);
EXPECT_NEAR(fout.resolution, f.resolution, 1e-6);
EXPECT_NEAR(fout.origin_x, f.origin_x, 1e-6);
EXPECT_NEAR(fout.origin_y, f.origin_y, 1e-6);
EXPECT_EQ(fout.mm, f.mm);
// Khung khong co khoi: luoi san tra ve rong, khong phai rac cua lan truoc.
ASSERT_TRUE(DecodeMapFull(plain, &out, &fout));
EXPECT_EQ(fout.width, 0u);
EXPECT_TRUE(fout.mm.empty());
// Kich thuoc sai (mm thieu o) -> khong ghi khoi, khung y het ban phang.
MapFloorGrid bad = f;
bad.mm.pop_back();
std::string with_bad;
EncodeMapFull(m, UnixTime::fromSec(2.0), &with_bad, BinaryType::kMapFull, &bad);
EXPECT_EQ(with_bad, plain);
}
// --- Ban do voxel 3D -------------------------------------------------------
namespace {

View File

@@ -261,6 +261,292 @@ TEST(GlobalLocalizer, PhongDoiXungQuay180ChanOCongHuong) {
EXPECT_EQ(Decide(m, 5, cfg), RelocVerdict::kAmbiguousYaw);
}
// --- Bang chung ngoai LiDAR (`admit`) -------------------------------------
//
// Tren doc, do nghieng IMU noi robot dang chuc bao nhieu, ve phia nao; ban do
// biet doc o dau. Hai test dau la hai ca LiDAR nhap nhang o tren -- bang chung
// ngoai phai PHAN XU dung. Hai test sau khoa phan an toan: khong bao gio day
// mot khop LiDAR kem ro len thang, va bang chung "cai gi cung duoc" khong lam
// lech nguoi thang.
TEST(GlobalLocalizer, BangChungNgoaiTachHaiPhongGiongHet) {
OccupancyGrid g = MakeGrid(24.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
AsymRoom(&g, 12.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
// Vd phong phai la san doc ma IMU do phang: robot KHONG the o do.
const RelocAdmit admit = [&](const Pose2D& T) { return Pose2DCompose(T, odom).x < 12.0; };
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
EXPECT_TRUE(m.tilt_used);
EXPECT_FALSE(m.tilt_conflict);
EXPECT_GT(m.tilt_rejected, 0);
const Pose2D est = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1);
EXPECT_LT(std::fabs(AngleDiff(est.theta, truth.theta)) * 180.0 / M_PI, 1.0);
EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAccept)
<< "ty le " << m.ratio() << ", ty le huong " << m.ratio_yaw();
for (const RelocHypothesis& h : m.hyps) {
EXPECT_LT(Pose2DCompose(h.map_from_odom, odom).x, 12.0) << "gia thuyet bi loai van tra ve";
}
}
TEST(GlobalLocalizer, BangChungNgoaiChonHuongPhongDoiXung) {
// Phong doi xung quay 180 do: LiDAR khong biet huong (PhongDoiXungQuay180...).
// Bang chung chi nhan nua huong quanh `want` -> ra DUNG `want`, ca hai chieu:
// chinh bang chung quyet dinh, khong phai may rui.
OccupancyGrid g = MakeGrid(9.0, 6.0);
Room(&g, 0.5, 0.5, 8.5, 5.5);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth{4.5, 3.0, 0.3};
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
for (const double want : {truth.theta, truth.theta + M_PI}) {
const RelocAdmit admit = [&](const Pose2D& T) {
return std::fabs(AngleDiff(Pose2DCompose(T, odom).theta, want)) < M_PI / 2;
};
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
const Pose2D est = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::fabs(AngleDiff(est.theta, want)) * 180.0 / M_PI, 1.0) << "want " << want;
EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1);
EXPECT_GE(m.ratio_yaw(), cfg.min_ratio_yaw) << "doi thu huong (lat 180) chua bi loai";
EXPECT_NE(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAmbiguousYaw);
}
}
TEST(GlobalLocalizer, BangChungMauThuanLiDARChacThiGiuLiDAR) {
// Phong KHONG doi xung: LiDAR chac chan. Bang chung noi "khong the o do"
// (vd IMU hong) -- KHONG duoc day mot cho kem han len thang. Ket qua phai y
// het khi khong co bang chung, va danh dau xung dot.
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
const RelocMatch base = GlobalMatch(f, pts, cfg);
const RelocAdmit admit = [&](const Pose2D& T) {
const Pose2D p = Pose2DCompose(T, odom);
return std::hypot(p.x - truth.x, p.y - truth.y) > 1.5;
};
const RelocMatch m = GlobalMatch(f, pts, cfg, admit);
ASSERT_TRUE(m.ok);
EXPECT_TRUE(m.tilt_conflict);
EXPECT_FALSE(m.tilt_used);
EXPECT_NEAR(m.map_from_odom.x, base.map_from_odom.x, 1e-9);
EXPECT_NEAR(m.map_from_odom.y, base.map_from_odom.y, 1e-9);
EXPECT_NEAR(m.map_from_odom.theta, base.map_from_odom.theta, 1e-9);
EXPECT_DOUBLE_EQ(m.s1, base.s1);
EXPECT_DOUBLE_EQ(m.s2, base.s2);
EXPECT_DOUBLE_EQ(m.s2_yaw, base.s2_yaw);
}
TEST(GlobalLocalizer, BangChungChapNhanHetKhongLechNguoiThang) {
// San phang + IMU phang: moi gia thuyet hop le. Nguoi thang va cong phai
// nhu cu; ung vien them chi co the lam doi thu MANH hon (than trong hon).
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
const RelocMatch base = GlobalMatch(f, pts, cfg);
const RelocMatch m = GlobalMatch(f, pts, cfg, [](const Pose2D&) { return true; });
ASSERT_TRUE(m.ok);
EXPECT_FALSE(m.tilt_used);
EXPECT_FALSE(m.tilt_conflict);
const Pose2D a = Pose2DCompose(base.map_from_odom, odom);
const Pose2D b = Pose2DCompose(m.map_from_odom, odom);
EXPECT_LT(std::hypot(a.x - b.x, a.y - b.y), 0.01);
EXPECT_LT(std::fabs(AngleDiff(a.theta, b.theta)), 0.002);
EXPECT_LE(m.ratio(), base.ratio() + 1e-9);
EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), Decide(base, cfg.min_cycles, cfg));
}
TEST(GlobalLocalizer, SuyBienDocTrucHanhLangVaPhong) {
// Hanh lang dai 20 m chi co hai tuong song song: dich doc hanh lang khong
// lam xau khop (~100%). Phong khong doi xung: dich 1 m thi tut ro. Day la
// kiem chan chot nho do nghieng (sim: doc 30 do, chot lech 0.77 m doc lan).
OccupancyGrid g = MakeGrid(24.0, 6.0);
Fill(&g, 0.0, 1.5, 24.0, 4.5, 0);
Fill(&g, 0.0, 1.5, 24.0, 1.6, 100);
Fill(&g, 0.0, 4.4, 24.0, 4.5, 100);
const LikelihoodField fc = LikelihoodField::FromGrid(g, 0.15);
const Pose2D in_corridor{12.0, 3.0, 0.2};
const Pose2D odom{-1.0, 0.5, -0.3};
// T_map_odom dung = truth o (-) odom.
auto T_of = [&](const Pose2D& truth) { return Pose2DCompose(truth, Pose2DInverse(odom)); };
const double rc =
ShiftScoreRatio(fc, ToOdom(Raycast(g, in_corridor, 720, 6.0), odom), T_of(in_corridor), 1.0);
EXPECT_GT(rc, 0.95) << "hanh lang ma dich doc truc lai tut diem";
OccupancyGrid r = MakeGrid(12.0, 10.0);
AsymRoom(&r, 0.0, 0.0);
const LikelihoodField fr = LikelihoodField::FromGrid(r, 0.15);
const double rr =
ShiftScoreRatio(fr, ToOdom(Raycast(r, kAsymTruth), odom), T_of(kAsymTruth), 1.0);
EXPECT_GT(rr, 0.0);
EXPECT_LT(rr, 0.9) << "phong co dac diem ma dich 1 m van giu diem";
}
// --- Vong DUNG YEN (DecideStatic) ---
//
// Dung yen thi cac vong nhin gan y het: thu mai roi chot o vong VOT qua cong
// la dao nhieu. Sim 2026-10-05 da lot hai lan: chot vong le (1.63 sau 21 vong
// ~1.44), roi trung vi 3 vong (1.63 / 1.40 / 1.64). Luat: NHO NHAT qua moi vong
// cung cho.
namespace {
StaticRound Round(double x, double ratio, double yaw = 3.5, double shift = 0.85) {
StaticRound r;
r.robot = Pose2D{x, 23.0, 1.67};
r.map_from_odom = r.robot; // odom trung map trong test
r.ratio = ratio;
r.ratio_yaw = yaw;
r.shift = shift;
return r;
}
} // namespace
TEST(GlobalLocalizer, DungYenKhongDaoNhieu) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
// Doi thu that (~1.44) chi bi bo sot o vai vong -> KHONG bao gio chot.
for (const double r : {1.63, 1.40, 1.64, 1.63, 1.65, 1.62, 1.64}) {
EXPECT_NE(DecideStatic(&h, Round(1.2, r), {}, cfg, true, &ax, &why), RelocVerdict::kAccept)
<< "vong " << h.size() << ": " << why;
}
}
TEST(GlobalLocalizer, DungYenDuVongDeuCaoThiChot) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.64), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(DecideStatic(&h, Round(1.21, 1.95), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(DecideStatic(&h, Round(1.19, 1.96), {}, cfg, true, &ax, &why), RelocVerdict::kAccept) << why;
EXPECT_FALSE(ax);
}
TEST(GlobalLocalizer, DungYenDoiNguoiThangThiDemLai) {
const GlobalLocalizerConfig cfg;
std::vector<StaticRound> h;
bool ax = false;
std::string why;
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
// Vong 3 ra cho khac (cach 1 m) -> dem lai tu dau, chua du vong.
EXPECT_EQ(DecideStatic(&h, Round(2.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles);
EXPECT_EQ(h.size(), 1u);
}
TEST(GlobalLocalizer, DungYenChanMuDocTrucVaNhapNhang) {
const GlobalLocalizerConfig cfg;
bool ax = false;
std::string why;
{
// Mot vong mu doc truc (dich 1 m giu 100%) la du chan, ke ca ty le cao.
std::vector<StaticRound> h;
DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why);
DecideStatic(&h, Round(1.2, 2.0, 3.5, 1.0), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous);
EXPECT_TRUE(ax);
// Khong ap kiem doc truc (vd khong co bang chung nghieng) -> qua.
std::vector<StaticRound> h2 = h;
h2.pop_back();
EXPECT_EQ(DecideStatic(&h2, Round(1.2, 2.0), {}, cfg, false, &ax, &why), RelocVerdict::kAccept);
}
{
std::vector<StaticRound> h;
for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why),
RelocVerdict::kAmbiguousYaw);
}
{
std::vector<StaticRound> h;
for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why);
EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous);
EXPECT_FALSE(ax);
}
}
// Hai cho (truoc / sau khi bo tren doc). Robot di 0.5 m nen pose robot doi,
// nhung T_map_odom cua CUNG gia thuyet giu nguyen.
namespace {
StaticRound Placed(double y, double ratio, const Pose2D& T) {
StaticRound r;
r.robot = Pose2D{1.2, y, 1.67};
r.map_from_odom = T;
r.ratio = ratio;
r.ratio_yaw = 3.5;
r.shift = 0.85;
return r;
}
// Chay cac vong o mot cho; tra verdict vong cuoi.
RelocVerdict AtPlace(std::vector<StaticRound>* h, const std::vector<StaticPlace>& prev, double y,
const Pose2D& T, std::initializer_list<double> ratios, std::string* why) {
const GlobalLocalizerConfig cfg;
bool ax = false;
RelocVerdict v = RelocVerdict::kFailed;
for (const double r : ratios) v = DecideStatic(h, Placed(y, r, T), prev, cfg, true, &ax, why);
return v;
}
} // namespace
TEST(GlobalLocalizer, HaiChoCungPoseMoiChoDeuQuaThiChot) {
// Sim: gan dinh doc 5 do, cho 1 ty le 1.57-1.60 (duoi chuan mot cho 1.60),
// bo 0.5 m, cho 2 ~1.49 -> hai cho cung pose, moi cho deu >= 1.30 -> chot.
const Pose2D T{0.1, -0.2, 0.05};
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
EXPECT_NE(AtPlace(&h, places, 23.0, T, {1.57, 1.60, 1.58}, &why), RelocVerdict::kAccept) << why;
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.49}, &why), RelocVerdict::kNeedCycles) << "1 vong chua du";
EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.47, 1.50}, &why), RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, HaiChoMaMotChoTungTutThiKhongChot) {
// Dung kieu chot SAI o chan doc 10 / 15 do: nguoi thang sai on dinh, ty le
// 1.0-1.2 roi mot vong nhay 1.32. Moi cho phai qua o MOI vong cua no.
const Pose2D T{0.1, -0.2, 0.05};
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
AtPlace(&h, places, 9.0, T, {1.05, 1.19, 1.32}, &why);
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_NE(AtPlace(&h, places, 8.5, T, {1.32, 1.34, 1.31}, &why), RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, HaiChoKhacGiaThuyetThiKhongChot) {
// Hai cho deu qua 1.30 nhung chi ve HAI pose khac nhau (T lech 0.5 m) -> khong chot.
std::vector<StaticRound> h;
std::vector<StaticPlace> places;
std::string why;
AtPlace(&h, places, 23.0, Pose2D{0.1, -0.2, 0.05}, {1.5, 1.5, 1.5}, &why);
places.push_back(SummarizePlace(h));
h.clear();
EXPECT_NE(AtPlace(&h, places, 23.5, Pose2D{0.1, 0.3, 0.05}, {1.5, 1.5, 1.5}, &why),
RelocVerdict::kAccept) << why;
}
TEST(GlobalLocalizer, DiemCanhLacTutKhiPoseSai) {
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);

View File

@@ -97,3 +97,37 @@ TEST(FloorModel, RollNghiengSangTrai) {
ASSERT_TRUE(fm.FloorAt(-1.0, 0.0, &z));
EXPECT_NEAR(z, std::tan(5 * kDeg), 1e-6);
}
// Do doc san + do lech nghieng: nen cua viec loai gia thuyet dinh vi lai tren
// doc (GlobalMatch + `admit`). Sai dau o day thi bo loc loai DUNG cho that.
TEST(FloorModel, DoDocVaDoLechNghieng) {
// Doc 15 do di LEN theo +y cua map (node huong +y, mui ngoc = pitch am).
std::vector<FloorNode> nodes(1);
nodes[0].theta = M_PI / 2;
nodes[0].pitch = -15 * kDeg;
FloorModel fm;
fm.Build(nodes);
double gx = 0, gy = 0;
ASSERT_TRUE(FloorGradientAt(fm, 0.3, 0.2, 1.5, &gx, &gy));
EXPECT_NEAR(gx, 0.0, 1e-9);
EXPECT_NEAR(gy, std::tan(15 * kDeg), 1e-9);
// Node xa hon max_dist -> khong biet san o do.
EXPECT_FALSE(FloorGradientAt(fm, 3.0, 0.0, 1.5, &gx, &gy));
const double t15 = std::tan(15 * kDeg);
// Robot mui LEN doc (yaw +y) do duoc pitch -15: khop.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, M_PI / 2, 0.0, t15), 0.0, 1e-9);
// Cung do nghieng nhung gia thuyet mui XUONG doc (lat 180 do): lech 2 lan doc.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, -M_PI / 2, 0.0, t15), 2 * t15, 1e-9);
// Gia thuyet o san PHANG: lech dung bang doc do duoc.
EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, 0.3, 0.0, 0.0), t15, 1e-9);
// Mui NGANG doc (yaw +x, doc len ve +y = ben TRAI): roll duong, pitch 0.
const double roll = std::atan(t15); // cos(pitch) = 1
EXPECT_NEAR(TiltResidual(roll, 0.0, 0.0, 0.0, t15), 0.0, 1e-9);
EXPECT_NEAR(TiltResidual(-roll, 0.0, 0.0, 0.0, t15), 2 * t15, 1e-9);
// Than nghieng ca hai truc (mui len doc cheo 45 do): van khop khi dung huong.
const double g = 0.2; // doc theo +y
const double sf = g * std::sin(M_PI / 4), sl = g * std::cos(M_PI / 4);
const double p = -std::atan(sf), r = std::atan(sl * std::cos(p));
EXPECT_NEAR(TiltResidual(r, p, M_PI / 4, 0.0, g), 0.0, 1e-9);
}

405
test/www/test_map_floor.js Normal file
View File

@@ -0,0 +1,405 @@
// Do cao SAN cua ban do SLAM (che do doc): giai khoi FLH1 o app.js, uon mat
// phang ban do va nang scan/cloud/quy dao o app3d.js.
//
// ================== VI SAO CAN BAI KIEM NAY ==================
// Mat phang ban do 2D ve phang o z = 0 trong khi tuong voxel o z that: tren
// tang cao 1.5 m nguoi xem thay tuong lo lung con san "thung" xuong tang duoi.
// Sai mot dau trong phep doi truc cuc bo -> ROS (PlaneGeometry quay -PI/2
// quanh X) thi doc nghieng NGUOC chieu -- van ve duoc, khong mot loi nao.
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const WWW = path.join(__dirname, '..', '..', 'libs', 'vslam_web', 'www');
let bad = 0;
function check(name, cond, chiTiet) {
if (cond) return;
bad++;
console.log(` ${name}: HONG${chiTiet ? ' -- ' + chiTiet : ''}`);
}
const near = (a, b, tol) => a !== null && Math.abs(a - b) <= tol;
// --- Khung ban do y het binary_codec.cc EncodeMapFull ----------------------
// Luoi 2D 0.05 m, 40 x 20 o, mot run duy nhat (toan o trong = 0).
const MAP = { res: 0.05, w: 40, h: 20, ox: -1.0, oy: 2.0 };
// Luoi san 0.2 m phu cung khung: 10 x 5 o. Doc 1 m/1 m theo +x tu cot 2 toi
// cot 7 (z = 0 .. 1.0), san tren 1.5 m o cot 8-9; hang 4 chua biet. Mot HO
// -0.1 m o goc tay-nam (hang 0, cot 0-1) de bat loi lat chieu y.
const FL = { res: 0.2, w: 10, h: 5 };
function floorMm(c, r) {
if (r === 4) return -32768;
if (c >= 8) return 1500;
if (c < 2) return r === 0 ? -100 : 0;
return Math.round((c - 2) * 200); // tam o: doc 45 do de so de doc
}
function mapFrame(withFloor) {
const n = MAP.w * MAP.h;
const runs = Math.ceil(n / 65535);
const tail = withFloor ? 24 + FL.w * FL.h * 2 : 0;
const buf = new ArrayBuffer(16 + 28 + runs * 3 + tail);
const dv = new DataView(buf);
dv.setUint8(0, 0x56); dv.setUint8(1, 0x53); dv.setUint8(2, 0x4C); dv.setUint8(3, 0x31);
dv.setUint8(4, 3);
dv.setUint8(5, 1);
let o = 16;
dv.setFloat32(o, MAP.res, true);
dv.setInt32(o + 4, MAP.w, true);
dv.setInt32(o + 8, MAP.h, true);
dv.setFloat32(o + 12, MAP.ox, true);
dv.setFloat32(o + 16, MAP.oy, true);
dv.setFloat32(o + 20, 0, true);
dv.setUint32(o + 24, runs, true);
o += 28;
dv.setUint16(o, n, true);
dv.setInt8(o + 2, 0);
o += 3;
if (withFloor) {
'FLH1'.split('').forEach((ch, i) => dv.setUint8(o + i, ch.charCodeAt(0)));
dv.setFloat32(o + 4, FL.res, true);
dv.setInt32(o + 8, FL.w, true);
dv.setInt32(o + 12, FL.h, true);
dv.setFloat32(o + 16, MAP.ox, true);
dv.setFloat32(o + 20, MAP.oy, true);
for (let r = 0; r < FL.h; ++r) {
for (let c = 0; c < FL.w; ++c) {
dv.setInt16(o + 24 + (r * FL.w + c) * 2, floorMm(c, r), true);
}
}
}
return dv;
}
// --- Phan 1: app.js giai khoi ----------------------------------------------
const el = () => ({
textContent: '', className: '', value: '', checked: false, style: {},
width: 0, height: 0, clientWidth: 800, clientHeight: 600,
addEventListener() {}, getContext: () => ctx2d(), classList: { toggle() {}, add() {}, remove() {} },
appendChild() {}, querySelectorAll: () => [], getBoundingClientRect: () =>
({ left: 0, top: 0, width: 800, height: 600 }),
});
const ctx2d = () => new Proxy({}, {
get: (t, k) => (k === 'canvas' ? el() : () => ({ data: new Uint8ClampedArray(4) })),
});
const ws = { readyState: 1, send() {} };
const sbApp = {
console, Date, Math, JSON, Set, Map, Number, String, Array, Object,
Float32Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
DataView, ArrayBuffer, isNaN, parseFloat, parseInt,
document: {
getElementById: () => el(), querySelectorAll: () => [], querySelector: () => el(),
addEventListener() {}, createElement: () => el(), body: el(), documentElement: el(),
},
window: { addEventListener() {}, devicePixelRatio: 1, location: { search: '', host: 'x' } },
location: { search: '', host: 'x', protocol: 'http:' },
navigator: { userAgent: 'node' },
requestAnimationFrame: () => 0,
setInterval: () => 0, setTimeout: () => 0, clearTimeout: () => 0,
fetch: () => new Promise(() => {}),
URLSearchParams: class { constructor() {} get() { return null; } },
WebSocket: function () { return ws; },
performance: { now: () => 0 },
// rasterize() cua app.js dung ImageData khi nhan khung ban do.
ImageData: function (w, h) { this.width = w; this.height = h;
this.data = new Uint8ClampedArray(w * h * 4); },
};
sbApp.globalThis = sbApp;
vm.createContext(sbApp);
try {
vm.runInContext(fs.readFileSync(path.join(WWW, 'app.js'), 'utf8'), sbApp, { filename: 'app.js' });
} catch (e) {
console.log(' (app.js dung som: ' + e.message + ')');
}
let state = null;
try { state = vm.runInContext('state', sbApp); } catch (e) { /* bao o duoi */ }
if (typeof sbApp.onBinary !== 'function' || !state) {
console.log(' KHONG lay duoc onBinary/state tu app.js\n\n => HONG');
process.exit(1);
}
sbApp.onBinary(mapFrame(true));
const g = state.map;
check('giai: co ban do', g && g.w === MAP.w && g.h === MAP.h);
const f = g && g.floor;
check('giai: co khoi san', f && f.w === FL.w && f.h === FL.h, JSON.stringify(f && { w: f.w, h: f.h }));
if (f) {
check('giai: res/goc', Math.abs(f.res - 0.2) < 1e-6 && Math.abs(f.ox - MAP.ox) < 1e-6 &&
Math.abs(f.oy - MAP.oy) < 1e-6);
check('giai: san tren', f.mm[2 * FL.w + 9] === 1500, String(f.mm[2 * FL.w + 9]));
check('giai: o chua biet', f.mm[4 * FL.w + 3] === -32768, String(f.mm[4 * FL.w + 3]));
}
// Luoi 2D khong bi khoi phia sau lam lech.
check('giai: o 2D dung', g && g.cells.every((v) => v === 0));
sbApp.onBinary(mapFrame(false));
check('khong khoi: floor = null', state.map && state.map.floor === null);
// --- Phan 2: app3d.js uon mat phang + nang scan/cloud/quy dao --------------
class V3 {
constructor(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }
set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }
}
const node = () => ({ position: new V3(), rotation: { x: 0, y: 0, z: 0 }, userData: {},
visible: true });
class Attr {
constructor(a, n) { this.array = a; this.itemSize = n; this.count = a.length / n; }
getX(i) { return this.array[i * 3]; }
getY(i) { return this.array[i * 3 + 1]; }
setZ(i, v) { this.array[i * 3 + 2] = v; }
}
// Bo cuc dinh y het three.js PlaneGeometry: hang tu +h/2 xuong -h/2, cot tu
// -w/2 sang +w/2, mat phang z = 0.
class PlaneGeometry {
constructor(w, h, sx = 1, sy = 1) {
const a = [];
for (let iy = 0; iy <= sy; ++iy) {
for (let ix = 0; ix <= sx; ++ix) a.push(ix * w / sx - w / 2, -(iy * h / sy - h / 2), 0);
}
this.attributes = { position: new Attr(new Float32Array(a), 3) };
}
dispose() {}
}
class BufferGeometry {
constructor() { this.attributes = {}; }
setAttribute(n, a) { this.attributes[n] = a; }
setFromPoints(p) { this.points = p; return this; }
dispose() {}
}
const obj = () => class {
constructor(g, m) { Object.assign(this, node()); this.geometry = g; this.material = m; }
};
const THREE = {
PlaneGeometry, BufferGeometry, Vector3: V3,
BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } },
Mesh: obj(), Points: obj(), Line: obj(),
MeshBasicMaterial: class { constructor(o) { Object.assign(this, o); } dispose() {} },
PointsMaterial: class { constructor(o) { Object.assign(this, o); } },
LineBasicMaterial: class { constructor(o) { Object.assign(this, o); } },
CanvasTexture: class { dispose() {} },
NearestFilter: 1, LinearMipmapLinearFilter: 2,
};
class Root {
constructor() { this.children = []; }
add(c) { this.children.push(c); }
remove(c) { this.children = this.children.filter((x) => x !== c); }
}
const canvas = () => ({
width: 0, height: 0,
getContext: () => ({
createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }),
putImageData() {},
}),
});
const sb3 = { THREE, console, Math, Int16Array, Int32Array, Float32Array,
window: {}, document: { createElement: canvas } };
vm.createContext(sb3);
vm.runInContext(fs.readFileSync(path.join(WWW, 'app3d.js'), 'utf8') +
'\n;this.__V3D = V3D; this.__at = v3dFloorAt; this.__fill = v3dFloorFill;' +
'\n;this.__map = v3dSetMap; this.__scan = v3dSetScan; this.__cloud = v3dSetCloud;' +
'\n;this.__path = v3dSetPath; this.__render = v3dRender; this.__lift = FLOOR_LIFT;' +
'\n;this.__worldVis = v3dSetWorldVisible; this.__ground = v3dSetGround;', sb3);
const V3D = sb3.__V3D;
V3D.ready = true;
V3D.root = new Root();
const L = sb3.__lift; // mat ban do uon nang len tren san uoc luong
check('nang: 2-10 cm', L >= 0.02 && L <= 0.1, String(L));
// v3dFloorAt: tam o tra dung gia tri o; giua hai tam noi suy tuyen tinh.
{
const fl = f;
const cx = (c) => MAP.ox + (c + 0.5) * 0.2, cy = (r) => MAP.oy + (r + 0.5) * 0.2;
check('at: tam o san duoi', near(sb3.__at(fl, cx(0), cy(1)), 0.0, 1e-6));
check('at: tam o san tren', near(sb3.__at(fl, cx(9), cy(1)), 1.5, 1e-6));
// Giua tam cot 4 (0.4) va cot 5 (0.6) -> 0.5.
check('at: noi suy tren doc', near(sb3.__at(fl, cx(4) + 0.1, cy(1)), 0.5, 1e-6),
String(sb3.__at(fl, cx(4) + 0.1, cy(1))));
// Chi o chua biet -> null (khong phai 0).
check('at: chua biet = null', sb3.__at(fl, cx(3), cy(4)) === null,
String(sb3.__at(fl, cx(3), cy(4))));
check('at: ngoai luoi = null', sb3.__at(fl, MAP.ox - 5, cy(1)) === null);
check('at: khong co luoi = null', sb3.__at(null, 0, 0) === null);
// Lap o chua biet bang o DA BIET gan nhat: hang 4 lay hang 3.
const filled = sb3.__fill(fl);
check('fill: khong con o chua biet', filled && filled.mm.every((v) => v !== -32768));
check('fill: lay o ke', filled && filled.mm[4 * FL.w + 9] === 1500 &&
filled.mm[4 * FL.w + 4] === 400, filled && String(filled.mm.slice(40)));
check('fill: khong dong vao luoi goc', fl.mm[4 * FL.w + 9] === -32768);
}
// v3dSetMap: dinh mat phang o dung cao do san, dung chieu doc.
{
sb3.__map({ ...g, data: g.cells, floor: f });
const m = V3D.mapMesh;
check('map: co mesh', !!m);
if (m) {
check('map: quay -PI/2 quanh X', Math.abs(m.rotation.x + Math.PI / 2) < 1e-9);
const p = m.geometry.attributes.position;
check('map: chia doan theo luoi san', p.count === (FL.w + 1) * (FL.h + 1), String(p.count));
// Dinh cuc bo -> ROS: x = pos.x + lx, y = -pos.z + ly, z = pos.y + lz.
const ros = (i) => [m.position.x + p.getX(i), -m.position.z + p.getY(i),
m.position.y + p.array[i * 3 + 2]];
const zAt = (qx, qy) => {
for (let i = 0; i < p.count; ++i) {
const [x, y, z] = ros(i);
if (Math.abs(x - qx) < 1e-4 && Math.abs(y - qy) < 1e-4) return z;
}
return null;
};
let maxEast = -1e9, maxWest = -1e9;
for (let i = 0; i < p.count; ++i) {
const [x, , z] = ros(i);
if (x > MAP.ox + 1.9) maxEast = Math.max(maxEast, z);
if (x < MAP.ox + 0.1) maxWest = Math.max(maxWest, z);
}
// Ca mat nang L tren san uoc luong (khong chim duoi mesh san that).
check('map: nang L', Math.abs(m.position.y - L) < 1e-9, String(m.position.y));
check('map: co co mapHasFloor', V3D.mapHasFloor === true);
// Chieu x: mep dong (cot 9, san tren) ~1.5; mep tay (san duoi) ~0.
check('map: mep dong o san tren', Math.abs(maxEast - (1.5 + L)) < 0.01, String(maxEast));
check('map: mep tay o san duoi', Math.abs(maxWest - L) < 0.01, String(maxWest));
// Chieu y: ho o goc tay-NAM (y nho), goc tay-BAC phang.
const sw = zAt(MAP.ox, MAP.oy), nw = zAt(MAP.ox, MAP.oy + 1.0);
check('map: ho o goc tay-nam', near(sw, -0.1 + L, 1e-3), String(sw));
check('map: goc tay-bac phang', near(nw, L, 1e-3), String(nw));
// Dinh tai x = ox + 1.0 (ranh cot 4|5) tren hang giua: (0.4 + 0.6) / 2.
const mid = zAt(MAP.ox + 1.0, MAP.oy + 0.4);
check('map: dinh giua doc', near(mid, 0.5 + L, 1e-3), String(mid));
}
// Cung mang o -> khong dung lai; mang moi -> dung lai.
const truoc = V3D.mapMesh;
sb3.__map({ ...g, data: g.cells, floor: f });
check('map: cung du lieu khong dung lai', V3D.mapMesh === truoc);
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null });
check('map: du lieu moi dung lai', V3D.mapMesh !== truoc);
const pf = V3D.mapMesh.geometry.attributes.position;
check('map: khong san -> phang', pf.count === 4 &&
[0, 1, 2, 3].every((i) => pf.array[i * 3 + 2] === 0));
// Ban do phang giu nguyen cao do cu (duoi luoi va vanh cliff).
check('map: khong san -> y cu', V3D.mapMesh.position.y === -0.002 && V3D.mapHasFloor === false,
String(V3D.mapMesh.position.y));
}
// Scan/cloud nang theo cao do san duoi robot; quy dao theo luoi san.
{
const r = { laser_x: 0.24, laser_y: 0, laser_z: 0.1415, wheel_radius: 0.075 };
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 1.5 }, r);
const sy = V3D.scanPts.geometry.attributes.position.array[1];
check('scan: nang theo z', Math.abs(sy - (1.5 + 0.1415 + 0.075)) < 1e-6, String(sy));
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0 }, r);
const sy0 = V3D.scanPts.geometry.attributes.position.array[1];
check('scan: khong z -> nhu cu', Math.abs(sy0 - (0.1415 + 0.075)) < 1e-6, String(sy0));
sb3.__cloud(new Float32Array([1.0, 0.0, 0.3]), { x: 0, y: 0, yaw: 0, z: 1.5 });
const cy = V3D.cloudPts.geometry.attributes.position.array[1];
check('cloud: nang theo z', Math.abs(cy - 1.8) < 1e-6, String(cy));
// Scan THO nghieng theo than: doc 15 do mui NGANG len (pitch ROS am).
// Diem 1 m truoc LiDAR: he footprint (1.24, 0, 0.2165) quay Ry(-15 do).
const P = -15 * Math.PI / 180;
sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 0.5, pitch: P }, r);
const a = V3D.scanPts.geometry.attributes.position.array;
const ex = 1.24 * Math.cos(P) + 0.2165 * Math.sin(P);
const ez = -1.24 * Math.sin(P) + 0.2165 * Math.cos(P);
check('scan: pitch keo diem truoc len', Math.abs(a[0] - ex) < 1e-6 && Math.abs(a[1] - (0.5 + ez)) < 1e-6,
a[0] + ', ' + a[1]);
// Roll +10 do (ROS: ben TRAI len): diem 1 m ben trai cao hon goc LiDAR.
const R = 10 * Math.PI / 180;
sb3.__scan(new Float32Array([0.0, 1.0]), { x: 0, y: 0, yaw: 0, roll: R }, r);
const b = V3D.scanPts.geometry.attributes.position.array;
check('scan: roll keo ben trai len',
Math.abs(b[1] - (Math.sin(R) + 0.2165 * Math.cos(R))) < 1e-6 &&
Math.abs(b[2] + (Math.cos(R) - 0.2165 * Math.sin(R))) < 1e-6, b[1] + ', ' + b[2]);
const cx = (c) => MAP.ox + (c + 0.5) * 0.2, yy = MAP.oy + 0.3;
sb3.__path([cx(0), yy, cx(9), yy], f);
const pts = V3D.pathLine.geometry.points;
// Tren mat ban do uon (nang L) 1 cm.
check('path: diem san duoi', pts && Math.abs(pts[0].y - (L + 0.01)) < 1e-6,
pts && String(pts[0].y));
check('path: diem san tren', pts && Math.abs(pts[1].y - (1.5 + L + 0.01)) < 1e-6,
pts && String(pts[1].y));
sb3.__path([cx(0), yy, cx(9), yy], null);
const pts0 = V3D.pathLine.geometry.points;
check('path: khong luoi -> 0.01 nhu cu', pts0 && pts0.every((q) => Math.abs(q.y - 0.01) < 1e-9));
}
// v3dRender: tam quay bam CAO DO robot khi "bam robot"; nua SLAM an mat san
// the gioi khi ban do co do cao san.
{
const calls = [];
V3D.floorMesh = { visible: true };
V3D.renderer = {
setSize() {}, setScissorTest() {}, setViewport() {}, setScissor() {},
render() { calls.push(V3D.floorMesh.visible); },
};
V3D.camera = { aspect: 1, updateProjectionMatrix() {}, position: new V3(),
lookAt(x, y, z) { this.look = [x, y, z]; } };
V3D.robotGroup = { position: new V3(2, 1.5, -3) };
const cv = { clientWidth: 800, clientHeight: 600, width: 800, height: 600 };
const o = V3D.orbit;
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: f }); // co san
sb3.__render(cv, true, true);
check('render: tam quay o cao do robot', Math.abs(V3D.camera.look[1] - 1.7) < 1e-9,
String(V3D.camera.look));
check('render: camera nang theo robot',
Math.abs(V3D.camera.position.y - (1.5 + o.dist * Math.sin(o.el))) < 1e-9);
check('render: nua the gioi CO san, nua SLAM KHONG', calls.length === 2 && calls[0] === true &&
calls[1] === false, JSON.stringify(calls));
check('render: tra lai san sau khi ve', V3D.floorMesh.visible === true);
calls.length = 0;
sb3.__render(cv, false, true);
check('render: khong bam -> tam quay 0.2 nhu cu', Math.abs(V3D.camera.look[1] - 0.2) < 1e-9,
String(V3D.camera.look));
// Tat "the gioi": ban do co san -> an mat san z = 0; bat lai -> hien.
sb3.__worldVis(false);
check('tat the gioi + co san -> an mat san', V3D.floorMesh.visible === false);
sb3.__worldVis(true);
check('bat the gioi -> hien mat san', V3D.floorMesh.visible === true);
calls.length = 0;
sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); // ban do phang
sb3.__render(cv, false, true);
check('render: ban do phang -> nua SLAM van co san', calls[1] === true, JSON.stringify(calls));
sb3.__worldVis(false);
check('tat the gioi + ban do phang -> giu mat san nhu cu', V3D.floorMesh.visible === true);
}
// v3dSetGround: duoc goi MOI khung khi chay tu `.world`. Cung luoi -> KHONG
// dung lai (ban cu dung lai moi khung va ro GridHelper tren GPU); luoi moi ->
// dung lai va giai phong ca geometry lan material cu.
{
let disposed = 0;
const disp = () => { disposed++; };
THREE.GridHelper = class {
constructor() { Object.assign(this, node()); this.geometry = { dispose: disp };
this.material = { dispose: disp }; }
};
THREE.MeshStandardMaterial = class { constructor(o) { Object.assign(this, o); } dispose() { disp(); } };
V3D.scene = { fog: { near: 0, far: 0 } };
V3D.floorMesh = null;
V3D.gridHelper = null;
const wg = { res: 0.05, w: 400, h: 600, ox: -1, oy: -2 };
sb3.__ground(wg);
const f1 = V3D.floorMesh, g1 = V3D.gridHelper;
const n0 = V3D.root.children.length;
for (let i = 0; i < 100; ++i) sb3.__ground(wg);
check('ground: cung luoi khong dung lai', V3D.floorMesh === f1 && V3D.gridHelper === g1 &&
disposed === 0, String(disposed));
check('ground: root khong phinh', V3D.root.children.length === n0);
check('ground: suong mu theo bao the gioi', Math.abs(V3D.scene.fog.far - 30 * 1.4) < 1e-9,
String(V3D.scene.fog.far));
f1.geometry.dispose = disp;
sb3.__ground({ ...wg, w: 500 });
check('ground: luoi moi dung lai', V3D.floorMesh !== f1 && V3D.gridHelper !== g1);
check('ground: giai phong san + luoi cu (geometry + material)', disposed === 4, String(disposed));
check('ground: root van 1 san 1 luoi', V3D.root.children.length === n0 &&
!V3D.root.children.includes(f1) && !V3D.root.children.includes(g1));
}
console.log(bad ? '\n => HONG' : '\n => DAT');
process.exit(bad ? 1 : 0);