Files
vslam_cpp/libs/vslam_web/www/app.js
trung09122002 48bd5377dc upload
2026-09-18 18:14:42 +07:00

841 lines
30 KiB
JavaScript

'use strict';
// Web UI thay RViz. Khong dependency.
//
// Ban do la occupancy grid 2D, scan la 2D, path la 2D, pose la mot tam giac.
// Thu 3D duy nhat la point cloud, va no la view debug perception -- nhin tu
// tren xuong to mau theo do cao la du. Do la ly do dung canvas 2D chu khong
// three.js: three.js ~600 kB phai vendor va theo doi license, doi lay mot
// goc nhin ma bai toan nay khong can.
// --- Giai ma nhi phan (khop libs/vslam_web/include/vslam/binary_codec.h) ---
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 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.
const T_WORLD_MAP = 6;
// Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh.
const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
const R_INF = 0xFFFE; // khong co phan xa (vuot range_max)
const R_BLANKED = 0xFFFD; // bi sector mask cat (than robot che)
const state = {
pose: null, gt: null, scan: null, cloud: null, path: null,
map: null, mapImage: null, mapVersion: 0,
bytes: 0, lastBytes: 0, wireRate: 0,
};
const view = { x: 0, y: 0, scale: 40, init: false }; // scale = pixel/met
// --- WebSocket -------------------------------------------------------------
let ws = null;
let reconnectTimer = null;
function connect() {
const token = new URLSearchParams(location.search).get('token');
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = proto + '//' + location.host + '/ws' + (token ? '?token=' + token : '');
ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.onopen = () => setConn(true);
ws.onclose = () => {
setConn(false);
if (!reconnectTimer) reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, 1000);
};
ws.onerror = () => ws.close();
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
state.bytes += ev.data.length;
try { onState(JSON.parse(ev.data)); } catch (e) { /* khung hong, bo */ }
} else {
state.bytes += ev.data.byteLength;
onBinary(new DataView(ev.data));
}
};
}
function setConn(ok) {
const el = document.getElementById('conn');
el.textContent = ok ? 'da ket noi' : 'mat ket noi';
el.className = 'chip ' + (ok ? 'ok' : 'bad');
}
// --- Khung nhi phan --------------------------------------------------------
function onBinary(dv) {
if (dv.byteLength < 16 || dv.getUint32(0, true) !== MAGIC) return;
const type = dv.getUint8(4);
const off = 16;
if (type === T_SCAN) {
const angleMin = dv.getFloat32(off, true);
const angleInc = dv.getFloat32(off + 4, true);
const rangeMax = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 2);
let m = 0;
for (let i = 0; i < n; i++) {
const raw = dv.getUint16(off + 20 + i * 2, true);
// Ba gia tri canh bien deu KHONG ve. Ve tia blanked se lam ra mot
// vong cung gia o ban kinh range_max quanh robot -- trong nhu tuong.
if (raw === R_NAN || raw === R_INF || raw === R_BLANKED) continue;
const r = raw * 0.001;
const a = angleMin + i * angleInc;
pts[m++] = r * Math.cos(a);
pts[m++] = r * Math.sin(a);
}
state.scan = pts.subarray(0, m);
return;
}
if (type === T_CLOUD) {
const scale = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const b = off + 20 + i * 6;
pts[i * 3] = dv.getInt16(b, true) * scale;
pts[i * 3 + 1] = dv.getInt16(b + 2, true) * scale;
pts[i * 3 + 2] = dv.getInt16(b + 4, true) * scale;
}
state.cloud = pts;
return;
}
if (type === T_MAP_FULL || type === T_WORLD_MAP) {
const res = dv.getFloat32(off, true);
const w = dv.getInt32(off + 4, true);
const h = dv.getInt32(off + 8, true);
const ox = dv.getFloat32(off + 12, true);
const oy = dv.getFloat32(off + 16, true);
const runs = dv.getUint32(off + 24, true);
const cells = new Int8Array(w * h);
let p = 0;
for (let r = 0; r < runs; r++) {
const b = off + 28 + r * 3;
const len = dv.getUint16(b, true);
const val = dv.getInt8(b + 2);
cells.fill(val, p, p + len);
p += len;
}
const grid = { res, w, h, ox, oy, cells };
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);
if (!view.init) centerOnMap(grid);
return;
}
state.map = grid;
state.mapImage = rasterize(grid);
// 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);
// Bao cho server biet da nhan: no se khong gui lai phien ban nay.
if (ws && ws.readyState === 1 && state.mapVersion) {
ws.send(JSON.stringify({ t: 'ack_map', version: state.mapVersion }));
}
return;
}
if (type === T_PATH) {
const n = dv.getUint32(off, true);
const pts = new Float32Array(n * 2);
for (let i = 0; i < n * 2; i++) pts[i] = dv.getFloat32(off + 4 + i * 4, true);
state.path = pts;
return;
}
}
// 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) {
const img = new ImageData(map.w, map.h);
const d = img.data;
for (let i = 0; i < map.cells.length; i++) {
const v = map.cells[i];
// Hang 0 cua occupancy grid la o duoi cung (goc o origin), con hang 0 cua
// ImageData la o tren cung -> lat theo truc y khi ghi.
const x = i % map.w;
const y = map.h - 1 - Math.floor(i / map.w);
const j = (y * map.w + x) * 4;
// ⚠️ CHUA BIET phai TRONG SUOT.
//
// Ban truoc ve no DAC (alpha 255) mau xam toi. Hau qua: ban do SLAM luc
// moi quet gan nhu toan o chua biet, nen no hien ra thanh mot TAM XAM DAC
// 11.8 x 21.7 m che kin khung -- va vi phan chua biet doi rat cham, ca
// khung trong nhu dung yen. Bao cao "khung SLAM khong realtime" chinh la
// trieu chung cua viec nay, KHONG phai cua tan so cap nhat.
//
// 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.
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
d[j] = c[0]; d[j + 1] = c[1]; d[j + 2] = c[2]; d[j + 3] = c[3];
}
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
cv.getContext('2d').putImageData(img, 0, 0);
return cv;
}
// --- Khung trang thai (JSON) ----------------------------------------------
function onState(s) {
state.pose = s.pose;
state.mapVersion = s.slam.map_version;
// Hinh hoc robot den TU SERVER (robot.yaml). File nay khong duoc chua mot
// hang so kich thuoc nao -- xem ghi chu trong app3d.js.
if (s.robot) state.robot = s.robot;
txt('px', fmt(s.pose.x, 3));
txt('py', fmt(s.pose.y, 3));
txt('pyaw', fmt(s.pose.yaw, 3));
// Ground truth: chi hien khi CO. Khong co ma hien 0 la noi doi -- client
// khong phan biet duoc "dung o goc" voi "khong biet".
state.gt = s.gt || null;
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--');
state.slamMode = s.slam.mode;
txt('mode', s.slam.mode);
const st = s.safety.state;
const sv = document.getElementById('safeState');
sv.textContent = st;
sv.className = 'state ' + (st === 'OK' ? 'ok' : (st.indexOf('SLOW') >= 0 ? 'warn' : 'bad'));
txt('safeDetail', s.safety.detail || '');
// min_front la null khi khong do duoc (JSON khong co Infinity).
txt('minFront', s.safety.min_front === null ? 'inf' : fmt(s.safety.min_front, 2) + ' m');
txt('rays', s.safety.front_usable + ' / ' + s.safety.front_rays);
txt('blanked', String(s.safety.front_blanked));
// Vuc: ba trang thai phan biet ro. `detail` mang tien to "cliff:" khi
// khong phan xet duoc -- xem CliffBailName trong cliff_detect.cc.
const cd = String(s.safety.detail || '');
const cv = document.getElementById('cliffState');
if (cv) {
if (s.safety.cliff) {
cv.textContent = 'VUC PHIA TRUOC';
cv.className = 'state bad';
} else if (cd.indexOf('cliff:') === 0) {
cv.textContent = 'khong biet (' + cd.slice(6) + ')';
cv.className = 'state warn';
} else {
cv.textContent = 'khong co vuc';
cv.className = 'state ok';
}
}
if (s.tilt) {
txt('tRoll', fmt(s.tilt.roll * 57.2958, 2) + ' deg');
txt('tPitch', fmt(s.tilt.pitch * 57.2958, 2) + ' deg');
// accel_ok=false nghia la bo loc dang chi tich phan gyro (robot dang
// tang/giam toc hoac vua va cham) -> nghieng dang troi.
txt('tAccel', s.tilt.accel_ok ? 'neo trong luc' : 'gyro thuan (troi)');
}
txt('loc', s.slam.localized ? 'co' : 'khong');
txt('score', fmt(s.slam.score, 2));
txt('pms', fmt(s.slam.process_ms, 0) + ' ms');
txt('mapver', String(s.slam.map_version));
txt('hzLidar', fmt(s.health.lidar_hz, 1));
txt('hzCam', fmt(s.health.camera_hz, 1));
txt('hzImu', fmt(s.health.imu_hz, 1));
txt('hzEkf', fmt(s.health.ekf_hz, 1));
txt('cpu', fmt(s.health.cpu_pct, 0) + ' %');
txt('rss', fmt(s.health.rss_mb, 0) + ' MB');
let total = 0;
for (const k in s.health.drops) total += s.health.drops[k];
txt('drops', String(total));
if (s.teleop) {
txt('linSpeed', fmt(s.teleop.linear_speed, 2));
txt('angSpeed', fmt(s.teleop.angular_speed, 2));
}
const btn = document.getElementById('estop');
btn.textContent = s.safety.estop ? 'GO E-STOP' : 'E-STOP';
joy.classList.toggle('estop', !!s.safety.estop);
}
function txt(id, v) {
const el = document.getElementById(id);
if (el) el.textContent = v;
}
function fmt(v, d) {
return (v === null || v === undefined) ? '--' : Number(v).toFixed(d);
}
// --- Ve --------------------------------------------------------------------
const cv = document.getElementById('main');
const ctx = cv.getContext('2d');
function resize() {
const dpr = window.devicePixelRatio || 1;
cv.width = cv.clientWidth * dpr;
cv.height = cv.clientHeight * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
window.addEventListener('resize', resize);
function centerOnMap(grid) {
const m = grid || state.worldMap || state.map;
if (!m) return;
view.x = m.ox + m.w * m.res / 2;
view.y = m.oy + m.h * m.res / 2;
const w = cv.clientWidth, h = cv.clientHeight;
view.scale = Math.min(w / (m.w * m.res), h / (m.h * m.res)) * 0.9;
view.init = true;
}
// The gioi -> man hinh. y lat dau vi truc y cua canvas huong xuong.
// Canvas DANG duoc ve. O che do chia doi, hai khung dung CHUNG `view` -- co
// 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; }
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;
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.fillStyle = color;
ctx.fill();
ctx.restore();
}
// Ve MOT khung.
//
// `grid`/`gridImage` : ban do de ve (THE GIOI hay SLAM)
// `robotPose` : pose ve tam giac dac -- su that o khung trai, uoc
// luong o khung phai
// `showGt` : co ve them tam giac ground truth mo khong
//
// 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) {
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.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.font = '13px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('SLAM dang TAT', w / 2, h / 2 - 10);
ctx.fillText('them --slam vao lenh de quet ban do', w / 2, h / 2 + 10);
ctx.textAlign = 'left';
}
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),
m.w * m.res * view.scale, m.h * m.res * view.scale);
}
if (state.path && on('lyPath')) {
ctx.strokeStyle = '#5aa9e6';
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]);
i === 0 ? ctx.moveTo(X, Y) : ctx.lineTo(X, Y);
}
ctx.stroke();
}
// scan va cloud o frame robot -> xoay theo pose truoc khi ve.
const p = robotPose;
if (p) {
const c = Math.cos(p.yaw), s = Math.sin(p.yaw);
// 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);
}
if (state.cloud && on('lyCloud')) {
const pts = state.cloud;
for (let i = 0; i < pts.length; i += 3) {
const x = p.x + c * pts[i] - s * pts[i + 1];
const y = p.y + s * pts[i] + c * pts[i + 1];
const z = pts[i + 2];
// To mau theo do cao: day la view debug perception, va do cao la
// thu duy nhat dang nhin o goc tu tren xuong.
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);
}
}
if (state.scan && on('lyScan')) {
ctx.fillStyle = '#e2574c';
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().
const lx = (state.robot && state.robot.laser_x) || 0;
const ly = (state.robot && state.robot.laser_y) || 0;
for (let i = 0; i < pts.length; i += 2) {
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);
}
}
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, '#4ec9a0', 1.0);
}
}
// Nhan khung phai noi KICH THUOC ban do SLAM.
//
// O muc zoom vua ca toa nha (26 x 58 m), ban do SLAM luc moi quet chi
// 1.3 x 1.1 m -- nho duoi mot pixel, va khung phai trong y het nhu hong. Mot
// con so lam ro khac biet giua "chua quet duoc gi" va "khung bi loi".
// ⚠️ Nhan phai noi DUNG trang thai cua SLAM, khong phai doan tu `state.map`.
//
// Ban truoc luon viet "SLAM dang dung", ke ca khi `slam.mode === 'off'`. Khung
// den kem mot nhan noi SLAM dang chay lam nguoi van hanh di tim loi trong SLAM
// suot nhieu phut, trong khi su that chi la node chay THIEU co `--slam`.
//
// Cung lop loi voi chuyen web hien `cliff` tu so do da cu 10 giay trong khi
// FSM da bo qua no: nguoi van hanh tin cai ho NHIN THAY.
function updateSlamLabel() {
if (state.slamMode === 'off' || !state.slamMode) {
labR.textContent = 'SLAM TAT -- chay lai voi --slam';
return;
}
const m = state.map;
labR.textContent = m
? 'SLAM ' + state.slamMode + ' ' + (m.w * m.res).toFixed(1) + ' x ' +
(m.h * m.res).toFixed(1) + ' m'
: 'SLAM ' + state.slamMode + ' (chua co ban do -- lai them)';
}
function draw() {
// ⚠️ 3D va CHIA DOI phai chay CUNG NHAU.
//
// Ban truoc viet `if (use3d) { draw3d(); return; }` -- tuc khi bat 3D thi
// khung PHAI khong bao gio duoc ve lai, no giu nguyen hinh cuoi truoc luc
// bam nut. Trieu chung dung la "tab SLAM khong cap nhat", va no chi xuat
// hien khi bat CA HAI nut -- dung to hop huu ich nhat:
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM (RViz)
if (use3d) {
draw3d();
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
}
requestAnimationFrame(draw);
return;
}
if (split) {
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');
// 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');
} 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');
}
requestAnimationFrame(draw);
}
// --- Tuong tac -------------------------------------------------------------
let dragging = false, lastX = 0, lastY = 0;
cv.addEventListener('mousedown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
});
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;
lastX = e.clientX; lastY = e.clientY;
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 ------------------------------------------------------------------
function post(cmd, body) {
const token = new URLSearchParams(location.search).get('token');
const headers = { 'Content-Type': 'application/json' };
if (token) headers['X-Auth-Token'] = token;
return fetch('/api/' + cmd, { method: 'POST', headers, body: JSON.stringify(body || {}) })
.then(r => r.json())
.then(r => { if (r.code !== 0) alert(cmd + ': ' + r.message); })
.catch(e => alert(cmd + ': ' + e));
}
document.getElementById('estop').addEventListener('click', () => {
const on = document.getElementById('estop').textContent === 'E-STOP';
// Tuong minh, KHONG toggle: mot request bi retry khong duoc phep GO e-stop.
post('safety/estop', { on });
});
document.getElementById('reset').addEventListener('click', () => post('safety/reset', {}));
// --- Joystick --------------------------------------------------------------
//
// Thay cho virtual_joystick.py (896 dong Tkinter) cua ban ROS.
//
// Trang nay CHI gui gia tri da chuan hoa [-1, 1]. Moi phep ramp gia toc, moi
// gioi han van toc, va deadman deu nam o C++. Khong bao gio tin trinh duyet
// ve dinh dang chuyen dong: WebSocket co the lag, tab co the bi treo, va may
// tram co the ngu giua chung.
//
// Ba lop deadman doc lap, tu nong ra sau:
// 1. o day -- nha tay thi knob ve tam va gui 0
// 2. o day -- ngung gui hoan toan neu mat ket noi
// 3. o base -- tu dung neu khong nhan lenh trong 300 ms (lop duy nhat con
// song khi ca tab lan wifi deu chet)
const joy = document.getElementById('joy');
const knob = document.getElementById('knob');
const stick = { active: false, vx: 0, wz: 0, pointerId: null };
const JOY_RADIUS = 54; // do lech toi da cua knob, pixel
const DEADZONE = 0.08; // bo rung tay quanh tam
function setKnob(dx, dy) {
knob.style.transform = 'translate(' + dx + 'px,' + dy + 'px)';
}
function applyStick(dx, dy) {
// Kep vao hinh TRON, khong phai hinh vuong: keo cheo khong duoc phep cho ra
// van toc lon hon keo thang.
const len = Math.hypot(dx, dy);
if (len > JOY_RADIUS) {
dx = dx / len * JOY_RADIUS;
dy = dy / len * JOY_RADIUS;
}
setKnob(dx, dy);
let vx = -dy / JOY_RADIUS; // keo LEN = tien
let wz = -dx / JOY_RADIUS; // keo TRAI = quay trai (nguoc chieu kim dong ho)
if (Math.abs(vx) < DEADZONE) vx = 0;
if (Math.abs(wz) < DEADZONE) wz = 0;
stick.vx = vx;
stick.wz = wz;
txt('jvx', vx.toFixed(2));
txt('jwz', wz.toFixed(2));
}
function releaseStick() {
stick.active = false;
stick.pointerId = null;
joy.classList.remove('active');
applyStick(0, 0);
sendCmd(); // gui 0 NGAY, khong doi tick 20 Hz ke tiep
}
function pointerPos(e) {
const r = joy.getBoundingClientRect();
return {
dx: e.clientX - (r.left + r.width / 2),
dy: e.clientY - (r.top + r.height / 2),
};
}
joy.addEventListener('pointerdown', (e) => {
e.preventDefault();
stick.active = true;
stick.pointerId = e.pointerId;
joy.setPointerCapture(e.pointerId);
joy.classList.add('active');
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
joy.addEventListener('pointermove', (e) => {
if (!stick.active || e.pointerId !== stick.pointerId) return;
e.preventDefault();
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
// pointerup VA pointercancel: pointercancel la truong hop trinh duyet cuop
// lai con tro (cuon trang, goi den, chuyen tab). Thieu no thi knob ket o vi
// tri cu va robot chay tiep.
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) {
joy.addEventListener(ev, (e) => {
if (e.pointerId !== stick.pointerId) return;
releaseStick();
});
}
// --- Ban phim --------------------------------------------------------------
// Phim MUI TEN, khop SUPPORTED_KEYS cua TeleopModel ben C++
// ("Up"/"Down"/"Left"/"Right"). Ban dau toi dung WASD -- do la tu nghi ra,
// khong khop mo hinh da co.
const keys = new Set();
const KEY_MAP = {
ArrowUp: [1, 0], ArrowDown: [-1, 0], ArrowLeft: [0, 1], ArrowRight: [0, -1],
};
window.addEventListener('keydown', (e) => {
if (e.key === ' ') { keys.clear(); applyKeys(); e.preventDefault(); return; }
if (e.key === 'q' || e.key === 'Q') { adjustSpeed('lin', -1); return; }
if (e.key === 'e' || e.key === 'E') { adjustSpeed('lin', +1); return; }
if (e.key === '+' || e.key === '=') { adjustSpeed('lin', +1); return; }
if (e.key === '-' || e.key === '_') { adjustSpeed('lin', -1); return; }
if (!(e.key in KEY_MAP) || stick.active) return;
keys.add(e.key);
applyKeys();
e.preventDefault();
});
window.addEventListener('keyup', (e) => {
if (!keys.delete(e.key)) return;
applyKeys();
});
// Mat focus (chuyen tab, alt-tab) = nha het phim. Neu khong thi mot phim
// "dinh" se lam robot chay mai.
window.addEventListener('blur', () => { keys.clear(); applyKeys(); });
function applyKeys() {
if (stick.active) return;
let vx = 0, wz = 0;
for (const k of keys) { vx += KEY_MAP[k][0]; wz += KEY_MAP[k][1]; }
applyStick(-wz * JOY_RADIUS, -vx * JOY_RADIUS);
}
// --- Chinh toc do ----------------------------------------------------------
// Tinh nang cua teleop_model.py: doi scale van toc NGAY KHI DANG CHAY.
// Viec kep vao [min, max] do C++ lam; o day chi gui yeu cau.
function adjustSpeed(which, dir) {
post('teleop/adjust', { axis: which, dir: dir });
}
for (const b of document.querySelectorAll('.sbtn')) {
b.addEventListener('click', () => adjustSpeed(b.dataset.adj, Number(b.dataset.dir)));
}
// --- Gui lenh 20 Hz --------------------------------------------------------
function sendCmd() {
if (!ws || ws.readyState !== 1) return;
ws.send(JSON.stringify({ t: 'cmd', vx: stick.vx, wz: stick.wz }));
}
setInterval(() => {
// Gui LIEN TUC ke ca khi dung yen: deadman o base can nhan duoc lenh deu
// dan de biet nguoi lai van con day. Ngung gui = base tu dung sau 300 ms.
sendCmd();
}, 50);
// --- Do bang thong ---------------------------------------------------------
setInterval(() => {
state.wireRate = state.bytes - state.lastBytes;
state.lastBytes = state.bytes;
txt('wire', (state.wireRate / 1024).toFixed(1) + ' kB/s');
}, 1000);
resize();
connect();
// --- Doi 2D / 3D ----------------------------------------------------------
//
// Hai trinh ve doc CUNG mot `state`, nen khong the lech du lieu. Chi mot cai
// chay tai mot thoi diem: render WebGL khi khong ai nhin la dot CPU/GPU vo
// ich tren Jetson.
// ============ Chia doi: THE GIOI | SLAM ============
//
// 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');
let split = false;
btnSplit.addEventListener('click', () => {
if (!state.worldMap) {
// Khong co su that de doi chieu -- chay that, khong phai mo phong.
btnSplit.textContent = 'khong co su that';
setTimeout(() => { btnSplit.textContent = 'chia doi'; }, 1800);
return;
}
split = !split;
wrap.classList.toggle('split', split);
document.getElementById('labL').style.display = split ? '' : 'none';
labR.style.display = split ? '' : 'none';
btnSplit.textContent = split ? 'mot khung' : 'chia doi';
// 3D va chia doi KHONG loai tru nhau: `.split.three` cho ra
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM 2D (RViz)
// -- dung to hop huu ich nhat khi dang quet.
});
{
const el = document.getElementById('uiVer');
if (el) el.textContent = 'ui ' + UI_VERSION;
console.log('vslam ui ' + UI_VERSION);
}
const cv3d = document.getElementById('main3d');
const btn3d = document.getElementById('btn3d');
let use3d = false;
// Hinh hoc 3D THAT cua the gioi -- tai MOT lan, khi bat 3D lan dau.
//
// Khong tai luc mo trang: 6.7 MB la lang phi voi nguoi chi xem khung 2D. Va
// khong tai lai: the gioi khong doi trong mot phien.
//
// 404 KHONG phai loi -- nghia la node chay tu `--map` chu khong tu `--world`,
// va khung 3D quay ve khoi hop dung tu luoi chiem dung.
let worldMeshState = 'chua'; // chua | dang | xong | khong-co
function loadWorldMeshes() {
if (worldMeshState !== 'chua') return;
worldMeshState = 'dang';
fetch('/api/world.bin')
.then((r) => {
if (r.status === 404) { worldMeshState = 'khong-co'; return null; }
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.arrayBuffer();
})
.then((buf) => {
if (!buf) return;
worldMeshState = v3dSetWorldMeshes(buf) ? 'xong' : 'khong-co';
})
.catch((e) => {
console.warn('world.bin:', e);
worldMeshState = 'khong-co';
});
}
btn3d.addEventListener('click', () => {
if (!use3d && !V3D.ready) {
if (!v3dInit(cv3d)) {
btn3d.textContent = '3D loi';
btn3d.classList.add('bad');
return;
}
}
if (!use3d) loadWorldMeshes();
use3d = !use3d;
// 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';
});
// Khoang cach VE giua hai hinh robot -- do tren chinh hai doi tuong 3D, khong
// phai tinh lai tu du lieu.
//
// ⚠️ Doc NGAY tren cai dang duoc ve moi tra loi duoc cau hoi "no lech that hay
// chi trong nhu lech": sai so du lieu va khoang cach hien thi la HAI so khac
// nhau, va da co lan chung khac nhau that (hinh ground truth bi tut 0.075 m vi
// cau truc nhom lech mot tang).
function updateGapChip() {
const el = document.getElementById('gap');
if (!el) return;
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);
}
function draw3d() {
if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose);
if (state.gt && on('lyGt')) {
if (V3D.gtGroup) V3D.gtGroup.visible = true;
v3dSetPose(V3D.gtGroup, state.gt);
} else if (V3D.gtGroup) {
V3D.gtGroup.visible = false;
}
updateGapChip();
v3dSetScan(on('lyScan') ? state.scan : null, state.pose, state.robot);
v3dSetCloud(on('lyCloud') ? state.cloud : null, state.pose);
// THE GIOI: tuong 3D dung tu ban do mo phong -- day la phan "Gazebo".
// Dung MOT lan (ban do the gioi la tinh), roi chi bat/tat.
// Overlay cam bien (frustum, vanh cliff): tat mac dinh cho giong Gazebo.
v3dSetOverlays(on('lyCam'));
if (state.worldMap) v3dSetWorld(state.worldMap, 2.0);
v3dSetWorldVisible(on('lyWorld'));
// SLAM: lop phu tren san, hien DAN khi quet -- day la phan "RViz". O chua
// quet trong suot nen tuong 3D van nhin xuyen qua.
if (state.map && on('lyMap')) {
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
}
if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map;
if (on('lyPath')) v3dSetPath(state.path);
else if (V3D.pathLine) V3D.pathLine.visible = false;
v3dRender(cv3d, on('lyFollow'));
}
requestAnimationFrame(draw);