@mathzetta/qblur 0.1.2 → 0.2.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/CHANGELOG.md +34 -0
- package/README.md +24 -21
- package/dist/cpu-worker.js +2 -2
- package/dist/qblur-apply.js +2 -2
- package/dist/qblur-element.js +2 -2
- package/dist/qblur.core.js +2 -2
- package/dist/qblur.external.global.min.js +2 -2
- package/dist/qblur.external.js +2 -2
- package/dist/qblur.global.min.js +2 -2
- package/dist/qblur.js +2 -2
- package/docs/filters.md +91 -88
- package/docs/library.md +51 -51
- package/package.json +4 -4
- package/src/apply-filter.js +8 -7
- package/src/apply.d.ts +12 -11
- package/src/cpu-helpers.js +7 -7
- package/src/cpu.js +51 -23
- package/src/element.d.ts +1 -1
- package/src/element.js +3 -3
- package/src/format.js +14 -14
- package/src/graphics.js +11 -11
- package/src/index.d.ts +11 -11
- package/src/library.js +29 -29
- package/src/png.js +18 -17
- package/src/save.js +7 -7
- package/src/strokes.js +4 -4
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
|
|
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
|
-
*
|
|
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
|
|
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
|
|
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
|
-
/**
|
|
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
|
|
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
|
|
@@ -161,7 +182,7 @@ class Generator {
|
|
|
161
182
|
this.fail(`unknown name "${v}"`);
|
|
162
183
|
}
|
|
163
184
|
|
|
164
|
-
/** A named picture's
|
|
185
|
+
/** A named picture's color at this pixel (vec4), sampled once per pixel. */
|
|
165
186
|
pictureHere(name) {
|
|
166
187
|
if (!this.perPixel.has(name)) {
|
|
167
188
|
const s = this.sampler(name, '$px', '$py');
|
|
@@ -180,7 +201,7 @@ class Generator {
|
|
|
180
201
|
this.pictureNames.add(name);
|
|
181
202
|
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
203
|
}
|
|
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
|
|
204
|
+
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 color
|
|
184
205
|
return vec([0, 1, 2, 3].map((k) => `${out}[${k}]`));
|
|
185
206
|
}
|
|
186
207
|
|
|
@@ -226,6 +247,8 @@ class Generator {
|
|
|
226
247
|
case '\\xor': { const [a, b] = A(); return bool(`(${this.truth(a)} !== ${this.truth(b)})`); }
|
|
227
248
|
case '\\nand': { const [a, b] = A(); return bool(`!(${this.truth(a)} && ${this.truth(b)})`); }
|
|
228
249
|
case '\\nor': { const [a, b] = A(); return bool(`!(${this.truth(a)} || ${this.truth(b)})`); }
|
|
250
|
+
case '\\implies': { const [a, b] = A(); return bool(`(!${this.truth(a)} || ${this.truth(b)})`); }
|
|
251
|
+
case '\\iff': { const [a, b] = A(); return bool(`(${this.truth(a)} === ${this.truth(b)})`); }
|
|
229
252
|
case '\\not': { const [a] = A(); return bool(`!${this.truth(a)}`); }
|
|
230
253
|
case '?:': return this.ternary(args);
|
|
231
254
|
case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${op}(${xs.join(', ')})`);
|
|
@@ -234,7 +257,7 @@ class Generator {
|
|
|
234
257
|
case 'mean': return this.componentwise(A(), (...xs) => `((${xs.join(' + ')}) / ${xs.length})`);
|
|
235
258
|
case '()': case '[]': case '{}': case '(]': case '[)': {
|
|
236
259
|
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
|
|
260
|
+
if (parts.length > 4) this.fail('a color has at most 4 values (r, g, b, a)');
|
|
238
261
|
return vec(parts);
|
|
239
262
|
}
|
|
240
263
|
case '!': return this.componentwise(A(), (x) => `$h_factorial(${x})`);
|
|
@@ -247,8 +270,12 @@ class Generator {
|
|
|
247
270
|
}
|
|
248
271
|
case 'log': { const [base, x] = A(); return this.componentwise([base, x], (b, xx) => `(Math.log(${xx}) / Math.log(${b}))`); }
|
|
249
272
|
case 'root': { const [n, x] = A(); return this.componentwise([n, x], (nn, xx) => `$h_root(${nn}, ${xx})`); }
|
|
250
|
-
case '∈': case '∉':
|
|
273
|
+
case '∈': case '∉': {
|
|
274
|
+
const test = setCondition(node); // y ∈ {x | P}: P with y for x, as the shader writes it
|
|
275
|
+
return test ? this.value(test) : this.membership(node);
|
|
276
|
+
}
|
|
251
277
|
case 'random': return this.random();
|
|
278
|
+
case 'evaluated': return this.value(evaluationDifference(node)); // [F]_a^b: F at b minus F at a, as the shader writes it
|
|
252
279
|
case '_': {
|
|
253
280
|
const [a, b] = args;
|
|
254
281
|
if (a.type === 'symbol' && (b.type === 'number' || b.type === 'symbol')) return this.leaf({ type: 'symbol', value: `${a.value}_${b.value}` });
|
|
@@ -318,7 +345,8 @@ class Generator {
|
|
|
318
345
|
const [lo, hi] = set.args.map((a) => num(this.value(a)));
|
|
319
346
|
test = `(${v} ${set.op[0] === '[' ? '>=' : '>'} ${lo} && ${v} ${set.op[1] === ']' ? '<=' : '<'} ${hi})`;
|
|
320
347
|
} else if (set.type === 'op' && set.op === '{}') {
|
|
321
|
-
|
|
348
|
+
// ∅ (an empty {}): nothing is in it — `false`, as the shader's
|
|
349
|
+
test = set.args.length ? `(${set.args.map((item) => `${v} === ${num(this.value(item))}`).join(' || ')})` : 'false';
|
|
322
350
|
} else if (set.type === 'symbol' && ['ℝ', 'ℤ', 'ℕ'].includes(set.value)) {
|
|
323
351
|
test = { 'ℝ': `Number.isFinite(${v})`, 'ℤ': `Number.isInteger(${v})`, 'ℕ': `(Number.isInteger(${v}) && ${v} > 0)` }[set.value];
|
|
324
352
|
} else this.fail('∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ');
|
|
@@ -330,7 +358,7 @@ class Generator {
|
|
|
330
358
|
return f(this.temp('$h_random($px, $py, $h, ++$seed)'));
|
|
331
359
|
}
|
|
332
360
|
|
|
333
|
-
// ---- functions: pictures, geometry,
|
|
361
|
+
// ---- functions: pictures, geometry, neighborhoods, GLSL built-ins ------------
|
|
334
362
|
|
|
335
363
|
call(name, args, node) {
|
|
336
364
|
const A = () => args.map((a) => this.value(a));
|
|
@@ -374,7 +402,7 @@ class Generator {
|
|
|
374
402
|
let v;
|
|
375
403
|
if (args.length === 2) v = this.call('pixel', args);
|
|
376
404
|
else if (args.length === 1) v = this.value(args[0]);
|
|
377
|
-
else this.fail(`${name}() takes a
|
|
405
|
+
else this.fail(`${name}() takes a color, or a position px, py`);
|
|
378
406
|
const k = { red: 0, green: 1, blue: 2, alpha: 3 }[name];
|
|
379
407
|
if (name === 'luma') return f(`(${num(v, 0)} * 0.299 + ${num(v, 1)} * 0.587 + ${num(v, 2)} * 0.114)`);
|
|
380
408
|
if (name === 'alpha' && size(v) === 3) return f('1');
|
|
@@ -398,7 +426,7 @@ class Generator {
|
|
|
398
426
|
}
|
|
399
427
|
case 'cross': {
|
|
400
428
|
const [a, b] = A();
|
|
401
|
-
if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two
|
|
429
|
+
if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two colors (3 values each)');
|
|
402
430
|
const [x1, y1, z1] = a.c; const [x2, y2, z2] = b.c;
|
|
403
431
|
return this.keep(vec([`(${y1} * ${z2} - ${z1} * ${y2})`, `(${z1} * ${x2} - ${x1} * ${z2})`, `(${x1} * ${y2} - ${y1} * ${x2})`]));
|
|
404
432
|
}
|
|
@@ -414,8 +442,8 @@ class Generator {
|
|
|
414
442
|
case 'tolinear': case 'fromlinear': case 'tohsv': case 'fromhsv': case 'tohsl': case 'fromhsl':
|
|
415
443
|
case 'tolab': case 'fromlab': case 'tooklab': case 'fromoklab': case 'toycbcr': case 'fromycbcr': {
|
|
416
444
|
const a = A();
|
|
417
|
-
const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a
|
|
418
|
-
if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a
|
|
445
|
+
const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a color, or three numbers
|
|
446
|
+
if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a color`);
|
|
419
447
|
const out = this.scratchArray();
|
|
420
448
|
this.body.push(`$h_col_${name}(${c.join(', ')}, ${out});`);
|
|
421
449
|
return this.keep(vec([0, 1, 2].map((k) => `${out}[${k}]`)));
|
|
@@ -431,7 +459,7 @@ class Generator {
|
|
|
431
459
|
case 'log': return this.builtin('ln', A());
|
|
432
460
|
case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${name}(${xs.join(', ')})`);
|
|
433
461
|
}
|
|
434
|
-
if (PLANES[name]) return this.
|
|
462
|
+
if (PLANES[name]) return this.neighborhood(name, args);
|
|
435
463
|
this.fail(`unknown function "${name}"`);
|
|
436
464
|
}
|
|
437
465
|
|
|
@@ -471,9 +499,9 @@ class Generator {
|
|
|
471
499
|
|
|
472
500
|
/**
|
|
473
501
|
* 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
|
|
502
|
+
* the whole plane is computed once before the loop; otherwise this pixel's neighborhood is.
|
|
475
503
|
*/
|
|
476
|
-
|
|
504
|
+
neighborhood(name, args) {
|
|
477
505
|
const kind = PLANES[name];
|
|
478
506
|
const constant = args.every((a) => this.isUniform(a));
|
|
479
507
|
if (constant) {
|
|
@@ -514,7 +542,7 @@ class Generator {
|
|
|
514
542
|
|
|
515
543
|
// ---- assembling the pass ------------------------------------------------------
|
|
516
544
|
|
|
517
|
-
/** One channel line of the
|
|
545
|
+
/** One channel line of the color, as filterShader writes it (mz_keep, then mz_rgba / mz_rgb / mz_ch_*). */
|
|
518
546
|
channel(ch, tree) {
|
|
519
547
|
const keepValue = ch === 'rgba' || ch === 'rgb' ? '$gray' : `$c${'rgba'.indexOf(ch)}`;
|
|
520
548
|
this.body.push(`$u = ${keepValue}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);
|
|
@@ -522,11 +550,11 @@ class Generator {
|
|
|
522
550
|
const n = size(v);
|
|
523
551
|
const comp = (k) => num(v, k);
|
|
524
552
|
if (ch === 'rgba') {
|
|
525
|
-
if (n === 2) this.fail('a
|
|
553
|
+
if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two');
|
|
526
554
|
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
555
|
this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]}; $c3 = ${c[3]};`);
|
|
528
556
|
} else if (ch === 'rgb') {
|
|
529
|
-
if (n === 2) this.fail('a
|
|
557
|
+
if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four — not two');
|
|
530
558
|
const c = n === 1 ? [comp(0), comp(0), comp(0)] : [comp(0), comp(1), comp(2)];
|
|
531
559
|
this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]};`);
|
|
532
560
|
} else {
|
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
|
-
/**
|
|
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.
|
|
5
|
-
* <qblur-image src="photo.jpg" filter="Sepia" alt="The
|
|
4
|
+
* <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.2/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
|
|
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 —
|
|
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
|
|
27
|
-
* picture and write
|
|
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,
|
|
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
|
|
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
|
|
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 (!
|
|
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
|
|
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(`
|
|
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
|
|
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' ? '
|
|
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 =
|
|
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
|
|
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
|
|
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 });
|
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
|
|
7
|
-
*
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
68
|
-
if (typeof value !== 'string' || !
|
|
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:
|
|
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:
|
|
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 =
|
|
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') {
|
package/src/index.d.ts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* qblur — image filters written as
|
|
2
|
+
* qblur — image filters written as math. Types for `import … from '@mathzetta/qblur'`
|
|
3
3
|
* (and dist/qblur.js, dist/qblur.external.js, window.QBlur in the classic builds).
|
|
4
4
|
* The format itself is described in docs/filters.md; these follow src/.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
// ---- the filter document (mathzetta-filter/1) ----------------------------------------------
|
|
8
8
|
|
|
9
|
-
export type
|
|
9
|
+
export type Color = [number, number, number];
|
|
10
10
|
|
|
11
|
-
/** A knob: `0.5` (a number 0–1), `[1, 0, 0]` (a
|
|
12
|
-
export type ParamSpec = number |
|
|
11
|
+
/** A knob: `0.5` (a number 0–1), `[1, 0, 0]` (a color), or in full. */
|
|
12
|
+
export type ParamSpec = number | Color | {
|
|
13
13
|
type?: 'number' | 'color';
|
|
14
|
-
default?: number |
|
|
14
|
+
default?: number | Color;
|
|
15
15
|
min?: number;
|
|
16
16
|
max?: number;
|
|
17
17
|
step?: number;
|
|
18
18
|
label?: string;
|
|
19
19
|
/** A menu of these values. */
|
|
20
20
|
options?: number[];
|
|
21
|
-
/** "box": typed in, as
|
|
21
|
+
/** "box": typed in, as math; the default is a slider. */
|
|
22
22
|
input?: 'slider' | 'box';
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
export interface NormalizedParam {
|
|
26
26
|
type: 'number' | 'color';
|
|
27
|
-
default: number |
|
|
27
|
+
default: number | Color;
|
|
28
28
|
min?: number;
|
|
29
29
|
max?: number;
|
|
30
30
|
step?: number;
|
|
@@ -55,7 +55,7 @@ export interface GraphicSpec {
|
|
|
55
55
|
/** One expression for every channel, or one per channel. */
|
|
56
56
|
export type ColorExpression = string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
57
57
|
|
|
58
|
-
export type
|
|
58
|
+
export type ColorSpace = 'srgb' | 'linear' | 'hsv' | 'hsl' | 'lab' | 'oklab' | 'ycbcr';
|
|
59
59
|
|
|
60
60
|
/** A step of a chain: an expression, a filter, or a filter with settings. */
|
|
61
61
|
export type Step = string | FilterDocument | {
|
|
@@ -67,7 +67,7 @@ export type Step = string | FilterDocument | {
|
|
|
67
67
|
skip?: boolean;
|
|
68
68
|
};
|
|
69
69
|
|
|
70
|
-
/** A filter as published:
|
|
70
|
+
/** A filter as published: math plus a name, an author, its knobs and the pictures it needs. */
|
|
71
71
|
export interface FilterDocument {
|
|
72
72
|
format?: 'mathzetta-filter/1';
|
|
73
73
|
name?: string;
|
|
@@ -78,7 +78,7 @@ export interface FilterDocument {
|
|
|
78
78
|
params?: Record<string, ParamSpec>;
|
|
79
79
|
images?: string[] | Record<string, ImageSpec>;
|
|
80
80
|
graphics?: Record<string, GraphicSpec>;
|
|
81
|
-
space?:
|
|
81
|
+
space?: ColorSpace | { in?: ColorSpace; out?: ColorSpace };
|
|
82
82
|
/** A filter has either `color` or `steps`. */
|
|
83
83
|
color?: ColorExpression;
|
|
84
84
|
steps?: Step[];
|
|
@@ -104,7 +104,7 @@ export interface NormalizedFilter {
|
|
|
104
104
|
params?: Record<string, NormalizedParam>;
|
|
105
105
|
images?: Record<string, ImageSpec>;
|
|
106
106
|
graphics?: Record<string, GraphicSpec>;
|
|
107
|
-
space?: { in:
|
|
107
|
+
space?: { in: ColorSpace; out: ColorSpace };
|
|
108
108
|
color?: string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
109
109
|
steps?: NormalizedStep[];
|
|
110
110
|
}
|