// Do cao SAN cua ban do SLAM (che do doc): giai khoi FLH1 o app.js, uon mat // phang ban do va nang scan/cloud/quy dao o app3d.js. // // ================== VI SAO CAN BAI KIEM NAY ================== // Mat phang ban do 2D ve phang o z = 0 trong khi tuong voxel o z that: tren // tang cao 1.5 m nguoi xem thay tuong lo lung con san "thung" xuong tang duoi. // Sai mot dau trong phep doi truc cuc bo -> ROS (PlaneGeometry quay -PI/2 // quanh X) thi doc nghieng NGUOC chieu -- van ve duoc, khong mot loi nao. const fs = require('fs'); const path = require('path'); const vm = require('vm'); const WWW = path.join(__dirname, '..', '..', 'libs', 'vslam_web', 'www'); let bad = 0; function check(name, cond, chiTiet) { if (cond) return; bad++; console.log(` ${name}: HONG${chiTiet ? ' -- ' + chiTiet : ''}`); } const near = (a, b, tol) => a !== null && Math.abs(a - b) <= tol; // --- Khung ban do y het binary_codec.cc EncodeMapFull ---------------------- // Luoi 2D 0.05 m, 40 x 20 o, mot run duy nhat (toan o trong = 0). const MAP = { res: 0.05, w: 40, h: 20, ox: -1.0, oy: 2.0 }; // Luoi san 0.2 m phu cung khung: 10 x 5 o. Doc 1 m/1 m theo +x tu cot 2 toi // cot 7 (z = 0 .. 1.0), san tren 1.5 m o cot 8-9; hang 4 chua biet. Mot HO // -0.1 m o goc tay-nam (hang 0, cot 0-1) de bat loi lat chieu y. const FL = { res: 0.2, w: 10, h: 5 }; function floorMm(c, r) { if (r === 4) return -32768; if (c >= 8) return 1500; if (c < 2) return r === 0 ? -100 : 0; return Math.round((c - 2) * 200); // tam o: doc 45 do de so de doc } function mapFrame(withFloor) { const n = MAP.w * MAP.h; const runs = Math.ceil(n / 65535); const tail = withFloor ? 24 + FL.w * FL.h * 2 : 0; const buf = new ArrayBuffer(16 + 28 + runs * 3 + tail); const dv = new DataView(buf); dv.setUint8(0, 0x56); dv.setUint8(1, 0x53); dv.setUint8(2, 0x4C); dv.setUint8(3, 0x31); dv.setUint8(4, 3); dv.setUint8(5, 1); let o = 16; dv.setFloat32(o, MAP.res, true); dv.setInt32(o + 4, MAP.w, true); dv.setInt32(o + 8, MAP.h, true); dv.setFloat32(o + 12, MAP.ox, true); dv.setFloat32(o + 16, MAP.oy, true); dv.setFloat32(o + 20, 0, true); dv.setUint32(o + 24, runs, true); o += 28; dv.setUint16(o, n, true); dv.setInt8(o + 2, 0); o += 3; if (withFloor) { 'FLH1'.split('').forEach((ch, i) => dv.setUint8(o + i, ch.charCodeAt(0))); dv.setFloat32(o + 4, FL.res, true); dv.setInt32(o + 8, FL.w, true); dv.setInt32(o + 12, FL.h, true); dv.setFloat32(o + 16, MAP.ox, true); dv.setFloat32(o + 20, MAP.oy, true); for (let r = 0; r < FL.h; ++r) { for (let c = 0; c < FL.w; ++c) { dv.setInt16(o + 24 + (r * FL.w + c) * 2, floorMm(c, r), true); } } } return dv; } // --- Phan 1: app.js giai khoi ---------------------------------------------- const el = () => ({ textContent: '', className: '', value: '', checked: false, style: {}, width: 0, height: 0, clientWidth: 800, clientHeight: 600, addEventListener() {}, getContext: () => ctx2d(), classList: { toggle() {}, add() {}, remove() {} }, appendChild() {}, querySelectorAll: () => [], getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600 }), }); const ctx2d = () => new Proxy({}, { get: (t, k) => (k === 'canvas' ? el() : () => ({ data: new Uint8ClampedArray(4) })), }); const ws = { readyState: 1, send() {} }; const sbApp = { console, Date, Math, JSON, Set, Map, Number, String, Array, Object, Float32Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, DataView, ArrayBuffer, isNaN, parseFloat, parseInt, document: { getElementById: () => el(), querySelectorAll: () => [], querySelector: () => el(), addEventListener() {}, createElement: () => el(), body: el(), documentElement: el(), }, window: { addEventListener() {}, devicePixelRatio: 1, location: { search: '', host: 'x' } }, location: { search: '', host: 'x', protocol: 'http:' }, navigator: { userAgent: 'node' }, requestAnimationFrame: () => 0, setInterval: () => 0, setTimeout: () => 0, clearTimeout: () => 0, fetch: () => new Promise(() => {}), URLSearchParams: class { constructor() {} get() { return null; } }, WebSocket: function () { return ws; }, performance: { now: () => 0 }, // rasterize() cua app.js dung ImageData khi nhan khung ban do. ImageData: function (w, h) { this.width = w; this.height = h; this.data = new Uint8ClampedArray(w * h * 4); }, }; sbApp.globalThis = sbApp; vm.createContext(sbApp); try { vm.runInContext(fs.readFileSync(path.join(WWW, 'app.js'), 'utf8'), sbApp, { filename: 'app.js' }); } catch (e) { console.log(' (app.js dung som: ' + e.message + ')'); } let state = null; try { state = vm.runInContext('state', sbApp); } catch (e) { /* bao o duoi */ } if (typeof sbApp.onBinary !== 'function' || !state) { console.log(' KHONG lay duoc onBinary/state tu app.js\n\n => HONG'); process.exit(1); } sbApp.onBinary(mapFrame(true)); const g = state.map; check('giai: co ban do', g && g.w === MAP.w && g.h === MAP.h); const f = g && g.floor; check('giai: co khoi san', f && f.w === FL.w && f.h === FL.h, JSON.stringify(f && { w: f.w, h: f.h })); if (f) { check('giai: res/goc', Math.abs(f.res - 0.2) < 1e-6 && Math.abs(f.ox - MAP.ox) < 1e-6 && Math.abs(f.oy - MAP.oy) < 1e-6); check('giai: san tren', f.mm[2 * FL.w + 9] === 1500, String(f.mm[2 * FL.w + 9])); check('giai: o chua biet', f.mm[4 * FL.w + 3] === -32768, String(f.mm[4 * FL.w + 3])); } // Luoi 2D khong bi khoi phia sau lam lech. check('giai: o 2D dung', g && g.cells.every((v) => v === 0)); sbApp.onBinary(mapFrame(false)); check('khong khoi: floor = null', state.map && state.map.floor === null); // --- Phan 2: app3d.js uon mat phang + nang scan/cloud/quy dao -------------- class V3 { constructor(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; } set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; } } const node = () => ({ position: new V3(), rotation: { x: 0, y: 0, z: 0 }, userData: {}, visible: true }); class Attr { constructor(a, n) { this.array = a; this.itemSize = n; this.count = a.length / n; } getX(i) { return this.array[i * 3]; } getY(i) { return this.array[i * 3 + 1]; } setZ(i, v) { this.array[i * 3 + 2] = v; } } // Bo cuc dinh y het three.js PlaneGeometry: hang tu +h/2 xuong -h/2, cot tu // -w/2 sang +w/2, mat phang z = 0. class PlaneGeometry { constructor(w, h, sx = 1, sy = 1) { const a = []; for (let iy = 0; iy <= sy; ++iy) { for (let ix = 0; ix <= sx; ++ix) a.push(ix * w / sx - w / 2, -(iy * h / sy - h / 2), 0); } this.attributes = { position: new Attr(new Float32Array(a), 3) }; } dispose() {} } class BufferGeometry { constructor() { this.attributes = {}; } setAttribute(n, a) { this.attributes[n] = a; } setFromPoints(p) { this.points = p; return this; } dispose() {} } const obj = () => class { constructor(g, m) { Object.assign(this, node()); this.geometry = g; this.material = m; } }; const THREE = { PlaneGeometry, BufferGeometry, Vector3: V3, BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } }, Mesh: obj(), Points: obj(), Line: obj(), MeshBasicMaterial: class { constructor(o) { Object.assign(this, o); } dispose() {} }, PointsMaterial: class { constructor(o) { Object.assign(this, o); } }, LineBasicMaterial: class { constructor(o) { Object.assign(this, o); } }, CanvasTexture: class { dispose() {} }, NearestFilter: 1, LinearMipmapLinearFilter: 2, }; class Root { constructor() { this.children = []; } add(c) { this.children.push(c); } remove(c) { this.children = this.children.filter((x) => x !== c); } } const canvas = () => ({ width: 0, height: 0, getContext: () => ({ createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }), putImageData() {}, }), }); const sb3 = { THREE, console, Math, Int16Array, Int32Array, Float32Array, window: {}, document: { createElement: canvas } }; vm.createContext(sb3); vm.runInContext(fs.readFileSync(path.join(WWW, 'app3d.js'), 'utf8') + '\n;this.__V3D = V3D; this.__at = v3dFloorAt; this.__fill = v3dFloorFill;' + '\n;this.__map = v3dSetMap; this.__scan = v3dSetScan; this.__cloud = v3dSetCloud;' + '\n;this.__path = v3dSetPath; this.__render = v3dRender; this.__lift = FLOOR_LIFT;' + '\n;this.__worldVis = v3dSetWorldVisible; this.__ground = v3dSetGround;', sb3); const V3D = sb3.__V3D; V3D.ready = true; V3D.root = new Root(); const L = sb3.__lift; // mat ban do uon nang len tren san uoc luong check('nang: 2-10 cm', L >= 0.02 && L <= 0.1, String(L)); // v3dFloorAt: tam o tra dung gia tri o; giua hai tam noi suy tuyen tinh. { const fl = f; const cx = (c) => MAP.ox + (c + 0.5) * 0.2, cy = (r) => MAP.oy + (r + 0.5) * 0.2; check('at: tam o san duoi', near(sb3.__at(fl, cx(0), cy(1)), 0.0, 1e-6)); check('at: tam o san tren', near(sb3.__at(fl, cx(9), cy(1)), 1.5, 1e-6)); // Giua tam cot 4 (0.4) va cot 5 (0.6) -> 0.5. check('at: noi suy tren doc', near(sb3.__at(fl, cx(4) + 0.1, cy(1)), 0.5, 1e-6), String(sb3.__at(fl, cx(4) + 0.1, cy(1)))); // Chi o chua biet -> null (khong phai 0). check('at: chua biet = null', sb3.__at(fl, cx(3), cy(4)) === null, String(sb3.__at(fl, cx(3), cy(4)))); check('at: ngoai luoi = null', sb3.__at(fl, MAP.ox - 5, cy(1)) === null); check('at: khong co luoi = null', sb3.__at(null, 0, 0) === null); // Lap o chua biet bang o DA BIET gan nhat: hang 4 lay hang 3. const filled = sb3.__fill(fl); check('fill: khong con o chua biet', filled && filled.mm.every((v) => v !== -32768)); check('fill: lay o ke', filled && filled.mm[4 * FL.w + 9] === 1500 && filled.mm[4 * FL.w + 4] === 400, filled && String(filled.mm.slice(40))); check('fill: khong dong vao luoi goc', fl.mm[4 * FL.w + 9] === -32768); } // v3dSetMap: dinh mat phang o dung cao do san, dung chieu doc. { sb3.__map({ ...g, data: g.cells, floor: f }); const m = V3D.mapMesh; check('map: co mesh', !!m); if (m) { check('map: quay -PI/2 quanh X', Math.abs(m.rotation.x + Math.PI / 2) < 1e-9); const p = m.geometry.attributes.position; check('map: chia doan theo luoi san', p.count === (FL.w + 1) * (FL.h + 1), String(p.count)); // Dinh cuc bo -> ROS: x = pos.x + lx, y = -pos.z + ly, z = pos.y + lz. const ros = (i) => [m.position.x + p.getX(i), -m.position.z + p.getY(i), m.position.y + p.array[i * 3 + 2]]; const zAt = (qx, qy) => { for (let i = 0; i < p.count; ++i) { const [x, y, z] = ros(i); if (Math.abs(x - qx) < 1e-4 && Math.abs(y - qy) < 1e-4) return z; } return null; }; let maxEast = -1e9, maxWest = -1e9; for (let i = 0; i < p.count; ++i) { const [x, , z] = ros(i); if (x > MAP.ox + 1.9) maxEast = Math.max(maxEast, z); if (x < MAP.ox + 0.1) maxWest = Math.max(maxWest, z); } // Ca mat nang L tren san uoc luong (khong chim duoi mesh san that). check('map: nang L', Math.abs(m.position.y - L) < 1e-9, String(m.position.y)); check('map: co co mapHasFloor', V3D.mapHasFloor === true); // Chieu x: mep dong (cot 9, san tren) ~1.5; mep tay (san duoi) ~0. check('map: mep dong o san tren', Math.abs(maxEast - (1.5 + L)) < 0.01, String(maxEast)); check('map: mep tay o san duoi', Math.abs(maxWest - L) < 0.01, String(maxWest)); // Chieu y: ho o goc tay-NAM (y nho), goc tay-BAC phang. const sw = zAt(MAP.ox, MAP.oy), nw = zAt(MAP.ox, MAP.oy + 1.0); check('map: ho o goc tay-nam', near(sw, -0.1 + L, 1e-3), String(sw)); check('map: goc tay-bac phang', near(nw, L, 1e-3), String(nw)); // Dinh tai x = ox + 1.0 (ranh cot 4|5) tren hang giua: (0.4 + 0.6) / 2. const mid = zAt(MAP.ox + 1.0, MAP.oy + 0.4); check('map: dinh giua doc', near(mid, 0.5 + L, 1e-3), String(mid)); } // Cung mang o -> khong dung lai; mang moi -> dung lai. const truoc = V3D.mapMesh; sb3.__map({ ...g, data: g.cells, floor: f }); check('map: cung du lieu khong dung lai', V3D.mapMesh === truoc); sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); check('map: du lieu moi dung lai', V3D.mapMesh !== truoc); const pf = V3D.mapMesh.geometry.attributes.position; check('map: khong san -> phang', pf.count === 4 && [0, 1, 2, 3].every((i) => pf.array[i * 3 + 2] === 0)); // Ban do phang giu nguyen cao do cu (duoi luoi va vanh cliff). check('map: khong san -> y cu', V3D.mapMesh.position.y === -0.002 && V3D.mapHasFloor === false, String(V3D.mapMesh.position.y)); } // Scan/cloud nang theo cao do san duoi robot; quy dao theo luoi san. { const r = { laser_x: 0.24, laser_y: 0, laser_z: 0.1415, wheel_radius: 0.075 }; sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 1.5 }, r); const sy = V3D.scanPts.geometry.attributes.position.array[1]; check('scan: nang theo z', Math.abs(sy - (1.5 + 0.1415 + 0.075)) < 1e-6, String(sy)); sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0 }, r); const sy0 = V3D.scanPts.geometry.attributes.position.array[1]; check('scan: khong z -> nhu cu', Math.abs(sy0 - (0.1415 + 0.075)) < 1e-6, String(sy0)); sb3.__cloud(new Float32Array([1.0, 0.0, 0.3]), { x: 0, y: 0, yaw: 0, z: 1.5 }); const cy = V3D.cloudPts.geometry.attributes.position.array[1]; check('cloud: nang theo z', Math.abs(cy - 1.8) < 1e-6, String(cy)); // Scan THO nghieng theo than: doc 15 do mui NGANG len (pitch ROS am). // Diem 1 m truoc LiDAR: he footprint (1.24, 0, 0.2165) quay Ry(-15 do). const P = -15 * Math.PI / 180; sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 0.5, pitch: P }, r); const a = V3D.scanPts.geometry.attributes.position.array; const ex = 1.24 * Math.cos(P) + 0.2165 * Math.sin(P); const ez = -1.24 * Math.sin(P) + 0.2165 * Math.cos(P); check('scan: pitch keo diem truoc len', Math.abs(a[0] - ex) < 1e-6 && Math.abs(a[1] - (0.5 + ez)) < 1e-6, a[0] + ', ' + a[1]); // Roll +10 do (ROS: ben TRAI len): diem 1 m ben trai cao hon goc LiDAR. const R = 10 * Math.PI / 180; sb3.__scan(new Float32Array([0.0, 1.0]), { x: 0, y: 0, yaw: 0, roll: R }, r); const b = V3D.scanPts.geometry.attributes.position.array; check('scan: roll keo ben trai len', Math.abs(b[1] - (Math.sin(R) + 0.2165 * Math.cos(R))) < 1e-6 && Math.abs(b[2] + (Math.cos(R) - 0.2165 * Math.sin(R))) < 1e-6, b[1] + ', ' + b[2]); const cx = (c) => MAP.ox + (c + 0.5) * 0.2, yy = MAP.oy + 0.3; sb3.__path([cx(0), yy, cx(9), yy], f); const pts = V3D.pathLine.geometry.points; // Tren mat ban do uon (nang L) 1 cm. check('path: diem san duoi', pts && Math.abs(pts[0].y - (L + 0.01)) < 1e-6, pts && String(pts[0].y)); check('path: diem san tren', pts && Math.abs(pts[1].y - (1.5 + L + 0.01)) < 1e-6, pts && String(pts[1].y)); sb3.__path([cx(0), yy, cx(9), yy], null); const pts0 = V3D.pathLine.geometry.points; check('path: khong luoi -> 0.01 nhu cu', pts0 && pts0.every((q) => Math.abs(q.y - 0.01) < 1e-9)); } // v3dRender: tam quay bam CAO DO robot khi "bam robot"; nua SLAM an mat san // the gioi khi ban do co do cao san. { const calls = []; V3D.floorMesh = { visible: true }; V3D.renderer = { setSize() {}, setScissorTest() {}, setViewport() {}, setScissor() {}, render() { calls.push(V3D.floorMesh.visible); }, }; V3D.camera = { aspect: 1, updateProjectionMatrix() {}, position: new V3(), lookAt(x, y, z) { this.look = [x, y, z]; } }; V3D.robotGroup = { position: new V3(2, 1.5, -3) }; const cv = { clientWidth: 800, clientHeight: 600, width: 800, height: 600 }; const o = V3D.orbit; sb3.__map({ ...g, data: new Int8Array(g.cells), floor: f }); // co san sb3.__render(cv, true, true); check('render: tam quay o cao do robot', Math.abs(V3D.camera.look[1] - 1.7) < 1e-9, String(V3D.camera.look)); check('render: camera nang theo robot', Math.abs(V3D.camera.position.y - (1.5 + o.dist * Math.sin(o.el))) < 1e-9); check('render: nua the gioi CO san, nua SLAM KHONG', calls.length === 2 && calls[0] === true && calls[1] === false, JSON.stringify(calls)); check('render: tra lai san sau khi ve', V3D.floorMesh.visible === true); calls.length = 0; sb3.__render(cv, false, true); check('render: khong bam -> tam quay 0.2 nhu cu', Math.abs(V3D.camera.look[1] - 0.2) < 1e-9, String(V3D.camera.look)); // Tat "the gioi": ban do co san -> an mat san z = 0; bat lai -> hien. sb3.__worldVis(false); check('tat the gioi + co san -> an mat san', V3D.floorMesh.visible === false); sb3.__worldVis(true); check('bat the gioi -> hien mat san', V3D.floorMesh.visible === true); calls.length = 0; sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); // ban do phang sb3.__render(cv, false, true); check('render: ban do phang -> nua SLAM van co san', calls[1] === true, JSON.stringify(calls)); sb3.__worldVis(false); check('tat the gioi + ban do phang -> giu mat san nhu cu', V3D.floorMesh.visible === true); } // v3dSetGround: duoc goi MOI khung khi chay tu `.world`. Cung luoi -> KHONG // dung lai (ban cu dung lai moi khung va ro GridHelper tren GPU); luoi moi -> // dung lai va giai phong ca geometry lan material cu. { let disposed = 0; const disp = () => { disposed++; }; THREE.GridHelper = class { constructor() { Object.assign(this, node()); this.geometry = { dispose: disp }; this.material = { dispose: disp }; } }; THREE.MeshStandardMaterial = class { constructor(o) { Object.assign(this, o); } dispose() { disp(); } }; V3D.scene = { fog: { near: 0, far: 0 } }; V3D.floorMesh = null; V3D.gridHelper = null; const wg = { res: 0.05, w: 400, h: 600, ox: -1, oy: -2 }; sb3.__ground(wg); const f1 = V3D.floorMesh, g1 = V3D.gridHelper; const n0 = V3D.root.children.length; for (let i = 0; i < 100; ++i) sb3.__ground(wg); check('ground: cung luoi khong dung lai', V3D.floorMesh === f1 && V3D.gridHelper === g1 && disposed === 0, String(disposed)); check('ground: root khong phinh', V3D.root.children.length === n0); check('ground: suong mu theo bao the gioi', Math.abs(V3D.scene.fog.far - 30 * 1.4) < 1e-9, String(V3D.scene.fog.far)); f1.geometry.dispose = disp; sb3.__ground({ ...wg, w: 500 }); check('ground: luoi moi dung lai', V3D.floorMesh !== f1 && V3D.gridHelper !== g1); check('ground: giai phong san + luoi cu (geometry + material)', disposed === 4, String(disposed)); check('ground: root van 1 san 1 luoi', V3D.root.children.length === n0 && !V3D.root.children.includes(f1) && !V3D.root.children.includes(g1)); } console.log(bad ? '\n => HONG' : '\n => DAT'); process.exit(bad ? 1 : 0);