@mathzetta/qblur 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cpu.js CHANGED
@@ -4,24 +4,24 @@
4
4
  * The same language as the shaders (mathzetta/glsl's filterShader): the
5
5
  * same names (r g b a x y px py w h t gray rgb unchanged), the same
6
6
  * functions (pixel, blur, gaussian, sobel, zoom, the pictures a filter
7
- * names…), the same rules for turning a number or a colour into a pixel.
7
+ * names…), the same rules for turning a number or a color into a pixel.
8
8
  * The GLSL is typed and so is this: every node of the expression gets a
9
9
  * type — float, bool, vec2, vec3 or vec4 — and becomes one local variable
10
10
  * per component inside a loop over the pixels. No vector objects exist at
11
11
  * run time; a filter is one straight-line loop body.
12
12
  *
13
- * Neighbourhood functions whose argument is the same for every pixel
13
+ * Neighborhood functions whose argument is the same for every pixel
14
14
  * (blur(radius) with radius a parameter) are worked out once per pass,
15
15
  * over the whole picture and separably — blur, gaussian, dilate and erode
16
16
  * over a square are a horizontal pass then a vertical one, the same sums
17
17
  * in a different order — then read per pixel. An argument that changes
18
- * per pixel falls back to computing that pixel's neighbourhood directly.
18
+ * per pixel falls back to computing that pixel's neighborhood directly.
19
19
  *
20
20
  * The generated code is compiled with new Function only after mathzetta's
21
21
  * checkGeneratedJs has passed it: every name in it is one this file
22
22
  * generates ($-prefixed) or a Math member, it holds no strings, and only
23
23
  * the arrays made here can be indexed. A filter is user input — shared by
24
- * link, pasted as JSON — and can read the picture and write colours,
24
+ * link, pasted as JSON — and can read the picture and write colors,
25
25
  * nothing else.
26
26
  */
27
27
 
@@ -38,7 +38,7 @@ const table = (entries) => Object.assign(Object.create(null), entries);
38
38
 
39
39
  /** Constants and leaves every expression has. */
40
40
  const SCALARS = table({ r: '$r', g: '$g', b: '$b', a: '$a', x: '$x', y: '$y', px: '$px', py: '$py', w: '$w', h: '$h', t: '$t', gray: '$gray' });
41
- const CONSTANTS = table({ pi: 'Math.PI', 'π': 'Math.PI', e: 'Math.E', tau: '(2 * Math.PI)', 'τ': '(2 * Math.PI)', '∞': 'Infinity', '-∞': '(-Infinity)' });
41
+ const CONSTANTS = table({ pi: 'Math.PI', 'π': 'Math.PI', e: 'Math.E', tau: '(2 * Math.PI)', 'τ': '(2 * Math.PI)', '∞': 'Infinity', '-∞': '(-Infinity)', '°': '(Math.PI / 180)' }); // 30° as the shader's radians(30.0)
42
42
 
43
43
  /** Functions applied to each component: name → (args as JS) => JS. */
44
44
  const COMPONENTWISE = table({
@@ -48,6 +48,8 @@ const COMPONENTWISE = table({
48
48
  csc: (x) => `(1 / Math.sin(${x}))`, sec: (x) => `(1 / Math.cos(${x}))`, cot: (x) => `(1 / Math.tan(${x}))`,
49
49
  fract: (x) => `(${x} - Math.floor(${x}))`, radians: (x) => `(${x} * 0.017453292519943295)`, degrees: (x) => `(${x} * 57.29577951308232)`,
50
50
  inversesqrt: (x) => `(1 / Math.sqrt(${x}))`,
51
+ // as MathZetta's shaders write them: acos(1/x), asin(1/x), π/2 − atan(x)
52
+ arcsec: (x) => `Math.acos(1 / ${x})`, arccsc: (x) => `Math.asin(1 / ${x})`, arccot: (x) => `(Math.PI / 2 - Math.atan(${x}))`,
51
53
  atan2: (y, x) => `Math.atan2(${y}, ${x})`, pow: (x, y) => `Math.pow(${x}, ${y})`,
52
54
  mod: (x, y) => `(${x} - ${y} * Math.floor(${x} / ${y}))`,
53
55
  step: (edge, x) => `(${x} < ${edge} ? 0 : 1)`,
@@ -57,7 +59,26 @@ const COMPONENTWISE = table({
57
59
  });
58
60
  const FIXED_ARITY = table({ atan2: 2, pow: 2, mod: 2, step: 2, clamp: 3, mix: 3, smoothstep: 3 });
59
61
 
60
- /** Neighbourhood functions: the result kind, and whether the per-pass plane is computed once for a constant argument. */
62
+ /** y ∈ {x | P} (or {x ∈ S | P}) as the test it stands for: P with y for x; null for any other membership. */
63
+ function setCondition(node) {
64
+ const [y, set] = node.args;
65
+ if (set.type !== 'op' || set.op !== 'setbuilder') return null;
66
+ let [element, condition] = set.args;
67
+ let domain = null;
68
+ if (element.type === 'op' && element.op === '∈') [element, domain] = element.args;
69
+ const put = (n) => (n.type === 'symbol' && n.value === element.value ? y : n.type === 'op' ? { ...n, args: n.args.map(put) } : n);
70
+ const test = domain ? { type: 'op', op: '&', args: [{ type: 'op', op: '∈', args: [y, domain] }, put(condition)] } : put(condition);
71
+ return node.op === '∉' ? { type: 'op', op: '\\not', args: [test] } : test;
72
+ }
73
+
74
+ /** [F]_a^b (F x a b evaluated) as F with b put in for x, minus F with a: what MathZetta's GLSL writes. */
75
+ function evaluationDifference(node) {
76
+ const [body, variable, lo, hi] = node.args;
77
+ const put = (n, value) => (n.type === 'symbol' && n.value === variable.value ? value : n.type === 'op' ? { ...n, args: n.args.map((a) => put(a, value)) } : n);
78
+ return { type: 'op', op: '-', args: [put(body, hi), put(body, lo)] };
79
+ }
80
+
81
+ /** Neighborhood functions: the result kind, and whether the per-pass plane is computed once for a constant argument. */
61
82
  const PLANES = table({
62
83
  blur: 3, blurx: 3, blury: 3, gaussian: 3, gaussianx: 3, gaussiany: 3, dilate: 3, erode: 3, sharpen: 3,
63
84
  sobel: 1, sobelx: 1, sobely: 1, laplacian: 1, emboss: 1,
@@ -141,7 +162,7 @@ class Generator {
141
162
 
142
163
  leaf(node) {
143
164
  if (node.type === 'number') return f(`(${node.value.replace(/\.+$/, '')})`);
144
- if (node.type === 'string') this.fail('a filter has no text: numbers and colours only');
165
+ if (node.type === 'string') this.fail('a filter has no text: numbers and colors only');
145
166
  const v = node.value;
146
167
  const percent = /^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(v);
147
168
  if (percent) return f(`(${percent[1]} / 100)`); // 50% is 0.5, as in the shader
@@ -150,6 +171,10 @@ class Generator {
150
171
  if (v === 'rgb') return vec(['$r', '$g', '$b']);
151
172
  if (v === 'unchanged') return f('$u'); // the kept value; as a whole if/else branch it takes the other branch's type (ternary)
152
173
  if (v === 'selected') return f(this.pictureHere('selection').c[0]); // the selection mask: white = 1; white everywhere when none
174
+ if (v === 'away') { // pixels from the selection, from the picture `away` (src/distance.js; white = 0)
175
+ const [red, green] = this.pictureHere('away').c;
176
+ return f(`(${red} > 0 ? 255 * (1 - ${red}) : 1020 * (1 - ${green}))`);
177
+ }
153
178
  if (CONSTANTS[v]) return f(CONSTANTS[v]);
154
179
  if (v === 'true' || v === 'false') return bool(v);
155
180
  if (Object.prototype.hasOwnProperty.call(this.params, v)) {
@@ -161,7 +186,7 @@ class Generator {
161
186
  this.fail(`unknown name "${v}"`);
162
187
  }
163
188
 
164
- /** A named picture's colour at this pixel (vec4), sampled once per pixel. */
189
+ /** A named picture's color at this pixel (vec4), sampled once per pixel. */
165
190
  pictureHere(name) {
166
191
  if (!this.perPixel.has(name)) {
167
192
  const s = this.sampler(name, '$px', '$py');
@@ -180,7 +205,7 @@ class Generator {
180
205
  this.pictureNames.add(name);
181
206
  this.body.push(`$h_picture($Q_${name}, $qw_${name}, $qh_${name}, $w, $h, $qz_${name}, $qx_${name}, $qy_${name}, $qa_${name}, $qm_${name}, ${X}, ${Y}, ${out});`);
182
207
  }
183
- if (this.space && name !== 'selection') this.body.push(`$h_col_to${this.space}(${out}[0], ${out}[1], ${out}[2], ${out});`); // a mask is not a colour
208
+ if (this.space && name !== 'selection' && name !== 'away') this.body.push(`$h_col_to${this.space}(${out}[0], ${out}[1], ${out}[2], ${out});`); // a mask is not a color
184
209
  return vec([0, 1, 2, 3].map((k) => `${out}[${k}]`));
185
210
  }
186
211
 
@@ -226,6 +251,8 @@ class Generator {
226
251
  case '\\xor': { const [a, b] = A(); return bool(`(${this.truth(a)} !== ${this.truth(b)})`); }
227
252
  case '\\nand': { const [a, b] = A(); return bool(`!(${this.truth(a)} && ${this.truth(b)})`); }
228
253
  case '\\nor': { const [a, b] = A(); return bool(`!(${this.truth(a)} || ${this.truth(b)})`); }
254
+ case '\\implies': { const [a, b] = A(); return bool(`(!${this.truth(a)} || ${this.truth(b)})`); }
255
+ case '\\iff': { const [a, b] = A(); return bool(`(${this.truth(a)} === ${this.truth(b)})`); }
229
256
  case '\\not': { const [a] = A(); return bool(`!${this.truth(a)}`); }
230
257
  case '?:': return this.ternary(args);
231
258
  case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${op}(${xs.join(', ')})`);
@@ -234,7 +261,7 @@ class Generator {
234
261
  case 'mean': return this.componentwise(A(), (...xs) => `((${xs.join(' + ')}) / ${xs.length})`);
235
262
  case '()': case '[]': case '{}': case '(]': case '[)': {
236
263
  const parts = A().flatMap((v) => (v.kind === 'b' ? [num(v)] : v.c.map((_, k) => num(v, k))));
237
- if (parts.length > 4) this.fail('a colour has at most 4 values (r, g, b, a)');
264
+ if (parts.length > 4) this.fail('a color has at most 4 values (r, g, b, a)');
238
265
  return vec(parts);
239
266
  }
240
267
  case '!': return this.componentwise(A(), (x) => `$h_factorial(${x})`);
@@ -247,8 +274,12 @@ class Generator {
247
274
  }
248
275
  case 'log': { const [base, x] = A(); return this.componentwise([base, x], (b, xx) => `(Math.log(${xx}) / Math.log(${b}))`); }
249
276
  case 'root': { const [n, x] = A(); return this.componentwise([n, x], (nn, xx) => `$h_root(${nn}, ${xx})`); }
250
- case '∈': case '∉': return this.membership(node);
277
+ case '∈': case '∉': {
278
+ const test = setCondition(node); // y ∈ {x | P}: P with y for x, as the shader writes it
279
+ return test ? this.value(test) : this.membership(node);
280
+ }
251
281
  case 'random': return this.random();
282
+ case 'evaluated': return this.value(evaluationDifference(node)); // [F]_a^b: F at b minus F at a, as the shader writes it
252
283
  case '_': {
253
284
  const [a, b] = args;
254
285
  if (a.type === 'symbol' && (b.type === 'number' || b.type === 'symbol')) return this.leaf({ type: 'symbol', value: `${a.value}_${b.value}` });
@@ -318,7 +349,8 @@ class Generator {
318
349
  const [lo, hi] = set.args.map((a) => num(this.value(a)));
319
350
  test = `(${v} ${set.op[0] === '[' ? '>=' : '>'} ${lo} && ${v} ${set.op[1] === ']' ? '<=' : '<'} ${hi})`;
320
351
  } else if (set.type === 'op' && set.op === '{}') {
321
- test = `(${set.args.map((item) => `${v} === ${num(this.value(item))}`).join(' || ')})`;
352
+ // ∅ (an empty {}): nothing is in it — `false`, as the shader's
353
+ test = set.args.length ? `(${set.args.map((item) => `${v} === ${num(this.value(item))}`).join(' || ')})` : 'false';
322
354
  } else if (set.type === 'symbol' && ['ℝ', 'ℤ', 'ℕ'].includes(set.value)) {
323
355
  test = { 'ℝ': `Number.isFinite(${v})`, 'ℤ': `Number.isInteger(${v})`, 'ℕ': `(Number.isInteger(${v}) && ${v} > 0)` }[set.value];
324
356
  } else this.fail('∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ');
@@ -330,7 +362,7 @@ class Generator {
330
362
  return f(this.temp('$h_random($px, $py, $h, ++$seed)'));
331
363
  }
332
364
 
333
- // ---- functions: pictures, geometry, neighbourhoods, GLSL built-ins ------------
365
+ // ---- functions: pictures, geometry, neighborhoods, GLSL built-ins ------------
334
366
 
335
367
  call(name, args, node) {
336
368
  const A = () => args.map((a) => this.value(a));
@@ -374,7 +406,7 @@ class Generator {
374
406
  let v;
375
407
  if (args.length === 2) v = this.call('pixel', args);
376
408
  else if (args.length === 1) v = this.value(args[0]);
377
- else this.fail(`${name}() takes a colour, or a position px, py`);
409
+ else this.fail(`${name}() takes a color, or a position px, py`);
378
410
  const k = { red: 0, green: 1, blue: 2, alpha: 3 }[name];
379
411
  if (name === 'luma') return f(`(${num(v, 0)} * 0.299 + ${num(v, 1)} * 0.587 + ${num(v, 2)} * 0.114)`);
380
412
  if (name === 'alpha' && size(v) === 3) return f('1');
@@ -398,7 +430,7 @@ class Generator {
398
430
  }
399
431
  case 'cross': {
400
432
  const [a, b] = A();
401
- if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two colours (3 values each)');
433
+ if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two colors (3 values each)');
402
434
  const [x1, y1, z1] = a.c; const [x2, y2, z2] = b.c;
403
435
  return this.keep(vec([`(${y1} * ${z2} - ${z1} * ${y2})`, `(${z1} * ${x2} - ${x1} * ${z2})`, `(${x1} * ${y2} - ${y1} * ${x2})`]));
404
436
  }
@@ -414,8 +446,8 @@ class Generator {
414
446
  case 'tolinear': case 'fromlinear': case 'tohsv': case 'fromhsv': case 'tohsl': case 'fromhsl':
415
447
  case 'tolab': case 'fromlab': case 'tooklab': case 'fromoklab': case 'toycbcr': case 'fromycbcr': {
416
448
  const a = A();
417
- const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a colour, or three numbers
418
- if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a colour`);
449
+ const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a color, or three numbers
450
+ if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a color`);
419
451
  const out = this.scratchArray();
420
452
  this.body.push(`$h_col_${name}(${c.join(', ')}, ${out});`);
421
453
  return this.keep(vec([0, 1, 2].map((k) => `${out}[${k}]`)));
@@ -431,7 +463,7 @@ class Generator {
431
463
  case 'log': return this.builtin('ln', A());
432
464
  case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${name}(${xs.join(', ')})`);
433
465
  }
434
- if (PLANES[name]) return this.neighbourhood(name, args);
466
+ if (PLANES[name]) return this.neighborhood(name, args);
435
467
  this.fail(`unknown function "${name}"`);
436
468
  }
437
469
 
@@ -471,9 +503,9 @@ class Generator {
471
503
 
472
504
  /**
473
505
  * blur(radius) and friends. With an argument the same for every pixel (numbers, params, t),
474
- * the whole plane is computed once before the loop; otherwise this pixel's neighbourhood is.
506
+ * the whole plane is computed once before the loop; otherwise this pixel's neighborhood is.
475
507
  */
476
- neighbourhood(name, args) {
508
+ neighborhood(name, args) {
477
509
  const kind = PLANES[name];
478
510
  const constant = args.every((a) => this.isUniform(a));
479
511
  if (constant) {
@@ -514,7 +546,7 @@ class Generator {
514
546
 
515
547
  // ---- assembling the pass ------------------------------------------------------
516
548
 
517
- /** One channel line of the colour, as filterShader writes it (mz_keep, then mz_rgba / mz_rgb / mz_ch_*). */
549
+ /** One channel line of the color, as filterShader writes it (mz_keep, then mz_rgba / mz_rgb / mz_ch_*). */
518
550
  channel(ch, tree) {
519
551
  const keepValue = ch === 'rgba' || ch === 'rgb' ? '$gray' : `$c${'rgba'.indexOf(ch)}`;
520
552
  this.body.push(`$u = ${keepValue}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);
@@ -522,11 +554,11 @@ class Generator {
522
554
  const n = size(v);
523
555
  const comp = (k) => num(v, k);
524
556
  if (ch === 'rgba') {
525
- if (n === 2) this.fail('a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two');
557
+ if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two');
526
558
  const c = n === 1 ? [comp(0), comp(0), comp(0), '1'] : n === 3 ? [comp(0), comp(1), comp(2), '1'] : [0, 1, 2, 3].map(comp);
527
559
  this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]}; $c3 = ${c[3]};`);
528
560
  } else if (ch === 'rgb') {
529
- if (n === 2) this.fail('a colour is one number (grey), three (r, g, b) or four — not two');
561
+ if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four — not two');
530
562
  const c = n === 1 ? [comp(0), comp(0), comp(0)] : [comp(0), comp(1), comp(2)];
531
563
  this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]};`);
532
564
  } else {
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `away`: how far each pixel is from the selection, in pixels — 0 inside it, and 0 everywhere when nothing is selected.
3
+ *
4
+ * The runners make it themselves from the picture given as `selection`, and only for a filter that uses `away`
5
+ * (runner.setImage('away', …) gives one made elsewhere instead). The distance is the exact Euclidean distance transform
6
+ * of Felzenszwalb & Huttenlocher: a pass down each column, then one across each row, each linear in the pixels. A
7
+ * selection is measured at most AWAY_SIZE pixels on its long side (about 12 ms for 512 × 512), the distances scaled
8
+ * back to the selection's own pixels — the frame's, normally.
9
+ *
10
+ * The picture holds it in 8-bit channels, white where it is 0 (so a picture not given — white — means "0 everywhere"):
11
+ * red = 1 − min(d, 255) / 255 near: whole pixels up to 255 away
12
+ * green = 1 − min(d, 1020) / 1020 far: 4-pixel steps up to 1020 away
13
+ * blue = 1 − min(d_in, 255) / 255 inside the selection: how far from its edge
14
+ * and the shader reads `away` = red > 0 ? 255 (1 − red) : 1020 (1 − green) (mathzetta/glsl's filterShader; src/cpu.js).
15
+ */
16
+
17
+ const INF = 1e20;
18
+ /** The largest side a selection is measured at (the distances are scaled back up). */
19
+ export const AWAY_SIZE = 512;
20
+
21
+ /** 1-D squared distance transform of f (n values) into d, with scratch v (Int32Array n) and z (Float64Array n + 1). */
22
+ function edt1d(f, n, d, v, z) {
23
+ let k = 0;
24
+ v[0] = 0; z[0] = -INF; z[1] = INF;
25
+ for (let q = 1; q < n; q++) {
26
+ const fq = f[q] + q * q;
27
+ let p = v[k], s = (fq - (f[p] + p * p)) / (2 * (q - p));
28
+ while (s <= z[k]) { k--; p = v[k]; s = (fq - (f[p] + p * p)) / (2 * (q - p)); } // never below 0: INF is finite, so s > -INF
29
+ k++; v[k] = q; z[k] = s; z[k + 1] = INF;
30
+ }
31
+ k = 0;
32
+ for (let q = 0; q < n; q++) {
33
+ while (z[k + 1] < q) k++;
34
+ const p = v[k];
35
+ d[q] = (q - p) * (q - p) + f[p];
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Distance (in pixels) from every pixel to the nearest pixel where `inside(i)` is true; 0 on the shape.
41
+ * `inside` is a function of the pixel index, or a typed array (non-zero = on the shape). Infinity when there is no shape.
42
+ */
43
+ export function distanceTo(inside, width, height) {
44
+ const on = typeof inside === 'function' ? inside : (i) => inside[i] !== 0;
45
+ const n = Math.max(width, height);
46
+ const f = new Float64Array(n), d = new Float64Array(n), v = new Int32Array(n), z = new Float64Array(n + 1);
47
+ const grid = new Float64Array(width * height);
48
+ for (let i = 0; i < grid.length; i++) grid[i] = on(i) ? 0 : INF;
49
+ for (let x = 0; x < width; x++) { // down each column
50
+ for (let y = 0; y < height; y++) f[y] = grid[y * width + x];
51
+ edt1d(f, height, d, v, z);
52
+ for (let y = 0; y < height; y++) grid[y * width + x] = d[y];
53
+ }
54
+ const out = new Float32Array(width * height);
55
+ for (let y = 0; y < height; y++) { // then across each row
56
+ const row = y * width;
57
+ for (let x = 0; x < width; x++) f[x] = grid[row + x];
58
+ edt1d(f, width, d, v, z);
59
+ for (let x = 0; x < width; x++) out[row + x] = d[x] >= INF / 2 ? Infinity : Math.sqrt(d[x]);
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * The `away` picture from a mask's pixels (`data`: 4 per pixel, bytes 0–255 or floats 0–1; on the shape where `channel` —
66
+ * 0, red, as `selected` reads it — is at least half). `scale` multiplies the distances (a mask measured at half size: 2).
67
+ * @returns {{ data: Uint8ClampedArray, width: number, height: number }}
68
+ */
69
+ export function encodeAway(data, width, height, { channel = 0, scale = 1 } = {}) {
70
+ const half = data instanceof Float32Array || data instanceof Float64Array ? 0.5 : 128;
71
+ const at = (i) => data[i * 4 + channel] >= half;
72
+ const out = distanceTo(at, width, height);
73
+ const inn = distanceTo((i) => !at(i), width, height);
74
+ const px = new Uint8ClampedArray(width * height * 4);
75
+ for (let i = 0, j = 0; i < out.length; i++, j += 4) {
76
+ const d = out[i] * scale, e = inn[i] * scale;
77
+ px[j] = 255 - Math.min(d, 255);
78
+ px[j + 1] = 255 - Math.min(d, 1020) / 4;
79
+ px[j + 2] = 255 - Math.min(e, 255);
80
+ px[j + 3] = 255;
81
+ }
82
+ return { data: px, width, height };
83
+ }
84
+
85
+ /** `away` (in pixels) back from the picture's channels, 0–1 — what the shader and the CPU runner compute. */
86
+ export const awayFromChannels = (red, green) => (red > 0 ? 255 * (1 - red) : 1020 * (1 - green));
87
+
88
+ /**
89
+ * The `away` picture for a selection: ImageData, { data, width, height } (bytes or floats), or in a browser an
90
+ * <img>/<canvas>/<video>/ImageBitmap; null for none (then `away` is 0 everywhere). Measured at most `size` on the long side.
91
+ */
92
+ export function awayPicture(selection, { size = AWAY_SIZE } = {}) {
93
+ if (!selection) return null;
94
+ const W = selection.naturalWidth || selection.videoWidth || selection.width, H = selection.naturalHeight || selection.videoHeight || selection.height;
95
+ if (!W || !H) return null;
96
+ const k = Math.min(1, size / Math.max(W, H)), w = Math.max(1, Math.round(W * k)), h = Math.max(1, Math.round(H * k));
97
+ let data;
98
+ if (selection.data && !(typeof HTMLElement !== 'undefined' && selection instanceof HTMLElement)) {
99
+ data = selection.data;
100
+ if (w !== W || h !== H) { // nearest pixel: a mask, so no need to average
101
+ const small = new (data.constructor)(w * h * 4);
102
+ for (let y = 0; y < h; y++) {
103
+ const sy = Math.min(H - 1, Math.floor(((y + 0.5) * H) / h));
104
+ for (let x = 0; x < w; x++) {
105
+ const sx = Math.min(W - 1, Math.floor(((x + 0.5) * W) / w)), from = (sy * W + sx) * 4, to = (y * w + x) * 4;
106
+ for (let c = 0; c < 4; c++) small[to + c] = data[from + c];
107
+ }
108
+ }
109
+ data = small;
110
+ }
111
+ } else {
112
+ const canvas = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, h) : Object.assign(document.createElement('canvas'), { width: w, height: h });
113
+ const g = canvas.getContext('2d', { willReadFrequently: true });
114
+ g.drawImage(selection, 0, 0, w, h);
115
+ data = g.getImageData(0, 0, w, h).data;
116
+ }
117
+ return encodeAway(data, w, h, { scale: W / w });
118
+ }
119
+
120
+ /** Whether a compiled filter (compileFilter()) reads `away`. */
121
+ export const usesAway = (compiled) => compiled.passes.some((pass) => pass.images?.includes('away'));
122
+
123
+ /**
124
+ * For a filter that reads `away`: the runner makes its picture from each `selection` it is given (and drops it with the
125
+ * selection), unless the page gives one itself — runner.setImage('away', picture); setImage('away', null) goes back to
126
+ * making it. Other runners are returned untouched.
127
+ */
128
+ export function deriveAway(runner, compiled) {
129
+ if (!usesAway(compiled)) return runner;
130
+ const set = runner.setImage.bind(runner);
131
+ let given = false, selection = null;
132
+ runner.setImage = (name, image) => {
133
+ if (name === 'away') {
134
+ given = image != null;
135
+ return set('away', given ? image : awayPicture(selection));
136
+ }
137
+ set(name, image);
138
+ if (name === 'selection') {
139
+ selection = image ?? null;
140
+ if (!given) set('away', awayPicture(selection));
141
+ }
142
+ return runner;
143
+ };
144
+ return runner;
145
+ }
package/src/element.d.ts CHANGED
@@ -3,7 +3,7 @@ export declare class QBlurImage extends HTMLElement {
3
3
  static readonly observedAttributes: string[];
4
4
  /** The drawing, a 2D canvas the picture's size (for toBlob). */
5
5
  readonly canvas: HTMLCanvasElement;
6
- /** Maths, a built-in filter's name, filter JSON or a share link (the `filter` attribute). */
6
+ /** Math, a built-in filter's name, filter JSON or a share link (the `filter` attribute). */
7
7
  filter: string;
8
8
  /** Knob values; set an object, or the `params` attribute as JSON. */
9
9
  params: Record<string, number | [number, number, number]>;
package/src/element.js CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * <qblur-image>: a picture with a filter on it, as an HTML element.
3
3
  *
4
- * <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur-element.js"></script>
5
- * <qblur-image src="photo.jpg" filter="Sepia" alt="The harbour at dusk"></qblur-image>
4
+ * <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.3/dist/qblur-element.js"></script>
5
+ * <qblur-image src="photo.jpg" filter="Sepia" alt="The harbor at dusk"></qblur-image>
6
6
  * <qblur-image src="photo.jpg" filter="if gray > cutoff then 1 else 0" params='{"cutoff": 0.4}'></qblur-image>
7
7
  *
8
8
  * Attributes (each change redraws):
9
9
  * src the picture's address (from another site it must allow CORS; add crossorigin)
10
- * filter maths, a built-in filter's name, filter JSON or a share link
10
+ * filter math, a built-in filter's name, filter JSON or a share link
11
11
  * params JSON of knob values, { "name": value } — or set the `params` property to an object
12
12
  * (whichever was set last counts)
13
13
  * t the frame, for filters that move
package/src/format.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shareable image filters.
3
3
  *
4
- * A filter is a small JSON document anyone can publish — maths plus a
4
+ * A filter is a small JSON document anyone can publish — math plus a
5
5
  * name, an author, the knobs it exposes and the pictures it needs:
6
6
  *
7
7
  * { "format": "mathzetta-filter/1",
@@ -23,8 +23,8 @@
23
23
  *
24
24
  * A chain is a filter too, so published chains nest inside new ones and
25
25
  * keep their authors' names (compileFilter() lists them as credits).
26
- * Because a filter is only maths, sharing one is safe: it can read the
27
- * picture and write colours, nothing else.
26
+ * Because a filter is only math, sharing one is safe: it can read the
27
+ * picture and write colors, nothing else.
28
28
  *
29
29
  * normalizeFilter() fills in defaults and rejects bad shapes,
30
30
  * validateFilter() lists every problem, and compileFilter() flattens a
@@ -33,7 +33,7 @@
33
33
  * to pass one around; readFilter() accepts either, or a bare expression.
34
34
  */
35
35
  import { filterShader } from 'mathzetta/glsl';
36
- import { FILTER_NAMES, PLACES, COLOUR_SPACES } from 'mathzetta/glsl';
36
+ import { FILTER_NAMES, PLACES, COLOR_SPACES } from 'mathzetta/glsl';
37
37
  import { normalizeGraphic, shadowLayerNames, MAX_SHADOW_LAYERS } from './graphics.js';
38
38
 
39
39
  export const FILTER_FORMAT = 'mathzetta-filter/1';
@@ -99,7 +99,7 @@ export function normalizeFilter(def) {
99
99
  }
100
100
 
101
101
  /**
102
- * The filter's page: Markdown text (with maths: Inline Math draws it, and `{{k}}` is a knob's value)
102
+ * The filter's page: Markdown text (with math: Inline Math draws it, and `{{k}}` is a knob's value)
103
103
  * and where each knob's input goes — `["Darker below the *cutoff*:", { "param": "cutoff" }]`.
104
104
  * Knobs it doesn't place come before it.
105
105
  */
@@ -117,10 +117,10 @@ function normalizeNotes(notes, params) {
117
117
  function normalizeSpace(space) {
118
118
  if (space === undefined || space === null) return null;
119
119
  const pair = typeof space === 'string' ? { in: space, out: space } : space;
120
- if (!isObject(pair)) throw new Error(`"space" is a colour space (${COLOUR_SPACES.join(', ')}) or { "in": …, "out": … }`);
120
+ if (!isObject(pair)) throw new Error(`"space" is a color space (${COLOR_SPACES.join(', ')}) or { "in": …, "out": … }`);
121
121
  const out = { in: pair.in ?? 'srgb', out: pair.out ?? 'srgb' };
122
122
  for (const key of ['in', 'out']) {
123
- if (!COLOUR_SPACES.includes(out[key])) throw new Error(`"space": "${out[key]}" is not a colour space; they are ${COLOUR_SPACES.join(', ')}`);
123
+ if (!COLOR_SPACES.includes(out[key])) throw new Error(`"space": "${out[key]}" is not a color space; they are ${COLOR_SPACES.join(', ')}`);
124
124
  }
125
125
  return out.in === 'srgb' && out.out === 'srgb' ? null : out;
126
126
  }
@@ -216,7 +216,7 @@ function normalizeParams(params) {
216
216
  return out;
217
217
  }
218
218
 
219
- /** `0.5` → a number 0–1; `[1, 0, 0]` → a colour; or the full `{ type, default, min, max, step, label }`. */
219
+ /** `0.5` → a number 0–1; `[1, 0, 0]` → a color; or the full `{ type, default, min, max, step, label }`. */
220
220
  function normalizeParam(name, spec) {
221
221
  if (typeof spec === 'number') spec = { default: spec };
222
222
  else if (Array.isArray(spec)) spec = { type: 'color', default: spec };
@@ -226,12 +226,12 @@ function normalizeParam(name, spec) {
226
226
  if (spec.label !== undefined) out.label = String(spec.label);
227
227
  if (type === 'color') {
228
228
  const value = spec.default ?? [1, 1, 1];
229
- if (!isColor(value)) throw new Error(`Colour parameter "${name}" needs a default of three numbers, 0–1`);
229
+ if (!isColor(value)) throw new Error(`Color parameter "${name}" needs a default of three numbers, 0–1`);
230
230
  out.default = value.map(Number);
231
231
  return out;
232
232
  }
233
233
  if (type !== 'number') throw new Error(`Parameter "${name}": the type is "number" or "color", not "${type}"`);
234
- // `options`: a choice of values (a menu); `input: "box"`: typed in, as maths; otherwise a slider
234
+ // `options`: a choice of values (a menu); `input: "box"`: typed in, as math; otherwise a slider
235
235
  let options = null;
236
236
  if (spec.options !== undefined) {
237
237
  if (!Array.isArray(spec.options) || !spec.options.length || !spec.options.every((n) => n !== '' && Number.isFinite(Number(n)))) throw new Error(`Parameter "${name}": "options" is a list of numbers`);
@@ -317,7 +317,7 @@ function check(step, path, problems, shaders) {
317
317
  const param = Object.hasOwn(params, name) ? params[name] : null;
318
318
  if (!param) problems.push(`${where}: "with" sets "${name}", but there is no parameter called that`);
319
319
  else if (param.type === 'color' ? !isColor(value) : !Number.isFinite(Number(value))) {
320
- problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'colour: three numbers, 0–1' : 'number'}`);
320
+ problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'color: three numbers, 0–1' : 'number'}`);
321
321
  }
322
322
  }
323
323
  if (filter.steps) {
@@ -377,7 +377,7 @@ function flatten(step, path, outer, context) {
377
377
  if (!context.problems.includes(problem)) context.problems.push(problem);
378
378
  return;
379
379
  }
380
- const rewritten = inColourSpace(step.filter) ?? separableBlur(step.filter);
380
+ const rewritten = inColorSpace(step.filter) ?? separableBlur(step.filter);
381
381
  if (rewritten) {
382
382
  if (step.filter === context.top) context.top = rewritten; // still the filter itself, not something it uses
383
383
  flatten({ ...step, filter: rewritten }, path, outer, context);
@@ -407,7 +407,7 @@ function flatten(step, path, outer, context) {
407
407
  }
408
408
 
409
409
  /**
410
- * A step whose whole colour is just `gaussian(s)` or `blur(r)` is computed
410
+ * A step whose whole color is just `gaussian(s)` or `blur(r)` is computed
411
411
  * separably — one pass along x, one along y: the same blur for 2n taps
412
412
  * instead of n², and reaching further (±24 pixels instead of ±8). The
413
413
  * step keeps its name, params, pictures and opacity; the two passes share
@@ -420,7 +420,7 @@ function flatten(step, path, outer, context) {
420
420
  * converted too — then convert back. Opacity blends the result over
421
421
  * the input in sRGB, as any chain's does.
422
422
  */
423
- function inColourSpace(filter) {
423
+ function inColorSpace(filter) {
424
424
  if (!filter.space || typeof filter.color === 'undefined') return null;
425
425
  const { space, name, author, description, ...core } = filter; // the chain carries the name; the middle step is nameless, so it is not a credit
426
426
  const step = (f) => ({ filter: f, with: {}, opacity: 1, skip: false });
@@ -498,6 +498,7 @@ function makePass(filter, settings, opacity, path, version) {
498
498
  const images = Object.keys(placements);
499
499
  if (fragment.includes('uniform sampler2D mz_img_source;')) images.push('source');
500
500
  if (fragment.includes('uniform sampler2D mz_img_selection;')) images.push('selection');
501
+ if (fragment.includes('uniform sampler2D mz_img_away;')) images.push('away'); // `away`: the runners make it from the selection
501
502
  // `color` is the filter's own expression(s): the CPU runner compiles that, the GPU runner the fragment shader.
502
503
  return { name: filter.name ?? '', author: filter.author ?? '', path, color: filter.color, space: filter._space ?? 'srgb', fragment, params, values, opacity, images, placements, graphics, keepInput: 0, blendKept: false };
503
504
  }
package/src/graphics.js CHANGED
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * A filter's `graphics` names things to draw — text, rectangles, ovals —
5
5
  * each rasterized into a transparent picture the size of the frame under
6
- * its name. The maths then treats it like any picture: `title` is its
7
- * colour, `alpha(title)` where it is, so
6
+ * its name. The math then treats it like any picture: `title` is its
7
+ * color, `alpha(title)` where it is, so
8
8
  *
9
9
  * mix(rgb, title, alpha(title)) lays the text on
10
10
  * mix(rgb, gaussian(6) * 0.8, alpha(panel)) frosts the picture behind a panel
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * A graphic's `shadow` is drawn into it. Its `shadows` — a list, back to
14
14
  * front — are drawn each into a picture of its own, `title_shadow1`,
15
- * `title_shadow2`…, so every shadow layer can have its own maths:
15
+ * `title_shadow2`…, so every shadow layer can have its own math:
16
16
  *
17
17
  * mix(mix(rgb, gaussian(4), alpha(title_shadow1)), title, alpha(title))
18
18
  * mix(mix(rgb, (1, 0.3, 0.6) , alpha(shift(title_shadow1, 2 sin(t / 9), 0))), title, alpha(title))
@@ -49,23 +49,23 @@ export const MAX_SHADOW_LAYERS = 8;
49
49
  /**
50
50
  * The picture names of a graphic's separate shadow layers, back to front:
51
51
  * title_shadow1, title_shadow2… Each is a picture of that shadow alone, so
52
- * the maths can treat it on its own (blur it, colour it, move it with t).
52
+ * the math can treat it on its own (blur it, color it, move it with t).
53
53
  */
54
54
  export const shadowLayerNames = (name, spec) => (spec.shadows ?? []).map((_, k) => `${name}_shadow${k + 1}`);
55
55
 
56
- /** The maths that lays a graphic on with its shadow layers, back to front — what a new text step starts with. */
56
+ /** The math that lays a graphic on with its shadow layers, back to front — what a new text step starts with. */
57
57
  export function layeredExpression(name, spec) {
58
58
  let base = 'rgb';
59
59
  for (const layer of shadowLayerNames(name, spec)) base = `mix(${base}, ${layer}, alpha(${layer}))`;
60
60
  return `mix(${base}, ${name}, alpha(${name}))`;
61
61
  }
62
62
 
63
- const COLOUR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i;
63
+ const COLOR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i;
64
64
  const FAMILY = /^[\w\s,'"-]{1,80}$/;
65
65
  const WEIGHTS = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
66
66
 
67
- function colour(name, key, value) {
68
- if (typeof value !== 'string' || !COLOUR.test(value.trim())) throw new Error(`Graphic "${name}": "${key}" is a colour like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);
67
+ function color(name, key, value) {
68
+ if (typeof value !== 'string' || !COLOR.test(value.trim())) throw new Error(`Graphic "${name}": "${key}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);
69
69
  return value.trim();
70
70
  }
71
71
 
@@ -79,7 +79,7 @@ function number(name, key, value, min = -Infinity, max = Infinity) {
79
79
  function outline(name, value) {
80
80
  if (value === null || value === false) return null;
81
81
  if (typeof value !== 'object') throw new Error(`Graphic "${name}": "outline" is { "color", "width" } or null`);
82
- return { color: colour(name, 'outline.color', value.color ?? '#000000'), width: number(name, 'outline.width', value.width ?? 0.06, 0, 1) };
82
+ return { color: color(name, 'outline.color', value.color ?? '#000000'), width: number(name, 'outline.width', value.width ?? 0.06, 0, 1) };
83
83
  }
84
84
 
85
85
  /** `{ color, blur, dx, dy }` behind it; blur and offsets are fractions of the text size (frame height for shapes). */
@@ -87,7 +87,7 @@ function shadow(name, value) {
87
87
  if (value === null || value === false) return null;
88
88
  if (typeof value !== 'object') throw new Error(`Graphic "${name}": "shadow" is { "color", "blur", "dx", "dy" } or null`);
89
89
  return {
90
- color: colour(name, 'shadow.color', value.color ?? 'rgba(0,0,0,0.6)'),
90
+ color: color(name, 'shadow.color', value.color ?? 'rgba(0,0,0,0.6)'),
91
91
  blur: number(name, 'shadow.blur', value.blur ?? 0.15, 0, 2),
92
92
  dx: number(name, 'shadow.dx', value.dx ?? 0, -2, 2),
93
93
  dy: number(name, 'shadow.dy', value.dy ?? 0, -2, 2),
@@ -106,7 +106,7 @@ export function normalizeGraphic(name, spec) {
106
106
  for (const [key, fallback] of Object.entries(base)) {
107
107
  if (key === 'type') continue;
108
108
  const value = key in spec && spec[key] !== undefined ? spec[key] : fallback; // null is a value: "no shadow"
109
- if (key === 'color') out.color = colour(name, key, value);
109
+ if (key === 'color') out.color = color(name, key, value);
110
110
  else if (key === 'outline') out.outline = outline(name, value);
111
111
  else if (key === 'shadow') out.shadow = shadow(name, value);
112
112
  else if (key === 'shadows') {