// A worker pool for band rendering, exposed to Dart as one promise-returning // function. // // The pool lives here rather than in Dart because dart:js_interop has no // ergonomic Worker binding, and because the interesting part — a work queue // feeding N workers — is the same code in either language. (function () { const workers = []; const idle = []; let nextId = 1; let poolSize = 0; // More bands than cores is deliberate: bands cost wildly different amounts // (interior rows run the full iteration cap), so over-decomposing keeps a // free worker busy instead of waiting on the slowest band. Same finding as // `just sweep` on native. const maxWorkers = Math.max(1, (self.navigator && self.navigator.hardwareConcurrency) || 4); function grow(n) { const want = Math.min(n, maxWorkers); while (workers.length < want) { const w = new Worker('nimflutter_worker.js'); w.pending = new Map(); w.onmessage = (e) => { const resolve = w.pending.get(e.data.id); if (!resolve) return; w.pending.delete(e.data.id); resolve(e.data); }; workers.push(w); idle.push(w); } poolSize = workers.length; } function run(worker, job) { return new Promise((resolve) => { worker.pending.set(job.id, resolve); worker.postMessage(job); }); } self.nimflutterPoolSize = () => poolSize; self.nimflutterRenderParallel = function (w, h, cx, cy, scale, iter, tiles) { const count = Math.max(1, Math.min(tiles, h)); grow(count); const rowsPer = Math.ceil(h / count); const queue = []; for (let t = 0; t < count; t++) { const y0 = t * rowsPer; const y1 = Math.min((t + 1) * rowsPer, h); if (y0 >= y1) break; queue.push({ id: nextId++, w, h, cx, cy, scale, iter, y0, y1 }); } const out = new Uint8Array(w * h * 4); // Hand each worker the next band as it frees up, rather than dealing the // whole deck up front — that is what turns uneven band costs into a // balanced schedule. const pump = (worker) => { const job = queue.shift(); if (!job) return Promise.resolve(); return run(worker, job).then((res) => { out.set(res.band, res.y0 * w * 4); return pump(worker); }); }; return Promise.all(workers.map(pump)).then(() => out); }; })();