/** * Rust WebAssembly rendering bridge and complete JavaScript geometry picking. * (`board-accel.wasm` compiled from `tools/board-viewer/rust-accel/src/lib.rs`). * * Provides: * - Zero-allocation (post-init) 32x8 uniform spatial grid in WASM linear memory * - Sub-30us viewport frustum culling + Level-of-Detail (LOD) batch buffer generation * - Complete JS scan for pins, resistor pads, resistors, and connectors * - Picking works with or without WASM; rendering acceleration remains optional */ export const CAT_BIT = { CON: 1, J: 2, PL: 4, TP: 8, R: 16, }; export const ROLE_CODE = { contact: 0, electrical: 0, shield: 1, mechanical: 2, unknown: 3, }; export const SIDE_CODE = { front: 0, back: 1, both: 2, }; export function categoriesToMask(categoriesSet) { let mask = 0; if (!categoriesSet) return mask; for (const cat of categoriesSet) { mask |= CAT_BIT[cat] || 0; } return mask; } export function isShieldPinHelper(pin) { if (!pin) return false; const num = String(pin.number || "").trim().toUpperCase(); if (num.startsWith("SH")) return true; if (pin.pad_role === "shield") return true; if (pin.pad_role === "mechanical" && (num.startsWith("SH") || num.startsWith("MH") || num === "")) { return true; } return false; } export class BoardWasmAccelerator { constructor() { this.wasm = null; this.memory = null; this.ready = false; this.engineType = "JS-Fallback"; this.lastCullMs = 0; this.lastDrawMs = 0; this.lastVisibleCount = 0; this.lastCulledCount = 0; this.totalIndexedCount = 0; this.boardData = null; } async init(wasmSource = "/board-accel.wasm") { if (this.ready) return true; try { let instance; if (wasmSource instanceof ArrayBuffer || ArrayBuffer.isView(wasmSource)) { const res = await WebAssembly.instantiate(wasmSource, {}); instance = res.instance || res; } else { const response = await fetch(wasmSource); if (!response.ok) throw new Error(`HTTP ${response.status}`); if (WebAssembly.instantiateStreaming) { try { const res = await WebAssembly.instantiateStreaming(response, {}); instance = res.instance; } catch { const bytes = await (await fetch(wasmSource)).arrayBuffer(); const res = await WebAssembly.instantiate(bytes, {}); instance = res.instance; } } else { const bytes = await response.arrayBuffer(); const res = await WebAssembly.instantiate(bytes, {}); instance = res.instance; } } this.wasm = instance.exports; this.memory = instance.exports.memory; this.ready = true; this.engineType = "Rust-WASM"; return true; } catch { this.ready = false; this.engineType = "JS-HitTest"; return false; } } /** * Populate the Rust WASM 32x8 spatial grid from boardData. */ buildIndex(boardData) { this.boardData = boardData; if (!boardData) return; const width = Number(boardData.board?.view_box?.width) || 430; const height = Number(boardData.board?.view_box?.height) || 75; const tps = boardData.touchpoints || []; const resistors = boardData.resistors || []; let estimatedCap = tps.length + resistors.length * 3; for (const tp of tps) estimatedCap += (tp.pins?.length || 0); if (this.ready && this.wasm) { this.wasm.wasm_clear_world(width, height, estimatedCap); let count = 0; for (let ti = 0; ti < tps.length; ti++) { const tp = tps[ti]; const catBit = CAT_BIT[tp.category] || 1; const sideCode = SIDE_CODE[tp.side] ?? 0; const vb = tp.view_bounds || {x: 0, y: 0, width: 1.2, height: 1.2}; const bw = Math.max(Number(vb.width) || 1.2, 1.2); const bh = Math.max(Number(vb.height) || 1.2, 1.2); const cx = Number(vb.x) + (Number(vb.width) || 0) * 0.5; const cy = Number(vb.y) + (Number(vb.height) || 0) * 0.5; // Kind 1: Touchpoint hotspot this.wasm.wasm_add_item( cx, cy, bw, bh, 0.0, 1, sideCode, catBit, 0, 0, 0, ti, 0xffff, ); count++; const pins = tp.pins || []; for (let pi = 0; pi < pins.length; pi++) { const pin = pins[pi]; const pw = Number(pin.size?.width) || 1.4; const ph = Number(pin.size?.height) || 1.4; const rot = Number(pin.rotation || 0); const isRound = pin.shape === "circle" || (!pin.shape && Math.abs(pw - ph) < 0.05) ? 1 : 0; const role = ROLE_CODE[pin.pad_role] ?? 3; const isSh = isShieldPinHelper(pin) ? 1 : 0; const px = Number(pin.view_position?.x) || 0; const py = Number(pin.view_position?.y) || 0; // Kind 2: Touchpoint pin this.wasm.wasm_add_item( px, py, pw, ph, rot, 2, sideCode, catBit, isRound, role, isSh, ti, pi, ); count++; } } for (let ri = 0; ri < resistors.length; ri++) { const res = resistors[ri]; const sideCode = SIDE_CODE[res.side] ?? 0; const vb = res.view_bounds || {x: 0, y: 0, width: 0.4, height: 0.4}; const bw = Math.max(Number(vb.width) || 0.4, 0.4); const bh = Math.max(Number(vb.height) || 0.4, 0.4); const cx = Number(vb.x) + (Number(vb.width) || 0) * 0.5; const cy = Number(vb.y) + (Number(vb.height) || 0) * 0.5; // Kind 3: Resistor hotspot this.wasm.wasm_add_item( cx, cy, bw, bh, 0.0, 3, sideCode, CAT_BIT.R, 0, 0, 0, ri, 0xffff, ); count++; const pads = res.pads || []; for (let pi = 0; pi < pads.length; pi++) { const pad = pads[pi]; const pw = Number(pad.size?.width) || 0.55; const ph = Number(pad.size?.height) || 0.75; const rot = Number(pad.rotation || res.rotation || 0); const role = ROLE_CODE[pad.pad_role] ?? 0; const px = Number(pad.view_position?.x) || 0; const py = Number(pad.view_position?.y) || 0; // Kind 4: Resistor pad this.wasm.wasm_add_item( px, py, pw, ph, rot, 4, sideCode, CAT_BIT.R, 0, role, 0, ri, pi, ); count++; } } this.totalIndexedCount = count; } else { this.totalIndexedCount = estimatedCap; } } /** * Scan all indexed geometry for picking. The WASM center grid can omit a * wide item's edge, even when another lower-priority item was found nearby. * Keep the same pad/body priority, distance, mirror and visibility rules. */ hitTest(xMm, yMm, boardSide, categoriesSet, showShield, zoomRatio = 1.0) { if (!this.boardData) return null; const sideCode = boardSide === "back" ? 1 : 0; const width = Number(this.boardData.board?.view_box?.width) || 430; const rawX = sideCode === 1 ? width - xMm : xMm; const catMask = categoriesToMask(categoriesSet); const extraMargin = Math.min(Math.max(0.35 / Math.max(zoomRatio, 0.5), 0.04), 0.35); let best = null; let bestPriority = 0; let bestDistance = Infinity; const consider = (x, y, w, h, rotation, round, priority, result) => { const dx = rawX - x; const dy = yMm - y; const radians = rotation * Math.PI / 180; const cos = Math.cos(radians); const sin = Math.sin(radians); const lx = dx * cos + dy * sin; const ly = -dx * sin + dy * cos; const hw = Math.max(w, 0.15) * 0.5 + extraMargin; const hh = Math.max(h, 0.15) * 0.5 + extraMargin; const inside = round ? lx * lx + ly * ly <= Math.max(hw, hh) ** 2 : Math.abs(lx) <= hw && Math.abs(ly) <= hh; const distance = dx * dx + dy * dy; if (inside && (priority > bestPriority || (priority === bestPriority && distance < bestDistance))) { best = result; bestPriority = priority; bestDistance = distance; } }; const scan = (item, isResistor) => { const side = SIDE_CODE[item.side] ?? 0; const category = isResistor ? CAT_BIT.R : (CAT_BIT[item.category] || CAT_BIT.CON); if ((side !== 2 && side !== sideCode) || !(category & catMask)) return; const minBody = isResistor ? 0.4 : 1.2; const bounds = item.view_bounds || {x: 0, y: 0, width: minBody, height: minBody}; const bodyWidth = Number(bounds.width) || 0; const bodyHeight = Number(bounds.height) || 0; consider(Number(bounds.x) + bodyWidth * 0.5, Number(bounds.y) + bodyHeight * 0.5, Math.max(bodyWidth, minBody), Math.max(bodyHeight, minBody), 0, false, isResistor ? 2 : 1, isResistor ? {kind: "resistor", resistor: item, pad: null} : {kind: "touchpoint", touchpoint: item, pin: null}); for (const pad of (isResistor ? item.pads : item.pins) || []) { const shield = !isResistor && isShieldPinHelper(pad); const role = ROLE_CODE[pad.pad_role] ?? (isResistor ? 0 : 3); if ((shield && !showShield) || (role === 2 && !shield)) continue; const w = Number(pad.size?.width) || (isResistor ? 0.55 : 1.4); const h = Number(pad.size?.height) || (isResistor ? 0.75 : 1.4); const rotation = Number(pad.rotation || (isResistor ? item.rotation : 0) || 0); const round = !isResistor && (pad.shape === "circle" || (!pad.shape && Math.abs(w - h) < 0.05)); consider(Number(pad.view_position?.x) || 0, Number(pad.view_position?.y) || 0, w, h, rotation, round, 3, isResistor ? {kind: "resistor_pad", resistor: item, pad} : {kind: "pin", touchpoint: item, pin: pad}); } }; for (const item of this.boardData.touchpoints || []) scan(item, false); for (const item of this.boardData.resistors || []) scan(item, true); return best; } /** * Frustum-cull and return a Float32Array view into WASM memory for ultra-fast Canvas 2D rendering. */ cullViewport(viewBox, boardSide, categoriesSet, showShield, zoomRatio, selectionState) { const t0 = performance.now(); if (!this.ready || !this.wasm || !viewBox) { this.lastCullMs = 0; return null; } const sideCode = boardSide === "back" ? 1 : 0; const catMask = categoriesToMask(categoriesSet); const shieldFlag = showShield ? 1 : 0; let selKind = 0; let selOwner = -1; let selSub = -1; if (selectionState?.selectedResistor) { selKind = 3; selOwner = selectionState.resistorIndex ?? -1; selSub = selectionState.padIndex ?? -1; } else if (selectionState?.selectedTouchpoint) { selKind = 1; selOwner = selectionState.touchpointIndex ?? -1; selSub = selectionState.pinIndex ?? -1; } const visibleCount = this.wasm.wasm_cull_viewport( viewBox.x, viewBox.y, viewBox.width, viewBox.height, sideCode, catMask, shieldFlag, zoomRatio, selKind, selOwner, selSub, ); const statsPtr = this.wasm.wasm_stats_ptr() >>> 2; const u32 = new Uint32Array(this.memory.buffer); this.totalIndexedCount = u32[statsPtr]; this.lastVisibleCount = u32[statsPtr + 1]; this.lastCulledCount = u32[statsPtr + 2]; const bufPtr = this.wasm.wasm_render_buf_ptr() >>> 2; const f32 = new Float32Array(this.memory.buffer, bufPtr * 4, visibleCount * 8); this.lastCullMs = performance.now() - t0; return {count: visibleCount, buffer: f32}; } }