@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/save.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saving a result: a canvas or a picture ({ data, width, height }, what the
|
|
3
|
+
* CPU runner and applyFilter() in Node return) as a file.
|
|
4
|
+
*
|
|
5
|
+
* const blob = await toBlob(canvas, { type: 'image/jpeg', quality: 0.9 });
|
|
6
|
+
* const png = await toBlob(picture); // PNG in Node too: no canvas needed
|
|
7
|
+
* const gif = await encodeGif(frames, { gifenc, delay: 40 }); // bring your own gifenc
|
|
8
|
+
*
|
|
9
|
+
* PNG is written by the package itself (src/png.js: indexed when the picture
|
|
10
|
+
* has at most 256 colours, RGB when nothing is transparent), so it works
|
|
11
|
+
* anywhere CompressionStream does — every current browser and Node ≥ 18.
|
|
12
|
+
* JPEG and WebP need the browser's encoder (a canvas). GIF needs a colour
|
|
13
|
+
* quantizer and an LZW encoder; the package has no dependencies, so
|
|
14
|
+
* encodeGif() takes gifenc (npm i gifenc) as an option rather than bundling it.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { encodePng } from './png.js';
|
|
18
|
+
|
|
19
|
+
const isPicture = (v) => v && v.data && Number.isFinite(v.width) && Number.isFinite(v.height) && typeof v.getContext !== 'function';
|
|
20
|
+
|
|
21
|
+
/** The RGBA bytes of a canvas or a picture (8-bit, or 0–1 floats as the CPU runner keeps them). */
|
|
22
|
+
export function pictureData(what) {
|
|
23
|
+
if (isPicture(what)) {
|
|
24
|
+
const { data, width, height } = what;
|
|
25
|
+
if (data instanceof Uint8ClampedArray || data instanceof Uint8Array) return { data, width, height };
|
|
26
|
+
const out = new Uint8ClampedArray(width * height * 4);
|
|
27
|
+
const scale = data instanceof Float32Array || data instanceof Float64Array ? 255 : 1;
|
|
28
|
+
for (let j = 0; j < out.length; j++) out[j] = Math.round(data[j] * scale);
|
|
29
|
+
return { data: out, width, height };
|
|
30
|
+
}
|
|
31
|
+
if (what && typeof what.getContext === 'function') {
|
|
32
|
+
const ctx = what.getContext('2d', { willReadFrequently: true });
|
|
33
|
+
if (!ctx) throw new Error('This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first');
|
|
34
|
+
return ctx.getImageData(0, 0, what.width, what.height);
|
|
35
|
+
}
|
|
36
|
+
throw new Error('Give a canvas or a picture ({ data, width, height })');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A canvas (HTMLCanvasElement or OffscreenCanvas) holding the picture; null where there is none (Node). */
|
|
40
|
+
function canvasOf(picture) {
|
|
41
|
+
const { width, height } = picture;
|
|
42
|
+
let canvas = null;
|
|
43
|
+
if (typeof OffscreenCanvas !== 'undefined') canvas = new OffscreenCanvas(width, height);
|
|
44
|
+
else if (typeof document !== 'undefined') canvas = Object.assign(document.createElement('canvas'), { width, height });
|
|
45
|
+
if (!canvas) return null;
|
|
46
|
+
canvas.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(picture.data), width, height), 0, 0);
|
|
47
|
+
return canvas;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The picture as a file.
|
|
52
|
+
* @param {HTMLCanvasElement|OffscreenCanvas|{ data, width, height }} what
|
|
53
|
+
* @param {{ type?: string, quality?: number, palette?: 'auto' | 'none' }} [options]
|
|
54
|
+
* type: 'image/png' (the default), 'image/jpeg' or 'image/webp' (browser only); quality 0–1 for the last two.
|
|
55
|
+
* palette (PNG): 'auto' writes an indexed PNG when there are at most 256 colours, 'none' never does.
|
|
56
|
+
* @returns {Promise<Blob>}
|
|
57
|
+
*/
|
|
58
|
+
export async function toBlob(what, { type = 'image/png', quality, palette = 'auto' } = {}) {
|
|
59
|
+
if (type === 'image/png') {
|
|
60
|
+
const png = await encodePng({ ...pictureData(what), palette });
|
|
61
|
+
if (png) return png.blob;
|
|
62
|
+
}
|
|
63
|
+
const canvas = isPicture(what) ? canvasOf(pictureData(what)) : what;
|
|
64
|
+
if (!canvas) throw new Error(`Saving as ${type} needs a browser (a canvas encodes it); in Node, save as image/png`);
|
|
65
|
+
if (typeof canvas.convertToBlob === 'function') return canvas.convertToBlob({ type, quality });
|
|
66
|
+
return new Promise((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error(`The browser could not encode ${type}`))), type, quality));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* An animated GIF from frames (canvases or pictures, all one size), each `delay` ms.
|
|
71
|
+
* Needs gifenc: `import * as gifenc from 'gifenc'` and pass it as `{ gifenc }`.
|
|
72
|
+
* Each frame gets its own palette of up to `colours` colours.
|
|
73
|
+
* @param {Iterable|AsyncIterable} frames
|
|
74
|
+
* @param {{ gifenc: object, delay?: number, repeat?: number, colours?: number }} options
|
|
75
|
+
* @returns {Promise<Blob>}
|
|
76
|
+
*/
|
|
77
|
+
export async function encodeGif(frames, { gifenc, delay = 1000 / 30, repeat = 0, colours = 256 } = {}) {
|
|
78
|
+
const G = gifenc && (gifenc.GIFEncoder ? gifenc : gifenc.default);
|
|
79
|
+
if (!G || typeof G.GIFEncoder !== 'function') throw new Error('encodeGif needs gifenc: import * as gifenc from \'gifenc\' and pass { gifenc }');
|
|
80
|
+
const encoder = G.GIFEncoder();
|
|
81
|
+
let size = null;
|
|
82
|
+
let count = 0;
|
|
83
|
+
for await (const frame of frames) {
|
|
84
|
+
let { data, width, height } = pictureData(frame);
|
|
85
|
+
if (data.byteOffset || data.byteLength !== data.buffer.byteLength) data = data.slice(); // gifenc reads the whole buffer
|
|
86
|
+
if (size && (size[0] !== width || size[1] !== height)) throw new Error(`Frame ${count + 1} is ${width} × ${height}; the first was ${size[0]} × ${size[1]}`);
|
|
87
|
+
size = [width, height];
|
|
88
|
+
const transparent = hasTransparency(data);
|
|
89
|
+
const format = transparent ? 'rgba4444' : 'rgb565';
|
|
90
|
+
const palette = G.quantize(data, Math.max(2, Math.min(256, colours)), { format, oneBitAlpha: transparent });
|
|
91
|
+
const index = G.applyPalette(data, palette, format);
|
|
92
|
+
const options = { palette, delay: Math.round(delay), repeat };
|
|
93
|
+
if (transparent) {
|
|
94
|
+
const k = palette.findIndex((c) => c.length > 3 && c[3] === 0);
|
|
95
|
+
if (k >= 0) Object.assign(options, { transparent: true, transparentIndex: k });
|
|
96
|
+
}
|
|
97
|
+
encoder.writeFrame(index, width, height, options);
|
|
98
|
+
count++;
|
|
99
|
+
}
|
|
100
|
+
if (!count) throw new Error('encodeGif: no frames');
|
|
101
|
+
encoder.finish();
|
|
102
|
+
return new Blob([encoder.bytes()], { type: 'image/gif' });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function hasTransparency(data) {
|
|
106
|
+
for (let i = 3; i < data.length; i += 4) if (data[i] < 255) return true;
|
|
107
|
+
return false;
|
|
108
|
+
}
|
package/src/strokes.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brush strokes: a graphic painted by hand, drawn again for every frame.
|
|
3
|
+
*
|
|
4
|
+
* A strokes graphic records each stroke's points as the user drew them —
|
|
5
|
+
* [x, y, ms, pressure], x and y as fractions of the frame — and a brush.
|
|
6
|
+
* For frame t it becomes a picture whose channels are data, not colour:
|
|
7
|
+
*
|
|
8
|
+
* alpha coverage: how much paint is here so far, 0–1
|
|
9
|
+
* red age: how long ago this pixel was last painted, 0 (just now) → 1 (`age` frames or more)
|
|
10
|
+
* green passes ÷ 4: how many strokes have gone over it (soft brushes count partly)
|
|
11
|
+
* blue progress: how far through the whole drawing it was painted, 0 → 1
|
|
12
|
+
*
|
|
13
|
+
* so the maths decides what the paint does:
|
|
14
|
+
*
|
|
15
|
+
* mix(rgb, ink, alpha(brush)) ink
|
|
16
|
+
* mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush)) a blur that grows with every pass
|
|
17
|
+
* mix(rgb, mix((1, 0.85, 0.35), (0.12, 0.08, 0.06), red(brush)), alpha(brush)) glowing, then cooling
|
|
18
|
+
* mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush)) a rainbow along the drawing
|
|
19
|
+
*
|
|
20
|
+
* Only paint laid down by frame t is there, so the drawing animates.
|
|
21
|
+
* Timing: `recorded` (the user's own speed; pauses between strokes become
|
|
22
|
+
* `gap` frames), `even` (time follows the length drawn), or `per-stroke`
|
|
23
|
+
* (every stroke takes the same time); `speed` scales it, `start` delays it,
|
|
24
|
+
* `fit` stretches the whole drawing to that many frames. `clip` keeps the
|
|
25
|
+
* paint inside (or outside) a mask — the editor passes the selection.
|
|
26
|
+
*
|
|
27
|
+
* normalizeStrokes(name, spec) the spec in full, or an error naming what is wrong
|
|
28
|
+
* strokeTimeline(spec, aspect) every point's frame and width; .total frames
|
|
29
|
+
* rasterizeStrokes(spec, w, h, t, { mask }) → ImageData-like { data, width, height }
|
|
30
|
+
* traceContours(mask, w, h) the outlines of a mask, as polylines (for "outline the selection")
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
export const BRUSHES = ['round', 'soft', 'marker', 'chalk', 'spray'];
|
|
34
|
+
export const TIMINGS = ['recorded', 'even', 'per-stroke'];
|
|
35
|
+
export const WIDTH_FROM = ['pressure', 'speed', 'none'];
|
|
36
|
+
export const CLIPS = ['none', 'inside', 'outside'];
|
|
37
|
+
export const FPS = 30; // t counts frames; recorded milliseconds become frames at this rate
|
|
38
|
+
|
|
39
|
+
export const STROKES_DEFAULTS = {
|
|
40
|
+
type: 'strokes', strokes: [], brush: 'round', size: 0.03, flow: 1, spacing: 0.2, taper: 0, buildUp: false, widthFrom: 'pressure',
|
|
41
|
+
timing: 'recorded', speed: 1, gap: 6, start: 0, fit: 0, age: 30, clip: 'none', shadows: [],
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const MAX_POINTS = 60000;
|
|
45
|
+
|
|
46
|
+
function fail(name, text) { throw new Error(`Graphic "${name}": ${text}`); }
|
|
47
|
+
|
|
48
|
+
function num(name, key, value, min, max) {
|
|
49
|
+
const v = Number(value);
|
|
50
|
+
if (!Number.isFinite(v) || v < min || v > max) fail(name, `"${key}" is a number from ${min} to ${max}`);
|
|
51
|
+
return v;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The whole spec, defaults filled in. Points are rounded, so a drawing stays compact. */
|
|
55
|
+
export function normalizeStrokes(name, spec) {
|
|
56
|
+
for (const key of Object.keys(spec)) if (!(key in STROKES_DEFAULTS)) fail(name, `no such setting "${key}" for strokes`);
|
|
57
|
+
const s = { ...STROKES_DEFAULTS, ...spec };
|
|
58
|
+
const choose = (key, list) => { if (!list.includes(s[key])) fail(name, `"${key}" is ${list.join(', ')} — not "${s[key]}"`); return s[key]; };
|
|
59
|
+
const out = {
|
|
60
|
+
type: 'strokes',
|
|
61
|
+
brush: choose('brush', BRUSHES), widthFrom: choose('widthFrom', WIDTH_FROM), timing: choose('timing', TIMINGS), clip: choose('clip', CLIPS),
|
|
62
|
+
size: num(name, 'size', s.size, 0.001, 0.5), flow: num(name, 'flow', s.flow, 0.01, 1), spacing: num(name, 'spacing', s.spacing, 0.02, 2),
|
|
63
|
+
taper: num(name, 'taper', s.taper, 0, 0.5), speed: num(name, 'speed', s.speed, 0.05, 20), gap: num(name, 'gap', s.gap, 0, 600),
|
|
64
|
+
start: num(name, 'start', s.start, 0, 10000), fit: num(name, 'fit', s.fit, 0, 10000), age: num(name, 'age', s.age, 1, 10000),
|
|
65
|
+
buildUp: Boolean(s.buildUp), shadows: [],
|
|
66
|
+
};
|
|
67
|
+
if (!Array.isArray(s.strokes)) fail(name, '"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');
|
|
68
|
+
let count = 0;
|
|
69
|
+
out.strokes = s.strokes.map((stroke, k) => {
|
|
70
|
+
const points = Array.isArray(stroke) ? stroke : stroke?.points;
|
|
71
|
+
if (!Array.isArray(points)) fail(name, `stroke ${k + 1} is { "points": [[x, y, ms, pressure], …] }`);
|
|
72
|
+
count += points.length;
|
|
73
|
+
if (count > MAX_POINTS) fail(name, `a drawing has at most ${MAX_POINTS} points`);
|
|
74
|
+
return {
|
|
75
|
+
points: points.map((p, j) => {
|
|
76
|
+
if (!Array.isArray(p) || p.length < 2 || !p.every((v) => Number.isFinite(Number(v)))) fail(name, `stroke ${k + 1}, point ${j + 1} is [x, y, ms, pressure]`);
|
|
77
|
+
return [+Number(p[0]).toFixed(4), +Number(p[1]).toFixed(4), Math.round(Number(p[2] ?? j * 16)), +Math.min(1, Math.max(0, Number(p[3] ?? 1))).toFixed(2)];
|
|
78
|
+
}),
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* When each point is painted (frame) and how wide (a factor of the brush size).
|
|
86
|
+
* `aspect` is the frame's width ÷ height, so lengths are measured in frame heights.
|
|
87
|
+
*/
|
|
88
|
+
export function strokeTimeline(spec, aspect = 1) {
|
|
89
|
+
const strokes = [];
|
|
90
|
+
let clock = spec.start;
|
|
91
|
+
const evenPace = FPS / spec.speed; // `even`: one frame height of path a second at speed 1
|
|
92
|
+
const perStroke = 20 / spec.speed; // `per-stroke`: frames each
|
|
93
|
+
for (const stroke of spec.strokes) {
|
|
94
|
+
const pts = stroke.points;
|
|
95
|
+
if (!pts.length) continue;
|
|
96
|
+
const lengths = [0];
|
|
97
|
+
for (let j = 1; j < pts.length; j++) lengths.push(lengths[j - 1] + Math.hypot((pts[j][0] - pts[j - 1][0]) * aspect, pts[j][1] - pts[j - 1][1]));
|
|
98
|
+
const length = lengths[lengths.length - 1] || 1e-9;
|
|
99
|
+
const t0 = pts[0][2];
|
|
100
|
+
const out = pts.map((p, j) => {
|
|
101
|
+
let f;
|
|
102
|
+
if (spec.timing === 'recorded') f = ((p[2] - t0) / 1000) * FPS / spec.speed;
|
|
103
|
+
else if (spec.timing === 'even') f = lengths[j] * evenPace;
|
|
104
|
+
else f = (lengths[j] / length) * perStroke;
|
|
105
|
+
// width: pressure, or speed (fast is thin, as with a pen), then the taper at both ends
|
|
106
|
+
let wf = 1;
|
|
107
|
+
if (spec.widthFrom === 'pressure') wf = 0.3 + 0.7 * p[3];
|
|
108
|
+
else if (spec.widthFrom === 'speed' && j > 0) {
|
|
109
|
+
const dt = Math.max(1, p[2] - pts[j - 1][2]);
|
|
110
|
+
const v = ((lengths[j] - lengths[j - 1]) / dt) * 1000; // frame heights a second
|
|
111
|
+
wf = Math.min(1.3, Math.max(0.35, 1.3 - v * 0.6));
|
|
112
|
+
}
|
|
113
|
+
if (spec.taper > 0) wf *= Math.max(0.15, Math.min(1, lengths[j] / length / spec.taper, (1 - lengths[j] / length) / spec.taper));
|
|
114
|
+
return { x: p[0], y: p[1], f, wf };
|
|
115
|
+
});
|
|
116
|
+
if (spec.widthFrom === 'speed' && out.length > 1) out[0].wf = out[1].wf;
|
|
117
|
+
const duration = out[out.length - 1].f;
|
|
118
|
+
for (const p of out) p.f += clock;
|
|
119
|
+
strokes.push({ points: out, start: clock, end: clock + duration });
|
|
120
|
+
clock += duration + spec.gap;
|
|
121
|
+
}
|
|
122
|
+
let total = strokes.length ? strokes[strokes.length - 1].end : spec.start;
|
|
123
|
+
if (spec.fit > 0 && total > spec.start) { // stretch the drawing to `fit` frames after the start
|
|
124
|
+
const k = spec.fit / (total - spec.start);
|
|
125
|
+
for (const s of strokes) {
|
|
126
|
+
for (const p of s.points) p.f = spec.start + (p.f - spec.start) * k;
|
|
127
|
+
s.start = spec.start + (s.start - spec.start) * k;
|
|
128
|
+
s.end = spec.start + (s.end - spec.start) * k;
|
|
129
|
+
}
|
|
130
|
+
total = spec.start + spec.fit;
|
|
131
|
+
}
|
|
132
|
+
return { strokes, total };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A repeatable random number 0–1 for two integers. */
|
|
136
|
+
function hash(a, b) {
|
|
137
|
+
let x = Math.imul(a | 0, 374761393) + Math.imul(b | 0, 668265263) | 0;
|
|
138
|
+
x = Math.imul(x ^ (x >>> 13), 1274126177);
|
|
139
|
+
return ((x ^ (x >>> 16)) >>> 0) / 4294967296;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const buffers = new Map();
|
|
143
|
+
function scratch(n) {
|
|
144
|
+
let b = buffers.get(n);
|
|
145
|
+
if (!b) {
|
|
146
|
+
b = { alpha: new Float32Array(n), passes: new Float32Array(n), latest: new Float32Array(n), cov: new Float32Array(n), when: new Float32Array(n), touched: new Int32Array(n) };
|
|
147
|
+
buffers.clear(); // one size at a time: the preview, or an export
|
|
148
|
+
buffers.set(n, b);
|
|
149
|
+
}
|
|
150
|
+
b.alpha.fill(0); b.passes.fill(0); b.latest.fill(-1);
|
|
151
|
+
return b;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The strokes as painted by frame `t` (Infinity: all of them, as at the end), w × h.
|
|
156
|
+
* `mask` (Float32Array of w × h, 0–1) is the selection for `clip`.
|
|
157
|
+
* @returns {{ data: Uint8ClampedArray, width: number, height: number, total: number }}
|
|
158
|
+
*/
|
|
159
|
+
export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {}) {
|
|
160
|
+
const n = w * h;
|
|
161
|
+
const { alpha, passes, latest, cov, when, touched } = scratch(n);
|
|
162
|
+
const { strokes, total } = strokeTimeline(spec, w / h);
|
|
163
|
+
const now = Number.isFinite(t) ? t : total;
|
|
164
|
+
const base = Math.max(0.5, (spec.size * h) / 2); // brush radius in pixels
|
|
165
|
+
let dabCount = 0;
|
|
166
|
+
|
|
167
|
+
strokes.forEach((stroke) => {
|
|
168
|
+
if (stroke.start > now) return;
|
|
169
|
+
let used = 0;
|
|
170
|
+
const stamp = (x, y, r, f) => {
|
|
171
|
+
const k = dabCount++;
|
|
172
|
+
if (spec.brush === 'spray') { // a few dots scattered in the brush's circle
|
|
173
|
+
const dots = Math.max(3, Math.round(r * 0.6));
|
|
174
|
+
const dr = Math.max(0.6, r * 0.07);
|
|
175
|
+
for (let d = 0; d < dots; d++) {
|
|
176
|
+
const a = hash(k, d * 2) * Math.PI * 2, rr = Math.sqrt(hash(k, d * 2 + 1)) * r;
|
|
177
|
+
dab(x + Math.cos(a) * rr, y + Math.sin(a) * rr, dr, f, 'round');
|
|
178
|
+
}
|
|
179
|
+
} else dab(x, y, r, f, spec.brush);
|
|
180
|
+
};
|
|
181
|
+
const dab = (cx, cy, r, f, kind) => {
|
|
182
|
+
const reach = kind === 'marker' ? r : r + 1;
|
|
183
|
+
const x0 = Math.max(0, Math.floor(cx - reach)), x1 = Math.min(w - 1, Math.ceil(cx + reach));
|
|
184
|
+
const y0 = Math.max(0, Math.floor(cy - reach)), y1 = Math.min(h - 1, Math.ceil(cy + reach));
|
|
185
|
+
for (let py = y0; py <= y1; py++) {
|
|
186
|
+
for (let px = x0; px <= x1; px++) {
|
|
187
|
+
const dx = px + 0.5 - cx, dy = py + 0.5 - cy;
|
|
188
|
+
let c;
|
|
189
|
+
if (kind === 'soft') { const d = Math.hypot(dx, dy) / r; if (d >= 1) continue; const u = 1 - d; c = u * u * (3 - 2 * u); }
|
|
190
|
+
else if (kind === 'marker') { // a flat nib, 45°, a third as thick as it is wide
|
|
191
|
+
const u = (dx + dy) * Math.SQRT1_2, v = (dy - dx) * Math.SQRT1_2;
|
|
192
|
+
const e = Math.hypot(u / r, v / (r * 0.33));
|
|
193
|
+
c = Math.min(1, Math.max(0, (1 - e) * r * 0.33 + 0.5));
|
|
194
|
+
} else {
|
|
195
|
+
c = Math.min(1, Math.max(0, r - Math.hypot(dx, dy) + 0.5));
|
|
196
|
+
if (kind === 'chalk') c *= hash(px, py * 7919) > 0.42 ? 1 : 0.12; // grain fixed to the paper, so it stays put
|
|
197
|
+
}
|
|
198
|
+
if (c <= 0) continue;
|
|
199
|
+
c *= spec.flow;
|
|
200
|
+
const i = py * w + px;
|
|
201
|
+
if (c > cov[i]) { if (cov[i] === 0) touched[used++] = i; cov[i] = c; }
|
|
202
|
+
if (c > 0.02) when[i] = f;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
// dabs along each segment painted by `now`, `spacing` brush widths apart
|
|
207
|
+
const pts = stroke.points;
|
|
208
|
+
let carry = 0;
|
|
209
|
+
const P = (p) => [p.x * w, p.y * h];
|
|
210
|
+
if (pts.length === 1 || pts.every((p) => p.x === pts[0].x && p.y === pts[0].y)) {
|
|
211
|
+
const [x, y] = P(pts[0]);
|
|
212
|
+
stamp(x, y, base * pts[0].wf, pts[0].f);
|
|
213
|
+
}
|
|
214
|
+
for (let j = 1; j < pts.length; j++) {
|
|
215
|
+
const a = pts[j - 1], b = pts[j];
|
|
216
|
+
if (a.f > now) break;
|
|
217
|
+
const [ax, ay] = P(a), [bx, by] = P(b);
|
|
218
|
+
let u1 = 1;
|
|
219
|
+
if (b.f > now) u1 = (now - a.f) / Math.max(1e-9, b.f - a.f);
|
|
220
|
+
const len = Math.hypot(bx - ax, by - ay);
|
|
221
|
+
let s = j === 1 ? 0 : carry;
|
|
222
|
+
while (s <= len * u1) {
|
|
223
|
+
const u = len ? s / len : 0;
|
|
224
|
+
const r = base * (a.wf + (b.wf - a.wf) * u);
|
|
225
|
+
stamp(ax + (bx - ax) * u, ay + (by - ay) * u, r, a.f + (b.f - a.f) * u);
|
|
226
|
+
s += Math.max(0.5, spec.spacing * 2 * r);
|
|
227
|
+
}
|
|
228
|
+
carry = s - len;
|
|
229
|
+
if (u1 < 1) break;
|
|
230
|
+
}
|
|
231
|
+
// this stroke counts once wherever it went, however often it crossed itself
|
|
232
|
+
for (let k = 0; k < used; k++) {
|
|
233
|
+
const i = touched[k], c = cov[i];
|
|
234
|
+
alpha[i] = spec.buildUp ? 1 - (1 - alpha[i]) * (1 - c) : Math.max(alpha[i], c);
|
|
235
|
+
passes[i] += c;
|
|
236
|
+
if (c > 0.02 && when[i] > latest[i]) latest[i] = when[i];
|
|
237
|
+
cov[i] = 0;
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const data = new Uint8ClampedArray(n * 4);
|
|
242
|
+
const inside = spec.clip === 'inside', outside = spec.clip === 'outside';
|
|
243
|
+
for (let i = 0; i < n; i++) {
|
|
244
|
+
let a = alpha[i];
|
|
245
|
+
if (a === 0) continue;
|
|
246
|
+
let m = 1;
|
|
247
|
+
if (mask && (inside || outside)) m = inside ? mask[i] : 1 - mask[i];
|
|
248
|
+
a *= m;
|
|
249
|
+
const j = i * 4;
|
|
250
|
+
data[j] = Math.round(Math.min(1, Math.max(0, (now - latest[i]) / spec.age)) * 255);
|
|
251
|
+
data[j + 1] = Math.round(Math.min(1, (passes[i] * m) / 4) * 255);
|
|
252
|
+
data[j + 2] = Math.round(Math.min(1, Math.max(0, latest[i] / Math.max(1e-9, total))) * 255);
|
|
253
|
+
data[j + 3] = Math.round(a * 255);
|
|
254
|
+
}
|
|
255
|
+
return { data, width: w, height: h, total };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The outlines of a mask (values > 0.5 are in), each a closed polyline of pixel
|
|
260
|
+
* centres, simplified; parts smaller than `minArea` pixels are left out.
|
|
261
|
+
* Moore-neighbour tracing, one outline per connected part.
|
|
262
|
+
*/
|
|
263
|
+
export function traceContours(mask, w, h, { minArea = 40, tolerance = 0.8 } = {}) {
|
|
264
|
+
const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && mask[y * w + x] > 0.5;
|
|
265
|
+
const label = new Int32Array(w * h).fill(-1);
|
|
266
|
+
const outlines = [];
|
|
267
|
+
const dirs = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; // clockwise on screen
|
|
268
|
+
let parts = 0;
|
|
269
|
+
for (let y = 0; y < h; y++) {
|
|
270
|
+
for (let x = 0; x < w; x++) {
|
|
271
|
+
if (!inside(x, y) || label[y * w + x] >= 0) continue;
|
|
272
|
+
// the whole part, so its outline is traced once
|
|
273
|
+
const id = parts++;
|
|
274
|
+
const stack = [y * w + x];
|
|
275
|
+
label[y * w + x] = id;
|
|
276
|
+
let area = 0;
|
|
277
|
+
while (stack.length) {
|
|
278
|
+
const p = stack.pop();
|
|
279
|
+
area++;
|
|
280
|
+
const px = p % w, py = (p - px) / w;
|
|
281
|
+
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
|
|
282
|
+
const qx = px + dx, qy = py + dy;
|
|
283
|
+
if (inside(qx, qy) && label[qy * w + qx] < 0) { label[qy * w + qx] = id; stack.push(qy * w + qx); }
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (area < minArea) continue;
|
|
287
|
+
// (x, y) is its top-left pixel: the one to its left is outside
|
|
288
|
+
const path = [[x, y]];
|
|
289
|
+
let cx = x, cy = y, back = 4; // we came from the west
|
|
290
|
+
for (let steps = 0; steps < 4 * area + 16; steps++) {
|
|
291
|
+
let found = false;
|
|
292
|
+
for (let k = 1; k <= 8; k++) {
|
|
293
|
+
const d = (back + k) % 8;
|
|
294
|
+
const nx = cx + dirs[d][0], ny = cy + dirs[d][1];
|
|
295
|
+
if (inside(nx, ny) && label[ny * w + nx] === id) {
|
|
296
|
+
back = (d + 4) % 8; // where we came from: the next search starts just past it, clockwise
|
|
297
|
+
cx = nx; cy = ny;
|
|
298
|
+
found = true;
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!found || (cx === x && cy === y)) break;
|
|
303
|
+
path.push([cx, cy]);
|
|
304
|
+
}
|
|
305
|
+
outlines.push(simplifyLoop(path, tolerance));
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return outlines;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* A closed loop (first point not repeated) simplified, and closed again: as two
|
|
313
|
+
* halves split at the point farthest from the start — simplify() alone would measure
|
|
314
|
+
* everything against a line from a point to itself, and keep nothing.
|
|
315
|
+
*/
|
|
316
|
+
export function simplifyLoop(points, tolerance) {
|
|
317
|
+
if (points.length < 4) return [...points, points[0]];
|
|
318
|
+
const [x, y] = points[0];
|
|
319
|
+
let far = 0;
|
|
320
|
+
points.forEach(([px, py], i) => { if (Math.hypot(px - x, py - y) > Math.hypot(points[far][0] - x, points[far][1] - y)) far = i; });
|
|
321
|
+
return [...simplify(points.slice(0, far + 1), tolerance), ...simplify([...points.slice(far), points[0]], tolerance).slice(1)];
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Ramer–Douglas–Peucker: fewer points, within `tolerance` pixels of the line. */
|
|
325
|
+
export function simplify(points, tolerance) {
|
|
326
|
+
if (points.length < 3) return points;
|
|
327
|
+
const keep = new Uint8Array(points.length);
|
|
328
|
+
keep[0] = keep[points.length - 1] = 1;
|
|
329
|
+
const stack = [[0, points.length - 1]];
|
|
330
|
+
while (stack.length) {
|
|
331
|
+
const [a, b] = stack.pop();
|
|
332
|
+
const [ax, ay] = points[a], [bx, by] = points[b];
|
|
333
|
+
const len = Math.hypot(bx - ax, by - ay) || 1e-9;
|
|
334
|
+
let worst = -1, at = -1;
|
|
335
|
+
for (let i = a + 1; i < b; i++) {
|
|
336
|
+
const d = Math.abs((bx - ax) * (ay - points[i][1]) - (ax - points[i][0]) * (by - ay)) / len;
|
|
337
|
+
if (d > worst) { worst = d; at = i; }
|
|
338
|
+
}
|
|
339
|
+
if (worst > tolerance) { keep[at] = 1; stack.push([a, at], [at, b]); }
|
|
340
|
+
}
|
|
341
|
+
return points.filter((_, i) => keep[i]);
|
|
342
|
+
}
|