This commit is contained in:
trung09122002
2026-09-19 15:33:52 +07:00
parent 48bd5377dc
commit 3b281174d0
22 changed files with 1913 additions and 119 deletions

View File

@@ -31,6 +31,20 @@ struct RobotGeometry {
double wheel_separation = 0.36;
double robot_radius = 0.24;
double body_half_width = 0.17;
// Than robot la mot KHOI HOP, khong phai hinh tru.
//
// Lay tu `robot.urdf.xacro` cua ban ROS: body 0.40 x 0.34 x 0.85 m, lech
// -0.06 m theo x, va day hop cach san `ground_clearance`.
//
// ⚠️ Cac so nay chi de VE. `robot_radius` van la thu dung cho va cham va
// cho bumper -- mot hinh tron bao ngoai khoi hop. Doi hai thu do lam mot se
// lam phep va cham phu thuoc goc quay, va do la mot lop bug moi.
double body_length = 0.40;
double body_width = 0.34;
double body_height = 0.85;
double body_offset_x = -0.06;
double ground_clearance = 0.04;
};
struct BaseLimits {

View File

@@ -53,7 +53,9 @@ StatusResponse RobotModel::Load(const ConfigNode& root) {
// thay vi `wheel_separation` nghia la moi phep quay sai ti le, va khong
// co gi bao.
const std::vector<std::string> unknown = g.UnknownKeys(
{"wheel_radius", "wheel_separation", "robot_radius", "body_half_width"});
{"wheel_radius", "wheel_separation", "robot_radius",
"body_half_width", "body_length", "body_width", "body_height",
"body_offset_x", "ground_clearance"});
if (!unknown.empty()) {
std::string m = "robot.yaml geometry: khoa la:";
for (const auto& k : unknown) m += " " + k;
@@ -65,6 +67,15 @@ StatusResponse RobotModel::Load(const ConfigNode& root) {
geometry_.robot_radius = g.get<double>("robot_radius", geometry_.robot_radius);
geometry_.body_half_width =
g.get<double>("body_half_width", geometry_.body_half_width);
// Kich thuoc khoi hop -- chi de VE, xem ghi chu o RobotGeometry.
geometry_.body_length =
g.get<double>("body_length", geometry_.body_length);
geometry_.body_width = g.get<double>("body_width", geometry_.body_width);
geometry_.body_height = g.get<double>("body_height", geometry_.body_height);
geometry_.body_offset_x =
g.get<double>("body_offset_x", geometry_.body_offset_x);
geometry_.ground_clearance =
g.get<double>("ground_clearance", geometry_.ground_clearance);
}
if (!(geometry_.wheel_radius > 0.0) || !(geometry_.wheel_separation > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,

View File

@@ -96,6 +96,50 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
const WorldRasterOptions& opt,
OccupancyGrid* out);
// ---------------------------------------------------------------------------
// Chi muc doan 2D, de raycast trung MAT TUONG chu khong trung bien o
// ---------------------------------------------------------------------------
//
// ⚠️ VI SAO CAN: DDA tren luoi tra ve khoang cach toi MAT VAO cua o bi chiem
// dau tien, ma o do chi duoc danh dau khi tam giac di qua TAM o. Mat vao ay
// nam lui vao trong tuong toi mot o day du.
//
// Do duoc tren the gioi benh vien, khoang cach tu diem quet toi mat tuong
// NHIN THAY, o luoi 0.05 m: p50 = 3.7 cm, p90 = 5.6 cm. MOI tia deu dung som.
// Do khong phai loi cai dat -- do la he qua cua luong tu hoa.
//
// Cach chua khong phai lam luoi min hon (van luong tu, chi nho hon) ma la giu
// DDA de tim O trung, roi CAT chinh xac voi doan nam trong o do. Luoi van la
// nguon su that cho kinh, vuc va va cham -- chi rieng khoang cach tra ve la
// chinh xac.
struct WorldSegments {
// Doan thang 2D: 4 float moi doan (x0, y0, x1, y1), he toa do THE GIOI.
// Lay tu canh cua tam giac va cham nam trong dai z cua LiDAR.
std::vector<float> seg;
// Chi muc CSR theo O CUA LUOI: o `i` chua cac doan
// cell_items[cell_start[i] .. cell_start[i + 1]).
std::vector<uint32_t> cell_start;
std::vector<uint32_t> cell_items;
uint32_t width = 0, height = 0;
double resolution = 0.05;
double origin_x = 0.0, origin_y = 0.0;
bool empty() const { return seg.empty(); }
};
// Dung chi muc tu mesh VA CHAM cua world, khop luoi voi `grid`.
//
// Dung mesh VA CHAM chu khong mesh hien thi: mo phong phai TU NHAT QUAN -- thu
// LiDAR do duoc phai la thu robot dam vao. Vai model trong bo nay co hull va
// cham don gian hoa khac han mesh hien thi (do duoc: PatientWheelChair,
// nursesstation_01), va Gazebo cung hanh xu y het.
StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt,
const OccupancyGrid& grid,
WorldSegments* out);
// ---------------------------------------------------------------------------
// Xuat hinh hoc cho khung 3D
// ---------------------------------------------------------------------------

View File

@@ -292,6 +292,13 @@ class SimSource {
// khong dong bo voi bat ky thu gi dang chay, nen goi truoc khi Run().
void SetMapForTest(const OccupancyGrid& m);
// Khoang cach LiDAR do duoc tu MOT DIEM bat ky, khong qua than robot.
//
// Chi dung cho test: no la cach duy nhat kiem duoc rang tia dung o MAT
// TUONG chu khong o bien o luoi. Do qua duong ong day du thi phai lai robot
// toi dung cho, va khi do sai so dat cho lan at sai so dang muon do.
double RangeForTest(double x, double y, double angle) const;
// Model doc duoc tu `.world`; rong neu khong chay tu world. Khung 3D dung
// no de ve do dac that thay vi khoi hop dung tu luoi.
const GazeboWorld& world() const;

View File

@@ -4,6 +4,9 @@
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <limits>
#include <vector>
#include <fstream>
#include <map>
#include <sstream>
@@ -736,6 +739,133 @@ StatusResponse RasterizeGazeboWorld(const GazeboWorld& world,
// ---------------------------------------------------------------------------
StatusResponse BuildWorldSegments(const GazeboWorld& world,
const WorldRasterOptions& opt,
const OccupancyGrid& grid,
WorldSegments* out) {
if (out == nullptr) {
return StatusResponse::Error(StatusCode::kInvalidArgument, "out == null");
}
out->seg.clear();
out->cell_items.clear();
out->cell_start.assign(static_cast<size_t>(grid.width) * grid.height + 1, 0);
out->width = grid.width;
out->height = grid.height;
out->resolution = grid.resolution;
out->origin_x = grid.origin.position.x;
out->origin_y = grid.origin.position.y;
const double res = grid.resolution;
const double ox = out->origin_x, oy = out->origin_y;
const int W = static_cast<int>(grid.width), H = static_cast<int>(grid.height);
// --- Gom doan tu canh cua tam giac trong dai z ---
//
// Lay CA BA canh cua moi tam giac. Canh nam trong long vat the (vd canh cua
// tam giac mat tren chieu xuong) khong gay hai: chung luon nam XA hon mat
// truoc doc theo tia, va phep cat lay t NHO NHAT.
std::map<std::string, std::vector<Tri>> cache;
for (const WorldModel& m : world.models) {
if (m.collision_obj.empty()) continue;
auto it = cache.find(m.model_name);
if (it == cache.end()) {
std::vector<Tri> tris;
const bool ok = IsDae(m.collision_obj)
? ReadDaeTriangles(m.collision_obj, &tris)
: ReadObjTriangles(m.collision_obj, &tris);
if (!ok) tris.clear();
it = cache.emplace(m.model_name, std::move(tris)).first;
}
if (it->second.empty()) continue;
const double cy = std::cos(m.yaw), sny = std::sin(m.yaw);
for (const Tri& t0 : it->second) {
double X[3], Y[3], Z[3];
for (int k = 0; k < 3; ++k) {
const double sx = t0.x[k] * m.sx, sy = t0.y[k] * m.sy;
X[k] = sx * cy - sy * sny + m.x;
Y[k] = sx * sny + sy * cy + m.y;
Z[k] = t0.z[k] * m.sz + m.z;
}
const double zlo = std::min({Z[0], Z[1], Z[2]});
const double zhi = std::max({Z[0], Z[1], Z[2]});
if (zhi < opt.z_min || zlo > opt.z_max) continue;
for (int e = 0; e < 3; ++e) {
const int a = e, b = (e + 1) % 3;
out->seg.push_back(static_cast<float>(X[a]));
out->seg.push_back(static_cast<float>(Y[a]));
out->seg.push_back(static_cast<float>(X[b]));
out->seg.push_back(static_cast<float>(Y[b]));
}
}
}
const size_t n_seg = out->seg.size() / 4;
if (n_seg == 0) {
return StatusResponse::Error(StatusCode::kNotFound,
"khong dung duoc doan nao tu mesh va cham");
}
// --- Chi muc CSR: hai luot, dem roi dien ---
//
// Moi doan duoc ghi vao MOI O no cat qua, di bang DDA supercover. Dung bao
// loi cua doan se re hon nhung mot buc tuong cheo dai 5 m se dinh vao hang
// nghin o no khong he cham.
auto walk = [&](size_t s, const std::function<void(int, int)>& visit) {
double ax = out->seg[s * 4], ay = out->seg[s * 4 + 1];
double bx = out->seg[s * 4 + 2], by = out->seg[s * 4 + 3];
double px = (ax - ox) / res, py = (ay - oy) / res;
const double qx = (bx - ox) / res, qy = (by - oy) / res;
int cx = static_cast<int>(std::floor(px));
int cyi = static_cast<int>(std::floor(py));
const int ex = static_cast<int>(std::floor(qx));
const int ey = static_cast<int>(std::floor(qy));
const double dx = qx - px, dy = qy - py;
const int sx = dx > 0 ? 1 : (dx < 0 ? -1 : 0);
const int sy = dy > 0 ? 1 : (dy < 0 ? -1 : 0);
const double inf = std::numeric_limits<double>::infinity();
const double tdx = dx != 0.0 ? std::fabs(1.0 / dx) : inf;
const double tdy = dy != 0.0 ? std::fabs(1.0 / dy) : inf;
double tmx = dx != 0.0 ? ((dx > 0 ? (cx + 1 - px) : (px - cx)) * tdx) : inf;
double tmy = dy != 0.0 ? ((dy > 0 ? (cyi + 1 - py) : (py - cyi)) * tdy) : inf;
for (int guard = 0; guard < 4096; ++guard) {
if (cx >= 0 && cyi >= 0 && cx < W && cyi < H) visit(cx, cyi);
if (cx == ex && cyi == ey) break;
if (tmx < tmy) { tmx += tdx; cx += sx; }
else { tmy += tdy; cyi += sy; }
if (tmx > 1.0 && tmy > 1.0) {
if (cx >= 0 && cyi >= 0 && cx < W && cyi < H) visit(cx, cyi);
break;
}
}
};
for (size_t s = 0; s < n_seg; ++s) {
walk(s, [&](int cx, int cyi) {
out->cell_start[static_cast<size_t>(cyi) * grid.width + cx + 1]++;
});
}
for (size_t i = 1; i < out->cell_start.size(); ++i) {
out->cell_start[i] += out->cell_start[i - 1];
}
out->cell_items.assign(out->cell_start.back(), 0);
std::vector<uint32_t> fill(out->cell_start.begin(), out->cell_start.end() - 1);
for (size_t s = 0; s < n_seg; ++s) {
walk(s, [&](int cx, int cyi) {
out->cell_items[fill[static_cast<size_t>(cyi) * grid.width + cx]++] =
static_cast<uint32_t>(s);
});
}
VSLAM_INFO("world -> doan: " << n_seg << " doan, " << out->cell_items.size()
<< " muc chi muc (" << (out->seg.size() * 4 +
out->cell_items.size() * 4) / 1048576.0
<< " MB)");
return StatusResponse::Ok();
}
// ---------------------------------------------------------------------------
StatusResponse ExportWorldMeshes(const GazeboWorld& world, bool visual,
WorldMeshes* out) {
if (out == nullptr) {

View File

@@ -168,6 +168,10 @@ 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;
@@ -213,6 +217,81 @@ struct SimSource::Impl {
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
@@ -260,7 +339,7 @@ struct SimSource::Impl {
static_cast<size_t>(cx);
const bool is_glass = cidx < glass.size() && glass[cidx] != 0;
if (cell >= 50 && !is_glass) {
return t * res;
return Refined(ox, oy, angle, t * res, max_range);
}
if (t_max_x < t_max_y) {
t = t_max_x;
@@ -393,7 +472,12 @@ struct SimSource::Impl {
// 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) {
return t;
// 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();
@@ -486,7 +570,12 @@ struct SimSource::Impl {
const double lo = fz, hi = fz + cfg.wall_height;
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)) {
return std::max(t_enter, 0.0) * res;
// 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;
}
}
@@ -935,6 +1024,16 @@ StatusResponse SimSource::Open() {
WorldRasterOptions wo;
const StatusResponse rs = RasterizeGazeboWorld(impl_->world, wo, &impl_->map);
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);
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,
@@ -986,6 +1085,10 @@ 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);

View File

@@ -76,6 +76,13 @@ struct RobotShape {
double wheel_separation = 0.36;
double body_half_width = 0.17;
// Khoi hop cua than, CHI de ve. `radius` van la thu dung cho va cham.
double body_length = 0.40;
double body_width = 0.34;
double body_height = 0.85;
double body_offset_x = -0.06;
double ground_clearance = 0.04;
// Vi tri cam bien trong base_link (met). z do tu TAM TRUC banh, khong tu
// san -- trinh ve tu cong wheel_radius khi can toa do so voi san.
double laser_x = 0.24, laser_y = 0.0, laser_z = 0.125;

View File

@@ -90,6 +90,11 @@ void WriteStateJson(const WebSnapshot& s, std::string* out) {
Num("wheel_radius", s.robot.wheel_radius, 4, out); Comma(out);
Num("wheel_sep", s.robot.wheel_separation, 4, out); Comma(out);
Num("half_width", s.robot.body_half_width, 4, out); Comma(out);
Num("body_l", s.robot.body_length, 4, out); Comma(out);
Num("body_w", s.robot.body_width, 4, out); Comma(out);
Num("body_h", s.robot.body_height, 4, out); Comma(out);
Num("body_off_x", s.robot.body_offset_x, 4, out); Comma(out);
Num("clearance", s.robot.ground_clearance, 4, out); Comma(out);
Num("laser_x", s.robot.laser_x, 4, out); Comma(out);
Num("laser_y", s.robot.laser_y, 4, out); Comma(out);
Num("laser_z", s.robot.laser_z, 4, out); Comma(out);

View File

@@ -12,7 +12,55 @@ 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-18c';
const UI_VERSION = '2026-09-19f';
// ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau.
//
// Ban truoc dung MOT bang cho ca hai: `free` gan trang (#ffffff) tren nen gan
// trang (#f3f6fa). Hai mau do cach nhau vai don vi, nen vung DA QUET va vung
// chua co gi trong y het nhau -- khong con biet quet toi dau.
//
// Gio moi khung mang tone cua cong cu no thay the:
//
// `world` -- khung THE GIOI, tone Gazebo: nen troi, san sang, tuong xam.
// `slam` -- khung SLAM, tone RViz: nen than chi, o TRONG sang bat len, o bi
// chiem gan den. Tuong phan nam giua `free` va `bg`, khong giua
// `occupied` va `bg` -- vi cai nguoi van hanh can thay la vung DA
// QUET lon den dau.
//
// Nguyen tac khong doi cho ca hai: CHUA BIET trong suot (xem rasterize()).
const PALETTE = {
world: {
bg: '#a9b8c6', // troi Gazebo
occupied: [86, 97, 108, 255], // tuong, xam dam
free: [232, 237, 241, 235], // san, sang
unknown: [0, 0, 0, 0],
path: '#1b5e8a',
scan: '#c0392b',
cloud: '#1f7a4d',
nose: '#eef2f6',
text: '#44505c',
robot: '#1a6ea8',
gt: '#0f9d58',
},
slam: {
// Nen RViz. Sang hon mot nac so voi ban dau (#2e3033): o do tuong gan
// den chi cach nen 29.5 don vi, nen mot o tuong le giua vung chua quet la
// vo hinh. Tuong phan chinh van la free-vs-bg, nhung occupied-vs-bg cung
// phai du.
bg: '#3c4046',
occupied: [18, 18, 20, 255], // tuong, gan den
free: [206, 208, 211, 235], // vung da quet, SANG -- day la tuong phan
unknown: [0, 0, 0, 0],
path: '#4fc3f7',
scan: '#ff5a4d',
cloud: '#34d17e',
nose: '#3c4046',
text: '#9aa3ad',
robot: '#42a5f5',
gt: '#2ee06a',
},
};
const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_MAP_PATCH = 4, T_PATH = 5;
// Ban do THE GIOI cua bo mo phong -- khung nhin "Gazebo". Tinh: gui mot lan.
@@ -29,7 +77,10 @@ const state = {
bytes: 0, lastBytes: 0, wireRate: 0,
};
const view = { x: 0, y: 0, scale: 40, init: false }; // scale = pixel/met
// `rot` = goc XOAY cua khung nhin, radian, nguoc chieu kim dong ho trong he
// the gioi. Hai khung dung CHUNG view nay nen chung luon thang hang -- doi
// chieu duoc hai ban do la ca ly do mo hai khung.
const view = { x: 0, y: 0, scale: 40, rot: 0, init: false }; // scale = pixel/met
// --- WebSocket -------------------------------------------------------------
@@ -134,12 +185,12 @@ function onBinary(dv) {
if (type === T_WORLD_MAP) {
// Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map.
state.worldMap = grid;
state.worldMapImage = rasterize(grid);
state.worldMapImage = rasterize(grid, PALETTE.world);
if (!view.init) centerOnMap(grid);
return;
}
state.map = grid;
state.mapImage = rasterize(grid);
state.mapImage = rasterize(grid, PALETTE.slam);
// Can khung theo ban do THE GIOI neu co -- no la cai khong doi, con ban
// do SLAM lon dan khi quet va se keo khung nhin chay theo.
if (!view.init && !state.worldMap) centerOnMap(grid);
@@ -161,7 +212,7 @@ function onBinary(dv) {
// Giai RLE mot lan cho moi map_version roi blit -- moi khung chi con mot
// drawImage thay vi ve lai tung o.
function rasterize(map) {
function rasterize(map, pal) {
const img = new ImageData(map.w, map.h);
const d = img.data;
for (let i = 0; i < map.cells.length; i++) {
@@ -182,12 +233,12 @@ function rasterize(map) {
// RViz ve chua-biet trong suot, va do la ly do ban do o do "lon dan" nhin
// thay duoc.
//
// Mau cung dao lai cho nen TOI: bi chiem SANG (tuong noi len), trong thi
// mo. Ban truoc de bi chiem gan DEN tren nen den -- vo hinh.
// Mau lay tu `CANVAS` o dau file, khong go tai cho: bang do phai doi cung
// luc voi bien CSS, va de hai noi thi chac chan se lech.
let c;
if (v < 0) c = [0, 0, 0, 0]; // chua biet -> TRONG SUOT
else if (v < 50) c = [58, 70, 86, 170]; // trong, mo
else c = [222, 232, 244, 255]; // bi chiem, SANG
if (v < 0) c = pal.unknown; // chua biet -> TRONG SUOT
else if (v < 50) c = pal.free;
else c = pal.occupied;
d[j] = c[0]; d[j + 1] = c[1]; d[j + 2] = c[2]; d[j + 3] = c[3];
}
const cv = document.createElement('canvas');
@@ -271,6 +322,20 @@ function onState(s) {
if (s.teleop) {
txt('linSpeed', fmt(s.teleop.linear_speed, 2));
txt('angSpeed', fmt(s.teleop.angular_speed, 2));
// Thanh truot: chi dong bo khi NGUOI DUNG khong dang keo, va lay tran
// tu server (`--max-speed` co the noi tran len cho mo phong).
syncRange('linRange', s.teleop.linear_speed, s.teleop.max_linear_speed);
syncRange('angRange', s.teleop.angular_speed, s.teleop.max_angular_speed);
}
// Toc do DO DUOC tu encoder, de canh gia tri dat.
//
// ⚠️ Dat 2.0 ma do duoc 0.98 KHONG phai loi: `accel_limit` 0.30 m/s^2 can
// 6.7 giay va ~6.7 m duong chay de len toi 2 m/s, ma cho rong nhat trong
// toa nha chi 4.75 m. Hai so nay canh nhau thi khac biet do nhin thay ngay
// thay vi thanh mot cau hoi.
if (s.odom) {
txt('linReal', fmt(Math.abs(s.odom.vx), 2));
txt('angReal', fmt(Math.abs(s.odom.vyaw), 2));
}
const btn = document.getElementById('estop');
@@ -291,6 +356,11 @@ function fmt(v, d) {
const cv = document.getElementById('main');
const ctx = cv.getContext('2d');
// ⚠️ Khai o DAY chu khong o cho dung dau tien: bo xu ly chuot ben duoi gan
// cho ca hai khung, va `const` khai muon hon cho dung se nem ReferenceError
// ngay luc nap trang.
const cvR = document.getElementById('mainR');
const ctxR = cvR.getContext('2d');
function resize() {
const dpr = window.devicePixelRatio || 1;
@@ -315,27 +385,47 @@ function centerOnMap(grid) {
// y: hai ban do phai thang hang thi moi doi chieu duoc, ma doi chieu chinh la
// ly do mo hai khung.
let curCv = null;
function sx(x) { return (x - view.x) * view.scale + curCv.clientWidth / 2; }
function sy(y) { return curCv.clientHeight / 2 - (y - view.y) * view.scale; }
// The gioi -> man hinh, qua ba buoc: doi goc ve tam nhin, XOAY, roi doi ti le.
// Truc y cua canvas nguoc voi truc y the gioi, nen moi phep xoay xuat hien o
// `ctx.rotate()` deu mang dau am.
function sx(x, y) {
const c = Math.cos(view.rot), s_ = Math.sin(view.rot);
const dx = x - view.x, dy = y - view.y;
return (dx * c - dy * s_) * view.scale + curCv.clientWidth / 2;
}
function sy(x, y) {
const c = Math.cos(view.rot), s_ = Math.sin(view.rot);
const dx = x - view.x, dy = y - view.y;
return curCv.clientHeight / 2 - (dx * s_ + dy * c) * view.scale;
}
function on(id) { return document.getElementById(id).checked; }
// Tam giac chi huong. Mot ham cho ca pose uoc luong lan ground truth: hai ban
// chep cua cung mot hinh se lech nhau ngay lan sua dau tien, va luc do khong ai
// so sanh duoc hai cai nua.
function drawRobot(ctx, x, y, yaw, color, alpha) {
const L = 0.30 * view.scale, W = 0.17 * view.scale;
// Robot ve theo HINH HOP, dung kich thuoc that tu robot.yaml.
//
// ⚠️ Ban truoc ve tam giac voi hai hang so 0.30 va 0.17 go thang vao day. Do
// la dung lop bug "hai cho phai giu dong bo" ma `PROJECT_CONTEXT.md` da ghi
// giua URDF va launch param: doi hinh hoc trong robot.yaml thi hinh ve khong
// doi theo, va khong co gi bao.
//
// Hop mot minh thi khong doc duoc huong, nen them mot vach o dau mui.
function drawRobot(ctx, x, y, yaw, color, alpha, pal) {
const r = state.robot;
const L = (r && r.body_l ? r.body_l : 0.40) * view.scale;
const W = (r && r.body_w ? r.body_w : 0.34) * view.scale;
const off = (r && r.body_off_x ? r.body_off_x : 0) * view.scale;
ctx.save();
ctx.globalAlpha = alpha;
ctx.translate(sx(x), sy(y));
ctx.rotate(-yaw);
ctx.beginPath();
ctx.moveTo(L, 0);
ctx.lineTo(-L * 0.6, -W);
ctx.lineTo(-L * 0.6, W);
ctx.closePath();
ctx.translate(sx(x, y), sy(x, y));
ctx.rotate(-yaw - view.rot);
ctx.fillStyle = color;
ctx.fill();
ctx.fillRect(off - L / 2, -W / 2, L, W);
// Vach mui: chi ro dau la phia truoc.
ctx.fillStyle = pal.nose;
ctx.fillRect(off + L / 2 - L * 0.14, -W * 0.16, L * 0.14, W * 0.32);
ctx.restore();
}
@@ -348,21 +438,21 @@ function drawRobot(ctx, x, y, yaw, color, alpha) {
//
// Mot ham cho ca hai khung: hai ban chep se lech nhau ngay lan sua dau, va
// luc do khong con doi chieu duoc nua.
function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapToggle) {
function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapToggle, pal) {
curCv = targetCv;
const ctx = targetCtx;
const w = targetCv.clientWidth, h = targetCv.clientHeight;
if (targetCv.width !== w || targetCv.height !== h) {
targetCv.width = w; targetCv.height = h;
}
ctx.fillStyle = '#12151a';
ctx.fillStyle = pal.bg;
ctx.fillRect(0, 0, w, h);
// Mot khung den khong noi duoc vi sao no den. Neu day la khung SLAM va
// SLAM dang TAT, viet ra -- nguoi van hanh khong phai doan.
if (!grid && mapToggle === 'lyMap' &&
(state.slamMode === 'off' || !state.slamMode)) {
ctx.fillStyle = '#7d8896';
ctx.fillStyle = pal.text;
ctx.font = '13px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('SLAM dang TAT', w / 2, h / 2 - 10);
@@ -373,17 +463,24 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
if (grid && gridImage && on(mapToggle || 'lyMap')) {
const m = grid;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(gridImage,
sx(m.ox), sy(m.oy + m.h * m.res),
// Goc TREN-TRAI cua anh trong he the gioi la (ox, oy + h*res). Dua goc do
// vao dung cho roi xoay CA anh quanh no.
const gx = m.ox, gy = m.oy + m.h * m.res;
ctx.save();
ctx.translate(sx(gx, gy), sy(gx, gy));
ctx.rotate(-view.rot);
ctx.drawImage(gridImage, 0, 0,
m.w * m.res * view.scale, m.h * m.res * view.scale);
ctx.restore();
}
if (state.path && on('lyPath')) {
ctx.strokeStyle = '#5aa9e6';
ctx.strokeStyle = pal.path;
ctx.lineWidth = 1.5;
ctx.beginPath();
for (let i = 0; i < state.path.length; i += 2) {
const X = sx(state.path[i]), Y = sy(state.path[i + 1]);
const X = sx(state.path[i], state.path[i + 1]);
const Y = sy(state.path[i], state.path[i + 1]);
i === 0 ? ctx.moveTo(X, Y) : ctx.lineTo(X, Y);
}
ctx.stroke();
@@ -397,7 +494,7 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
// Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta
// dang danh gia phai nhin ro hon cai lam chuan.
if (showGt && state.gt && on('lyGt')) {
drawRobot(ctx, state.gt.x, state.gt.y, state.gt.yaw, '#00c853', 0.45);
drawRobot(ctx, state.gt.x, state.gt.y, state.gt.yaw, pal.gt, 0.45, pal);
}
if (state.cloud && on('lyCloud')) {
@@ -411,12 +508,12 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
const t = Math.max(0, Math.min(1, z / 1.2));
ctx.fillStyle = 'rgb(' + Math.round(80 + 175 * t) + ',' +
Math.round(200 - 90 * t) + ',' + Math.round(120 + 60 * t) + ')';
ctx.fillRect(sx(x) - 1, sy(y) - 1, 2, 2);
ctx.fillRect(sx(x, y) - 1, sy(x, y) - 1, 2, 2);
}
}
if (state.scan && on('lyScan')) {
ctx.fillStyle = '#e2574c';
ctx.fillStyle = pal.scan;
const pts = state.scan;
// ⚠️ Scan trong frame LASER -- phai bu vi tri gan LiDAR truoc khi dua
// vao pose cua base. Xem ghi chu trong v3dSetScan().
@@ -426,11 +523,11 @@ function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapT
const bx = pts[i] + lx, by = pts[i + 1] + ly;
const x = p.x + c * bx - s * by;
const y = p.y + s * bx + c * by;
ctx.fillRect(sx(x) - 1.5, sy(y) - 1.5, 3, 3);
ctx.fillRect(sx(x, y) - 1.5, sy(x, y) - 1.5, 3, 3);
}
}
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, '#4ec9a0', 1.0);
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, pal.robot, 1.0, pal);
}
}
@@ -460,6 +557,9 @@ function updateSlamLabel() {
}
function draw() {
// Goi o DAY chu khong trong draw3d(): o so sanh uoc luong voi ground truth
// phai chay ca khi dang xem khung 2D.
updateGapChip();
// ⚠️ 3D va CHIA DOI phai chay CUNG NHAU.
//
// Ban truoc viet `if (use3d) { draw3d(); return; }` -- tuc khi bat 3D thi
@@ -472,7 +572,8 @@ function draw() {
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
PALETTE.slam);
}
requestAnimationFrame(draw);
return;
@@ -481,17 +582,19 @@ function draw() {
updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld');
state.gt || state.pose, false, 'lyWorld', PALETTE.world);
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap',
PALETTE.slam);
} else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
const haveSlam = !!state.map;
drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld');
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld',
haveSlam ? PALETTE.slam : PALETTE.world);
}
requestAnimationFrame(draw);
}
@@ -500,24 +603,48 @@ function draw() {
let dragging = false, lastX = 0, lastY = 0;
cv.addEventListener('mousedown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
});
// ⚠️ Gan cho CA HAI khung.
//
// Truoc day chi khung trai nhan chuot, nen khung SLAM ben phai khong keo va
// khong phong to duoc -- ma do moi la khung nguoi dung nhin lau nhat khi quet.
//
// Hai khung dung chung mot `view`, nen keo o khung nao thi ca hai cung di. Do
// la co y: doi chieu duoc hai ban do la ca ly do mo hai khung.
for (const c of [cv, cvR]) {
c.addEventListener('mousedown', (e) => {
dragging = e.button === 2 ? 'rot' : 'pan';
lastX = e.clientX; lastY = e.clientY;
e.preventDefault();
});
c.addEventListener('contextmenu', (e) => e.preventDefault());
c.addEventListener('wheel', (e) => {
e.preventDefault();
view.scale *= e.deltaY < 0 ? 1.1 : 1 / 1.1;
view.scale = Math.max(2, Math.min(400, view.scale));
view.init = true;
}, { passive: false });
c.addEventListener('dblclick', () => { view.rot = 0; centerOnMap(); });
}
window.addEventListener('mouseup', () => { dragging = false; });
window.addEventListener('mousemove', (e) => {
if (!dragging) return;
view.x -= (e.clientX - lastX) / view.scale;
view.y += (e.clientY - lastY) / view.scale;
const dx = e.clientX - lastX, dy = e.clientY - lastY;
lastX = e.clientX; lastY = e.clientY;
if (dragging === 'rot') {
// Keo ngang de xoay khung nhin. Keo sang PHAI thi canh quay sang phai.
view.rot -= dx * 0.005;
} else {
// Keo canh: canh phai di THEO tay, ke ca khi khung nhin dang xoay. Nen
// phai dua do doi man hinh NGUOC ve he the gioi truoc.
const c = Math.cos(view.rot), s_ = Math.sin(view.rot);
const wx = dx / view.scale, wy = -dy / view.scale;
view.x -= wx * c + wy * s_;
view.y -= -wx * s_ + wy * c;
}
view.init = true;
});
cv.addEventListener('wheel', (e) => {
e.preventDefault();
view.scale *= e.deltaY < 0 ? 1.1 : 1 / 1.1;
view.scale = Math.max(2, Math.min(400, view.scale));
view.init = true;
}, { passive: false });
cv.addEventListener('dblclick', () => { centerOnMap(); });
// --- Lenh ------------------------------------------------------------------
@@ -671,6 +798,26 @@ function adjustSpeed(which, dir) {
post('teleop/adjust', { axis: which, dir: dir });
}
// Dong bo thanh truot voi gia tri server, TRU khi nguoi dung dang keo no.
// Ghi de giua luc keo lam thanh truot giat nguoc ve va khong dat duoc gia tri.
function syncRange(id, value, max) {
const el = document.getElementById(id);
if (!el || el === document.activeElement || el.dataset.drag === '1') return;
if (max && Number(el.max) !== max) el.max = String(max);
el.value = String(value);
}
for (const [id, axis] of [['linRange', 'lin'], ['angRange', 'ang']]) {
const el = document.getElementById(id);
if (!el) continue;
el.addEventListener('pointerdown', () => { el.dataset.drag = '1'; });
el.addEventListener('pointerup', () => { el.dataset.drag = '0'; });
el.addEventListener('input', () => {
txt(id === 'linRange' ? 'linSpeed' : 'angSpeed', Number(el.value).toFixed(2));
post('teleop/set', { axis: axis, value: Number(el.value) });
});
}
for (const b of document.querySelectorAll('.sbtn')) {
b.addEventListener('click', () => adjustSpeed(b.dataset.adj, Number(b.dataset.dir)));
}
@@ -707,8 +854,6 @@ connect();
// Tuong duong mo ca Gazebo lan RViz. Khung trai la SU THAT (de lai cho
// chuan), khung phai la cai SLAM dang dung (de biet quet toi dau). Hai khung
// dung CHUNG `view`, nen pan/zoom khoa voi nhau va doi chieu duoc truc tiep.
const cvR = document.getElementById('mainR');
const ctxR = cvR.getContext('2d');
const btnSplit = document.getElementById('btnSplit');
const labR = document.getElementById('labR');
const wrap = document.querySelector('.canvas-wrap');
@@ -769,21 +914,27 @@ function loadWorldMeshes() {
});
}
btn3d.addEventListener('click', () => {
if (!use3d && !V3D.ready) {
// Bat/tat khung 3D. Tach ra khoi bo xu ly nut vi CAC NUT GOC NHIN cung goi
// no: bam "tren" khi dang o 2D thi phai vao 3D roi moi dat goc, khong thi nut
// khong lam gi ca va nguoi dung tuong no hong.
function setThreeD(on) {
if (on && !V3D.ready) {
if (!v3dInit(cv3d)) {
btn3d.textContent = '3D loi';
btn3d.classList.add('bad');
return;
return false;
}
}
if (!use3d) loadWorldMeshes();
use3d = !use3d;
if (on && !use3d) loadWorldMeshes();
use3d = on;
// Chi doi CLASS. Dat style inline o day se de bep quy tac .split trong
// stylesheet -- dung cai bay da lam khung phai den xi mot lan.
wrap.classList.toggle('three', use3d);
btn3d.textContent = use3d ? '2D' : '3D';
});
return true;
}
btn3d.addEventListener('click', () => { setThreeD(!use3d); });
// Khoang cach VE giua hai hinh robot -- do tren chinh hai doi tuong 3D, khong
// phai tinh lai tu du lieu.
@@ -795,12 +946,39 @@ btn3d.addEventListener('click', () => {
function updateGapChip() {
const el = document.getElementById('gap');
if (!el) return;
// Sai so DU LIEU: khoang cach giua pose uoc luong va ground truth, tinh tu
// chinh hai con so server gui len.
let dData = null;
if (state.pose && state.gt) {
dData = Math.hypot(state.pose.x - state.gt.x, state.pose.y - state.gt.y);
}
// Khoang cach VE: do tren hai doi tuong 3D that su dang duoc ve.
let dDraw = null;
const a = V3D.robotGroup && V3D.robotGroup.position;
const b = V3D.gtGroup && V3D.gtGroup.position;
if (!a || !b || !V3D.gtGroup.visible) { el.textContent = 'gap --'; return; }
const d = Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
el.textContent = 'gap ' + d.toFixed(3) + ' m';
el.classList.toggle('bad', d > 0.05);
if (a && b && V3D.gtGroup.visible) {
dDraw = Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
}
if (dData === null) { el.textContent = 'gap --'; el.title = ''; return; }
// ⚠️ Hien CA HAI khi chung khac nhau.
//
// Sai so du lieu va khoang cach ve la HAI so. Bang nhau nghia la hinh ve
// trung thuc va cai nhin thay la sai so that. Khac nhau nghia la con loi o
// tang hien thi -- da xay ra hai lan (thieu lop boc, va quen laser_x).
const drift = dDraw !== null && Math.abs(dDraw - dData) > 0.01;
el.textContent = 'gap ' + dData.toFixed(3) + ' m' +
(drift ? ' / ve ' + dDraw.toFixed(3) : '');
el.title = drift
? 'Sai so du lieu va khoang cach VE khac nhau -- con loi o tang hien thi.'
: 'Sai so uoc luong vs ground truth. Hinh ve trung thuc voi du lieu.';
el.classList.toggle('bad', dData > 0.05 || drift);
}
for (const b of document.querySelectorAll('.vbtn')) {
b.addEventListener('click', () => {
if (!setThreeD(true)) return;
v3dSetView(b.dataset.view);
});
}
function draw3d() {
@@ -813,7 +991,6 @@ function draw3d() {
V3D.gtGroup.visible = false;
}
updateGapChip();
v3dSetScan(on('lyScan') ? state.scan : null, state.pose, state.robot);
v3dSetCloud(on('lyCloud') ? state.cloud : null, state.pose);

View File

@@ -56,7 +56,9 @@ function v3dInit(canvas) {
// lai cua trang nay la nen toi, nhung khung 3D co bang mau RIENG -- vi muc
// tieu cua no la trong giong Gazebo, va tuong trang tren nen toi doc rat te:
// khong co bong, khong co chieu sau, moi khoi thanh mot mang bet.
V3D.scene.background = new THREE.Color(0xb8c6d4);
// ⚠️ Tone nay phai khop `PALETTE.world` trong app.js: hai khung cung the
// hien MOT the gioi, lech tone thi nhin nhu hai noi khac nhau.
V3D.scene.background = new THREE.Color(0xa9b8c6); // = PALETTE.world.bg
// Suong mu xa: ban do 2000x2000 o do phan giai 0.05 m la 100 m moi chieu,
// ve het se thanh mot vung nhieu xam. Suong mu cat no mem hon la cat cung.
// Mau suong = mau nen, neu khong se thay mot duong chan troi gia.
@@ -89,7 +91,7 @@ function v3dInit(canvas) {
V3D.scene.add(V3D.root);
// Luoi san 1 m, va truc goc toa do map.
V3D.gridHelper = new THREE.GridHelper(40, 40, 0x93a3b3, 0xa9b6c4);
V3D.gridHelper = new THREE.GridHelper(40, 40, 0x93a2b0, 0xa6b3c0);
V3D.root.add(V3D.gridHelper);
V3D.root.add(new THREE.AxesHelper(0.5));
@@ -109,13 +111,41 @@ function v3dBindMouse(canvas) {
const dx = e.clientX - V3D.dragging.x, dy = e.clientY - V3D.dragging.y;
V3D.dragging.x = e.clientX; V3D.dragging.y = e.clientY;
if (V3D.dragging.btn === 0) {
// ⚠️ CANH DI THEO TAY, va DAU CUA HAI TRUC KHONG GIONG NHAU.
//
// Suy luan tay o day rat de sai: phep xoay lam ca VI TRI lan HE TRUC cua
// camera doi cung luc, va phan he truc moi la phan quyet dinh. Toi da
// suy sai mot lan va dao ca hai truc, lam hong truc ngang trong khi
// dang sua truc doc.
//
// Dau duoi day duoc CHOT BANG PHEP DO: `test/www/test_orbit_camera.js`
// chieu mot diem the gioi qua dung phep camera cua v3dRender() roi xem
// no di ve phia nao. Doi dau o day ma khong chay bai do lai la quay ve
// dung cho cu.
V3D.orbit.az -= dx * 0.006;
// Chan o hai dau: qua thien dinh thi khung nhin lat nguoc va nguoi dung
// mat phuong huong.
V3D.orbit.el = Math.max(0.05, Math.min(1.45, V3D.orbit.el + dy * 0.006));
V3D.orbit.el = Math.max(0.05, Math.min(1.45, V3D.orbit.el - dy * 0.006));
} else {
V3D.orbit.tx -= dx * 0.01;
V3D.orbit.ty += dy * 0.01;
// Keo canh: phai di theo HUONG NHIN, khong theo truc the gioi. Khong doi
// he thi o mot goc bat ky, keo sang phai lam canh di cheo.
//
// Dau tru: `tx`/`ty` la TAM NHIN. Canh di sang phai nghia la tam nhin
// di sang TRAI.
const c = Math.cos(V3D.orbit.az), s = Math.sin(V3D.orbit.az);
const k = V3D.orbit.dist * 0.0016;
// ⚠️ Truc DOC phai bu do rut ngan theo goc nhin.
//
// Mat san nhin cheo bi rut ngan mot he so sin(el): doi tam nhin 1 m ve
// phia truoc lam canh dich it hon nhieu so voi 1 m sang ngang. Dung
// chung mot he so cho ca hai truc lam canh KEO HUT theo chieu doc -- do
// duoc: ti le do doi 0.27 trong khi ti le keo la 0.63.
//
// Chan mau o 0.25 cho goc nhin "canh": o do sin(el) -> 0 va phep bu se
// no ra vo cuc.
const kf = k / Math.max(Math.sin(V3D.orbit.el), 0.25);
V3D.orbit.tx -= dx * s * k + dy * c * kf;
V3D.orbit.ty -= -dx * c * k + dy * s * kf;
}
});
canvas.addEventListener('wheel', (e) => {
@@ -135,23 +165,36 @@ function v3dBuildRobot(r) {
// toa do map voi san la 0.
g.position.y = r.wheel_radius;
const bodyMat = new THREE.MeshLambertMaterial({ color: 0x3d6ea5 });
const bodyMat = new THREE.MeshLambertMaterial({ color: 0x1a6ea8 });
const darkMat = new THREE.MeshLambertMaterial({ color: 0x20262e });
// Than: tru tron ban kinh `radius`. Chieu cao chon theo ban kinh, khong
// phai mot hang so -- robot.yaml khong co chieu cao than.
const bodyH = r.radius * 1.2;
// Than: KHOI HOP, dung kich thuoc that tu robot.yaml.
//
// Ban truoc ve hinh tru ban kinh `robot_radius` vi robot.yaml chua co chieu
// cao than. Nhung robot that la mot hop 0.40 x 0.34 x 0.85 m -- hinh tru
// 0.24 m lam no trong lun va tron, khong nhan ra duoc huong.
//
// `robot_radius` van la thu dung cho va cham: mot hinh tron bao ngoai hop.
// Khong dung kich thuoc hop cho va cham -- lam vay thi phep va cham phu
// thuoc goc quay, va do la mot lop bug moi.
const bodyL = r.body_l || r.radius * 1.6;
const bodyW = r.body_w || r.radius * 1.4;
const bodyH = r.body_h || r.radius * 1.2;
const clear = r.clearance || 0.0;
const body = new THREE.Mesh(
new THREE.CylinderGeometry(r.radius, r.radius, bodyH, 28), bodyMat);
body.position.y = bodyH / 2;
new THREE.BoxGeometry(bodyL, bodyH, bodyW), bodyMat);
// `base_link` o tam truc banh; day hop cach SAN dung `clearance`, nen tam
// hop nam tren base_link mot doan (clearance + bodyH/2 - wheel_radius).
body.position.set(r.body_off_x || 0, clear + bodyH / 2 - r.wheel_radius, 0);
g.add(body);
// Mui chi huong +X, de nhin mot cai la biet dau la truoc.
const nose = new THREE.Mesh(
new THREE.ConeGeometry(r.radius * 0.28, r.radius * 0.5, 16),
new THREE.ConeGeometry(bodyW * 0.16, bodyL * 0.22, 16),
new THREE.MeshLambertMaterial({ color: 0x8ec5ff }));
nose.rotation.z = -Math.PI / 2;
nose.position.set(r.radius * 0.85, bodyH * 0.55, 0);
nose.position.set((r.body_off_x || 0) + bodyL / 2,
clear + bodyH * 0.85 - r.wheel_radius, 0);
g.add(nose);
// Hai banh chu dong, cach nhau `wheel_sep`.
@@ -402,7 +445,7 @@ function v3dSetGround(grid) {
const fw = grid.w * r, fh = grid.h * r;
V3D.floorMesh = new THREE.Mesh(
new THREE.PlaneGeometry(fw, fh),
new THREE.MeshStandardMaterial({ color: 0x9aa5ad, roughness: 1.0 }));
new THREE.MeshStandardMaterial({ color: 0xe8edf1, roughness: 1.0 }));
V3D.floorMesh.rotation.x = -Math.PI / 2;
V3D.floorMesh.position.set(grid.ox + fw / 2, -0.004, -(grid.oy + fh / 2));
V3D.floorMesh.receiveShadow = true;
@@ -416,7 +459,7 @@ function v3dSetGround(grid) {
V3D.scene.fog.far = span * 1.4;
if (V3D.gridHelper) V3D.root.remove(V3D.gridHelper);
V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span),
0x93a3b3, 0xa9b6c4);
0x93a2b0, 0xa6b3c0);
V3D.root.add(V3D.gridHelper);
}
@@ -683,6 +726,27 @@ function v3dSetWorldVisible(on) {
if (V3D.worldMesh) V3D.worldMesh.visible = on;
}
// Dat khung nhin ve mot goc chuan.
//
// Ba goc nay la ba cau hoi khac nhau: "mat bang the nao" (tren), "cao thap ra
// sao" (canh), va "tong the" (cheo). Xoay tay toi dung mot trong ba goc do rat
// kho, nen chung la nut.
function v3dSetView(name) {
if (!V3D.ready) return;
const o = V3D.orbit;
if (name === 'top') {
o.el = 1.45; // gan thien dinh; 1.5708 lam khung nhin suy bien
o.az = -Math.PI / 2; // +X sang phai, +Y len tren -- nhu khung 2D
} else if (name === 'side') {
o.el = 0.06; // sat mat san
o.az = -Math.PI / 2;
} else {
o.el = 0.55;
o.az = -2.2;
}
o.tx = 0; o.ty = 0;
}
function v3dSetOverlays(on) {
if (!V3D.ready || !V3D.root) return;
V3D.root.traverse((o) => {

View File

@@ -20,6 +20,15 @@
</div>
<button id="btnSplit" class="chip" title="Hai khung: THE GIOI (de lai) va SLAM (de xem ban do dang dung)">chia doi</button>
<button id="btn3d" class="chip" title="Doi giua nhin tu tren (2D) va 3D">3D</button>
<!-- Goc nhin chuan cho khung 3D. An khi dang o 2D. -->
<!-- LUON hien. An chung cho toi khi bam 3D lam chung khong tim thay duoc:
nguoi dung khong biet co thu do de ma di tim. Bam mot trong ba nut se
tu vao 3D. -->
<span id="viewBtns" class="viewgrp">
<button class="chip vbtn" data-view="top" title="Nhin tu tren xuong">tren</button>
<button class="chip vbtn" data-view="side" title="Nhin ngang, sat mat san">canh</button>
<button class="chip vbtn" data-view="iso" title="Goc cheo mac dinh">cheo</button>
</span>
<div class="spacer"></div>
<!-- ⚠️ O nay ton tai de tra loi MOT cau hoi: trinh duyet dang chay ban JS
nao. Sua o `www/` la sua file tinh, khong phai sua server, nen khoi
@@ -126,20 +135,27 @@
<tr><td>wz</td><td id="jwz">0.00</td></tr>
</table>
<!-- ⚠️ Thanh truot, khong phai hai nut +/-.
Buoc chinh la 0.05 m/s, nen tu 0.30 len tran 2.00 la 34 lan bam.
Nguoi van hanh bam vai cai, thay van cham, roi ket luan la lenh
khong an. `dat` hien gia tri DAT, `that` hien toc do DO DUOC tu
encoder -- hai so do khac nhau khi base con dang tang toc. -->
<div class="speed-row">
<button class="sbtn" data-adj="lin" data-dir="-1">&minus;</button>
<span class="slabel">toc do</span>
<input type="range" id="linRange" class="srange"
min="0.05" max="2.00" step="0.05" value="0.30">
<span id="linSpeed" class="sval">0.30</span>
<button class="sbtn" data-adj="lin" data-dir="1">+</button>
<span id="linReal" class="sreal">0.00</span>
</div>
<div class="speed-row">
<button class="sbtn" data-adj="ang" data-dir="-1">&minus;</button>
<span class="slabel">quay</span>
<input type="range" id="angRange" class="srange"
min="0.10" max="2.00" step="0.05" value="0.70">
<span id="angSpeed" class="sval">0.70</span>
<button class="sbtn" data-adj="ang" data-dir="1">+</button>
<span id="angReal" class="sreal">0.00</span>
</div>
<div class="hint-sm">keo joystick &middot; phim mui ten &middot; Space = dung<br>+ &minus; hoac Q E de chinh toc do</div>
<div class="hint-sm">keo joystick &middot; phim mui ten &middot; Space = dung<br>keo thanh truot hoac Q E de chinh toc do &middot; so mo la toc do DO DUOC</div>
</section>
<section class="controls">

View File

@@ -1,14 +1,18 @@
/* Mot trang, khong dependency. Muc tieu < 60 kB cho ca ba file. */
:root {
--bg: #12151a;
--panel: #1a1f27;
--line: #2a323d;
--fg: #d6dde7;
--dim: #7c8798;
--ok: #4ec9a0;
--warn: #e0b34a;
--bad: #e2574c;
--accent: #5aa9e6;
/* Tone SANG. Moi mau di theo cap voi mot mau tren canvas -- xem
`CANVAS` trong app.js. Doi mot ben ma quen ben kia se lam ban do chim
vao nen: o bi chiem tung duoc ve SANG cho nen toi. */
--bg: #eef1f6;
--panel: #ffffff;
--line: #ccd5e0;
--fg: #1c232c;
--dim: #66717f;
--ok: #157a56;
--warn: #8a6100;
--bad: #c0392b;
--accent: #1f6fb8;
--chip: #e3e9f1;
}
* { box-sizing: border-box; }
@@ -31,10 +35,10 @@ header {
.chip {
padding: 3px 10px; border-radius: 3px;
background: #222a34; border: 1px solid var(--line);
background: var(--chip); border: 1px solid var(--line);
}
.chip.ok { color: var(--ok); border-color: #2c5b4c; }
.chip.bad { color: var(--bad); border-color: #5b2f2c; }
.chip.ok { color: var(--ok); border-color: #9ccbb9; }
.chip.bad { color: var(--bad); border-color: #e0a9a3; }
main { display: flex; height: calc(100% - 41px); }
@@ -63,22 +67,22 @@ aside td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
.state {
padding: 5px 8px; border-radius: 3px; text-align: center;
background: #222a34; border: 1px solid var(--line); margin-bottom: 4px;
background: var(--chip); border: 1px solid var(--line); margin-bottom: 4px;
}
.state.ok { color: var(--ok); border-color: #2c5b4c; }
.state.warn { color: var(--warn); border-color: #5b4d2c; }
.state.bad { color: var(--bad); border-color: #5b2f2c; }
.state.ok { color: var(--ok); border-color: #9ccbb9; }
.state.warn { color: var(--warn); border-color: #d9c48a; }
.state.bad { color: var(--bad); border-color: #e0a9a3; }
.detail { color: var(--dim); font-size: 11px; min-height: 16px; margin-bottom: 4px; }
.controls { display: flex; gap: 8px; }
button {
flex: 1; padding: 9px; cursor: pointer;
background: #222a34; color: var(--fg);
background: var(--chip); color: var(--fg);
border: 1px solid var(--line); border-radius: 3px;
font: inherit;
}
button:hover { border-color: var(--accent); }
button.danger { color: var(--bad); border-color: #5b2f2c; }
button.danger { color: var(--bad); border-color: #e0a9a3; }
button.danger:hover { background: var(--bad); color: #fff; }
/* --- Joystick ---
@@ -90,7 +94,7 @@ button.danger:hover { background: var(--bad); color: #fff; }
position: relative;
width: 160px; height: 160px;
border-radius: 50%;
background: radial-gradient(circle at 50% 50%, #222a34 0%, #1a1f27 70%);
background: radial-gradient(circle at 50% 50%, #ffffff 0%, #dfe6ef 70%);
border: 1px solid var(--line);
touch-action: none; /* tat pan/zoom cua trinh duyet khi keo */
user-select: none;
@@ -166,3 +170,14 @@ button.danger:hover { background: var(--bad); color: #fff; }
}
#labL { left: 8px; }
#labR { left: 50%; margin-left: 8px; }
/* Thanh truot toc do. `sval` la gia tri DAT, `sreal` la toc do DO DUOC. */
.speed-row { display: flex; align-items: center; gap: 6px; margin: 4px 0; }
.srange { flex: 1; min-width: 70px; accent-color: var(--accent); }
.sval { font-variant-numeric: tabular-nums; min-width: 34px; text-align: right; }
.sreal {
font-variant-numeric: tabular-nums; min-width: 34px; text-align: right;
color: var(--dim); font-size: 11px;
}
.viewgrp { display: inline-flex; gap: 4px; }
.viewgrp[hidden] { display: none; }