update
This commit is contained in:
@@ -15,6 +15,9 @@
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "vslam/vslam_common.h" // StatusResponse. Khong vong:
|
||||
// vslam_common.h chi keo unix_time.h
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// --- Duong dan mac dinh ----------------------------------------------------
|
||||
@@ -93,6 +96,30 @@ std::string RecordDir();
|
||||
// map_hospital.db ma khong phai copy 3.8 GB.
|
||||
std::string CorpusDir();
|
||||
|
||||
// --- Duong dan ban do: giai tuong doi + no {stamp} -------------------------
|
||||
|
||||
// Giai database_path cua SLAM:
|
||||
// "" -> "" (DB trong RAM -- giu nguyen nghia)
|
||||
// "/abs/x.db" -> "/abs/x.db" (tuyet doi thi khong dung toi)
|
||||
// "x.db" -> MapDir() + "/x.db" (tuong doi = nam trong project)
|
||||
//
|
||||
// `{stamp}` o bat ky dau bi thay bang dau thoi gian DIA PHUONG %Y%m%d_%H%M%S,
|
||||
// tinh MOT lan cho ca chuoi (hai lan xuat hien ra cung mot gia tri).
|
||||
//
|
||||
// ⚠️ Dung dong ho TUONG (std::time), KHONG phai Clock cua he: replay 100x
|
||||
// se duc ra ten trung nhau neu lay dong ho mo phong.
|
||||
//
|
||||
// Khong gian `~`: shell da lam roi, lam lai la lech voi doi so trong nhay.
|
||||
// Idempotent: f(f(x)) == f(x).
|
||||
std::string ResolveMapPath(const std::string& raw);
|
||||
|
||||
// mkdir -p cho thu muc CHA cua `path`. Ok neu da co.
|
||||
//
|
||||
// Dung mkdir() POSIX chu khong phai <filesystem>: tren GCC 9 (xem
|
||||
// CMakeLists.txt:76-88) <filesystem> can link them -lstdc++fs, ma vslam_common
|
||||
// la dep cua MOI target trong cay nay.
|
||||
StatusResponse EnsureParentDir(const std::string& path);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_NODE_CONSTANTS_H
|
||||
|
||||
@@ -151,6 +151,46 @@ struct OccupancyGrid {
|
||||
std::vector<int8_t> data; // size = width * height
|
||||
};
|
||||
|
||||
// Ban do VOXEL: dang thua, chi nhung o BI CHIEM.
|
||||
//
|
||||
// Nam o vslam_common chu khong o vslam_slam vi `vslam_web` phai ma hoa duoc
|
||||
// kieu nay ma no chi phu thuoc vslam_common -- y het ly do OccupancyGrid nam
|
||||
// o day.
|
||||
//
|
||||
// Chi so la SO NGUYEN CO DAU quanh goc (0,0,0) cua frame map:
|
||||
// index = floor(toa_do / resolution)
|
||||
// Goc ghim vinh vien tai goc cua map frame, khong troi theo ban do, nho vay
|
||||
// hai lan xuat khac nhau so sanh truc tiep duoc bang phep tru tap hop.
|
||||
// int16 o 0.10 m = +-3276 m, thua cho moi toa nha trong nha.
|
||||
//
|
||||
// Ten la `VoxelIndex` chu khong phai `VoxelKey`: `vslam::VoxelKey` DA TON TAI
|
||||
// la mot HAM trong depth_filter.h. C++ cho phep ham va lop trung ten trong
|
||||
// cung mot scope, nhung ham CHE ten lop -- `std::vector<VoxelKey>` khi do bat
|
||||
// phai cai ham va bao "expected a type". Da mac dung loi nay mot lan.
|
||||
struct VoxelIndex {
|
||||
int16_t x = 0;
|
||||
int16_t y = 0;
|
||||
int16_t z = 0;
|
||||
};
|
||||
|
||||
struct VoxelGrid {
|
||||
Header header; // frame_id = kMapFrame
|
||||
float resolution = 0.10f; // kich thuoc o PHAT (khac Grid/CellSize cua SLAM)
|
||||
double origin_x = 0.0; // luon 0 hien tai; giu tren day de doi sau nay
|
||||
double origin_y = 0.0;
|
||||
double origin_z = 0.0;
|
||||
|
||||
// Tang khi tap cu KHONG con dung nua (do thi vua duoc toi uu lai sau mot
|
||||
// vong dong, hoac doi resolution). Client thay epoch la se tai lai tu dau
|
||||
// thay vi ap delta.
|
||||
uint32_t epoch = 0;
|
||||
|
||||
bool truncated = false; // cham tran max_cells -> ban do bi cat bot
|
||||
std::vector<VoxelIndex> cells; // DA SAP XEP theo khoa goi, khong trung
|
||||
};
|
||||
|
||||
using VoxelGridPtr = std::shared_ptr<const VoxelGrid>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// sensor_msgs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
@@ -18,6 +23,19 @@ std::string Join(const std::string& dir, const std::string& rel) {
|
||||
return dir + "/" + rel;
|
||||
}
|
||||
|
||||
constexpr char kStampToken[] = "{stamp}";
|
||||
|
||||
// Dau thoi gian DIA PHUONG. Sap xep duoc theo thu tu chu cai, va nguoi van
|
||||
// hanh doc no bang `ls` tren chinh con robot -- do la ly do khong dung UTC.
|
||||
std::string NowStamp() {
|
||||
const std::time_t t = std::time(nullptr);
|
||||
std::tm tm {};
|
||||
localtime_r(&t, &tm);
|
||||
char buf[32];
|
||||
std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
|
||||
@@ -40,4 +58,58 @@ std::string CorpusDir() {
|
||||
return MapDir();
|
||||
}
|
||||
|
||||
std::string ResolveMapPath(const std::string& raw) {
|
||||
if (raw.empty()) return raw; // DB trong RAM -- giu nguyen
|
||||
|
||||
std::string p = raw;
|
||||
if (p.find(kStampToken) != std::string::npos) {
|
||||
// MOT dau thoi gian cho ca chuoi: hai lan xuat hien phai ra cung gia tri,
|
||||
// khong thi ten file va ten thu muc lech nhau mot giay.
|
||||
const std::string stamp = NowStamp();
|
||||
std::string out;
|
||||
out.reserve(p.size() + 16);
|
||||
size_t i = 0;
|
||||
for (;;) {
|
||||
const size_t k = p.find(kStampToken, i);
|
||||
if (k == std::string::npos) {
|
||||
out.append(p, i, std::string::npos);
|
||||
break;
|
||||
}
|
||||
out.append(p, i, k - i);
|
||||
out += stamp;
|
||||
i = k + sizeof(kStampToken) - 1;
|
||||
}
|
||||
p.swap(out);
|
||||
}
|
||||
|
||||
// Cung khuon mau voi dcf_path o app_config.cc: tuyet doi thi dung nguyen,
|
||||
// tuong doi thi giai theo thu muc cua chinh loai file do.
|
||||
if (p.front() == '/') return p;
|
||||
return Join(MapDir(), p);
|
||||
}
|
||||
|
||||
StatusResponse EnsureParentDir(const std::string& path) {
|
||||
const size_t slash = path.find_last_of('/');
|
||||
// Khong co '/' = file o thu muc hien tai; slash == 0 = ngay duoi root.
|
||||
if (slash == std::string::npos || slash == 0) return StatusResponse::Ok();
|
||||
|
||||
const std::string dir = path.substr(0, slash);
|
||||
for (size_t i = 1; i <= dir.size(); ++i) {
|
||||
if (i != dir.size() && dir[i] != '/') continue;
|
||||
const std::string part = dir.substr(0, i);
|
||||
if (::mkdir(part.c_str(), 0775) == 0) continue;
|
||||
if (errno == EEXIST) {
|
||||
// EEXIST chua phai tin tot: co the la mot FILE thuong trung ten.
|
||||
struct stat st {};
|
||||
if (::stat(part.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) continue;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"khong phai thu muc: " + part);
|
||||
}
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"khong tao duoc thu muc " + part + ": " + std::strerror(errno));
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
@@ -15,6 +15,7 @@ vslam_add_library(vslam_slam
|
||||
rtabmap_slam.h
|
||||
sensor_data_builder.h
|
||||
occupancy_export.h
|
||||
voxel_export.h
|
||||
FIND_DEPS
|
||||
vslam_common
|
||||
RTABMap
|
||||
|
||||
@@ -26,6 +26,11 @@ struct DbFacts {
|
||||
int nodes = 0;
|
||||
int words = 0; // 0 = ban do quet KHONG co tu vung
|
||||
std::string optimizer_strategy; // tham so DB nho, co the khac cai ta ep
|
||||
|
||||
// DB nay duoc quet voi luoi cuc bo 3D hay khong. Quet phang roi mo ban do
|
||||
// voxel len thi chi thay MOT lop ngang o cao do LiDAR -- canh bao duoc, chu
|
||||
// khong phai loi.
|
||||
bool grid_3d = false;
|
||||
};
|
||||
|
||||
DbFacts InspectDatabase(const std::string& path);
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
#include "vslam/rtabmap_params.h"
|
||||
#include "vslam/slam_types.h"
|
||||
#include "vslam/voxel_export.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
@@ -75,11 +76,22 @@ class RtabmapSlam {
|
||||
// Xuat occupancy grid hien tai. Dat, goi khi map_version doi.
|
||||
StatusResponse ExportMap(OccupancyGrid* out);
|
||||
|
||||
// Xuat ban do VOXEL 3D. Dat hon ExportMap: no quet lai o bi chiem cua moi
|
||||
// node. Goi cung nhip va cung ngan sach voi ExportMap -- xem Runtime::SlamLoop.
|
||||
//
|
||||
// `out->epoch` khong duoc dat o day: vong doi epoch la viec cua nguoi goi,
|
||||
// chi ho moi biet tap truoc do la gi.
|
||||
StatusResponse ExportVoxels(const VoxelExportOptions& opt, VoxelGrid* out);
|
||||
|
||||
StatusResponse Close(bool save_database);
|
||||
|
||||
const SlamStats& stats() const;
|
||||
SlamMode mode() const;
|
||||
|
||||
// Duong dan DB DA GIAI (tuong doi -> MapDir(), {stamp} da no).
|
||||
// Rong = DB trong RAM. Chi co nghia sau Init().
|
||||
const std::string& database_path() const;
|
||||
|
||||
private:
|
||||
std::unique_ptr<RtabmapSlamImpl> impl_;
|
||||
};
|
||||
|
||||
100
libs/vslam_slam/include/vslam/voxel_export.h
Normal file
100
libs/vslam_slam/include/vslam/voxel_export.h
Normal file
@@ -0,0 +1,100 @@
|
||||
#ifndef VSLAM_VOXEL_EXPORT_H
|
||||
#define VSLAM_VOXEL_EXPORT_H
|
||||
|
||||
// Xuat BAN DO VOXEL 3D tu do thi RTAB-Map, cho khung 3D cua web UI.
|
||||
//
|
||||
// Khac occupancy_export.cc o mot cho ban le: o day KHONG dung
|
||||
// rtabmap::OccupancyGrid. `BuildFromCache` ep Grid/3D="false" ngay trong ham
|
||||
// (occupancy_export.cc) va do la dung cho duong 2D -- no chieu moi thu xuong
|
||||
// mot mat phang. Ban do 3D phai lay o BI CHIEM o he cuc bo cua tung node roi
|
||||
// tu bien doi bang pose DA TOI UU.
|
||||
//
|
||||
// ⚠️ Chinh vi dung pose da toi uu ma ban do 3D tu NAN lai sau moi vong dong:
|
||||
// khong co buoc "sua ban do" nao ca, ta dung lai tu dau tu do thi moi. Doi
|
||||
// lai, sau mot lan toi uu thi gan nhu MOI voxel doi chi so -- xem `epoch`
|
||||
// trong VoxelGrid va luat 35% o phia web.
|
||||
//
|
||||
// ⚠️ `data.uncompressData()` la BAT BUOC truoc khi doc gridObstacleCellsRaw().
|
||||
// Quen no thi moi node tra ve ma tran RONG, va trieu chung la "1990 node, 0 o"
|
||||
// -- y het cai bay da co trong occupancy_export.h.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace rtabmap {
|
||||
class Rtabmap;
|
||||
}
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct VoxelExportOptions {
|
||||
// Kich thuoc o PHAT. Doc lap voi Grid/CellSize (0.05) cua SLAM: lam tho
|
||||
// them mot bac cat bon lan so voxel ma mat rat it hinh dang.
|
||||
double emit_size_m = 0.10;
|
||||
|
||||
// Cat san va tran. z do tu base_footprint = mat san.
|
||||
double z_min = 0.05;
|
||||
double z_max = 2.00;
|
||||
|
||||
// Tran cung. Cham tran thi cat bot va bat `truncated` chu khong am tham
|
||||
// nuot: mot ban do 3D thieu mot nua trong im lang la kieu hong te nhat.
|
||||
size_t max_cells = 150000;
|
||||
|
||||
// Gom bao nhieu khoa thi sort+unique mot lan. Doi bo nho dinh lay so lan
|
||||
// tron: 2M khoa = 16 MB tam thoi.
|
||||
size_t flush_every = 2000000;
|
||||
};
|
||||
|
||||
// Gom diem -> tap voxel. KHONG chua kieu nao cua RTAB-Map, nen test duoc ma
|
||||
// khong can mot Rtabmap dang chay -- do la ly do no tach rieng khoi
|
||||
// ExportVoxelGrid.
|
||||
class VoxelAccumulator {
|
||||
public:
|
||||
explicit VoxelAccumulator(const VoxelExportOptions& opt);
|
||||
|
||||
// Toa do trong frame MAP, met.
|
||||
void AddPoint(double x, double y, double z);
|
||||
|
||||
// Sort + unique lan cuoi roi do ra `out`. `out->cells` da sap xep.
|
||||
void Finish(VoxelGrid* out);
|
||||
|
||||
// So diem bi bo vi ra ngoai dai int16. Khac 0 nghia la ban do vuot +-3 km
|
||||
// hoac resolution bi dat sai.
|
||||
size_t clamped() const { return clamped_; }
|
||||
// So diem bi cat vi nam ngoai [z_min, z_max].
|
||||
size_t z_rejected() const { return z_rejected_; }
|
||||
|
||||
private:
|
||||
void Flush();
|
||||
|
||||
VoxelExportOptions opt_;
|
||||
double inv_size_ = 10.0;
|
||||
std::vector<uint64_t> scratch_;
|
||||
std::vector<uint64_t> acc_; // luon o trang thai da sort+unique
|
||||
size_t clamped_ = 0;
|
||||
size_t z_rejected_ = 0;
|
||||
};
|
||||
|
||||
// Quet toan bo pose da toi uu va dung lai tap voxel tu dau.
|
||||
//
|
||||
// `out->epoch` KHONG duoc dat o day -- nguoi goi quan ly vong doi epoch, vi
|
||||
// chi ho moi biet tap truoc do la gi.
|
||||
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
|
||||
const VoxelExportOptions& opt, VoxelGrid* out);
|
||||
|
||||
// Hieu hai tap DA SAP XEP: `added` co trong `now` ma khong co trong `prev`,
|
||||
// `removed` thi nguoc lai. O(n + m), mot luot.
|
||||
//
|
||||
// Tach ra de test duoc va de nguoi goi quyet dinh gui delta hay gui lai ca
|
||||
// tap dua tren ti le thay doi.
|
||||
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
|
||||
const std::vector<VoxelIndex>& now,
|
||||
std::vector<VoxelIndex>* added,
|
||||
std::vector<VoxelIndex>* removed);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_VOXEL_EXPORT_H
|
||||
@@ -106,6 +106,12 @@ DbFacts InspectDatabase(const std::string& path) {
|
||||
auto it = db_params.find(rtabmap::Parameters::kOptimizerStrategy());
|
||||
if (it != db_params.end()) f.optimizer_strategy = it->second;
|
||||
|
||||
// Cung co che: doc lai tham so DB da luu. "true"/"1" deu tinh la bat.
|
||||
auto it3d = db_params.find(rtabmap::Parameters::kGrid3D());
|
||||
if (it3d != db_params.end()) {
|
||||
f.grid_3d = (it3d->second == "true" || it3d->second == "1");
|
||||
}
|
||||
|
||||
driver->closeConnection(false);
|
||||
return f;
|
||||
}
|
||||
|
||||
@@ -116,6 +116,42 @@ std::map<std::string, std::string> BuildRtabmapParams(
|
||||
// Kp/MaxFeatures: -1 = tat han tui tu. >0 = so dac trung moi anh.
|
||||
out["Kp/MaxFeatures"] = cfg.visual_loop ? "400" : "-1";
|
||||
|
||||
// --- camera_3d: luoi cuc bo 3D de dung ban do voxel cho web ---
|
||||
//
|
||||
// Nam o muc 3 chu khong o `project_defaults`: slam.yaml dat THANG
|
||||
// `Grid/Sensor: "0"` va `Grid/3D: "false"`, ma muc 2 (YAML) ghi de len muc
|
||||
// 1. De o day thi ba key nay la HE QUA cua co, dung nhu Mem/IncrementalMemory
|
||||
// la he qua cua mode.
|
||||
if (cfg.camera_3d) {
|
||||
// 0=scan 1=depth 2=ca hai. Can "2": LiDAR van la trong tai cho ICP, con
|
||||
// depth la thu duy nhat co chieu cao.
|
||||
out["Grid/Sensor"] = "2";
|
||||
out["Grid/3D"] = "true";
|
||||
|
||||
// Tach san/vat can bang NGUONG CHIEU CAO, khong bang phap tuyen.
|
||||
// NormalsSegmentation mac dinh true va la duong DAT: no uoc luong phap
|
||||
// tuyen (Grid/NormalK = 20 lang gieng) cho moi diem, moi khung. Robot nay
|
||||
// la 2.5D (Reg/Force3DoF), san phang, nen mot nguong chieu cao la du.
|
||||
// RTAB-Map cung noi thang: MaxGroundHeight "should be set if
|
||||
// NormalsSegmentation is false".
|
||||
out["Grid/NormalsSegmentation"] = "false";
|
||||
out["Grid/MaxGroundHeight"] = "0.10"; // duoi nguong = san
|
||||
out["Grid/MaxObstacleHeight"] = "2.0"; // tren nguong = tran, vut di
|
||||
|
||||
// ⚠️ Grid/RayTracing GIU NGUYEN "true" (mac dinh cua du an), khong tat.
|
||||
//
|
||||
// Tat no re hon that -- voi Grid/3D=true, ray tracing dien o KHONG GIAN
|
||||
// chu khong phai mat phang, va ban do voxel chi doc o BI CHIEM nen o
|
||||
// trong la chi phi thuan. Nhung no cung chinh la thu sinh ra o "trong"
|
||||
// cua luoi 2D: do tren robot that 2026-09-23, mot phien 3.5 phut cho
|
||||
// 84961 o trong / 5049 o bi chiem. Tat di thi khung ban do tren web gan
|
||||
// nhu chi con mau "chua biet".
|
||||
//
|
||||
// Muon danh doi nguoc lai thi dat `Grid/RayTracing: "false"` trong khoi
|
||||
// `rtabmap:` cua slam.yaml -- do la viec cua nguoi van hanh, khong phai
|
||||
// mot he qua am tham cua camera_3d.
|
||||
}
|
||||
|
||||
// Optimizer: dat TUONG MINH, luon luon.
|
||||
//
|
||||
// DB hien co (`map_house.db`) luu Optimizer/Strategy=2 (GTSAM). Tren Jetson
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
#include "vslam/occupancy_export.h"
|
||||
#include "vslam/sensor_data_builder.h"
|
||||
|
||||
@@ -69,6 +70,10 @@ void RtabmapSlam::SetExtrinsics(const Transform& laser_to_base,
|
||||
SlamMode RtabmapSlam::mode() const { return impl_->cfg.mode; }
|
||||
const SlamStats& RtabmapSlam::stats() const { return impl_->stats; }
|
||||
|
||||
const std::string& RtabmapSlam::database_path() const {
|
||||
return impl_->cfg.database_path;
|
||||
}
|
||||
|
||||
Pose2D RtabmapSlam::map_correction() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->out_mu);
|
||||
return impl_->map_correction;
|
||||
@@ -88,6 +93,27 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
}
|
||||
impl_->cfg = cfg;
|
||||
|
||||
// --- Giai duong dan DB: tuong doi -> MapDir(), no {stamp} ---
|
||||
//
|
||||
// Lam o DAY chu khong o app_config: duong `--check` khong dung toi
|
||||
// RtabmapSlam, nen cau hinh van kiem duoc tren may khong co quyen ghi vao
|
||||
// /var/lib -- bon test badconfig chay dung kieu do.
|
||||
impl_->cfg.database_path = ResolveMapPath(cfg.database_path);
|
||||
const std::string& db_path = impl_->cfg.database_path;
|
||||
if (db_path != cfg.database_path) {
|
||||
VSLAM_INFO("slam: database_path \"" << cfg.database_path << "\" -> " << db_path);
|
||||
}
|
||||
|
||||
// {stamp} o che do localization la mot loi logic, khong phai tuy chon: ten
|
||||
// sinh moi lan chay thi khong bao gio khop ban do da quet.
|
||||
if (cfg.mode == SlamMode::kLocalization &&
|
||||
cfg.database_path.find("{stamp}") != std::string::npos) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"localization voi {stamp} trong database_path: ten sinh moi lan chay "
|
||||
"thi khong bao gio tim thay ban do da quet.");
|
||||
}
|
||||
|
||||
// ULogger cua RTAB-Map mac dinh in thang ra stdout va rat on. Day ve ERROR;
|
||||
// thong tin can thiet da co trong SlamOutput va stats.
|
||||
ULogger::setType(ULogger::kTypeNoLog);
|
||||
@@ -113,14 +139,14 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, msg);
|
||||
}
|
||||
|
||||
const DbFacts facts = InspectDatabase(cfg.database_path);
|
||||
const DbFacts facts = InspectDatabase(db_path);
|
||||
if (cfg.mode == SlamMode::kLocalization) {
|
||||
// Localization can mot ban do DA CO. Khong co thi no chay im lang ma
|
||||
// khong bao gio dinh vi duoc vao dau -- da do: process_ms 0.3-2.4 ms va
|
||||
// map->odom luon bang 0, trong nhu "SLAM dang chay tot".
|
||||
//
|
||||
// Duong dan rong = DB trong RAM = chac chan khong co ban do.
|
||||
if (cfg.database_path.empty()) {
|
||||
if (db_path.empty()) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"che do localization nhung database_path de rong (DB trong RAM). "
|
||||
@@ -129,7 +155,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
if (!facts.exists || facts.nodes == 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"che do localization nhung DB khong co node nao: " + cfg.database_path);
|
||||
"che do localization nhung DB khong co node nao: " + db_path);
|
||||
}
|
||||
}
|
||||
if (cfg.visual_loop && facts.exists && facts.words == 0) {
|
||||
@@ -141,6 +167,11 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
"visual_loop=true nhung DB khong co tu vung (Word = 0). Ban do nay "
|
||||
"duoc quet voi visual_loop=false; hai co phai khop nhau.");
|
||||
}
|
||||
if (cfg.camera_3d && facts.exists && !facts.grid_3d) {
|
||||
VSLAM_WARN("slam: camera_3d=true nhung DB nay duoc quet voi Grid/3D=false "
|
||||
"-- ban do voxel se chi co MOT lop ngang o cao do LiDAR. Quet "
|
||||
"lai vao DB moi neu can ban do 3D that.");
|
||||
}
|
||||
if (facts.exists && facts.optimizer_strategy != cfg.optimizer_strategy) {
|
||||
VSLAM_WARN("slam: DB luu Optimizer/Strategy=" << facts.optimizer_strategy
|
||||
<< ", dang ep ve " << cfg.optimizer_strategy
|
||||
@@ -169,10 +200,19 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
" node: RTAB-Map 0.21.13 nem 'UNIQUE constraint failed: "
|
||||
"Statistics.id' o MOI khung va khong dung duoc ban do nao.\n"
|
||||
" - Quet lai tu dau : --slam-db <duong dan MOI>\n"
|
||||
" - Dat ten tu dong : --slam-db \"map_{stamp}.db\"\n"
|
||||
" - Dung ban do nay : --slam-mode localization "
|
||||
"--slam-init-pose x,y,yaw");
|
||||
}
|
||||
|
||||
// rtabmap.init() tao FILE, khong tao THU MUC -- thieu thu muc cha thi no
|
||||
// nem tu trong ruot sqlite. Chi can o mapping; localization thi DB bat buoc
|
||||
// da ton tai va da qua phep kiem ben tren.
|
||||
if (cfg.mode == SlamMode::kMapping && !db_path.empty()) {
|
||||
const StatusResponse mk = EnsureParentDir(db_path);
|
||||
if (!mk.ok()) return mk;
|
||||
}
|
||||
|
||||
rtabmap::ParametersMap pm(params.begin(), params.end());
|
||||
try {
|
||||
// loadDatabaseParameters = FALSE, luon luon.
|
||||
@@ -180,7 +220,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
// map_house.db luu Optimizer/Strategy=2 (GTSAM). Neu de RTAB-Map doc lai
|
||||
// tham so tu DB thi tren Jetson build -DWITH_GTSAM=OFF no se chon GTSAM
|
||||
// va crash thieu symbol.
|
||||
impl_->rtabmap.init(pm, cfg.database_path, /*loadDatabaseParameters=*/false);
|
||||
impl_->rtabmap.init(pm, db_path, /*loadDatabaseParameters=*/false);
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInternal,
|
||||
std::string("rtabmap init: ") + e.what());
|
||||
@@ -205,7 +245,7 @@ StatusResponse RtabmapSlam::Init(const RtabmapConfig& cfg) {
|
||||
impl_->map_version = 1;
|
||||
}
|
||||
VSLAM_INFO("slam: " << SlamModeName(cfg.mode) << ", DB "
|
||||
<< (cfg.database_path.empty() ? "(RAM)" : cfg.database_path)
|
||||
<< (db_path.empty() ? "(RAM)" : db_path)
|
||||
<< " (" << facts.nodes << " node, " << facts.words
|
||||
<< " tu vung), optimizer " << cfg.optimizer_strategy);
|
||||
return StatusResponse::Ok();
|
||||
@@ -307,6 +347,14 @@ StatusResponse RtabmapSlam::ExportMap(OccupancyGrid* out) {
|
||||
return ExportOccupancyGrid(impl_->rtabmap, out);
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::ExportVoxels(const VoxelExportOptions& opt,
|
||||
VoxelGrid* out) {
|
||||
if (!impl_->inited) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "chua init");
|
||||
}
|
||||
return ExportVoxelGrid(impl_->rtabmap, opt, out);
|
||||
}
|
||||
|
||||
StatusResponse RtabmapSlam::Close(bool save_database) {
|
||||
if (!impl_->inited) return StatusResponse::Ok();
|
||||
impl_->inited = false;
|
||||
|
||||
246
libs/vslam_slam/src/voxel_export.cc
Normal file
246
libs/vslam_slam/src/voxel_export.cc
Normal file
@@ -0,0 +1,246 @@
|
||||
#include "vslam/voxel_export.h"
|
||||
|
||||
#include <rtabmap/core/Memory.h>
|
||||
#include <rtabmap/core/Rtabmap.h>
|
||||
#include <rtabmap/core/SensorData.h>
|
||||
#include <rtabmap/core/Transform.h>
|
||||
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Goi chi so co dau vao 63 bit: 21 bit moi truc, lech +2^20 de so am van sap
|
||||
// xep dung thu tu khi so sanh uint64.
|
||||
//
|
||||
// Vi sao vector<uint64> da sort chu khong phai hash set hay octree: tap nay
|
||||
// duoc dung LAI TU DAU moi lan xuat (pose toi uu dich cho, cau truc tang dan
|
||||
// vo nghia), va nguoi tieu thu can dau ra DA SAP XEP de lam phep tru tap hop
|
||||
// O(n). Mot vector phang sort cache tot hon han hash 2 trieu phan tu.
|
||||
constexpr int32_t kIdxBias = 1 << 20;
|
||||
constexpr int32_t kIdxMin = -kIdxBias;
|
||||
constexpr int32_t kIdxMax = kIdxBias - 1;
|
||||
|
||||
inline uint64_t PackKey(int32_t x, int32_t y, int32_t z) {
|
||||
const uint64_t ux = static_cast<uint64_t>(static_cast<uint32_t>(x + kIdxBias)) & 0x1FFFFFULL;
|
||||
const uint64_t uy = static_cast<uint64_t>(static_cast<uint32_t>(y + kIdxBias)) & 0x1FFFFFULL;
|
||||
const uint64_t uz = static_cast<uint64_t>(static_cast<uint32_t>(z + kIdxBias)) & 0x1FFFFFULL;
|
||||
return (ux << 42) | (uy << 21) | uz;
|
||||
}
|
||||
|
||||
inline void UnpackKey(uint64_t k, int32_t* x, int32_t* y, int32_t* z) {
|
||||
*x = static_cast<int32_t>((k >> 42) & 0x1FFFFFULL) - kIdxBias;
|
||||
*y = static_cast<int32_t>((k >> 21) & 0x1FFFFFULL) - kIdxBias;
|
||||
*z = static_cast<int32_t>(k & 0x1FFFFFULL) - kIdxBias;
|
||||
}
|
||||
|
||||
inline bool FitsInt16(int32_t v) {
|
||||
return v >= -32768 && v <= 32767;
|
||||
}
|
||||
|
||||
inline uint64_t KeyOf(const VoxelIndex& k) {
|
||||
return PackKey(k.x, k.y, k.z);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VoxelAccumulator::VoxelAccumulator(const VoxelExportOptions& opt) : opt_(opt) {
|
||||
if (opt_.emit_size_m <= 0.0) opt_.emit_size_m = 0.10;
|
||||
inv_size_ = 1.0 / opt_.emit_size_m;
|
||||
scratch_.reserve(1 << 16);
|
||||
}
|
||||
|
||||
void VoxelAccumulator::AddPoint(double x, double y, double z) {
|
||||
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) return;
|
||||
if (z < opt_.z_min || z > opt_.z_max) {
|
||||
++z_rejected_;
|
||||
return;
|
||||
}
|
||||
|
||||
const double fx = std::floor(x * inv_size_);
|
||||
const double fy = std::floor(y * inv_size_);
|
||||
const double fz = std::floor(z * inv_size_);
|
||||
// Kiem TRUOC khi ep kieu: ep mot double khong lot int32 la hanh vi khong
|
||||
// xac dinh, va o day no den tu du lieu cam bien chu khong tu hang so.
|
||||
if (fx < kIdxMin || fx > kIdxMax || fy < kIdxMin || fy > kIdxMax ||
|
||||
fz < kIdxMin || fz > kIdxMax) {
|
||||
++clamped_;
|
||||
return;
|
||||
}
|
||||
const int32_t ix = static_cast<int32_t>(fx);
|
||||
const int32_t iy = static_cast<int32_t>(fy);
|
||||
const int32_t iz = static_cast<int32_t>(fz);
|
||||
// Dang truyen la int16 -> chi so ngoai dai do la bo, khong phai kep: kep se
|
||||
// dan mot buc tuong gia o ria ban do.
|
||||
if (!FitsInt16(ix) || !FitsInt16(iy) || !FitsInt16(iz)) {
|
||||
++clamped_;
|
||||
return;
|
||||
}
|
||||
|
||||
scratch_.push_back(PackKey(ix, iy, iz));
|
||||
if (scratch_.size() >= opt_.flush_every) Flush();
|
||||
}
|
||||
|
||||
void VoxelAccumulator::Flush() {
|
||||
if (scratch_.empty()) return;
|
||||
std::sort(scratch_.begin(), scratch_.end());
|
||||
scratch_.erase(std::unique(scratch_.begin(), scratch_.end()), scratch_.end());
|
||||
|
||||
if (acc_.empty()) {
|
||||
acc_.swap(scratch_);
|
||||
} else {
|
||||
std::vector<uint64_t> merged;
|
||||
merged.reserve(acc_.size() + scratch_.size());
|
||||
std::set_union(acc_.begin(), acc_.end(), scratch_.begin(), scratch_.end(),
|
||||
std::back_inserter(merged));
|
||||
acc_.swap(merged);
|
||||
}
|
||||
scratch_.clear();
|
||||
}
|
||||
|
||||
void VoxelAccumulator::Finish(VoxelGrid* out) {
|
||||
Flush();
|
||||
|
||||
out->resolution = static_cast<float>(opt_.emit_size_m);
|
||||
out->origin_x = 0.0;
|
||||
out->origin_y = 0.0;
|
||||
out->origin_z = 0.0;
|
||||
out->header.frame_id = kMapFrame;
|
||||
out->truncated = acc_.size() > opt_.max_cells;
|
||||
|
||||
const size_t n = std::min(acc_.size(), opt_.max_cells);
|
||||
out->cells.clear();
|
||||
out->cells.reserve(n);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
int32_t x = 0, y = 0, z = 0;
|
||||
UnpackKey(acc_[i], &x, &y, &z);
|
||||
VoxelIndex k;
|
||||
k.x = static_cast<int16_t>(x);
|
||||
k.y = static_cast<int16_t>(y);
|
||||
k.z = static_cast<int16_t>(z);
|
||||
out->cells.push_back(k);
|
||||
}
|
||||
// `acc_` da sort theo khoa goi, va khoa goi giu dung thu tu tu nhien cua
|
||||
// (x, y, z) nho phep lech +2^20 -- nen out->cells cung da sap xep.
|
||||
}
|
||||
|
||||
void DiffVoxelGrids(const std::vector<VoxelIndex>& prev,
|
||||
const std::vector<VoxelIndex>& now,
|
||||
std::vector<VoxelIndex>* added,
|
||||
std::vector<VoxelIndex>* removed) {
|
||||
added->clear();
|
||||
removed->clear();
|
||||
size_t i = 0, j = 0;
|
||||
while (i < prev.size() && j < now.size()) {
|
||||
const uint64_t a = KeyOf(prev[i]);
|
||||
const uint64_t b = KeyOf(now[j]);
|
||||
if (a == b) {
|
||||
++i;
|
||||
++j;
|
||||
} else if (a < b) {
|
||||
removed->push_back(prev[i++]);
|
||||
} else {
|
||||
added->push_back(now[j++]);
|
||||
}
|
||||
}
|
||||
for (; i < prev.size(); ++i) removed->push_back(prev[i]);
|
||||
for (; j < now.size(); ++j) added->push_back(now[j]);
|
||||
}
|
||||
|
||||
StatusResponse ExportVoxelGrid(rtabmap::Rtabmap& slam,
|
||||
const VoxelExportOptions& opt, VoxelGrid* out) {
|
||||
const std::map<int, rtabmap::Transform>& poses = slam.getLocalOptimizedPoses();
|
||||
if (poses.empty()) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
||||
"khong co pose nao de dung ban do voxel");
|
||||
}
|
||||
const rtabmap::Memory* mem = slam.getMemory();
|
||||
if (mem == nullptr) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
||||
"rtabmap chua co Memory");
|
||||
}
|
||||
|
||||
VoxelAccumulator acc(opt);
|
||||
size_t nodes_with_grid = 0;
|
||||
int channels_seen = 0;
|
||||
|
||||
for (const auto& kv : poses) {
|
||||
if (kv.second.isNull()) continue;
|
||||
rtabmap::SensorData data = mem->getNodeData(kv.first, false, false, false, true);
|
||||
// ⚠️ BAT BUOC. Thieu dong nay thi gridObstacleCellsRaw() tra ma tran RONG
|
||||
// o moi node va ban do 3D im lang rong khong.
|
||||
data.uncompressData();
|
||||
if (data.gridCellSize() <= 0.0f) continue;
|
||||
|
||||
const cv::Mat& obs = data.gridObstacleCellsRaw();
|
||||
if (obs.empty()) continue;
|
||||
if (obs.depth() != CV_32F) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInternal,
|
||||
"o luoi cuc bo khong phai float32 (depth=" +
|
||||
std::to_string(obs.depth()) + ") -- phien ban RTAB-Map la");
|
||||
}
|
||||
|
||||
const int ch = obs.channels();
|
||||
if (ch < 2) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInternal,
|
||||
"o luoi cuc bo co " + std::to_string(ch) +
|
||||
" kenh, cho doi 2 (XY) hoac 3/4 (XYZ[+RGB])");
|
||||
}
|
||||
if (channels_seen == 0) channels_seen = ch;
|
||||
|
||||
// Pose da toi uu: node -> map. Dung ma tran 3x4 dung san, 12 phep nhan
|
||||
// cho moi diem, thay vi dung mot rtabmap::Transform cho tung diem.
|
||||
const rtabmap::Transform& T = kv.second;
|
||||
const float r00 = T.r11(), r01 = T.r12(), r02 = T.r13(), tx = T.x();
|
||||
const float r10 = T.r21(), r11 = T.r22(), r12 = T.r23(), ty = T.y();
|
||||
const float r20 = T.r31(), r21 = T.r32(), r22 = T.r33(), tz = T.z();
|
||||
|
||||
const int n = obs.cols * obs.rows;
|
||||
const float* p = obs.ptr<float>();
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const float px = p[0];
|
||||
const float py = p[1];
|
||||
// 2 kenh = luoi PHANG (DB quet voi Grid/3D=false). Van ve duoc, chi la
|
||||
// ra mot lop ngang -- Init() da canh bao truong hop nay.
|
||||
const float pz = (ch >= 3) ? p[2] : 0.0f;
|
||||
p += ch;
|
||||
|
||||
acc.AddPoint(r00 * px + r01 * py + r02 * pz + tx,
|
||||
r10 * px + r11 * py + r12 * pz + ty,
|
||||
r20 * px + r21 * py + r22 * pz + tz);
|
||||
}
|
||||
++nodes_with_grid;
|
||||
}
|
||||
|
||||
if (nodes_with_grid == 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"khong node nao co luoi cuc bo -- RGBD/CreateOccupancyGrid tat, hoac "
|
||||
"DB quet truoc khi bat camera_3d");
|
||||
}
|
||||
|
||||
acc.Finish(out);
|
||||
|
||||
// Mot dong, mot lan moi 30 giay: so kenh la thu duy nhat trong ca duong nay
|
||||
// khong doc duoc tu header RTAB-Map, nen no phai hien ra o log that.
|
||||
VSLAM_INFO_THROTTLE(30.0, "slam: voxel " << out->cells.size() << " o tu "
|
||||
<< nodes_with_grid << " node (" << channels_seen
|
||||
<< " kenh/o" << (out->truncated ? ", DA CAT BOT" : "")
|
||||
<< ")");
|
||||
if (acc.clamped() > 0) {
|
||||
VSLAM_WARN_THROTTLE(30.0, "slam: " << acc.clamped()
|
||||
<< " diem ngoai dai chi so voxel -- bo qua");
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
@@ -40,6 +40,21 @@ enum class BinaryType : uint8_t {
|
||||
// TINH: trong mo phong no khong bao gio doi, nen chi gui MOT lan cho moi
|
||||
// client.
|
||||
kWorldMap = 6,
|
||||
|
||||
// --- Ban do voxel 3D ---
|
||||
//
|
||||
// kVoxelFull di theo TUNG MANH: mot ban do 60k o la ~360 kB, gui mot cuc se
|
||||
// nghen ca hang doi 4 khung cua session. Moi manh tu mo ta (epoch,
|
||||
// chunk_index, chunk_count) nen client rap lai duoc ma khong can trang thai
|
||||
// ngoai.
|
||||
//
|
||||
// kVoxelDelta chi mang phan THEM/BOT so voi epoch client dang giu. Quet
|
||||
// tien binh thuong thi n_del = 0 va khung chi vai tram byte.
|
||||
//
|
||||
// ⚠️ KHONG tai dung so 4 (kMapPatch, da bo): mot trinh duyet con cache
|
||||
// app.js cu se giai khung voxel thanh map patch va ve rac len ban do.
|
||||
kVoxelFull = 7,
|
||||
kVoxelDelta = 8,
|
||||
};
|
||||
|
||||
constexpr size_t kBinaryHeaderSize = 16;
|
||||
@@ -72,10 +87,52 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points
|
||||
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
|
||||
BinaryType type = BinaryType::kMapFull);
|
||||
|
||||
// Chi vung bao (bbox) cac o doi so voi `prev`. Tra false neu kich thuoc hai
|
||||
// map khac nhau (khi do phai gui MAP_FULL) hoac khong co o nao doi.
|
||||
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
|
||||
UnixTime stamp, std::string* out);
|
||||
// (kMapPatch = 4 da bi BO. No noi duoc vao dau: cong per-session chi la mot
|
||||
// atomic `acked_map_version_`, khong dien ta noi "session nay dang giu luoi
|
||||
// NAO", va ban than no bail moi khi origin hay kich thuoc doi -- tuc gan nhu
|
||||
// luon bail dung luc mapping. Viec nen delta thuc su co lai nam o ban do
|
||||
// voxel, xem EncodeVoxelDelta.)
|
||||
|
||||
// --- Ban do voxel 3D -------------------------------------------------------
|
||||
|
||||
// Mot manh cua ban do day du. `cells` phai DA SAP XEP; ham nay khong sap lai.
|
||||
//
|
||||
// Bo cuc payload (sau header 16 byte):
|
||||
// 0 f32 resolution kich thuoc o, m
|
||||
// 4 f32 origin_x
|
||||
// 8 f32 origin_y
|
||||
// 12 f32 origin_z
|
||||
// 16 u32 epoch
|
||||
// 20 u32 total tong so o cua CA epoch (khong phai cua manh nay)
|
||||
// 24 u16 chunk_index 0-based
|
||||
// 26 u16 chunk_count
|
||||
// 28 u32 n so o trong manh nay
|
||||
// 32 n * (i16 x, i16 y, i16 z)
|
||||
//
|
||||
// Khong luong tu hoa them: chi so voxel CHINH LA du lieu, khac kCloud von
|
||||
// phai chia cho quant_m.
|
||||
void EncodeVoxelFull(const VoxelGrid& grid, UnixTime stamp, size_t first,
|
||||
size_t count, uint16_t chunk_index, uint16_t chunk_count,
|
||||
std::string* out);
|
||||
|
||||
// So manh can de gui het `grid` voi tran `chunk_bytes` moi manh. Luon >= 1,
|
||||
// ke ca khi ban do rong -- client can mot khung de biet "ban do gio rong".
|
||||
uint16_t VoxelChunkCount(const VoxelGrid& grid, uint32_t chunk_bytes);
|
||||
size_t VoxelCellsPerChunk(uint32_t chunk_bytes);
|
||||
|
||||
// Phan THEM/BOT so voi epoch client dang giu.
|
||||
//
|
||||
// Bo cuc payload:
|
||||
// 0 u32 epoch phai khop epoch client dang giu, khong thi client xin sync lai
|
||||
// 4 u32 seq tang dan moi delta; hut so = mat khung -> xin sync lai
|
||||
// 8 u32 n_add
|
||||
// 12 u32 n_del
|
||||
// 16 n_add * (i16 x, i16 y, i16 z)
|
||||
// .. n_del * (i16 x, i16 y, i16 z)
|
||||
void EncodeVoxelDelta(uint32_t epoch, uint32_t seq,
|
||||
const std::vector<VoxelIndex>& added,
|
||||
const std::vector<VoxelIndex>& removed, UnixTime stamp,
|
||||
std::string* out);
|
||||
|
||||
// Thua hoa: chi giu diem cach diem truoc > min_step_m.
|
||||
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
|
||||
@@ -94,6 +151,21 @@ bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
|
||||
bool DecodeScan(const std::string& buf, LaserScan* out);
|
||||
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out);
|
||||
|
||||
// Giai mot manh. `out` duoc NOI THEM, khong xoa -- rap nhieu manh bang cach
|
||||
// goi lien tiep. `total`/`chunk_index`/`chunk_count`/`epoch` tra qua con tro
|
||||
// de test kiem duoc phan dieu phoi.
|
||||
struct VoxelChunkInfo {
|
||||
uint32_t epoch = 0;
|
||||
uint32_t total = 0;
|
||||
uint16_t chunk_index = 0;
|
||||
uint16_t chunk_count = 0;
|
||||
};
|
||||
bool DecodeVoxelFull(const std::string& buf, VoxelChunkInfo* info,
|
||||
std::vector<VoxelIndex>* out);
|
||||
bool DecodeVoxelDelta(const std::string& buf, uint32_t* epoch, uint32_t* seq,
|
||||
std::vector<VoxelIndex>* added,
|
||||
std::vector<VoxelIndex>* removed);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_BINARY_CODEC_H
|
||||
|
||||
@@ -31,11 +31,25 @@ struct WebConfig {
|
||||
double path_hz = 1.0;
|
||||
// MAP khong co tan so: chi gui khi map_version doi.
|
||||
|
||||
// Ban do voxel khong co tan so gui, ca tap day du lan delta: chung di theo
|
||||
// SU KIEN (epoch doi / do thi doi), giong MAP. Nhip that do duty 25% cua
|
||||
// luong slam quyet dinh -- xem Runtime::SlamLoop.
|
||||
|
||||
// --- Giam bang thong --------------------------------------------------
|
||||
uint32_t cloud_max_points = 4000; // voxel-stride truoc khi ma hoa
|
||||
float cloud_quant_m = 0.01f; // luong tu hoa i16 -> dai +-327 m
|
||||
double path_min_step_m = 0.1; // thua hoa quy dao
|
||||
|
||||
// Mot manh cua ban do voxel day du. 16 kB = 2722 o.
|
||||
//
|
||||
// ⚠️ Manh full-sync KHONG di qua hang doi (xem Publish): chung duoc bom
|
||||
// `voxel_sync_chunks_per_tick` manh moi lan Publish. O 10 Hz va 16 kB thi
|
||||
// mot dot dong bo la 160 kB/s -- vuot ngan sach 120 kB/s, nhung CHI trong
|
||||
// vai giay dau va chi voi client vua vao. Khung cloud (drop duoc) hap thu
|
||||
// phan chenh.
|
||||
uint32_t voxel_chunk_bytes = 16384;
|
||||
uint32_t voxel_sync_chunks_per_tick = 1;
|
||||
|
||||
// Hang doi gui moi phien. Day thi drop khung CU NHAT khong phai MAP.
|
||||
// MAP khong bao gio bi drop -- thay vao do bat co map_pending.
|
||||
size_t max_queued_frames = 4;
|
||||
|
||||
@@ -45,6 +45,13 @@ struct SlamSnapshot {
|
||||
int proximity_total = 0;
|
||||
uint32_t map_version = 0;
|
||||
double process_ms = 0.0;
|
||||
|
||||
// Ban do voxel 3D den tu dau: "scan+depth" | "scan" | "off".
|
||||
// Hien trong JSON status de mot ban do 3D RONG doc duoc ma khong phai mo
|
||||
// khung 3D len xem -- cung ly do voi dong dem o/trong/chua-biet cua luoi 2D.
|
||||
std::string voxels_source = "off";
|
||||
uint32_t voxel_cells = 0;
|
||||
uint32_t voxel_epoch = 0;
|
||||
};
|
||||
|
||||
struct TeleopSnapshot {
|
||||
@@ -163,6 +170,17 @@ struct WebSnapshot {
|
||||
// that -- luc do khong co su that nao de doi chieu.
|
||||
OccupancyGridPtr world_map;
|
||||
std::vector<Pose2D> trajectory;
|
||||
|
||||
// --- Ban do voxel 3D ---
|
||||
//
|
||||
// `voxels` la TAP DAY DU hien tai (da sap xep). WebServer chia manh va gui
|
||||
// cho session nao chua co epoch nay.
|
||||
//
|
||||
// `voxel_delta` la payload DA MA HOA san cua phan them/bot so voi epoch
|
||||
// truoc -- ma hoa MOT lan o luong slam roi dung chung cho moi session, y het
|
||||
// cach khung MAP_FULL dung chung mot `buf`. Null khi khong co gi doi.
|
||||
VoxelGridPtr voxels;
|
||||
std::shared_ptr<const std::string> voxel_delta;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
@@ -171,66 +171,89 @@ void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
|
||||
}
|
||||
}
|
||||
|
||||
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
|
||||
UnixTime stamp, std::string* out) {
|
||||
// Kich thuoc doi -> khong vá duoc, phai gui full.
|
||||
if (map.width != prev.width || map.height != prev.height ||
|
||||
map.data.size() != prev.data.size() ||
|
||||
std::abs(map.resolution - prev.resolution) > 1e-6f ||
|
||||
std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 ||
|
||||
std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) {
|
||||
return false;
|
||||
// --- Ban do voxel 3D -------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t kVoxelFullHeaderBytes = 32; // sau header chung 16 byte
|
||||
constexpr size_t kVoxelCellBytes = 6; // i16 * 3
|
||||
|
||||
void PutCells(std::string* out, const VoxelIndex* cells, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
PutI16(out, cells[i].x);
|
||||
PutI16(out, cells[i].y);
|
||||
PutI16(out, cells[i].z);
|
||||
}
|
||||
}
|
||||
|
||||
// Vung bao cac o doi.
|
||||
int32_t x0 = static_cast<int32_t>(map.width);
|
||||
int32_t y0 = static_cast<int32_t>(map.height);
|
||||
int32_t x1 = -1, y1 = -1;
|
||||
|
||||
for (uint32_t y = 0; y < map.height; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (uint32_t x = 0; x < map.width; ++x) {
|
||||
if (map.data[row + x] == prev.data[row + x]) continue;
|
||||
const int32_t xi = static_cast<int32_t>(x);
|
||||
const int32_t yi = static_cast<int32_t>(y);
|
||||
if (xi < x0) x0 = xi;
|
||||
if (yi < y0) y0 = yi;
|
||||
if (xi > x1) x1 = xi;
|
||||
if (yi > y1) y1 = yi;
|
||||
}
|
||||
}
|
||||
|
||||
if (x1 < 0) return false; // khong o nao doi
|
||||
|
||||
const int32_t w = x1 - x0 + 1;
|
||||
const int32_t h = y1 - y0 + 1;
|
||||
|
||||
std::vector<int8_t> patch;
|
||||
patch.reserve(static_cast<size_t>(w) * static_cast<size_t>(h));
|
||||
for (int32_t y = y0; y <= y1; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (int32_t x = x0; x <= x1; ++x) {
|
||||
patch.push_back(map.data[row + static_cast<size_t>(x)]);
|
||||
}
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kMapPatch, stamp);
|
||||
PutI32(out, x0);
|
||||
PutI32(out, y0);
|
||||
PutI32(out, w);
|
||||
PutI32(out, h);
|
||||
|
||||
const size_t run_count_off = out->size();
|
||||
PutU32(out, 0);
|
||||
const size_t runs = RleEncode(patch, out);
|
||||
const uint32_t r32 = static_cast<uint32_t>(runs);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
(*out)[run_count_off + static_cast<size_t>(i)] =
|
||||
static_cast<char>((r32 >> (8 * i)) & 0xFF);
|
||||
bool GetCells(const std::string& b, size_t off, size_t n,
|
||||
std::vector<VoxelIndex>* out) {
|
||||
if (b.size() < off + n * kVoxelCellBytes) return false;
|
||||
out->reserve(out->size() + n);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const size_t o = off + i * kVoxelCellBytes;
|
||||
VoxelIndex k;
|
||||
// Qua uint16 roi ep ve int16: ep thang tu char la noi dau am di lac.
|
||||
k.x = static_cast<int16_t>(GetU16(b, o));
|
||||
k.y = static_cast<int16_t>(GetU16(b, o + 2));
|
||||
k.z = static_cast<int16_t>(GetU16(b, o + 4));
|
||||
out->push_back(k);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
size_t VoxelCellsPerChunk(uint32_t chunk_bytes) {
|
||||
const size_t usable = chunk_bytes > (kBinaryHeaderSize + kVoxelFullHeaderBytes)
|
||||
? chunk_bytes - kBinaryHeaderSize - kVoxelFullHeaderBytes
|
||||
: 0;
|
||||
const size_t n = usable / kVoxelCellBytes;
|
||||
return n > 0 ? n : 1; // khong bao gio 0: se lap vo han khi chia manh
|
||||
}
|
||||
|
||||
uint16_t VoxelChunkCount(const VoxelGrid& grid, uint32_t chunk_bytes) {
|
||||
const size_t per = VoxelCellsPerChunk(chunk_bytes);
|
||||
// Ban do RONG van phai co MOT manh: do la cach client biet "gio khong con
|
||||
// gi" thay vi giu mai tap cu.
|
||||
if (grid.cells.empty()) return 1;
|
||||
const size_t n = (grid.cells.size() + per - 1) / per;
|
||||
return static_cast<uint16_t>(std::min<size_t>(n, 65535));
|
||||
}
|
||||
|
||||
void EncodeVoxelFull(const VoxelGrid& grid, UnixTime stamp, size_t first,
|
||||
size_t count, uint16_t chunk_index, uint16_t chunk_count,
|
||||
std::string* out) {
|
||||
const size_t total = grid.cells.size();
|
||||
const size_t begin = std::min(first, total);
|
||||
const size_t n = std::min(count, total - begin);
|
||||
|
||||
PutHeader(out, BinaryType::kVoxelFull, stamp);
|
||||
PutF32(out, grid.resolution);
|
||||
PutF32(out, static_cast<float>(grid.origin_x));
|
||||
PutF32(out, static_cast<float>(grid.origin_y));
|
||||
PutF32(out, static_cast<float>(grid.origin_z));
|
||||
PutU32(out, grid.epoch);
|
||||
PutU32(out, static_cast<uint32_t>(total));
|
||||
PutU16(out, chunk_index);
|
||||
PutU16(out, chunk_count);
|
||||
PutU32(out, static_cast<uint32_t>(n));
|
||||
PutCells(out, grid.cells.data() + begin, n);
|
||||
}
|
||||
|
||||
void EncodeVoxelDelta(uint32_t epoch, uint32_t seq,
|
||||
const std::vector<VoxelIndex>& added,
|
||||
const std::vector<VoxelIndex>& removed, UnixTime stamp,
|
||||
std::string* out) {
|
||||
PutHeader(out, BinaryType::kVoxelDelta, stamp);
|
||||
PutU32(out, epoch);
|
||||
PutU32(out, seq);
|
||||
PutU32(out, static_cast<uint32_t>(added.size()));
|
||||
PutU32(out, static_cast<uint32_t>(removed.size()));
|
||||
PutCells(out, added.data(), added.size());
|
||||
PutCells(out, removed.data(), removed.size());
|
||||
}
|
||||
|
||||
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
|
||||
std::string* out) {
|
||||
std::vector<const Pose2D*> kept;
|
||||
@@ -332,4 +355,38 @@ bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DecodeVoxelFull(const std::string& buf, VoxelChunkInfo* info,
|
||||
std::vector<VoxelIndex>* out) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kVoxelFull) return false;
|
||||
if (buf.size() < kBinaryHeaderSize + 32) return false;
|
||||
const size_t o = kBinaryHeaderSize;
|
||||
|
||||
info->epoch = GetU32(buf, o + 16);
|
||||
info->total = GetU32(buf, o + 20);
|
||||
info->chunk_index = GetU16(buf, o + 24);
|
||||
info->chunk_count = GetU16(buf, o + 26);
|
||||
const uint32_t n = GetU32(buf, o + 28);
|
||||
return GetCells(buf, o + 32, n, out);
|
||||
}
|
||||
|
||||
bool DecodeVoxelDelta(const std::string& buf, uint32_t* epoch, uint32_t* seq,
|
||||
std::vector<VoxelIndex>* added,
|
||||
std::vector<VoxelIndex>* removed) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kVoxelDelta) return false;
|
||||
if (buf.size() < kBinaryHeaderSize + 16) return false;
|
||||
const size_t o = kBinaryHeaderSize;
|
||||
|
||||
*epoch = GetU32(buf, o);
|
||||
*seq = GetU32(buf, o + 4);
|
||||
const uint32_t n_add = GetU32(buf, o + 8);
|
||||
const uint32_t n_del = GetU32(buf, o + 12);
|
||||
|
||||
added->clear();
|
||||
removed->clear();
|
||||
if (!GetCells(buf, o + 16, n_add, added)) return false;
|
||||
return GetCells(buf, o + 16 + static_cast<size_t>(n_add) * 6, n_del, removed);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
@@ -188,7 +188,12 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
|
||||
Int("prox_id", s.slam.proximity_id, out); Comma(out);
|
||||
Int("prox_total", s.slam.proximity_total, out); Comma(out);
|
||||
Int("map_version", s.slam.map_version, out); Comma(out);
|
||||
Num("process_ms", s.slam.process_ms, 1, out);
|
||||
Num("process_ms", s.slam.process_ms, 1, out); Comma(out);
|
||||
// Ban do 3D: nguon va so o. Mot ban do voxel RONG phai doc duoc tu day, chu
|
||||
// khong phai bang cach mo khung 3D len roi doan.
|
||||
Str("voxels_source", s.slam.voxels_source, out); Comma(out);
|
||||
Int("voxel_cells", static_cast<int>(s.slam.voxel_cells), out); Comma(out);
|
||||
Int("voxel_epoch", static_cast<int>(s.slam.voxel_epoch), out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("teleop", out);
|
||||
|
||||
@@ -265,6 +265,20 @@ class WsSession : public std::enable_shared_from_this<WsSession>,
|
||||
void mark_world_map_sent() { world_map_sent_.store(true); }
|
||||
void set_acked_map_version(uint32_t v) { acked_map_version_.store(v); }
|
||||
|
||||
// --- Ban do voxel 3D ---
|
||||
// `voxel_epoch_` = epoch client DA co du. 0 = chua co gi.
|
||||
// `voxel_sync_from_` = da bom toi o thu may cua epoch dang dong bo.
|
||||
uint32_t voxel_epoch() const { return voxel_epoch_.load(); }
|
||||
void set_voxel_epoch(uint32_t v) { voxel_epoch_.store(v); }
|
||||
bool voxel_resync() const { return voxel_resync_.load(); }
|
||||
void set_voxel_resync(bool v) { voxel_resync_.store(v); }
|
||||
uint32_t voxel_sync_epoch() const { return voxel_sync_epoch_.load(); }
|
||||
size_t voxel_sync_from() const { return voxel_sync_from_.load(); }
|
||||
void set_voxel_sync(uint32_t epoch, size_t from) {
|
||||
voxel_sync_epoch_.store(epoch);
|
||||
voxel_sync_from_.store(from);
|
||||
}
|
||||
|
||||
void Close() override {
|
||||
auto self = shared_from_this();
|
||||
asio::post(ws_.get_executor(), [self] {
|
||||
@@ -342,6 +356,23 @@ class WsSession : public std::enable_shared_from_this<WsSession>,
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Client da rap du moi manh cua mot epoch voxel.
|
||||
if (type == "ack_voxel") {
|
||||
double v = 0.0;
|
||||
if (JsonGetNumber(msg, "epoch", &v) && v >= 0.0) {
|
||||
set_voxel_epoch(static_cast<uint32_t>(v));
|
||||
set_voxel_resync(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Client phat hien hut so thu tu delta hoac lech epoch -> xin ca tap.
|
||||
if (type == "voxel_resync") {
|
||||
set_voxel_resync(true);
|
||||
set_voxel_epoch(0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void Enqueue(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
|
||||
@@ -401,6 +432,10 @@ class WsSession : public std::enable_shared_from_this<WsSession>,
|
||||
// Ban do the gioi la TINH trong mo phong -- gui mot lan la du, khong can
|
||||
// co che version/ACK nhu ban do SLAM.
|
||||
std::atomic<bool> world_map_sent_{false};
|
||||
std::atomic<uint32_t> voxel_epoch_{0};
|
||||
std::atomic<bool> voxel_resync_{false};
|
||||
std::atomic<uint32_t> voxel_sync_epoch_{0};
|
||||
std::atomic<size_t> voxel_sync_from_{0};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -801,6 +836,81 @@ void WebServer::Publish(const WebSnapshot& snap) {
|
||||
s->set_acked_map_version(snap.slam.map_version);
|
||||
}
|
||||
}
|
||||
|
||||
// --- BAN DO VOXEL 3D ---
|
||||
//
|
||||
// Hai duong, va chung KHONG doi xung:
|
||||
//
|
||||
// full-sync : client chua co epoch nay -> bom `voxel_sync_chunks_per_tick`
|
||||
// manh moi lan Publish, cho toi het. KHONG danh dau is_map:
|
||||
// `Enqueue` khong bao gio drop khung map, nen 23 manh voxel
|
||||
// danh dau is_map se lam hang doi phinh vo han. Chung la
|
||||
// khung THUONG, drop duoc; mat manh nao thi ACK khong bao gio
|
||||
// toi va lan dong bo sau bat dau lai.
|
||||
//
|
||||
// delta : client dang giu dung epoch -> gui phan them/bot ngay khi co.
|
||||
// Payload da duoc ma hoa san o luong slam va chi song MOT lan
|
||||
// (WebLoop lay xong la xoa), nen khong co cong tan so nao o day.
|
||||
if (snap.voxels) {
|
||||
const uint32_t epoch = snap.voxels->epoch;
|
||||
const size_t per = VoxelCellsPerChunk(impl_->cfg.voxel_chunk_bytes);
|
||||
const uint16_t chunks =
|
||||
VoxelChunkCount(*snap.voxels, impl_->cfg.voxel_chunk_bytes);
|
||||
// KHONG gate theo tan so: delta chi sinh ra khi luong slam xuat ban do
|
||||
// (<= map_rebuild_rate_hz, va da bi duty 25% ghim lai), nen nhip do CHINH
|
||||
// la nhip tu nhien. Mot cong tan so o day chi co the LAM MAT khung.
|
||||
|
||||
for (const auto& s : targets) {
|
||||
const bool synced = !s->voxel_resync() && s->voxel_epoch() == epoch;
|
||||
if (synced) {
|
||||
// ⚠️ is_map=TRUE cho delta. Khong phai vi no la ban do 2D, ma vi
|
||||
// `Enqueue` chi drop khung khong-map: mat mot delta la client giu mot
|
||||
// ban do SAI vinh vien, y het mat mot khung MAP. Delta nho (vai tram
|
||||
// byte) va toi da ~4 khung/giay nen giu chung lai la re.
|
||||
if (snap.voxel_delta) s->Send(snap.voxel_delta, true, /*is_map=*/true);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Bat dau lai tu manh 0 khi epoch doi giua chung -- tron hai epoch la
|
||||
// cach chac chan nhat de ra mot ban do sai ma khong ai biet.
|
||||
size_t from = s->voxel_sync_from();
|
||||
if (s->voxel_sync_epoch() != epoch) from = 0;
|
||||
|
||||
for (uint32_t k = 0;
|
||||
k < impl_->cfg.voxel_sync_chunks_per_tick &&
|
||||
from < snap.voxels->cells.size();
|
||||
++k) {
|
||||
const uint16_t index = static_cast<uint16_t>(from / per);
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeVoxelFull(*snap.voxels, snap.stamp, from, per, index, chunks, buf.get());
|
||||
s->Send(buf, true, /*is_map=*/false);
|
||||
from += per;
|
||||
}
|
||||
|
||||
// Ban do RONG: van gui MOT manh rong, de client biet "gio khong con gi"
|
||||
// thay vi giu mai tap cu.
|
||||
if (snap.voxels->cells.empty()) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeVoxelFull(*snap.voxels, snap.stamp, 0, 0, 0, 1, buf.get());
|
||||
s->Send(buf, true, /*is_map=*/false);
|
||||
}
|
||||
|
||||
s->set_voxel_sync(epoch, from);
|
||||
|
||||
// Da bom het -> danh dau DA DONG BO ngay, khong doi `ack_voxel`.
|
||||
//
|
||||
// ⚠️ Cho ACK o day la mot cho treo that: ACK mat thi server coi
|
||||
// client van dang dong bo, ma `from` da toi cuoi nen vong tren khong gui
|
||||
// gi nua, va delta cung khong duoc gui vi chua "synced" -- ban do 3D
|
||||
// dung yen vinh vien ma khong mot loi nao. Danh dau lac quan o day va de
|
||||
// client TU xin resync khi no phat hien hut so thu tu delta; do la cung
|
||||
// khuon mau `set_acked_map_version` ngay sau khi xep hang o khoi MAP.
|
||||
if (from >= snap.voxels->cells.size()) {
|
||||
s->set_voxel_epoch(epoch);
|
||||
s->set_voxel_resync(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t WebServer::client_count() const {
|
||||
|
||||
@@ -12,7 +12,7 @@ const MAGIC = 0x314C5356; // 'VSL1' little-endian
|
||||
// Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css.
|
||||
// Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
|
||||
// cache ban cu".
|
||||
const UI_VERSION = '2026-09-19g';
|
||||
const UI_VERSION = '2026-09-23a';
|
||||
|
||||
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau.
|
||||
//
|
||||
@@ -62,9 +62,12 @@ const PALETTE = {
|
||||
},
|
||||
};
|
||||
|
||||
const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_MAP_PATCH = 4, T_PATH = 5;
|
||||
const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_PATH = 5;
|
||||
// 4 = kMapPatch, DA BO o phia server. Giu lo trong, khong tai dung.
|
||||
// Ban do THE GIOI cua bo mo phong -- khung nhin "Gazebo". Tinh: gui mot lan.
|
||||
const T_WORLD_MAP = 6;
|
||||
// Ban do voxel 3D: tap day du (chia manh) va phan them/bot.
|
||||
const T_VOXEL_FULL = 7, T_VOXEL_DELTA = 8;
|
||||
|
||||
// Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh.
|
||||
const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
|
||||
@@ -77,6 +80,14 @@ const state = {
|
||||
// anchorPose(). `scanDelta` den tu khung state, dung ngay khung scan ke tiep.
|
||||
cloudPose: null, scanPose: null, scanDelta: null,
|
||||
map: null, mapImage: null, mapVersion: 0,
|
||||
// Ban do voxel 3D. `set` la Set CAC SO (khong phai chuoi): o 100k phan tu
|
||||
// thi Set<number> re hon han Set<string> ca ve bo nho lan thoi gian.
|
||||
// `dirty` = co gi doi ke tu lan dung lai hinh gan nhat.
|
||||
voxels: {
|
||||
epoch: 0, res: 0.1, ox: 0, oy: 0, oz: 0,
|
||||
set: new Set(), total: 0, seq: 0, syncing: false, dirty: false,
|
||||
},
|
||||
voxelResyncAt: 0,
|
||||
bytes: 0, lastBytes: 0, wireRate: 0,
|
||||
};
|
||||
|
||||
@@ -127,6 +138,32 @@ function setConn(ok) {
|
||||
|
||||
// --- Khung nhi phan --------------------------------------------------------
|
||||
|
||||
// Khoa voxel dang SO. Ba chi so i16 -> mot so nguyen <= 2^48, van chinh xac
|
||||
// tuyet doi trong double.
|
||||
function voxelKey(x, y, z) {
|
||||
return ((x + 32768) * 65536 + (y + 32768)) * 65536 + (z + 32768);
|
||||
}
|
||||
|
||||
function voxelUnpack(k) {
|
||||
const z = (k % 65536) - 32768;
|
||||
k = (k - (z + 32768)) / 65536;
|
||||
const y = (k % 65536) - 32768;
|
||||
k = (k - (y + 32768)) / 65536;
|
||||
return [k - 32768, y, z];
|
||||
}
|
||||
|
||||
// Xin server gui lai ca tap. Ham han MOT lan moi giay: lech epoch thuong keo
|
||||
// theo mot chum khung delta, va moi khung lai goi vao day.
|
||||
function requestVoxelResync() {
|
||||
const now = Date.now();
|
||||
if (now - state.voxelResyncAt < 1000) return;
|
||||
state.voxelResyncAt = now;
|
||||
state.voxels.seq = 0;
|
||||
if (ws && ws.readyState === 1) {
|
||||
ws.send(JSON.stringify({ t: 'voxel_resync' }));
|
||||
}
|
||||
}
|
||||
|
||||
function onBinary(dv) {
|
||||
if (dv.byteLength < 16 || dv.getUint32(0, true) !== MAGIC) return;
|
||||
const type = dv.getUint8(4);
|
||||
@@ -212,6 +249,84 @@ function onBinary(dv) {
|
||||
return;
|
||||
}
|
||||
|
||||
// --- Ban do voxel 3D ---
|
||||
//
|
||||
// Khoa la mot SO, khong phai chuoi: `((x+32768)*65536 + (y+32768))*65536 +
|
||||
// (z+32768)` toi da 2^48, double bieu dien chinh xac tuyet doi. Set<string>
|
||||
// o 100k phan tu la mot con duong chac chan toi giat hinh.
|
||||
if (type === T_VOXEL_FULL) {
|
||||
const res = dv.getFloat32(off, true);
|
||||
const ox = dv.getFloat32(off + 4, true);
|
||||
const oy = dv.getFloat32(off + 8, true);
|
||||
const oz = dv.getFloat32(off + 12, true);
|
||||
const epoch = dv.getUint32(off + 16, true);
|
||||
const total = dv.getUint32(off + 20, true);
|
||||
const chunkIndex = dv.getUint16(off + 24, true);
|
||||
const chunkCount = dv.getUint16(off + 26, true);
|
||||
const n = dv.getUint32(off + 28, true);
|
||||
|
||||
const v = state.voxels;
|
||||
// Manh dau, hoac epoch la giua chung -> bo het lam lai. Tron hai epoch se
|
||||
// ra mot ban do khong ton tai o dau ca.
|
||||
if (chunkIndex === 0 || epoch !== v.epoch) {
|
||||
v.set = new Set();
|
||||
v.epoch = epoch;
|
||||
v.res = res;
|
||||
v.ox = ox; v.oy = oy; v.oz = oz;
|
||||
v.total = total;
|
||||
v.seq = 0;
|
||||
v.syncing = true;
|
||||
}
|
||||
for (let i = 0; i < n; i++) {
|
||||
const b = off + 32 + i * 6;
|
||||
v.set.add(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true),
|
||||
dv.getInt16(b + 4, true)));
|
||||
}
|
||||
v.dirty = true;
|
||||
|
||||
if (chunkIndex + 1 >= chunkCount) {
|
||||
v.syncing = false;
|
||||
// Dem lai truoc khi bao "xong": manh full-sync la khung THUONG, server
|
||||
// drop duoc chung khi hang doi day. Thieu mot manh ma van ack thi ban do
|
||||
// co mot lo hong khong bao gio duoc lap, va khong mot dau hieu nao.
|
||||
if (v.set.size !== v.total) {
|
||||
requestVoxelResync();
|
||||
} else if (ws && ws.readyState === 1) {
|
||||
ws.send(JSON.stringify({ t: 'ack_voxel', epoch: v.epoch }));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === T_VOXEL_DELTA) {
|
||||
const epoch = dv.getUint32(off, true);
|
||||
const seq = dv.getUint32(off + 4, true);
|
||||
const nAdd = dv.getUint32(off + 8, true);
|
||||
const nDel = dv.getUint32(off + 12, true);
|
||||
|
||||
const v = state.voxels;
|
||||
// Lech epoch = server da dung lai ban do (vong dong). Hut so thu tu = mat
|
||||
// khung. Ca hai deu khong va duoc, phai xin lai ca tap.
|
||||
if (epoch !== v.epoch || (v.seq !== 0 && seq !== v.seq + 1)) {
|
||||
requestVoxelResync();
|
||||
return;
|
||||
}
|
||||
v.seq = seq;
|
||||
|
||||
let b = off + 16;
|
||||
for (let i = 0; i < nAdd; i++, b += 6) {
|
||||
v.set.add(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true),
|
||||
dv.getInt16(b + 4, true)));
|
||||
}
|
||||
for (let i = 0; i < nDel; i++, b += 6) {
|
||||
v.set.delete(voxelKey(dv.getInt16(b, true), dv.getInt16(b + 2, true),
|
||||
dv.getInt16(b + 4, true)));
|
||||
}
|
||||
v.total = v.set.size;
|
||||
v.dirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (type === T_PATH) {
|
||||
const n = dv.getUint32(off, true);
|
||||
const pts = new Float32Array(n * 2);
|
||||
@@ -1069,6 +1184,11 @@ function draw3d() {
|
||||
|
||||
// SLAM: lop phu tren san, hien DAN khi quet -- day la phan "RViz". O chua
|
||||
// quet trong suot nen tuong 3D van nhin xuyen qua.
|
||||
// VOXEL: "cai gi dung tren san", bu cho tam phang cua v3dSetMap ("da quet
|
||||
// toi dau"). Hai lop khong tranh nhau: tam phang o y = -0.002, voxel bat
|
||||
// dau tu z_min = 0.05.
|
||||
v3dSetVoxels(state.voxels, on('lyVoxel'));
|
||||
|
||||
if (state.map && on('lyMap')) {
|
||||
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ const V3D = {
|
||||
ready: false,
|
||||
scene: null, camera: null, renderer: null, root: null,
|
||||
robotGroup: null, scanPts: null, cloudPts: null, mapMesh: null,
|
||||
voxelMesh: null, voxelCap: 0, voxelEpoch: -1,
|
||||
worldMesh: null, worldKey: null,
|
||||
meshWorld: null, // nhom mesh THAT doc tu .world; co thi khong dung khoi hop
|
||||
gtGroup: null, pathLine: null,
|
||||
@@ -496,6 +497,93 @@ function v3dSetCloud(arr, pose) {
|
||||
V3D.cloudPts.geometry.setAttribute('color', new THREE.BufferAttribute(col, 3));
|
||||
}
|
||||
|
||||
// --- Ban do voxel 3D -------------------------------------------------------
|
||||
//
|
||||
// Nguon: SLAM, khong phai bo mo phong. Day la "cai gi dung tren san" do chinh
|
||||
// robot do duoc, bu cho tam phang cua v3dSetMap ("da quet toi dau").
|
||||
//
|
||||
// Ba cho CO Y khac v3dSetWorld va v3dSetCloud, moi cho vi mot ly do:
|
||||
//
|
||||
// 1. Dung lai theo NOI DUNG (`v.dirty`), khong theo kich thuoc. v3dSetWorld
|
||||
// cache theo `w x h @ ox,oy` -- dung cho mot ban do TINH, sai hoan toan o
|
||||
// day vi tap voxel doi lien tuc trong khi bao ngoai dung yen.
|
||||
//
|
||||
// 2. KHONG dispose/dung lai hinh moi khung nhu v3dSetCloud. InstancedMesh co
|
||||
// so luong co dinh, nen cap phat du `capacity` roi chi doi `count`. O
|
||||
// 100k the thi kieu cua cloud khong song noi.
|
||||
//
|
||||
// 3. KHONG do bong. v3dSetWorld bat ca castShadow lan receiveShadow; nem
|
||||
// 100k the vao shadow map 2048^2 la mat frame rate. Dung "sua" lai.
|
||||
function v3dSetVoxels(v, visible) {
|
||||
if (!V3D.ready) return;
|
||||
if (!v || !visible || v.set.size === 0) {
|
||||
if (V3D.voxelMesh) V3D.voxelMesh.visible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const n = v.set.size;
|
||||
const needNew = !V3D.voxelMesh || n > V3D.voxelCap ||
|
||||
(V3D.voxelMesh && V3D.voxelRes !== v.res);
|
||||
if (needNew) {
|
||||
if (V3D.voxelMesh) {
|
||||
V3D.root.remove(V3D.voxelMesh);
|
||||
V3D.voxelMesh.geometry.dispose();
|
||||
V3D.voxelMesh.material.dispose();
|
||||
}
|
||||
// Cap phat du de lon them mot doan ma khong phai cap phat lai moi khung.
|
||||
let cap = 1024;
|
||||
while (cap < Math.ceil(n * 1.5)) cap *= 2;
|
||||
const geo = new THREE.BoxGeometry(v.res, v.res, v.res);
|
||||
const mat = new THREE.MeshStandardMaterial({ roughness: 0.9, metalness: 0.0 });
|
||||
V3D.voxelMesh = new THREE.InstancedMesh(geo, mat, cap);
|
||||
// Bounding sphere cua InstancedMesh lay tu hinh GOC (mot hop 0.1 m), nen
|
||||
// de mac dinh thi three.js cull ca ban do ngay khi goc toa do ra khoi khung.
|
||||
V3D.voxelMesh.frustumCulled = false;
|
||||
V3D.voxelMesh.castShadow = false;
|
||||
V3D.voxelMesh.receiveShadow = false;
|
||||
V3D.voxelCap = cap;
|
||||
V3D.voxelRes = v.res;
|
||||
V3D.root.add(V3D.voxelMesh);
|
||||
v.dirty = true; // hinh moi -> phai do lai du lieu
|
||||
}
|
||||
|
||||
V3D.voxelMesh.visible = true;
|
||||
if (!v.dirty) return;
|
||||
v.dirty = false;
|
||||
|
||||
const m4 = new THREE.Matrix4();
|
||||
const col = new THREE.Color();
|
||||
const half = v.res * 0.5;
|
||||
let i = 0;
|
||||
for (const key of v.set) {
|
||||
// Giai khoa tai cho: goi voxelUnpack() 100k lan moi lan dung lai la
|
||||
// 100k mang tam.
|
||||
const z = (key % 65536) - 32768;
|
||||
const k1 = (key - (z + 32768)) / 65536;
|
||||
const y = (k1 % 65536) - 32768;
|
||||
const x = (k1 - (y + 32768)) / 65536 - 32768;
|
||||
|
||||
// Tam o, khong phai goc o. ROS (x, y, z) -> three (x, z, -y) -- giong
|
||||
// toScene(), nhung noi thang vao day: toScene() cap phat mot Vector3 moi
|
||||
// lan goi, va 100k lan cap phat moi lan dung lai la mot con bao GC.
|
||||
const wx = v.ox + x * v.res + half;
|
||||
const wy = v.oy + y * v.res + half;
|
||||
const wz = v.oz + z * v.res + half;
|
||||
m4.makeTranslation(wx, wz, -wy);
|
||||
V3D.voxelMesh.setMatrixAt(i, m4);
|
||||
|
||||
// Cung thang mau voi point cloud, gian ra toi 2 m: hai lop phai doc nhu
|
||||
// mot he, khong phai hai he mau canh nhau.
|
||||
const t = Math.max(0, Math.min(1, wz / 2.0));
|
||||
col.setRGB((80 + 175 * t) / 255, (200 - 90 * t) / 255, (120 + 60 * t) / 255);
|
||||
V3D.voxelMesh.setColorAt(i, col);
|
||||
++i;
|
||||
}
|
||||
V3D.voxelMesh.count = i;
|
||||
V3D.voxelMesh.instanceMatrix.needsUpdate = true;
|
||||
if (V3D.voxelMesh.instanceColor) V3D.voxelMesh.instanceColor.needsUpdate = true;
|
||||
}
|
||||
|
||||
// The gioi 3D: o BI CHIEM -> hop, dung nhu Gazebo dung tuong tu ban do.
|
||||
//
|
||||
// ================== VI SAO INSTANCED ==================
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
<div class="layers">
|
||||
<label><input type="checkbox" id="lyWorld" checked> the gioi</label>
|
||||
<label><input type="checkbox" id="lyMap" checked> map SLAM</label>
|
||||
<!-- Ban do voxel 3D. TAT mac dinh: no chi co du lieu khi slam.yaml dat
|
||||
camera_3d: true, va bat san se lam nguoi dung tuong tinh nang hong
|
||||
trong khi that ra no dang tat o cau hinh. -->
|
||||
<label><input type="checkbox" id="lyVoxel"> voxel 3D</label>
|
||||
<label><input type="checkbox" id="lyScan" checked> scan</label>
|
||||
<label><input type="checkbox" id="lyCloud" checked> cloud</label>
|
||||
<label><input type="checkbox" id="lyPath" checked> path</label>
|
||||
|
||||
Reference in New Issue
Block a user