inlaytrace 0.0.0-stage → 0.1.1
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 +20 -0
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/dist/index.d.ts +156 -0
- package/dist/index.js +1534 -0
- package/package.json +52 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1534 @@
|
|
|
1
|
+
//#region src/fit.ts
|
|
2
|
+
const R = 6;
|
|
3
|
+
const END_TRIM = 3;
|
|
4
|
+
const SMOOTH = 12;
|
|
5
|
+
/**
|
|
6
|
+
* A straight line is accepted at 1.5× the curve tolerance. Straight edges are
|
|
7
|
+
* common in flat art, and a ripple along one is almost always JPEG noise (its
|
|
8
|
+
* colour is stored in 16 px blocks), not a shape the artist drew.
|
|
9
|
+
*/
|
|
10
|
+
const LINE_BIAS = 1.5;
|
|
11
|
+
const sub = (a, b) => ({
|
|
12
|
+
x: a.x - b.x,
|
|
13
|
+
y: a.y - b.y
|
|
14
|
+
});
|
|
15
|
+
const add = (a, b) => ({
|
|
16
|
+
x: a.x + b.x,
|
|
17
|
+
y: a.y + b.y
|
|
18
|
+
});
|
|
19
|
+
const mul = (a, k) => ({
|
|
20
|
+
x: a.x * k,
|
|
21
|
+
y: a.y * k
|
|
22
|
+
});
|
|
23
|
+
const dot = (a, b) => a.x * b.x + a.y * b.y;
|
|
24
|
+
const len = (a) => Math.hypot(a.x, a.y);
|
|
25
|
+
const norm = (a) => {
|
|
26
|
+
const l = len(a);
|
|
27
|
+
return l > 1e-12 ? {
|
|
28
|
+
x: a.x / l,
|
|
29
|
+
y: a.y / l
|
|
30
|
+
} : {
|
|
31
|
+
x: 0,
|
|
32
|
+
y: 0
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
|
|
36
|
+
const line = (a, b) => [
|
|
37
|
+
a,
|
|
38
|
+
add(a, mul(sub(b, a), 1 / 3)),
|
|
39
|
+
add(a, mul(sub(b, a), 2 / 3)),
|
|
40
|
+
b
|
|
41
|
+
];
|
|
42
|
+
/** A cubic whose handles sit on its chord (within 0.15 px, and between the ends) is a line. */
|
|
43
|
+
function isFlat([p0, c1, c2, p3]) {
|
|
44
|
+
const d = sub(p3, p0);
|
|
45
|
+
const l = len(d);
|
|
46
|
+
if (l < 1e-9) return true;
|
|
47
|
+
const off = (p) => Math.abs((p.x - p0.x) * d.y - (p.y - p0.y) * d.x) / l;
|
|
48
|
+
const t = (p) => dot(sub(p, p0), d) / (l * l);
|
|
49
|
+
return off(c1) < .15 && off(c2) < .15 && t(c1) >= -.01 && t(c1) <= 1.01 && t(c2) >= -.01 && t(c2) <= 1.01;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Fit a chain. Open: from points[0] to the last point, which stay fixed.
|
|
53
|
+
* Closed: points[0] is not repeated at the end; the result is a loop that starts
|
|
54
|
+
* at a corner if there is one.
|
|
55
|
+
*/
|
|
56
|
+
function fitChain(points, closed, o) {
|
|
57
|
+
const pts = resample(points, closed);
|
|
58
|
+
const n = pts.length;
|
|
59
|
+
if (n < 2) return [];
|
|
60
|
+
if (!closed && n === 2) return [line(pts[0], pts[1])];
|
|
61
|
+
const corners = findCorners(pts, closed, o.cornerAngle).filter((c) => closed || dist(c.at, pts[0]) >= MIN_GAP && dist(c.at, pts[n - 1]) >= MIN_GAP);
|
|
62
|
+
if (closed && corners.length === 0) {
|
|
63
|
+
if (n < 4) return polygon(pts, true);
|
|
64
|
+
let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH);
|
|
65
|
+
const first = straights(smoothed.true, smoothed.radius, o.tolerance)[0];
|
|
66
|
+
if (first && first[0] > 0 && first[0] < n) {
|
|
67
|
+
const k = first[0];
|
|
68
|
+
const turned = [...pts.slice(k), ...pts.slice(0, k)];
|
|
69
|
+
smoothed = smooth([...turned, turned[0]], true, o.smoothing ?? SMOOTH);
|
|
70
|
+
}
|
|
71
|
+
const run = smoothed.true;
|
|
72
|
+
const t = norm(sub(run[1], run[run.length - 2]));
|
|
73
|
+
return flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
|
|
74
|
+
}
|
|
75
|
+
const breaks = corners.map((c) => ({
|
|
76
|
+
index: c.index,
|
|
77
|
+
at: c.at
|
|
78
|
+
}));
|
|
79
|
+
if (!closed) {
|
|
80
|
+
if (!breaks.length || breaks[0].index !== 0) breaks.unshift({
|
|
81
|
+
index: 0,
|
|
82
|
+
at: pts[0]
|
|
83
|
+
});
|
|
84
|
+
if (breaks[breaks.length - 1].index !== n - 1) breaks.push({
|
|
85
|
+
index: n - 1,
|
|
86
|
+
at: pts[n - 1]
|
|
87
|
+
});
|
|
88
|
+
breaks[0].at = pts[0];
|
|
89
|
+
breaks[breaks.length - 1].at = pts[n - 1];
|
|
90
|
+
}
|
|
91
|
+
const out = [];
|
|
92
|
+
const segments = closed ? breaks.length : breaks.length - 1;
|
|
93
|
+
for (let b = 0; b < segments; b++) {
|
|
94
|
+
const from = breaks[b];
|
|
95
|
+
const to = breaks[(b + 1) % breaks.length];
|
|
96
|
+
const run = [];
|
|
97
|
+
for (let i = from.index;; i = (i + 1) % n) {
|
|
98
|
+
run.push(pts[i]);
|
|
99
|
+
if (i === to.index && run.length > 1) break;
|
|
100
|
+
}
|
|
101
|
+
run[0] = from.at;
|
|
102
|
+
run[run.length - 1] = to.at;
|
|
103
|
+
out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH), o.tolerance));
|
|
104
|
+
}
|
|
105
|
+
return flatten(out);
|
|
106
|
+
}
|
|
107
|
+
/** Straight runs written as exact lines, so they serialise as L, not C. */
|
|
108
|
+
function flatten(cubics) {
|
|
109
|
+
return cubics.map((c) => isFlat(c) ? line(c[0], c[3]) : c);
|
|
110
|
+
}
|
|
111
|
+
function polygon(pts, closed) {
|
|
112
|
+
const out = [];
|
|
113
|
+
for (let i = 0; i < pts.length - (closed ? 0 : 1); i++) out.push(line(pts[i], pts[(i + 1) % pts.length]));
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
/** About one point per pixel of length, so every measure below is in px. */
|
|
117
|
+
function resample(points, closed) {
|
|
118
|
+
const out = [];
|
|
119
|
+
const m = closed ? points.length : points.length - 1;
|
|
120
|
+
for (let i = 0; i < m; i++) {
|
|
121
|
+
const a = points[i];
|
|
122
|
+
const b = points[(i + 1) % points.length];
|
|
123
|
+
if (dist(a, b) < 1e-9) continue;
|
|
124
|
+
const k = Math.max(1, Math.ceil(dist(a, b)));
|
|
125
|
+
for (let s = 0; s < k; s++) out.push({
|
|
126
|
+
x: a.x + (b.x - a.x) * s / k,
|
|
127
|
+
y: a.y + (b.y - a.y) * s / k
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (!closed && points.length) out.push(points[points.length - 1]);
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The point `ds` px along the chain from sample i (negative = backwards).
|
|
135
|
+
* Open chains stop at their ends; `null` means the chain ran out.
|
|
136
|
+
*/
|
|
137
|
+
function along(pts, closed, i, ds) {
|
|
138
|
+
const n = pts.length;
|
|
139
|
+
let k = i;
|
|
140
|
+
let left = Math.abs(ds);
|
|
141
|
+
const step = ds >= 0 ? 1 : -1;
|
|
142
|
+
while (left > 1e-9) {
|
|
143
|
+
const next = k + step;
|
|
144
|
+
if (!closed && (next < 0 || next >= n)) return null;
|
|
145
|
+
const a = pts[k];
|
|
146
|
+
const b = pts[(next + n) % n];
|
|
147
|
+
const l = dist(a, b);
|
|
148
|
+
if (l >= left) return add(a, mul(sub(b, a), left / l));
|
|
149
|
+
left -= l;
|
|
150
|
+
k = (next + n) % n;
|
|
151
|
+
}
|
|
152
|
+
return pts[k];
|
|
153
|
+
}
|
|
154
|
+
/** Px of chain available before (side -1) or after (side 1) sample i. Points are ≈ 1 px apart. */
|
|
155
|
+
const room = (n, closed, i, side) => closed ? Infinity : side < 0 ? i : n - 1 - i;
|
|
156
|
+
/**
|
|
157
|
+
* How far the chain turns at sample i over r px each side, in degrees. Near an
|
|
158
|
+
* open chain's end (a junction, where a peak often sits) it measures over what
|
|
159
|
+
* is there, down to MIN_REACH px; null when even that is missing.
|
|
160
|
+
*/
|
|
161
|
+
function turn(pts, closed, i, r) {
|
|
162
|
+
const p = pts[i];
|
|
163
|
+
const reach = Math.min(r, room(pts.length, closed, i, -1), room(pts.length, closed, i, 1));
|
|
164
|
+
if (reach < Math.min(r, MIN_REACH)) return null;
|
|
165
|
+
const before = along(pts, closed, i, -reach);
|
|
166
|
+
const after = along(pts, closed, i, reach);
|
|
167
|
+
if (!before || !after) return null;
|
|
168
|
+
const a = norm(sub(p, before));
|
|
169
|
+
const b = norm(sub(after, p));
|
|
170
|
+
return Math.acos(Math.max(-1, Math.min(1, dot(a, b)))) * 180 / Math.PI;
|
|
171
|
+
}
|
|
172
|
+
function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
|
|
173
|
+
const n = pts.length;
|
|
174
|
+
const score = new Array(n).fill(0);
|
|
175
|
+
const meet = new Array(n).fill(null);
|
|
176
|
+
const sm = lightly(pts, closed);
|
|
177
|
+
for (let i = 0; i < n; i++) {
|
|
178
|
+
const wide = turn(pts, closed, i, R);
|
|
179
|
+
if (wide === null || wide < cornerAngle) continue;
|
|
180
|
+
const a = arm(sm, closed, i, -1);
|
|
181
|
+
const b = arm(sm, closed, i, 1);
|
|
182
|
+
if (!a || !b || a.rms > ARM_RMS || a.bend > ARM_BEND || b.rms > ARM_RMS || b.bend > ARM_BEND) continue;
|
|
183
|
+
const interior = Math.acos(Math.max(-1, Math.min(1, dot(a.dir, b.dir)))) * 180 / Math.PI;
|
|
184
|
+
const bend = 180 - interior;
|
|
185
|
+
if (bend < cornerAngle) continue;
|
|
186
|
+
const x = intersect(a.at, add(a.at, a.dir), b.at, add(b.at, b.dir));
|
|
187
|
+
const half = interior / 2 * Math.PI / 180;
|
|
188
|
+
const reachOut = 1 / Math.sin(half) - 1;
|
|
189
|
+
if (!x || dist(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
|
|
190
|
+
let d = Infinity;
|
|
191
|
+
for (let k = -6; k <= R; k++) {
|
|
192
|
+
const j = closed ? ((i + k) % n + n) % n : i + k;
|
|
193
|
+
if (j >= 0 && j < n) d = Math.min(d, dist(pts[j], x));
|
|
194
|
+
}
|
|
195
|
+
if (d / Math.max(1e-6, reachOut) > maxRounding && d > .75) continue;
|
|
196
|
+
score[i] = bend;
|
|
197
|
+
meet[i] = x;
|
|
198
|
+
}
|
|
199
|
+
const corners = [];
|
|
200
|
+
for (let i = 0; i < n; i++) {
|
|
201
|
+
if (!score[i]) continue;
|
|
202
|
+
let best = true;
|
|
203
|
+
for (let k = -6; k <= R && best; k++) {
|
|
204
|
+
if (k === 0) continue;
|
|
205
|
+
let j = i + k;
|
|
206
|
+
if (closed) j = (j + n) % n;
|
|
207
|
+
else if (j < 0 || j >= n) continue;
|
|
208
|
+
if (score[j] > score[i] || score[j] === score[i] && j < i) best = false;
|
|
209
|
+
}
|
|
210
|
+
if (best) corners.push({
|
|
211
|
+
index: i,
|
|
212
|
+
at: meet[i]
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return corners.filter((c) => !corners.some((o) => o !== c && dist(o.at, c.at) < R && (score[o.index] > score[c.index] || score[o.index] === score[c.index] && o.index < c.index)));
|
|
216
|
+
}
|
|
217
|
+
/** ±2-point moving average; an open chain keeps its ends. Same length and indices as the input. */
|
|
218
|
+
function lightly(pts, closed) {
|
|
219
|
+
const n = pts.length;
|
|
220
|
+
if (n < 6) return pts;
|
|
221
|
+
return pts.map((p, i) => {
|
|
222
|
+
const reach = closed ? 2 : Math.min(2, i, n - 1 - i);
|
|
223
|
+
if (!reach) return p;
|
|
224
|
+
let x = 0;
|
|
225
|
+
let y = 0;
|
|
226
|
+
for (let k = -reach; k <= reach; k++) {
|
|
227
|
+
const q = pts[((i + k) % n + n) % n];
|
|
228
|
+
x += q.x;
|
|
229
|
+
y += q.y;
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
x: x / (2 * reach + 1),
|
|
233
|
+
y: y / (2 * reach + 1)
|
|
234
|
+
};
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const MIN_GAP = 4;
|
|
238
|
+
const MIN_REACH = 4;
|
|
239
|
+
const ARM_RMS = .6;
|
|
240
|
+
const ARM_BEND = 14;
|
|
241
|
+
const MAX_ROUNDING = 1.5;
|
|
242
|
+
const MAX_REACH_OUT = 18;
|
|
243
|
+
/**
|
|
244
|
+
* A least-squares line through the chain from R/2 to 1.5R px before (side -1)
|
|
245
|
+
* or after (side 1) sample i: a point on it, its direction pointing away from
|
|
246
|
+
* i, and the RMS distance of the points from it. Null near an open end.
|
|
247
|
+
*/
|
|
248
|
+
function arm(pts, closed, i, side) {
|
|
249
|
+
const avail = room(pts.length, closed, i, side);
|
|
250
|
+
if (avail < MIN_REACH) return null;
|
|
251
|
+
const reach = Math.min(1.5 * R, avail);
|
|
252
|
+
const sample = [];
|
|
253
|
+
for (let d = Math.min(R / 2, reach / 3); d <= reach + 1e-9; d += 1) {
|
|
254
|
+
const p = along(pts, closed, i, side * d);
|
|
255
|
+
if (!p) break;
|
|
256
|
+
sample.push(p);
|
|
257
|
+
}
|
|
258
|
+
if (sample.length < 3) return null;
|
|
259
|
+
const cx = sample.reduce((s, p) => s + p.x, 0) / sample.length;
|
|
260
|
+
const cy = sample.reduce((s, p) => s + p.y, 0) / sample.length;
|
|
261
|
+
let sxx = 0;
|
|
262
|
+
let sxy = 0;
|
|
263
|
+
let syy = 0;
|
|
264
|
+
for (const p of sample) {
|
|
265
|
+
sxx += (p.x - cx) ** 2;
|
|
266
|
+
sxy += (p.x - cx) * (p.y - cy);
|
|
267
|
+
syy += (p.y - cy) ** 2;
|
|
268
|
+
}
|
|
269
|
+
const theta = .5 * Math.atan2(2 * sxy, sxx - syy);
|
|
270
|
+
let dir = {
|
|
271
|
+
x: Math.cos(theta),
|
|
272
|
+
y: Math.sin(theta)
|
|
273
|
+
};
|
|
274
|
+
const outward = sub(sample[sample.length - 1], sample[0]);
|
|
275
|
+
if (dot(dir, outward) < 0) dir = mul(dir, -1);
|
|
276
|
+
const rms = Math.sqrt(sample.reduce((s, p) => s + ((p.x - cx) * dir.y - (p.y - cy) * dir.x) ** 2, 0) / sample.length);
|
|
277
|
+
const mid = Math.floor(sample.length / 2);
|
|
278
|
+
const near = norm(sub(sample[mid], sample[0]));
|
|
279
|
+
const far = norm(sub(sample[sample.length - 1], sample[mid]));
|
|
280
|
+
const bend = Math.acos(Math.max(-1, Math.min(1, dot(near, far)))) * 180 / Math.PI;
|
|
281
|
+
return {
|
|
282
|
+
at: {
|
|
283
|
+
x: cx,
|
|
284
|
+
y: cy
|
|
285
|
+
},
|
|
286
|
+
dir,
|
|
287
|
+
rms,
|
|
288
|
+
bend
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function intersect(a0, a1, b0, b1) {
|
|
292
|
+
const d1 = sub(a1, a0);
|
|
293
|
+
const d2 = sub(b1, b0);
|
|
294
|
+
const den = d1.x * d2.y - d1.y * d2.x;
|
|
295
|
+
if (Math.abs(den) < 1e-9) return null;
|
|
296
|
+
const t = ((b0.x - a0.x) * d2.y - (b0.y - a0.y) * d2.x) / den;
|
|
297
|
+
return add(a0, mul(d1, t));
|
|
298
|
+
}
|
|
299
|
+
function smooth(run, loop, half) {
|
|
300
|
+
const n = run.length;
|
|
301
|
+
const h = Math.max(0, Math.min(Math.round(half), Math.floor(n / (loop ? 16 : 4))));
|
|
302
|
+
if (!h || n < 4) return {
|
|
303
|
+
flat: run,
|
|
304
|
+
true: run,
|
|
305
|
+
minRadius: Infinity,
|
|
306
|
+
radius: new Float64Array(n).fill(1e9)
|
|
307
|
+
};
|
|
308
|
+
const m = loop ? n - 1 : n;
|
|
309
|
+
const base = run.slice(0, m);
|
|
310
|
+
const at = (i) => base[loop ? (i % m + m) % m : Math.max(0, Math.min(m - 1, i))];
|
|
311
|
+
const avg = (reachOf) => base.map((p, i) => {
|
|
312
|
+
if (!loop && (i === 0 || i === m - 1)) return p;
|
|
313
|
+
const reach = loop ? reachOf(i) : Math.min(reachOf(i), i, m - 1 - i);
|
|
314
|
+
if (reach <= 0) return p;
|
|
315
|
+
let x = 0;
|
|
316
|
+
let y = 0;
|
|
317
|
+
for (let k = -reach; k <= reach; k++) {
|
|
318
|
+
const q = at(i + k);
|
|
319
|
+
x += q.x;
|
|
320
|
+
y += q.y;
|
|
321
|
+
}
|
|
322
|
+
return {
|
|
323
|
+
x: x / (2 * reach + 1),
|
|
324
|
+
y: y / (2 * reach + 1)
|
|
325
|
+
};
|
|
326
|
+
});
|
|
327
|
+
const flat = avg(() => h);
|
|
328
|
+
const r = 5;
|
|
329
|
+
const light = avg(() => Math.min(h, 2));
|
|
330
|
+
const lat = (i) => light[loop ? (i % m + m) % m : Math.max(0, Math.min(m - 1, i))];
|
|
331
|
+
const radiusAt = (i, span) => {
|
|
332
|
+
const a = norm(sub(lat(i), lat(i - span)));
|
|
333
|
+
const b = norm(sub(lat(i + span), lat(i)));
|
|
334
|
+
const turn = Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
|
|
335
|
+
return turn > 1e-6 ? span / turn : 1e9;
|
|
336
|
+
};
|
|
337
|
+
const raw = new Float64Array(m);
|
|
338
|
+
for (let i = 0; i < m; i++) raw[i] = Math.max(radiusAt(i, r), radiusAt(i, 15));
|
|
339
|
+
const allow = new Int32Array(m);
|
|
340
|
+
const radius = new Float64Array(loop ? m + 1 : m);
|
|
341
|
+
let minRadius = Infinity;
|
|
342
|
+
for (let i = 0; i < m; i++) {
|
|
343
|
+
const win = [];
|
|
344
|
+
for (let k = -3; k <= 3; k++) {
|
|
345
|
+
const j = loop ? ((i + k) % m + m) % m : Math.max(0, Math.min(m - 1, i + k));
|
|
346
|
+
win.push(raw[j]);
|
|
347
|
+
}
|
|
348
|
+
win.sort((x, y) => x - y);
|
|
349
|
+
const rho = win[3];
|
|
350
|
+
radius[i] = rho;
|
|
351
|
+
if (rho < minRadius) minRadius = rho;
|
|
352
|
+
allow[i] = Math.min(h, Math.floor(Math.sqrt(.9 * rho)));
|
|
353
|
+
}
|
|
354
|
+
const reachAt = (i) => {
|
|
355
|
+
let reach = allow[i];
|
|
356
|
+
for (let k = 1; k <= h + 1 && k - 1 < reach; k++) for (const j of [i - k, i + k]) {
|
|
357
|
+
if (!loop && (j < 0 || j >= m)) continue;
|
|
358
|
+
const aj = allow[(j % m + m) % m];
|
|
359
|
+
if (aj < reach) reach = Math.max(aj, k - 1);
|
|
360
|
+
}
|
|
361
|
+
return reach;
|
|
362
|
+
};
|
|
363
|
+
const fitted = avg(reachAt);
|
|
364
|
+
const close = (pts) => loop ? [...pts, pts[0]] : pts;
|
|
365
|
+
if (loop) radius[m] = radius[0];
|
|
366
|
+
return {
|
|
367
|
+
flat: close(flat),
|
|
368
|
+
true: close(fitted),
|
|
369
|
+
minRadius,
|
|
370
|
+
radius
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** A run between two fixed points: a line if it is one, else curves with free end tangents. */
|
|
374
|
+
function fitBetween(smoothed, tolerance) {
|
|
375
|
+
const run = smoothed.flat;
|
|
376
|
+
const a = run[0];
|
|
377
|
+
const b = run[run.length - 1];
|
|
378
|
+
const trim = Math.min(END_TRIM, Math.floor(run.length / 4));
|
|
379
|
+
if (run.length <= 2 || maxOffLine(run.slice(trim, run.length - trim), a, b) <= tolerance * LINE_BIAS) return [line(a, b)];
|
|
380
|
+
const curve = smoothed.true;
|
|
381
|
+
return fitMixed(smoothed, tolerance, endTangent(curve, false), endTangent(curve, true), END_TRIM);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* A run that is neither one line nor one smooth curve, like a stroke's
|
|
385
|
+
* straight side running into its round end. Find the straight stretches first
|
|
386
|
+
* (at least MIN_LINE px, every point within tolerance), make each a line, and
|
|
387
|
+
* fit curves only between them, leaving and arriving along the lines' own
|
|
388
|
+
* directions so every join is smooth. Without this a curve would cover the
|
|
389
|
+
* end of the straight and the bend together and overshoot the bend.
|
|
390
|
+
*/
|
|
391
|
+
function fitMixed(s, tolerance, t1, t2, skipEnds) {
|
|
392
|
+
const curve = s.true;
|
|
393
|
+
const n = curve.length;
|
|
394
|
+
const tol = curveTolerance(tolerance, s.minRadius);
|
|
395
|
+
const lines = straights(curve, s.radius, tolerance);
|
|
396
|
+
if (!lines.length) return fitRun(curve, t1, t2, tol, 0, skipEnds, skipEnds);
|
|
397
|
+
const out = [];
|
|
398
|
+
let from = 0;
|
|
399
|
+
let tFrom = t1;
|
|
400
|
+
let fromAt = curve[0];
|
|
401
|
+
for (const [i, j] of lines) {
|
|
402
|
+
const isStub = (p, q) => dist(curve[p], curve[q]) < MIN_GAP && Math.abs(q - p) < 12;
|
|
403
|
+
const short = i > from && isStub(from, i);
|
|
404
|
+
const a = short ? fromAt : curve[i];
|
|
405
|
+
const b = curve[j];
|
|
406
|
+
const dir = norm(sub(b, a));
|
|
407
|
+
if (i > from && !short) {
|
|
408
|
+
const piece = curve.slice(from, i + 1);
|
|
409
|
+
piece[0] = fromAt;
|
|
410
|
+
piece[piece.length - 1] = a;
|
|
411
|
+
out.push(...fitRun(piece, tFrom, mul(dir, -1), tol, 0, from === 0 ? skipEnds : 0, 0));
|
|
412
|
+
}
|
|
413
|
+
out.push(line(i > from && !short ? a : fromAt, b));
|
|
414
|
+
from = j;
|
|
415
|
+
fromAt = b;
|
|
416
|
+
tFrom = dir;
|
|
417
|
+
}
|
|
418
|
+
if (from < n - 1 && out.length && dist(fromAt, curve[n - 1]) < MIN_GAP && n - 1 - from < 12) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
|
|
419
|
+
else if (from < n - 1) {
|
|
420
|
+
const piece = curve.slice(from);
|
|
421
|
+
piece[0] = fromAt;
|
|
422
|
+
out.push(...fitRun(piece, tFrom, t2, tol, 0, 0, skipEnds));
|
|
423
|
+
} else if (out.length) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
const MAX_SWEEP = 100;
|
|
427
|
+
const MIN_LINE = 12;
|
|
428
|
+
/**
|
|
429
|
+
* Maximal straight stretches [start, end] (indices), greedily from the start,
|
|
430
|
+
* on the shape-true points (fully smoothed along straight stretches anyway,
|
|
431
|
+
* and unlike the flat ones they don't sag near a bend). Each end is then
|
|
432
|
+
* trimmed back until the outline sits on the line (within 0.3 px): otherwise a
|
|
433
|
+
* line would run a few px into the bend that follows and chamfer it.
|
|
434
|
+
*/
|
|
435
|
+
function straights(exact, radius, tolerance) {
|
|
436
|
+
const n = exact.length;
|
|
437
|
+
const straight = (i, j) => {
|
|
438
|
+
const a = exact[i];
|
|
439
|
+
const d = norm(sub(exact[j], a));
|
|
440
|
+
let worst = 0;
|
|
441
|
+
let bow = 0;
|
|
442
|
+
for (let k = i + 1; k < j; k++) {
|
|
443
|
+
const o = (exact[k].x - a.x) * d.y - (exact[k].y - a.y) * d.x;
|
|
444
|
+
worst = Math.max(worst, Math.abs(o));
|
|
445
|
+
bow += o;
|
|
446
|
+
}
|
|
447
|
+
return worst <= tolerance && Math.abs(bow / Math.max(1, j - i - 1)) <= .12;
|
|
448
|
+
};
|
|
449
|
+
const found = [];
|
|
450
|
+
let i = 0;
|
|
451
|
+
while (i < n - MIN_LINE) {
|
|
452
|
+
let j = i + MIN_LINE;
|
|
453
|
+
if (!straight(i, j)) {
|
|
454
|
+
i++;
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
while (j + 1 < n && straight(i, j + 1)) j++;
|
|
458
|
+
const a = exact[i];
|
|
459
|
+
const d = norm(sub(exact[j], a));
|
|
460
|
+
const off = (p) => Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x);
|
|
461
|
+
let s = i;
|
|
462
|
+
let e = j;
|
|
463
|
+
while (e - s > MIN_LINE && off(exact[s]) > .3) s++;
|
|
464
|
+
while (e - s > MIN_LINE && off(exact[e]) > .3) e--;
|
|
465
|
+
const beside = [s - R, e + R].filter((k) => k >= 0 && k < n).map((k) => radius[k]);
|
|
466
|
+
const own = [...radius.slice(s + 1, e)].sort((x, y) => x - y)[Math.floor((e - s - 1) / 2)] ?? 1e9;
|
|
467
|
+
const context = beside.length ? Math.min(own, Math.max(...beside)) : own;
|
|
468
|
+
const needed = 2.5 * Math.sqrt(Math.min(1e6, context));
|
|
469
|
+
if (e - s >= MIN_LINE && dist(exact[s], exact[e]) >= needed) found.push([s, e]);
|
|
470
|
+
i = j;
|
|
471
|
+
}
|
|
472
|
+
return found;
|
|
473
|
+
}
|
|
474
|
+
function maxOffLine(run, a, b) {
|
|
475
|
+
const d = sub(b, a);
|
|
476
|
+
const l = len(d);
|
|
477
|
+
let worst = 0;
|
|
478
|
+
for (const p of run) {
|
|
479
|
+
const off = l < 1e-9 ? dist(p, a) : Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x) / l;
|
|
480
|
+
if (off > worst) worst = off;
|
|
481
|
+
}
|
|
482
|
+
return worst;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* A 1 px tolerance lets one curve cut across a bend only 4 px in radius (the
|
|
486
|
+
* round end of a stroke) and overshoot it, which reads as a hook. Runs with a
|
|
487
|
+
* tight bend are fitted to a fraction of their tightest radius instead.
|
|
488
|
+
*/
|
|
489
|
+
const curveTolerance = (tolerance, minRadius) => Math.min(tolerance, Math.max(.3, minRadius / 8));
|
|
490
|
+
/** Tangent at an end, pointing into the run, from the point R px in. */
|
|
491
|
+
function endTangent(run, atEnd) {
|
|
492
|
+
const n = run.length;
|
|
493
|
+
const k = Math.min(n - 1, R);
|
|
494
|
+
return atEnd ? norm(sub(run[n - 1 - k], run[n - 1])) : norm(sub(run[k], run[0]));
|
|
495
|
+
}
|
|
496
|
+
/** Schneider's recursive fit: one cubic, or split at the worst point and recurse. */
|
|
497
|
+
function fitRun(pts, t1, t2, tolerance, depth = 0, skipStart = 0, skipEnd = 0) {
|
|
498
|
+
const n = pts.length;
|
|
499
|
+
if (n === 2) {
|
|
500
|
+
const d = dist(pts[0], pts[1]) / 3;
|
|
501
|
+
return [[
|
|
502
|
+
pts[0],
|
|
503
|
+
add(pts[0], mul(t1, d)),
|
|
504
|
+
add(pts[1], mul(t2, d)),
|
|
505
|
+
pts[1]
|
|
506
|
+
]];
|
|
507
|
+
}
|
|
508
|
+
if (Math.acos(Math.max(-1, Math.min(1, -dot(t1, t2)))) * 180 / Math.PI > MAX_SWEEP && n >= 8 && depth <= 12 && dist(pts[0], pts[n - 1]) >= 8) {
|
|
509
|
+
const mid = Math.floor(n / 2);
|
|
510
|
+
const span = Math.min(3, mid, n - 1 - mid);
|
|
511
|
+
const tm = norm(sub(pts[mid - span], pts[mid + span]));
|
|
512
|
+
return [...fitRun(pts.slice(0, mid + 1), t1, tm, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(mid), mul(tm, -1), t2, tolerance, depth + 1, 0, skipEnd)];
|
|
513
|
+
}
|
|
514
|
+
let u = chordParams(pts);
|
|
515
|
+
let bez = generate(pts, u, t1, t2);
|
|
516
|
+
let { error, split } = maxError(pts, bez, u, skipStart, skipEnd);
|
|
517
|
+
const tol2 = tolerance * tolerance;
|
|
518
|
+
if (error <= tol2) return [bez];
|
|
519
|
+
if (error <= tol2 * 4) for (let it = 0; it < 4; it++) {
|
|
520
|
+
u = u.map((ui, i) => newton(bez, pts[i], ui));
|
|
521
|
+
bez = generate(pts, u, t1, t2);
|
|
522
|
+
({error, split} = maxError(pts, bez, u, skipStart, skipEnd));
|
|
523
|
+
if (error <= tol2) return [bez];
|
|
524
|
+
}
|
|
525
|
+
if (depth > 12 || n < 4) return [bez];
|
|
526
|
+
split = Math.min(n - 2, Math.max(1, split));
|
|
527
|
+
const span = Math.min(3, split, n - 1 - split);
|
|
528
|
+
const tc = norm(sub(pts[split - span], pts[split + span]));
|
|
529
|
+
return [...fitRun(pts.slice(0, split + 1), t1, tc, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(split), mul(tc, -1), t2, tolerance, depth + 1, 0, skipEnd)];
|
|
530
|
+
}
|
|
531
|
+
function chordParams(pts) {
|
|
532
|
+
const u = [0];
|
|
533
|
+
for (let i = 1; i < pts.length; i++) u.push(u[i - 1] + dist(pts[i], pts[i - 1]));
|
|
534
|
+
const total = u[u.length - 1] || 1;
|
|
535
|
+
return u.map((x) => x / total);
|
|
536
|
+
}
|
|
537
|
+
const B = [
|
|
538
|
+
(t) => (1 - t) ** 3,
|
|
539
|
+
(t) => 3 * t * (1 - t) ** 2,
|
|
540
|
+
(t) => 3 * t * t * (1 - t),
|
|
541
|
+
(t) => t ** 3
|
|
542
|
+
];
|
|
543
|
+
function pointAt(b, t) {
|
|
544
|
+
return add(add(mul(b[0], B[0](t)), mul(b[1], B[1](t))), add(mul(b[2], B[2](t)), mul(b[3], B[3](t))));
|
|
545
|
+
}
|
|
546
|
+
/** Least-squares handle lengths along the given tangents (Schneider's GenerateBezier). */
|
|
547
|
+
function generate(pts, u, t1, t2) {
|
|
548
|
+
const p0 = pts[0];
|
|
549
|
+
const p3 = pts[pts.length - 1];
|
|
550
|
+
let c00 = 0;
|
|
551
|
+
let c01 = 0;
|
|
552
|
+
let c11 = 0;
|
|
553
|
+
let x0 = 0;
|
|
554
|
+
let x1 = 0;
|
|
555
|
+
for (let i = 0; i < pts.length; i++) {
|
|
556
|
+
const a1 = mul(t1, B[1](u[i]));
|
|
557
|
+
const a2 = mul(t2, B[2](u[i]));
|
|
558
|
+
c00 += dot(a1, a1);
|
|
559
|
+
c01 += dot(a1, a2);
|
|
560
|
+
c11 += dot(a2, a2);
|
|
561
|
+
const tmp = sub(pts[i], add(mul(p0, B[0](u[i]) + B[1](u[i])), mul(p3, B[2](u[i]) + B[3](u[i]))));
|
|
562
|
+
x0 += dot(a1, tmp);
|
|
563
|
+
x1 += dot(a2, tmp);
|
|
564
|
+
}
|
|
565
|
+
const det = c00 * c11 - c01 * c01;
|
|
566
|
+
let alpha1 = Math.abs(det) > 1e-12 ? (x0 * c11 - x1 * c01) / det : 0;
|
|
567
|
+
let alpha2 = Math.abs(det) > 1e-12 ? (c00 * x1 - c01 * x0) / det : 0;
|
|
568
|
+
const seg = dist(p0, p3);
|
|
569
|
+
if (alpha1 < 1e-6 * seg || alpha2 < 1e-6 * seg) alpha1 = alpha2 = seg / 3;
|
|
570
|
+
return [
|
|
571
|
+
p0,
|
|
572
|
+
add(p0, mul(t1, alpha1)),
|
|
573
|
+
add(p3, mul(t2, alpha2)),
|
|
574
|
+
p3
|
|
575
|
+
];
|
|
576
|
+
}
|
|
577
|
+
/** Worst squared distance, ignoring `skipStart` / `skipEnd` points at the ends. */
|
|
578
|
+
function maxError(pts, b, u, skipStart = 0, skipEnd = 0) {
|
|
579
|
+
let error = 0;
|
|
580
|
+
let split = Math.floor(pts.length / 2);
|
|
581
|
+
const from = Math.max(1, Math.min(skipStart, Math.floor(pts.length / 4)));
|
|
582
|
+
const to = pts.length - 1 - Math.min(skipEnd, Math.floor(pts.length / 4));
|
|
583
|
+
for (let i = from; i < Math.max(from, to); i++) {
|
|
584
|
+
const p = pointAt(b, u[i]);
|
|
585
|
+
const e = (p.x - pts[i].x) ** 2 + (p.y - pts[i].y) ** 2;
|
|
586
|
+
if (e >= error) {
|
|
587
|
+
error = e;
|
|
588
|
+
split = i;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
error,
|
|
593
|
+
split
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
/** One Newton–Raphson step towards the parameter of the point on `b` nearest `p`. */
|
|
597
|
+
function newton(b, p, u) {
|
|
598
|
+
const d1 = [
|
|
599
|
+
mul(sub(b[1], b[0]), 3),
|
|
600
|
+
mul(sub(b[2], b[1]), 3),
|
|
601
|
+
mul(sub(b[3], b[2]), 3)
|
|
602
|
+
];
|
|
603
|
+
const d2 = [mul(sub(d1[1], d1[0]), 2), mul(sub(d1[2], d1[1]), 2)];
|
|
604
|
+
const q = pointAt(b, u);
|
|
605
|
+
const q1 = add(add(mul(d1[0], (1 - u) ** 2), mul(d1[1], 2 * u * (1 - u))), mul(d1[2], u * u));
|
|
606
|
+
const q2 = add(mul(d2[0], 1 - u), mul(d2[1], u));
|
|
607
|
+
const num = dot(sub(q, p), q1);
|
|
608
|
+
const den = dot(q1, q1) + dot(sub(q, p), q2);
|
|
609
|
+
if (Math.abs(den) < 1e-12) return u;
|
|
610
|
+
return Math.min(1, Math.max(0, u - num / den));
|
|
611
|
+
}
|
|
612
|
+
//#endregion
|
|
613
|
+
//#region src/palette.ts
|
|
614
|
+
function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002 } = {}) {
|
|
615
|
+
const bins = /* @__PURE__ */ new Map();
|
|
616
|
+
let opaque = 0;
|
|
617
|
+
for (let i = 0; i < rgba.length; i += 4) {
|
|
618
|
+
if (rgba[i + 3] < 128) continue;
|
|
619
|
+
const r = rgba[i];
|
|
620
|
+
const g = rgba[i + 1];
|
|
621
|
+
const b = rgba[i + 2];
|
|
622
|
+
const key = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
|
|
623
|
+
const bin = bins.get(key);
|
|
624
|
+
if (bin) {
|
|
625
|
+
bin.n++;
|
|
626
|
+
bin.r += r;
|
|
627
|
+
bin.g += g;
|
|
628
|
+
bin.b += b;
|
|
629
|
+
} else bins.set(key, {
|
|
630
|
+
n: 1,
|
|
631
|
+
r,
|
|
632
|
+
g,
|
|
633
|
+
b
|
|
634
|
+
});
|
|
635
|
+
opaque++;
|
|
636
|
+
}
|
|
637
|
+
const sorted = [...bins.values()].sort((a, b) => b.n - a.n);
|
|
638
|
+
const picked = [];
|
|
639
|
+
for (const bin of sorted) {
|
|
640
|
+
if (picked.length >= maxColors) break;
|
|
641
|
+
if (bin.n / opaque < minShare && picked.length > 0) break;
|
|
642
|
+
const rgb = [
|
|
643
|
+
bin.r / bin.n,
|
|
644
|
+
bin.g / bin.n,
|
|
645
|
+
bin.b / bin.n
|
|
646
|
+
];
|
|
647
|
+
const lab = oklab(rgb);
|
|
648
|
+
if (picked.every((p) => distance(p.lab, lab) >= minDistance)) picked.push({
|
|
649
|
+
lab,
|
|
650
|
+
rgb
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
return picked.map((p) => toHex(p.rgb));
|
|
654
|
+
}
|
|
655
|
+
function oklab([r, g, b]) {
|
|
656
|
+
const lin = (c) => {
|
|
657
|
+
c /= 255;
|
|
658
|
+
return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
|
|
659
|
+
};
|
|
660
|
+
const [lr, lg, lb] = [
|
|
661
|
+
lin(r),
|
|
662
|
+
lin(g),
|
|
663
|
+
lin(b)
|
|
664
|
+
];
|
|
665
|
+
const l = Math.cbrt(.4122214708 * lr + .5363325363 * lg + .0514459929 * lb);
|
|
666
|
+
const m = Math.cbrt(.2119034982 * lr + .6806995451 * lg + .1073969566 * lb);
|
|
667
|
+
const s = Math.cbrt(.0883024619 * lr + .2817188376 * lg + .6299787005 * lb);
|
|
668
|
+
return [
|
|
669
|
+
.2104542553 * l + .793617785 * m - .0040720468 * s,
|
|
670
|
+
1.9779984951 * l - 2.428592205 * m + .4505937099 * s,
|
|
671
|
+
.0259040371 * l + .7827717662 * m - .808675766 * s
|
|
672
|
+
];
|
|
673
|
+
}
|
|
674
|
+
const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
675
|
+
const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
|
|
676
|
+
/**
|
|
677
|
+
* Pixel art's palette: its colours exactly, most-used first. Pixel art has a
|
|
678
|
+
* handful of deliberate colours, and a one-pixel eye matters as much as the
|
|
679
|
+
* sky, so nothing is merged or dropped for being rare or close to another.
|
|
680
|
+
* Beyond `maxColors` distinct colours (a photo picked as pixel art), the
|
|
681
|
+
* rarest ones take their nearest kept colour when pixels are labelled.
|
|
682
|
+
*/
|
|
683
|
+
function exactPalette(rgba, maxColors) {
|
|
684
|
+
const counts = /* @__PURE__ */ new Map();
|
|
685
|
+
for (let i = 0; i < rgba.length; i += 4) {
|
|
686
|
+
if (rgba[i + 3] < 128) continue;
|
|
687
|
+
const key = rgba[i] << 16 | rgba[i + 1] << 8 | rgba[i + 2];
|
|
688
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
689
|
+
}
|
|
690
|
+
return [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0]).slice(0, Math.max(1, maxColors)).map(([k]) => `#${k.toString(16).padStart(6, "0")}`);
|
|
691
|
+
}
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region src/path.ts
|
|
694
|
+
const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
|
|
695
|
+
const PARAMS = {
|
|
696
|
+
M: 2,
|
|
697
|
+
L: 2,
|
|
698
|
+
H: 1,
|
|
699
|
+
V: 1,
|
|
700
|
+
C: 6,
|
|
701
|
+
S: 4,
|
|
702
|
+
Q: 4,
|
|
703
|
+
T: 2,
|
|
704
|
+
A: 7,
|
|
705
|
+
Z: 0
|
|
706
|
+
};
|
|
707
|
+
const SAME = 1e-6;
|
|
708
|
+
function parsePath(d) {
|
|
709
|
+
const tokens = d.match(TOKEN) ?? [];
|
|
710
|
+
const subs = [];
|
|
711
|
+
let sub = null;
|
|
712
|
+
let cur = {
|
|
713
|
+
x: 0,
|
|
714
|
+
y: 0
|
|
715
|
+
};
|
|
716
|
+
let start = {
|
|
717
|
+
x: 0,
|
|
718
|
+
y: 0
|
|
719
|
+
};
|
|
720
|
+
let lastCubic = null;
|
|
721
|
+
let lastQuad = null;
|
|
722
|
+
let i = 0;
|
|
723
|
+
let cmd = "";
|
|
724
|
+
const begin = (p) => {
|
|
725
|
+
sub = {
|
|
726
|
+
nodes: [{
|
|
727
|
+
x: p.x,
|
|
728
|
+
y: p.y,
|
|
729
|
+
in: null,
|
|
730
|
+
out: null
|
|
731
|
+
}],
|
|
732
|
+
closed: false
|
|
733
|
+
};
|
|
734
|
+
subs.push(sub);
|
|
735
|
+
};
|
|
736
|
+
const ensure = () => {
|
|
737
|
+
if (!sub || sub.closed) begin(cur);
|
|
738
|
+
return sub;
|
|
739
|
+
};
|
|
740
|
+
const lineTo = (p) => {
|
|
741
|
+
ensure().nodes.push({
|
|
742
|
+
x: p.x,
|
|
743
|
+
y: p.y,
|
|
744
|
+
in: null,
|
|
745
|
+
out: null
|
|
746
|
+
});
|
|
747
|
+
cur = p;
|
|
748
|
+
};
|
|
749
|
+
const at = (a, b) => a.x === b.x && a.y === b.y;
|
|
750
|
+
const curveTo = (c1, c2, p) => {
|
|
751
|
+
const s = ensure();
|
|
752
|
+
const prev = s.nodes[s.nodes.length - 1];
|
|
753
|
+
prev.out = at(c1, prev) ? null : c1;
|
|
754
|
+
s.nodes.push({
|
|
755
|
+
x: p.x,
|
|
756
|
+
y: p.y,
|
|
757
|
+
in: at(c2, p) ? null : c2,
|
|
758
|
+
out: null
|
|
759
|
+
});
|
|
760
|
+
cur = p;
|
|
761
|
+
};
|
|
762
|
+
while (i < tokens.length) {
|
|
763
|
+
const t = tokens[i];
|
|
764
|
+
if (/[a-z]/i.test(t)) {
|
|
765
|
+
cmd = t;
|
|
766
|
+
i++;
|
|
767
|
+
if (cmd === "Z" || cmd === "z") {
|
|
768
|
+
if (sub) close(sub);
|
|
769
|
+
cur = start;
|
|
770
|
+
lastCubic = lastQuad = null;
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
} else if (!cmd) {
|
|
774
|
+
i++;
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
const upper = cmd.toUpperCase();
|
|
778
|
+
const n = PARAMS[upper];
|
|
779
|
+
if (i + n > tokens.length) break;
|
|
780
|
+
const v = tokens.slice(i, i + n).map(Number);
|
|
781
|
+
if (v.some((x) => !Number.isFinite(x))) break;
|
|
782
|
+
i += n;
|
|
783
|
+
const rel = cmd !== upper;
|
|
784
|
+
const ox = rel ? cur.x : 0;
|
|
785
|
+
const oy = rel ? cur.y : 0;
|
|
786
|
+
let cubic = null;
|
|
787
|
+
let quad = null;
|
|
788
|
+
switch (upper) {
|
|
789
|
+
case "M":
|
|
790
|
+
cur = start = {
|
|
791
|
+
x: v[0] + ox,
|
|
792
|
+
y: v[1] + oy
|
|
793
|
+
};
|
|
794
|
+
begin(cur);
|
|
795
|
+
cmd = rel ? "l" : "L";
|
|
796
|
+
break;
|
|
797
|
+
case "L":
|
|
798
|
+
lineTo({
|
|
799
|
+
x: v[0] + ox,
|
|
800
|
+
y: v[1] + oy
|
|
801
|
+
});
|
|
802
|
+
break;
|
|
803
|
+
case "H":
|
|
804
|
+
lineTo({
|
|
805
|
+
x: v[0] + ox,
|
|
806
|
+
y: cur.y
|
|
807
|
+
});
|
|
808
|
+
break;
|
|
809
|
+
case "V":
|
|
810
|
+
lineTo({
|
|
811
|
+
x: cur.x,
|
|
812
|
+
y: v[0] + oy
|
|
813
|
+
});
|
|
814
|
+
break;
|
|
815
|
+
case "C":
|
|
816
|
+
cubic = {
|
|
817
|
+
x: v[2] + ox,
|
|
818
|
+
y: v[3] + oy
|
|
819
|
+
};
|
|
820
|
+
curveTo({
|
|
821
|
+
x: v[0] + ox,
|
|
822
|
+
y: v[1] + oy
|
|
823
|
+
}, cubic, {
|
|
824
|
+
x: v[4] + ox,
|
|
825
|
+
y: v[5] + oy
|
|
826
|
+
});
|
|
827
|
+
break;
|
|
828
|
+
case "S": {
|
|
829
|
+
const c1 = lastCubic ? {
|
|
830
|
+
x: 2 * cur.x - lastCubic.x,
|
|
831
|
+
y: 2 * cur.y - lastCubic.y
|
|
832
|
+
} : cur;
|
|
833
|
+
cubic = {
|
|
834
|
+
x: v[0] + ox,
|
|
835
|
+
y: v[1] + oy
|
|
836
|
+
};
|
|
837
|
+
curveTo(c1, cubic, {
|
|
838
|
+
x: v[2] + ox,
|
|
839
|
+
y: v[3] + oy
|
|
840
|
+
});
|
|
841
|
+
break;
|
|
842
|
+
}
|
|
843
|
+
case "Q":
|
|
844
|
+
case "T": {
|
|
845
|
+
const q = upper === "Q" ? {
|
|
846
|
+
x: v[0] + ox,
|
|
847
|
+
y: v[1] + oy
|
|
848
|
+
} : lastQuad ? {
|
|
849
|
+
x: 2 * cur.x - lastQuad.x,
|
|
850
|
+
y: 2 * cur.y - lastQuad.y
|
|
851
|
+
} : cur;
|
|
852
|
+
const p = upper === "Q" ? {
|
|
853
|
+
x: v[2] + ox,
|
|
854
|
+
y: v[3] + oy
|
|
855
|
+
} : {
|
|
856
|
+
x: v[0] + ox,
|
|
857
|
+
y: v[1] + oy
|
|
858
|
+
};
|
|
859
|
+
const p0 = cur;
|
|
860
|
+
curveTo({
|
|
861
|
+
x: p0.x + 2 / 3 * (q.x - p0.x),
|
|
862
|
+
y: p0.y + 2 / 3 * (q.y - p0.y)
|
|
863
|
+
}, {
|
|
864
|
+
x: p.x + 2 / 3 * (q.x - p.x),
|
|
865
|
+
y: p.y + 2 / 3 * (q.y - p.y)
|
|
866
|
+
}, p);
|
|
867
|
+
quad = q;
|
|
868
|
+
break;
|
|
869
|
+
}
|
|
870
|
+
case "A": lineTo({
|
|
871
|
+
x: v[5] + ox,
|
|
872
|
+
y: v[6] + oy
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
lastCubic = cubic;
|
|
876
|
+
lastQuad = quad;
|
|
877
|
+
}
|
|
878
|
+
return subs;
|
|
879
|
+
}
|
|
880
|
+
function close(sub) {
|
|
881
|
+
if (sub.closed) return;
|
|
882
|
+
sub.closed = true;
|
|
883
|
+
const { nodes } = sub;
|
|
884
|
+
if (nodes.length < 2) return;
|
|
885
|
+
const first = nodes[0];
|
|
886
|
+
const last = nodes[nodes.length - 1];
|
|
887
|
+
if (Math.abs(first.x - last.x) < SAME && Math.abs(first.y - last.y) < SAME) {
|
|
888
|
+
first.in = last.in;
|
|
889
|
+
nodes.pop();
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
const num = (n) => {
|
|
893
|
+
const r = Math.round(n * 1e3) / 1e3;
|
|
894
|
+
return Object.is(r, -0) ? "0" : String(r);
|
|
895
|
+
};
|
|
896
|
+
const pt = (p) => `${num(p.x)} ${num(p.y)}`;
|
|
897
|
+
function segment(a, b) {
|
|
898
|
+
return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
|
|
899
|
+
}
|
|
900
|
+
function serializePath(subs) {
|
|
901
|
+
let d = "";
|
|
902
|
+
for (const s of subs) {
|
|
903
|
+
if (!s.nodes.length) continue;
|
|
904
|
+
d += `M${pt(s.nodes[0])}`;
|
|
905
|
+
for (let i = 1; i < s.nodes.length; i++) d += segment(s.nodes[i - 1], s.nodes[i]);
|
|
906
|
+
if (s.closed) {
|
|
907
|
+
const first = s.nodes[0];
|
|
908
|
+
const last = s.nodes[s.nodes.length - 1];
|
|
909
|
+
if (s.nodes.length > 1 && (last.out || first.in)) d += segment(last, first);
|
|
910
|
+
d += "Z";
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
return d;
|
|
914
|
+
}
|
|
915
|
+
function mapPoints(subs, f) {
|
|
916
|
+
const m = (p) => p ? f(p) : null;
|
|
917
|
+
return subs.map((s) => ({
|
|
918
|
+
closed: s.closed,
|
|
919
|
+
nodes: s.nodes.map((n) => ({
|
|
920
|
+
...f(n),
|
|
921
|
+
in: m(n.in),
|
|
922
|
+
out: m(n.out)
|
|
923
|
+
}))
|
|
924
|
+
}));
|
|
925
|
+
}
|
|
926
|
+
//#endregion
|
|
927
|
+
//#region src/inlay.ts
|
|
928
|
+
/**
|
|
929
|
+
* Inlay, our shared-edge tracer: Logo, Illustration, Line art and Pixel art.
|
|
930
|
+
* Like inlaid wood, every piece is cut to fit its neighbours exactly.
|
|
931
|
+
*
|
|
932
|
+
* VTracer traces every colour region on its own, so an edge between two
|
|
933
|
+
* regions is traced twice. Fitting the two copies separately leaves hairline
|
|
934
|
+
* gaps and slivers; leaving them to VTracer's spline fitter gives the wobbly
|
|
935
|
+
* lines and rounded corners this replaces. Instead:
|
|
936
|
+
*
|
|
937
|
+
* 1. Label every pixel with a palette colour (or ink / paper for line art).
|
|
938
|
+
* Anti-aliased pixels, which sit between two colours, take the closest
|
|
939
|
+
* colour *among their neighbours*, so an edge between red and blue never
|
|
940
|
+
* grows a one-pixel purple sliver.
|
|
941
|
+
* 2. Merge specks smaller than `speckle`² pixels into whatever surrounds them.
|
|
942
|
+
* 3. Walk the cracks between differently labelled pixels. Where three or more
|
|
943
|
+
* regions meet (or two meet diagonally) is a junction; every boundary
|
|
944
|
+
* between two junctions is one chain, with one region on each side.
|
|
945
|
+
* 4. Fit each chain once (src/lib/fit.ts): corners first, then straight lines
|
|
946
|
+
* where they fit and curves where they don't.
|
|
947
|
+
* 5. Build each region's outline from its chains, reversing the ones it sees
|
|
948
|
+
* from the other side. Neighbours share the exact same fitted edge: no
|
|
949
|
+
* gaps, no overlaps, which is also what a vinyl cutter wants.
|
|
950
|
+
*
|
|
951
|
+
* Regions are 4-connected, so two pixels touching only at a corner are
|
|
952
|
+
* separate shapes, and each region is one <path> (its outline plus its holes,
|
|
953
|
+
* wound oppositely so the default nonzero fill rule cuts the holes).
|
|
954
|
+
*/
|
|
955
|
+
const VOID = -1;
|
|
956
|
+
/** The trace as an SVG document. */
|
|
957
|
+
function toSvg(r) {
|
|
958
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${r.width}" height="${r.height}" viewBox="0 0 ${r.width} ${r.height}">\n${r.paths.map((p) => `<path d="${p.d}" fill="${p.fill}"/>`).join("\n")}\n</svg>\n`;
|
|
959
|
+
}
|
|
960
|
+
/** Trace to an SVG string; `trace` gives the shapes as data. */
|
|
961
|
+
const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
|
|
962
|
+
/**
|
|
963
|
+
* Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
|
|
964
|
+
* into filled shapes that share their edges exactly.
|
|
965
|
+
*/
|
|
966
|
+
function trace(rgba, w, h, o) {
|
|
967
|
+
const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette) : labelBinary(rgba, w, h, o.threshold);
|
|
968
|
+
if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
|
|
969
|
+
if (!o.pixels) despur(labels, w, h);
|
|
970
|
+
mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
|
|
971
|
+
const { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
|
|
972
|
+
const chains = findChains(comp, w, h);
|
|
973
|
+
const byComp = /* @__PURE__ */ new Map();
|
|
974
|
+
for (const c of chains) {
|
|
975
|
+
const cubics = o.pixels ? staircase(c.pts, c.closed) : fitChain(c.pts, c.closed, o);
|
|
976
|
+
if (!cubics.length) continue;
|
|
977
|
+
if (c.left !== VOID) addOriented(byComp, c.left, {
|
|
978
|
+
...c,
|
|
979
|
+
cubics,
|
|
980
|
+
reversed: false
|
|
981
|
+
});
|
|
982
|
+
if (c.right !== VOID) addOriented(byComp, c.right, {
|
|
983
|
+
...c,
|
|
984
|
+
cubics: reverse(cubics),
|
|
985
|
+
reversed: true
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
const order = [...byComp.keys()].sort((a, b) => compArea[b] - compArea[a]);
|
|
989
|
+
const paths = [];
|
|
990
|
+
for (const id of order) {
|
|
991
|
+
const subs = assemble(byComp.get(id));
|
|
992
|
+
if (!subs.length) continue;
|
|
993
|
+
paths.push({
|
|
994
|
+
d: serializePath(subs),
|
|
995
|
+
fill: colors[compLabel[id]]
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
return {
|
|
999
|
+
width: w,
|
|
1000
|
+
height: h,
|
|
1001
|
+
paths
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* A chain as its exact pixel boundary: a line between each pair of turns.
|
|
1006
|
+
* The points are pixel corners about a pixel apart, so a run of them in one
|
|
1007
|
+
* direction is one straight edge. A closed loop starts at a turn, so its seam
|
|
1008
|
+
* isn't a node in the middle of an edge.
|
|
1009
|
+
*/
|
|
1010
|
+
function staircase(pts, closed) {
|
|
1011
|
+
const n = pts.length;
|
|
1012
|
+
if (n < 2) return [];
|
|
1013
|
+
const dir = (a, b) => `${Math.sign(b.x - a.x)},${Math.sign(b.y - a.y)}`;
|
|
1014
|
+
const isTurn = (i) => {
|
|
1015
|
+
const a = pts[(i - 1 + n) % n];
|
|
1016
|
+
const b = pts[i];
|
|
1017
|
+
const c = pts[(i + 1) % n];
|
|
1018
|
+
return dir(a, b) !== dir(b, c);
|
|
1019
|
+
};
|
|
1020
|
+
const keep = [];
|
|
1021
|
+
if (closed) {
|
|
1022
|
+
const start = pts.findIndex((_, i) => isTurn(i));
|
|
1023
|
+
if (start < 0) return [];
|
|
1024
|
+
for (let k = 0; k < n; k++) {
|
|
1025
|
+
const i = (start + k) % n;
|
|
1026
|
+
if (isTurn(i)) keep.push(pts[i]);
|
|
1027
|
+
}
|
|
1028
|
+
keep.push(keep[0]);
|
|
1029
|
+
} else {
|
|
1030
|
+
keep.push(pts[0]);
|
|
1031
|
+
for (let i = 1; i < n - 1; i++) if (isTurn(i)) keep.push(pts[i]);
|
|
1032
|
+
keep.push(pts[n - 1]);
|
|
1033
|
+
}
|
|
1034
|
+
const out = [];
|
|
1035
|
+
for (let i = 1; i < keep.length; i++) {
|
|
1036
|
+
const a = keep[i - 1];
|
|
1037
|
+
const b = keep[i];
|
|
1038
|
+
out.push([
|
|
1039
|
+
a,
|
|
1040
|
+
{
|
|
1041
|
+
x: a.x + (b.x - a.x) / 3,
|
|
1042
|
+
y: a.y + (b.y - a.y) / 3
|
|
1043
|
+
},
|
|
1044
|
+
{
|
|
1045
|
+
x: a.x + (b.x - a.x) * 2 / 3,
|
|
1046
|
+
y: a.y + (b.y - a.y) * 2 / 3
|
|
1047
|
+
},
|
|
1048
|
+
b
|
|
1049
|
+
]);
|
|
1050
|
+
}
|
|
1051
|
+
return out;
|
|
1052
|
+
}
|
|
1053
|
+
/** Relabel merged colours as their targets, following chains, in place. */
|
|
1054
|
+
function mergeLabels(labels, colors, merge) {
|
|
1055
|
+
const index = new Map(colors.map((c, i) => [c, i]));
|
|
1056
|
+
const remap = colors.map((c, i) => {
|
|
1057
|
+
let to = c;
|
|
1058
|
+
let at = i;
|
|
1059
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1060
|
+
while (merge[to] && !seen.has(to)) {
|
|
1061
|
+
seen.add(to);
|
|
1062
|
+
to = merge[to].toLowerCase();
|
|
1063
|
+
const k = index.get(to);
|
|
1064
|
+
if (k !== void 0) at = k;
|
|
1065
|
+
}
|
|
1066
|
+
return at;
|
|
1067
|
+
});
|
|
1068
|
+
if (remap.every((t, i) => t === i)) return;
|
|
1069
|
+
for (let i = 0; i < labels.length; i++) labels[i] = remap[labels[i]];
|
|
1070
|
+
}
|
|
1071
|
+
function labelPalette(rgba, w, h, palette) {
|
|
1072
|
+
const pal = palette.map(hexToRgb);
|
|
1073
|
+
const labs = pal.map(oklab);
|
|
1074
|
+
const n = w * h;
|
|
1075
|
+
const labels = new Int32Array(n);
|
|
1076
|
+
const unsure = new Uint8Array(n);
|
|
1077
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1078
|
+
const transparent = pal.length;
|
|
1079
|
+
for (let i = 0; i < n; i++) {
|
|
1080
|
+
const r = rgba[i * 4];
|
|
1081
|
+
const g = rgba[i * 4 + 1];
|
|
1082
|
+
const b = rgba[i * 4 + 2];
|
|
1083
|
+
if (rgba[i * 4 + 3] < 128) {
|
|
1084
|
+
labels[i] = transparent;
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
const key = r << 16 | g << 8 | b;
|
|
1088
|
+
let hit = cache.get(key);
|
|
1089
|
+
if (hit === void 0) {
|
|
1090
|
+
const lab = oklab([
|
|
1091
|
+
r,
|
|
1092
|
+
g,
|
|
1093
|
+
b
|
|
1094
|
+
]);
|
|
1095
|
+
let best = 0;
|
|
1096
|
+
let d1 = Infinity;
|
|
1097
|
+
let d2 = Infinity;
|
|
1098
|
+
labs.forEach((p, k) => {
|
|
1099
|
+
const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
|
|
1100
|
+
if (d < d1) {
|
|
1101
|
+
d2 = d1;
|
|
1102
|
+
d1 = d;
|
|
1103
|
+
best = k;
|
|
1104
|
+
} else if (d < d2) d2 = d;
|
|
1105
|
+
});
|
|
1106
|
+
hit = best | (d2 < Infinity && d1 > .4 * d2 ? 256 : 0);
|
|
1107
|
+
cache.set(key, hit);
|
|
1108
|
+
}
|
|
1109
|
+
labels[i] = hit & 255;
|
|
1110
|
+
unsure[i] = hit >> 8;
|
|
1111
|
+
}
|
|
1112
|
+
const fixed = labels.slice();
|
|
1113
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
1114
|
+
const i = y * w + x;
|
|
1115
|
+
if (!unsure[i]) continue;
|
|
1116
|
+
const lab = oklab([
|
|
1117
|
+
rgba[i * 4],
|
|
1118
|
+
rgba[i * 4 + 1],
|
|
1119
|
+
rgba[i * 4 + 2]
|
|
1120
|
+
]);
|
|
1121
|
+
let best = -1;
|
|
1122
|
+
let bd = Infinity;
|
|
1123
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
1124
|
+
const nx = x + dx;
|
|
1125
|
+
const ny = y + dy;
|
|
1126
|
+
if (!dx && !dy || nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
|
1127
|
+
const j = ny * w + nx;
|
|
1128
|
+
if (unsure[j]) continue;
|
|
1129
|
+
const l = labels[j];
|
|
1130
|
+
if (l === transparent || l === best) continue;
|
|
1131
|
+
const p = labs[l];
|
|
1132
|
+
const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
|
|
1133
|
+
if (d < bd) {
|
|
1134
|
+
bd = d;
|
|
1135
|
+
best = l;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
if (best >= 0) fixed[i] = best;
|
|
1139
|
+
}
|
|
1140
|
+
return {
|
|
1141
|
+
labels: fixed,
|
|
1142
|
+
colors: [...palette.map((c) => c.toLowerCase()), ""],
|
|
1143
|
+
drawn: [...palette.map(() => true), false]
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
function labelBinary(rgba, w, h, threshold) {
|
|
1147
|
+
const n = w * h;
|
|
1148
|
+
const lum = new Uint8Array(n);
|
|
1149
|
+
const alpha = new Uint8Array(n);
|
|
1150
|
+
for (let i = 0; i < n; i++) {
|
|
1151
|
+
lum[i] = Math.round(.299 * rgba[i * 4] + .587 * rgba[i * 4 + 1] + .114 * rgba[i * 4 + 2]);
|
|
1152
|
+
alpha[i] = rgba[i * 4 + 3] >= 128 ? 1 : 0;
|
|
1153
|
+
}
|
|
1154
|
+
const labels = new Int32Array(n);
|
|
1155
|
+
if (threshold !== null) for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < threshold ? 0 : 1;
|
|
1156
|
+
else {
|
|
1157
|
+
const global = otsu(lum, alpha);
|
|
1158
|
+
const mean = boxMean(lum, w, h, Math.max(7, Math.round(Math.min(w, h) / 32)));
|
|
1159
|
+
for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < mean[i] - 12 && lum[i] < global + 32 ? 0 : 1;
|
|
1160
|
+
}
|
|
1161
|
+
return {
|
|
1162
|
+
labels,
|
|
1163
|
+
colors: ["#000000", ""],
|
|
1164
|
+
drawn: [true, false]
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
/** Mean of a (2r+1)² window around each pixel, clipped at the edges, via an integral image. */
|
|
1168
|
+
function boxMean(v, w, h, r) {
|
|
1169
|
+
const W = w + 1;
|
|
1170
|
+
const sum = new Float64Array(W * (h + 1));
|
|
1171
|
+
for (let y = 0; y < h; y++) {
|
|
1172
|
+
let row = 0;
|
|
1173
|
+
for (let x = 0; x < w; x++) {
|
|
1174
|
+
row += v[y * w + x];
|
|
1175
|
+
sum[(y + 1) * W + x + 1] = sum[y * W + x + 1] + row;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
const out = new Float32Array(w * h);
|
|
1179
|
+
for (let y = 0; y < h; y++) {
|
|
1180
|
+
const y0 = Math.max(0, y - r);
|
|
1181
|
+
const y1 = Math.min(h, y + r + 1);
|
|
1182
|
+
for (let x = 0; x < w; x++) {
|
|
1183
|
+
const x0 = Math.max(0, x - r);
|
|
1184
|
+
const x1 = Math.min(w, x + r + 1);
|
|
1185
|
+
out[y * w + x] = (sum[y1 * W + x1] - sum[y0 * W + x1] - sum[y1 * W + x0] + sum[y0 * W + x0]) / ((x1 - x0) * (y1 - y0));
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
return out;
|
|
1189
|
+
}
|
|
1190
|
+
/** Otsu's threshold over opaque pixels: the split that best separates two populations. */
|
|
1191
|
+
function otsu(lum, alpha) {
|
|
1192
|
+
const hist = new Array(256).fill(0);
|
|
1193
|
+
let total = 0;
|
|
1194
|
+
for (let i = 0; i < lum.length; i++) if (alpha[i]) {
|
|
1195
|
+
hist[lum[i]]++;
|
|
1196
|
+
total++;
|
|
1197
|
+
}
|
|
1198
|
+
let sum = 0;
|
|
1199
|
+
for (let v = 0; v < 256; v++) sum += v * hist[v];
|
|
1200
|
+
let sumB = 0;
|
|
1201
|
+
let wB = 0;
|
|
1202
|
+
let best = 128;
|
|
1203
|
+
let bestVar = -1;
|
|
1204
|
+
for (let t = 0; t < 256; t++) {
|
|
1205
|
+
wB += hist[t];
|
|
1206
|
+
if (!wB) continue;
|
|
1207
|
+
const wF = total - wB;
|
|
1208
|
+
if (!wF) break;
|
|
1209
|
+
sumB += t * hist[t];
|
|
1210
|
+
const mB = sumB / wB;
|
|
1211
|
+
const mF = (sum - sumB) / wF;
|
|
1212
|
+
const between = wB * wF * (mB - mF) ** 2;
|
|
1213
|
+
if (between > bestVar) {
|
|
1214
|
+
bestVar = between;
|
|
1215
|
+
best = t + 1;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
return best;
|
|
1219
|
+
}
|
|
1220
|
+
const hexToRgb = (hex) => [
|
|
1221
|
+
parseInt(hex.slice(1, 3), 16),
|
|
1222
|
+
parseInt(hex.slice(3, 5), 16),
|
|
1223
|
+
parseInt(hex.slice(5, 7), 16)
|
|
1224
|
+
];
|
|
1225
|
+
/**
|
|
1226
|
+
* A pixel whose eight neighbours are at least seven of one other colour takes
|
|
1227
|
+
* that colour: a lone pixel jutting out of an edge, or a one-pixel nick in one.
|
|
1228
|
+
* Where several colours meet, JPEG noise leaves exactly these, and fitted they
|
|
1229
|
+
* become little bumps and notches. A pixel on a one-pixel line has two
|
|
1230
|
+
* neighbours of its own colour, so lines survive, though such a line loses up
|
|
1231
|
+
* to two pixels at each end (an end pixel looks exactly like a spur). Two passes.
|
|
1232
|
+
*/
|
|
1233
|
+
function despur(labels, w, h) {
|
|
1234
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
1235
|
+
const src = labels.slice();
|
|
1236
|
+
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
|
|
1237
|
+
const i = y * w + x;
|
|
1238
|
+
const own = src[i];
|
|
1239
|
+
let best = -1;
|
|
1240
|
+
let bestCount = 0;
|
|
1241
|
+
for (let k = 0; k < 8; k++) {
|
|
1242
|
+
const l = src[i + NEIGHBOURS[k][1] * w + NEIGHBOURS[k][0]];
|
|
1243
|
+
if (l === own || l === best) continue;
|
|
1244
|
+
let c = 0;
|
|
1245
|
+
for (let q = 0; q < 8; q++) if (src[i + NEIGHBOURS[q][1] * w + NEIGHBOURS[q][0]] === l) c++;
|
|
1246
|
+
if (c > bestCount) {
|
|
1247
|
+
bestCount = c;
|
|
1248
|
+
best = l;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if (bestCount >= 7) labels[i] = best;
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
const NEIGHBOURS = [
|
|
1256
|
+
[-1, -1],
|
|
1257
|
+
[0, -1],
|
|
1258
|
+
[1, -1],
|
|
1259
|
+
[-1, 0],
|
|
1260
|
+
[1, 0],
|
|
1261
|
+
[-1, 1],
|
|
1262
|
+
[0, 1],
|
|
1263
|
+
[1, 1]
|
|
1264
|
+
];
|
|
1265
|
+
/**
|
|
1266
|
+
* 4-connected components of equal labels (two-pass union-find, linear time).
|
|
1267
|
+
* `keep` decides which labels count as regions; the rest are VOID.
|
|
1268
|
+
*/
|
|
1269
|
+
function components(labels, w, h, keep) {
|
|
1270
|
+
const n = w * h;
|
|
1271
|
+
const parent = new Int32Array(n);
|
|
1272
|
+
const kept = new Uint8Array(n);
|
|
1273
|
+
const find = (i) => {
|
|
1274
|
+
let r = i;
|
|
1275
|
+
while (parent[r] !== r) r = parent[r];
|
|
1276
|
+
while (parent[i] !== r) {
|
|
1277
|
+
const next = parent[i];
|
|
1278
|
+
parent[i] = r;
|
|
1279
|
+
i = next;
|
|
1280
|
+
}
|
|
1281
|
+
return r;
|
|
1282
|
+
};
|
|
1283
|
+
let maxLabel = 0;
|
|
1284
|
+
for (let i = 0; i < n; i++) if (labels[i] > maxLabel) maxLabel = labels[i];
|
|
1285
|
+
const keepLabel = new Uint8Array(maxLabel + 1);
|
|
1286
|
+
for (let l = 0; l <= maxLabel; l++) keepLabel[l] = keep(l) ? 1 : 0;
|
|
1287
|
+
for (let i = 0, x = 0; i < n; i++, x = x === w - 1 ? 0 : x + 1) {
|
|
1288
|
+
const l = labels[i];
|
|
1289
|
+
if (!keepLabel[l]) continue;
|
|
1290
|
+
kept[i] = 1;
|
|
1291
|
+
parent[i] = i;
|
|
1292
|
+
const left = x > 0 && kept[i - 1] && labels[i - 1] === l ? find(i - 1) : -1;
|
|
1293
|
+
const up = i >= w && kept[i - w] && labels[i - w] === l ? find(i - w) : -1;
|
|
1294
|
+
if (left >= 0 && up >= 0) {
|
|
1295
|
+
const r = Math.min(left, up);
|
|
1296
|
+
parent[left] = r;
|
|
1297
|
+
parent[up] = r;
|
|
1298
|
+
parent[i] = r;
|
|
1299
|
+
} else if (left >= 0) parent[i] = left;
|
|
1300
|
+
else if (up >= 0) parent[i] = up;
|
|
1301
|
+
}
|
|
1302
|
+
const comp = new Int32Array(n);
|
|
1303
|
+
const idOf = new Int32Array(n).fill(-1);
|
|
1304
|
+
const compLabel = [];
|
|
1305
|
+
const compArea = [];
|
|
1306
|
+
for (let i = 0; i < n; i++) {
|
|
1307
|
+
if (!kept[i]) {
|
|
1308
|
+
comp[i] = VOID;
|
|
1309
|
+
continue;
|
|
1310
|
+
}
|
|
1311
|
+
const r = find(i);
|
|
1312
|
+
let id = idOf[r];
|
|
1313
|
+
if (id < 0) {
|
|
1314
|
+
id = idOf[r] = compLabel.length;
|
|
1315
|
+
compLabel.push(labels[i]);
|
|
1316
|
+
compArea.push(0);
|
|
1317
|
+
}
|
|
1318
|
+
comp[i] = id;
|
|
1319
|
+
compArea[id]++;
|
|
1320
|
+
}
|
|
1321
|
+
return {
|
|
1322
|
+
comp,
|
|
1323
|
+
compLabel,
|
|
1324
|
+
compArea
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
/** Relabel every region smaller than `minArea` with the label it shares the most edge with. Smallest first. */
|
|
1328
|
+
function mergeSpecks(labels, w, h, minArea) {
|
|
1329
|
+
if (minArea <= 1) return;
|
|
1330
|
+
const { comp, compArea } = components(labels, w, h, () => true);
|
|
1331
|
+
const small = compArea.map((a, id) => ({
|
|
1332
|
+
a,
|
|
1333
|
+
id
|
|
1334
|
+
})).filter((c) => c.a < minArea);
|
|
1335
|
+
if (!small.length) return;
|
|
1336
|
+
const start = new Int32Array(compArea.length + 1);
|
|
1337
|
+
for (let i = 0; i < compArea.length; i++) start[i + 1] = start[i] + compArea[i];
|
|
1338
|
+
const fill = start.slice(0, compArea.length);
|
|
1339
|
+
const pixels = new Int32Array(w * h);
|
|
1340
|
+
for (let i = 0; i < w * h; i++) pixels[fill[comp[i]]++] = i;
|
|
1341
|
+
small.sort((p, q) => p.a - q.a);
|
|
1342
|
+
for (const { id } of small) {
|
|
1343
|
+
const own = labels[pixels[start[id]]];
|
|
1344
|
+
const votes = /* @__PURE__ */ new Map();
|
|
1345
|
+
for (let k = start[id]; k < start[id + 1]; k++) {
|
|
1346
|
+
const i = pixels[k];
|
|
1347
|
+
const x = i % w;
|
|
1348
|
+
const y = (i - x) / w;
|
|
1349
|
+
const vote = (j) => {
|
|
1350
|
+
const l = labels[j];
|
|
1351
|
+
if (l !== own) votes.set(l, (votes.get(l) ?? 0) + 1);
|
|
1352
|
+
};
|
|
1353
|
+
if (x > 0) vote(i - 1);
|
|
1354
|
+
if (x < w - 1) vote(i + 1);
|
|
1355
|
+
if (y > 0) vote(i - w);
|
|
1356
|
+
if (y < h - 1) vote(i + w);
|
|
1357
|
+
}
|
|
1358
|
+
let best = own;
|
|
1359
|
+
let most = 0;
|
|
1360
|
+
for (const [l, v] of votes) if (v > most) most = v, best = l;
|
|
1361
|
+
if (best !== own) for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
function findChains(comp, w, h) {
|
|
1365
|
+
const C = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? VOID : comp[y * w + x];
|
|
1366
|
+
const W1 = w + 1;
|
|
1367
|
+
const hEdge = new Uint8Array(W1 * (h + 1));
|
|
1368
|
+
const vEdge = new Uint8Array(W1 * (h + 1));
|
|
1369
|
+
for (let y = 0; y <= h; y++) for (let x = 0; x < w; x++) if (C(x, y - 1) !== C(x, y)) hEdge[y * W1 + x] = 1;
|
|
1370
|
+
for (let y = 0; y < h; y++) for (let x = 0; x <= w; x++) if (C(x - 1, y) !== C(x, y)) vEdge[y * W1 + x] = 1;
|
|
1371
|
+
const degree = (x, y) => (x > 0 && hEdge[y * W1 + x - 1] ? 1 : 0) + (x < w && hEdge[y * W1 + x] ? 1 : 0) + (y > 0 && vEdge[(y - 1) * W1 + x] ? 1 : 0) + (y < h && vEdge[y * W1 + x] ? 1 : 0);
|
|
1372
|
+
const DIRS = [
|
|
1373
|
+
{
|
|
1374
|
+
x: 1,
|
|
1375
|
+
y: 0
|
|
1376
|
+
},
|
|
1377
|
+
{
|
|
1378
|
+
x: 0,
|
|
1379
|
+
y: 1
|
|
1380
|
+
},
|
|
1381
|
+
{
|
|
1382
|
+
x: -1,
|
|
1383
|
+
y: 0
|
|
1384
|
+
},
|
|
1385
|
+
{
|
|
1386
|
+
x: 0,
|
|
1387
|
+
y: -1
|
|
1388
|
+
}
|
|
1389
|
+
];
|
|
1390
|
+
const has = (x, y, d) => d === 0 ? x < w && hEdge[y * W1 + x] : d === 1 ? y < h && vEdge[y * W1 + x] : d === 2 ? x > 0 && hEdge[y * W1 + x - 1] : y > 0 && vEdge[(y - 1) * W1 + x];
|
|
1391
|
+
const take = (x, y, d) => {
|
|
1392
|
+
if (d === 0) hEdge[y * W1 + x] = 0;
|
|
1393
|
+
else if (d === 1) vEdge[y * W1 + x] = 0;
|
|
1394
|
+
else if (d === 2) hEdge[y * W1 + x - 1] = 0;
|
|
1395
|
+
else vEdge[(y - 1) * W1 + x] = 0;
|
|
1396
|
+
};
|
|
1397
|
+
const sides = (x, y, d) => d === 0 ? [C(x, y - 1), C(x, y)] : d === 1 ? [C(x, y), C(x - 1, y)] : d === 2 ? [C(x - 1, y), C(x - 1, y - 1)] : [C(x - 1, y - 1), C(x, y - 1)];
|
|
1398
|
+
const junction = new Uint8Array(W1 * (h + 1));
|
|
1399
|
+
for (let y = 0; y <= h; y++) for (let x = 0; x <= w; x++) if (degree(x, y) >= 3) junction[y * W1 + x] = 1;
|
|
1400
|
+
const chains = [];
|
|
1401
|
+
const walk = (sx, sy, d0) => {
|
|
1402
|
+
const [left, right] = sides(sx, sy, d0);
|
|
1403
|
+
const pts = [{
|
|
1404
|
+
x: sx,
|
|
1405
|
+
y: sy
|
|
1406
|
+
}];
|
|
1407
|
+
let x = sx;
|
|
1408
|
+
let y = sy;
|
|
1409
|
+
let d = d0;
|
|
1410
|
+
let last = d0;
|
|
1411
|
+
for (;;) {
|
|
1412
|
+
take(x, y, d);
|
|
1413
|
+
x += DIRS[d].x;
|
|
1414
|
+
y += DIRS[d].y;
|
|
1415
|
+
last = d;
|
|
1416
|
+
if (junction[y * W1 + x] || x === sx && y === sy) break;
|
|
1417
|
+
const next = [
|
|
1418
|
+
d,
|
|
1419
|
+
(d + 1) % 4,
|
|
1420
|
+
(d + 3) % 4
|
|
1421
|
+
].find((k) => has(x, y, k));
|
|
1422
|
+
if (next === void 0) break;
|
|
1423
|
+
if (next !== d) pts.push({
|
|
1424
|
+
x,
|
|
1425
|
+
y
|
|
1426
|
+
});
|
|
1427
|
+
d = next;
|
|
1428
|
+
}
|
|
1429
|
+
const closed = x === sx && y === sy && !junction[sy * W1 + sx];
|
|
1430
|
+
if (!closed) pts.push({
|
|
1431
|
+
x,
|
|
1432
|
+
y
|
|
1433
|
+
});
|
|
1434
|
+
chains.push({
|
|
1435
|
+
pts,
|
|
1436
|
+
closed,
|
|
1437
|
+
left,
|
|
1438
|
+
right,
|
|
1439
|
+
from: sy * W1 + sx,
|
|
1440
|
+
to: y * W1 + x,
|
|
1441
|
+
first: DIRS[d0],
|
|
1442
|
+
last: DIRS[last]
|
|
1443
|
+
});
|
|
1444
|
+
};
|
|
1445
|
+
for (let y = 0; y <= h; y++) for (let x = 0; x <= w; x++) {
|
|
1446
|
+
if (!junction[y * W1 + x]) continue;
|
|
1447
|
+
for (let d = 0; d < 4; d++) while (has(x, y, d)) walk(x, y, d);
|
|
1448
|
+
}
|
|
1449
|
+
for (let y = 0; y <= h; y++) for (let x = 0; x < w; x++) if (hEdge[y * W1 + x]) walk(x, y, 0);
|
|
1450
|
+
for (let y = 0; y < h; y++) for (let x = 0; x <= w; x++) if (vEdge[y * W1 + x]) walk(x, y, 1);
|
|
1451
|
+
return chains;
|
|
1452
|
+
}
|
|
1453
|
+
function addOriented(map, id, c) {
|
|
1454
|
+
const list = map.get(id);
|
|
1455
|
+
if (list) list.push(c);
|
|
1456
|
+
else map.set(id, [c]);
|
|
1457
|
+
}
|
|
1458
|
+
const reverse = (cubics) => cubics.map(([a, b, c, d]) => [
|
|
1459
|
+
d,
|
|
1460
|
+
c,
|
|
1461
|
+
b,
|
|
1462
|
+
a
|
|
1463
|
+
]).reverse();
|
|
1464
|
+
/** Join a region's chains into closed loops, each walked with the region on its left. */
|
|
1465
|
+
function assemble(chains) {
|
|
1466
|
+
const subs = [];
|
|
1467
|
+
const open = [];
|
|
1468
|
+
for (const c of chains) if (c.closed) subs.push(toSubpath(c.cubics));
|
|
1469
|
+
else open.push(c);
|
|
1470
|
+
const start = (c) => c.reversed ? c.to : c.from;
|
|
1471
|
+
const end = (c) => c.reversed ? c.from : c.to;
|
|
1472
|
+
const firstDir = (c) => c.reversed ? neg(c.last) : c.first;
|
|
1473
|
+
const lastDir = (c) => c.reversed ? neg(c.first) : c.last;
|
|
1474
|
+
const byStart = /* @__PURE__ */ new Map();
|
|
1475
|
+
for (const c of open) {
|
|
1476
|
+
const k = start(c);
|
|
1477
|
+
const list = byStart.get(k);
|
|
1478
|
+
if (list) list.push(c);
|
|
1479
|
+
else byStart.set(k, [c]);
|
|
1480
|
+
}
|
|
1481
|
+
const used = /* @__PURE__ */ new Set();
|
|
1482
|
+
for (const first of open) {
|
|
1483
|
+
if (used.has(first)) continue;
|
|
1484
|
+
const loop = [];
|
|
1485
|
+
let c = first;
|
|
1486
|
+
while (c && !used.has(c)) {
|
|
1487
|
+
used.add(c);
|
|
1488
|
+
loop.push(...c.cubics);
|
|
1489
|
+
if (end(c) === start(first)) break;
|
|
1490
|
+
const into = lastDir(c);
|
|
1491
|
+
c = (byStart.get(end(c)) ?? []).filter((n) => !used.has(n)).sort((a, b) => cross(into, firstDir(a)) - cross(into, firstDir(b)))[0];
|
|
1492
|
+
}
|
|
1493
|
+
if (loop.length) subs.push(toSubpath(loop));
|
|
1494
|
+
}
|
|
1495
|
+
return subs;
|
|
1496
|
+
}
|
|
1497
|
+
const neg = (p) => ({
|
|
1498
|
+
x: -p.x,
|
|
1499
|
+
y: -p.y
|
|
1500
|
+
});
|
|
1501
|
+
/** y-down screen coordinates: negative is a left turn. */
|
|
1502
|
+
const cross = (a, b) => a.x * b.y - a.y * b.x;
|
|
1503
|
+
/** Cubics end to end → a closed subpath; straight ones carry no handles. Two decimals. */
|
|
1504
|
+
function toSubpath(cubics) {
|
|
1505
|
+
const r = (p) => ({
|
|
1506
|
+
x: Math.round(p.x * 100) / 100,
|
|
1507
|
+
y: Math.round(p.y * 100) / 100
|
|
1508
|
+
});
|
|
1509
|
+
const nodes = [];
|
|
1510
|
+
for (const c of cubics) {
|
|
1511
|
+
if (!nodes.length) nodes.push({
|
|
1512
|
+
...r(c[0]),
|
|
1513
|
+
in: null,
|
|
1514
|
+
out: null
|
|
1515
|
+
});
|
|
1516
|
+
const flat = isFlat(c);
|
|
1517
|
+
if (!flat) nodes[nodes.length - 1].out = r(c[1]);
|
|
1518
|
+
nodes.push({
|
|
1519
|
+
...r(c[3]),
|
|
1520
|
+
in: flat ? null : r(c[2]),
|
|
1521
|
+
out: null
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
if (nodes.length > 1) {
|
|
1525
|
+
const last = nodes.pop();
|
|
1526
|
+
nodes[0].in = last.in;
|
|
1527
|
+
}
|
|
1528
|
+
return {
|
|
1529
|
+
closed: true,
|
|
1530
|
+
nodes
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
//#endregion
|
|
1534
|
+
export { exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, serializePath, staircase, toSvg, trace, traceInlay };
|