1926 lines
76 KiB
C++
1926 lines
76 KiB
C++
#include "vslam/sim_source.h"
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cmath>
|
|
#include <deque>
|
|
#include <functional>
|
|
#include <mutex>
|
|
#include <random>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#include "vslam/buffer_pool.h"
|
|
#include "vslam/geometry.h"
|
|
#include "vslam/log.h"
|
|
#include "vslam/node_constants.h"
|
|
#include "vslam/occupancy_map_io.h"
|
|
#include "vslam/robot_model.h"
|
|
|
|
#include <limits>
|
|
|
|
namespace vslam {
|
|
namespace {
|
|
|
|
// Raycast dia hinh 3D: chi noi suy san khi tia da xuong trong dai nay tren
|
|
// mat san cua o. Lon hon nhieu sai khac giua gia tri o va gia tri noi suy
|
|
// (o doc 30 do: < 1.5 cm), nho hon do cao LiDAR (0.2165 m).
|
|
constexpr double kSmoothFloorBand = 0.15;
|
|
|
|
// Ma tran xoay R = Rz(yaw) * Ry(pitch) * Rx(roll), REP-103: than -> the gioi.
|
|
// pitch DUONG = mui chuc xuong, roll DUONG = ben trai nhac len. Tinh MOT lan
|
|
// cho moi scan / moi khung anh, khong goi sin/cos cho tung tia.
|
|
struct Rot3 {
|
|
double m[9];
|
|
static Rot3 FromRPY(double roll, double pitch, double yaw) {
|
|
const double cr = std::cos(roll), sr = std::sin(roll);
|
|
const double cp = std::cos(pitch), sp = std::sin(pitch);
|
|
const double cy = std::cos(yaw), sy = std::sin(yaw);
|
|
Rot3 r;
|
|
r.m[0] = cy * cp; r.m[1] = cy * sp * sr - sy * cr; r.m[2] = cy * sp * cr + sy * sr;
|
|
r.m[3] = sy * cp; r.m[4] = sy * sp * sr + cy * cr; r.m[5] = sy * sp * cr - cy * sr;
|
|
r.m[6] = -sp; r.m[7] = cp * sr; r.m[8] = cp * cr;
|
|
return r;
|
|
}
|
|
void Apply(double x, double y, double z, double* ox, double* oy, double* oz) const {
|
|
*ox = m[0] * x + m[1] * y + m[2] * z;
|
|
*oy = m[3] * x + m[4] * y + m[5] * z;
|
|
*oz = m[6] * x + m[7] * y + m[8] * z;
|
|
}
|
|
};
|
|
|
|
// Bon lop nay la interface driver THAT, y het ReplaySource. vslam_node khong
|
|
// phan biet duoc phan cung / file .vsr / mo phong.
|
|
|
|
class SimLidar : public LidarInterface {
|
|
public:
|
|
void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
void Push(LaserScanPtr s) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(std::move(s));
|
|
}
|
|
|
|
private:
|
|
ScanCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class SimMcu : public McuInterface {
|
|
public:
|
|
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
|
|
void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); }
|
|
void SetUltrasonicCallback(UltrasonicCallback cb) override { us_cb_ = std::move(cb); }
|
|
void SetBumperCallback(BumperCallback cb) override { bumper_cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
void PushImu(ImuPtr v) {
|
|
if (!open_ || !imu_cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
imu_cb_(std::move(v));
|
|
}
|
|
void PushUltrasonic(const UltrasonicReading& u) {
|
|
if (!open_ || !us_cb_) return;
|
|
us_cb_(u);
|
|
}
|
|
void PushBumper(const BumperReading& b) {
|
|
if (!open_ || !bumper_cb_) return;
|
|
bumper_cb_(b);
|
|
}
|
|
|
|
private:
|
|
ImuCallback imu_cb_;
|
|
BaroCallback baro_cb_;
|
|
UltrasonicCallback us_cb_;
|
|
BumperCallback bumper_cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class SimCamera : public CameraInterface {
|
|
public:
|
|
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
void Push(const CameraFrame& f) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(f);
|
|
}
|
|
|
|
private:
|
|
FrameCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class SimBase : public BaseInterface {
|
|
public:
|
|
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
|
|
|
|
void SetVelocity(double linear, double angular) override {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
cmd_linear_ = linear;
|
|
cmd_angular_ = angular;
|
|
last_cmd_age_ = 0.0;
|
|
}
|
|
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
|
|
void Push(const EncoderReading& e) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(e);
|
|
}
|
|
|
|
// DEADMAN. Goi moi buoc vat ly voi dt vua troi qua.
|
|
//
|
|
// Khong co cai nay thi: tab trinh duyet dong giua luc dang lai -> khong con
|
|
// ai gui lenh -> robot giu nguyen van toc cuoi VINH VIEN va lao di. Wifi
|
|
// rot cung cho ket qua y het.
|
|
//
|
|
// Day la chan cuoi cung, doc lap voi lop safety va voi deadman phia JS:
|
|
// ca hai deu co the chet, con cai nay thi nam ngay trong base.
|
|
void GetCommand(double* lin, double* ang, double dt) {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
last_cmd_age_ += dt;
|
|
if (last_cmd_age_ > cmd_timeout_sec_) {
|
|
*lin = 0.0;
|
|
*ang = 0.0;
|
|
if (!timed_out_) {
|
|
timed_out_ = true;
|
|
VSLAM_WARN("base: khong co lenh trong " << cmd_timeout_sec_
|
|
<< " s -- dung robot");
|
|
}
|
|
return;
|
|
}
|
|
timed_out_ = false;
|
|
*lin = cmd_linear_;
|
|
*ang = cmd_angular_;
|
|
}
|
|
|
|
void SetCmdTimeout(double sec) {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
cmd_timeout_sec_ = sec;
|
|
}
|
|
|
|
bool timed_out() const {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
return timed_out_;
|
|
}
|
|
|
|
private:
|
|
EncoderCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
mutable std::mutex mu_;
|
|
double cmd_linear_ = 0.0;
|
|
double cmd_angular_ = 0.0;
|
|
double last_cmd_age_ = 1e9; // chua co lenh nao -> coi nhu da het han
|
|
double cmd_timeout_sec_ = 0.3;
|
|
bool timed_out_ = false;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
struct SimSource::Impl {
|
|
SimConfig cfg;
|
|
OccupancyGrid map;
|
|
GazeboWorld world;
|
|
// Doan 2D cua the gioi, de tra ve khoang cach TRUNG MAT TUONG thay vi trung
|
|
// bien o. Rong khi chay tu `--map` (chi co luoi, khong co mesh) -- khi do
|
|
// moi raycast giu nguyen ket qua luoi nhu cu.
|
|
WorldSegments segments;
|
|
|
|
SimLidar lidar;
|
|
SimMcu mcu;
|
|
SimBase base;
|
|
SimCamera camera;
|
|
|
|
// Do cao san moi o. AM = bac hut xuong. Cung kich thuoc voi `map`.
|
|
std::vector<float> floor_z;
|
|
// O kinh: LiDAR va depth xuyen qua, sieu am thay. 1 = kinh.
|
|
std::vector<uint8_t> glass;
|
|
double us_acc = 0.0, bump_acc = 0.0;
|
|
bool bumper_now = false;
|
|
|
|
// Bo dem anh depth. Anh khong so huu bo nho (xem vslam_common.h), nen MOI
|
|
// khung lay mot bo dem rieng tu pool va giu no qua keep_alive -- SlamLoop
|
|
// giu khung moi nhat qua Rtabmap::process tren luong khac, va mot bo dem
|
|
// dung chung se bi khung sau ghi de giua chung.
|
|
std::shared_ptr<BufferPool<std::vector<uint8_t>>> depth_pool =
|
|
BufferPool<std::vector<uint8_t>>::Create(8);
|
|
|
|
// Renderer GPU tuy chon (SetCameraRenderer). null = raycast CPU, khong co IR.
|
|
std::shared_ptr<SimCameraRenderer> renderer;
|
|
std::vector<uint8_t> gl_ir;
|
|
std::vector<float> gl_depth;
|
|
bool gl_fail_logged = false;
|
|
std::shared_ptr<ReplayClock> clock;
|
|
|
|
// Trang thai that cua robot.
|
|
double x = 0.0, y = 0.0, yaw = 0.0;
|
|
double v = 0.0, w = 0.0; // van toc hien tai (sau khi ramp)
|
|
double left_rad = 0.0, right_rad = 0.0;
|
|
double prev_v = 0.0;
|
|
|
|
// Nghieng than robot: he lo xo - giam chan bac hai quanh gia tri can bang
|
|
// do gia toc dat ra. Trang thai la goc va van toc goc.
|
|
double roll = 0.0, pitch = 0.0;
|
|
double roll_rate = 0.0, pitch_rate = 0.0;
|
|
double terrain_pitch = 0.0; // nghieng do DIA HINH, cong vao than
|
|
double last_accel = 0.0;
|
|
|
|
// --- Dia hinh 3D (SimConfig::terrain). Tat thi khong truong nao duoi day
|
|
// duoc doc, va moi duong cu giu nguyen tung byte. ---
|
|
bool terrain_on = false; // chot o Open()
|
|
double ground_z = 0.0; // san duoi tam robot (base_footprint)
|
|
double terrain_roll = 0.0; // nghieng ngang do dia hinh
|
|
double terrain_pitch_rate = 0.0, terrain_roll_rate = 0.0;
|
|
// Goc dia hinh da co gia tri dau chua. Chua thi lan tinh dau KHONG sinh toc
|
|
// do goc -- neu khong, robot dat san tren doc se "quay" 10 do trong 5 ms.
|
|
bool terrain_ready = false;
|
|
bool steps_dirty = true; // san vua doi -> tinh lai mat na bac
|
|
std::vector<uint8_t> step_block; // o sat mep bac (chenh > max_step)
|
|
// Dinh vat can cao nhat moi o (he world, tu mesh). 0 = khong biet -> dung
|
|
// `wall_height` nhu cu.
|
|
std::vector<float> wall_top;
|
|
|
|
// --- IMU dong hoc (SimConfig::imu_model) va phat thua / tre ---
|
|
bool imu_kinematic = false; // chot o Open()
|
|
// RNG RIENG cho IMU dong hoc: dung chung `rng` se xao toan bo chuoi nhieu
|
|
// cua LiDAR/camera va moi ban ghi cu doi theo.
|
|
std::mt19937 imu_rng{1234};
|
|
Rot3 imu_R_prev{}; // tu the buoc truoc
|
|
double imu_p[3][3] = {}; // vi tri diem dat IMU: k-2, k-1, k
|
|
int imu_hist = 0; // so buoc da co lich su (toi da 3)
|
|
double imu_bg[3] = {0.0, 0.0, 0.0}, imu_ba[3] = {0.0, 0.0, 0.0};
|
|
bool imu_lpf_init = false;
|
|
double imu_lpf_w[3] = {0.0, 0.0, 0.0}, imu_lpf_f[3] = {0.0, 0.0, 0.0};
|
|
double imu_out_acc = 0.0;
|
|
std::deque<std::pair<double, ImuPtr>> imu_fifo; // (thoi diem DO, mau)
|
|
|
|
// --- Ground truth cho tool ghi ---
|
|
SimSource::GroundTruthCallback gt_cb;
|
|
double gt_period = 0.0, gt_acc = 0.0;
|
|
|
|
std::atomic<bool> stop{false};
|
|
mutable std::mutex state_mu;
|
|
Stats stats;
|
|
|
|
std::mt19937 rng{1234}; // gieo lai tu cfg.seed trong Open()
|
|
|
|
// Bo tich luy lay mau thua. Phai song qua nhieu lan goi RunFor() -- xem
|
|
// ghi chu trong RunFor().
|
|
double lidar_acc = 0.0, enc_acc = 0.0, cam_acc = 0.0;
|
|
double sim_elapsed = 0.0;
|
|
|
|
explicit Impl(SimConfig c) : cfg(std::move(c)) {}
|
|
|
|
// --- Tinh chinh khoang cach bang doan 2D ----------------------------------
|
|
//
|
|
// ⚠️ DDA tra ve khoang cach toi MAT VAO cua o bi chiem, khong phai toi mat
|
|
// tuong. O do duoc danh dau khi tam giac di qua TAM o, nen mat vao ay nam
|
|
// lui vao trong tuong toi mot o day du.
|
|
//
|
|
// Do duoc o luoi 0.05 m: moi tia dung som, p50 = 3.7 cm, p90 = 5.6 cm so voi
|
|
// mat tuong nhin thay. Lam luoi min hon chi thu nho con so do chu khong xoa
|
|
// duoc no -- van la luong tu hoa.
|
|
//
|
|
// Nen: giu DDA de tim O trung (kinh, vuc, va cham deu van doc luoi), roi CAT
|
|
// chinh xac voi doan nam trong vung do.
|
|
//
|
|
// Tra ve NaN khi khong cat duoc gi -- khi do giu nguyen ket qua cua luoi.
|
|
// Do KHONG phai truong hop la: `--map` khong co mesh, va vai o bi chiem den
|
|
// tu `SetGlass`/tuong chen tay chu khong tu tam giac nao.
|
|
double RefineHit(double ox, double oy, double dx, double dy, double t_grid,
|
|
double max_range) const {
|
|
if (segments.empty()) return std::numeric_limits<double>::quiet_NaN();
|
|
const double res = segments.resolution;
|
|
const int W = static_cast<int>(segments.width);
|
|
const int H = static_cast<int>(segments.height);
|
|
|
|
// Quet vai o quanh cho DDA bao trung. Lui MOT o vi mat tuong that co the
|
|
// nam truoc mat vao (tuong cheo di qua o ma khong qua tam o do), va tien
|
|
// BA o vi no co the nam sau.
|
|
int cells[16][2];
|
|
int n_cells = 0;
|
|
for (int k = -2; k <= 6; ++k) {
|
|
const double t = t_grid + k * res * 0.5;
|
|
if (t < 0.0) continue;
|
|
const int cx = static_cast<int>(
|
|
std::floor((ox + dx * t - segments.origin_x) / res));
|
|
const int cy = static_cast<int>(
|
|
std::floor((oy + dy * t - segments.origin_y) / res));
|
|
if (cx < 0 || cy < 0 || cx >= W || cy >= H) continue;
|
|
bool dup = false;
|
|
for (int i = 0; i < n_cells; ++i) {
|
|
if (cells[i][0] == cx && cells[i][1] == cy) { dup = true; break; }
|
|
}
|
|
if (!dup && n_cells < 16) { cells[n_cells][0] = cx; cells[n_cells][1] = cy; n_cells++; }
|
|
}
|
|
|
|
double best = std::numeric_limits<double>::infinity();
|
|
for (int i = 0; i < n_cells; ++i) {
|
|
const size_t idx = static_cast<size_t>(cells[i][1]) * segments.width +
|
|
static_cast<size_t>(cells[i][0]);
|
|
for (uint32_t j = segments.cell_start[idx]; j < segments.cell_start[idx + 1];
|
|
++j) {
|
|
const uint32_t s = segments.cell_items[j];
|
|
const double ax = segments.seg[s * 4], ay = segments.seg[s * 4 + 1];
|
|
const double ex = segments.seg[s * 4 + 2] - ax;
|
|
const double ey = segments.seg[s * 4 + 3] - ay;
|
|
const double den = ex * dy - ey * dx;
|
|
if (std::fabs(den) < 1e-12) continue; // song song
|
|
const double wx = ax - ox, wy = ay - oy;
|
|
const double t = (ex * wy - ey * wx) / den;
|
|
if (t < 0.0 || t > max_range || t >= best) continue;
|
|
const double u = (dx * wy - dy * wx) / den;
|
|
if (u < 0.0 || u > 1.0) continue;
|
|
best = t;
|
|
}
|
|
}
|
|
if (!std::isfinite(best)) return std::numeric_limits<double>::quiet_NaN();
|
|
return best;
|
|
}
|
|
|
|
// Ket qua da tinh chinh, hoac chinh `t_grid` neu khong tinh chinh duoc.
|
|
double Refined(double ox, double oy, double angle, double t_grid,
|
|
double max_range) const {
|
|
const double r = RefineHit(ox, oy, std::cos(angle), std::sin(angle), t_grid,
|
|
max_range);
|
|
return std::isnan(r) ? t_grid : r;
|
|
}
|
|
|
|
// --- Raycast tren occupancy grid -----------------------------------------
|
|
// Thuat toan DDA: di tung o thay vi lay mau theo buoc co dinh. Lay mau theo
|
|
// buoc co dinh se BO SOT tuong mong khi buoc lon hon mot o, va do la loi im
|
|
// lang -- LiDAR nhin xuyen tuong ma khong co dau hieu gi.
|
|
double Raycast(double ox, double oy, double angle, double max_range) const {
|
|
const double res = map.resolution;
|
|
const double inv_res = 1.0 / res;
|
|
|
|
double px = (ox - map.origin.position.x) * inv_res;
|
|
double py = (oy - map.origin.position.y) * inv_res;
|
|
|
|
int cx = static_cast<int>(std::floor(px));
|
|
int cy = static_cast<int>(std::floor(py));
|
|
|
|
const double dx = std::cos(angle);
|
|
const double dy = std::sin(angle);
|
|
|
|
const int step_x = dx > 0 ? 1 : (dx < 0 ? -1 : 0);
|
|
const int step_y = dy > 0 ? 1 : (dy < 0 ? -1 : 0);
|
|
|
|
const double inf = std::numeric_limits<double>::infinity();
|
|
const double t_dx = dx != 0.0 ? std::abs(1.0 / dx) : inf;
|
|
const double t_dy = dy != 0.0 ? std::abs(1.0 / dy) : inf;
|
|
|
|
double t_max_x = dx != 0.0
|
|
? ((dx > 0 ? (cx + 1 - px) : (px - cx)) * t_dx)
|
|
: inf;
|
|
double t_max_y = dy != 0.0
|
|
? ((dy > 0 ? (cy + 1 - py) : (py - cy)) * t_dy)
|
|
: inf;
|
|
|
|
const double max_cells = max_range * inv_res;
|
|
double t = 0.0;
|
|
|
|
while (t < max_cells) {
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return inf; // ra ngoai ban do = khong co phan xa
|
|
}
|
|
const int8_t cell = map.data[static_cast<size_t>(cy) * map.width +
|
|
static_cast<size_t>(cx)];
|
|
// KINH: laser 940 nm gan nhu xuyen qua hoan toan. Tia di tiep.
|
|
// Do la ly do sieu am ton tai -- xem SimConfig::enable_ultrasonic.
|
|
const size_t cidx = static_cast<size_t>(cy) * map.width +
|
|
static_cast<size_t>(cx);
|
|
const bool is_glass = cidx < glass.size() && glass[cidx] != 0;
|
|
if (cell >= 50 && !is_glass) {
|
|
return Refined(ox, oy, angle, t * res, max_range);
|
|
}
|
|
if (t_max_x < t_max_y) {
|
|
t = t_max_x;
|
|
t_max_x += t_dx;
|
|
cx += step_x;
|
|
} else {
|
|
t = t_max_y;
|
|
t_max_y += t_dy;
|
|
cy += step_y;
|
|
}
|
|
}
|
|
return inf;
|
|
}
|
|
|
|
// Do cao san NOI SUY SONG TUYEN giua tam cac o (chi dia hinh 3D).
|
|
//
|
|
// Gia tri tung o la bac thang 5 cm: o doc 30 do moi o nhay 2.9 cm, va
|
|
// robot / tia doc san se thay rang cua thay vi mat doc. Ngoai ban do kep vao
|
|
// o bien -- robot khong ra duoc ngoai (va cham), con tia ra ngoai thi raycast
|
|
// da dung tu truoc.
|
|
double FloorAtSmooth(double wx, double wy) const {
|
|
if (floor_z.empty() || !std::isfinite(wx) || !std::isfinite(wy)) return 0.0;
|
|
const int W = static_cast<int>(map.width), H = static_cast<int>(map.height);
|
|
const double fx = std::min(
|
|
std::max((wx - map.origin.position.x) / map.resolution - 0.5, 0.0), W - 1.0);
|
|
const double fy = std::min(
|
|
std::max((wy - map.origin.position.y) / map.resolution - 0.5, 0.0), H - 1.0);
|
|
const int x0 = static_cast<int>(fx), y0 = static_cast<int>(fy);
|
|
const int x1 = std::min(x0 + 1, W - 1), y1 = std::min(y0 + 1, H - 1);
|
|
const double tx = fx - x0, ty = fy - y0;
|
|
auto at = [&](int cx, int cy) {
|
|
return static_cast<double>(
|
|
floor_z[static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx)]);
|
|
};
|
|
const double a = at(x0, y0) * (1.0 - tx) + at(x1, y0) * tx;
|
|
const double b = at(x0, y1) * (1.0 - tx) + at(x1, y1) * tx;
|
|
return a * (1.0 - ty) + b * ty;
|
|
}
|
|
|
|
// O nao sat mep bac -- chenh san voi mot o ke > max_step. Danh dau CA HAI
|
|
// phia mep, va CellBlocked() coi chung nhu tuong: robot khong leo duoc
|
|
// len bac, cung khong roi khoi mep san cao.
|
|
void RebuildStepMask() {
|
|
const uint32_t W = map.width, H = map.height;
|
|
step_block.assign(static_cast<size_t>(W) * H, 0);
|
|
const float lim = static_cast<float>(cfg.max_step);
|
|
size_t n = 0;
|
|
for (uint32_t cy = 0; cy < H; ++cy) {
|
|
for (uint32_t cx = 0; cx < W; ++cx) {
|
|
const size_t i = static_cast<size_t>(cy) * W + cx;
|
|
const float f = floor_z[i];
|
|
const bool step = (cx + 1 < W && std::fabs(floor_z[i + 1] - f) > lim) ||
|
|
(cx > 0 && std::fabs(floor_z[i - 1] - f) > lim) ||
|
|
(cy + 1 < H && std::fabs(floor_z[i + W] - f) > lim) ||
|
|
(cy > 0 && std::fabs(floor_z[i - W] - f) > lim);
|
|
if (step) { step_block[i] = 1; n++; }
|
|
}
|
|
}
|
|
steps_dirty = false;
|
|
VSLAM_DEBUG("sim: mat na bac: " << n << " o chenh > " << cfg.max_step << " m");
|
|
}
|
|
|
|
// z, pitch, roll do DIA HINH tai tu the hien tai, va toc do doi cua chung
|
|
// (cho gyro). Bon diem do: truoc/sau cach nhau `wheelbase_for_slope`,
|
|
// trai/phai cach nhau `wheel_separation`.
|
|
void UpdateTerrainPose(double dt) {
|
|
const double hl = cfg.wheelbase_for_slope / 2.0;
|
|
const double hw = cfg.wheel_separation / 2.0;
|
|
const double c = std::cos(yaw), s = std::sin(yaw);
|
|
const double ff = FloorAtSmooth(x + hl * c, y + hl * s);
|
|
const double fb = FloorAtSmooth(x - hl * c, y - hl * s);
|
|
const double fl = FloorAtSmooth(x - hw * s, y + hw * c);
|
|
const double fr = FloorAtSmooth(x + hw * s, y - hw * c);
|
|
// Doc len phia truoc -> mui ngoc len -> pitch AM (quy uoc cu). Ben TRAI
|
|
// cao hon -> roll DUONG (quay quanh +X dua +Y len).
|
|
const double np = -std::atan2(ff - fb, 2.0 * hl);
|
|
const double nr = std::atan2(fl - fr, 2.0 * hw);
|
|
if (terrain_ready && dt > 0.0) {
|
|
terrain_pitch_rate = (np - terrain_pitch) / dt;
|
|
terrain_roll_rate = (nr - terrain_roll) / dt;
|
|
} else {
|
|
terrain_pitch_rate = 0.0;
|
|
terrain_roll_rate = 0.0;
|
|
terrain_ready = true;
|
|
}
|
|
terrain_pitch = np;
|
|
terrain_roll = nr;
|
|
ground_z = FloorAtSmooth(x, y);
|
|
}
|
|
|
|
// Do cao san tai mot diem the gioi. Ngoai ban do coi nhu phang.
|
|
float FloorAt(double wx, double wy) const {
|
|
const int cx = static_cast<int>(
|
|
std::floor((wx - map.origin.position.x) / map.resolution));
|
|
const int cy = static_cast<int>(
|
|
std::floor((wy - map.origin.position.y) / map.resolution));
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return 0.0f;
|
|
}
|
|
return floor_z[static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx)];
|
|
}
|
|
|
|
// Raycast 2.5D cho MOT diem anh depth.
|
|
//
|
|
// The gioi la: ban do chiem dung DUNG THANH tuong cao `wall_height` tu san,
|
|
// va moi o co do cao san rieng. Tia dung lai khi:
|
|
// - vao mot o bi chiem VA do cao tia nam trong than tuong, hoac
|
|
// - do cao tia tut xuong DUOI mat san tai o do
|
|
//
|
|
// Truong hop thu hai la thu cho phep nhin thay VUC: tia di qua mep bac,
|
|
// roi cham san thap hon o xa hon -- dung khoang cach ma cliff_detect dung
|
|
// de so voi mat phang ky vong.
|
|
// Raycast cho SIEU AM. Khac LiDAR o hai diem, ca hai deu quan trong:
|
|
//
|
|
// 1. THAY KINH. Song am phan xa tot tren kinh; do la ca ly do cam bien
|
|
// nay ton tai tren robot.
|
|
// 2. CHUM RONG (~30 do). HC-SR04 khong do mot TIA ma do mot NON, va tra
|
|
// ve vat GAN NHAT trong non do. Mo phong bang mot tia thi cam bien se
|
|
// "nhin xuyen" qua chan ban, cot -- dung nhung thu no sinh ra de bat.
|
|
//
|
|
// Tra inf khi khong co tieng vong (hop le), NaN thi do nguoi goi quyet dinh.
|
|
UltrasonicReading MakeUltrasonic(UnixTime stamp) {
|
|
UltrasonicReading u;
|
|
u.stamp = stamp;
|
|
double rx, ry, ryaw;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x; ry = y; ryaw = yaw;
|
|
}
|
|
std::normal_distribution<double> noise(0.0, cfg.us_noise_stddev);
|
|
std::uniform_real_distribution<double> uni01(0.0, 1.0);
|
|
|
|
const size_t n = std::min(cfg.us_angles.size(), size_t{8});
|
|
u.count = n;
|
|
for (size_t i = 0; i < n; ++i) {
|
|
if (cfg.us_dropout_rate > 0.0 && uni01(rng) < cfg.us_dropout_rate) {
|
|
// Cam bien khong tra loi -> NaN -> US_TIMEOUT. KHONG phai 0 va
|
|
// KHONG phai inf: "chet" khac han "khong thay gi".
|
|
u.range[i] = std::numeric_limits<double>::quiet_NaN();
|
|
continue;
|
|
}
|
|
const double r = RaycastUltrasonic(rx, ry, ryaw + cfg.us_angles[i]);
|
|
if (!std::isfinite(r)) {
|
|
u.range[i] = std::numeric_limits<double>::infinity();
|
|
} else {
|
|
const double v = r + noise(rng);
|
|
// Duoi tam toi thieu thi cam bien khong do duoc -- do la VUNG MU,
|
|
// khong phai "vat can o 0 m".
|
|
u.range[i] = (v < cfg.us_min_range)
|
|
? std::numeric_limits<double>::infinity()
|
|
: v;
|
|
}
|
|
}
|
|
return u;
|
|
}
|
|
|
|
BumperReading MakeBumper(UnixTime stamp) {
|
|
BumperReading b;
|
|
b.stamp = stamp;
|
|
double rx, ry;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x; ry = y;
|
|
}
|
|
const bool hit = CheckBumper(rx, ry);
|
|
bumper_now = hit;
|
|
// Mot cong tac duy nhat o bit 0. Robot that co the co nhieu hon; mo
|
|
// phong mot cai la du de chay nhanh BUMPER, va khong gia vo biet bo tri
|
|
// that co bao nhieu cai.
|
|
b.mask = hit ? 1u : 0u;
|
|
return b;
|
|
}
|
|
|
|
double RaycastUltrasonic(double ox, double oy, double angle) const {
|
|
double best = std::numeric_limits<double>::infinity();
|
|
// Lay mau chum: tia giua cong vai tia bien. 7 tia la du de khong bo lot
|
|
// mot cot o tam 2 m (2 m * 30 do / 7 ~ 15 cm).
|
|
constexpr int kRays = 7;
|
|
for (int i = 0; i < kRays; ++i) {
|
|
const double f = (kRays == 1) ? 0.0
|
|
: (2.0 * i / (kRays - 1) - 1.0);
|
|
const double a = angle + f * cfg.us_beam_half_angle;
|
|
const double r = RaycastAny(ox, oy, a, cfg.us_max_range);
|
|
if (std::isfinite(r)) best = std::min(best, r);
|
|
}
|
|
return best;
|
|
}
|
|
|
|
// Nhu Raycast() nhung KHONG xuyen kinh -- dung cho sieu am.
|
|
double RaycastAny(double ox, double oy, double angle, double max_range) const {
|
|
const double res = map.resolution;
|
|
const double dx = std::cos(angle), dy = std::sin(angle);
|
|
const double step = res * 0.5;
|
|
const int n = static_cast<int>(max_range / step);
|
|
for (int i = 1; i <= n; ++i) {
|
|
const double t = i * step;
|
|
const int cx = static_cast<int>(
|
|
std::floor((ox + dx * t - map.origin.position.x) / res));
|
|
const int cy = static_cast<int>(
|
|
std::floor((oy + dy * t - map.origin.position.y) / res));
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return std::numeric_limits<double>::infinity();
|
|
}
|
|
// KHONG kiem glass: sieu am thay moi vat can, ke ca kinh.
|
|
if (map.data[static_cast<size_t>(cy) * map.width +
|
|
static_cast<size_t>(cx)] >= 50) {
|
|
// Cung tinh chinh nhu LiDAR. Voi sieu am con quan trong hon theo ti
|
|
// le: nguong `us_stop_distance` chi 0.30 m, nen lech 3 cm la 10 %.
|
|
//
|
|
// Buc KINH do `--sim-glass-at` chen tay vao luoi khong co tam giac
|
|
// nao, nen RefineHit() tra NaN va ta giu ket qua luoi -- dung.
|
|
return Refined(ox, oy, angle, t, max_range);
|
|
}
|
|
}
|
|
return std::numeric_limits<double>::infinity();
|
|
}
|
|
|
|
// Bumper: than robot (ban kinh robot_radius) cham vat can chua.
|
|
//
|
|
// Kiem theo VONG TRON quanh tam, khong phai mot diem: mot robot tron cham
|
|
// tuong bang MEP, va kiem tam se bao cham muon mat dung mot ban kinh.
|
|
bool CheckBumper(double rx, double ry) const {
|
|
// Do o `robot_radius + bumper_reach`, KHONG phai `robot_radius`.
|
|
//
|
|
// Phep va cham cua sim tu choi chuyen dong khi vanh robot cham vat can,
|
|
// nen robot khong bao gio vao duoc vi tri ma mot bumper dat dung
|
|
// `robot_radius` nhin thay -- nhanh BUMPER se khong bao gio chay. Bumper
|
|
// that cung nho ra that: cong tac kich khi CHAM, khong phai khi da lun.
|
|
const double r = cfg.robot_radius + cfg.bumper_reach;
|
|
constexpr int kProbes = 16;
|
|
for (int i = 0; i < kProbes; ++i) {
|
|
const double a = 2.0 * M_PI * i / kProbes;
|
|
const double px = rx + r * std::cos(a);
|
|
const double py = ry + r * std::sin(a);
|
|
const int cx = static_cast<int>(
|
|
std::floor((px - map.origin.position.x) / map.resolution));
|
|
const int cy = static_cast<int>(
|
|
std::floor((py - map.origin.position.y) / map.resolution));
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return true; // ra ngoai ban do = dam vao gi do
|
|
}
|
|
// Kinh VAN lam bumper kich: no la vat can THAT, chi la vat can ma
|
|
// LiDAR khong thay. Do chinh la kich ban nguy hiem dang mo phong.
|
|
if (map.data[static_cast<size_t>(cy) * map.width +
|
|
static_cast<size_t>(cx)] >= 50) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
double RaycastDepth(double ox, double oy, double oz, double dx, double dy,
|
|
double dz, double max_range) const {
|
|
// DDA tren luoi 2D, kiem z tai MOI O thay vi moi buoc co dinh.
|
|
//
|
|
// Ban dau viet buoc co dinh 2.5 cm: 400 buoc moi tia x 76800 tia = 30
|
|
// trieu buoc moi khung. DDA di theo O nen so buoc bang so o cat qua --
|
|
// it hon nhieu lan, va khong bo sot tuong mong nhu buoc co dinh co the.
|
|
const double res = map.resolution;
|
|
const double inv_res = 1.0 / res;
|
|
|
|
double px = (ox - map.origin.position.x) * inv_res;
|
|
double py = (oy - map.origin.position.y) * inv_res;
|
|
int cx = static_cast<int>(std::floor(px));
|
|
int cy = static_cast<int>(std::floor(py));
|
|
|
|
const int step_x = dx > 0 ? 1 : (dx < 0 ? -1 : 0);
|
|
const int step_y = dy > 0 ? 1 : (dy < 0 ? -1 : 0);
|
|
const double inf = std::numeric_limits<double>::infinity();
|
|
const double t_dx = dx != 0.0 ? std::abs(1.0 / dx) : inf;
|
|
const double t_dy = dy != 0.0 ? std::abs(1.0 / dy) : inf;
|
|
|
|
double t_max_x = dx != 0.0 ? ((dx > 0 ? (cx + 1 - px) : (px - cx)) * t_dx) : inf;
|
|
double t_max_y = dy != 0.0 ? ((dy > 0 ? (cy + 1 - py) : (py - cy)) * t_dy) : inf;
|
|
|
|
const double max_cells = max_range * inv_res;
|
|
double t = 0.0; // tinh bang O
|
|
double prev_gap = oz; // khoang cach tu tia toi san, met
|
|
|
|
while (t < max_cells) {
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return inf;
|
|
}
|
|
const size_t idx = static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx);
|
|
const double fz = floor_z[idx];
|
|
|
|
// Do cao tia khi VAO o nay va khi RA khoi o.
|
|
const double t_enter = t;
|
|
const double t_exit = std::min(t_max_x, t_max_y);
|
|
const double z_enter = oz + dz * t_enter * res;
|
|
const double z_exit = oz + dz * t_exit * res;
|
|
|
|
// Cham tuong: o bi chiem va tia con nam trong than tuong.
|
|
//
|
|
// KINH thi tia XUYEN QUA. Do la ca ly do sieu am ton tai: kinh phan xa
|
|
// am rat tot nhung gan nhu trong suot voi laser 940 nm va voi IR cua
|
|
// depth camera. Mot robot dich vu di vao cua kinh la truong hop that,
|
|
// va no la ly do nhanh US_BLOCKED cua FSM ton tai.
|
|
if (map.data[idx] >= 50 && !(idx < glass.size() && glass[idx])) {
|
|
const double lo = fz;
|
|
double hi = fz + cfg.wall_height;
|
|
// Dia hinh 3D: vat can cao dung bang mesh cua no. Tuong 4 m ben doc
|
|
// khong duoc thanh tuong 2 m chi vi san o day bang 0.
|
|
if (terrain_on && idx < wall_top.size() && wall_top[idx] > lo) {
|
|
hi = wall_top[idx];
|
|
}
|
|
if ((z_enter >= lo && z_enter <= hi) || (z_exit >= lo && z_exit <= hi) ||
|
|
(z_enter > hi && z_exit < lo) || (z_enter < lo && z_exit > hi)) {
|
|
// Chi tinh chinh theo mat phang XY: tuong trong dai z la thang dung,
|
|
// nen cat trong mat bang la du. Nhanh cham SAN o duoi da noi suy
|
|
// dung tu truoc, khong can dong toi.
|
|
const double t_xy = std::max(t_enter, 0.0) * res;
|
|
const double r = RefineHit(ox, oy, dx, dy, t_xy, max_range);
|
|
return std::isnan(r) ? t_xy : r;
|
|
}
|
|
}
|
|
|
|
// Cham san: tia tut xuong duoi mat san trong o nay. Noi suy tuyen tinh
|
|
// giua hai dau o de khong luong tu hoa khoang cach theo kich thuoc o.
|
|
//
|
|
// Dia hinh 3D: san tai hai dau o lay NOI SUY, de mat doc la mat phang
|
|
// chu khong phai bac thang. Chi tinh khi tia da xuong gan san -- tia
|
|
// LiDAR cach san 0.22 m bay qua hang tram o, va noi suy o moi o la
|
|
// phi.
|
|
double f_in = fz, f_out = fz;
|
|
if (terrain_on && std::min(z_enter, z_exit) < fz + kSmoothFloorBand) {
|
|
f_in = FloorAtSmooth(ox + dx * t_enter * res, oy + dy * t_enter * res);
|
|
f_out = FloorAtSmooth(ox + dx * t_exit * res, oy + dy * t_exit * res);
|
|
}
|
|
const double gap_enter = z_enter - f_in;
|
|
const double gap_exit = z_exit - f_out;
|
|
if (gap_enter > 0.0 && gap_exit <= 0.0) {
|
|
const double frac = gap_enter / (gap_enter - gap_exit);
|
|
return (t_enter + frac * (t_exit - t_enter)) * res;
|
|
}
|
|
if (gap_enter <= 0.0 && prev_gap > 0.0) {
|
|
return t_enter * res; // tut xuong ngay o bien o (mep bac)
|
|
}
|
|
prev_gap = gap_exit;
|
|
|
|
if (t_max_x < t_max_y) {
|
|
t = t_max_x;
|
|
t_max_x += t_dx;
|
|
cx += step_x;
|
|
} else {
|
|
t = t_max_y;
|
|
t_max_y += t_dy;
|
|
cy += step_y;
|
|
}
|
|
}
|
|
return inf;
|
|
}
|
|
|
|
bool CellBlocked(double wx, double wy) const {
|
|
const int cx = static_cast<int>(
|
|
std::floor((wx - map.origin.position.x) / map.resolution));
|
|
const int cy = static_cast<int>(
|
|
std::floor((wy - map.origin.position.y) / map.resolution));
|
|
if (cx < 0 || cy < 0 || cx >= static_cast<int>(map.width) ||
|
|
cy >= static_cast<int>(map.height)) {
|
|
return true;
|
|
}
|
|
const size_t idx = static_cast<size_t>(cy) * map.width + static_cast<size_t>(cx);
|
|
if (map.data[idx] >= 50) return true;
|
|
// Dia hinh 3D: mep bac / mep san cao cung chan nhu tuong.
|
|
return terrain_on && idx < step_block.size() && step_block[idx] != 0;
|
|
}
|
|
|
|
// Kiem va cham: lay 8 diem tren vanh robot.
|
|
bool Collides(double nx, double ny) const {
|
|
if (!cfg.enable_collision) return false;
|
|
constexpr int kN = 8;
|
|
for (int i = 0; i < kN; ++i) {
|
|
const double a = 2.0 * 3.14159265358979323846 * i / kN;
|
|
if (CellBlocked(nx + cfg.robot_radius * std::cos(a),
|
|
ny + cfg.robot_radius * std::sin(a))) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void StepPhysics(double dt) {
|
|
double cmd_v = 0.0, cmd_w = 0.0;
|
|
base.GetCommand(&cmd_v, &cmd_w, dt);
|
|
|
|
cmd_v = std::max(-cfg.max_linear, std::min(cfg.max_linear, cmd_v));
|
|
cmd_w = std::max(-cfg.max_angular, std::min(cfg.max_angular, cmd_w));
|
|
|
|
// Gioi han gia toc: khong co dong co nao nhay tuc thoi tu 0 len 0.35 m/s,
|
|
// va chinh doan tang toc la luc banh truot.
|
|
const double dv_max = cfg.accel_limit * dt;
|
|
v += std::max(-dv_max, std::min(dv_max, cmd_v - v));
|
|
w += std::max(-dv_max * 3.0, std::min(dv_max * 3.0, cmd_w - w));
|
|
|
|
const double accel = dt > 0.0 ? (v - prev_v) / dt : 0.0;
|
|
prev_v = v;
|
|
|
|
// Tich phan pose THAT.
|
|
double nx, ny, nyaw;
|
|
if (terrain_on) {
|
|
// Lenh v la toc do BANH, doc mat san: di NGANG v*cos(pitch). Than quay
|
|
// quanh truc z CUA NO (dang nghieng), nen huong tren mat bang doi
|
|
// w*cos(roll)/cos(pitch) -- bo qua thi sai 15% o doc 30 do.
|
|
const double ct = std::cos(terrain_pitch);
|
|
const double cr = std::cos(terrain_roll);
|
|
nx = x + v * ct * std::cos(yaw) * dt;
|
|
ny = y + v * ct * std::sin(yaw) * dt;
|
|
nyaw = NormalizeAngle(yaw + w * cr / std::max(ct, 0.1) * dt);
|
|
} else {
|
|
nx = x + v * std::cos(yaw) * dt;
|
|
ny = y + v * std::sin(yaw) * dt;
|
|
nyaw = NormalizeAngle(yaw + w * dt);
|
|
}
|
|
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
if (terrain_on && steps_dirty) RebuildStepMask();
|
|
if (Collides(nx, ny)) {
|
|
// Dung tai cho. Robot that se truot va quay, nhung "dung han" la mo
|
|
// hinh trung thuc hon voi mot robot dich vu co bumper cat nguon.
|
|
v = 0.0;
|
|
stats.collisions++;
|
|
} else {
|
|
const double d = std::hypot(nx - x, ny - y);
|
|
stats.distance_travelled += d;
|
|
x = nx;
|
|
y = ny;
|
|
}
|
|
yaw = nyaw;
|
|
|
|
// --- Nghieng than robot ------------------------------------------------
|
|
// Robot that co giam xoc: tang toc lam no NGOC LEN (pitch am theo quy uoc
|
|
// huong xuong duong), quay gap lam no NGHIENG ra ngoai.
|
|
//
|
|
// Mo hinh: he lo xo - giam chan bac hai keo goc ve vi tri can bang ma gia
|
|
// toc dat ra. Bac hai chu khong phai gan truc tiep, vi robot that co quan
|
|
// tinh -- no KHONG bat dau nghieng tuc thoi, va do tre do chinh la thu lam
|
|
// gravity_align kho.
|
|
last_accel = accel;
|
|
const double centrip = v * w;
|
|
|
|
const double pitch_target = -cfg.tilt_pitch_per_accel * accel;
|
|
const double roll_target = cfg.tilt_roll_per_centrip * centrip;
|
|
|
|
const double wn = cfg.tilt_natural_freq;
|
|
const double z = cfg.tilt_damping;
|
|
|
|
pitch_rate += (wn * wn * (pitch_target - pitch) - 2.0 * z * wn * pitch_rate) * dt;
|
|
pitch += pitch_rate * dt;
|
|
roll_rate += (wn * wn * (roll_target - roll) - 2.0 * z * wn * roll_rate) * dt;
|
|
roll += roll_rate * dt;
|
|
|
|
// Nghieng do DIA HINH: do chenh lech do cao san giua truoc va sau robot.
|
|
if (terrain_on) {
|
|
// Ca z, pitch va roll, voi toc do doi cho gyro.
|
|
UpdateTerrainPose(dt);
|
|
} else if (cfg.follow_terrain_slope) {
|
|
const double half = cfg.wheelbase_for_slope / 2.0;
|
|
const double fz = FloorAt(x + half * std::cos(yaw), y + half * std::sin(yaw));
|
|
const double bz = FloorAt(x - half * std::cos(yaw), y - half * std::sin(yaw));
|
|
// Doc len phia truoc -> mui ngoc len -> pitch AM (quy uoc huong xuong
|
|
// duong, giong ban ROS).
|
|
terrain_pitch = -std::atan2(fz - bz, cfg.wheelbase_for_slope);
|
|
} else {
|
|
terrain_pitch = 0.0;
|
|
}
|
|
|
|
// Encoder: goc banh xe tich luy.
|
|
//
|
|
// TRUOT BANH mo phong bang cach cho ENCODER quay NHIEU HON quang duong
|
|
// that khi tang toc. Do dung chieu cua hien tuong: banh quay, xe khong di,
|
|
// nen odometry bao di XA HON thuc te -- dung nhu bai L6 cua repo cu, noi
|
|
// odometry noi 2.05 m con thuc te 1.74 m.
|
|
const bool accelerating = std::abs(accel) > cfg.slip_accel_threshold;
|
|
|
|
// Doi xung: ca hai banh truot bang nhau. Gyro KHONG thay gi.
|
|
double sym = 0.0;
|
|
if (cfg.slip_factor > 0.0 && accelerating) {
|
|
sym = cfg.slip_factor * std::abs(accel);
|
|
}
|
|
// Vi sai: banh trai truot nhieu hon banh phai. Sinh phep quay GIA ma gyro
|
|
// khong thay -- day chinh la thu slip_metric duoc thiet ke de bat.
|
|
double diff = 0.0;
|
|
if (cfg.slip_differential > 0.0 && accelerating) {
|
|
diff = cfg.slip_differential * std::abs(accel);
|
|
}
|
|
|
|
const double v_wheel = v * (1.0 + sym);
|
|
const double vl = (v_wheel - w * cfg.wheel_separation / 2.0) * (1.0 + diff);
|
|
const double vr = (v_wheel + w * cfg.wheel_separation / 2.0) * (1.0 - diff);
|
|
left_rad += vl / cfg.wheel_radius * dt;
|
|
right_rad += vr / cfg.wheel_radius * dt;
|
|
}
|
|
|
|
// LiDAR tren dia hinh 3D: MOT mat phang quet gan cung vao than, nghieng
|
|
// theo dia hinh (va theo lo xo neu `lidar_follow_suspension`). Moi tia la
|
|
// tia 3D, cham tuong / vat can / MAT SAN that.
|
|
//
|
|
// Day la thu cho thay loi cua SLAM 2D tren doc: dung o san phang nhin vao
|
|
// chan doc goc t, tia ngang cham mat doc o 0.2165 / tan(t) -- mot "tuong"
|
|
// khong co that, va no lui dan khi robot tien len.
|
|
void FillScan3D(LaserScan* s) {
|
|
double rx, ry, rz, ryaw, rroll, rpitch;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x; ry = y; rz = ground_z; ryaw = yaw;
|
|
rroll = terrain_roll;
|
|
rpitch = terrain_pitch;
|
|
if (cfg.lidar_follow_suspension) { rroll += roll; rpitch += pitch; }
|
|
}
|
|
const Rot3 R = Rot3::FromRPY(rroll, rpitch, ryaw);
|
|
// Goc tia: base_footprint (tren san) + R * (lidar_x, 0, r_banh + lidar_z).
|
|
// `lidar_z` do tu TAM TRUC banh, nhu laser_link trong robot.yaml.
|
|
double ox, oy, oz;
|
|
R.Apply(cfg.lidar_x, 0.0, cfg.wheel_radius + cfg.lidar_z, &ox, &oy, &oz);
|
|
ox += rx; oy += ry; oz += rz;
|
|
|
|
std::normal_distribution<double> noise(0.0, cfg.lidar_noise_stddev);
|
|
for (uint32_t i = 0; i < cfg.lidar_samples; ++i) {
|
|
const double a = s->angle_min + i * s->angle_increment;
|
|
double dx, dy, dz;
|
|
R.Apply(std::cos(a), std::sin(a), 0.0, &dx, &dy, &dz);
|
|
const double r = RaycastDepth(ox, oy, oz, dx, dy, dz, cfg.lidar_range_max);
|
|
if (std::isinf(r)) {
|
|
s->ranges[i] = std::numeric_limits<float>::infinity();
|
|
} else {
|
|
const double rn = r + noise(rng);
|
|
s->ranges[i] = static_cast<float>(
|
|
rn < cfg.lidar_range_min ? cfg.lidar_range_min : rn);
|
|
}
|
|
}
|
|
}
|
|
|
|
LaserScanPtr MakeScan(UnixTime stamp) {
|
|
auto s = std::make_shared<LaserScan>();
|
|
s->header.stamp = stamp;
|
|
s->header.frame_id = kLaserFrame;
|
|
s->angle_min = static_cast<float>(-cfg.lidar_fov_rad / 2.0);
|
|
s->angle_max = static_cast<float>(cfg.lidar_fov_rad / 2.0);
|
|
s->angle_increment =
|
|
static_cast<float>(cfg.lidar_fov_rad / (cfg.lidar_samples - 1));
|
|
s->scan_time = static_cast<float>(1.0 / cfg.lidar_rate_hz);
|
|
s->time_increment = s->scan_time / static_cast<float>(cfg.lidar_samples);
|
|
s->range_min = static_cast<float>(cfg.lidar_range_min);
|
|
s->range_max = static_cast<float>(cfg.lidar_range_max);
|
|
s->ranges.resize(cfg.lidar_samples);
|
|
|
|
if (terrain_on) {
|
|
FillScan3D(s.get());
|
|
return s;
|
|
}
|
|
|
|
double rx, ry, ryaw;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x;
|
|
ry = y;
|
|
ryaw = yaw;
|
|
}
|
|
// LiDAR khong o tam robot: laser_joint dat no o x = 0.24.
|
|
const double lx = rx + cfg.lidar_x * std::cos(ryaw);
|
|
const double ly = ry + cfg.lidar_x * std::sin(ryaw);
|
|
|
|
std::normal_distribution<double> noise(0.0, cfg.lidar_noise_stddev);
|
|
for (uint32_t i = 0; i < cfg.lidar_samples; ++i) {
|
|
const double a = ryaw + s->angle_min + i * s->angle_increment;
|
|
const double r = Raycast(lx, ly, a, cfg.lidar_range_max);
|
|
if (std::isinf(r)) {
|
|
// Khong co phan xa -- KHAC voi "khong do duoc". ScanSanitizer va
|
|
// safety_monitor dua vao dung su khac biet nay.
|
|
s->ranges[i] = std::numeric_limits<float>::infinity();
|
|
} else {
|
|
const double rn = r + noise(rng);
|
|
s->ranges[i] = static_cast<float>(
|
|
rn < cfg.lidar_range_min ? cfg.lidar_range_min : rn);
|
|
}
|
|
}
|
|
return s;
|
|
}
|
|
|
|
// Dung khung depth. Quy uoc frame quang hoc: +Z TRUOC, +X PHAI, +Y XUONG.
|
|
void MakeDepthFrame(UnixTime stamp, CameraFrame* out) {
|
|
const uint32_t dec = std::max<uint32_t>(1, cfg.depth_decimate);
|
|
const uint32_t w = cfg.depth_width / dec;
|
|
const uint32_t h = cfg.depth_height / dec;
|
|
|
|
// 16UC1. Vong lap ben duoi ghi MOI diem anh, nen khong can xoa truoc.
|
|
auto buf = depth_pool->Acquire();
|
|
buf->resize(static_cast<size_t>(w) * h * 2);
|
|
std::vector<uint8_t>& depth_buf = *buf;
|
|
|
|
double rx, ry, rz, ryaw;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x;
|
|
ry = y;
|
|
rz = ground_z;
|
|
ryaw = yaw;
|
|
}
|
|
|
|
// Vi tri camera trong the gioi. Dia hinh 3D tinh lai ben duoi, theo tu the
|
|
// 6-DoF cua than.
|
|
double cx_w = rx + cfg.camera_x * std::cos(ryaw);
|
|
double cy_w = ry + cfg.camera_x * std::sin(ryaw);
|
|
double cz_w = cfg.camera_z;
|
|
|
|
// Noi suy tu HFOV. Anh da decimate nen fx/fy tinh theo kich thuoc DA
|
|
// giam; binning trong CameraInfo bao cho consumer biet dieu do.
|
|
const double fx = (cfg.depth_width / 2.0) /
|
|
std::tan(cfg.depth_hfov_rad / 2.0) / dec;
|
|
const double fy = fx;
|
|
const double ppx = w / 2.0;
|
|
const double ppy = h / 2.0;
|
|
|
|
// Camera gan cung vao than, nen no nghieng THEO than. Day la thu lam
|
|
// `cliff_detect` kho: mat phang san ky vong dich theo tung khung.
|
|
double body_roll, body_pitch;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
body_roll = roll;
|
|
body_pitch = pitch + terrain_pitch;
|
|
if (terrain_on) body_roll += terrain_roll;
|
|
}
|
|
const double total_pitch = cfg.camera_pitch + body_pitch;
|
|
const double cp = std::cos(total_pitch), sp = std::sin(total_pitch);
|
|
const double cr_b = std::cos(body_roll), sr_b = std::sin(body_roll);
|
|
const double cy_r = std::cos(ryaw), sy_r = std::sin(ryaw);
|
|
|
|
// Dia hinh 3D: than xoay du ba goc, camera chuc `camera_pitch` TREN than.
|
|
// (Duong cu cong camera_pitch vao pitch cua than va xoay roll truoc --
|
|
// chi dung khi roll = 0, du cho san phang.)
|
|
const Rot3 R_body = Rot3::FromRPY(body_roll, body_pitch, ryaw);
|
|
const double ccp = std::cos(cfg.camera_pitch), csp = std::sin(cfg.camera_pitch);
|
|
if (terrain_on) {
|
|
R_body.Apply(cfg.camera_x, 0.0, cfg.camera_z, &cx_w, &cy_w, &cz_w);
|
|
cx_w += rx;
|
|
cy_w += ry;
|
|
cz_w += rz;
|
|
}
|
|
|
|
// Huong (don vi) trong THE GIOI cua mot huong trong frame quang hoc.
|
|
// Quang hoc -> than robot: +Z_quang = +X_than, +X_quang = -Y_than,
|
|
// +Y_quang = -Z_than. Roi chuc xuong `camera_pitch`, roi xoay theo than.
|
|
// Raycast CPU va renderer GPU dung CHUNG ham nay, nen tia cua hai duong
|
|
// trung nhau tung pixel.
|
|
auto to_world = [&](double bx0, double by0, double bz0, double* wx, double* wy,
|
|
double* wz) {
|
|
if (terrain_on) {
|
|
// Chuc camera tren than (quanh y than), roi xoay theo than.
|
|
const double mx = bx0 * ccp + bz0 * csp;
|
|
const double mz = -bx0 * csp + bz0 * ccp;
|
|
R_body.Apply(mx, by0, mz, wx, wy, wz);
|
|
} else {
|
|
// Nghieng ngang cua than (roll) truoc, roi chuc xuong (pitch).
|
|
const double by1 = by0 * cr_b - bz0 * sr_b;
|
|
const double bz1 = by0 * sr_b + bz0 * cr_b;
|
|
const double px = bx0 * cp + bz1 * sp;
|
|
*wz = -bx0 * sp + bz1 * cp;
|
|
const double py = by1;
|
|
|
|
*wx = px * cy_r - py * sy_r;
|
|
*wy = px * sy_r + py * cy_r;
|
|
}
|
|
};
|
|
|
|
// Renderer GPU: ve CA khung mot lan (depth + IR), vong lap ben duoi chi
|
|
// ap nhieu. Ve hong thi khung nay quay ve raycast CPU.
|
|
bool use_gl = false;
|
|
if (renderer) {
|
|
SimCameraView view;
|
|
// Cot j cua R_wc = truc j cua frame quang hoc trong world.
|
|
double ax[3][3];
|
|
to_world(0.0, -1.0, 0.0, &ax[0][0], &ax[0][1], &ax[0][2]); // +X quang
|
|
to_world(0.0, 0.0, -1.0, &ax[1][0], &ax[1][1], &ax[1][2]); // +Y quang
|
|
to_world(1.0, 0.0, 0.0, &ax[2][0], &ax[2][1], &ax[2][2]); // +Z quang
|
|
for (int i = 0; i < 3; ++i) {
|
|
for (int j = 0; j < 3; ++j) view.R_wc[i * 3 + j] = ax[j][i];
|
|
}
|
|
view.t_wc[0] = cx_w;
|
|
view.t_wc[1] = cy_w;
|
|
view.t_wc[2] = cz_w;
|
|
view.fx = fx;
|
|
view.fy = fy;
|
|
view.cx = ppx;
|
|
view.cy = ppy;
|
|
view.width = static_cast<int>(w);
|
|
view.height = static_cast<int>(h);
|
|
view.far_m = std::max(cfg.depth_far, 1.0) + 1.0;
|
|
use_gl = renderer->Render(view, &gl_ir, &gl_depth);
|
|
if (!use_gl && !gl_fail_logged) {
|
|
gl_fail_logged = true;
|
|
VSLAM_WARN("sim: renderer GPU ve hong -- camera quay ve raycast CPU, KHONG co anh IR");
|
|
}
|
|
}
|
|
|
|
// Khong dung mot `normal_distribution` chung: sigma phu thuoc KHOANG
|
|
// CACH cua tung diem anh, nen phan phoi duoc dung ngay trong vong lap.
|
|
std::uniform_real_distribution<double> uni01(0.0, 1.0);
|
|
|
|
for (uint32_t v = 0; v < h; ++v) {
|
|
for (uint32_t u = 0; u < w; ++u) {
|
|
// Tia trong frame quang hoc.
|
|
const double ox = (u - ppx) / fx;
|
|
const double oy = (v - ppy) / fy;
|
|
const double oz = 1.0;
|
|
const double inv = 1.0 / std::sqrt(ox * ox + oy * oy + oz * oz);
|
|
|
|
double d;
|
|
if (use_gl) {
|
|
// GPU tra thang Z-DEPTH; 0 = khong trung gi.
|
|
const float zg = gl_depth[static_cast<size_t>(v) * w + u];
|
|
d = zg > 0.0f ? static_cast<double>(zg) : std::numeric_limits<double>::infinity();
|
|
} else {
|
|
double wx, wy, pz;
|
|
to_world(oz * inv, -ox * inv, -oy * inv, &wx, &wy, &pz);
|
|
d = RaycastDepth(cx_w, cy_w, cz_w, wx, wy, pz, cfg.depth_far);
|
|
}
|
|
uint16_t mm = 0; // 0 = khong do duoc, dung quy uoc cua RealSense
|
|
|
|
// Depth dropout: D410 that mat diem o be mat toi, be mat bong, va o
|
|
// mep vat the. Mo phong bang xac suat deu -- tho hon thuc te nhung du
|
|
// de buoc `depth_filter` va `cliff_detect` chiu duoc lo hong.
|
|
if (cfg.depth_dropout_rate > 0.0 && uni01(rng) < cfg.depth_dropout_rate) {
|
|
d = std::numeric_limits<double>::infinity();
|
|
}
|
|
|
|
if (std::isfinite(d)) {
|
|
// RaycastDepth tra CU LY EUCLID doc theo tia. Anh depth thi theo
|
|
// quy uoc Z-DEPTH: gia tri diem anh la hinh chieu len TRUC QUANG,
|
|
// khong phai do dai tia. Ca RealSense lan
|
|
// libgazebo_ros_openni_kinect deu phat Z-depth, va
|
|
// depth_to_cloud/cliff_detect deu doc nhu vay.
|
|
//
|
|
// Tia don vi trong frame quang hoc la (ox,oy,1)*inv, nen thanh phan
|
|
// doc truc quang dung bang `inv`.
|
|
//
|
|
// Bo qua phep nhan nay lam moi tia LECH TRUC bi thoi phong theo
|
|
// 1/cos: o day anh he so len toi ~1.15. Hau qua do duoc: mat san
|
|
// dung ra phang o z=0 bi cliff_detect khop thanh z0 = -0.254 m,
|
|
// doc +0.114 -- va 87/1903 tia trong cua so roi duoi nguong, tuc
|
|
// BAO VUC GIA tren san hoan toan phang, MAD 0.037 van lot cong.
|
|
//
|
|
// GPU da tra Z-depth roi -- nhan them la sai lan nua.
|
|
if (!use_gl) d *= inv;
|
|
|
|
// Nhieu depth theo MO HINH STEREO, khong phai hang so.
|
|
//
|
|
// D410 khong DO khoang cach -- no do do lech pixel giua hai mat IR
|
|
// roi suy ra d = f*B / disparity.
|
|
// Sai so khop pixel gan nhu CO DINH (~0.1 px), nhung `d` ti le
|
|
// NGHICH voi disparity, nen khi lan sai so:
|
|
// sigma_d = d^2 * sigma_disp / (f * B)
|
|
// Sai so tang theo BINH PHUONG khoang cach: vat xa gap doi thi sai
|
|
// so gap BON.
|
|
//
|
|
// ⚠️ Truoc day cho nay dung mot HANG SO 7 mm. Sai o DANG, khong chi
|
|
// o tri -- gan thi bi quan, xa thi lac quan. Do duoc voi f = 466 px,
|
|
// B = 50 mm:
|
|
// 1.0 m -> that ~4 mm (hang so cu 7 mm: bi quan)
|
|
// 2.5 m -> that ~27 mm (hang so cu 7 mm: LAC QUAN 3.8 lan)
|
|
// 4.0 m -> that ~69 mm (hang so cu 7 mm: LAC QUAN 9.8 lan)
|
|
//
|
|
// 2.5 m la MEP XA cua cua so cliff_detect, nen sai so o do quyet
|
|
// dinh truc tiep nguong co chiu duoc tren phan cung that khong. Mot
|
|
// bo mo phong DE HON thuc te la loai te nhat: no cho qua nhung
|
|
// nguong se hong ngoai hien truong.
|
|
// ⚠️ Dung `fx` o DO PHAN GIAI GOC, khong phai `fx` da chia cho
|
|
// `dec`.
|
|
//
|
|
// Khop stereo xay ra o do phan giai DAY DU cua cam bien; decimate
|
|
// (tuong duong `image_proc/crop_decimate` cua ban ROS) chi LAY MAU
|
|
// THUA mot anh depth da tinh xong, no khong lam tung diem anh kem
|
|
// chinh xac di.
|
|
//
|
|
// Dung `fx` da decimate se thoi phong nhieu dung bang `dec` lan --
|
|
// do duoc: sigma gap 2.0 lan ky vong o MOI cu ly voi dec = 2.
|
|
const double fx_full = fx * dec;
|
|
const double sigma_disp =
|
|
d * d * cfg.depth_disparity_noise_px / (fx_full * cfg.depth_baseline);
|
|
const double sigma = std::sqrt(cfg.depth_noise_floor * cfg.depth_noise_floor +
|
|
sigma_disp * sigma_disp);
|
|
d += std::normal_distribution<double>(0.0, sigma)(rng);
|
|
|
|
// Duoi Min-Z thi camera KHONG THAY GI -- do la vung mu ma bumper
|
|
// phai bit, khong phai vat can o khoang cach do. Min-Z cua D410 la
|
|
// dac ta theo Z-depth, nen phai kep SAU khi doi.
|
|
if (d >= cfg.depth_near && d <= cfg.depth_far) {
|
|
mm = static_cast<uint16_t>(d * 1000.0);
|
|
}
|
|
}
|
|
const size_t idx = (static_cast<size_t>(v) * w + u) * 2;
|
|
depth_buf[idx] = static_cast<uint8_t>(mm & 0xFF);
|
|
depth_buf[idx + 1] = static_cast<uint8_t>((mm >> 8) & 0xFF);
|
|
}
|
|
}
|
|
|
|
auto img = std::make_shared<Image>();
|
|
img->header.stamp = stamp;
|
|
img->header.frame_id = kCameraDepthOpticalFrame;
|
|
img->width = w;
|
|
img->height = h;
|
|
img->step = w * 2;
|
|
img->format = PixelFormat::kMono16;
|
|
img->depth_scale = 0.001f;
|
|
img->data = depth_buf.data();
|
|
img->keep_alive = buf;
|
|
if (use_gl) {
|
|
// Anh IR cung kich thuoc, cung K va cung stamp voi depth -- giong
|
|
// RealSense: hai anh IR va depth thang hang tung pixel.
|
|
auto ibuf = depth_pool->Acquire();
|
|
ibuf->assign(gl_ir.begin(), gl_ir.end());
|
|
auto ir = std::make_shared<Image>();
|
|
ir->header = img->header;
|
|
ir->width = w;
|
|
ir->height = h;
|
|
ir->step = w;
|
|
ir->format = PixelFormat::kMono8;
|
|
ir->data = ibuf->data();
|
|
ir->keep_alive = ibuf;
|
|
out->infra1 = ir;
|
|
}
|
|
|
|
out->header = img->header;
|
|
out->depth = img;
|
|
|
|
CameraInfo info;
|
|
info.header = img->header;
|
|
info.width = w;
|
|
info.height = h;
|
|
// K giu gia tri cua anh GOC; binning bao cho consumer tu bu. Dung nhu
|
|
// image_proc/crop_decimate lam, va dung nhu image_geometry mong doi.
|
|
info.k[0] = fx * dec;
|
|
info.k[2] = ppx * dec;
|
|
info.k[4] = fy * dec;
|
|
info.k[5] = ppy * dec;
|
|
info.k[8] = 1.0;
|
|
info.binning_x = dec;
|
|
info.binning_y = dec;
|
|
out->depth_info = info;
|
|
}
|
|
|
|
ImuPtr MakeImu(UnixTime stamp) {
|
|
auto m = std::make_shared<Imu>();
|
|
m->header.stamp = stamp;
|
|
m->header.frame_id = kImuFrame;
|
|
|
|
std::normal_distribution<double> gn(0.0, cfg.gyro_noise_stddev);
|
|
std::normal_distribution<double> an(0.0, cfg.accel_noise_stddev);
|
|
|
|
double cur_w, cur_v, cur_roll, cur_pitch, cur_rr, cur_pr, cur_accel;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
cur_w = w;
|
|
cur_v = v;
|
|
cur_roll = roll;
|
|
cur_pitch = pitch + terrain_pitch;
|
|
cur_rr = roll_rate;
|
|
cur_pr = pitch_rate;
|
|
cur_accel = last_accel;
|
|
if (terrain_on) {
|
|
// Than nghieng theo dia hinh thi gyro PHAI thay luc no nghieng --
|
|
// khong thi gia toc ke bao "dang tren doc" con gyro bao "chua he xoay",
|
|
// va moi bo loc (gravity_align, VIO) bi hai cam bien cai nhau.
|
|
cur_roll += terrain_roll;
|
|
cur_rr += terrain_roll_rate;
|
|
cur_pr += terrain_pitch_rate;
|
|
}
|
|
}
|
|
|
|
// Con quay do van toc goc THAT tren ca ba truc.
|
|
m->angular_velocity.x = cur_rr + gn(rng);
|
|
m->angular_velocity.y = cur_pr + gn(rng);
|
|
m->angular_velocity.z = cur_w + gn(rng);
|
|
|
|
// ================== GIA TOC KE ==================
|
|
// Day la cho quan trong nhat cua toan bo bo mo phong doi voi
|
|
// `gravity_align`: gia toc ke KHONG phan biet duoc nghieng voi tang toc.
|
|
// No do TONG cua hai thu:
|
|
// 1. trong luc chieu xuong ba truc cua than (phu thuoc roll/pitch)
|
|
// 2. gia toc rieng cua robot (tinh tien + huong tam)
|
|
//
|
|
// `gravity_align` phai TU tach hai thanh phan do ra bang cach tru gia toc
|
|
// rieng (`axc = ax - a_lin`). Neu mo phong chi tra trong luc thuan thi
|
|
// phep tru do khong bao gio bi kiem tra.
|
|
const double cr = std::cos(cur_roll), sr = std::sin(cur_roll);
|
|
const double cp = std::cos(cur_pitch), sp = std::sin(cur_pitch);
|
|
|
|
// Trong luc trong he than robot (pitch duong = mui chuc xuong).
|
|
const double gx = -kGravity * sp;
|
|
const double gy = kGravity * sr * cp;
|
|
const double gz = kGravity * cr * cp;
|
|
|
|
m->linear_acceleration.x = gx + cur_accel + an(rng);
|
|
m->linear_acceleration.y = gy + cur_v * cur_w + an(rng);
|
|
m->linear_acceleration.z = gz + an(rng);
|
|
|
|
m->orientation_covariance[0] = -1.0; // khong co orientation
|
|
m->angular_velocity_covariance[0] = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev;
|
|
m->angular_velocity_covariance[4] = m->angular_velocity_covariance[0];
|
|
m->angular_velocity_covariance[8] = m->angular_velocity_covariance[0];
|
|
m->linear_acceleration_covariance[0] =
|
|
cfg.accel_noise_stddev * cfg.accel_noise_stddev;
|
|
m->linear_acceleration_covariance[4] = m->linear_acceleration_covariance[0];
|
|
m->linear_acceleration_covariance[8] = m->linear_acceleration_covariance[0];
|
|
return m;
|
|
}
|
|
|
|
// IMU tinh TU quy dao that (SimConfig::ImuModel::kKinematic). Goi sau
|
|
// StepPhysics, MOI buoc vat ly -- lich su vi tri can deu buoc.
|
|
//
|
|
// gyro = Log(R_truoc^T R) / dt (van toc goc trong he THAN)
|
|
// accel = R^T (a + (0, 0, g)), a = sai phan lui bac hai vi tri diem dat IMU
|
|
//
|
|
// Tich phan nguoc (xoay gia toc ve the gioi bang tu the that, tru trong
|
|
// luc, tich phan hai lan) ra DUNG quy dao, sai so chi o muc lam tron. Mo
|
|
// hinh cu chi xap xi: thieu gia toc theo phuong dung khi len doc, thieu
|
|
// canh tay don cua diem dat IMU khi than nghieng.
|
|
// Tu the THAT va vi tri diem dat IMU o trang thai hien tai:
|
|
// base_footprint + R * (imu_x, imu_y, r_banh + imu_z).
|
|
void ImuTruth(Rot3* R, double p[3]) {
|
|
double rx, ry, rz, ryaw, rroll, rpitch;
|
|
{
|
|
std::lock_guard<std::mutex> lk(state_mu);
|
|
rx = x; ry = y; ryaw = yaw;
|
|
rz = terrain_on ? ground_z : 0.0;
|
|
rroll = roll + (terrain_on ? terrain_roll : 0.0);
|
|
rpitch = pitch + terrain_pitch;
|
|
}
|
|
*R = Rot3::FromRPY(rroll, rpitch, ryaw);
|
|
R->Apply(cfg.imu_x, cfg.imu_y, cfg.wheel_radius + cfg.imu_z, &p[0], &p[1], &p[2]);
|
|
p[0] += rx; p[1] += ry; p[2] += rz;
|
|
}
|
|
|
|
// Gieo lich su IMU tai tu the hien tai, robot coi nhu dang dung yen. Goi
|
|
// o Open(): mau dau tien phai mang CA chuyen dong cua buoc vat ly dau tien,
|
|
// khong thi tich phan IMU lech su that ngay tu dau.
|
|
void SeedImuHistory() {
|
|
double p[3];
|
|
ImuTruth(&imu_R_prev, p);
|
|
for (int i = 0; i < 3; ++i) {
|
|
for (int j = 0; j < 3; ++j) imu_p[i][j] = p[j];
|
|
}
|
|
imu_hist = 1;
|
|
}
|
|
|
|
ImuPtr MakeImuKinematic(UnixTime stamp, double dt) {
|
|
Rot3 R;
|
|
double pnow[3];
|
|
ImuTruth(&R, pnow);
|
|
if (imu_hist == 0) SeedImuHistory();
|
|
for (int i = 0; i < 2; ++i) {
|
|
for (int j = 0; j < 3; ++j) imu_p[i][j] = imu_p[i + 1][j];
|
|
}
|
|
for (int j = 0; j < 3; ++j) imu_p[2][j] = pnow[j];
|
|
imu_hist = std::min(imu_hist + 1, 3);
|
|
|
|
double w[3] = {0.0, 0.0, 0.0};
|
|
if (dt > 0.0) {
|
|
// Rr = R_truoc^T * R, roi Log() ve vector quay.
|
|
double Rr[9];
|
|
for (int i = 0; i < 3; ++i) {
|
|
for (int j = 0; j < 3; ++j) {
|
|
Rr[i * 3 + j] = imu_R_prev.m[0 * 3 + i] * R.m[0 * 3 + j] +
|
|
imu_R_prev.m[1 * 3 + i] * R.m[1 * 3 + j] +
|
|
imu_R_prev.m[2 * 3 + i] * R.m[2 * 3 + j];
|
|
}
|
|
}
|
|
const double c = std::max(-1.0, std::min(1.0, (Rr[0] + Rr[4] + Rr[8] - 1.0) / 2.0));
|
|
const double th = std::acos(c);
|
|
const double k = th < 1e-9 ? 0.5 : th / (2.0 * std::sin(th));
|
|
w[0] = k * (Rr[7] - Rr[5]) / dt;
|
|
w[1] = k * (Rr[2] - Rr[6]) / dt;
|
|
w[2] = k * (Rr[3] - Rr[1]) / dt;
|
|
}
|
|
imu_R_prev = R;
|
|
|
|
double a[3] = {0.0, 0.0, 0.0};
|
|
if (dt > 0.0) {
|
|
for (int j = 0; j < 3; ++j) {
|
|
a[j] = (imu_p[2][j] - 2.0 * imu_p[1][j] + imu_p[0][j]) / (dt * dt);
|
|
}
|
|
}
|
|
const double aw[3] = {a[0], a[1], a[2] + kGravity};
|
|
double f[3];
|
|
for (int i = 0; i < 3; ++i) {
|
|
f[i] = R.m[0 * 3 + i] * aw[0] + R.m[1 * 3 + i] * aw[1] + R.m[2 * 3 + i] * aw[2];
|
|
}
|
|
|
|
// Bias troi + nhieu trang.
|
|
std::normal_distribution<double> n01(0.0, 1.0);
|
|
const double sq = std::sqrt(std::max(dt, 0.0));
|
|
for (int i = 0; i < 3; ++i) {
|
|
if (cfg.gyro_bias_rw > 0.0) imu_bg[i] += cfg.gyro_bias_rw * sq * n01(imu_rng);
|
|
if (cfg.accel_bias_rw > 0.0) imu_ba[i] += cfg.accel_bias_rw * sq * n01(imu_rng);
|
|
w[i] += imu_bg[i];
|
|
f[i] += imu_ba[i];
|
|
if (cfg.gyro_noise_stddev > 0.0) w[i] += cfg.gyro_noise_stddev * n01(imu_rng);
|
|
if (cfg.accel_noise_stddev > 0.0) f[i] += cfg.accel_noise_stddev * n01(imu_rng);
|
|
}
|
|
// Loc trong cam bien (WT61PC co loc noi): lam tre va lam mem tin hieu.
|
|
if (cfg.imu_lpf_hz > 0.0 && dt > 0.0) {
|
|
const double al = dt / (dt + 1.0 / (2.0 * M_PI * cfg.imu_lpf_hz));
|
|
if (!imu_lpf_init) {
|
|
for (int i = 0; i < 3; ++i) { imu_lpf_w[i] = w[i]; imu_lpf_f[i] = f[i]; }
|
|
imu_lpf_init = true;
|
|
}
|
|
for (int i = 0; i < 3; ++i) {
|
|
imu_lpf_w[i] += al * (w[i] - imu_lpf_w[i]);
|
|
imu_lpf_f[i] += al * (f[i] - imu_lpf_f[i]);
|
|
w[i] = imu_lpf_w[i];
|
|
f[i] = imu_lpf_f[i];
|
|
}
|
|
}
|
|
|
|
auto m = std::make_shared<Imu>();
|
|
m->header.stamp = stamp;
|
|
m->header.frame_id = kImuFrame;
|
|
m->angular_velocity.x = w[0];
|
|
m->angular_velocity.y = w[1];
|
|
m->angular_velocity.z = w[2];
|
|
m->linear_acceleration.x = f[0];
|
|
m->linear_acceleration.y = f[1];
|
|
m->linear_acceleration.z = f[2];
|
|
m->orientation_covariance[0] = -1.0; // khong co orientation
|
|
const double gv = cfg.gyro_noise_stddev * cfg.gyro_noise_stddev;
|
|
const double av = cfg.accel_noise_stddev * cfg.accel_noise_stddev;
|
|
m->angular_velocity_covariance[0] = gv;
|
|
m->angular_velocity_covariance[4] = gv;
|
|
m->angular_velocity_covariance[8] = gv;
|
|
m->linear_acceleration_covariance[0] = av;
|
|
m->linear_acceleration_covariance[4] = av;
|
|
m->linear_acceleration_covariance[8] = av;
|
|
return m;
|
|
}
|
|
|
|
// Phat mau IMU theo tan so phat va do tre. Tra true neu da phat.
|
|
//
|
|
// Mac dinh (imu_output_hz = 0, imu_delay_sec = 0): phat MOI mau ngay khi do,
|
|
// y het truoc. Co tre: mau phat luc `now` la mau DO tai `now - delay`, mang
|
|
// stamp `now` -- dung cai driver that thay khi dong dau bang gio nhan.
|
|
bool EmitImu(UnixTime now, ImuPtr meas, double dt) {
|
|
if (cfg.imu_output_hz <= 0.0 && cfg.imu_delay_sec <= 0.0) {
|
|
mcu.PushImu(std::move(meas));
|
|
return true;
|
|
}
|
|
const double t = sim_elapsed;
|
|
imu_fifo.emplace_back(t, std::move(meas));
|
|
imu_out_acc += dt;
|
|
const double period = cfg.imu_output_hz > 0.0 ? 1.0 / cfg.imu_output_hz : dt;
|
|
if (imu_out_acc + 1e-9 < period) {
|
|
// Khong de hang doi phinh khi tan so phat thap: giu toi da 2 s.
|
|
while (imu_fifo.size() > 1 && imu_fifo.front().first < t - cfg.imu_delay_sec - 2.0) {
|
|
imu_fifo.pop_front();
|
|
}
|
|
return false;
|
|
}
|
|
imu_out_acc -= period;
|
|
ImuPtr pick;
|
|
const double want = t - cfg.imu_delay_sec;
|
|
while (!imu_fifo.empty() && imu_fifo.front().first <= want + 1e-9) {
|
|
pick = imu_fifo.front().second;
|
|
imu_fifo.pop_front();
|
|
}
|
|
if (!pick) return false; // vua khoi dong, chua du tre
|
|
auto out = std::make_shared<Imu>(*pick);
|
|
out->header.stamp = now;
|
|
mcu.PushImu(std::move(out));
|
|
return true;
|
|
}
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
SimSource::SimSource(SimConfig cfg) : impl_(std::make_unique<Impl>(std::move(cfg))) {}
|
|
SimSource::~SimSource() { RequestStop(); }
|
|
|
|
StatusResponse SimSource::Open() {
|
|
// Gieo lai TRUOC moi thu: hat giong quyet dinh toan bo chuoi nhieu, va
|
|
// chuoi do phai giong nhau giua hai lan ghi cung mot kich ban.
|
|
impl_->rng.seed(impl_->cfg.seed);
|
|
|
|
WorldTerrain terr;
|
|
if (!impl_->cfg.world_path.empty()) {
|
|
const StatusResponse st = LoadGazeboWorld(
|
|
impl_->cfg.world_path, impl_->cfg.world_model_paths, &impl_->world);
|
|
if (!st.ok()) return st;
|
|
WorldRasterOptions wo;
|
|
const StatusResponse rs =
|
|
RasterizeGazeboWorld(impl_->world, wo, &impl_->map, &terr);
|
|
if (!rs.ok()) return rs;
|
|
// Chi muc doan 2D, de khoang cach tra ve trung MAT TUONG chu khong trung
|
|
// bien o. Khong dung duoc thi van chay -- chi la moi tia dung som toi mot
|
|
// o, y nhu truoc day.
|
|
const StatusResponse ss = BuildWorldSegments(
|
|
impl_->world, wo, impl_->map, &impl_->segments,
|
|
terr.terrain_cells > 0 ? &terr.floor_z : nullptr);
|
|
if (!ss.ok()) {
|
|
VSLAM_WARN("sim: khong dung duoc chi muc doan (" << ss.message
|
|
<< ") -- raycast se luong tu hoa theo o "
|
|
<< impl_->map.resolution << " m");
|
|
}
|
|
} else if (impl_->cfg.map_yaml.empty()) {
|
|
impl_->map = MakeSyntheticWorld(impl_->cfg.synthetic_width,
|
|
impl_->cfg.synthetic_height,
|
|
impl_->cfg.synthetic_resolution);
|
|
VSLAM_INFO("sim: dung the gioi tong hop " << impl_->map.width << "x"
|
|
<< impl_->map.height);
|
|
} else {
|
|
MapLoadResult r;
|
|
const StatusResponse st = LoadOccupancyMap(impl_->cfg.map_yaml, &r);
|
|
if (!st.ok()) return st;
|
|
impl_->map = std::move(r.grid);
|
|
}
|
|
|
|
// San phang mac dinh. SetFloorHeight() tao bac hut xuong.
|
|
const size_t n_cells = static_cast<size_t>(impl_->map.width) * impl_->map.height;
|
|
impl_->floor_z.assign(n_cells, 0.0f);
|
|
impl_->glass.assign(n_cells, 0);
|
|
impl_->wall_top.clear();
|
|
impl_->step_block.clear();
|
|
// World co dia hinh (san cao, doc): san lay tu mesh dia hinh.
|
|
if (terr.terrain_cells > 0 && terr.floor_z.size() == n_cells) {
|
|
impl_->floor_z = terr.floor_z;
|
|
}
|
|
if (terr.wall_top.size() == n_cells) impl_->wall_top = terr.wall_top;
|
|
|
|
const SimConfig::TerrainMode tm = impl_->cfg.terrain;
|
|
impl_->terrain_on = tm == SimConfig::TerrainMode::kOn ||
|
|
(tm == SimConfig::TerrainMode::kAuto && terr.terrain_cells > 0);
|
|
if (impl_->terrain_on) {
|
|
VSLAM_INFO("sim: dia hinh 3D BAT -- " << terr.terrain_cells << " o dia hinh, san tu "
|
|
<< terr.floor_min << " den " << terr.floor_max
|
|
<< " m. Robot di tren mat san, LiDAR quet tia 3D, chenh san > "
|
|
<< impl_->cfg.max_step << " m la vat can.");
|
|
}
|
|
|
|
impl_->x = impl_->cfg.start_x;
|
|
impl_->y = impl_->cfg.start_y;
|
|
impl_->yaw = impl_->cfg.start_yaw;
|
|
|
|
if (impl_->terrain_on) {
|
|
impl_->RebuildStepMask();
|
|
impl_->terrain_ready = false;
|
|
impl_->UpdateTerrainPose(0.0);
|
|
}
|
|
|
|
// Mo hinh IMU. RNG rieng, gieo tu seed: cung kich ban => cung chuoi nhieu.
|
|
const SimConfig::ImuModel im = impl_->cfg.imu_model;
|
|
impl_->imu_kinematic = im == SimConfig::ImuModel::kKinematic ||
|
|
(im == SimConfig::ImuModel::kAuto && impl_->terrain_on);
|
|
impl_->imu_rng.seed(impl_->cfg.seed + 101u);
|
|
impl_->imu_hist = 0;
|
|
if (impl_->imu_kinematic) impl_->SeedImuHistory();
|
|
impl_->imu_lpf_init = false;
|
|
impl_->imu_fifo.clear();
|
|
impl_->imu_out_acc = 0.0;
|
|
for (int i = 0; i < 3; ++i) { impl_->imu_bg[i] = 0.0; impl_->imu_ba[i] = 0.0; }
|
|
if (impl_->imu_kinematic) {
|
|
std::normal_distribution<double> n01(0.0, 1.0);
|
|
for (int i = 0; i < 3; ++i) {
|
|
impl_->imu_bg[i] = impl_->cfg.gyro_bias_sigma * n01(impl_->imu_rng);
|
|
impl_->imu_ba[i] = impl_->cfg.accel_bias_sigma * n01(impl_->imu_rng);
|
|
}
|
|
VSLAM_INFO("sim: IMU dong hoc -- tinh tu quy dao 6-DoF that"
|
|
<< (impl_->cfg.imu_output_hz > 0.0
|
|
? ", phat " + std::to_string(impl_->cfg.imu_output_hz) + " Hz"
|
|
: std::string(""))
|
|
<< (impl_->cfg.imu_delay_sec > 0.0
|
|
? ", tre " + std::to_string(impl_->cfg.imu_delay_sec) + " s"
|
|
: std::string("")));
|
|
}
|
|
|
|
if (impl_->Collides(impl_->x, impl_->y)) {
|
|
// Bao NGAY thay vi de robot ket ngay tu khung dau tien va nguoi dung ngoi
|
|
// doan tai sao no khong nhuc nhich.
|
|
return StatusResponse::Error(
|
|
StatusCode::kInvalidArgument,
|
|
"vi tri xuat phat (" + std::to_string(impl_->x) + ", " +
|
|
std::to_string(impl_->y) + ") nam trong tuong hoac ngoai ban do");
|
|
}
|
|
|
|
impl_->base.SetCmdTimeout(impl_->cfg.cmd_timeout_sec);
|
|
impl_->clock = MakeReplayClock(UnixTime::now());
|
|
impl_->clock->SetSpeed(impl_->cfg.speed);
|
|
return StatusResponse::Ok();
|
|
}
|
|
|
|
ClockPtr SimSource::clock() const { return impl_->clock; }
|
|
LidarInterface* SimSource::lidar() { return &impl_->lidar; }
|
|
McuInterface* SimSource::mcu() { return &impl_->mcu; }
|
|
BaseInterface* SimSource::base() { return &impl_->base; }
|
|
const OccupancyGrid& SimSource::map() const { return impl_->map; }
|
|
|
|
CameraInterface* SimSource::camera() {
|
|
return impl_->cfg.enable_depth_camera ? &impl_->camera : nullptr;
|
|
}
|
|
|
|
const std::vector<float>& SimSource::floor_height() const { return impl_->floor_z; }
|
|
const std::vector<uint8_t>& SimSource::glass_mask() const { return impl_->glass; }
|
|
|
|
const GazeboWorld& SimSource::world() const { return impl_->world; }
|
|
|
|
double SimSource::RangeForTest(double x, double y, double angle) const {
|
|
return impl_->Raycast(x, y, angle, impl_->cfg.lidar_range_max);
|
|
}
|
|
|
|
void SimSource::SetMapForTest(const OccupancyGrid& m) {
|
|
impl_->map = m;
|
|
impl_->floor_z.assign(static_cast<size_t>(m.width) * m.height, 0.0f);
|
|
impl_->glass.assign(static_cast<size_t>(m.width) * m.height, 0);
|
|
impl_->wall_top.clear();
|
|
impl_->step_block.clear();
|
|
impl_->steps_dirty = true;
|
|
impl_->terrain_ready = false;
|
|
}
|
|
bool SimSource::true_bumper() const { return impl_->bumper_now; }
|
|
|
|
void SimSource::SetGlass(double x0, double y0, double x1, double y1, bool is_glass) {
|
|
const OccupancyGrid& m = impl_->map;
|
|
const double res = m.resolution;
|
|
auto cell = [&](double w, double o) { return static_cast<int>(std::floor((w - o) / res)); };
|
|
const int cx0 = std::max(0, cell(std::min(x0, x1), m.origin.position.x));
|
|
const int cx1 = std::min(static_cast<int>(m.width) - 1, cell(std::max(x0, x1), m.origin.position.x));
|
|
const int cy0 = std::max(0, cell(std::min(y0, y1), m.origin.position.y));
|
|
const int cy1 = std::min(static_cast<int>(m.height) - 1, cell(std::max(y0, y1), m.origin.position.y));
|
|
|
|
size_t marked = 0, skipped = 0;
|
|
for (int cy = cy0; cy <= cy1; ++cy) {
|
|
for (int cx = cx0; cx <= cx1; ++cx) {
|
|
const size_t idx = static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx);
|
|
// CHI o bi chiem moi thanh kinh duoc. Kinh la VAT CAN that -- chi la
|
|
// vat can ma LiDAR va depth khong thay. Danh dau mot o trong la kinh
|
|
// khong co y nghia gi, va am tham bo qua se de nguoi dung tuong da dat
|
|
// duoc mot buc kinh.
|
|
if (m.data[idx] < 50) { skipped++; continue; }
|
|
impl_->glass[idx] = is_glass ? 1 : 0;
|
|
marked++;
|
|
}
|
|
}
|
|
VSLAM_INFO("sim: danh dau " << marked << " o kinh trong vung (" << x0 << ", "
|
|
<< y0 << ") - (" << x1 << ", " << y1 << ")"
|
|
<< (skipped > 0 ? "; bo qua " + std::to_string(skipped) +
|
|
" o TRONG (kinh phai la o bi chiem)"
|
|
: ""));
|
|
}
|
|
|
|
void SimSource::SetFloorHeight(double x0, double y0, double x1, double y1, float z) {
|
|
const OccupancyGrid& m = impl_->map;
|
|
auto to_cell = [&](double w, double origin) {
|
|
return static_cast<int>(std::floor((w - origin) / m.resolution));
|
|
};
|
|
const int cx0 = std::max(0, to_cell(std::min(x0, x1), m.origin.position.x));
|
|
const int cy0 = std::max(0, to_cell(std::min(y0, y1), m.origin.position.y));
|
|
const int cx1 = std::min<int>(static_cast<int>(m.width) - 1,
|
|
to_cell(std::max(x0, x1), m.origin.position.x));
|
|
const int cy1 = std::min<int>(static_cast<int>(m.height) - 1,
|
|
to_cell(std::max(y0, y1), m.origin.position.y));
|
|
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
for (int cy = cy0; cy <= cy1; ++cy) {
|
|
for (int cx = cx0; cx <= cx1; ++cx) {
|
|
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] = z;
|
|
}
|
|
}
|
|
// Dia hinh 3D: mat na bac tinh lai o buoc vat ly sau, va goc dia hinh lay
|
|
// lai tu dau (khong sinh toc do goc gia).
|
|
impl_->steps_dirty = true;
|
|
impl_->terrain_ready = false;
|
|
VSLAM_INFO("sim: dat do cao san " << z << " m cho vung (" << x0 << ", " << y0
|
|
<< ") - (" << x1 << ", " << y1 << ")");
|
|
}
|
|
|
|
void SimSource::SetFloorRamp(double x0, double y0, double x1, double y1,
|
|
float z_at_x0, float z_at_x1) {
|
|
const OccupancyGrid& m = impl_->map;
|
|
if (x1 == x0) return;
|
|
auto to_cell = [&](double w, double origin) {
|
|
return static_cast<int>(std::floor((w - origin) / m.resolution));
|
|
};
|
|
const int cx0 = std::max(0, to_cell(std::min(x0, x1), m.origin.position.x));
|
|
const int cy0 = std::max(0, to_cell(std::min(y0, y1), m.origin.position.y));
|
|
const int cx1 = std::min<int>(static_cast<int>(m.width) - 1,
|
|
to_cell(std::max(x0, x1), m.origin.position.x));
|
|
const int cy1 = std::min<int>(static_cast<int>(m.height) - 1,
|
|
to_cell(std::max(y0, y1), m.origin.position.y));
|
|
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
for (int cy = cy0; cy <= cy1; ++cy) {
|
|
for (int cx = cx0; cx <= cx1; ++cx) {
|
|
// Do cao tai TAM o, cung quy uoc voi raster dia hinh tu world.
|
|
const double wx = m.origin.position.x + (cx + 0.5) * m.resolution;
|
|
const double t = std::min(1.0, std::max(0.0, (wx - x0) / (x1 - x0)));
|
|
impl_->floor_z[static_cast<size_t>(cy) * m.width + static_cast<size_t>(cx)] =
|
|
static_cast<float>(z_at_x0 + t * (z_at_x1 - z_at_x0));
|
|
}
|
|
}
|
|
impl_->steps_dirty = true;
|
|
impl_->terrain_ready = false;
|
|
VSLAM_INFO("sim: doc tu x = " << x0 << " (" << z_at_x0 << " m) toi x = " << x1
|
|
<< " (" << z_at_x1 << " m)");
|
|
}
|
|
|
|
bool SimSource::terrain_active() const { return impl_->terrain_on; }
|
|
|
|
void SimSource::SetCameraRenderer(std::shared_ptr<SimCameraRenderer> r) {
|
|
impl_->renderer = std::move(r);
|
|
impl_->gl_fail_logged = false;
|
|
}
|
|
|
|
void SimSource::SetGroundTruthCallback(GroundTruthCallback cb, double rate_hz) {
|
|
impl_->gt_cb = std::move(cb);
|
|
impl_->gt_period = rate_hz > 0.0 ? 1.0 / rate_hz : 0.0;
|
|
impl_->gt_acc = 0.0;
|
|
}
|
|
|
|
void SimConfigFromRobot(const RobotModel& robot, SimConfig* c) {
|
|
const RobotGeometry& g = robot.geometry();
|
|
c->wheel_radius = g.wheel_radius;
|
|
c->wheel_separation = g.wheel_separation;
|
|
c->robot_radius = g.robot_radius;
|
|
c->camera_z = robot.camera_height_above_floor();
|
|
c->camera_pitch = robot.camera_pitch();
|
|
Transform t;
|
|
if (robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
|
|
c->lidar_x = t.translation.x;
|
|
// Do cao LiDAR tren TAM TRUC. Duong 2D cu khong dung; dia hinh 3D thi
|
|
// can de tia o dung 0.2165 m tren san.
|
|
c->lidar_z = t.translation.z;
|
|
}
|
|
if (robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
|
|
c->camera_x = t.translation.x;
|
|
}
|
|
if (robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t)) {
|
|
c->imu_x = t.translation.x;
|
|
c->imu_y = t.translation.y;
|
|
c->imu_z = t.translation.z;
|
|
}
|
|
}
|
|
|
|
void SimSource::true_tilt(double* roll_out, double* pitch_out) const {
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
// Tat dia hinh 3D thi KHONG cong (ke ca 0.0): giu dung tung bit nhu cu.
|
|
*roll_out = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
|
|
*pitch_out = impl_->pitch + impl_->terrain_pitch;
|
|
}
|
|
|
|
SimPose3 SimSource::ground_truth_3d() const {
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
SimPose3 p;
|
|
p.x = impl_->x;
|
|
p.y = impl_->y;
|
|
p.yaw = impl_->yaw;
|
|
// Tat dia hinh 3D thi robot luon o z = 0, ke ca khi SetFloorHeight tao vuc:
|
|
// do cao san luc do chi de camera NHIN thay, robot khong di len no.
|
|
p.z = impl_->terrain_on ? impl_->ground_z : 0.0;
|
|
p.roll = impl_->terrain_on ? impl_->roll + impl_->terrain_roll : impl_->roll;
|
|
p.pitch = impl_->pitch + impl_->terrain_pitch;
|
|
return p;
|
|
}
|
|
|
|
Pose2D SimSource::ground_truth() const {
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
return Pose2D{impl_->x, impl_->y, impl_->yaw};
|
|
}
|
|
|
|
void SimSource::RequestStop() { impl_->stop.store(true); }
|
|
|
|
void SimSource::RunFor(double seconds) {
|
|
// Buoc vat ly chay o tan so cao nhat (IMU), cac nguon khac lay mau thua ra.
|
|
const double dt = 1.0 / impl_->cfg.imu_rate_hz;
|
|
|
|
// Bo tich luy thay vi chia nguyen.
|
|
//
|
|
// `tick % (imu_hz / cam_hz)` lam tron xuong: 200/30 = 6 (khong phai 6.67),
|
|
// nen camera chay 33.3 Hz chu khong phai 30. Sai so ngam nay lan sang moi
|
|
// phep do tan so va moi bai kiem nhip.
|
|
// Bo tich luy la TRANG THAI CUA SIM, khong phai bien cuc bo cua ham nay.
|
|
//
|
|
// De cuc bo thi moi lan goi RunFor() lai bat dau tu 0, va goi lien tiep
|
|
// nhieu lat ngan se lam cac nguon lay mau thua IM LANG: voi lat 50 ms va
|
|
// camera 10 Hz (chu ky 100 ms), `cam_acc` khong bao gio toi nguong -> KHONG
|
|
// MOT KHUNG ANH NAO duoc sinh ra, ma khong co gi bao loi.
|
|
//
|
|
// Da mac: `vslam_record` phai goi RunFor theo lat de phat lai lenh cho
|
|
// watchdog cua base, va ban ghi mat sach anh depth.
|
|
double& lidar_acc = impl_->lidar_acc;
|
|
double& enc_acc = impl_->enc_acc;
|
|
double& cam_acc = impl_->cam_acc;
|
|
double& us_acc = impl_->us_acc;
|
|
double& bump_acc = impl_->bump_acc;
|
|
const double lidar_period = 1.0 / impl_->cfg.lidar_rate_hz;
|
|
const double enc_period = 1.0 / impl_->cfg.encoder_rate_hz;
|
|
const double us_period = impl_->cfg.us_rate_hz > 0.0
|
|
? 1.0 / impl_->cfg.us_rate_hz : 1e9;
|
|
const double bump_period = impl_->cfg.bumper_rate_hz > 0.0
|
|
? 1.0 / impl_->cfg.bumper_rate_hz : 1e9;
|
|
const double cam_period = impl_->cfg.camera_rate_hz > 0.0
|
|
? 1.0 / impl_->cfg.camera_rate_hz
|
|
: 1e9;
|
|
|
|
const uint64_t total = seconds > 0.0
|
|
? static_cast<uint64_t>(seconds * impl_->cfg.imu_rate_hz)
|
|
: 0;
|
|
uint64_t tick = 0;
|
|
|
|
while (!impl_->stop.load()) {
|
|
if (total > 0 && tick >= total) break;
|
|
|
|
impl_->clock->Advance(Duration::fromSec(dt));
|
|
const UnixTime now = impl_->clock->Now();
|
|
|
|
impl_->StepPhysics(dt);
|
|
impl_->sim_elapsed += dt;
|
|
|
|
ImuPtr meas = impl_->imu_kinematic ? impl_->MakeImuKinematic(now, dt)
|
|
: impl_->MakeImu(now);
|
|
const bool imu_out = impl_->EmitImu(now, std::move(meas), dt);
|
|
{
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
if (imu_out) impl_->stats.imu++;
|
|
impl_->stats.sim_time_sec += dt;
|
|
}
|
|
|
|
// Su that cho tool ghi (SetGroundTruthCallback). Khong stage nao doc no.
|
|
if (impl_->gt_cb) {
|
|
impl_->gt_acc += dt;
|
|
if (impl_->gt_period <= 0.0 || impl_->gt_acc + 1e-9 >= impl_->gt_period) {
|
|
if (impl_->gt_period > 0.0) impl_->gt_acc -= impl_->gt_period;
|
|
impl_->gt_cb(now, ground_truth_3d());
|
|
}
|
|
}
|
|
|
|
enc_acc += dt;
|
|
if (enc_acc >= enc_period) {
|
|
enc_acc -= enc_period;
|
|
EncoderReading e;
|
|
e.stamp = now;
|
|
e.valid = true;
|
|
{
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
e.left_rad = impl_->left_rad;
|
|
e.right_rad = impl_->right_rad;
|
|
impl_->stats.encoder++;
|
|
}
|
|
impl_->base.Push(e);
|
|
}
|
|
|
|
lidar_acc += dt;
|
|
// RUT DAY LiDAR: trong cua so [cut_at, cut_at + cut_for) thi KHONG phat
|
|
// scan nao. Bo tich luy van chay, nen khi cam lai thi nhip tro lai ngay
|
|
// -- giong het mot soi cap bi long.
|
|
const bool lidar_cut =
|
|
impl_->cfg.lidar_cut_for > 0.0 &&
|
|
impl_->sim_elapsed >= impl_->cfg.lidar_cut_at &&
|
|
impl_->sim_elapsed < impl_->cfg.lidar_cut_at + impl_->cfg.lidar_cut_for;
|
|
if (lidar_acc >= lidar_period && lidar_cut) {
|
|
lidar_acc -= lidar_period; // nuot mau nay, khong don lai
|
|
} else if (lidar_acc >= lidar_period) {
|
|
lidar_acc -= lidar_period;
|
|
impl_->lidar.Push(impl_->MakeScan(now));
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
impl_->stats.scans++;
|
|
}
|
|
|
|
// --- Sieu am ---
|
|
us_acc += dt;
|
|
if (impl_->cfg.enable_ultrasonic && !impl_->cfg.us_angles.empty() &&
|
|
us_acc >= us_period) {
|
|
us_acc -= us_period;
|
|
impl_->mcu.PushUltrasonic(impl_->MakeUltrasonic(now));
|
|
}
|
|
|
|
// --- Bumper ---
|
|
bump_acc += dt;
|
|
if (impl_->cfg.enable_bumper && bump_acc >= bump_period) {
|
|
bump_acc -= bump_period;
|
|
impl_->mcu.PushBumper(impl_->MakeBumper(now));
|
|
}
|
|
|
|
cam_acc += dt;
|
|
if (impl_->cfg.enable_depth_camera && cam_acc >= cam_period) {
|
|
cam_acc -= cam_period;
|
|
CameraFrame f;
|
|
impl_->MakeDepthFrame(now, &f);
|
|
impl_->camera.Push(f);
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
impl_->stats.camera_frames++;
|
|
}
|
|
|
|
if (impl_->cfg.speed > 0.0) {
|
|
std::this_thread::sleep_for(
|
|
std::chrono::nanoseconds(static_cast<int64_t>(dt * 1e9 / impl_->cfg.speed)));
|
|
}
|
|
tick++;
|
|
}
|
|
}
|
|
|
|
void SimSource::Run() { RunFor(0.0); }
|
|
|
|
SimSource::Stats SimSource::stats() const {
|
|
std::lock_guard<std::mutex> lk(impl_->state_mu);
|
|
return impl_->stats;
|
|
}
|
|
|
|
} // namespace vslam
|