aboutsummaryrefslogtreecommitdiff
path: root/build/js/imaging/dither.js
blob: bd3bffc3f1d5db48c18c120db14fb75cde3e925b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Restricted color modes with dithering.
//
// The image is converted to a float "working" buffer (one luminance channel or three RGB
// channels, values 0..1 in sRGB or linear light). An algorithm rewrites that buffer so
// every value is one of the channel's levels; `finish` then maps each value to its level's
// output color. That last step snaps to the nearest level, so whatever an algorithm (or a
// user script) leaves in the buffer, the result only ever uses the restricted palette.
//
// This module touches no DOM: dither-worker.js imports it to give user scripts the same
// helpers (see scriptApi).

// ------------------------------------------------------------------ color spaces

const srgbToLinear = (u) => (u <= 0.04045 ? u / 12.92 : ((u + 0.055) / 1.055) ** 2.4);
const linearToSrgb = (l) => (l <= 0.0031308 ? l * 12.92 : 1.055 * l ** (1 / 2.4) - 0.055);
const BYTE_TO_LINEAR = Float32Array.from({ length: 256 }, (_, i) => srgbToLinear(i / 255));
const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);

// ------------------------------------------------------------------ levels

/** Index of the level nearest to v (levels ascending). NaN maps to 0. */
export function nearestIndex(levels, v) {
  const n = levels.length;
  if (!(v > levels[0])) return 0;
  if (v >= levels[n - 1]) return n - 1;
  let lo = 0, hi = n - 1; // levels[lo] < v < levels[hi]
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (levels[mid] <= v) lo = mid; else hi = mid;
  }
  return v - levels[lo] < levels[hi] - v ? lo : hi;
}

/** Index k such that levels[k] <= v < levels[k + 1] (clamped to 0..n-2). */
function lowerIndex(levels, v) {
  let lo = 0, hi = levels.length - 1;
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (levels[mid] <= v) lo = mid; else hi = mid;
  }
  return lo;
}

// ------------------------------------------------------------------ error diffusion

/** Kernels as [dx, dy, weight] taps relative to the current pixel; weights / divisor. */
export const KERNELS = {
  'floyd-steinberg': { label: 'Floyd–Steinberg', divisor: 16, taps: [[1, 0, 7], [-1, 1, 3], [0, 1, 5], [1, 1, 1]] },
  atkinson: { label: 'Atkinson', divisor: 8, taps: [[1, 0, 1], [2, 0, 1], [-1, 1, 1], [0, 1, 1], [1, 1, 1], [0, 2, 1]] },
  jarvis: {
    label: 'Jarvis–Judice–Ninke', divisor: 48,
    taps: [[1, 0, 7], [2, 0, 5], [-2, 1, 3], [-1, 1, 5], [0, 1, 7], [1, 1, 5], [2, 1, 3], [-2, 2, 1], [-1, 2, 3], [0, 2, 5], [1, 2, 3], [2, 2, 1]],
  },
  stucki: {
    label: 'Stucki', divisor: 42,
    taps: [[1, 0, 8], [2, 0, 4], [-2, 1, 2], [-1, 1, 4], [0, 1, 8], [1, 1, 4], [2, 1, 2], [-2, 2, 1], [-1, 2, 2], [0, 2, 4], [1, 2, 2], [2, 2, 1]],
  },
  burkes: { label: 'Burkes', divisor: 32, taps: [[1, 0, 8], [2, 0, 4], [-2, 1, 2], [-1, 1, 4], [0, 1, 8], [1, 1, 4], [2, 1, 2]] },
  sierra: {
    label: 'Sierra', divisor: 32,
    taps: [[1, 0, 5], [2, 0, 3], [-2, 1, 2], [-1, 1, 4], [0, 1, 5], [1, 1, 4], [2, 1, 2], [-1, 2, 2], [0, 2, 3], [1, 2, 2]],
  },
  'sierra-2': { label: 'Two-Row Sierra', divisor: 16, taps: [[1, 0, 4], [2, 0, 3], [-2, 1, 1], [-1, 1, 2], [0, 1, 3], [1, 1, 2], [2, 1, 1]] },
  'sierra-lite': { label: 'Sierra Lite', divisor: 4, taps: [[1, 0, 2], [-1, 1, 1], [0, 1, 1]] },
};

/**
 * Error diffusion in place. buf: w*h*ch floats; alpha: w*h bytes (0 = skip the pixel, and
 * error that lands on it is dropped). levels: one ascending Float32Array per channel.
 */
export function diffuse(buf, w, h, ch, alpha, levels, taps, { divisor, serpentine = true, strength = 1 } = {}) {
  const div = divisor || taps.reduce((s, t) => s + t[2], 0) || 1;
  const n = taps.length;
  const dx = taps.map((t) => t[0]), dy = taps.map((t) => t[1]), wt = taps.map((t) => (t[2] / div) * strength);
  for (let y = 0; y < h; y++) {
    const rev = serpentine && (y & 1) === 1;
    for (let xi = 0; xi < w; xi++) {
      const x = rev ? w - 1 - xi : xi;
      const p = y * w + x;
      if (!alpha[p]) continue;
      for (let c = 0; c < ch; c++) {
        const i = p * ch + c, L = levels[c];
        const v = buf[i];
        const q = L[nearestIndex(L, v)];
        buf[i] = q;
        const e = v - q;
        if (e === 0 || !Number.isFinite(e)) continue;
        for (let t = 0; t < n; t++) {
          const xx = rev ? x - dx[t] : x + dx[t], yy = y + dy[t];
          if (xx < 0 || xx >= w || yy >= h || yy < 0) continue;
          buf[(yy * w + xx) * ch + c] += e * wt[t];
        }
      }
    }
  }
}

// ------------------------------------------------------------------ ordered dithering

/**
 * Ordered dithering in place: each value is rounded up to the next level when its position
 * between the two surrounding levels exceeds threshold(gx, gy) in 0..1. (gx, gy) are document
 * coordinates divided by `scale`, so patterns line up across selections.
 */
export function ordered(buf, w, h, ch, alpha, levels, threshold, { x0 = 0, y0 = 0, scale = 1 } = {}) {
  scale = Math.max(1, scale);
  for (let y = 0; y < h; y++) {
    const gy = Math.floor((y + y0) / scale);
    for (let x = 0; x < w; x++) {
      const p = y * w + x;
      if (!alpha[p]) continue;
      const t = threshold(Math.floor((x + x0) / scale), gy);
      for (let c = 0; c < ch; c++) {
        const i = p * ch + c, L = levels[c], v = buf[i];
        if (!(v > L[0])) { buf[i] = L[0]; continue; }
        if (v >= L[L.length - 1]) { buf[i] = L[L.length - 1]; continue; }
        const k = lowerIndex(L, v);
        buf[i] = (v - L[k]) / (L[k + 1] - L[k]) > t ? L[k + 1] : L[k];
      }
    }
  }
}

/** A threshold matrix built from any square/rectangular 2D array: values are ranked. */
export function matrixFromValues(rows) {
  const h = rows.length, w = rows[0].length;
  const cells = [];
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) cells.push({ i: y * w + x, v: Number(rows[y][x]) || 0 });
  cells.sort((a, b) => a.v - b.v || a.i - b.i);
  const t = new Float32Array(w * h);
  cells.forEach((c, rank) => { t[c.i] = (rank + 0.5) / cells.length; });
  return { w, h, t };
}

export const matrixThreshold = (m) => (gx, gy) => m.t[(gy % m.h) * m.w + (gx % m.w)];

/** Bayer index matrix as a 2D array of ranks 0..n²-1 (n a power of two). */
export function bayer(n) {
  let m = [[0]];
  while (m.length < n) {
    const s = m.length, next = [];
    for (let y = 0; y < s * 2; y++) next.push(new Array(s * 2));
    for (let y = 0; y < s; y++) {
      for (let x = 0; x < s; x++) {
        const v = m[y][x] * 4;
        next[y][x] = v; next[y][x + s] = v + 2; next[y + s][x] = v + 3; next[y + s][x + s] = v + 1;
      }
    }
    m = next;
  }
  return m;
}

/** Clustered-dot halftone: dots grow from the cell center (light) and corners (dark). */
function halftone(n) {
  const rows = [];
  for (let y = 0; y < n; y++) {
    rows.push([]);
    for (let x = 0; x < n; x++) {
      const u = (2 * Math.PI * (x + 0.5)) / n, v = (2 * Math.PI * (y + 0.5)) / n;
      // tiny angular term breaks the four-way ties so dots grow round, not in a scan order
      rows[y].push(Math.cos(u) + Math.cos(v) + 1e-4 * Math.atan2(y + 0.5 - n / 2, x + 0.5 - n / 2));
    }
  }
  return rows;
}

/** Horizontal line screen: lines thicken row by row; Bayer order within a row. */
function lineScreen(n) {
  const b = bayer(n)[0];
  return Array.from({ length: n }, (_, y) => Array.from({ length: n }, (_, x) => Math.cos((2 * Math.PI * (y + 0.5)) / n) + 1e-3 * b[x]));
}

/** Small fast seeded PRNG. */
export function mulberry32(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/** Stateless hash of integer coordinates to [0, 1). */
export function hash(x, y, seed = 0) {
  let h = Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x9e3779b9);
  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
  h ^= h >>> 16;
  return (h >>> 0) / 4294967296;
}

/**
 * 64×64 blue-noise threshold matrix by void-and-cluster (Ulichney 1993), generated once.
 * Phase 3 keeps filling the largest voids, which ranks the last zeros evenly too.
 */
let blueNoiseCache = null;
export function blueNoise() {
  if (blueNoiseCache) return blueNoiseCache;
  const N = 64, n = N * N, sigma = 1.5;
  const K = new Float32Array(n);
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      const dx = Math.min(x, N - x), dy = Math.min(y, N - y);
      K[y * N + x] = Math.exp(-(dx * dx + dy * dy) / (2 * sigma * sigma));
    }
  }
  const splat = (E, p, sign) => {
    const px = p % N, py = (p / N) | 0;
    for (let y = 0; y < N; y++) {
      const krow = ((y - py + N) % N) * N, erow = y * N;
      for (let x = 0; x < N; x++) E[erow + x] += sign * K[krow + ((x - px + N) % N)];
    }
  };
  const extreme = (bits, E, want, max) => {
    let best = -1, bv = max ? -Infinity : Infinity;
    for (let p = 0; p < n; p++) {
      if (bits[p] !== want) continue;
      if (max ? E[p] > bv : E[p] < bv) { bv = E[p]; best = p; }
    }
    return best;
  };
  const rnd = mulberry32(0x5eed);
  const bits = new Uint8Array(n), E = new Float32Array(n);
  const ones = n / 10;
  for (let placed = 0; placed < ones;) {
    const p = (rnd() * n) | 0;
    if (!bits[p]) { bits[p] = 1; splat(E, p, 1); placed++; }
  }
  // relax the initial pattern: move the tightest cluster into the largest void until stable
  for (let iter = 0; iter < n; iter++) {
    const c = extreme(bits, E, 1, true);
    bits[c] = 0; splat(E, c, -1);
    const v = extreme(bits, E, 0, false);
    bits[v] = 1; splat(E, v, 1);
    if (v === c) break;
  }
  const rank = new Uint32Array(n);
  const b1 = bits.slice(), E1 = E.slice();
  for (let r = ones - 1; r >= 0; r--) {
    const c = extreme(b1, E1, 1, true);
    b1[c] = 0; splat(E1, c, -1); rank[c] = r;
  }
  for (let r = ones; r < n; r++) {
    const v = extreme(bits, E, 0, false);
    bits[v] = 1; splat(E, v, 1); rank[v] = r;
  }
  const t = new Float32Array(n);
  for (let p = 0; p < n; p++) t[p] = (rank[p] + 0.5) / n;
  blueNoiseCache = { w: N, h: N, t };
  return blueNoiseCache;
}

const fromRows = (rowsFn) => { let m = null; return () => matrixThreshold(m ||= matrixFromValues(rowsFn())); };

// ------------------------------------------------------------------ algorithm registry

/**
 * kind: 'none' (nearest level), 'diffusion' (uses KERNELS[id]), 'ordered' (threshold(params)
 * returns a (gx, gy) => 0..1 function), or 'script' (user scripts; see the worker).
 */
export const ALGORITHMS = [
  { id: 'none', label: 'None (nearest color)', kind: 'none' },
  ...Object.entries(KERNELS).map(([id, k]) => ({ id, label: k.label, kind: 'diffusion' })),
  { id: 'bayer2', label: 'Bayer 2×2', kind: 'ordered', threshold: fromRows(() => bayer(2)) },
  { id: 'bayer4', label: 'Bayer 4×4', kind: 'ordered', threshold: fromRows(() => bayer(4)) },
  { id: 'bayer8', label: 'Bayer 8×8', kind: 'ordered', threshold: fromRows(() => bayer(8)) },
  { id: 'bayer16', label: 'Bayer 16×16', kind: 'ordered', threshold: fromRows(() => bayer(16)) },
  { id: 'halftone4', label: 'Halftone dots 4×4', kind: 'ordered', threshold: fromRows(() => halftone(4)) },
  { id: 'halftone8', label: 'Halftone dots 8×8', kind: 'ordered', threshold: fromRows(() => halftone(8)) },
  { id: 'lines', label: 'Line screen', kind: 'ordered', threshold: fromRows(() => lineScreen(8)) },
  { id: 'blue-noise', label: 'Blue noise', kind: 'ordered', threshold: () => matrixThreshold(blueNoise()) },
  {
    id: 'ign', label: 'Interleaved gradient noise', kind: 'ordered',
    threshold: () => (x, y) => { const f = 52.9829189 * ((0.06711056 * x + 0.00583715 * y) % 1); return f - Math.floor(f); },
  },
  { id: 'random', label: 'Random (white noise)', kind: 'ordered', threshold: (p) => (x, y) => hash(x, y, p.seed) },
];

// ------------------------------------------------------------------ user scripts

let userScripts = [];
/** [{ id, name, source }]; the app loads these from preferences. */
export function setUserScripts(list) { userScripts = Array.isArray(list) ? list.filter((s) => s && s.id && typeof s.source === 'string') : []; }
export function getUserScripts() { return userScripts; }

export function algorithmKind(id) {
  if (typeof id === 'string' && id.startsWith('script:')) return 'script';
  return ALGORITHMS.find((a) => a.id === id)?.kind || 'none';
}

export function algorithmOptions() {
  return [
    ...ALGORITHMS.map((a) => ({ value: a.id, label: a.label })),
    ...userScripts.map((s) => ({ value: `script:${s.id}`, label: `Script: ${s.name || 'Untitled'}` })),
  ];
}

// ------------------------------------------------------------------ filter params

export function ditherParams() {
  const mono = (v) => v.mode !== 'rgb', rgb = (v) => v.mode === 'rgb';
  const kind = (v) => algorithmKind(v.algorithm);
  return [
    {
      key: 'mode', label: 'Color mode', type: 'select', default: 'mono',
      options: [{ value: 'mono', label: 'Luminance (1 channel)' }, { value: 'rgb', label: 'RGB (3 channels)' }],
    },
    { key: 'levels', label: 'Levels', min: 2, max: 64, default: 2, when: mono },
    {
      key: 'ink', label: 'Colors', type: 'select', default: 'bw', when: mono,
      options: [{ value: 'bw', label: 'Black → White' }, { value: 'fgbg', label: 'Foreground → Background' }],
    },
    { key: 'rLevels', label: 'Red levels', min: 2, max: 64, default: 2, when: rgb },
    { key: 'gLevels', label: 'Green levels', min: 2, max: 64, default: 2, when: rgb },
    { key: 'bLevels', label: 'Blue levels', min: 2, max: 64, default: 2, when: rgb },
    { key: 'algorithm', label: 'Algorithm', type: 'select', default: 'floyd-steinberg', options: algorithmOptions() },
    { key: 'strength', label: 'Diffusion', min: 0, max: 100, default: 100, unit: '%', when: (v) => kind(v) === 'diffusion' || kind(v) === 'script' },
    { key: 'serpentine', label: 'Serpentine scan', type: 'checkbox', default: true, when: (v) => kind(v) === 'diffusion' || kind(v) === 'script' },
    { key: 'scale', label: 'Pattern scale', min: 1, max: 16, default: 1, unit: '×', when: (v) => kind(v) === 'ordered' || kind(v) === 'script' },
    { key: 'seed', label: 'Seed', min: 0, max: 999, default: 1, when: (v) => v.algorithm === 'random' || kind(v) === 'script' },
    { key: 'brightness', label: 'Brightness', min: -100, max: 100, default: 0 },
    { key: 'contrast', label: 'Contrast', min: -100, max: 100, default: 0 },
    { key: 'linear', label: 'Dither in linear light', type: 'checkbox', default: false, title: 'Measure error in linear light: tones match at 100% zoom, but midtones look lighter than the usual sRGB result' },
    { key: 'hardAlpha', label: 'Hard-edged transparency', type: 'checkbox', default: false, title: 'Make every pixel fully opaque or fully transparent (threshold at 50%)' },
  ];
}

// ------------------------------------------------------------------ pipeline

const levelCount = (n) => Math.max(2, Math.min(256, Math.round(Number(n) || 2)));

/**
 * Build the working buffer for an ImageData. Returns everything `finish` and the
 * algorithms need. env: { fg, bg } colors ({r, g, b}).
 */
export function prepare(src, p, env = {}) {
  const { width: w, height: h, data: d } = src;
  const mono = p.mode !== 'rgb';
  const ch = mono ? 1 : 3;
  const counts = mono ? [levelCount(p.levels)] : [levelCount(p.rLevels), levelCount(p.gLevels), levelCount(p.bLevels)];
  const lin = !!p.linear;
  const space = lin ? srgbToLinear : (u) => u;
  // Output levels are evenly spaced sRGB bytes; in linear mode their working values are not.
  const bytes = counts.map((n) => Uint8ClampedArray.from({ length: n }, (_, k) => Math.round((k * 255) / (n - 1))));
  const levels = bytes.map((b) => Float32Array.from(b, (v) => space(v / 255)));
  // Output color per level, for mono modes (rgb modes use `bytes` per channel).
  let colors = null;
  if (mono) {
    const n = counts[0];
    const a = p.ink === 'fgbg' && env.fg ? env.fg : { r: 0, g: 0, b: 0 };
    const b = p.ink === 'fgbg' && env.bg ? env.bg : { r: 255, g: 255, b: 255 };
    colors = Array.from({ length: n }, (_, k) => {
      const t = k / (n - 1);
      return [Math.round(a.r + (b.r - a.r) * t), Math.round(a.g + (b.g - a.g) * t), Math.round(a.b + (b.b - a.b) * t)];
    });
  }
  // brightness / contrast (same curve as the Brightness/Contrast adjustment), then the space
  const con = Math.tan((((p.contrast || 0) / 100 + 1) * Math.PI) / 4), bri = (p.brightness || 0) / 200;
  const STEPS = 4080; // 16 per byte value
  const lut = new Float32Array(STEPS + 1);
  for (let i = 0; i <= STEPS; i++) lut[i] = space(clamp01((i / STEPS - 0.5) * con + 0.5 + bri));
  const toWork = (g) => lut[Math.round(g * 16)];

  const n = w * h;
  const buf = new Float32Array(n * ch);
  const alpha = new Uint8Array(n);
  for (let px = 0, i = 0; px < n; px++, i += 4) {
    let a = d[i + 3];
    if (p.hardAlpha) a = a >= 128 ? 255 : 0;
    alpha[px] = a;
    if (!a) continue;
    if (mono) {
      const g = lin
        ? linearToSrgb(0.2126 * BYTE_TO_LINEAR[d[i]] + 0.7152 * BYTE_TO_LINEAR[d[i + 1]] + 0.0722 * BYTE_TO_LINEAR[d[i + 2]]) * 255
        : 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2];
      buf[px] = toWork(g);
    } else {
      buf[px * 3] = toWork(d[i]);
      buf[px * 3 + 1] = toWork(d[i + 1]);
      buf[px * 3 + 2] = toWork(d[i + 2]);
    }
  }
  return { w, h, ch, buf, alpha, levels, bytes, colors };
}

/** Write the (snapped) buffer back into `out` (an ImageData of the same size). */
export function finish(s, out, buf = s.buf) {
  const d = out.data, { ch, alpha, levels, bytes, colors } = s;
  const n = s.w * s.h;
  for (let px = 0, i = 0; px < n; px++, i += 4) {
    const a = alpha[px];
    d[i + 3] = a;
    if (!a) continue;
    if (ch === 1) {
      const c = colors[nearestIndex(levels[0], buf[px])];
      d[i] = c[0]; d[i + 1] = c[1]; d[i + 2] = c[2];
    } else {
      const o = px * 3;
      d[i] = bytes[0][nearestIndex(levels[0], buf[o])];
      d[i + 1] = bytes[1][nearestIndex(levels[1], buf[o + 1])];
      d[i + 2] = bytes[2][nearestIndex(levels[2], buf[o + 2])];
    }
  }
  return out;
}

/** Run a built-in algorithm on a prepared buffer. */
export function runBuiltin(s, p, env = {}) {
  const alg = ALGORITHMS.find((a) => a.id === p.algorithm) || ALGORITHMS[0];
  if (alg.kind === 'diffusion') {
    const k = KERNELS[alg.id];
    diffuse(s.buf, s.w, s.h, s.ch, s.alpha, s.levels, k.taps, {
      divisor: k.divisor, serpentine: p.serpentine !== false, strength: (p.strength ?? 100) / 100,
    });
  } else if (alg.kind === 'ordered') {
    ordered(s.buf, s.w, s.h, s.ch, s.alpha, s.levels, alg.threshold(p), { x0: env.x || 0, y0: env.y || 0, scale: p.scale || 1 });
  }
  // 'none': finish() snaps to the nearest level
}

/**
 * The filter entry point: ImageData → ImageData (in place). Returns a Promise when the
 * algorithm is a user script, which runs in a worker.
 */
export function applyDither(id, p, env = {}) {
  const s = prepare(id, p, env);
  if (algorithmKind(p.algorithm) !== 'script') {
    runBuiltin(s, p, env);
    return finish(s, id);
  }
  const sid = p.algorithm.slice('script:'.length);
  const script = userScripts.find((x) => x.id === sid);
  if (!script) throw new Error('That dither script no longer exists. Pick another algorithm.');
  return runScript(script.source, s, p, env).then(({ data }) => finish(s, id, data));
}

// ------------------------------------------------------------------ script runner (main thread)

let running = null;
export const SCRIPT_TIMEOUT_MS = 30000;

/**
 * Run a user script on a prepared buffer in a module worker. Starting a new run cancels the
 * previous one (its promise rejects with err.superseded = true), so a slow or stuck script
 * never piles up behind live-preview updates. Resolves { data, ms }.
 */
export function runScript(source, s, p, env = {}, { timeout = SCRIPT_TIMEOUT_MS } = {}) {
  running?.cancel();
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL('./dither-worker.js', import.meta.url), { type: 'module' });
    let timer = 0;
    const job = {};
    const done = () => {
      clearTimeout(timer);
      worker.terminate();
      if (running === job) running = null;
    };
    job.cancel = () => { done(); reject(Object.assign(new Error('Superseded by a newer run'), { superseded: true })); };
    running = job;
    timer = setTimeout(() => { done(); reject(new Error(`The script was still running after ${timeout / 1000} s, so it was stopped.`)); }, timeout);
    worker.onmessage = (e) => {
      done();
      const r = e.data;
      if (!r.ok) reject(new Error(r.error));
      else if (!(r.data instanceof Float32Array) || r.data.length !== s.buf.length) reject(new Error('The script replaced img.data with an array of the wrong type or size.'));
      else resolve(r);
    };
    worker.onerror = (e) => { e.preventDefault?.(); done(); reject(new Error(e.message || 'The script worker failed to start.')); };
    const img = {
      width: s.w, height: s.h, channels: s.ch, data: s.buf, alpha: s.alpha,
      x0: env.x || 0, y0: env.y || 0,
      params: { strength: (p.strength ?? 100) / 100, serpentine: p.serpentine !== false, scale: p.scale || 1, seed: p.seed ?? 1 },
    };
    worker.postMessage({ source, img, levels: s.levels });
  });
}

// ------------------------------------------------------------------ script API (worker side)

/** The `api` object a user script receives. Documented in ui/ditherscripts.js. */
export function scriptApi(img, levels) {
  const { width: w, height: h, channels: ch, alpha, params } = img;
  const rnd = mulberry32(params.seed ?? 1);
  return {
    levels: levels.map((l) => Array.from(l)),
    nearest: (v, c = 0) => levels[c][nearestIndex(levels[c], v)],
    bracket(v, c = 0) {
      const L = levels[c];
      if (!(v > L[0])) return { lo: L[0], hi: L[0], t: 0 };
      if (v >= L[L.length - 1]) return { lo: L[L.length - 1], hi: L[L.length - 1], t: 0 };
      const k = lowerIndex(L, v);
      return { lo: L[k], hi: L[k + 1], t: (v - L[k]) / (L[k + 1] - L[k]) };
    },
    diffuse(kernel, opts = {}) {
      if (typeof kernel === 'string') {
        if (!KERNELS[kernel]) throw new Error(`Unknown kernel "${kernel}". Known: ${Object.keys(KERNELS).join(', ')}`);
        opts = { divisor: KERNELS[kernel].divisor, ...opts };
        kernel = KERNELS[kernel].taps;
      }
      diffuse(img.data, w, h, ch, alpha, levels, kernel, {
        divisor: opts.divisor, serpentine: opts.serpentine ?? params.serpentine, strength: opts.strength ?? params.strength,
      });
    },
    ordered(pattern, opts = {}) {
      let fn = pattern;
      if (typeof pattern === 'string') {
        const a = ALGORITHMS.find((x) => x.id === pattern && x.kind === 'ordered');
        if (!a) throw new Error(`Unknown pattern "${pattern}". Known: ${ALGORITHMS.filter((x) => x.kind === 'ordered').map((x) => x.id).join(', ')}`);
        fn = a.threshold({ seed: params.seed });
      } else if (Array.isArray(pattern)) fn = matrixThreshold(matrixFromValues(pattern));
      ordered(img.data, w, h, ch, alpha, levels, fn, { x0: img.x0, y0: img.y0, scale: opts.scale ?? params.scale });
    },
    bayer,
    random: rnd,
    hash,
  };
}