// Phep bien doi cua khung 2D: xoay, keo canh, va hinh hop robot. // // ================== VI SAO CAN BAI KIEM NAY ================== // Khung 2D vua co them phep XOAY. Ba thu phai dung cung luc: phep chieu // (`sx`/`sy`), phep keo canh (phai nghich dao dung phep xoay), va hinh robot. // // Sai mot dau se khong gay loi nao: canh van ve, robot van hien, chi la keo // chuot sang phai thi canh di cheo. Da co ba lan lien tiep loi nam o tang // hien thi trong khi build sach va ctest xanh. // // Phep kiem manh nhat la BAT BIEN: diem the gioi nam duoi con tro phai O // NGUYEN duoi con tro sau khi keo. Do la dinh nghia cua "canh di theo tay", // va no dung o MOI goc xoay. const fs = require('fs'); const path = require('path'); const vm = require('vm'); // --- DOM gia: du de app.js chay het pham vi module --- const handlers = { window: {}, el: {} }; function mkEl(id) { const h = {}; return { id, checked: true, value: '0', max: '2', dataset: {}, style: {}, hidden: false, textContent: '', classList: { add() {}, remove() {}, toggle() {} }, clientWidth: 800, clientHeight: 600, width: 800, height: 600, addEventListener(ev, fn) { (handlers.el[id] = handlers.el[id] || {})[ev] = fn; }, getContext() { // ⚠️ Ghi LAI moi lenh ve. Mot ngu canh nuot het khong phan biet duoc // "ve dung" voi "khong ve gi" -- ma "khong ve gi" chinh la trieu chung // cua loi da xay ra: hai khung trang tinh trong khi du lieu van chay. const calls = (this.calls = this.calls || {}); return new Proxy({}, { get: (_, k) => (...a) => { calls[k] = (calls[k] || 0) + 1; return a[0]; }, set: () => true, }); }, getBoundingClientRect() { return { left: 0, top: 0, width: 800, height: 600 }; }, appendChild() {}, removeChild() {}, setAttribute() {}, focus() {}, }; } const els = {}; const doc = { getElementById(id) { return (els[id] = els[id] || mkEl(id)); }, querySelectorAll() { return []; }, querySelector(sel) { return (els[sel] = els[sel] || mkEl(sel)); }, createElement(t) { return mkEl('#' + t); }, addEventListener(ev, fn) { handlers.window[ev] = fn; }, activeElement: null, body: mkEl('body'), }; const sandbox = { document: doc, console, window: { addEventListener(ev, fn) { handlers.window[ev] = fn; }, devicePixelRatio: 1, location: { search: '' } }, location: { search: '' }, requestAnimationFrame() {}, setInterval() {}, setTimeout() {}, fetch() { return Promise.resolve({ json: () => Promise.resolve({ code: 0 }) }); }, WebSocket: function () { this.send = () => {}; this.readyState = 0; }, ImageData: function (w, h) { this.width = w; this.height = h; this.data = new Uint8ClampedArray(w * h * 4); }, URLSearchParams: function () { this.get = () => null; }, V3D: { ready: false }, }; sandbox.window.document = doc; for (const k of ['v3dInit', 'v3dSetShape', 'v3dSetPose', 'v3dSetScan', 'v3dSetCloud', 'v3dSetWorld', 'v3dSetMap', 'v3dSetPath', 'v3dSetOverlays', 'v3dRender', 'v3dSetWorldMeshes', 'v3dSetWorldVisible', 'v3dSetView', 'v3dFrustum', 'v3dCliffRings']) { sandbox[k] = () => {}; } vm.createContext(sandbox); const src = fs.readFileSync( path.resolve(__dirname, '../../libs/vslam_web/www/app.js'), 'utf8'); vm.runInContext(src + '\n;this.__view = view; this.__sx = sx; this.__sy = sy;' + '\n;this.__ver = UI_VERSION; this.__setCv = (c) => { curCv = c; };' + '\n;this.__pal = PALETTE; this.__state = state;' + '\n;this.__draw = draw; this.__rasterize = rasterize;', sandbox); const view = sandbox.__view; const sx = sandbox.__sx, sy = sandbox.__sy; // `curCv` chi duoc dat trong drawScene(); dat tay de do phep chieu rieng le. sandbox.__setCv(doc.getElementById('main')); const bad = []; const chk = (label, got, want, tol) => { const ok = Math.abs(got - want) <= (tol === undefined ? 1e-9 : tol); console.log(` ${label.padEnd(40)} ${got.toFixed(4)}${ok ? '' : ' != ' + want.toFixed(4)}`); if (!ok) bad.push(label); }; // Canvas 800x600, tam o (400, 300). view.x = 0; view.y = 0; view.scale = 50; view.rot = 0; chk('rot=0: goc the gioi o tam man hinh (x)', sx(0, 0), 400); chk('rot=0: goc the gioi o tam man hinh (y)', sy(0, 0), 300); chk('rot=0: (1,0) sang PHAI', sx(1, 0), 450); chk('rot=0: (0,1) LEN TREN', sy(0, 1), 250); // Xoay 90 do: truc +X the gioi phai chi LEN TREN man hinh. view.rot = Math.PI / 2; chk('rot=90: (1,0) khong lech ngang', sx(1, 0), 400, 1e-9); chk('rot=90: (1,0) di LEN', sy(1, 0), 250, 1e-9); // ⚠️ BAT BIEN: diem duoi con tro phai O NGUYEN duoi con tro sau khi keo. // // Day la dinh nghia cua "canh di theo tay". No phai dung o MOI goc xoay -- // va chinh o goc khac 0 thi phep nghich dao sai moi lo ra. const down = handlers.el['main'] && handlers.el['main'].mousedown; const move = handlers.window.mousemove; const up = handlers.window.mouseup; if (!down || !move) { console.log(' khong bat duoc bo xu ly chuot cua khung 2D'); bad.push('bo xu ly chuot'); } else { for (const rot of [0, 0.7, Math.PI / 2, -1.3]) { view.x = 3; view.y = -2; view.scale = 50; view.rot = rot; // Diem the gioi dang nam duoi con tro tai (500, 250). // Giai nguoc: tu man hinh ve the gioi. const c = Math.cos(rot), s_ = Math.sin(rot); const rx = (500 - 400) / 50, ry = (300 - 250) / 50; const wx = view.x + rx * c + ry * s_; const wy = view.y + -rx * s_ + ry * c; // Kiem phep giai nguoc truoc. if (Math.abs(sx(wx, wy) - 500) > 1e-6 || Math.abs(sy(wx, wy) - 250) > 1e-6) { bad.push('giai nguoc rot=' + rot.toFixed(2)); continue; } down({ button: 0, clientX: 500, clientY: 250, preventDefault() {} }); move({ clientX: 560, clientY: 215 }); up(); const nx = sx(wx, wy), ny = sy(wx, wy); const err = Math.hypot(nx - 560, ny - 215); console.log(` keo theo tay @ rot=${rot.toFixed(2).padStart(5)}` + ` lech ${err.toFixed(4)} px`); if (err > 1e-6) bad.push('keo @ rot=' + rot.toFixed(2)); } } // --- Bang mau: hai mau canh nhau phai PHAN BIET DUOC --- // // ⚠️ Day la mot loi that, khong phai gia dinh. Ban truoc dung MOT bang cho ca // hai khung, voi `free` = #ffffff tren `bg` = #f3f6fa. Hai mau cach nhau 12 // don vi -- vung DA QUET va vung chua co gi trong y het nhau, nen khong con // biet quet toi dau. Khong loi, khong canh bao: ban do van ve du. // // Cap quan trong nhat la `free` voi `bg`: cai nguoi van hanh can thay la vung // da quet LON DEN DAU, khong phai vi tri tung buc tuong. console.log('\n --- bang mau: khoang cach giua cac mau ---'); const pal = sandbox.__pal; function rgb(v) { if (Array.isArray(v)) return v.slice(0, 3); const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(v); return m ? [1, 2, 3].map((i) => parseInt(m[i], 16)) : null; } // Khoang cach co trong so theo do nhay cua mat (xap xi Rec. 601). function dist(a, b) { const A = rgb(a), B = rgb(b); const w = [0.30, 0.59, 0.11]; let d = 0; for (let i = 0; i < 3; ++i) d += w[i] * (A[i] - B[i]) * (A[i] - B[i]); return Math.sqrt(d); } const MIN_GAP = 40; for (const name of ['world', 'slam']) { const P = pal[name]; for (const [x, y] of [['free', 'bg'], ['occupied', 'free'], ['occupied', 'bg']]) { const d = dist(P[x], P[y]); const ok = d >= MIN_GAP; console.log(` ${name}: ${(x + ' vs ' + y).padEnd(17)} ${d.toFixed(1).padStart(6)}` + (ok ? '' : ` < ${MIN_GAP} <-- KHONG PHAN BIET DUOC`)); if (!ok) bad.push(`${name}.${x} vs ${y}`); } } // Hai khung phai KHAC tone: cung tone thi khong biet dang nhin khung nao. const dpane = dist(pal.world.bg, pal.slam.bg); console.log(` nen hai khung khac nhau ${dpane.toFixed(1).padStart(6)}` + (dpane >= 60 ? '' : ' <-- QUA GIONG')); if (dpane < 60) bad.push('hai khung cung tone'); // --- CHAY THAT duong ve --- // // ⚠️ Bai kiem nay ton tai vi mot loi that: `drawRobot()` doc `pal.nose` nhung // khong co tham so `pal`. ReferenceError ngay lan ve dau, va vi // `requestAnimationFrame(draw)` nam o CUOI draw(), vong ve chet vinh vien. // Ca hai khung trang tinh trong khi thanh ben van cap nhat binh thuong -- // WebSocket chay o duong khac. // // Cac bai kiem truoc do khong bat duoc vi chung khong lan nao GOI draw(). console.log('\n --- chay that duong ve ---'); { const st = sandbox.__state; const grid = { res: 0.05, w: 40, h: 30, ox: -1, oy: -1, cells: new Int8Array(40 * 30) }; for (let i = 0; i < grid.cells.length; ++i) { grid.cells[i] = i % 7 === 0 ? 100 : (i % 3 === 0 ? -1 : 0); } st.pose = { x: 0.5, y: 0.5, yaw: 0.3 }; st.gt = { x: 0.52, y: 0.5, yaw: 0.3, err: 0.02 }; st.robot = { radius: 0.24, wheel_radius: 0.075, wheel_sep: 0.36, laser_x: 0.24, laser_y: 0, laser_z: 0.125, body_l: 0.40, body_w: 0.34, body_h: 0.85, body_off_x: -0.06, clearance: 0.04 }; st.scan = new Float32Array([1.0, 0.0, 0.0, 1.0, -1.0, 0.0]); st.path = new Float32Array([0, 0, 0.5, 0.5, 1.0, 0.4]); st.worldMap = grid; st.worldMapImage = sandbox.__rasterize(grid, sandbox.__pal.world); st.map = grid; st.mapImage = sandbox.__rasterize(grid, sandbox.__pal.slam); st.slamMode = 'mapping'; const main = doc.getElementById('main'); const mainR = doc.getElementById('mainR'); // ⚠️ XOA KHOA, dung thay object: Proxy trong getContext() da giu tham chieu // toi object cu, nen gan mot object moi se cat mat duong ghi nhan. for (const el of [main, mainR]) { el.calls = el.calls || {}; for (const k of Object.keys(el.calls)) delete el.calls[k]; } let threw = null; try { sandbox.__draw(); } catch (e) { threw = e; } console.log(' goi draw() ' + (threw ? 'NEM: ' + threw.message : 'khong nem')); if (threw) bad.push('draw() nem ngoai le'); // Dem NOI DUNG: draw() co that su ve gi khong. const n = (el) => Object.values(el.calls || {}).reduce((a, b) => a + b, 0); console.log(` lenh ve tren khung trai ${n(main)}`); if (n(main) < 5) bad.push('khung trai khong duoc ve'); if (!(main.calls && main.calls.drawImage)) bad.push('ban do khong duoc ve'); } console.log('\n UI_VERSION = ' + sandbox.__ver); console.log(bad.length ? '\n => HONG: ' + bad.join(', ') : '\n => DAT'); process.exit(bad.length ? 1 : 0);