wasm-engine.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /**
  2. * Rust WebAssembly rendering bridge and complete JavaScript geometry picking.
  3. * (`board-accel.wasm` compiled from `tools/board-viewer/rust-accel/src/lib.rs`).
  4. *
  5. * Provides:
  6. * - Zero-allocation (post-init) 32x8 uniform spatial grid in WASM linear memory
  7. * - Sub-30us viewport frustum culling + Level-of-Detail (LOD) batch buffer generation
  8. * - Complete JS scan for pins, resistor pads, resistors, and connectors
  9. * - Picking works with or without WASM; rendering acceleration remains optional
  10. */
  11. export const CAT_BIT = {
  12. CON: 1,
  13. J: 2,
  14. PL: 4,
  15. TP: 8,
  16. R: 16,
  17. };
  18. export const ROLE_CODE = {
  19. contact: 0,
  20. electrical: 0,
  21. shield: 1,
  22. mechanical: 2,
  23. unknown: 3,
  24. };
  25. export const SIDE_CODE = {
  26. front: 0,
  27. back: 1,
  28. both: 2,
  29. };
  30. export function categoriesToMask(categoriesSet) {
  31. let mask = 0;
  32. if (!categoriesSet) return mask;
  33. for (const cat of categoriesSet) {
  34. mask |= CAT_BIT[cat] || 0;
  35. }
  36. return mask;
  37. }
  38. export function isShieldPinHelper(pin) {
  39. if (!pin) return false;
  40. const num = String(pin.number || "").trim().toUpperCase();
  41. if (num.startsWith("SH")) return true;
  42. if (pin.pad_role === "shield") return true;
  43. if (pin.pad_role === "mechanical" && (num.startsWith("SH") || num.startsWith("MH") || num === "")) {
  44. return true;
  45. }
  46. return false;
  47. }
  48. export class BoardWasmAccelerator {
  49. constructor() {
  50. this.wasm = null;
  51. this.memory = null;
  52. this.ready = false;
  53. this.engineType = "JS-Fallback";
  54. this.lastCullMs = 0;
  55. this.lastDrawMs = 0;
  56. this.lastVisibleCount = 0;
  57. this.lastCulledCount = 0;
  58. this.totalIndexedCount = 0;
  59. this.boardData = null;
  60. }
  61. async init(wasmSource = "/board-accel.wasm") {
  62. if (this.ready) return true;
  63. try {
  64. let instance;
  65. if (wasmSource instanceof ArrayBuffer || ArrayBuffer.isView(wasmSource)) {
  66. const res = await WebAssembly.instantiate(wasmSource, {});
  67. instance = res.instance || res;
  68. } else {
  69. const response = await fetch(wasmSource);
  70. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  71. if (WebAssembly.instantiateStreaming) {
  72. try {
  73. const res = await WebAssembly.instantiateStreaming(response, {});
  74. instance = res.instance;
  75. } catch {
  76. const bytes = await (await fetch(wasmSource)).arrayBuffer();
  77. const res = await WebAssembly.instantiate(bytes, {});
  78. instance = res.instance;
  79. }
  80. } else {
  81. const bytes = await response.arrayBuffer();
  82. const res = await WebAssembly.instantiate(bytes, {});
  83. instance = res.instance;
  84. }
  85. }
  86. this.wasm = instance.exports;
  87. this.memory = instance.exports.memory;
  88. this.ready = true;
  89. this.engineType = "Rust-WASM";
  90. return true;
  91. } catch {
  92. this.ready = false;
  93. this.engineType = "JS-HitTest";
  94. return false;
  95. }
  96. }
  97. /**
  98. * Populate the Rust WASM 32x8 spatial grid from boardData.
  99. */
  100. buildIndex(boardData) {
  101. this.boardData = boardData;
  102. if (!boardData) return;
  103. const width = Number(boardData.board?.view_box?.width) || 430;
  104. const height = Number(boardData.board?.view_box?.height) || 75;
  105. const tps = boardData.touchpoints || [];
  106. const resistors = boardData.resistors || [];
  107. let estimatedCap = tps.length + resistors.length * 3;
  108. for (const tp of tps) estimatedCap += (tp.pins?.length || 0);
  109. if (this.ready && this.wasm) {
  110. this.wasm.wasm_clear_world(width, height, estimatedCap);
  111. let count = 0;
  112. for (let ti = 0; ti < tps.length; ti++) {
  113. const tp = tps[ti];
  114. const catBit = CAT_BIT[tp.category] || 1;
  115. const sideCode = SIDE_CODE[tp.side] ?? 0;
  116. const vb = tp.view_bounds || {x: 0, y: 0, width: 1.2, height: 1.2};
  117. const bw = Math.max(Number(vb.width) || 1.2, 1.2);
  118. const bh = Math.max(Number(vb.height) || 1.2, 1.2);
  119. const cx = Number(vb.x) + (Number(vb.width) || 0) * 0.5;
  120. const cy = Number(vb.y) + (Number(vb.height) || 0) * 0.5;
  121. // Kind 1: Touchpoint hotspot
  122. this.wasm.wasm_add_item(
  123. cx,
  124. cy,
  125. bw,
  126. bh,
  127. 0.0,
  128. 1,
  129. sideCode,
  130. catBit,
  131. 0,
  132. 0,
  133. 0,
  134. ti,
  135. 0xffff,
  136. );
  137. count++;
  138. const pins = tp.pins || [];
  139. for (let pi = 0; pi < pins.length; pi++) {
  140. const pin = pins[pi];
  141. const pw = Number(pin.size?.width) || 1.4;
  142. const ph = Number(pin.size?.height) || 1.4;
  143. const rot = Number(pin.rotation || 0);
  144. const isRound =
  145. pin.shape === "circle" || (!pin.shape && Math.abs(pw - ph) < 0.05) ? 1 : 0;
  146. const role = ROLE_CODE[pin.pad_role] ?? 3;
  147. const isSh = isShieldPinHelper(pin) ? 1 : 0;
  148. const px = Number(pin.view_position?.x) || 0;
  149. const py = Number(pin.view_position?.y) || 0;
  150. // Kind 2: Touchpoint pin
  151. this.wasm.wasm_add_item(
  152. px,
  153. py,
  154. pw,
  155. ph,
  156. rot,
  157. 2,
  158. sideCode,
  159. catBit,
  160. isRound,
  161. role,
  162. isSh,
  163. ti,
  164. pi,
  165. );
  166. count++;
  167. }
  168. }
  169. for (let ri = 0; ri < resistors.length; ri++) {
  170. const res = resistors[ri];
  171. const sideCode = SIDE_CODE[res.side] ?? 0;
  172. const vb = res.view_bounds || {x: 0, y: 0, width: 0.4, height: 0.4};
  173. const bw = Math.max(Number(vb.width) || 0.4, 0.4);
  174. const bh = Math.max(Number(vb.height) || 0.4, 0.4);
  175. const cx = Number(vb.x) + (Number(vb.width) || 0) * 0.5;
  176. const cy = Number(vb.y) + (Number(vb.height) || 0) * 0.5;
  177. // Kind 3: Resistor hotspot
  178. this.wasm.wasm_add_item(
  179. cx,
  180. cy,
  181. bw,
  182. bh,
  183. 0.0,
  184. 3,
  185. sideCode,
  186. CAT_BIT.R,
  187. 0,
  188. 0,
  189. 0,
  190. ri,
  191. 0xffff,
  192. );
  193. count++;
  194. const pads = res.pads || [];
  195. for (let pi = 0; pi < pads.length; pi++) {
  196. const pad = pads[pi];
  197. const pw = Number(pad.size?.width) || 0.55;
  198. const ph = Number(pad.size?.height) || 0.75;
  199. const rot = Number(pad.rotation || res.rotation || 0);
  200. const role = ROLE_CODE[pad.pad_role] ?? 0;
  201. const px = Number(pad.view_position?.x) || 0;
  202. const py = Number(pad.view_position?.y) || 0;
  203. // Kind 4: Resistor pad
  204. this.wasm.wasm_add_item(
  205. px,
  206. py,
  207. pw,
  208. ph,
  209. rot,
  210. 4,
  211. sideCode,
  212. CAT_BIT.R,
  213. 0,
  214. role,
  215. 0,
  216. ri,
  217. pi,
  218. );
  219. count++;
  220. }
  221. }
  222. this.totalIndexedCount = count;
  223. } else {
  224. this.totalIndexedCount = estimatedCap;
  225. }
  226. }
  227. /**
  228. * Scan all indexed geometry for picking. The WASM center grid can omit a
  229. * wide item's edge, even when another lower-priority item was found nearby.
  230. * Keep the same pad/body priority, distance, mirror and visibility rules.
  231. */
  232. hitTest(xMm, yMm, boardSide, categoriesSet, showShield, zoomRatio = 1.0) {
  233. if (!this.boardData) return null;
  234. const sideCode = boardSide === "back" ? 1 : 0;
  235. const width = Number(this.boardData.board?.view_box?.width) || 430;
  236. const rawX = sideCode === 1 ? width - xMm : xMm;
  237. const catMask = categoriesToMask(categoriesSet);
  238. const extraMargin = Math.min(Math.max(0.35 / Math.max(zoomRatio, 0.5), 0.04), 0.35);
  239. let best = null;
  240. let bestPriority = 0;
  241. let bestDistance = Infinity;
  242. const consider = (x, y, w, h, rotation, round, priority, result) => {
  243. const dx = rawX - x;
  244. const dy = yMm - y;
  245. const radians = rotation * Math.PI / 180;
  246. const cos = Math.cos(radians);
  247. const sin = Math.sin(radians);
  248. const lx = dx * cos + dy * sin;
  249. const ly = -dx * sin + dy * cos;
  250. const hw = Math.max(w, 0.15) * 0.5 + extraMargin;
  251. const hh = Math.max(h, 0.15) * 0.5 + extraMargin;
  252. const inside = round
  253. ? lx * lx + ly * ly <= Math.max(hw, hh) ** 2
  254. : Math.abs(lx) <= hw && Math.abs(ly) <= hh;
  255. const distance = dx * dx + dy * dy;
  256. if (inside && (priority > bestPriority || (priority === bestPriority && distance < bestDistance))) {
  257. best = result;
  258. bestPriority = priority;
  259. bestDistance = distance;
  260. }
  261. };
  262. const scan = (item, isResistor) => {
  263. const side = SIDE_CODE[item.side] ?? 0;
  264. const category = isResistor ? CAT_BIT.R : (CAT_BIT[item.category] || CAT_BIT.CON);
  265. if ((side !== 2 && side !== sideCode) || !(category & catMask)) return;
  266. const minBody = isResistor ? 0.4 : 1.2;
  267. const bounds = item.view_bounds || {x: 0, y: 0, width: minBody, height: minBody};
  268. const bodyWidth = Number(bounds.width) || 0;
  269. const bodyHeight = Number(bounds.height) || 0;
  270. consider(Number(bounds.x) + bodyWidth * 0.5, Number(bounds.y) + bodyHeight * 0.5,
  271. Math.max(bodyWidth, minBody), Math.max(bodyHeight, minBody), 0, false, isResistor ? 2 : 1,
  272. isResistor ? {kind: "resistor", resistor: item, pad: null} : {kind: "touchpoint", touchpoint: item, pin: null});
  273. for (const pad of (isResistor ? item.pads : item.pins) || []) {
  274. const shield = !isResistor && isShieldPinHelper(pad);
  275. const role = ROLE_CODE[pad.pad_role] ?? (isResistor ? 0 : 3);
  276. if ((shield && !showShield) || (role === 2 && !shield)) continue;
  277. const w = Number(pad.size?.width) || (isResistor ? 0.55 : 1.4);
  278. const h = Number(pad.size?.height) || (isResistor ? 0.75 : 1.4);
  279. const rotation = Number(pad.rotation || (isResistor ? item.rotation : 0) || 0);
  280. const round = !isResistor && (pad.shape === "circle" || (!pad.shape && Math.abs(w - h) < 0.05));
  281. consider(Number(pad.view_position?.x) || 0, Number(pad.view_position?.y) || 0,
  282. w, h, rotation, round, 3,
  283. isResistor ? {kind: "resistor_pad", resistor: item, pad} : {kind: "pin", touchpoint: item, pin: pad});
  284. }
  285. };
  286. for (const item of this.boardData.touchpoints || []) scan(item, false);
  287. for (const item of this.boardData.resistors || []) scan(item, true);
  288. return best;
  289. }
  290. /**
  291. * Frustum-cull and return a Float32Array view into WASM memory for ultra-fast Canvas 2D rendering.
  292. */
  293. cullViewport(viewBox, boardSide, categoriesSet, showShield, zoomRatio, selectionState) {
  294. const t0 = performance.now();
  295. if (!this.ready || !this.wasm || !viewBox) {
  296. this.lastCullMs = 0;
  297. return null;
  298. }
  299. const sideCode = boardSide === "back" ? 1 : 0;
  300. const catMask = categoriesToMask(categoriesSet);
  301. const shieldFlag = showShield ? 1 : 0;
  302. let selKind = 0;
  303. let selOwner = -1;
  304. let selSub = -1;
  305. if (selectionState?.selectedResistor) {
  306. selKind = 3;
  307. selOwner = selectionState.resistorIndex ?? -1;
  308. selSub = selectionState.padIndex ?? -1;
  309. } else if (selectionState?.selectedTouchpoint) {
  310. selKind = 1;
  311. selOwner = selectionState.touchpointIndex ?? -1;
  312. selSub = selectionState.pinIndex ?? -1;
  313. }
  314. const visibleCount = this.wasm.wasm_cull_viewport(
  315. viewBox.x,
  316. viewBox.y,
  317. viewBox.width,
  318. viewBox.height,
  319. sideCode,
  320. catMask,
  321. shieldFlag,
  322. zoomRatio,
  323. selKind,
  324. selOwner,
  325. selSub,
  326. );
  327. const statsPtr = this.wasm.wasm_stats_ptr() >>> 2;
  328. const u32 = new Uint32Array(this.memory.buffer);
  329. this.totalIndexedCount = u32[statsPtr];
  330. this.lastVisibleCount = u32[statsPtr + 1];
  331. this.lastCulledCount = u32[statsPtr + 2];
  332. const bufPtr = this.wasm.wasm_render_buf_ptr() >>> 2;
  333. const f32 = new Float32Array(this.memory.buffer, bufPtr * 4, visibleCount * 8);
  334. this.lastCullMs = performance.now() - t0;
  335. return {count: visibleCount, buffer: f32};
  336. }
  337. }