@mathzetta/qblur 0.0.0-stage → 0.1.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 +29 -0
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/cpu-worker.js +2 -0
- package/dist/qblur-apply.js +2 -0
- package/dist/qblur-element.js +2 -0
- package/dist/qblur.core.js +2 -0
- package/dist/qblur.external.global.min.js +2 -0
- package/dist/qblur.external.js +2 -0
- package/dist/qblur.global.min.js +2 -0
- package/dist/qblur.js +2 -0
- package/docs/filters.md +841 -0
- package/docs/library.md +604 -0
- package/package.json +112 -4
- package/src/apply-filter.js +245 -0
- package/src/apply.d.ts +64 -0
- package/src/apply.js +14 -0
- package/src/auto.js +41 -0
- package/src/cpu-helpers.js +416 -0
- package/src/cpu-runner.js +268 -0
- package/src/cpu-worker.js +58 -0
- package/src/cpu.js +581 -0
- package/src/element.d.ts +16 -0
- package/src/element.js +142 -0
- package/src/format.js +605 -0
- package/src/graphics.js +305 -0
- package/src/index.d.ts +283 -0
- package/src/index.js +13 -0
- package/src/library.js +173 -0
- package/src/png.js +154 -0
- package/src/runtime.js +229 -0
- package/src/save.js +108 -0
- package/src/strokes.js +342 -0
package/src/format.js
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shareable image filters.
|
|
3
|
+
*
|
|
4
|
+
* A filter is a small JSON document anyone can publish — maths plus a
|
|
5
|
+
* name, an author, the knobs it exposes and the pictures it needs:
|
|
6
|
+
*
|
|
7
|
+
* { "format": "mathzetta-filter/1",
|
|
8
|
+
* "name": "Threshold", "author": "Ada",
|
|
9
|
+
* "description": "Black or white, at a cutoff you choose",
|
|
10
|
+
* "params": { "cutoff": { "default": 0.5, "min": 0, "max": 1 } },
|
|
11
|
+
* "color": "if gray > cutoff then 1 else 0" }
|
|
12
|
+
*
|
|
13
|
+
* { "name": "Through a mask", "images": { "mask": { "description": "light where the effect shows" } },
|
|
14
|
+
* "color": "mix(source, rgb, luma(mask))" }
|
|
15
|
+
*
|
|
16
|
+
* A chain combines filters: each step is a filter (or just an expression)
|
|
17
|
+
* with optional settings for its params and an opacity:
|
|
18
|
+
*
|
|
19
|
+
* { "format": "mathzetta-filter/1", "name": "Old film", "author": "Bo",
|
|
20
|
+
* "steps": [
|
|
21
|
+
* { "filter": { …Ada's Threshold… }, "with": { "cutoff": 0.3 }, "opacity": 0.5 },
|
|
22
|
+
* "rgb * 0.9" ] }
|
|
23
|
+
*
|
|
24
|
+
* A chain is a filter too, so published chains nest inside new ones and
|
|
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.
|
|
28
|
+
*
|
|
29
|
+
* normalizeFilter() fills in defaults and rejects bad shapes,
|
|
30
|
+
* validateFilter() lists every problem, and compileFilter() flattens a
|
|
31
|
+
* filter into the shader passes runtime.js draws. filterToJSON() /
|
|
32
|
+
* filterFromJSON() and filterToLink() / filterFromLink() are the two ways
|
|
33
|
+
* to pass one around; readFilter() accepts either, or a bare expression.
|
|
34
|
+
*/
|
|
35
|
+
import { filterShader } from 'mathzetta/glsl';
|
|
36
|
+
import { FILTER_NAMES, PLACES, COLOUR_SPACES } from 'mathzetta/glsl';
|
|
37
|
+
import { normalizeGraphic, shadowLayerNames, MAX_SHADOW_LAYERS } from './graphics.js';
|
|
38
|
+
|
|
39
|
+
export const FILTER_FORMAT = 'mathzetta-filter/1';
|
|
40
|
+
|
|
41
|
+
const CHANNELS = ['r', 'g', 'b', 'a', 'rgb', 'rgba'];
|
|
42
|
+
const NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
43
|
+
|
|
44
|
+
/** Names a parameter can't take: what every expression already has, and GLSL's own words. */
|
|
45
|
+
const RESERVED = new Set([
|
|
46
|
+
...FILTER_NAMES, 'r', 'g', 'b', 'a', 'x', 'y', 'w', 'h', 't', 'c', 'e', 'pi',
|
|
47
|
+
'color', 'image', 'resolution', 'base', 'position', 'main',
|
|
48
|
+
'in', 'out', 'inout', 'const', 'uniform', 'varying', 'attribute', 'void', 'float', 'int', 'bool',
|
|
49
|
+
'vec2', 'vec3', 'vec4', 'mat2', 'mat3', 'mat4', 'sampler2D', 'struct', 'precision', 'highp', 'mediump', 'lowp',
|
|
50
|
+
'if', 'else', 'for', 'while', 'do', 'return', 'break', 'continue', 'discard', 'true', 'false',
|
|
51
|
+
'texture2D', 'texture', 'mix', 'clamp', 'step', 'smoothstep', 'abs', 'sign', 'floor', 'ceil', 'fract', 'mod',
|
|
52
|
+
'min', 'max', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'exp', 'log', 'exp2', 'log2', 'sqrt',
|
|
53
|
+
'inversesqrt', 'length', 'distance', 'dot', 'cross', 'normalize', 'radians', 'degrees',
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
const isColor = (v) => Array.isArray(v) && v.length === 3 && v.every((n) => Number.isFinite(Number(n)));
|
|
57
|
+
const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
|
58
|
+
/** How a named picture sits over the frame unless the filter or the chain says otherwise. */
|
|
59
|
+
export const PLACEMENT = { place: 'cover', zoom: 1, x: 0.5, y: 0.5, angle: 0 };
|
|
60
|
+
|
|
61
|
+
// ---- the shape ------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The full form of a filter: a string becomes `{ color }`, params get
|
|
65
|
+
* their type and range, every step gets `with` and `opacity`. Throws on
|
|
66
|
+
* anything that isn't a filter.
|
|
67
|
+
*/
|
|
68
|
+
export function normalizeFilter(def) {
|
|
69
|
+
if (typeof def === 'string') {
|
|
70
|
+
if (!def.trim()) throw new Error('The filter is empty');
|
|
71
|
+
return { format: FILTER_FORMAT, color: def.trim() };
|
|
72
|
+
}
|
|
73
|
+
if (!def || typeof def !== 'object' || Array.isArray(def)) throw new Error('A filter is an expression, or an object with "color" or "steps"');
|
|
74
|
+
if (def.format !== undefined && def.format !== FILTER_FORMAT) throw new Error(`Unknown filter format "${def.format}" (this is ${FILTER_FORMAT})`);
|
|
75
|
+
const out = { format: FILTER_FORMAT };
|
|
76
|
+
for (const key of ['name', 'author', 'description']) if (def[key] !== undefined && def[key] !== '') out[key] = String(def[key]);
|
|
77
|
+
if (def.steps !== undefined) {
|
|
78
|
+
if (def.color !== undefined) throw new Error('A filter has either "color" or "steps", not both');
|
|
79
|
+
if (!Array.isArray(def.steps) || !def.steps.length) throw new Error('"steps" must be a list with at least one step');
|
|
80
|
+
out.steps = def.steps.map(normalizeStep);
|
|
81
|
+
if (def.notes !== undefined) out.notes = normalizeNotes(def.notes, filterParams(out));
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
if (def.color === undefined) throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');
|
|
85
|
+
const params = normalizeParams(def.params ?? {});
|
|
86
|
+
if (Object.keys(params).length) out.params = params;
|
|
87
|
+
if (def.notes !== undefined) out.notes = normalizeNotes(def.notes, params);
|
|
88
|
+
const images = normalizeImages(def.images ?? {}, params);
|
|
89
|
+
if (Object.keys(images).length) out.images = images;
|
|
90
|
+
const graphics = normalizeGraphics(def.graphics ?? {}, params, images);
|
|
91
|
+
if (Object.keys(graphics).length) out.graphics = graphics;
|
|
92
|
+
const space = normalizeSpace(def.space);
|
|
93
|
+
if (space) out.space = space;
|
|
94
|
+
out.color = normalizeColor(def.color);
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The filter's page: Markdown text (with maths: Inline Math draws it, and `{{k}}` is a knob's value)
|
|
100
|
+
* and where each knob's input goes — `["Darker below the *cutoff*:", { "param": "cutoff" }]`.
|
|
101
|
+
* Knobs it doesn't place come before it.
|
|
102
|
+
*/
|
|
103
|
+
function normalizeNotes(notes, params) {
|
|
104
|
+
if (!Array.isArray(notes)) throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');
|
|
105
|
+
return notes.map((block) => {
|
|
106
|
+
if (typeof block === 'string') return block;
|
|
107
|
+
if (!isObject(block) || typeof block.param !== 'string' || Object.keys(block).length !== 1) throw new Error('"notes": each entry is a Markdown text or { "param": name }');
|
|
108
|
+
if (!(block.param in params)) throw new Error(`"notes" places "${block.param}", but there is no parameter called that`);
|
|
109
|
+
return { param: block.param };
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** `"hsv"` or `{ "in": "hsv", "out": "srgb" }` → `{ in, out }`; nothing when both are sRGB. */
|
|
114
|
+
function normalizeSpace(space) {
|
|
115
|
+
if (space === undefined || space === null) return null;
|
|
116
|
+
const pair = typeof space === 'string' ? { in: space, out: space } : space;
|
|
117
|
+
if (!isObject(pair)) throw new Error(`"space" is a colour space (${COLOUR_SPACES.join(', ')}) or { "in": …, "out": … }`);
|
|
118
|
+
const out = { in: pair.in ?? 'srgb', out: pair.out ?? 'srgb' };
|
|
119
|
+
for (const key of ['in', 'out']) {
|
|
120
|
+
if (!COLOUR_SPACES.includes(out[key])) throw new Error(`"space": "${out[key]}" is not a colour space; they are ${COLOUR_SPACES.join(', ')}`);
|
|
121
|
+
}
|
|
122
|
+
return out.in === 'srgb' && out.out === 'srgb' ? null : out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** `{ "title": { "type": "text", "text": "Hello", … } }` → each spec in full (src/graphics.js). */
|
|
126
|
+
function normalizeGraphics(graphics, params, images) {
|
|
127
|
+
if (!isObject(graphics)) throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const [name, spec] of Object.entries(graphics)) {
|
|
130
|
+
if (!NAME.test(name) || name.startsWith('mz_')) throw new Error(`Graphic name "${name}" must be letters, digits and _, starting with a letter`);
|
|
131
|
+
if (RESERVED.has(name) || name === 'source' || name === 'selection') throw new Error(`"${name}" is already defined in every filter; pick another graphic name`);
|
|
132
|
+
if (name in params || name in images) throw new Error(`"${name}" is both a graphic and a parameter or picture`);
|
|
133
|
+
out[name] = normalizeGraphic(name, spec);
|
|
134
|
+
}
|
|
135
|
+
// name_shadow1… are the pictures of its shadow layers: no other name may be one
|
|
136
|
+
const layers = new Set(Object.keys(out).flatMap((name) => Array.from({ length: MAX_SHADOW_LAYERS }, (_, k) => `${name}_shadow${k + 1}`)));
|
|
137
|
+
for (const name of [...Object.keys(out), ...Object.keys(params), ...Object.keys(images)]) {
|
|
138
|
+
if (layers.has(name)) throw new Error(`"${name}" is the name of a shadow layer of another graphic; pick another name`);
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Every graphic a filter draws, including those of the filters inside a chain (first one wins). */
|
|
144
|
+
export function filterGraphics(filter) {
|
|
145
|
+
if (filter.color) return { ...(filter.graphics ?? {}) };
|
|
146
|
+
const out = {};
|
|
147
|
+
for (const step of filter.steps) {
|
|
148
|
+
for (const [name, g] of Object.entries(filterGraphics(step.filter))) if (!(name in out)) out[name] = g;
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** `["mask", "overlay"]` or `{ "mask": { "description": "…" } }` → the object form. */
|
|
154
|
+
function normalizeImages(images, params) {
|
|
155
|
+
const list = Array.isArray(images) ? Object.fromEntries(images.map((name) => [name, {}])) : images;
|
|
156
|
+
if (!list || typeof list !== 'object') throw new Error('"images" is a list of names, or an object of name → { description }');
|
|
157
|
+
const out = {};
|
|
158
|
+
for (const [name, spec] of Object.entries(list)) {
|
|
159
|
+
if (!NAME.test(name) || name.startsWith('mz_')) throw new Error(`Image name "${name}" must be letters, digits and _, starting with a letter`);
|
|
160
|
+
if (name === 'source') throw new Error('"source" is always available: the picture the chain started from');
|
|
161
|
+
if (RESERVED.has(name)) throw new Error(`"${name}" is already defined in every filter; pick another image name`);
|
|
162
|
+
if (name in params) throw new Error(`"${name}" is both a parameter and an image`);
|
|
163
|
+
out[name] = normalizeImage(name, spec);
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `{ description, place, zoom, x, y, angle }` — only what is given; the rest is PLACEMENT. */
|
|
169
|
+
function normalizeImage(name, spec) {
|
|
170
|
+
if (!isObject(spec)) throw new Error(`Image "${name}": give { description, place, zoom, x, y, angle }`);
|
|
171
|
+
const out = {};
|
|
172
|
+
if (spec.description) out.description = String(spec.description);
|
|
173
|
+
if (spec.place !== undefined) {
|
|
174
|
+
if (!PLACES.includes(spec.place)) throw new Error(`Image "${name}": "place" is ${PLACES.join(', ')} — not "${spec.place}"`);
|
|
175
|
+
out.place = spec.place;
|
|
176
|
+
}
|
|
177
|
+
for (const key of ['zoom', 'x', 'y', 'angle']) {
|
|
178
|
+
if (spec[key] === undefined) continue;
|
|
179
|
+
const value = Number(spec[key]);
|
|
180
|
+
if (!Number.isFinite(value)) throw new Error(`Image "${name}": "${key}" is a number`);
|
|
181
|
+
out[key] = value;
|
|
182
|
+
}
|
|
183
|
+
for (const key of Object.keys(spec)) if (!['description', 'place', 'zoom', 'x', 'y', 'angle'].includes(key)) throw new Error(`Image "${name}": no such setting "${key}"`);
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function normalizeStep(step) {
|
|
188
|
+
if (typeof step === 'string') return { filter: normalizeFilter(step), with: {}, opacity: 1, skip: false };
|
|
189
|
+
if (!step || typeof step !== 'object' || Array.isArray(step)) throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');
|
|
190
|
+
const { filter, with: settings, opacity, skip, ...rest } = step;
|
|
191
|
+
const out = { filter: normalizeFilter(filter !== undefined ? filter : rest), with: {}, opacity: 1, skip: Boolean(skip) };
|
|
192
|
+
if (settings !== undefined) {
|
|
193
|
+
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('"with" is an object of parameter name → value');
|
|
194
|
+
out.with = { ...settings };
|
|
195
|
+
}
|
|
196
|
+
if (opacity !== undefined) {
|
|
197
|
+
const value = Number(opacity);
|
|
198
|
+
if (!(value >= 0 && value <= 1)) throw new Error('"opacity" is a number from 0 to 1');
|
|
199
|
+
out.opacity = value;
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function normalizeParams(params) {
|
|
205
|
+
if (!params || typeof params !== 'object' || Array.isArray(params)) throw new Error('"params" is an object of name → { default, min, max }');
|
|
206
|
+
const out = {};
|
|
207
|
+
for (const [name, spec] of Object.entries(params)) {
|
|
208
|
+
if (!NAME.test(name)) throw new Error(`Parameter name "${name}" must be letters, digits and _, starting with a letter`);
|
|
209
|
+
if (RESERVED.has(name)) throw new Error(`"${name}" is already defined in every filter; pick another parameter name`);
|
|
210
|
+
out[name] = normalizeParam(name, spec);
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** `0.5` → a number 0–1; `[1, 0, 0]` → a colour; or the full `{ type, default, min, max, step, label }`. */
|
|
216
|
+
function normalizeParam(name, spec) {
|
|
217
|
+
if (typeof spec === 'number') spec = { default: spec };
|
|
218
|
+
else if (Array.isArray(spec)) spec = { type: 'color', default: spec };
|
|
219
|
+
else if (!spec || typeof spec !== 'object') throw new Error(`Parameter "${name}" needs a default value`);
|
|
220
|
+
const type = spec.type ?? (Array.isArray(spec.default) ? 'color' : 'number');
|
|
221
|
+
const out = { type };
|
|
222
|
+
if (spec.label !== undefined) out.label = String(spec.label);
|
|
223
|
+
if (type === 'color') {
|
|
224
|
+
const value = spec.default ?? [1, 1, 1];
|
|
225
|
+
if (!isColor(value)) throw new Error(`Colour parameter "${name}" needs a default of three numbers, 0–1`);
|
|
226
|
+
out.default = value.map(Number);
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
if (type !== 'number') throw new Error(`Parameter "${name}": the type is "number" or "color", not "${type}"`);
|
|
230
|
+
// `options`: a choice of values (a menu); `input: "box"`: typed in, as maths; otherwise a slider
|
|
231
|
+
let options = null;
|
|
232
|
+
if (spec.options !== undefined) {
|
|
233
|
+
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`);
|
|
234
|
+
options = spec.options.map(Number);
|
|
235
|
+
}
|
|
236
|
+
if (spec.input !== undefined && spec.input !== 'slider' && spec.input !== 'box') throw new Error(`Parameter "${name}": "input" is "slider" or "box", not "${spec.input}"`);
|
|
237
|
+
const value = Number(spec.default ?? (options ? options[0] : 0));
|
|
238
|
+
if (!Number.isFinite(value)) throw new Error(`Parameter "${name}" needs a numeric default`);
|
|
239
|
+
out.default = value;
|
|
240
|
+
out.min = spec.min !== undefined ? Number(spec.min) : options ? Math.min(...options, value) : Math.min(0, value * 2);
|
|
241
|
+
out.max = spec.max !== undefined ? Number(spec.max) : options ? Math.max(...options, value) : Math.max(1, value * 2);
|
|
242
|
+
if (spec.step !== undefined) out.step = Number(spec.step);
|
|
243
|
+
if (options) out.options = options;
|
|
244
|
+
if (spec.input === 'box' && !options) out.input = 'box';
|
|
245
|
+
if (!(out.min <= value && value <= out.max)) throw new Error(`Parameter "${name}": the default ${value} is outside ${out.min} to ${out.max}`);
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function normalizeColor(color) {
|
|
250
|
+
if (typeof color === 'string') {
|
|
251
|
+
if (!color.trim()) throw new Error('"color" is empty');
|
|
252
|
+
return color.trim();
|
|
253
|
+
}
|
|
254
|
+
if (!color || typeof color !== 'object' || Array.isArray(color)) throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');
|
|
255
|
+
const out = {};
|
|
256
|
+
for (const [channel, expression] of Object.entries(color)) {
|
|
257
|
+
if (!CHANNELS.includes(channel)) throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${channel}"`);
|
|
258
|
+
if (typeof expression !== 'string' || !expression.trim()) throw new Error(`"color.${channel}" must be an expression`);
|
|
259
|
+
out[channel] = expression.trim();
|
|
260
|
+
}
|
|
261
|
+
if (!Object.keys(out).length) throw new Error('"color" sets no channels');
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Every picture a filter needs, including those of the filters inside a chain (first description wins). */
|
|
266
|
+
export function filterImages(filter) {
|
|
267
|
+
if (filter.color) return { ...(filter.images ?? {}) };
|
|
268
|
+
const out = {};
|
|
269
|
+
for (const step of filter.steps) {
|
|
270
|
+
for (const [name, image] of Object.entries(filterImages(step.filter))) if (!(name in out)) out[name] = image;
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Every parameter a filter exposes, including those of the filters inside a chain (first one wins). */
|
|
276
|
+
export function filterParams(filter) {
|
|
277
|
+
if (filter.color) return { ...(filter.params ?? {}) };
|
|
278
|
+
const out = {};
|
|
279
|
+
for (const step of filter.steps) {
|
|
280
|
+
for (const [name, param] of Object.entries(filterParams(step.filter))) if (!(name in out)) out[name] = param;
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ---- checking -------------------------------------------------------------
|
|
286
|
+
|
|
287
|
+
/** Every problem with a filter, as messages; empty when it will compile. */
|
|
288
|
+
export function validateFilter(def) {
|
|
289
|
+
let filter;
|
|
290
|
+
try { filter = normalizeFilter(def); } catch (e) { return [e.message]; }
|
|
291
|
+
const problems = [];
|
|
292
|
+
check({ filter, with: {}, opacity: 1 }, [], problems, true);
|
|
293
|
+
return problems;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Settings problems, and — with `shaders` — whether each expression compiles (compileFilter() learns that as it builds). */
|
|
297
|
+
function check(step, path, problems, shaders) {
|
|
298
|
+
const { filter } = step;
|
|
299
|
+
const where = describe(filter, path);
|
|
300
|
+
const params = filterParams(filter);
|
|
301
|
+
const images = filterImages(filter);
|
|
302
|
+
const graphics = filterGraphics(filter);
|
|
303
|
+
for (const [name, value] of Object.entries(step.with)) {
|
|
304
|
+
if (name in graphics) { // changing a graphic: { text, x, color, … }
|
|
305
|
+
if (!isObject(value)) problems.push(`${where}: "with" for the graphic "${name}" is an object of its settings`);
|
|
306
|
+
else try { normalizeGraphic(name, { ...graphics[name], ...value }); } catch (e) { problems.push(`${where}: ${e.message}`); }
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (name in images) { // placing a picture: { place, zoom, x, y, angle }
|
|
310
|
+
try { normalizeImage(name, value); } catch (e) { problems.push(`${where}: ${e.message}`); }
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const param = params[name];
|
|
314
|
+
if (!param) problems.push(`${where}: "with" sets "${name}", but there is no parameter called that`);
|
|
315
|
+
else if (param.type === 'color' ? !isColor(value) : !Number.isFinite(Number(value))) {
|
|
316
|
+
problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'colour: three numbers, 0–1' : 'number'}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (filter.steps) {
|
|
320
|
+
filter.steps.forEach((inner, i) => check(inner, [...path, i], problems, shaders));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (shaders) try { makePass(filter, Object.fromEntries(Object.entries(step.with).filter(([k]) => k in (filter.graphics ?? {}))), 1, path, 100); } catch (e) { problems.push(`${where}: ${e.message}`); } // with its settings: a "with" may add shadow layers
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function describe(filter, path) {
|
|
327
|
+
if (filter.name) return `"${filter.name}"`;
|
|
328
|
+
return path.length ? `step ${path.map((i) => i + 1).join('.')}` : 'the filter';
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---- compiling ------------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* A filter flattened into shader passes, in order. Each pass has the
|
|
335
|
+
* fragment shader, its `params` (declared as uniforms), the `values` to
|
|
336
|
+
* set them to, the `images` it samples (`source` among them when used)
|
|
337
|
+
* with how each is placed (`placements`: place, zoom, x, y, angle — live,
|
|
338
|
+
* like `values`), and an `opacity` (how much of the result shows over the
|
|
339
|
+
* pass's input). A chain used at partial opacity keeps its input
|
|
340
|
+
* (`keepInput`) and ends with a blend pass (`blendKept`).
|
|
341
|
+
*
|
|
342
|
+
* @param {string|object} def
|
|
343
|
+
* @param {{ version?: 100|300 }} [options]
|
|
344
|
+
* @returns {{ name, author, description, version, passes, credits }}
|
|
345
|
+
*/
|
|
346
|
+
export function compileFilter(def, options = {}) {
|
|
347
|
+
const filter = normalizeFilter(def);
|
|
348
|
+
const problems = [];
|
|
349
|
+
check({ filter, with: {}, opacity: 1 }, [], problems, false);
|
|
350
|
+
if (problems.length) throw new Error(problems.join('\n'));
|
|
351
|
+
const context = { passes: [], credits: [], problems, version: options.version === 300 ? 300 : 100, top: filter, graphics: {} };
|
|
352
|
+
flatten({ filter, with: {}, opacity: 1, skip: false }, [], {}, context);
|
|
353
|
+
if (problems.length) throw new Error(problems.join('\n'));
|
|
354
|
+
if (!context.passes.length) { // every step skipped: the picture as it is
|
|
355
|
+
context.passes.push(makePass(normalizeFilter('pixel(px, py)'), {}, 1, [], context.version));
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
name: filter.name ?? '',
|
|
359
|
+
author: filter.author ?? '',
|
|
360
|
+
description: filter.description ?? '',
|
|
361
|
+
version: context.version,
|
|
362
|
+
passes: context.passes,
|
|
363
|
+
credits: context.credits,
|
|
364
|
+
images: filterImages(filter),
|
|
365
|
+
graphics: context.graphics, // key → spec as drawn (with the chain's settings); pass.bind maps a pass's names to keys
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function flatten(step, path, outer, context) {
|
|
370
|
+
if (step.skip) return; // switched off: no passes, no credit
|
|
371
|
+
const rewritten = inColourSpace(step.filter) ?? separableBlur(step.filter);
|
|
372
|
+
if (rewritten) {
|
|
373
|
+
if (step.filter === context.top) context.top = rewritten; // still the filter itself, not something it uses
|
|
374
|
+
flatten({ ...step, filter: rewritten }, path, outer, context);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const { filter } = step;
|
|
378
|
+
const settings = { ...step.with, ...outer }; // whoever combines decides: outer settings win
|
|
379
|
+
for (const key of Object.keys(outer)) if (isObject(outer[key]) && isObject(step.with[key])) settings[key] = { ...step.with[key], ...outer[key] };
|
|
380
|
+
if (filter.name && filter !== context.top && !context.credits.some((c) => c.name === filter.name && c.author === (filter.author ?? ''))) {
|
|
381
|
+
context.credits.push({ name: filter.name, author: filter.author ?? '' });
|
|
382
|
+
}
|
|
383
|
+
if (filter.color) {
|
|
384
|
+
try { context.passes.push(bindGraphics(makePass(filter, settings, step.opacity, path, context.version), context.graphics)); }
|
|
385
|
+
catch (e) { context.problems.push(`${describe(filter, path)}: ${e.message}`); }
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const start = context.passes.length;
|
|
389
|
+
filter.steps.forEach((inner, i) => flatten(inner, [...path, i], settings, context));
|
|
390
|
+
if (step.opacity < 1) {
|
|
391
|
+
// mix(c, mix(c, f, a), b) is mix(c, f, ab): one pass can just fade more.
|
|
392
|
+
if (context.passes.length - start === 1) context.passes[start].opacity *= step.opacity;
|
|
393
|
+
else {
|
|
394
|
+
context.passes[start].keepInput += 1;
|
|
395
|
+
context.passes.push(blendPass(step.opacity, path, context.version));
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* A step whose whole colour is just `gaussian(s)` or `blur(r)` is computed
|
|
402
|
+
* separably — one pass along x, one along y: the same blur for 2n taps
|
|
403
|
+
* instead of n², and reaching further (±24 pixels instead of ±8). The
|
|
404
|
+
* step keeps its name, params, pictures and opacity; the two passes share
|
|
405
|
+
* its settings.
|
|
406
|
+
*/
|
|
407
|
+
/**
|
|
408
|
+
* A filter with a `space` becomes a chain: convert the frame into the
|
|
409
|
+
* space (its values, kept 0–1, go through the texture between passes),
|
|
410
|
+
* the filter itself — told the space, so pictures it samples are
|
|
411
|
+
* converted too — then convert back. Opacity blends the result over
|
|
412
|
+
* the input in sRGB, as any chain's does.
|
|
413
|
+
*/
|
|
414
|
+
function inColourSpace(filter) {
|
|
415
|
+
if (!filter.space || typeof filter.color === 'undefined') return null;
|
|
416
|
+
const { space, name, author, description, ...core } = filter; // the chain carries the name; the middle step is nameless, so it is not a credit
|
|
417
|
+
const step = (f) => ({ filter: f, with: {}, opacity: 1, skip: false });
|
|
418
|
+
const steps = [];
|
|
419
|
+
if (space.in !== 'srgb') steps.push(step({ format: FILTER_FORMAT, color: { rgb: `to${space.in}(rgb)` } }));
|
|
420
|
+
steps.push(step({ ...core, _space: space.in }));
|
|
421
|
+
if (space.out !== 'srgb') steps.push(step({ format: FILTER_FORMAT, color: { rgb: `from${space.out}(rgb)` } }));
|
|
422
|
+
const chain = { format: FILTER_FORMAT, steps };
|
|
423
|
+
for (const [key, value] of Object.entries({ name, author, description })) if (value) chain[key] = value;
|
|
424
|
+
return chain;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function separableBlur(filter) {
|
|
428
|
+
if (typeof filter.color !== 'string') return null;
|
|
429
|
+
const m = /^(gaussian|blur)\((.*)\)$/s.exec(filter.color.trim());
|
|
430
|
+
if (!m) return null;
|
|
431
|
+
let depth = 0;
|
|
432
|
+
for (const ch of m[2]) { // the brackets must belong to this one call: not "gaussian(2) + blur(3)"
|
|
433
|
+
if (ch === '(') depth++;
|
|
434
|
+
else if (ch === ')' && --depth < 0) return null;
|
|
435
|
+
}
|
|
436
|
+
if (depth !== 0) return null;
|
|
437
|
+
const { color, ...rest } = filter;
|
|
438
|
+
const half = (axis) => {
|
|
439
|
+
const inner = { format: FILTER_FORMAT, color: `${m[1]}${axis}(${m[2]})` };
|
|
440
|
+
if (rest.params) inner.params = rest.params;
|
|
441
|
+
if (rest.images) inner.images = rest.images;
|
|
442
|
+
if (rest.graphics) inner.graphics = rest.graphics;
|
|
443
|
+
return { filter: inner, with: {}, opacity: 1, skip: false };
|
|
444
|
+
};
|
|
445
|
+
return { ...rest, steps: [half('x'), half('y')] };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Pictures are shared by name across a chain (every step asking for `mask` gets the
|
|
450
|
+
* same one), but a graphic belongs to its step: two steps that both call their text
|
|
451
|
+
* `title` draw two different texts. So each pass's graphic gets a key of its own —
|
|
452
|
+
* `title`, then `title~2`… — the picture is drawn and bound under the key, and
|
|
453
|
+
* `pass.bind` says which key a name in that pass means.
|
|
454
|
+
*/
|
|
455
|
+
function bindGraphics(pass, all) {
|
|
456
|
+
pass.bind = {};
|
|
457
|
+
for (const [name, spec] of Object.entries(pass.graphics ?? {})) {
|
|
458
|
+
let key = name;
|
|
459
|
+
for (let n = 2; key in all && JSON.stringify(all[key]) !== JSON.stringify(spec); n++) key = `${name}~${n}`;
|
|
460
|
+
all[key] = spec;
|
|
461
|
+
pass.bind[name] = key;
|
|
462
|
+
}
|
|
463
|
+
return pass;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function makePass(filter, settings, opacity, path, version) {
|
|
467
|
+
const params = filter.params ?? {};
|
|
468
|
+
const values = {};
|
|
469
|
+
for (const [name, param] of Object.entries(params)) {
|
|
470
|
+
if (!(name in settings)) values[name] = param.default;
|
|
471
|
+
else values[name] = param.type === 'color' ? settings[name].map(Number) : Number(settings[name]);
|
|
472
|
+
}
|
|
473
|
+
const placements = {};
|
|
474
|
+
for (const [name, spec] of Object.entries(filter.images ?? {})) {
|
|
475
|
+
const { description, ...declared } = spec;
|
|
476
|
+
placements[name] = { ...PLACEMENT, ...declared, ...(isObject(settings[name]) ? settings[name] : {}) };
|
|
477
|
+
}
|
|
478
|
+
// A graphic is a frame-sized picture the page (or renderGraphics) draws: stretched, so it lies exactly on the frame.
|
|
479
|
+
const graphics = {};
|
|
480
|
+
for (const [name, spec] of Object.entries(filter.graphics ?? {})) {
|
|
481
|
+
graphics[name] = isObject(settings[name]) ? normalizeGraphic(name, { ...spec, ...settings[name] }) : spec;
|
|
482
|
+
placements[name] = { ...PLACEMENT, place: 'stretch' };
|
|
483
|
+
shadowLayerNames(name, graphics[name]).forEach((layer, k) => { // each shadow layer: a picture of its own
|
|
484
|
+
graphics[layer] = { ...graphics[name], onlyShadow: k };
|
|
485
|
+
placements[layer] = { ...PLACEMENT, place: 'stretch' };
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
const fragment = shaderFor(filter, version, placements);
|
|
489
|
+
const images = Object.keys(placements);
|
|
490
|
+
if (fragment.includes('uniform sampler2D mz_img_source;')) images.push('source');
|
|
491
|
+
if (fragment.includes('uniform sampler2D mz_img_selection;')) images.push('selection');
|
|
492
|
+
// `color` is the filter's own expression(s): the CPU runner compiles that, the GPU runner the fragment shader.
|
|
493
|
+
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 };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function shaderFor(filter, version, placements = null) {
|
|
497
|
+
const params = filter.params ?? {};
|
|
498
|
+
const uniforms = {};
|
|
499
|
+
for (const [name, param] of Object.entries(params)) uniforms[name] = param.type === 'color' ? 'vec3' : 'float';
|
|
500
|
+
const images = {};
|
|
501
|
+
for (const [name, spec] of Object.entries(filter.images ?? {})) images[name] = { place: placements?.[name]?.place ?? spec.place ?? PLACEMENT.place };
|
|
502
|
+
for (const [name, spec] of Object.entries(filter.graphics ?? {})) {
|
|
503
|
+
images[name] = { place: 'stretch' };
|
|
504
|
+
// its shadow layers: as compiled (a chain's "with" may add some), or as the filter has them when only checking
|
|
505
|
+
const layers = placements ? Object.keys(placements).filter((k) => /_shadow\d+$/.test(k) && k.startsWith(`${name}_shadow`)) : shadowLayerNames(name, spec);
|
|
506
|
+
for (const layer of layers) images[layer] = { place: 'stretch' };
|
|
507
|
+
}
|
|
508
|
+
return filterShader(filter.color, { version, uniforms, values: Object.keys(params), images, blend: true, space: filter._space ?? filter.space?.in ?? 'srgb' });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Mixes the pass before it (`image`) over the input a chain started from (`base`). */
|
|
512
|
+
function blendPass(opacity, path, version) {
|
|
513
|
+
const es3 = version === 300;
|
|
514
|
+
const sample = es3 ? 'texture' : 'texture2D';
|
|
515
|
+
const fragment = [
|
|
516
|
+
es3 ? '#version 300 es' : '',
|
|
517
|
+
'precision highp float;',
|
|
518
|
+
'uniform sampler2D image;',
|
|
519
|
+
'uniform sampler2D base;',
|
|
520
|
+
'uniform vec2 resolution;',
|
|
521
|
+
'uniform float mz_opacity;',
|
|
522
|
+
es3 ? 'out vec4 fragColor;' : '',
|
|
523
|
+
'void main() {',
|
|
524
|
+
' vec2 uv = gl_FragCoord.xy / resolution;',
|
|
525
|
+
` ${es3 ? 'fragColor' : 'gl_FragColor'} = mix(${sample}(base, uv), ${sample}(image, uv), mz_opacity);`,
|
|
526
|
+
'}',
|
|
527
|
+
].filter(Boolean).join('\n');
|
|
528
|
+
return { name: 'blend', author: '', path, fragment, params: {}, values: {}, opacity, images: [], placements: {}, graphics: {}, keepInput: 0, blendKept: true };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ---- passing filters around ----------------------------------------------
|
|
532
|
+
|
|
533
|
+
/** The filter as JSON to publish: normalized, with defaults left out. */
|
|
534
|
+
export function filterToJSON(def) {
|
|
535
|
+
return JSON.stringify(tidy(normalizeFilter(def), true), null, 2);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function filterFromJSON(text) {
|
|
539
|
+
let raw;
|
|
540
|
+
try { raw = JSON.parse(text); } catch { throw new Error('Not valid JSON'); }
|
|
541
|
+
return normalizeFilter(raw);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** `base + '#' + the filter`, URL-safe; `base` is the page that opens it. */
|
|
545
|
+
export function filterToLink(def, base = '') {
|
|
546
|
+
return `${base}#${toBase64Url(JSON.stringify(tidy(normalizeFilter(def), true)))}`;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
export function filterFromLink(text) {
|
|
550
|
+
const hash = text.includes('#') ? text.slice(text.lastIndexOf('#') + 1) : text;
|
|
551
|
+
let raw;
|
|
552
|
+
try { raw = JSON.parse(fromBase64Url(hash.trim())); } catch { throw new Error('Not a filter link'); }
|
|
553
|
+
return normalizeFilter(raw);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** A filter from whatever someone pasted: JSON, a share link, or a bare expression. */
|
|
557
|
+
export function readFilter(text) {
|
|
558
|
+
const trimmed = String(text ?? '').trim();
|
|
559
|
+
if (!trimmed) throw new Error('Nothing to read');
|
|
560
|
+
if (trimmed.startsWith('{')) return filterFromJSON(trimmed);
|
|
561
|
+
if (!/\s/.test(trimmed)) {
|
|
562
|
+
const hash = trimmed.includes('#') ? trimmed.slice(trimmed.lastIndexOf('#') + 1) : trimmed;
|
|
563
|
+
if (/^[A-Za-z0-9_-]{8,}$/.test(hash)) {
|
|
564
|
+
try { return filterFromLink(hash); } catch (e) { if (trimmed.includes('#')) throw e; }
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return normalizeFilter(trimmed);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** The normalized filter with defaults dropped: `with: {}`, `opacity: 1`, inner `format`s, and `{ color }` alone becomes its string. */
|
|
571
|
+
function tidy(filter, top) {
|
|
572
|
+
const out = {};
|
|
573
|
+
if (top) out.format = FILTER_FORMAT;
|
|
574
|
+
for (const key of ['name', 'author', 'description']) if (filter[key]) out[key] = filter[key];
|
|
575
|
+
if (filter.notes && filter.notes.length) out.notes = filter.notes;
|
|
576
|
+
if (filter.steps) {
|
|
577
|
+
out.steps = filter.steps.map((step) => {
|
|
578
|
+
const inner = tidy(step.filter, false);
|
|
579
|
+
const bare = Object.keys(inner).length === 1 && typeof inner.color === 'string' ? inner.color : inner;
|
|
580
|
+
const extras = {};
|
|
581
|
+
if (Object.keys(step.with).length) extras.with = step.with;
|
|
582
|
+
if (step.opacity !== 1) extras.opacity = step.opacity;
|
|
583
|
+
if (step.skip) extras.skip = true;
|
|
584
|
+
return Object.keys(extras).length ? { filter: bare, ...extras } : bare;
|
|
585
|
+
});
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
if (filter.params) out.params = filter.params;
|
|
589
|
+
if (filter.images) out.images = filter.images;
|
|
590
|
+
if (filter.graphics) out.graphics = filter.graphics;
|
|
591
|
+
if (filter.space) out.space = filter.space.in === filter.space.out ? filter.space.in : filter.space;
|
|
592
|
+
out.color = filter.color;
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function toBase64Url(text) {
|
|
597
|
+
let binary = '';
|
|
598
|
+
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
|
|
599
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function fromBase64Url(text) {
|
|
603
|
+
const binary = atob(text.replace(/-/g, '+').replace(/_/g, '/'));
|
|
604
|
+
return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
|
|
605
|
+
}
|