| Render in parallel on web, via a pool of Web Workers 4506a58 nandithebull 8h ago | 1 | // One Mandelbrot band, computed in its own wasm instance. |
| 2 | // |
| 3 | // Each worker instantiates its own copy of the module. That is the whole |
| 4 | // reason this needs no SharedArrayBuffer and no COOP/COEP headers: nothing is |
| 5 | // shared, so there is nothing to synchronise. The wasm is ~34 KB, so N copies |
| 6 | // is cheap. |
| 7 | importScripts('nimflutter.js'); |
| 8 | |
| 9 | const SIG = ['number', 'number', 'number', 'number', 'number', |
| 10 | 'number', 'number', 'number', 'number', 'number']; |
| 11 | |
| 12 | let mod = null; |
| 13 | const ready = createNimFlutterModule().then((m) => { |
| 14 | mod = m; |
| 15 | m.ccall('nf_init', null, [], []); |
| 16 | }); |
| 17 | |
| 18 | self.onmessage = async (e) => { |
| 19 | await ready; |
| 20 | const { id, w, h, cx, cy, scale, iter, y0, y1 } = e.data; |
| 21 | |
| 22 | const bytes = (y1 - y0) * w * 4; |
| 23 | const buf = mod._malloc(bytes); |
| 24 | try { |
| 25 | mod.ccall('nf_mandelbrot', null, SIG, |
| 26 | [buf, bytes, w, h, cx, cy, scale, iter, y0, y1]); |
| 27 | // .slice() copies out of the wasm heap, which may be detached by a later |
| 28 | // growth; the copy is then transferred rather than structured-cloned. |
| 29 | const band = mod.HEAPU8.slice(buf, buf + bytes); |
| 30 | self.postMessage({ id, y0, band }, [band.buffer]); |
| 31 | } finally { |
| 32 | mod._free(buf); |
| 33 | } |
| 34 | }; |