inlaytrace 0.4.0 → 0.6.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 +19 -0
- package/README.md +5 -1
- package/bin/inlaytrace.mjs +3 -0
- package/dist/index.d.ts +99 -2
- package/dist/index.js +3019 -150
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -197,11 +197,11 @@ function close(sub) {
|
|
|
197
197
|
nodes.pop();
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
|
-
const num$
|
|
200
|
+
const num$2 = (n) => {
|
|
201
201
|
const r = Math.round(n * 1e3) / 1e3;
|
|
202
202
|
return Object.is(r, -0) ? "0" : String(r);
|
|
203
203
|
};
|
|
204
|
-
const pt = (p) => `${num$
|
|
204
|
+
const pt = (p) => `${num$2(p.x)} ${num$2(p.y)}`;
|
|
205
205
|
function segment(a, b) {
|
|
206
206
|
return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
|
|
207
207
|
}
|
|
@@ -235,9 +235,25 @@ function mapPoints(subs, f) {
|
|
|
235
235
|
/** How closely an outline must follow a shape: RMS and worst distance, in px, of its pixel-edge midpoints. */
|
|
236
236
|
const MAX_RMS$1 = .3;
|
|
237
237
|
const MAX_OFF = .85;
|
|
238
|
+
/**
|
|
239
|
+
* A candidate within these looser limits isn't taken on trust: it's drawn,
|
|
240
|
+
* and kept only if it's as close to the region as the free fit (#147). A
|
|
241
|
+
* small hexagon's pixel edges stray further from its true sides than a big
|
|
242
|
+
* one's, so the strict limits turned it down, and its free fit came out lumpy.
|
|
243
|
+
*/
|
|
244
|
+
const LOOSE_RMS = .5;
|
|
245
|
+
const LOOSE_OFF = 1.4;
|
|
246
|
+
const STRICT = {
|
|
247
|
+
rms: MAX_RMS$1,
|
|
248
|
+
off: MAX_OFF
|
|
249
|
+
};
|
|
250
|
+
const LOOSE = {
|
|
251
|
+
rms: LOOSE_RMS,
|
|
252
|
+
off: LOOSE_OFF
|
|
253
|
+
};
|
|
238
254
|
/** An ellipse whose axes differ by less than this is drawn as a circle. */
|
|
239
255
|
const ROUND = .015;
|
|
240
|
-
const KAPPA = .5522847498307936;
|
|
256
|
+
const KAPPA$1 = .5522847498307936;
|
|
241
257
|
/** Area, centroid and central second moments (per unit area) of a closed polygon. */
|
|
242
258
|
function moments(pts) {
|
|
243
259
|
let a = 0;
|
|
@@ -294,15 +310,15 @@ function midpoints(pts) {
|
|
|
294
310
|
}
|
|
295
311
|
return out;
|
|
296
312
|
}
|
|
297
|
-
/** Whether every point is close to a shape, given its distance function
|
|
298
|
-
function fits(points, distance) {
|
|
313
|
+
/** Whether every point is close to a shape, given its distance function: within `gate`. */
|
|
314
|
+
function fits(points, distance, gate) {
|
|
299
315
|
let sum = 0;
|
|
300
316
|
for (const p of points) {
|
|
301
317
|
const d = Math.abs(distance(p));
|
|
302
|
-
if (d >
|
|
318
|
+
if (d > gate.off) return false;
|
|
303
319
|
sum += d * d;
|
|
304
320
|
}
|
|
305
|
-
return Math.sqrt(sum / points.length) <=
|
|
321
|
+
return Math.sqrt(sum / points.length) <= gate.rms;
|
|
306
322
|
}
|
|
307
323
|
/** Into a frame centred on (cx, cy) and turned by `angle`. */
|
|
308
324
|
const local = (p, cx, cy, cos, sin) => {
|
|
@@ -338,8 +354,8 @@ function quarter(cx, cy, cos, sin, a, b, ox, oy, t) {
|
|
|
338
354
|
const p = (u, v) => world(ox + u, oy + v, cx, cy, cos, sin);
|
|
339
355
|
return [
|
|
340
356
|
p(a * c0, b * s0),
|
|
341
|
-
p(a * c0 - KAPPA * a * s0, b * s0 + KAPPA * b * c0),
|
|
342
|
-
p(a * c1 + KAPPA * a * s1, b * s1 - KAPPA * b * c1),
|
|
357
|
+
p(a * c0 - KAPPA$1 * a * s0, b * s0 + KAPPA$1 * b * c0),
|
|
358
|
+
p(a * c1 + KAPPA$1 * a * s1, b * s1 - KAPPA$1 * b * c1),
|
|
343
359
|
p(a * c1, b * s1)
|
|
344
360
|
];
|
|
345
361
|
}
|
|
@@ -355,19 +371,82 @@ const reversed = (cubics) => cubics.map(([a, b, c, d]) => [
|
|
|
355
371
|
* the same way round as the outline; otherwise null. `corners` are the corner
|
|
356
372
|
* points the fitter found on it (a polygon's vertices; usually none for a round shape).
|
|
357
373
|
*/
|
|
358
|
-
function fitShape(pts, corners) {
|
|
374
|
+
function fitShape(pts, corners, gate = "strict") {
|
|
359
375
|
const f = moments(pts);
|
|
360
376
|
if (!f) return null;
|
|
361
377
|
const mids = midpoints(pts);
|
|
362
378
|
const p = principal(f);
|
|
363
|
-
const
|
|
379
|
+
const g = gate === "loose" ? LOOSE : STRICT;
|
|
380
|
+
const shape = (corners.length >= 3 ? withCorners(f, corners, mids, g) : null) ?? roundShape(f, p, mids, g);
|
|
364
381
|
if (!shape) return null;
|
|
382
|
+
if (shape.kind === "circle" && f.area < Math.PI * POLYGON_MAX_R ** 2) {
|
|
383
|
+
const poly = regularByArea(f, pts);
|
|
384
|
+
if (poly && poly.apart < POLYGON_WINS * areaApart(circlePoints(shape.cubics), pts)) shape.kind = "polygon", shape.cubics = poly.vertices.map((a, i) => lineTo(a, poly.vertices[(i + 1) % poly.vertices.length]));
|
|
385
|
+
}
|
|
365
386
|
let area = 0;
|
|
366
387
|
for (let i = 0; i < pts.length; i++) area += pts[i].x * pts[(i + 1) % pts.length].y - pts[(i + 1) % pts.length].x * pts[i].y;
|
|
367
388
|
if (Math.sign(signedArea(shape.cubics)) !== Math.sign(area)) shape.cubics = reversed(shape.cubics);
|
|
368
389
|
return shape;
|
|
369
390
|
}
|
|
370
|
-
|
|
391
|
+
/** A polygon replaces a circle only if it's off the region by less than this share of the circle's area apart. */
|
|
392
|
+
const POLYGON_WINS = .6;
|
|
393
|
+
/**
|
|
394
|
+
* Past this radius (px) a polygon's corners are sharp enough for the fitter to
|
|
395
|
+
* find, so the search (which costs about R² per try) isn't needed.
|
|
396
|
+
*/
|
|
397
|
+
const POLYGON_MAX_R = 16;
|
|
398
|
+
const circlePoints = (cubics) => cubics.flatMap(([a, b, c, d]) => Array.from({ length: 16 }, (_, k) => {
|
|
399
|
+
const t = k / 16;
|
|
400
|
+
const u = 1 - t;
|
|
401
|
+
return {
|
|
402
|
+
x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
|
|
403
|
+
y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y
|
|
404
|
+
};
|
|
405
|
+
}));
|
|
406
|
+
/**
|
|
407
|
+
* The regular polygon (3 to 8 sides) of the region's area and centroid that
|
|
408
|
+
* covers it best, turned to fit by trying its angle in steps; and how far
|
|
409
|
+
* apart it is from the region, in px².
|
|
410
|
+
*/
|
|
411
|
+
function regularByArea(f, pts) {
|
|
412
|
+
let best = null;
|
|
413
|
+
for (let k = 3; k <= 8; k++) {
|
|
414
|
+
const step = 2 * Math.PI / k;
|
|
415
|
+
const R = Math.sqrt(2 * f.area / (k * Math.sin(step)));
|
|
416
|
+
if (R < 2.5) continue;
|
|
417
|
+
const at = (phase) => Array.from({ length: k }, (_, i) => ({
|
|
418
|
+
x: f.cx + R * Math.cos(phase + i * step),
|
|
419
|
+
y: f.cy + R * Math.sin(phase + i * step)
|
|
420
|
+
}));
|
|
421
|
+
let phase = 0;
|
|
422
|
+
let apart = 1e400;
|
|
423
|
+
for (const [from, span, n] of [[
|
|
424
|
+
0,
|
|
425
|
+
step,
|
|
426
|
+
24
|
|
427
|
+
], [
|
|
428
|
+
-step / 24,
|
|
429
|
+
step / 12,
|
|
430
|
+
12
|
|
431
|
+
]]) {
|
|
432
|
+
const base = phase;
|
|
433
|
+
for (let j = 0; j < n; j++) {
|
|
434
|
+
const t = (from === 0 ? 0 : base) + from + span * j / n;
|
|
435
|
+
const e = areaApart(at(t), pts);
|
|
436
|
+
if (e < apart) {
|
|
437
|
+
apart = e;
|
|
438
|
+
phase = t;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (!best || apart < best.apart) best = {
|
|
443
|
+
vertices: at(phase),
|
|
444
|
+
apart
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
return best;
|
|
448
|
+
}
|
|
449
|
+
function roundShape(f, p, mids, g) {
|
|
371
450
|
const cos = Math.cos(p.angle);
|
|
372
451
|
const sin = Math.sin(p.angle);
|
|
373
452
|
let a = 2 * Math.sqrt(Math.max(0, p.big));
|
|
@@ -381,7 +460,7 @@ function roundShape(f, p, mids) {
|
|
|
381
460
|
const g = 2 * Math.hypot(u / (a * a), v / (b * b));
|
|
382
461
|
return g > 1e-12 ? F / g : 1e400;
|
|
383
462
|
};
|
|
384
|
-
if (fits(mids, off)) {
|
|
463
|
+
if (fits(mids, off, g)) {
|
|
385
464
|
const cubics = [
|
|
386
465
|
0,
|
|
387
466
|
1,
|
|
@@ -411,7 +490,7 @@ function roundShape(f, p, mids) {
|
|
|
411
490
|
const qy = Math.abs(v) - (hh - r);
|
|
412
491
|
return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
|
|
413
492
|
};
|
|
414
|
-
if (!fits(mids, off)) return null;
|
|
493
|
+
if (!fits(mids, off, g)) return null;
|
|
415
494
|
const at = (u, v) => world(u, v, f.cx, f.cy, cos, sin);
|
|
416
495
|
const iw = hw - r;
|
|
417
496
|
const ih = hh - r;
|
|
@@ -448,7 +527,7 @@ function roundShape(f, p, mids) {
|
|
|
448
527
|
cubics
|
|
449
528
|
};
|
|
450
529
|
}
|
|
451
|
-
function withCorners(f, corners, mids) {
|
|
530
|
+
function withCorners(f, corners, mids, g) {
|
|
452
531
|
const k = corners.length;
|
|
453
532
|
if (k < 3 || k > 12) return null;
|
|
454
533
|
const angles = corners.map((c) => Math.atan2(c.y - f.cy, c.x - f.cx));
|
|
@@ -476,7 +555,7 @@ function withCorners(f, corners, mids) {
|
|
|
476
555
|
const qy = Math.abs(v) - hh;
|
|
477
556
|
return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0);
|
|
478
557
|
};
|
|
479
|
-
if (!fits(mids, off)) return null;
|
|
558
|
+
if (!fits(mids, off, g)) return null;
|
|
480
559
|
const c = [
|
|
481
560
|
world(hw, -hh, f.cx, f.cy, cos, sin),
|
|
482
561
|
world(hw, hh, f.cx, f.cy, cos, sin),
|
|
@@ -515,12 +594,48 @@ function withCorners(f, corners, mids) {
|
|
|
515
594
|
}
|
|
516
595
|
return best;
|
|
517
596
|
};
|
|
518
|
-
if (!fits(mids, off)) return null;
|
|
597
|
+
if (!fits(mids, off, g)) return null;
|
|
519
598
|
return {
|
|
520
599
|
kind: "polygon",
|
|
521
600
|
cubics: vertices.map((a, i) => lineTo(a, vertices[(i + 1) % k]))
|
|
522
601
|
};
|
|
523
602
|
}
|
|
603
|
+
/**
|
|
604
|
+
* The area, in px², where two closed outlines differ (one covers and the other
|
|
605
|
+
* doesn't): each scanned in rows a quarter of a pixel apart, by where its
|
|
606
|
+
* edges cross the row (even-odd). How well a fit draws a region, measured the
|
|
607
|
+
* way it will be seen.
|
|
608
|
+
*/
|
|
609
|
+
function areaApart(a, b) {
|
|
610
|
+
let y0 = 1e400;
|
|
611
|
+
let y1 = -1e400;
|
|
612
|
+
for (const p of [...a, ...b]) {
|
|
613
|
+
if (p.y < y0) y0 = p.y;
|
|
614
|
+
if (p.y > y1) y1 = p.y;
|
|
615
|
+
}
|
|
616
|
+
const ROWS = 4;
|
|
617
|
+
let sum = 0;
|
|
618
|
+
for (let y = Math.floor(y0 * ROWS) / ROWS + .5 / ROWS; y < y1; y += 1 / ROWS) {
|
|
619
|
+
const xs = [];
|
|
620
|
+
for (const [poly, w] of [[a, 1], [b, 2]]) for (let i = 0; i < poly.length; i++) {
|
|
621
|
+
const p = poly[i];
|
|
622
|
+
const q = poly[(i + 1) % poly.length];
|
|
623
|
+
if (p.y > y !== q.y > y) xs.push({
|
|
624
|
+
x: p.x + (y - p.y) * (q.x - p.x) / (q.y - p.y),
|
|
625
|
+
w
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
xs.sort((m, n) => m.x - n.x);
|
|
629
|
+
let inA = false;
|
|
630
|
+
let inB = false;
|
|
631
|
+
for (let k = 0; k < xs.length; k++) {
|
|
632
|
+
if (xs[k].w === 1) inA = !inA;
|
|
633
|
+
else inB = !inB;
|
|
634
|
+
if (inA !== inB && k + 1 < xs.length) sum += xs[k + 1].x - xs[k].x;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return sum / ROWS;
|
|
638
|
+
}
|
|
524
639
|
// src/fit.ts
|
|
525
640
|
const R = 6;
|
|
526
641
|
const END_TRIM = 3;
|
|
@@ -597,6 +712,10 @@ function loopArea(pts) {
|
|
|
597
712
|
}
|
|
598
713
|
return a / 2;
|
|
599
714
|
}
|
|
715
|
+
/** A shape within the loose limits is kept if it's off the region by no more than this share of the free fit's area apart. */
|
|
716
|
+
const LOOSE_WINS = .9;
|
|
717
|
+
/** A fitted loop as points: each line's start, sixteen along each curve. */
|
|
718
|
+
const dense = (cubics) => cubics.flatMap((c) => isFlat(c) ? [c[0]] : Array.from({ length: 16 }, (_, k) => pointAt(c, k / 16)));
|
|
600
719
|
/** A fitted loop as points, four along each cubic. */
|
|
601
720
|
const sampled = (cubics) => cubics.flatMap((c) => [
|
|
602
721
|
0,
|
|
@@ -618,8 +737,17 @@ function fitOnce(points, closed, o, smoothLoop, fine) {
|
|
|
618
737
|
if (!closed && n === 2) return [line(pts[0], pts[1])];
|
|
619
738
|
const corners = smoothLoop ? [] : findCorners(pts, closed, o.cornerAngle).filter((c) => closed || dist$2(c.at, pts[0]) >= MIN_GAP && dist$2(c.at, pts[n - 1]) >= MIN_GAP);
|
|
620
739
|
if (closed && o.shapes) {
|
|
621
|
-
const
|
|
740
|
+
const at = corners.map((c) => c.at);
|
|
741
|
+
const shape = fitShape(fine ?? points, at);
|
|
622
742
|
if (shape) return shape.cubics;
|
|
743
|
+
const loose = fitShape(fine ?? points, at, "loose");
|
|
744
|
+
if (loose) {
|
|
745
|
+
const free = fitOnce(points, closed, {
|
|
746
|
+
...o,
|
|
747
|
+
shapes: false
|
|
748
|
+
}, smoothLoop, fine);
|
|
749
|
+
return areaApart(dense(loose.cubics), fine ?? points) <= LOOSE_WINS * areaApart(dense(free), fine ?? points) ? loose.cubics : free;
|
|
750
|
+
}
|
|
623
751
|
}
|
|
624
752
|
if (closed && corners.length === 0) {
|
|
625
753
|
if (n < 4) return polygon(pts, true);
|
|
@@ -632,7 +760,7 @@ function fitOnce(points, closed, o, smoothLoop, fine) {
|
|
|
632
760
|
}
|
|
633
761
|
const run = smoothed.true;
|
|
634
762
|
const t = norm(sub$1(run[1], run[run.length - 2]));
|
|
635
|
-
const loop = flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
|
|
763
|
+
const loop = flatten$1(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
|
|
636
764
|
return o.snap === false ? loop : snapLines(loop, true);
|
|
637
765
|
}
|
|
638
766
|
const breaks = corners.map((c) => ({
|
|
@@ -665,10 +793,10 @@ function fitOnce(points, closed, o, smoothLoop, fine) {
|
|
|
665
793
|
run[run.length - 1] = to.at;
|
|
666
794
|
out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH$1), o.tolerance));
|
|
667
795
|
}
|
|
668
|
-
return o.snap === false ? flatten(out) : snapLines(flatten(out), closed);
|
|
796
|
+
return o.snap === false ? flatten$1(out) : snapLines(flatten$1(out), closed);
|
|
669
797
|
}
|
|
670
798
|
/** Straight runs written as exact lines, so they serialise as L, not C. */
|
|
671
|
-
function flatten(cubics) {
|
|
799
|
+
function flatten$1(cubics) {
|
|
672
800
|
return cubics.map((c) => isFlat(c) ? line(c[0], c[3]) : c);
|
|
673
801
|
}
|
|
674
802
|
/** Lines within this many degrees of horizontal, vertical or 45° are made exactly that... */
|
|
@@ -1337,13 +1465,15 @@ function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minD
|
|
|
1337
1465
|
if (picked.length >= maxColors) break;
|
|
1338
1466
|
const share = it.weight / opaque;
|
|
1339
1467
|
if (share < minDetail && picked.length > 0) break;
|
|
1340
|
-
if (!picked.every((p) => distance(p.lab, it.lab) >= minDistance)) continue;
|
|
1468
|
+
if (!picked.every((p) => distance$1(p.lab, it.lab) >= minDistance)) continue;
|
|
1341
1469
|
if ((share < minShare || flat !== null && share < EDGE_SHARE && it.flatWeight < EDGE_FLAT * it.weight) && isBlend(it.rgb, it.lab, picked, minDistance)) continue;
|
|
1342
1470
|
picked.push({
|
|
1343
1471
|
lab: it.lab,
|
|
1344
1472
|
rgb: it.rgb
|
|
1345
1473
|
});
|
|
1346
1474
|
}
|
|
1475
|
+
const inner = width ? Math.min(opaque, Math.max(0, width - 2) * Math.max(0, rgba.length / 4 / width - 2)) : 0;
|
|
1476
|
+
if (flat && flat.total >= FLAT_ART * inner && picked.length < maxColors) picked.push(...closeFills(flat, opaque, picked, maxColors - picked.length, minDistance / 2, Math.max(minShare, CLOSE_MIN_SHARE)));
|
|
1347
1477
|
if (flat && picked.length < maxColors) picked.push(...flatTints(flat, opaque, picked, maxColors - picked.length, minTint, minFlat));
|
|
1348
1478
|
return picked.map((p) => toHex(p.rgb));
|
|
1349
1479
|
}
|
|
@@ -1421,7 +1551,7 @@ function weigh(items, radius) {
|
|
|
1421
1551
|
}
|
|
1422
1552
|
for (const it of items) {
|
|
1423
1553
|
const [cl, ca, cb] = it.lab.map(cell);
|
|
1424
|
-
for (let i = cl - 1; i <= cl + 1; i++) for (let j = ca - 1; j <= ca + 1; j++) for (let k = cb - 1; k <= cb + 1; k++) for (const o of grid.get(`${i},${j},${k}`) ?? []) if (distance(o.lab, it.lab) <= radius) {
|
|
1554
|
+
for (let i = cl - 1; i <= cl + 1; i++) for (let j = ca - 1; j <= ca + 1; j++) for (let k = cb - 1; k <= cb + 1; k++) for (const o of grid.get(`${i},${j},${k}`) ?? []) if (distance$1(o.lab, it.lab) <= radius) {
|
|
1425
1555
|
it.weight += o.n;
|
|
1426
1556
|
it.flatWeight += o.flat;
|
|
1427
1557
|
if (o.n > it.n) it.peak = false;
|
|
@@ -1458,7 +1588,7 @@ function flatTints(flat, opaque, picked, room, minTint, minFlat) {
|
|
|
1458
1588
|
const tint = (it) => it.peak && it.lab[0] >= TINT_LIGHTNESS && it.weight >= minFlat * opaque;
|
|
1459
1589
|
for (const it of items.filter(tint).sort((a, b) => b.weight - a.weight)) {
|
|
1460
1590
|
if (out.length >= room) break;
|
|
1461
|
-
if ([...picked, ...out].every((p) => distance(p.lab, it.lab) >= minTint)) out.push({
|
|
1591
|
+
if ([...picked, ...out].every((p) => distance$1(p.lab, it.lab) >= minTint)) out.push({
|
|
1462
1592
|
lab: it.lab,
|
|
1463
1593
|
rgb: it.rgb
|
|
1464
1594
|
});
|
|
@@ -1466,6 +1596,113 @@ function flatTints(flat, opaque, picked, room, minTint, minFlat) {
|
|
|
1466
1596
|
return out;
|
|
1467
1597
|
}
|
|
1468
1598
|
/**
|
|
1599
|
+
* Close fills are for flat art: at least this share of its pixels flat. The
|
|
1600
|
+
* truck logo is 0.92 flat, the score's shaded fixture 0.96; photos are 0.52 to
|
|
1601
|
+
* 0.73, and there they only added shades, which grew Illustration's SVG of
|
|
1602
|
+
* them by up to half.
|
|
1603
|
+
*/
|
|
1604
|
+
const FLAT_ART = .8;
|
|
1605
|
+
/**
|
|
1606
|
+
* Close fills: flat colours left out because they sit within `minDistance` of
|
|
1607
|
+
* a picked one. A truck logo's neutral-grey grille bars and tyre treads were
|
|
1608
|
+
* 0.057 from its blue-grey cab, so they traced as the cab, flecked with navy
|
|
1609
|
+
* where their shading fell nearer that. Only flat pixels count, so
|
|
1610
|
+
* anti-aliased edges and JPEG ringing can't raise a colour here, and only
|
|
1611
|
+
* while there's room under the cap: clean art, whose fills are all picked
|
|
1612
|
+
* already, leaves nothing over.
|
|
1613
|
+
*
|
|
1614
|
+
* Each round weighs the flat pixels still more than `radius` from every
|
|
1615
|
+
* colour picked, and takes the mean of the heaviest spot (the pixels within
|
|
1616
|
+
* `radius` of one bin) if it covers `minShare` of the image. A smooth ramp (a
|
|
1617
|
+
* photo's dark shading) is flat too, and its in-between shades would only
|
|
1618
|
+
* band it into near-copies, so a spot on the line through two picked colours
|
|
1619
|
+
* near it is passed over (see inRamp): the truck's grey lies off to the side
|
|
1620
|
+
* of the cab's blue-grey, not on from it.
|
|
1621
|
+
*/
|
|
1622
|
+
const RAMP_SPAN = 6;
|
|
1623
|
+
/** A floor on a close fill's share, whatever minShare is: at 0, JPEG noise inside fills would fill the cap. */
|
|
1624
|
+
const CLOSE_MIN_SHARE = .001;
|
|
1625
|
+
const RAMP_TOLERANCE = .012;
|
|
1626
|
+
function closeFills(flat, opaque, picked, room, radius, minShare) {
|
|
1627
|
+
const bins = flat.keys.map((key) => {
|
|
1628
|
+
const rgb = flat.mean(key);
|
|
1629
|
+
return {
|
|
1630
|
+
key,
|
|
1631
|
+
n: flat.n[key],
|
|
1632
|
+
flat: 0,
|
|
1633
|
+
rgb,
|
|
1634
|
+
lab: oklab(rgb),
|
|
1635
|
+
weight: 0,
|
|
1636
|
+
flatWeight: 0,
|
|
1637
|
+
peak: true
|
|
1638
|
+
};
|
|
1639
|
+
});
|
|
1640
|
+
const out = [];
|
|
1641
|
+
const passed = /* @__PURE__ */ new Set();
|
|
1642
|
+
while (out.length < room) {
|
|
1643
|
+
const all = [...picked, ...out];
|
|
1644
|
+
const left = bins.filter((b) => !passed.has(b.key) && b.lab[0] < TINT_LIGHTNESS && all.every((p) => distance$1(p.lab, b.lab) > radius));
|
|
1645
|
+
for (const b of left) b.weight = 0;
|
|
1646
|
+
weigh(left, radius);
|
|
1647
|
+
let best;
|
|
1648
|
+
for (const b of left) if (!best || b.weight > best.weight) best = b;
|
|
1649
|
+
if (!best || best.weight < minShare * opaque) break;
|
|
1650
|
+
const spot = left.filter((o) => distance$1(o.lab, best.lab) <= radius);
|
|
1651
|
+
const sum = [
|
|
1652
|
+
0,
|
|
1653
|
+
0,
|
|
1654
|
+
0
|
|
1655
|
+
];
|
|
1656
|
+
let n = 0;
|
|
1657
|
+
for (const o of spot) {
|
|
1658
|
+
for (let k = 0; k < 3; k++) sum[k] += o.rgb[k] * o.n;
|
|
1659
|
+
n += o.n;
|
|
1660
|
+
}
|
|
1661
|
+
const rgb = [
|
|
1662
|
+
sum[0] / n,
|
|
1663
|
+
sum[1] / n,
|
|
1664
|
+
sum[2] / n
|
|
1665
|
+
];
|
|
1666
|
+
const lab = oklab(rgb);
|
|
1667
|
+
if (inRamp(rgb, lab, all, RAMP_TOLERANCE, RAMP_SPAN * radius) || !all.every((p) => distance$1(p.lab, lab) > radius)) for (const o of spot) passed.add(o.key);
|
|
1668
|
+
else out.push({
|
|
1669
|
+
rgb,
|
|
1670
|
+
lab
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
1673
|
+
return out;
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Whether a colour lies on the line through two picked colours that are within
|
|
1677
|
+
* `span` of it and of each other, between them or up to their spacing beyond
|
|
1678
|
+
* either (a ramp runs on past its last peak), within `tolerance`. A gradient's
|
|
1679
|
+
* shades sit on that line almost exactly (0.002 on the score's shaded fixture);
|
|
1680
|
+
* the truck's grey was 0.021 off it.
|
|
1681
|
+
*/
|
|
1682
|
+
function inRamp(rgb, lab, picked, tolerance, span) {
|
|
1683
|
+
const near = picked.filter((p) => distance$1(p.lab, lab) <= span);
|
|
1684
|
+
for (let i = 0; i < near.length; i++) for (let j = i + 1; j < near.length; j++) {
|
|
1685
|
+
const a = near[i].rgb;
|
|
1686
|
+
const b = near[j].rgb;
|
|
1687
|
+
if (distance$1(near[i].lab, near[j].lab) > span) continue;
|
|
1688
|
+
const d = [
|
|
1689
|
+
b[0] - a[0],
|
|
1690
|
+
b[1] - a[1],
|
|
1691
|
+
b[2] - a[2]
|
|
1692
|
+
];
|
|
1693
|
+
const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
|
1694
|
+
if (!len) continue;
|
|
1695
|
+
const t = Math.min(2, Math.max(-1, ((rgb[0] - a[0]) * d[0] + (rgb[1] - a[1]) * d[1] + (rgb[2] - a[2]) * d[2]) / len));
|
|
1696
|
+
const mix = [
|
|
1697
|
+
0,
|
|
1698
|
+
1,
|
|
1699
|
+
2
|
|
1700
|
+
].map((k) => Math.min(255, Math.max(0, a[k] + t * d[k])));
|
|
1701
|
+
if (distance$1(oklab(mix), lab) < tolerance) return true;
|
|
1702
|
+
}
|
|
1703
|
+
return false;
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1469
1706
|
* Whether a colour lies near the line between two picked colours, mixed as a
|
|
1470
1707
|
* renderer mixes them (in sRGB): the nearest mix is within `tolerance` (OKLab).
|
|
1471
1708
|
*/
|
|
@@ -1481,7 +1718,7 @@ function isBlend(rgb, lab, picked, tolerance) {
|
|
|
1481
1718
|
const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
|
1482
1719
|
if (!len) continue;
|
|
1483
1720
|
const t = Math.min(1, Math.max(0, ((rgb[0] - a[0]) * d[0] + (rgb[1] - a[1]) * d[1] + (rgb[2] - a[2]) * d[2]) / len));
|
|
1484
|
-
if (distance(oklab([
|
|
1721
|
+
if (distance$1(oklab([
|
|
1485
1722
|
a[0] + t * d[0],
|
|
1486
1723
|
a[1] + t * d[1],
|
|
1487
1724
|
a[2] + t * d[2]
|
|
@@ -1643,7 +1880,7 @@ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
|
|
|
1643
1880
|
return [...new Set(hexes)];
|
|
1644
1881
|
}
|
|
1645
1882
|
const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
|
|
1646
|
-
const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
1883
|
+
const distance$1 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
1647
1884
|
const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
|
|
1648
1885
|
/**
|
|
1649
1886
|
* Pixel art's palette: its colours exactly, most-used first. Pixel art has a
|
|
@@ -1806,7 +2043,7 @@ function spanned(c, pts) {
|
|
|
1806
2043
|
return 2 * Math.PI - gap;
|
|
1807
2044
|
}
|
|
1808
2045
|
/** Points along cubics, about a pixel apart. */
|
|
1809
|
-
function sample(cubics) {
|
|
2046
|
+
function sample$1(cubics) {
|
|
1810
2047
|
const out = [];
|
|
1811
2048
|
for (const c of cubics) {
|
|
1812
2049
|
const n = Math.max(2, Math.ceil(dist$1(c[0], c[1]) + dist$1(c[1], c[2]) + dist$1(c[2], c[3])));
|
|
@@ -1864,7 +2101,7 @@ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
|
|
|
1864
2101
|
]]);
|
|
1865
2102
|
for (const c of candidates) {
|
|
1866
2103
|
if (!c) continue;
|
|
1867
|
-
const pts = sample(c);
|
|
2104
|
+
const pts = sample$1(c);
|
|
1868
2105
|
let out = 0;
|
|
1869
2106
|
for (const p of pts) if (!hidden(p)) out++;
|
|
1870
2107
|
if (out <= STRAY * pts.length) return c;
|
|
@@ -2369,7 +2606,7 @@ function refitJunctions(chains, width) {
|
|
|
2369
2606
|
});
|
|
2370
2607
|
}
|
|
2371
2608
|
/** A chain turns this much (radians) across a corner before it's redrawn as one: 60°. */
|
|
2372
|
-
const CORNER_TURN = Math.PI / 3;
|
|
2609
|
+
const CORNER_TURN$1 = Math.PI / 3;
|
|
2373
2610
|
/**
|
|
2374
2611
|
* Sharp corners drawn sharp. Thinning a stroke that turns sharply cuts the
|
|
2375
2612
|
* corner: the skeleton turns inside it, short of the point by up to a few
|
|
@@ -2424,7 +2661,7 @@ function refitCorners(c, width, ink, w, h) {
|
|
|
2424
2661
|
const qa = at(s[i] + cut);
|
|
2425
2662
|
const d2 = unit(qa, at(s[i] + cut + reach));
|
|
2426
2663
|
const turn = Math.acos(Math.max(-1, Math.min(1, d1.x * d2.x + d1.y * d2.y)));
|
|
2427
|
-
if (turn < CORNER_TURN) continue;
|
|
2664
|
+
if (turn < CORNER_TURN$1) continue;
|
|
2428
2665
|
const det = d1.x * -d2.y - d1.y * -d2.x;
|
|
2429
2666
|
if (Math.abs(det) < 1e-6) continue;
|
|
2430
2667
|
const u = ((qa.x - pa.x) * -d2.y - (qa.y - pa.y) * -d2.x) / det;
|
|
@@ -2636,8 +2873,7 @@ const MAX_STOPS = 5;
|
|
|
2636
2873
|
* region's flat colour.
|
|
2637
2874
|
*/
|
|
2638
2875
|
function shadings(rgba, w, h, comp, regions, colorOf) {
|
|
2639
|
-
const step =
|
|
2640
|
-
const count = /* @__PURE__ */ new Map();
|
|
2876
|
+
const { step, count } = steps(rgba, w, h, comp, regions);
|
|
2641
2877
|
const rgb = (i) => [
|
|
2642
2878
|
rgba[i * 4],
|
|
2643
2879
|
rgba[i * 4 + 1],
|
|
@@ -2645,21 +2881,6 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
|
|
|
2645
2881
|
];
|
|
2646
2882
|
const d3 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
2647
2883
|
const colors = Array.from({ length: regions }, (_, id) => colorOf(id));
|
|
2648
|
-
const crack = (a, b, before, after) => {
|
|
2649
|
-
const ca = comp[a];
|
|
2650
|
-
const cb = comp[b];
|
|
2651
|
-
if (ca < 0 || cb < 0 || ca === cb) return;
|
|
2652
|
-
const key = Math.min(ca, cb) * regions + Math.max(ca, cb);
|
|
2653
|
-
const p = before * 4;
|
|
2654
|
-
const q = after * 4;
|
|
2655
|
-
step.set(key, (step.get(key) ?? 0) + Math.hypot(rgba[p] - rgba[q], rgba[p + 1] - rgba[q + 1], rgba[p + 2] - rgba[q + 2]));
|
|
2656
|
-
count.set(key, (count.get(key) ?? 0) + 1);
|
|
2657
|
-
};
|
|
2658
|
-
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
2659
|
-
const i = y * w + x;
|
|
2660
|
-
if (x + 1 < w) crack(i, i + 1, y * w + Math.max(0, x - SPAN), y * w + Math.min(w - 1, x + 1 + SPAN));
|
|
2661
|
-
if (y + 1 < h) crack(i, i + w, Math.max(0, y - SPAN) * w + x, Math.min(h - 1, y + 1 + SPAN) * w + x);
|
|
2662
|
-
}
|
|
2663
2884
|
const parent = Array.from({ length: regions }, (_, i) => i);
|
|
2664
2885
|
const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i]);
|
|
2665
2886
|
for (const [key, n] of count) {
|
|
@@ -2783,6 +3004,101 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
|
|
|
2783
3004
|
return out;
|
|
2784
3005
|
}
|
|
2785
3006
|
/**
|
|
3007
|
+
* Per pair of touching regions (key `min * regions + max`): how many cracks
|
|
3008
|
+
* they share, and the image's summed step across them, measured between the
|
|
3009
|
+
* pixels SPAN either side of each crack.
|
|
3010
|
+
*/
|
|
3011
|
+
function steps(rgba, w, h, comp, regions, limit) {
|
|
3012
|
+
const step = /* @__PURE__ */ new Map();
|
|
3013
|
+
const count = /* @__PURE__ */ new Map();
|
|
3014
|
+
const soft = /* @__PURE__ */ new Map();
|
|
3015
|
+
const crack = (a, b, before, after) => {
|
|
3016
|
+
const ca = comp[a];
|
|
3017
|
+
const cb = comp[b];
|
|
3018
|
+
if (ca < 0 || cb < 0 || ca === cb) return;
|
|
3019
|
+
const key = Math.min(ca, cb) * regions + Math.max(ca, cb);
|
|
3020
|
+
const p = before * 4;
|
|
3021
|
+
const q = after * 4;
|
|
3022
|
+
const s = Math.hypot(rgba[p] - rgba[q], rgba[p + 1] - rgba[q + 1], rgba[p + 2] - rgba[q + 2]);
|
|
3023
|
+
step.set(key, (step.get(key) ?? 0) + s);
|
|
3024
|
+
count.set(key, (count.get(key) ?? 0) + 1);
|
|
3025
|
+
if (limit && Math.max(s, Math.hypot(rgba[a * 4] - rgba[b * 4], rgba[a * 4 + 1] - rgba[b * 4 + 1], rgba[a * 4 + 2] - rgba[b * 4 + 2])) < limit(ca, cb)) soft.set(key, (soft.get(key) ?? 0) + 1);
|
|
3026
|
+
};
|
|
3027
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
3028
|
+
const i = y * w + x;
|
|
3029
|
+
if (x + 1 < w) crack(i, i + 1, y * w + Math.max(0, x - SPAN), y * w + Math.min(w - 1, x + 1 + SPAN));
|
|
3030
|
+
if (y + 1 < h) crack(i, i + w, Math.max(0, y - SPAN) * w + x, Math.min(h - 1, y + 1 + SPAN) * w + x);
|
|
3031
|
+
}
|
|
3032
|
+
return {
|
|
3033
|
+
step,
|
|
3034
|
+
count,
|
|
3035
|
+
soft
|
|
3036
|
+
};
|
|
3037
|
+
}
|
|
3038
|
+
/** Colours this close (OKLab) are one colour's faint shading when the image passes softly from one to the other. */
|
|
3039
|
+
const FAINT = .07;
|
|
3040
|
+
/** …and the shades a faint run joins stay within this of each other. */
|
|
3041
|
+
const FAINT_SPREAD = .1;
|
|
3042
|
+
/** A faint boundary is softer than a soft one: the image steps by less than this share of the two colours' difference, with no floor for noise. */
|
|
3043
|
+
const FAINT_SOFT = .4;
|
|
3044
|
+
/** …across at least this share of their boundary: the rest can run beside an edge (a halo along a shape's outline). */
|
|
3045
|
+
const FAINT_SHARE = .5;
|
|
3046
|
+
/**
|
|
3047
|
+
* Faint shading: neighbouring regions in close colours (within FAINT in
|
|
3048
|
+
* OKLab) that the image passes between without an edge, as a palette bands a
|
|
3049
|
+
* barely-there gradient in a background. Each run of them becomes one region
|
|
3050
|
+
* in its commonest colour. Returned as each region's new colour index, or -1.
|
|
3051
|
+
*
|
|
3052
|
+
* Unlike `shadings`, a boundary is faint only when its step is a small share
|
|
3053
|
+
* of the colours' difference itself: a pale fill on white is as close in
|
|
3054
|
+
* colour, and its edge steps by about the whole difference.
|
|
3055
|
+
*/
|
|
3056
|
+
function faintShades(rgba, w, h, comp, regions, labelOf, rgbs, areaOf, skip) {
|
|
3057
|
+
const into = new Int32Array(regions).fill(-1);
|
|
3058
|
+
const labs = rgbs.map((c) => c ? oklab(c) : null);
|
|
3059
|
+
const parent = Array.from({ length: regions }, (_, i) => i);
|
|
3060
|
+
const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i]);
|
|
3061
|
+
const d = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
3062
|
+
const close = (a, b) => {
|
|
3063
|
+
const la = labelOf(a);
|
|
3064
|
+
const lb = labelOf(b);
|
|
3065
|
+
return la !== lb && !!labs[la] && !!labs[lb] && !skip(a) && !skip(b) && d(labs[la], labs[lb]) <= FAINT;
|
|
3066
|
+
};
|
|
3067
|
+
const { count, soft } = steps(rgba, w, h, comp, regions, (a, b) => close(a, b) ? FAINT_SOFT * d(rgbs[labelOf(a)], rgbs[labelOf(b)]) : -1);
|
|
3068
|
+
for (const [key, n] of count) {
|
|
3069
|
+
const a = Math.floor(key / regions);
|
|
3070
|
+
const b = key % regions;
|
|
3071
|
+
const k = soft.get(key) ?? 0;
|
|
3072
|
+
if (k < SOFT_MIN || k < FAINT_SHARE * n) continue;
|
|
3073
|
+
parent[find(a)] = find(b);
|
|
3074
|
+
}
|
|
3075
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3076
|
+
for (let id = 0; id < regions; id++) {
|
|
3077
|
+
const r = find(id);
|
|
3078
|
+
const g = groups.get(r);
|
|
3079
|
+
if (g) g.push(id);
|
|
3080
|
+
else groups.set(r, [id]);
|
|
3081
|
+
}
|
|
3082
|
+
for (const ids of groups.values()) {
|
|
3083
|
+
if (ids.length < 2) continue;
|
|
3084
|
+
const shades = [...new Set(ids.map(labelOf))];
|
|
3085
|
+
if (shades.length < 2) continue;
|
|
3086
|
+
if (spread(shades.map((l) => rgbs[l])) > FAINT_SPREAD) continue;
|
|
3087
|
+
const area = /* @__PURE__ */ new Map();
|
|
3088
|
+
for (const id of ids) area.set(labelOf(id), (area.get(labelOf(id)) ?? 0) + areaOf(id));
|
|
3089
|
+
const main = [...area].reduce((a, b) => b[1] > a[1] ? b : a)[0];
|
|
3090
|
+
for (const id of ids) into[id] = main;
|
|
3091
|
+
}
|
|
3092
|
+
return into;
|
|
3093
|
+
}
|
|
3094
|
+
/** The widest OKLab distance between any two of these colours. */
|
|
3095
|
+
function spread(rgbs) {
|
|
3096
|
+
const labs = [...new Map(rgbs.map((c) => [toHex(c), c])).values()].map(oklab);
|
|
3097
|
+
let most = 0;
|
|
3098
|
+
for (const a of labs) for (const b of labs) most = Math.max(most, Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]));
|
|
3099
|
+
return most;
|
|
3100
|
+
}
|
|
3101
|
+
/**
|
|
2786
3102
|
* Whether the gradient draws any one band of the shade worse than the band's
|
|
2787
3103
|
* own flat colour did: a gradient that suits the whole on average can still
|
|
2788
3104
|
* paint one member (a shirt's fold shadow, a strand of hair) the wrong colour.
|
|
@@ -3153,7 +3469,7 @@ function closeGaps(ink, w, h, o = {}) {
|
|
|
3153
3469
|
const ends = endsOf(skel, ink, w, h, width);
|
|
3154
3470
|
if (!ends.length) return 0;
|
|
3155
3471
|
const reachOf = (e) => Math.min(GAP_MAX * k, Math.max(GAP_MIN * k, GAP_WIDTHS * e.width));
|
|
3156
|
-
const cross = (ax, ay, bx, by) => crossing(ink, o.blocked, w, h, ax, ay, bx, by);
|
|
3472
|
+
const cross = (ax, ay, bx, by) => crossing$1(ink, o.blocked, w, h, ax, ay, bx, by);
|
|
3157
3473
|
const joins = [];
|
|
3158
3474
|
let widest = 0;
|
|
3159
3475
|
for (const e of ends) widest = Math.max(widest, e.width);
|
|
@@ -3295,7 +3611,7 @@ function radiusAt(ink, w, h, x, y, max) {
|
|
|
3295
3611
|
* ink; 0 when it never leaves the ink; -1 when it crosses more than one gap
|
|
3296
3612
|
* (another line in between) or ends on paper.
|
|
3297
3613
|
*/
|
|
3298
|
-
function crossing(ink, blocked, w, h, ax, ay, bx, by) {
|
|
3614
|
+
function crossing$1(ink, blocked, w, h, ax, ay, bx, by) {
|
|
3299
3615
|
const d = Math.hypot(bx - ax, by - ay);
|
|
3300
3616
|
const steps = Math.max(1, Math.ceil(d * 2));
|
|
3301
3617
|
let state = 0;
|
|
@@ -3412,7 +3728,7 @@ function toSvg(r) {
|
|
|
3412
3728
|
const head = defs.length ? `<defs>\n${defs.join("\n")}\n</defs>\n` : "";
|
|
3413
3729
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${attr(r.width)}" height="${attr(r.height)}" viewBox="0 0 ${attr(r.width)} ${attr(r.height)}">\n${head}${body}\n</svg>\n`;
|
|
3414
3730
|
}
|
|
3415
|
-
const num = (v) => String(Math.round(v * 100) / 100);
|
|
3731
|
+
const num$1 = (v) => String(Math.round(v * 100) / 100);
|
|
3416
3732
|
/** A short hash (FNV-1a, base 36). */
|
|
3417
3733
|
function fnv(s) {
|
|
3418
3734
|
let h = 2166136261;
|
|
@@ -3421,17 +3737,39 @@ function fnv(s) {
|
|
|
3421
3737
|
}
|
|
3422
3738
|
/** A gradient element, in the drawing's pixels. */
|
|
3423
3739
|
function gradientMarkup(g, id) {
|
|
3424
|
-
const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
|
|
3425
|
-
return g.type === "linear" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${num(g.x1)}" y1="${num(g.y1)}" x2="${num(g.x2)}" y2="${num(g.y2)}">${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${num(g.cx)}" cy="${num(g.cy)}" r="${num(g.r)}">${stops}</radialGradient>`;
|
|
3740
|
+
const stops = g.stops.map((s) => `<stop offset="${num$1(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
|
|
3741
|
+
return g.type === "linear" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${num$1(g.x1)}" y1="${num$1(g.y1)}" x2="${num$1(g.x2)}" y2="${num$1(g.y2)}">${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${num$1(g.cx)}" cy="${num$1(g.cy)}" r="${num$1(g.r)}">${stops}</radialGradient>`;
|
|
3426
3742
|
}
|
|
3427
3743
|
/**
|
|
3428
3744
|
* Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
|
|
3429
3745
|
* into filled shapes that share their edges exactly.
|
|
3430
3746
|
*/
|
|
3431
3747
|
function traceRaw(rgba, w, h, o) {
|
|
3748
|
+
return run(traceSteps(rgba, w, h, o));
|
|
3749
|
+
}
|
|
3750
|
+
/** Fitting, the longest stage, pauses after this many edges. */
|
|
3751
|
+
const FIT_STEP = 256;
|
|
3752
|
+
/** A trace's steps run straight through, as the synchronous `trace` does. */
|
|
3753
|
+
function run(steps) {
|
|
3754
|
+
for (;;) {
|
|
3755
|
+
const r = steps.next();
|
|
3756
|
+
if (r.done) return r.value;
|
|
3757
|
+
}
|
|
3758
|
+
}
|
|
3759
|
+
/** `traceRaw` as steps, pausing between stages (and every so many edges while fitting), so an async caller can report progress or stop. */
|
|
3760
|
+
function* traceSteps(rgba, w, h, o) {
|
|
3761
|
+
yield {
|
|
3762
|
+
stage: "label",
|
|
3763
|
+
done: 0
|
|
3764
|
+
};
|
|
3432
3765
|
const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette, !o.photo) : labelBinary(rgba, w, h, o.threshold);
|
|
3433
3766
|
const clean = o.mode === "palette" && !o.pixels && !o.photo && lossless(rgba, labels, w, h, colors);
|
|
3434
3767
|
if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
|
|
3768
|
+
if (o.mode === "palette" && !o.photo && !o.pixels) settleClosePairs(labels, rgba, w, h, colors, o.lines);
|
|
3769
|
+
yield {
|
|
3770
|
+
stage: "clean",
|
|
3771
|
+
done: 0
|
|
3772
|
+
};
|
|
3435
3773
|
if (!o.pixels) despur(labels, w, h);
|
|
3436
3774
|
if (!o.pixels && !(o.mode === "palette" && o.photo)) joinDiagonals(labels, w, h, rgba, drawn);
|
|
3437
3775
|
const labs = o.mode === "palette" && !o.photo ? colors.map((c) => c ? oklab(hexToRgb(c)) : null) : void 0;
|
|
@@ -3439,6 +3777,10 @@ function traceRaw(rgba, w, h, o) {
|
|
|
3439
3777
|
if (o.mode === "binary" && o.closeGaps && closeInkGaps(labels, w, h, o.scale)) mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
|
|
3440
3778
|
if (labs && !o.pixels) mergeSlivers(labels, w, h, labs, o.lines);
|
|
3441
3779
|
const lines = o.mode === "palette" && o.strokes && labs && !o.pixels ? strokesOf(rgba, labels, w, h, colors, labs, drawn, o) : [];
|
|
3780
|
+
yield {
|
|
3781
|
+
stage: "regions",
|
|
3782
|
+
done: 0
|
|
3783
|
+
};
|
|
3442
3784
|
let { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
|
|
3443
3785
|
const gradientOf = /* @__PURE__ */ new Map();
|
|
3444
3786
|
if (o.gradients && o.mode === "palette" && !o.pixels) {
|
|
@@ -3456,12 +3798,34 @@ function traceRaw(rgba, w, h, o) {
|
|
|
3456
3798
|
({comp, compLabel, compArea} = components(labels, w, h, (l) => drawn[l]));
|
|
3457
3799
|
}
|
|
3458
3800
|
}
|
|
3801
|
+
let faintPx = null;
|
|
3802
|
+
if (o.mode === "palette" && !o.pixels && !o.photo && o.faint !== false) {
|
|
3803
|
+
const rgbs = colors.map((c, l) => c && drawn[l] && !gradientOf.has(l) ? hexToRgb(c) : null);
|
|
3804
|
+
const into = faintShades(rgba, w, h, comp, compLabel.length, (id) => compLabel[id], rgbs, (id) => compArea[id], (id) => gradientOf.has(compLabel[id]));
|
|
3805
|
+
if (into.some((l) => l >= 0)) {
|
|
3806
|
+
faintPx = new Uint8Array(labels.length);
|
|
3807
|
+
for (let i = 0; i < labels.length; i++) if (comp[i] !== VOID && into[comp[i]] >= 0) {
|
|
3808
|
+
labels[i] = into[comp[i]];
|
|
3809
|
+
faintPx[i] = 1;
|
|
3810
|
+
}
|
|
3811
|
+
({comp, compLabel, compArea} = components(labels, w, h, (l) => drawn[l]));
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
const faintRegion = new Uint8Array(compLabel.length);
|
|
3815
|
+
if (faintPx) {
|
|
3816
|
+
for (let i = 0; i < faintPx.length; i++) if (faintPx[i] && comp[i] !== VOID) faintRegion[comp[i]] = 1;
|
|
3817
|
+
}
|
|
3459
3818
|
const chains = findChains(comp, w, h);
|
|
3460
3819
|
const rgbOf = clean ? (id) => hexToRgb(colors[compLabel[id]]) : null;
|
|
3461
|
-
const flatSides = (c) => !gradientOf.has(compLabel[c.left]) && !gradientOf.has(compLabel[c.right]);
|
|
3820
|
+
const flatSides = (c) => !gradientOf.has(compLabel[c.left]) && !gradientOf.has(compLabel[c.right]) && !(c.left !== VOID && faintRegion[c.left]) && !(c.right !== VOID && faintRegion[c.right]);
|
|
3462
3821
|
const fitted = [];
|
|
3463
3822
|
const chainsOf = /* @__PURE__ */ new Map();
|
|
3464
|
-
for (
|
|
3823
|
+
for (let k = 0; k < chains.length; k++) {
|
|
3824
|
+
if (k % FIT_STEP === 0) yield {
|
|
3825
|
+
stage: "fit",
|
|
3826
|
+
done: k / chains.length
|
|
3827
|
+
};
|
|
3828
|
+
const c = chains[k];
|
|
3465
3829
|
const cubics = o.pixels ? staircase(c.pts, c.closed) : fitChain(c.pts, c.closed, o, rgbOf && flatSides(c) ? edgePoints(c, comp, w, rgba, rgbOf) : void 0);
|
|
3466
3830
|
if (!cubics.length) continue;
|
|
3467
3831
|
const i = fitted.push({
|
|
@@ -3493,6 +3857,10 @@ function traceRaw(rgba, w, h, o) {
|
|
|
3493
3857
|
}
|
|
3494
3858
|
return assemble(out);
|
|
3495
3859
|
};
|
|
3860
|
+
yield {
|
|
3861
|
+
stage: "shapes",
|
|
3862
|
+
done: 0
|
|
3863
|
+
};
|
|
3496
3864
|
const shapes = [];
|
|
3497
3865
|
const paint = (id) => ({
|
|
3498
3866
|
fill: colors[compLabel[id]],
|
|
@@ -3661,7 +4029,7 @@ function completeLoop(l, id, inFront, under) {
|
|
|
3661
4029
|
const hiddenAt = cs.map((c) => across(c) !== VOID && inFront(across(c), id));
|
|
3662
4030
|
const start = hiddenAt.indexOf(false);
|
|
3663
4031
|
if (start < 0 || !hiddenAt.some(Boolean)) return l.sub;
|
|
3664
|
-
const visible = sample(cs.filter((_, k) => !hiddenAt[k]).flatMap((c) => c.cubics));
|
|
4032
|
+
const visible = sample$1(cs.filter((_, k) => !hiddenAt[k]).flatMap((c) => c.cubics));
|
|
3665
4033
|
const out = [];
|
|
3666
4034
|
const joins = /* @__PURE__ */ new Set();
|
|
3667
4035
|
let changed = false;
|
|
@@ -3684,7 +4052,7 @@ function completeLoop(l, id, inFront, under) {
|
|
|
3684
4052
|
const p1 = last[last.length - 1][3];
|
|
3685
4053
|
const front = under(id, new Set(run.map(across)));
|
|
3686
4054
|
let fill = t0 && t1 && front ? complete(p0, t0, p1, t1, visible, straightEnd(prev.cubics, true), straightEnd(next.cubics, false), front.hidden) : null;
|
|
3687
|
-
if (fill && front.covered([...sample(fill), ...sample(run.flatMap((c) => c.cubics)).reverse()]) < COVERED) fill = null;
|
|
4055
|
+
if (fill && front.covered([...sample$1(fill), ...sample$1(run.flatMap((c) => c.cubics)).reverse()]) < COVERED) fill = null;
|
|
3688
4056
|
if (fill) {
|
|
3689
4057
|
joins.add(out.length);
|
|
3690
4058
|
out.push(...fill);
|
|
@@ -4234,6 +4602,58 @@ const NEIGHBOURS = [
|
|
|
4234
4602
|
[0, 1],
|
|
4235
4603
|
[1, 1]
|
|
4236
4604
|
];
|
|
4605
|
+
/** Two palette colours closer than this (OKLab) can split one shade between them, pixel by pixel. */
|
|
4606
|
+
const CLOSE_PAIR = .07;
|
|
4607
|
+
/** Pale pairs are a fill and its paper, which meet along a clean edge: left alone. */
|
|
4608
|
+
const CLOSE_PALE = .85;
|
|
4609
|
+
/** Edges between the two colours, per pixel of the rarer one, past which a region is speckled with both, not two fills side by side. */
|
|
4610
|
+
const INTERLEAVED = .1;
|
|
4611
|
+
/**
|
|
4612
|
+
* A shade between two close palette colours goes one way, for the whole
|
|
4613
|
+
* region it fills, not pixel by pixel. A truck's bumper (#4e5057) lay between
|
|
4614
|
+
* its blue-grey cab and its neutral-grey bars, 0.03 from each, and noise
|
|
4615
|
+
* flipped it from one to the other in blotches. Each region of the two
|
|
4616
|
+
* colours together, when it is blotched with both (more than INTERLEAVED
|
|
4617
|
+
* edges between them per pixel of the rarer), takes whichever is nearer its
|
|
4618
|
+
* mean colour. Two fills that meet along a clean edge are left as they are,
|
|
4619
|
+
* and so are painted lines marked by keepOutlines.
|
|
4620
|
+
*/
|
|
4621
|
+
function settleClosePairs(labels, rgba, w, h, colors, lines) {
|
|
4622
|
+
const labs = colors.map((c) => c ? oklab(hexToRgb(c)) : null);
|
|
4623
|
+
const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
4624
|
+
for (let a = 0; a < colors.length; a++) for (let b = a + 1; b < colors.length; b++) {
|
|
4625
|
+
const la = labs[a];
|
|
4626
|
+
const lb = labs[b];
|
|
4627
|
+
if (!la || !lb || dist(la, lb) >= CLOSE_PAIR || la[0] >= CLOSE_PALE || lb[0] >= CLOSE_PALE) continue;
|
|
4628
|
+
const { comp, compLabel } = components(Int32Array.from(labels, (l, i) => lines?.[i] ? -1 : l === b ? a : l), w, h, (l) => l === a);
|
|
4629
|
+
const n = compLabel.length;
|
|
4630
|
+
const na = new Float64Array(n);
|
|
4631
|
+
const nb = new Float64Array(n);
|
|
4632
|
+
const edges = new Float64Array(n);
|
|
4633
|
+
const sum = new Float64Array(n * 3);
|
|
4634
|
+
for (let i = 0, x = 0; i < labels.length; i++, x = x === w - 1 ? 0 : x + 1) {
|
|
4635
|
+
const id = comp[i];
|
|
4636
|
+
if (id === VOID) continue;
|
|
4637
|
+
if (labels[i] === a) na[id]++;
|
|
4638
|
+
else nb[id]++;
|
|
4639
|
+
for (let k = 0; k < 3; k++) sum[id * 3 + k] += rgba[i * 4 + k];
|
|
4640
|
+
if (x < w - 1 && comp[i + 1] === id && labels[i + 1] !== labels[i]) edges[id]++;
|
|
4641
|
+
if (i + w < labels.length && comp[i + w] === id && labels[i + w] !== labels[i]) edges[id]++;
|
|
4642
|
+
}
|
|
4643
|
+
const to = new Int32Array(n).fill(-1);
|
|
4644
|
+
for (let id = 0; id < n; id++) {
|
|
4645
|
+
if (!na[id] || !nb[id] || edges[id] <= INTERLEAVED * Math.min(na[id], nb[id])) continue;
|
|
4646
|
+
const t = na[id] + nb[id];
|
|
4647
|
+
const mean = oklab([
|
|
4648
|
+
sum[id * 3] / t,
|
|
4649
|
+
sum[id * 3 + 1] / t,
|
|
4650
|
+
sum[id * 3 + 2] / t
|
|
4651
|
+
]);
|
|
4652
|
+
to[id] = dist(mean, la) <= dist(mean, lb) ? a : b;
|
|
4653
|
+
}
|
|
4654
|
+
for (let i = 0; i < labels.length; i++) if (comp[i] !== VOID && to[comp[i]] >= 0) labels[i] = to[comp[i]];
|
|
4655
|
+
}
|
|
4656
|
+
}
|
|
4237
4657
|
/**
|
|
4238
4658
|
* 4-connected components of equal labels (two-pass union-find, linear time).
|
|
4239
4659
|
* `keep` decides which labels count as regions; the rest are VOID.
|
|
@@ -5115,98 +5535,1895 @@ function centerline(rgba, w, h, o) {
|
|
|
5115
5535
|
measuredWidth: round(measured)
|
|
5116
5536
|
};
|
|
5117
5537
|
}
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
*
|
|
5122
|
-
|
|
5123
|
-
|
|
5124
|
-
|
|
5125
|
-
|
|
5126
|
-
|
|
5127
|
-
|
|
5128
|
-
|
|
5129
|
-
|
|
5130
|
-
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
*/
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
5137
|
-
|
|
5138
|
-
|
|
5139
|
-
|
|
5140
|
-
|
|
5538
|
+
/** Linear light (0–1) to sRGB (0–1). */
|
|
5539
|
+
const enc = (v) => v <= .0031308 ? 12.92 * Math.max(v, 0) : 1.055 * v ** (1 / 2.4) - .055;
|
|
5540
|
+
/** Slope of `enc`: how much a small error in linear light shows. */
|
|
5541
|
+
const encSlope = (v) => v <= .0031308 ? 12.92 : 1.055 / 2.4 * v ** (1 / 2.4 - 1);
|
|
5542
|
+
/** sRGB (0–255, any float) to linear light, 0–1. */
|
|
5543
|
+
const toLight = (v) => {
|
|
5544
|
+
const s = Math.min(1, Math.max(0, v / 255));
|
|
5545
|
+
return s <= .04045 ? s / 12.92 : ((s + .055) / 1.055) ** 2.4;
|
|
5546
|
+
};
|
|
5547
|
+
/** Blurred as stored: by a resize, a filter, an upscale. */
|
|
5548
|
+
const STORED = {
|
|
5549
|
+
to: (v) => Math.min(1, Math.max(0, v / 255)),
|
|
5550
|
+
back: (u) => u,
|
|
5551
|
+
shows: () => 1
|
|
5552
|
+
};
|
|
5553
|
+
/** Blurred as light: by a lens. */
|
|
5554
|
+
const LIGHT = {
|
|
5555
|
+
to: toLight,
|
|
5556
|
+
back: enc,
|
|
5557
|
+
shows: encSlope
|
|
5558
|
+
};
|
|
5559
|
+
/** A 1-D Gaussian of the given sigma, out to 3 sigma, summing to 1. */
|
|
5560
|
+
function gauss1(sigma) {
|
|
5561
|
+
const r = Math.max(1, Math.ceil(3 * sigma));
|
|
5562
|
+
const k = new Float32Array(2 * r + 1);
|
|
5563
|
+
let sum = 0;
|
|
5564
|
+
for (let i = -r; i <= r; i++) sum += k[i + r] = Math.exp(-(i * i) / (2 * sigma * sigma));
|
|
5565
|
+
for (let i = 0; i < k.length; i++) k[i] /= sum;
|
|
5566
|
+
return k;
|
|
5567
|
+
}
|
|
5568
|
+
/** `src` (w × h) blurred by a Gaussian; edges repeat. */
|
|
5569
|
+
function blur(src, w, h, sigma) {
|
|
5570
|
+
const k = gauss1(sigma);
|
|
5571
|
+
const r = k.length - 1 >> 1;
|
|
5572
|
+
const tmp = new Float32Array(w * h);
|
|
5573
|
+
const out = new Float32Array(w * h);
|
|
5574
|
+
for (let y = 0; y < h; y++) {
|
|
5575
|
+
const row = y * w;
|
|
5576
|
+
for (let x = 0; x < w; x++) {
|
|
5577
|
+
let s = 0;
|
|
5578
|
+
for (let i = -r; i <= r; i++) s += k[i + r] * src[row + Math.min(w - 1, Math.max(0, x + i))];
|
|
5579
|
+
tmp[row + x] = s;
|
|
5580
|
+
}
|
|
5581
|
+
}
|
|
5582
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
5583
|
+
let s = 0;
|
|
5584
|
+
for (let i = -r; i <= r; i++) s += k[i + r] * tmp[Math.min(h - 1, Math.max(0, y + i)) * w + x];
|
|
5585
|
+
out[y * w + x] = s;
|
|
5586
|
+
}
|
|
5587
|
+
return out;
|
|
5588
|
+
}
|
|
5589
|
+
/** `src` at (x, y), between pixels; edges repeat. */
|
|
5590
|
+
function sample(src, w, h, x, y) {
|
|
5591
|
+
const cx = Math.min(w - 1, Math.max(0, x));
|
|
5592
|
+
const cy = Math.min(h - 1, Math.max(0, y));
|
|
5593
|
+
const x0 = Math.min(w - 2 < 0 ? 0 : w - 2, Math.floor(cx));
|
|
5594
|
+
const y0 = Math.min(h - 2 < 0 ? 0 : h - 2, Math.floor(cy));
|
|
5595
|
+
const fx = cx - x0;
|
|
5596
|
+
const fy = cy - y0;
|
|
5597
|
+
const x1 = Math.min(w - 1, x0 + 1);
|
|
5598
|
+
const y1 = Math.min(h - 1, y0 + 1);
|
|
5599
|
+
return (src[y0 * w + x0] * (1 - fx) + src[y0 * w + x1] * fx) * (1 - fy) + (src[y1 * w + x0] * (1 - fx) + src[y1 * w + x1] * fx) * fy;
|
|
5600
|
+
}
|
|
5601
|
+
/** A coarse grid of values with weights, evened out and read back anywhere: empty cells take their neighbours'. */
|
|
5602
|
+
function gridField(values, weights, gw, gh, spread = 1.5) {
|
|
5603
|
+
const num = new Float32Array(gw * gh);
|
|
5604
|
+
let top = 0;
|
|
5605
|
+
for (let i = 0; i < num.length; i++) {
|
|
5606
|
+
num[i] = values[i] * weights[i];
|
|
5607
|
+
if (weights[i] > top) top = weights[i];
|
|
5608
|
+
}
|
|
5609
|
+
const n = blur(num, gw, gh, spread);
|
|
5610
|
+
const d = blur(weights, gw, gh, spread);
|
|
5611
|
+
const field = new Float32Array(gw * gh);
|
|
5612
|
+
let any = false;
|
|
5613
|
+
for (let i = 0; i < field.length; i++) if (d[i] > 1e-6 * top) {
|
|
5614
|
+
field[i] = n[i] / d[i];
|
|
5615
|
+
any = true;
|
|
5616
|
+
} else field[i] = NaN;
|
|
5617
|
+
for (let pass = 0; any && pass < gw + gh; pass++) {
|
|
5618
|
+
let left = false;
|
|
5619
|
+
const prev = Float32Array.from(field);
|
|
5620
|
+
for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
|
|
5621
|
+
const i = y * gw + x;
|
|
5622
|
+
if (!Number.isNaN(prev[i])) continue;
|
|
5623
|
+
let s = 0;
|
|
5624
|
+
let c = 0;
|
|
5625
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
5626
|
+
const xx = x + dx;
|
|
5627
|
+
const yy = y + dy;
|
|
5628
|
+
if (xx < 0 || yy < 0 || xx >= gw || yy >= gh) continue;
|
|
5629
|
+
const v = prev[yy * gw + xx];
|
|
5630
|
+
if (!Number.isNaN(v)) s += v, c++;
|
|
5631
|
+
}
|
|
5632
|
+
if (c) field[i] = s / c;
|
|
5633
|
+
else left = true;
|
|
5634
|
+
}
|
|
5635
|
+
if (!left) break;
|
|
5636
|
+
}
|
|
5637
|
+
if (!any) field.fill(0);
|
|
5638
|
+
return (gx, gy) => sample(field, gw, gh, gx, gy);
|
|
5639
|
+
}
|
|
5640
|
+
/** Half-size block (px) a channel's offset is measured over, and how far apart blocks start. */
|
|
5641
|
+
const FRINGE_BLOCK = 32;
|
|
5642
|
+
const FRINGE_STEP = 32;
|
|
5643
|
+
/** Furthest offset looked for, in half-size px. */
|
|
5644
|
+
const FRINGE_REACH = 6;
|
|
5645
|
+
/** Offsets under this (px) over nine tenths of the picture are left alone… */
|
|
5646
|
+
const FRINGE_MIN = .5;
|
|
5647
|
+
/** …as are offsets under this share of the blur: blurred colours' edges differ a little by channel anyway. */
|
|
5648
|
+
const FRINGE_PER_BLUR = .25;
|
|
5649
|
+
/** How far (blocks) the measured offsets are evened out: a lens's fringe changes slowly across the picture. */
|
|
5650
|
+
const FRINGE_SPREAD = 2;
|
|
5141
5651
|
/**
|
|
5142
|
-
*
|
|
5143
|
-
*
|
|
5144
|
-
*
|
|
5652
|
+
* Red and blue moved back onto green. Each is compared with green block by
|
|
5653
|
+
* block, at half size: the offset at which its edges line up best with
|
|
5654
|
+
* green's, across and down. The offsets, evened out into a smooth field (they
|
|
5655
|
+
* grow towards a lens's edge, and with the blur), are then undone. Returns
|
|
5656
|
+
* null when no block is off by enough to matter. Channels are 0–255 floats.
|
|
5145
5657
|
*/
|
|
5146
|
-
function
|
|
5147
|
-
const
|
|
5148
|
-
const
|
|
5149
|
-
const
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
|
|
5157
|
-
|
|
5158
|
-
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5658
|
+
function alignChannels(ch, w, h, blurPx) {
|
|
5659
|
+
const hw = w >> 1;
|
|
5660
|
+
const hh = h >> 1;
|
|
5661
|
+
const B = FRINGE_BLOCK;
|
|
5662
|
+
if (hw < 46 || hh < 46) return null;
|
|
5663
|
+
const gw = Math.floor((hw - B) / FRINGE_STEP) + 1;
|
|
5664
|
+
const gh = Math.floor((hh - B) / FRINGE_STEP) + 1;
|
|
5665
|
+
const n = w * h;
|
|
5666
|
+
const total = [
|
|
5667
|
+
new Float32Array(n),
|
|
5668
|
+
new Float32Array(n),
|
|
5669
|
+
new Float32Array(n),
|
|
5670
|
+
new Float32Array(n)
|
|
5671
|
+
];
|
|
5672
|
+
let cur = ch;
|
|
5673
|
+
let moved = false;
|
|
5674
|
+
for (let round = 0; round < 2; round++) {
|
|
5675
|
+
const grads = cur.map((c) => {
|
|
5676
|
+
const half = new Float32Array(hw * hh);
|
|
5677
|
+
for (let y = 0; y < hh; y++) for (let x = 0; x < hw; x++) half[y * hw + x] = (c[2 * y * w + 2 * x] + c[2 * y * w + 2 * x + 1] + c[(2 * y + 1) * w + 2 * x] + c[(2 * y + 1) * w + 2 * x + 1]) / 4;
|
|
5678
|
+
const s = blur(half, hw, hh, 1);
|
|
5679
|
+
const gx = new Float32Array(hw * hh);
|
|
5680
|
+
const gy = new Float32Array(hw * hh);
|
|
5681
|
+
for (let y = 1; y < hh - 1; y++) for (let x = 1; x < hw - 1; x++) {
|
|
5682
|
+
gx[y * hw + x] = (s[y * hw + x + 1] - s[y * hw + x - 1]) / 2;
|
|
5683
|
+
gy[y * hw + x] = (s[(y + 1) * hw + x] - s[(y - 1) * hw + x]) / 2;
|
|
5684
|
+
}
|
|
5685
|
+
return [gx, gy];
|
|
5686
|
+
});
|
|
5687
|
+
let biggest = 0;
|
|
5688
|
+
const fields = [];
|
|
5689
|
+
for (const c of [0, 2]) for (let axis = 0; axis < 2; axis++) {
|
|
5690
|
+
const ref = grads[1][axis];
|
|
5691
|
+
const mov = grads[c][axis];
|
|
5692
|
+
const step = axis === 0 ? 1 : hw;
|
|
5693
|
+
const vals = new Float32Array(gw * gh);
|
|
5694
|
+
const wts = new Float32Array(gw * gh);
|
|
5695
|
+
const score = /* @__PURE__ */ new Float32Array(13);
|
|
5696
|
+
for (let by = 0; by < gh; by++) for (let bx = 0; bx < gw; bx++) {
|
|
5697
|
+
const x0 = bx * FRINGE_STEP;
|
|
5698
|
+
const y0 = by * FRINGE_STEP;
|
|
5699
|
+
let e = 0;
|
|
5700
|
+
for (let y = y0; y < y0 + B; y++) for (let x = x0; x < x0 + B; x++) e += ref[y * hw + x] ** 2;
|
|
5701
|
+
if (e < 4096) continue;
|
|
5702
|
+
let best = 0;
|
|
5703
|
+
for (let d = -6; d <= FRINGE_REACH; d++) {
|
|
5704
|
+
let dot = 0;
|
|
5705
|
+
let own = 0;
|
|
5706
|
+
for (let y = y0; y < y0 + B; y++) for (let x = x0; x < x0 + B; x++) {
|
|
5707
|
+
const xx = axis === 0 ? x + d : x;
|
|
5708
|
+
const yy = axis === 0 ? y : y + d;
|
|
5709
|
+
if (xx < 0 || yy < 0 || xx >= hw || yy >= hh) continue;
|
|
5710
|
+
const v = mov[y * hw + x + d * step];
|
|
5711
|
+
dot += ref[y * hw + x] * v;
|
|
5712
|
+
own += v * v;
|
|
5713
|
+
}
|
|
5714
|
+
score[d + FRINGE_REACH] = dot / Math.sqrt(e * own + 1e-9);
|
|
5715
|
+
if (score[d + FRINGE_REACH] > score[best]) best = d + FRINGE_REACH;
|
|
5716
|
+
}
|
|
5717
|
+
if (best === 0 || best === score.length - 1 || score[best] <= 0) continue;
|
|
5718
|
+
const curve = score[best - 1] - 2 * score[best] + score[best + 1];
|
|
5719
|
+
const off = curve < 0 ? .5 * (score[best - 1] - score[best + 1]) / curve : 0;
|
|
5720
|
+
vals[by * gw + bx] = 2 * (best - FRINGE_REACH + off);
|
|
5721
|
+
wts[by * gw + bx] = score[best] * Math.sqrt(e);
|
|
5722
|
+
}
|
|
5723
|
+
const field = gridField(vals, wts, gw, gh, FRINGE_SPREAD);
|
|
5724
|
+
fields.push(field);
|
|
5725
|
+
const sizes = [];
|
|
5726
|
+
for (let i = 0; i < gw * gh; i++) if (wts[i] > 0) sizes.push(Math.abs(field(i % gw, Math.floor(i / gw))));
|
|
5727
|
+
sizes.sort((x, y) => x - y);
|
|
5728
|
+
if (sizes.length) biggest = Math.max(biggest, sizes[Math.floor(sizes.length * .9)]);
|
|
5165
5729
|
}
|
|
5166
|
-
|
|
5167
|
-
|
|
5168
|
-
const
|
|
5169
|
-
|
|
5170
|
-
|
|
5171
|
-
|
|
5172
|
-
|
|
5173
|
-
|
|
5174
|
-
const
|
|
5175
|
-
const
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
|
|
5179
|
-
let
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
const
|
|
5183
|
-
const
|
|
5184
|
-
|
|
5730
|
+
if (biggest < Math.max(FRINGE_MIN, FRINGE_PER_BLUR * blurPx)) break;
|
|
5731
|
+
moved = true;
|
|
5732
|
+
const next = [
|
|
5733
|
+
new Float32Array(n),
|
|
5734
|
+
cur[1],
|
|
5735
|
+
new Float32Array(n)
|
|
5736
|
+
];
|
|
5737
|
+
for (let k = 0; k < 2; k++) {
|
|
5738
|
+
const c = k * 2;
|
|
5739
|
+
const tx = total[k * 2];
|
|
5740
|
+
const ty = total[k * 2 + 1];
|
|
5741
|
+
const fx = fields[k * 2];
|
|
5742
|
+
const fy = fields[k * 2 + 1];
|
|
5743
|
+
for (let y = 0; y < h; y++) {
|
|
5744
|
+
const gy = (y / 2 - B / 2) / FRINGE_STEP;
|
|
5745
|
+
for (let x = 0; x < w; x++) {
|
|
5746
|
+
const gx = (x / 2 - B / 2) / FRINGE_STEP;
|
|
5747
|
+
const p = y * w + x;
|
|
5748
|
+
tx[p] += fx(gx, gy);
|
|
5749
|
+
ty[p] += fy(gx, gy);
|
|
5750
|
+
next[c][p] = sample(ch[c], w, h, x + tx[p], y + ty[p]);
|
|
5185
5751
|
}
|
|
5186
|
-
const j = i + offsets[k];
|
|
5187
|
-
if (src[j + 3] < 128) continue;
|
|
5188
|
-
const dr = src[j] - r;
|
|
5189
|
-
const dg = src[j + 1] - g;
|
|
5190
|
-
const db = src[j + 2] - b;
|
|
5191
|
-
const w = spatial[k] * near[dr * dr + dg * dg + db * db];
|
|
5192
|
-
sr += w * src[j];
|
|
5193
|
-
sg += w * src[j + 1];
|
|
5194
|
-
sb += w * src[j + 2];
|
|
5195
|
-
sw += w;
|
|
5196
5752
|
}
|
|
5197
|
-
out[i] = sr / sw;
|
|
5198
|
-
out[i + 1] = sg / sw;
|
|
5199
|
-
out[i + 2] = sb / sw;
|
|
5200
5753
|
}
|
|
5201
|
-
|
|
5754
|
+
cur = next;
|
|
5202
5755
|
}
|
|
5203
|
-
|
|
5204
|
-
return src;
|
|
5756
|
+
return moved ? cur : null;
|
|
5205
5757
|
}
|
|
5206
|
-
/**
|
|
5207
|
-
const
|
|
5208
|
-
/**
|
|
5209
|
-
const
|
|
5758
|
+
/** Contrast (of 255) an edge needs to be measured: only bold edges, whose two sides are surely flat. */
|
|
5759
|
+
const EDGE_CONTRAST = 40;
|
|
5760
|
+
/** How far (px) either side of an edge its ramp is followed. */
|
|
5761
|
+
const EDGE_REACH = 30;
|
|
5762
|
+
/** Block (px) the edges' blurs are pooled over, and how far apart blocks start. */
|
|
5763
|
+
const BLUR_BLOCK = 96;
|
|
5764
|
+
const BLUR_STEP = 48;
|
|
5765
|
+
/**
|
|
5766
|
+
* Every bold edge's ramp: from a point where the image is steepest, the
|
|
5767
|
+
* values along the way uphill, out to where they level off either side.
|
|
5768
|
+
* `each` gets the point, the slope there, and the ramp as `prof[lo..hi]`
|
|
5769
|
+
* (dark end first).
|
|
5770
|
+
*/
|
|
5771
|
+
function ramps(lum, w, h, reach, each) {
|
|
5772
|
+
const g = blur(lum, w, h, 1);
|
|
5773
|
+
const gx = new Float32Array(w * h);
|
|
5774
|
+
const gy = new Float32Array(w * h);
|
|
5775
|
+
const mag = new Float32Array(w * h);
|
|
5776
|
+
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
|
|
5777
|
+
const p = y * w + x;
|
|
5778
|
+
gx[p] = (g[p + 1] - g[p - 1]) / 2;
|
|
5779
|
+
gy[p] = (g[p + w] - g[p - w]) / 2;
|
|
5780
|
+
mag[p] = Math.hypot(gx[p], gy[p]);
|
|
5781
|
+
}
|
|
5782
|
+
const prof = new Float32Array(2 * reach + 1);
|
|
5783
|
+
let seen = 0;
|
|
5784
|
+
for (let y = 3; y < h - 3; y++) for (let x = 3; x < w - 3; x++) {
|
|
5785
|
+
const p = y * w + x;
|
|
5786
|
+
const m = mag[p];
|
|
5787
|
+
if (!(m > 1) || (Math.imul(seen++, 2654435761) >>> 0) % 3) continue;
|
|
5788
|
+
const dx = gx[p] / m;
|
|
5789
|
+
const dy = gy[p] / m;
|
|
5790
|
+
if (sample(mag, w, h, x + dx, y + dy) > m || sample(mag, w, h, x - dx, y - dy) > m) continue;
|
|
5791
|
+
for (let t = -reach; t <= reach; t++) prof[t + reach] = sample(g, w, h, x + dx * t, y + dy * t);
|
|
5792
|
+
let hi = reach;
|
|
5793
|
+
while (hi < 2 * reach - 1 && prof[hi + 1] - prof[hi] > .04 * m) hi++;
|
|
5794
|
+
let lo = reach;
|
|
5795
|
+
while (lo > 0 && prof[lo] - prof[lo - 1] > .04 * m) lo--;
|
|
5796
|
+
if (prof[hi] - prof[lo] >= EDGE_CONTRAST) each(x, y, m, prof, lo, hi);
|
|
5797
|
+
}
|
|
5798
|
+
}
|
|
5799
|
+
/**
|
|
5800
|
+
* How soft the image's edges are, and where. A step of contrast C blurred by
|
|
5801
|
+
* a Gaussian of sigma s is steepest at C / (s√2π), so every bold edge gives
|
|
5802
|
+
* s = C / (slope √2π), C being the rise of its ramp. Pooled by block (medians:
|
|
5803
|
+
* thin lines read too sharp, soft shadows too blurred) and evened out into a
|
|
5804
|
+
* map. `lum` is 0–255, in the space the blur happened in.
|
|
5805
|
+
*/
|
|
5806
|
+
function measureBlur(lum, w, h) {
|
|
5807
|
+
const found = [];
|
|
5808
|
+
ramps(lum, w, h, EDGE_REACH, (x, y, slope, prof, lo, hi) => {
|
|
5809
|
+
const s = (prof[hi] - prof[lo]) / (slope * Math.sqrt(2 * Math.PI));
|
|
5810
|
+
found.push(x, y, Math.sqrt(Math.max(s * s - 1, .01)));
|
|
5811
|
+
});
|
|
5812
|
+
if (!found.length) return {
|
|
5813
|
+
median: 0,
|
|
5814
|
+
at: () => 0
|
|
5815
|
+
};
|
|
5816
|
+
const all = [];
|
|
5817
|
+
for (let i = 2; i < found.length; i += 3) all.push(found[i]);
|
|
5818
|
+
all.sort((a, b) => a - b);
|
|
5819
|
+
const median = all[all.length >> 1];
|
|
5820
|
+
const gw = Math.max(1, Math.floor((w - BLUR_BLOCK) / BLUR_STEP) + 1);
|
|
5821
|
+
const gh = Math.max(1, Math.floor((h - BLUR_BLOCK) / BLUR_STEP) + 1);
|
|
5822
|
+
const cells = Array.from({ length: gw * gh }, () => []);
|
|
5823
|
+
for (let i = 0; i < found.length; i += 3) {
|
|
5824
|
+
const cx = (found[i] - BLUR_BLOCK / 2) / BLUR_STEP;
|
|
5825
|
+
const cy = (found[i + 1] - BLUR_BLOCK / 2) / BLUR_STEP;
|
|
5826
|
+
for (const by of [Math.floor(cy), Math.ceil(cy)]) for (const bx of [Math.floor(cx), Math.ceil(cx)]) {
|
|
5827
|
+
const x = Math.min(gw - 1, Math.max(0, bx));
|
|
5828
|
+
cells[Math.min(gh - 1, Math.max(0, by)) * gw + x].push(found[i + 2]);
|
|
5829
|
+
}
|
|
5830
|
+
}
|
|
5831
|
+
const vals = new Float32Array(gw * gh);
|
|
5832
|
+
const wts = new Float32Array(gw * gh);
|
|
5833
|
+
cells.forEach((c, i) => {
|
|
5834
|
+
if (c.length < 8) return;
|
|
5835
|
+
c.sort((a, b) => a - b);
|
|
5836
|
+
vals[i] = Math.min(c[c.length >> 1], 3 * median);
|
|
5837
|
+
wts[i] = Math.min(c.length, 60);
|
|
5838
|
+
});
|
|
5839
|
+
if (!wts.some((v) => v > 0)) return {
|
|
5840
|
+
median,
|
|
5841
|
+
at: () => median
|
|
5842
|
+
};
|
|
5843
|
+
const field = gridField(vals, wts, gw, gh);
|
|
5844
|
+
return {
|
|
5845
|
+
median,
|
|
5846
|
+
at: (x, y) => field((x - BLUR_BLOCK / 2) / BLUR_STEP, (y - BLUR_BLOCK / 2) / BLUR_STEP)
|
|
5847
|
+
};
|
|
5848
|
+
}
|
|
5849
|
+
/** Contrast (of 255) an edge needs to say which kind of blur it had, and how far (px) either side it is followed. */
|
|
5850
|
+
const STARK = 128;
|
|
5851
|
+
const STARK_REACH = 60;
|
|
5852
|
+
/** How much (of its rise) a ramp's ends may drift beyond it and still count as level. */
|
|
5853
|
+
const LEVEL = .08;
|
|
5854
|
+
/** How lopsided (bright half longer, as a share of the whole) stark edges' ramps are when light was blurred. */
|
|
5855
|
+
const LOPSIDED = .011;
|
|
5856
|
+
/**
|
|
5857
|
+
* Whether the blur happened to light (a lens out of focus) or to the stored
|
|
5858
|
+
* values (a resize, a filter, an upscale). Light blurs in linear units, where
|
|
5859
|
+
* white outweighs black many times over, so on screen a blurred black-white
|
|
5860
|
+
* edge has a long bright shoulder and a short dark toe; blurred as stored, it
|
|
5861
|
+
* is even. The lopsidedness of the starkest edges' ramps (how much further the
|
|
5862
|
+
* 84% point is from the middle than the 16% point) tells them apart.
|
|
5863
|
+
* `lum` is luma as stored, 0–255.
|
|
5864
|
+
*/
|
|
5865
|
+
function blurredAsLight(lum, w, h) {
|
|
5866
|
+
const skew = [];
|
|
5867
|
+
ramps(lum, w, h, STARK_REACH, (_x, _y, _slope, prof, lo, hi) => {
|
|
5868
|
+
const a = prof[lo];
|
|
5869
|
+
const range = prof[hi] - a;
|
|
5870
|
+
if (range < STARK) return;
|
|
5871
|
+
const beyond = Math.max(3, hi - lo);
|
|
5872
|
+
if (lo - beyond < 0 || hi + beyond >= prof.length) return;
|
|
5873
|
+
if (Math.abs(prof[lo - beyond] - a) > LEVEL * range || Math.abs(prof[hi + beyond] - prof[hi]) > LEVEL * range) return;
|
|
5874
|
+
const cross = (share) => {
|
|
5875
|
+
let i = lo + 1;
|
|
5876
|
+
while (i < hi && (prof[i] - a) / range < share) i++;
|
|
5877
|
+
const q0 = (prof[i - 1] - a) / range;
|
|
5878
|
+
const q1 = (prof[i] - a) / range;
|
|
5879
|
+
return i - 1 + (q1 > q0 ? (share - q0) / (q1 - q0) : 0);
|
|
5880
|
+
};
|
|
5881
|
+
const x16 = cross(.16);
|
|
5882
|
+
const x50 = cross(.5);
|
|
5883
|
+
const x84 = cross(.84);
|
|
5884
|
+
if (x84 - x16 > .5) skew.push((x84 - x50 - (x50 - x16)) / (x84 - x16));
|
|
5885
|
+
});
|
|
5886
|
+
if (skew.length < 20) return false;
|
|
5887
|
+
skew.sort((a, b) => a - b);
|
|
5888
|
+
return skew[skew.length >> 1] > LOPSIDED;
|
|
5889
|
+
}
|
|
5890
|
+
/**
|
|
5891
|
+
* How soft the image's edges are, in px: the Gaussian blur a hard edge would
|
|
5892
|
+
* need to look like the image's bold edges (their median). 0 when it has no
|
|
5893
|
+
* bold edges. Crisp art reads under 1, anti-aliasing and all.
|
|
5894
|
+
*/
|
|
5895
|
+
function edgeBlur(rgba, width, height) {
|
|
5896
|
+
const lum = new Float32Array(width * height);
|
|
5897
|
+
for (let p = 0; p < lum.length; p++) lum[p] = .2126 * rgba[p * 4] + .7152 * rgba[p * 4 + 1] + .0722 * rgba[p * 4 + 2];
|
|
5898
|
+
return measureBlur(lum, width, height).median;
|
|
5899
|
+
}
|
|
5900
|
+
/** Colours closer than this (RGB distance) are one colour. */
|
|
5901
|
+
const SAME_COLOUR = 36;
|
|
5902
|
+
/** A flat colour needs this share of the flat pixels. */
|
|
5903
|
+
const MIN_SHARE = 8e-4;
|
|
5904
|
+
/** Past this distance from every blend of two flat colours, a pixel is a colour of its own (a thin line's). */
|
|
5905
|
+
const NOT_A_BLEND = 26;
|
|
5906
|
+
/** Distance from `p` to the segment a–b. */
|
|
5907
|
+
function offSegment(p0, p1, p2, a, b) {
|
|
5908
|
+
const ab0 = b[0] - a[0];
|
|
5909
|
+
const ab1 = b[1] - a[1];
|
|
5910
|
+
const ab2 = b[2] - a[2];
|
|
5911
|
+
const t = Math.min(1, Math.max(0, ((p0 - a[0]) * ab0 + (p1 - a[1]) * ab1 + (p2 - a[2]) * ab2) / (ab0 * ab0 + ab1 * ab1 + ab2 * ab2 + 1e-9)));
|
|
5912
|
+
return Math.hypot(p0 - a[0] - t * ab0, p1 - a[1] - t * ab1, p2 - a[2] - t * ab2);
|
|
5913
|
+
}
|
|
5914
|
+
/** Which pixels sit in a flat area: every channel of the smoothed planes within FLAT levels across the 5 × 5 around them. */
|
|
5915
|
+
function flatMask(sm, w, h) {
|
|
5916
|
+
const flat = new Uint8Array(w * h);
|
|
5917
|
+
for (let y = 2; y < h - 2; y++) for (let x = 2; x < w - 2; x++) {
|
|
5918
|
+
let ok = true;
|
|
5919
|
+
for (let c = 0; c < 3 && ok; c++) {
|
|
5920
|
+
let lo = 255;
|
|
5921
|
+
let hi = 0;
|
|
5922
|
+
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) {
|
|
5923
|
+
const v = sm[c][(y + dy) * w + x + dx];
|
|
5924
|
+
if (v < lo) lo = v;
|
|
5925
|
+
if (v > hi) hi = v;
|
|
5926
|
+
}
|
|
5927
|
+
ok = hi - lo < FLAT;
|
|
5928
|
+
}
|
|
5929
|
+
if (ok) flat[y * w + x] = 1;
|
|
5930
|
+
}
|
|
5931
|
+
return flat;
|
|
5932
|
+
}
|
|
5933
|
+
const FLAT = 14;
|
|
5934
|
+
/**
|
|
5935
|
+
* The colours the picture is made of, from a blurred copy of it (sRGB planes,
|
|
5936
|
+
* 0–255). First the colours of its flat areas, where blur changes nothing:
|
|
5937
|
+
* the commonest, each far enough from the ones before. Then up to three more
|
|
5938
|
+
* that no blend of two of those explains, the colours of lines too thin to
|
|
5939
|
+
* have a flat middle (an orange pinstripe on navy): the strongest tenth of
|
|
5940
|
+
* such pixels, since blur only ever dilutes a thin line's colour.
|
|
5941
|
+
*/
|
|
5942
|
+
function flatColours(s, w, h) {
|
|
5943
|
+
const n = w * h;
|
|
5944
|
+
const sm = s.map((c) => blur(c, w, h, 1));
|
|
5945
|
+
const counts = /* @__PURE__ */ new Map();
|
|
5946
|
+
const mask = flatMask(sm, w, h);
|
|
5947
|
+
let flat = 0;
|
|
5948
|
+
for (let p = 0; p < n; p++) {
|
|
5949
|
+
if (!mask[p]) continue;
|
|
5950
|
+
flat++;
|
|
5951
|
+
const key = sm[0][p] >> 3 << 10 | sm[1][p] >> 3 << 5 | sm[2][p] >> 3;
|
|
5952
|
+
const e = counts.get(key);
|
|
5953
|
+
if (e) e[0] += sm[0][p], e[1] += sm[1][p], e[2] += sm[2][p], e[3]++;
|
|
5954
|
+
else counts.set(key, [
|
|
5955
|
+
sm[0][p],
|
|
5956
|
+
sm[1][p],
|
|
5957
|
+
sm[2][p],
|
|
5958
|
+
1
|
|
5959
|
+
]);
|
|
5960
|
+
}
|
|
5961
|
+
const palette = [];
|
|
5962
|
+
for (const e of [...counts.values()].sort((a, b) => b[3] - a[3])) {
|
|
5963
|
+
if (e[3] < flat * MIN_SHARE) break;
|
|
5964
|
+
const c = [
|
|
5965
|
+
e[0] / e[3],
|
|
5966
|
+
e[1] / e[3],
|
|
5967
|
+
e[2] / e[3]
|
|
5968
|
+
];
|
|
5969
|
+
if (palette.every((q) => Math.hypot(q[0] - c[0], q[1] - c[1], q[2] - c[2]) > SAME_COLOUR)) palette.push(c);
|
|
5970
|
+
if (palette.length >= 12) break;
|
|
5971
|
+
}
|
|
5972
|
+
if (palette.length < 2) return palette;
|
|
5973
|
+
const soft = s.map((c) => blur(c, w, h, .7));
|
|
5974
|
+
const off = new Float32Array(n);
|
|
5975
|
+
for (let extra = 0; extra < 3; extra++) {
|
|
5976
|
+
const far = [];
|
|
5977
|
+
for (let p = 0; p < n; p++) {
|
|
5978
|
+
let d = 1e400;
|
|
5979
|
+
for (let i = 0; i < palette.length && d > NOT_A_BLEND; i++) for (let j = i + 1; j < palette.length && d > NOT_A_BLEND; j++) d = Math.min(d, offSegment(soft[0][p], soft[1][p], soft[2][p], palette[i], palette[j]));
|
|
5980
|
+
off[p] = d;
|
|
5981
|
+
if (d > NOT_A_BLEND) far.push(p);
|
|
5982
|
+
}
|
|
5983
|
+
if (far.length < n * 5e-4) break;
|
|
5984
|
+
for (const p of far) {
|
|
5985
|
+
let d = 1e400;
|
|
5986
|
+
for (let i = 0; i < palette.length; i++) for (let j = i + 1; j < palette.length; j++) d = Math.min(d, offSegment(soft[0][p], soft[1][p], soft[2][p], palette[i], palette[j]));
|
|
5987
|
+
off[p] = d;
|
|
5988
|
+
}
|
|
5989
|
+
far.sort((a, b) => off[b] - off[a]);
|
|
5990
|
+
const top = far.slice(0, Math.max(20, Math.floor(far.length / 10)));
|
|
5991
|
+
const mean = (ps) => {
|
|
5992
|
+
const m = [
|
|
5993
|
+
0,
|
|
5994
|
+
0,
|
|
5995
|
+
0
|
|
5996
|
+
];
|
|
5997
|
+
for (const p of ps) for (let c = 0; c < 3; c++) m[c] += soft[c][p] / ps.length;
|
|
5998
|
+
return m;
|
|
5999
|
+
};
|
|
6000
|
+
const centre = mean(top);
|
|
6001
|
+
const near = top.filter((p) => Math.hypot(soft[0][p] - centre[0], soft[1][p] - centre[1], soft[2][p] - centre[2]) < 40);
|
|
6002
|
+
if (near.length < 10) break;
|
|
6003
|
+
palette.push(mean(near));
|
|
6004
|
+
}
|
|
6005
|
+
return palette;
|
|
6006
|
+
}
|
|
6007
|
+
/** Colours further apart than this are never one colour under uneven light. */
|
|
6008
|
+
const SHADE_REACH = 60;
|
|
6009
|
+
/** Where two colours meet, a real edge is at least this steep, as a share of what their difference blurred would be. */
|
|
6010
|
+
const SHADE_STEEP = .35;
|
|
6011
|
+
/** Smoothing (px) of the copy that steepness is measured on. */
|
|
6012
|
+
const SHADE_SMOOTH = 2.5;
|
|
6013
|
+
/**
|
|
6014
|
+
* The palette without the colours that are only another colour under uneven
|
|
6015
|
+
* light: a photo's white paper darkens towards a corner, and reads as two
|
|
6016
|
+
* near-whites meeting along a line no edge runs along. Where two close
|
|
6017
|
+
* colours' pixels meet, a real edge between them, however blurred, is about
|
|
6018
|
+
* as steep as their difference spread over the blur; lighting is many times
|
|
6019
|
+
* gentler. A colour that meets a commoner one only that gently is folded into
|
|
6020
|
+
* it (`start` is relabelled in place), and the search then treats the
|
|
6021
|
+
* difference as lighting. Returns the colours kept.
|
|
6022
|
+
*/
|
|
6023
|
+
function dropShades(s, w, h, sigma, palette, start) {
|
|
6024
|
+
const K = palette.length;
|
|
6025
|
+
const flat = flatMask(s.map((c) => blur(c, w, h, 1)), w, h);
|
|
6026
|
+
const wide = s.map((c) => blur(c, w, h, SHADE_SMOOTH));
|
|
6027
|
+
const steep = new Float64Array(K * K);
|
|
6028
|
+
const met = new Float64Array(K * K);
|
|
6029
|
+
const count = new Float64Array(K);
|
|
6030
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6031
|
+
const p = y * w + x;
|
|
6032
|
+
const a = start[p];
|
|
6033
|
+
count[a]++;
|
|
6034
|
+
for (const q of [x + 1 < w ? p + 1 : -1, y + 1 < h ? p + w : -1]) {
|
|
6035
|
+
if (q < 0) continue;
|
|
6036
|
+
const b = start[q];
|
|
6037
|
+
if (a === b || !flat[p] || !flat[q]) continue;
|
|
6038
|
+
const step = q - p;
|
|
6039
|
+
const far = step === 1 ? Math.min(3, x, w - 1 - x) : Math.min(3, y, h - 1 - y);
|
|
6040
|
+
if (!far) continue;
|
|
6041
|
+
const slope = Math.hypot(wide[0][p + far * step] - wide[0][p - far * step], wide[1][p + far * step] - wide[1][p - far * step], wide[2][p + far * step] - wide[2][p - far * step]) / (2 * far);
|
|
6042
|
+
const i = Math.min(a, b) * K + Math.max(a, b);
|
|
6043
|
+
steep[i] += slope * Math.sqrt(sigma[p] ** 2 + SHADE_SMOOTH ** 2) * Math.sqrt(2 * Math.PI);
|
|
6044
|
+
met[i]++;
|
|
6045
|
+
}
|
|
6046
|
+
}
|
|
6047
|
+
const into = Int32Array.from({ length: K }, (_, k) => k);
|
|
6048
|
+
const order = [...Array(K).keys()].sort((a, b) => count[a] - count[b]);
|
|
6049
|
+
for (const k of order) {
|
|
6050
|
+
let best = -1;
|
|
6051
|
+
for (let j = 0; j < K; j++) {
|
|
6052
|
+
if (j === k || count[j] <= count[k] || into[j] !== j) continue;
|
|
6053
|
+
const d = Math.hypot(palette[k][0] - palette[j][0], palette[k][1] - palette[j][1], palette[k][2] - palette[j][2]);
|
|
6054
|
+
const i = Math.min(k, j) * K + Math.max(k, j);
|
|
6055
|
+
if (d > SHADE_REACH || met[i] < 30 || steep[i] / met[i] / d >= SHADE_STEEP) continue;
|
|
6056
|
+
if (best < 0 || count[j] > count[best]) best = j;
|
|
6057
|
+
}
|
|
6058
|
+
if (best >= 0) into[k] = best;
|
|
6059
|
+
}
|
|
6060
|
+
const home = (k) => {
|
|
6061
|
+
while (into[k] !== k) k = into[k];
|
|
6062
|
+
return k;
|
|
6063
|
+
};
|
|
6064
|
+
for (const k of order) {
|
|
6065
|
+
const j = home(k);
|
|
6066
|
+
if (j !== k && Math.hypot(palette[k][0] - palette[j][0], palette[k][1] - palette[j][1], palette[k][2] - palette[j][2]) > SHADE_REACH) into[k] = k;
|
|
6067
|
+
}
|
|
6068
|
+
const kept = [];
|
|
6069
|
+
const index = new Int32Array(K).fill(-1);
|
|
6070
|
+
for (let k = 0; k < K; k++) if (into[k] === k) index[k] = kept.length, kept.push(palette[k]);
|
|
6071
|
+
for (let p = 0; p < start.length; p++) start[p] = index[home(start[p])];
|
|
6072
|
+
return kept;
|
|
6073
|
+
}
|
|
6074
|
+
/** Blur (work px) the search handles: more is treated as this. */
|
|
6075
|
+
const MAX_WORK_BLUR = 5;
|
|
6076
|
+
/** Blur levels a kernel is kept for, each this much wider than the last. */
|
|
6077
|
+
const LEVEL_RATIO = 1.08;
|
|
6078
|
+
/** How much boundary costs against misfit: higher is smoother and loses thin detail. */
|
|
6079
|
+
const BOUNDARY_COST = .03;
|
|
6080
|
+
/** Scale (work px) the boundary's length is measured at… */
|
|
6081
|
+
const BOUNDARY_SIGMA = 1.2;
|
|
6082
|
+
/** …growing with the blur there, by this much of it, up to BOUNDARY_SIGMA_MAX. */
|
|
6083
|
+
const BOUNDARY_PER_BLUR = .5;
|
|
6084
|
+
const BOUNDARY_SIGMA_MAX = 3;
|
|
6085
|
+
/** Sweeps at most, and the share of pixels a sweep must still change to earn another. */
|
|
6086
|
+
const SWEEPS = 24;
|
|
6087
|
+
const SETTLED = 2e-4;
|
|
6088
|
+
/** Sweeps between fresh looks at the slow lighting. */
|
|
6089
|
+
const RESHADE = 3;
|
|
6090
|
+
/** Slow lighting (a vignette, uneven paper) is set aside, measured over this many work px. */
|
|
6091
|
+
const SHADE_SIGMA = 20;
|
|
6092
|
+
/** A colour this near the line between two others (of 255), and not within this share of either end, is what they blend to. */
|
|
6093
|
+
const BLEND_OFF = 26;
|
|
6094
|
+
const BLEND_ENDS = .2;
|
|
6095
|
+
/**
|
|
6096
|
+
* An area of a blend's colour is re-read as the two it blends only when no
|
|
6097
|
+
* deeper than this many blurs, and a pixel. A line fades to the blend's colour
|
|
6098
|
+
* while it is under about 2.3 blurs wide, and is first read at about twice
|
|
6099
|
+
* its width, so that deep.
|
|
6100
|
+
*/
|
|
6101
|
+
const BLEND_DEPTH = 2.3;
|
|
6102
|
+
/**
|
|
6103
|
+
* And only a line with this share of its rim on the one colour: a line through
|
|
6104
|
+
* a field of it. A strip between two colours can as well be the wider, duller
|
|
6105
|
+
* strip it was first read as, and the blur leaves nothing to tell the two by.
|
|
6106
|
+
*/
|
|
6107
|
+
const BLEND_WITHIN = .75;
|
|
6108
|
+
/** Rounds of re-reading, and the sweeps that tidy up after each. */
|
|
6109
|
+
const BLEND_ROUNDS = 2;
|
|
6110
|
+
const BLEND_SWEEPS = 4;
|
|
6111
|
+
/** An area nowhere over two pixels wide goes where the misfit that costs is under this many times the boundary saved. */
|
|
6112
|
+
const SLIVER_WORTH = 12;
|
|
6113
|
+
/**
|
|
6114
|
+
* The label map (one palette index per pixel of a w × h picture) that, with
|
|
6115
|
+
* each pixel blurred by its own `sigma`, best matches `obs` (three planes,
|
|
6116
|
+
* 0–1, in the units of `space`: those the blur happened in), at the least
|
|
6117
|
+
* boundary.
|
|
6118
|
+
*
|
|
6119
|
+
* Starts from each pixel's nearest colour and improves it pixel by pixel,
|
|
6120
|
+
* down the picture and back up: a pixel takes a neighbour's label at once
|
|
6121
|
+
* wherever that lowers
|
|
6122
|
+
*
|
|
6123
|
+
* Σ weight² (blurred labels − photo)² + cost × boundary length,
|
|
6124
|
+
*
|
|
6125
|
+
* the misfit weighted by how visible it is (in light, the sRGB curve's slope:
|
|
6126
|
+
* a small error in a dark area shows more), the boundary measured by how
|
|
6127
|
+
* little each pixel's neighbourhood shares its label. A flip's effect on the
|
|
6128
|
+
* misfit is known from the misfit blurred back through the pixel's kernel,
|
|
6129
|
+
* and the misfit is kept up to date as flips are made. When that settles,
|
|
6130
|
+
* thin areas of a colour two others blend to are re-read as those two
|
|
6131
|
+
* (`unblend`), and slivers between areas are given to them (`dropSlivers`):
|
|
6132
|
+
* neither is reached by any run of single flips. A generator: it pauses
|
|
6133
|
+
* after every sweep.
|
|
6134
|
+
*/
|
|
6135
|
+
function* solve(obs, w, h, sigma, palette, start, space) {
|
|
6136
|
+
let top = .5;
|
|
6137
|
+
for (let p = 0; p < sigma.length; p++) top = Math.max(top, Math.min(MAX_WORK_BLUR, sigma[p]));
|
|
6138
|
+
const levels = [];
|
|
6139
|
+
for (let s = .5;; s *= LEVEL_RATIO) {
|
|
6140
|
+
const r = Math.max(1, Math.ceil(2.5 * s));
|
|
6141
|
+
const k = new Float32Array((2 * r + 1) ** 2);
|
|
6142
|
+
let sum = 0;
|
|
6143
|
+
for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) sum += k[(dy + r) * (2 * r + 1) + dx + r] = Math.exp(-(dx * dx + dy * dy) / (2 * s * s));
|
|
6144
|
+
let self = 0;
|
|
6145
|
+
for (let i = 0; i < k.length; i++) {
|
|
6146
|
+
k[i] /= sum;
|
|
6147
|
+
self += k[i] ** 2;
|
|
6148
|
+
}
|
|
6149
|
+
levels.push({
|
|
6150
|
+
r,
|
|
6151
|
+
k,
|
|
6152
|
+
self
|
|
6153
|
+
});
|
|
6154
|
+
if (s >= top) break;
|
|
6155
|
+
}
|
|
6156
|
+
const P = Math.max(levels[levels.length - 1].r + 1, Math.ceil(2.5 * BOUNDARY_SIGMA));
|
|
6157
|
+
const W = w + 2 * P;
|
|
6158
|
+
const H = h + 2 * P;
|
|
6159
|
+
const N = W * H;
|
|
6160
|
+
const inner = (x, y) => Math.min(h - 1, Math.max(0, y - P)) * w + Math.min(w - 1, Math.max(0, x - P));
|
|
6161
|
+
const level = new Uint8Array(N);
|
|
6162
|
+
const lab = new Uint8Array(N);
|
|
6163
|
+
const target = [
|
|
6164
|
+
new Float32Array(N),
|
|
6165
|
+
new Float32Array(N),
|
|
6166
|
+
new Float32Array(N)
|
|
6167
|
+
];
|
|
6168
|
+
const weight2 = [
|
|
6169
|
+
new Float32Array(N),
|
|
6170
|
+
new Float32Array(N),
|
|
6171
|
+
new Float32Array(N)
|
|
6172
|
+
];
|
|
6173
|
+
const smoothObs = obs.map((c) => blur(c, w, h, 2));
|
|
6174
|
+
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
|
6175
|
+
const p = y * W + x;
|
|
6176
|
+
const q = inner(x, y);
|
|
6177
|
+
level[p] = Math.min(levels.length - 1, Math.max(0, Math.round(Math.log(Math.max(.5, Math.min(MAX_WORK_BLUR, sigma[q])) / .5) / Math.log(LEVEL_RATIO))));
|
|
6178
|
+
lab[p] = start[q];
|
|
6179
|
+
const interior = x >= P && y >= P && x < W - P && y < H - P;
|
|
6180
|
+
for (let c = 0; c < 3; c++) {
|
|
6181
|
+
target[c][p] = obs[c][q];
|
|
6182
|
+
weight2[c][p] = interior ? space.shows(Math.max(smoothObs[c][q], 1e-4)) ** 2 : 0;
|
|
6183
|
+
}
|
|
6184
|
+
}
|
|
6185
|
+
const C = palette.map((c) => [
|
|
6186
|
+
space.to(c[0]),
|
|
6187
|
+
space.to(c[1]),
|
|
6188
|
+
space.to(c[2])
|
|
6189
|
+
]);
|
|
6190
|
+
const model = [
|
|
6191
|
+
new Float32Array(N),
|
|
6192
|
+
new Float32Array(N),
|
|
6193
|
+
new Float32Array(N)
|
|
6194
|
+
];
|
|
6195
|
+
const near = new Int32Array((W + 1) * (H + 1));
|
|
6196
|
+
const rebuild = () => {
|
|
6197
|
+
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
|
6198
|
+
const p = y * W + x;
|
|
6199
|
+
const edge = x + 1 < W && lab[p + 1] !== lab[p] || y + 1 < H && lab[p + W] !== lab[p] ? 1 : 0;
|
|
6200
|
+
near[(y + 1) * (W + 1) + x + 1] = edge + near[y * (W + 1) + x + 1] + near[(y + 1) * (W + 1) + x] - near[y * (W + 1) + x];
|
|
6201
|
+
}
|
|
6202
|
+
for (let y = P; y < H - P; y++) for (let x = P; x < W - P; x++) {
|
|
6203
|
+
const p = y * W + x;
|
|
6204
|
+
const { r, k } = levels[level[p]];
|
|
6205
|
+
const x0 = x - r - 1;
|
|
6206
|
+
const y0 = y - r - 1;
|
|
6207
|
+
if (!(near[(y + r + 1) * (W + 1) + x + r + 1] - near[y0 * (W + 1) + x + r + 1] - near[(y + r + 1) * (W + 1) + x0] + near[y0 * (W + 1) + x0])) {
|
|
6208
|
+
const c = C[lab[p]];
|
|
6209
|
+
model[0][p] = c[0];
|
|
6210
|
+
model[1][p] = c[1];
|
|
6211
|
+
model[2][p] = c[2];
|
|
6212
|
+
continue;
|
|
6213
|
+
}
|
|
6214
|
+
let m0 = 0;
|
|
6215
|
+
let m1 = 0;
|
|
6216
|
+
let m2 = 0;
|
|
6217
|
+
let i = 0;
|
|
6218
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
6219
|
+
let q = p + dy * W - r;
|
|
6220
|
+
for (let dx = -r; dx <= r; dx++, q++, i++) {
|
|
6221
|
+
const c = C[lab[q]];
|
|
6222
|
+
const kv = k[i];
|
|
6223
|
+
m0 += kv * c[0];
|
|
6224
|
+
m1 += kv * c[1];
|
|
6225
|
+
m2 += kv * c[2];
|
|
6226
|
+
}
|
|
6227
|
+
}
|
|
6228
|
+
model[0][p] = m0;
|
|
6229
|
+
model[1][p] = m1;
|
|
6230
|
+
model[2][p] = m2;
|
|
6231
|
+
}
|
|
6232
|
+
};
|
|
6233
|
+
rebuild();
|
|
6234
|
+
const shade = [
|
|
6235
|
+
new Float32Array(N),
|
|
6236
|
+
new Float32Array(N),
|
|
6237
|
+
new Float32Array(N)
|
|
6238
|
+
];
|
|
6239
|
+
const q4w = Math.ceil(w / 4);
|
|
6240
|
+
const q4h = Math.ceil(h / 4);
|
|
6241
|
+
const reshade = () => {
|
|
6242
|
+
for (let c = 0; c < 3; c++) {
|
|
6243
|
+
const small = new Float32Array(q4w * q4h);
|
|
6244
|
+
const cnt = new Float32Array(q4w * q4h);
|
|
6245
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6246
|
+
const p = (y + P) * W + x + P;
|
|
6247
|
+
const i = (y >> 2) * q4w + (x >> 2);
|
|
6248
|
+
small[i] += Math.sqrt(weight2[c][p]) * (target[c][p] + shade[c][p] - model[c][p]);
|
|
6249
|
+
cnt[i]++;
|
|
6250
|
+
}
|
|
6251
|
+
for (let i = 0; i < small.length; i++) small[i] /= cnt[i];
|
|
6252
|
+
const low = blur(small, q4w, q4h, SHADE_SIGMA / 4);
|
|
6253
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6254
|
+
const p = (y + P) * W + x + P;
|
|
6255
|
+
const s = sample(low, q4w, q4h, (x - 1.5) / 4, (y - 1.5) / 4) / Math.sqrt(weight2[c][p]);
|
|
6256
|
+
target[c][p] = target[c][p] + shade[c][p] - s;
|
|
6257
|
+
shade[c][p] = s;
|
|
6258
|
+
}
|
|
6259
|
+
}
|
|
6260
|
+
};
|
|
6261
|
+
const scales = [];
|
|
6262
|
+
for (let rho = BOUNDARY_SIGMA;; rho *= 1.25) {
|
|
6263
|
+
const r = Math.ceil(2.5 * rho);
|
|
6264
|
+
const k = new Float32Array((2 * r + 1) ** 2);
|
|
6265
|
+
let sum = 0;
|
|
6266
|
+
for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) sum += k[(dy + r) * (2 * r + 1) + dx + r] = Math.exp(-(dx * dx + dy * dy) / (2 * rho * rho));
|
|
6267
|
+
for (let i = 0; i < k.length; i++) k[i] /= sum;
|
|
6268
|
+
scales.push({
|
|
6269
|
+
r,
|
|
6270
|
+
k,
|
|
6271
|
+
k0: k[r * (2 * r + 1) + r]
|
|
6272
|
+
});
|
|
6273
|
+
if (rho * 1.25 > BOUNDARY_SIGMA_MAX || r >= P) break;
|
|
6274
|
+
}
|
|
6275
|
+
const scaleOf = new Uint8Array(N);
|
|
6276
|
+
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
|
6277
|
+
const rho = BOUNDARY_PER_BLUR * Math.min(MAX_WORK_BLUR, sigma[inner(x, y)]);
|
|
6278
|
+
scaleOf[y * W + x] = Math.min(scales.length - 1, Math.max(0, Math.round(Math.log(Math.max(rho, BOUNDARY_SIGMA) / BOUNDARY_SIGMA) / Math.log(1.25))));
|
|
6279
|
+
}
|
|
6280
|
+
const longer = (p, a, b) => {
|
|
6281
|
+
const { r, k, k0 } = scales[scaleOf[p]];
|
|
6282
|
+
let d = 0;
|
|
6283
|
+
let i = 0;
|
|
6284
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
6285
|
+
let q = p + dy * W - r;
|
|
6286
|
+
for (let dx = -r; dx <= r; dx++, q++, i++) {
|
|
6287
|
+
const l = lab[q];
|
|
6288
|
+
if (l === a) d += k[i];
|
|
6289
|
+
else if (l === b) d -= k[i];
|
|
6290
|
+
}
|
|
6291
|
+
}
|
|
6292
|
+
return 2 * (d - k0);
|
|
6293
|
+
};
|
|
6294
|
+
const owed = new Float32Array(3 * N);
|
|
6295
|
+
const settle = () => {
|
|
6296
|
+
for (let p = 0; p < N; p++) for (let c = 0; c < 3; c++) owed[3 * p + c] = weight2[c][p] * (model[c][p] - target[c][p]);
|
|
6297
|
+
};
|
|
6298
|
+
const spread = (p, d0, d1, d2) => {
|
|
6299
|
+
const r = levels[Math.min(levels.length - 1, level[p] + 2)].r;
|
|
6300
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
6301
|
+
let q = p + dy * W - r;
|
|
6302
|
+
for (let dx = -r; dx <= r; dx++, q++) {
|
|
6303
|
+
const lv = levels[level[q]];
|
|
6304
|
+
const rr = lv.r;
|
|
6305
|
+
if (dx > rr || dx < -rr || dy > rr || dy < -rr) continue;
|
|
6306
|
+
const kv = lv.k[(dy + rr) * (2 * rr + 1) + dx + rr];
|
|
6307
|
+
model[0][q] += kv * d0;
|
|
6308
|
+
model[1][q] += kv * d1;
|
|
6309
|
+
model[2][q] += kv * d2;
|
|
6310
|
+
owed[3 * q] += weight2[0][q] * kv * d0;
|
|
6311
|
+
owed[3 * q + 1] += weight2[1][q] * kv * d1;
|
|
6312
|
+
owed[3 * q + 2] += weight2[2][q] * kv * d2;
|
|
6313
|
+
}
|
|
6314
|
+
}
|
|
6315
|
+
};
|
|
6316
|
+
const repad = () => {
|
|
6317
|
+
const R = levels[levels.length - 1].r;
|
|
6318
|
+
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
|
6319
|
+
if (x >= P && y >= P && x < W - P && y < H - P) {
|
|
6320
|
+
x = W - P - 1;
|
|
6321
|
+
continue;
|
|
6322
|
+
}
|
|
6323
|
+
const p = y * W + x;
|
|
6324
|
+
const a = lab[p];
|
|
6325
|
+
const l = lab[Math.min(H - P - 1, Math.max(P, y)) * W + Math.min(W - P - 1, Math.max(P, x))];
|
|
6326
|
+
if (a === l) continue;
|
|
6327
|
+
lab[p] = l;
|
|
6328
|
+
const d0 = C[l][0] - C[a][0];
|
|
6329
|
+
const d1 = C[l][1] - C[a][1];
|
|
6330
|
+
const d2 = C[l][2] - C[a][2];
|
|
6331
|
+
for (let qy = Math.max(P, y - R); qy <= Math.min(H - P - 1, y + R); qy++) for (let qx = Math.max(P, x - R); qx <= Math.min(W - P - 1, x + R); qx++) {
|
|
6332
|
+
const q = qy * W + qx;
|
|
6333
|
+
const lv = levels[level[q]];
|
|
6334
|
+
const rr = lv.r;
|
|
6335
|
+
const dx = x - qx;
|
|
6336
|
+
const dy = y - qy;
|
|
6337
|
+
if (dx > rr || dx < -rr || dy > rr || dy < -rr) continue;
|
|
6338
|
+
const kv = lv.k[(dy + rr) * (2 * rr + 1) + dx + rr];
|
|
6339
|
+
model[0][q] += kv * d0;
|
|
6340
|
+
model[1][q] += kv * d1;
|
|
6341
|
+
model[2][q] += kv * d2;
|
|
6342
|
+
owed[3 * q] += weight2[0][q] * kv * d0;
|
|
6343
|
+
owed[3 * q + 1] += weight2[1][q] * kv * d1;
|
|
6344
|
+
owed[3 * q + 2] += weight2[2][q] * kv * d2;
|
|
6345
|
+
}
|
|
6346
|
+
}
|
|
6347
|
+
};
|
|
6348
|
+
const steps = [
|
|
6349
|
+
1,
|
|
6350
|
+
-1,
|
|
6351
|
+
W,
|
|
6352
|
+
-W
|
|
6353
|
+
];
|
|
6354
|
+
const inside = w * h;
|
|
6355
|
+
let sweep = 0;
|
|
6356
|
+
const pass = () => {
|
|
6357
|
+
if (sweep % RESHADE === 0) {
|
|
6358
|
+
repad();
|
|
6359
|
+
reshade();
|
|
6360
|
+
settle();
|
|
6361
|
+
}
|
|
6362
|
+
let flips = 0;
|
|
6363
|
+
for (let i = 0; i < inside; i++) {
|
|
6364
|
+
const j = sweep & 1 ? inside - 1 - i : i;
|
|
6365
|
+
const p = (P + Math.floor(j / w)) * W + P + j % w;
|
|
6366
|
+
const a = lab[p];
|
|
6367
|
+
let best = 0;
|
|
6368
|
+
let bestL = -1;
|
|
6369
|
+
let tried = -1;
|
|
6370
|
+
let g0 = 0;
|
|
6371
|
+
let g1 = 0;
|
|
6372
|
+
let g2 = 0;
|
|
6373
|
+
for (let s = 0; s < 4; s++) {
|
|
6374
|
+
const b = lab[p + steps[s]];
|
|
6375
|
+
if (b === a || b === tried || b === bestL) continue;
|
|
6376
|
+
const lv = levels[level[p]];
|
|
6377
|
+
if (tried < 0 && bestL < 0) {
|
|
6378
|
+
const { r, k } = lv;
|
|
6379
|
+
let i = 0;
|
|
6380
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
6381
|
+
let q = 3 * (p + dy * W - r);
|
|
6382
|
+
for (let dx = -r; dx <= r; dx++, q += 3, i++) {
|
|
6383
|
+
const kv = k[i];
|
|
6384
|
+
g0 += kv * owed[q];
|
|
6385
|
+
g1 += kv * owed[q + 1];
|
|
6386
|
+
g2 += kv * owed[q + 2];
|
|
6387
|
+
}
|
|
6388
|
+
}
|
|
6389
|
+
}
|
|
6390
|
+
tried = b;
|
|
6391
|
+
const ca = C[a];
|
|
6392
|
+
const cb = C[b];
|
|
6393
|
+
const d0 = cb[0] - ca[0];
|
|
6394
|
+
const d1 = cb[1] - ca[1];
|
|
6395
|
+
const d2 = cb[2] - ca[2];
|
|
6396
|
+
const dE = 2 * (d0 * g0 + d1 * g1 + d2 * g2) + lv.self * (d0 * d0 * weight2[0][p] + d1 * d1 * weight2[1][p] + d2 * d2 * weight2[2][p]) + BOUNDARY_COST * longer(p, a, b);
|
|
6397
|
+
if (dE < best) best = dE, bestL = b;
|
|
6398
|
+
}
|
|
6399
|
+
if (bestL < 0) continue;
|
|
6400
|
+
lab[p] = bestL;
|
|
6401
|
+
spread(p, C[bestL][0] - C[a][0], C[bestL][1] - C[a][1], C[bestL][2] - C[a][2]);
|
|
6402
|
+
flips++;
|
|
6403
|
+
}
|
|
6404
|
+
return flips;
|
|
6405
|
+
};
|
|
6406
|
+
function* search(sweeps) {
|
|
6407
|
+
for (const end = sweep + sweeps; sweep < end; sweep++) {
|
|
6408
|
+
const flips = pass();
|
|
6409
|
+
yield;
|
|
6410
|
+
if (flips < SETTLED * inside) break;
|
|
6411
|
+
}
|
|
6412
|
+
}
|
|
6413
|
+
yield* search(SWEEPS);
|
|
6414
|
+
const blends = C.map((ca, a) => {
|
|
6415
|
+
const found = [];
|
|
6416
|
+
for (let c = 0; c < C.length; c++) for (let b = c + 1; b < C.length; b++) {
|
|
6417
|
+
if (c === a || b === a) continue;
|
|
6418
|
+
const cc = C[c];
|
|
6419
|
+
const ab = [
|
|
6420
|
+
C[b][0] - cc[0],
|
|
6421
|
+
C[b][1] - cc[1],
|
|
6422
|
+
C[b][2] - cc[2]
|
|
6423
|
+
];
|
|
6424
|
+
const t = ((ca[0] - cc[0]) * ab[0] + (ca[1] - cc[1]) * ab[1] + (ca[2] - cc[2]) * ab[2]) / (ab[0] ** 2 + ab[1] ** 2 + ab[2] ** 2 + 1e-12);
|
|
6425
|
+
const off = 255 * Math.hypot(ca[0] - cc[0] - t * ab[0], ca[1] - cc[1] - t * ab[1], ca[2] - cc[2] - t * ab[2]);
|
|
6426
|
+
if (t >= BLEND_ENDS && t <= .8 && off <= BLEND_OFF) found.push({
|
|
6427
|
+
c,
|
|
6428
|
+
b,
|
|
6429
|
+
t,
|
|
6430
|
+
off
|
|
6431
|
+
});
|
|
6432
|
+
}
|
|
6433
|
+
return found.sort((x, y) => x.off - y.off);
|
|
6434
|
+
});
|
|
6435
|
+
let flipBoundary = 0;
|
|
6436
|
+
const flip = (p, to) => {
|
|
6437
|
+
const a = lab[p];
|
|
6438
|
+
const d0 = C[to][0] - C[a][0];
|
|
6439
|
+
const d1 = C[to][1] - C[a][1];
|
|
6440
|
+
const d2 = C[to][2] - C[a][2];
|
|
6441
|
+
flipBoundary = BOUNDARY_COST * longer(p, a, to);
|
|
6442
|
+
let dE = flipBoundary;
|
|
6443
|
+
const r = levels[Math.min(levels.length - 1, level[p] + 2)].r;
|
|
6444
|
+
for (let dy = -r; dy <= r; dy++) {
|
|
6445
|
+
let q = p + dy * W - r;
|
|
6446
|
+
for (let dx = -r; dx <= r; dx++, q++) {
|
|
6447
|
+
const lv = levels[level[q]];
|
|
6448
|
+
const rr = lv.r;
|
|
6449
|
+
if (dx > rr || dx < -rr || dy > rr || dy < -rr) continue;
|
|
6450
|
+
const kv = lv.k[(dy + rr) * (2 * rr + 1) + dx + rr];
|
|
6451
|
+
dE += kv * (2 * (owed[3 * q] * d0 + owed[3 * q + 1] * d1 + owed[3 * q + 2] * d2) + kv * (weight2[0][q] * d0 * d0 + weight2[1][q] * d1 * d1 + weight2[2][q] * d2 * d2));
|
|
6452
|
+
}
|
|
6453
|
+
}
|
|
6454
|
+
lab[p] = to;
|
|
6455
|
+
spread(p, d0, d1, d2);
|
|
6456
|
+
return dE;
|
|
6457
|
+
};
|
|
6458
|
+
/**
|
|
6459
|
+
* Thin areas of a blend's colour, re-read as the two colours it blends: the
|
|
6460
|
+
* share of the area nearest the one takes it, the rest the other, so the
|
|
6461
|
+
* area keeps its weight. Single flips never get there, since each alone
|
|
6462
|
+
* changes that weight. Two cases, one move: the last sliver of halo between
|
|
6463
|
+
* two colours goes, and a line thinner than the blur (which fades to the
|
|
6464
|
+
* blend's colour, and is first read as a wider line of it) gets its own
|
|
6465
|
+
* colour and width back. Kept only where the total drops.
|
|
6466
|
+
*/
|
|
6467
|
+
const unblend = () => {
|
|
6468
|
+
if (!blends.some((b) => b.length)) return false;
|
|
6469
|
+
const depth = new Uint16Array(N).fill(65535);
|
|
6470
|
+
for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) {
|
|
6471
|
+
const p = y * W + x;
|
|
6472
|
+
const a = lab[p];
|
|
6473
|
+
if (lab[p - 1] !== a || lab[p + 1] !== a || lab[p - W] !== a || lab[p + W] !== a) depth[p] = 1;
|
|
6474
|
+
}
|
|
6475
|
+
for (let p = W + 1; p < N - W - 1; p++) depth[p] = Math.min(depth[p], depth[p - 1] + 1, depth[p - W] + 1);
|
|
6476
|
+
for (let p = N - W - 2; p > W; p--) depth[p] = Math.min(depth[p], depth[p + 1] + 1, depth[p + W] + 1);
|
|
6477
|
+
const done = new Uint8Array(N);
|
|
6478
|
+
const beside = new Float64Array(C.length);
|
|
6479
|
+
const along = new Float32Array(N);
|
|
6480
|
+
let changed = false;
|
|
6481
|
+
let undone = false;
|
|
6482
|
+
for (let y0 = P; y0 < H - P; y0++) for (let x0 = P; x0 < W - P; x0++) {
|
|
6483
|
+
const first = y0 * W + x0;
|
|
6484
|
+
const a = lab[first];
|
|
6485
|
+
if (done[first] || !blends[a].length) continue;
|
|
6486
|
+
const area = [first];
|
|
6487
|
+
done[first] = 1;
|
|
6488
|
+
beside.fill(0);
|
|
6489
|
+
let deepest = 0;
|
|
6490
|
+
let blurSum = 0;
|
|
6491
|
+
let rim = 0;
|
|
6492
|
+
for (let i = 0; i < area.length; i++) {
|
|
6493
|
+
const p = area[i];
|
|
6494
|
+
if (depth[p] > deepest) deepest = depth[p];
|
|
6495
|
+
if (depth[p] === 1) rim++;
|
|
6496
|
+
const x = p % W;
|
|
6497
|
+
const yy = (p - x) / W;
|
|
6498
|
+
blurSum += Math.min(MAX_WORK_BLUR, sigma[inner(x, yy)]);
|
|
6499
|
+
for (const s of steps) {
|
|
6500
|
+
const q = p + s;
|
|
6501
|
+
const qx = q % W;
|
|
6502
|
+
const qy = (q - qx) / W;
|
|
6503
|
+
if (qx < P || qy < P || qx >= W - P || qy >= H - P) continue;
|
|
6504
|
+
if (lab[q] !== a) beside[lab[q]]++;
|
|
6505
|
+
else if (!done[q]) done[q] = 1, area.push(q);
|
|
6506
|
+
}
|
|
6507
|
+
}
|
|
6508
|
+
if (deepest > BLEND_DEPTH * (blurSum / area.length) + 1) continue;
|
|
6509
|
+
const line = rim * rim >= 32 * area.length;
|
|
6510
|
+
let around = 0;
|
|
6511
|
+
for (let l = 0; l < C.length; l++) around += beside[l];
|
|
6512
|
+
const field = BLEND_WITHIN * around;
|
|
6513
|
+
for (const { c, b, t } of blends[a].filter((x) => beside[x.c] && beside[x.b] || line && Math.max(beside[x.c], beside[x.b]) > field).slice(0, 2)) {
|
|
6514
|
+
const ab = [
|
|
6515
|
+
C[b][0] - C[c][0],
|
|
6516
|
+
C[b][1] - C[c][1],
|
|
6517
|
+
C[b][2] - C[c][2]
|
|
6518
|
+
];
|
|
6519
|
+
for (const p of area) along[p] = target[0][p] * ab[0] + target[1][p] * ab[1] + target[2][p] * ab[2];
|
|
6520
|
+
const order = area.slice().sort((p, q) => along[q] - along[p]);
|
|
6521
|
+
const take = Math.round(t * order.length);
|
|
6522
|
+
let dE = 0;
|
|
6523
|
+
for (let i = 0; i < order.length; i++) dE += flip(order[i], i < take ? b : c);
|
|
6524
|
+
if (dE < 0) {
|
|
6525
|
+
changed = true;
|
|
6526
|
+
break;
|
|
6527
|
+
}
|
|
6528
|
+
for (const p of order) flip(p, a);
|
|
6529
|
+
undone = true;
|
|
6530
|
+
}
|
|
6531
|
+
}
|
|
6532
|
+
if (undone) {
|
|
6533
|
+
rebuild();
|
|
6534
|
+
settle();
|
|
6535
|
+
}
|
|
6536
|
+
return changed;
|
|
6537
|
+
};
|
|
6538
|
+
for (let round = 0; round < BLEND_ROUNDS; round++) {
|
|
6539
|
+
repad();
|
|
6540
|
+
if (!unblend()) break;
|
|
6541
|
+
yield* search(BLEND_SWEEPS);
|
|
6542
|
+
}
|
|
6543
|
+
const tryFlips = (ps, to, worth) => {
|
|
6544
|
+
const was = ps.map((p) => lab[p]);
|
|
6545
|
+
let misfit = 0;
|
|
6546
|
+
let boundary = 0;
|
|
6547
|
+
for (const p of ps) {
|
|
6548
|
+
const dE = flip(p, to(p));
|
|
6549
|
+
boundary += flipBoundary;
|
|
6550
|
+
misfit += dE - flipBoundary;
|
|
6551
|
+
}
|
|
6552
|
+
if (misfit + worth * boundary < 0) return true;
|
|
6553
|
+
for (let i = ps.length - 1; i >= 0; i--) flip(ps[i], was[i]);
|
|
6554
|
+
return false;
|
|
6555
|
+
};
|
|
6556
|
+
/**
|
|
6557
|
+
* Slivers taken out: an area nowhere more than two pixels wide, given to
|
|
6558
|
+
* the areas beside it, where the photo barely notices. They are left where
|
|
6559
|
+
* three colours' ramps cross (a thin dark rim between orange trim and white
|
|
6560
|
+
* paper leaves specks of paper colour between the two), and read as gaps.
|
|
6561
|
+
*/
|
|
6562
|
+
const dropSlivers = () => {
|
|
6563
|
+
const done = new Uint8Array(N);
|
|
6564
|
+
let changed = false;
|
|
6565
|
+
const rim = (p) => {
|
|
6566
|
+
const a = lab[p];
|
|
6567
|
+
return lab[p - 1] !== a || lab[p + 1] !== a || lab[p - W] !== a || lab[p + W] !== a;
|
|
6568
|
+
};
|
|
6569
|
+
for (let y0 = P; y0 < H - P; y0++) for (let x0 = P; x0 < W - P; x0++) {
|
|
6570
|
+
const first = y0 * W + x0;
|
|
6571
|
+
if (done[first]) continue;
|
|
6572
|
+
const a = lab[first];
|
|
6573
|
+
const area = [first];
|
|
6574
|
+
done[first] = 1;
|
|
6575
|
+
let thin = true;
|
|
6576
|
+
for (let i = 0; i < area.length; i++) {
|
|
6577
|
+
const p = area[i];
|
|
6578
|
+
if (thin && !rim(p)) thin = false;
|
|
6579
|
+
for (const s of steps) {
|
|
6580
|
+
const q = p + s;
|
|
6581
|
+
const qx = q % W;
|
|
6582
|
+
const qy = (q - qx) / W;
|
|
6583
|
+
if (qx < P || qy < P || qx >= W - P || qy >= H - P || done[q] || lab[q] !== a) continue;
|
|
6584
|
+
done[q] = 1;
|
|
6585
|
+
area.push(q);
|
|
6586
|
+
}
|
|
6587
|
+
}
|
|
6588
|
+
if (!thin) continue;
|
|
6589
|
+
const into = /* @__PURE__ */ new Map();
|
|
6590
|
+
const beside = /* @__PURE__ */ new Set();
|
|
6591
|
+
for (const p of area) {
|
|
6592
|
+
let best = -1;
|
|
6593
|
+
let most = 0;
|
|
6594
|
+
for (const s of steps) {
|
|
6595
|
+
const l = lab[p + s];
|
|
6596
|
+
if (l === a) continue;
|
|
6597
|
+
beside.add(l);
|
|
6598
|
+
let n = 0;
|
|
6599
|
+
for (const t of steps) if (lab[p + t] === l) n++;
|
|
6600
|
+
if (n > most) most = n, best = l;
|
|
6601
|
+
}
|
|
6602
|
+
into.set(p, best);
|
|
6603
|
+
}
|
|
6604
|
+
if (beside.size < 2) continue;
|
|
6605
|
+
if (tryFlips(area, (p) => into.get(p), SLIVER_WORTH)) changed = true;
|
|
6606
|
+
}
|
|
6607
|
+
return changed;
|
|
6608
|
+
};
|
|
6609
|
+
repad();
|
|
6610
|
+
if (dropSlivers()) yield* search(BLEND_SWEEPS);
|
|
6611
|
+
const out = new Uint8Array(w * h);
|
|
6612
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) out[y * w + x] = lab[(y + P) * W + x + P];
|
|
6613
|
+
return out;
|
|
6614
|
+
}
|
|
6615
|
+
/** Work pixels at most: larger pictures are solved at a coarser scale. */
|
|
6616
|
+
const MAX_WORK_PIXELS = 42e4;
|
|
6617
|
+
/** The picture is shrunk until its sharper quarter is no more blurred than this, in work px: a wider blur costs its square in time and gains nothing. */
|
|
6618
|
+
const MAX_SHARP_BLUR = 2.2;
|
|
6619
|
+
/**
|
|
6620
|
+
* A copy of `rgba` (`width` × `height`, RGBA) with its blur taken out: flat
|
|
6621
|
+
* colours with clean, anti-aliased edges where the image had soft ramps.
|
|
6622
|
+
* `blur` is how soft its edges are (`edgeBlur`, measured when left out);
|
|
6623
|
+
* below `SOFT_EDGES` the image is only copied. `scale` is how many times the
|
|
6624
|
+
* image was enlarged before this: enlarging softens edges by as much, so the
|
|
6625
|
+
* threshold grows with it. Alpha is kept as it is.
|
|
6626
|
+
*/
|
|
6627
|
+
function deblur(rgba, width, height, blurPx, scale = 1) {
|
|
6628
|
+
const steps = deblurSteps(rgba, width, height, blurPx, scale);
|
|
6629
|
+
for (;;) {
|
|
6630
|
+
const r = steps.next();
|
|
6631
|
+
if (r.done) return r.value;
|
|
6632
|
+
}
|
|
6633
|
+
}
|
|
6634
|
+
/** `deblur` as steps: it pauses between its stages and after each sweep of the search (a tenth of a second or so apart on a megapixel image), so an async caller can stop it or let other work in. */
|
|
6635
|
+
function* deblurSteps(rgba, width, height, blurPx, scale = 1) {
|
|
6636
|
+
const out = Uint8ClampedArray.from(rgba);
|
|
6637
|
+
const n = width * height;
|
|
6638
|
+
if (width < 16 || height < 16) return out;
|
|
6639
|
+
const src = fillTransparent(out, width, height);
|
|
6640
|
+
let ch = [
|
|
6641
|
+
new Float32Array(n),
|
|
6642
|
+
new Float32Array(n),
|
|
6643
|
+
new Float32Array(n)
|
|
6644
|
+
];
|
|
6645
|
+
for (let p = 0; p < n; p++) {
|
|
6646
|
+
ch[0][p] = src[p * 4];
|
|
6647
|
+
ch[1][p] = src[p * 4 + 1];
|
|
6648
|
+
ch[2][p] = src[p * 4 + 2];
|
|
6649
|
+
}
|
|
6650
|
+
const lumOf = (space) => {
|
|
6651
|
+
const lum = new Float32Array(n);
|
|
6652
|
+
for (let p = 0; p < n; p++) lum[p] = 255 * (.2126 * space.to(ch[0][p]) + .7152 * space.to(ch[1][p]) + .0722 * space.to(ch[2][p]));
|
|
6653
|
+
return lum;
|
|
6654
|
+
};
|
|
6655
|
+
let stored = lumOf(STORED);
|
|
6656
|
+
let map = measureBlur(stored, width, height);
|
|
6657
|
+
if (!(map.median > 0) || (blurPx ?? map.median) < 1.5 * Math.max(1, scale)) return out;
|
|
6658
|
+
yield;
|
|
6659
|
+
const aligned = alignChannels(ch, width, height, map.median);
|
|
6660
|
+
if (aligned) {
|
|
6661
|
+
ch = aligned;
|
|
6662
|
+
stored = lumOf(STORED);
|
|
6663
|
+
}
|
|
6664
|
+
const space = blurredAsLight(stored, width, height) ? LIGHT : STORED;
|
|
6665
|
+
if (aligned || space === LIGHT) map = measureBlur(space === LIGHT ? lumOf(LIGHT) : stored, width, height);
|
|
6666
|
+
if (!(map.median > 0)) return out;
|
|
6667
|
+
yield;
|
|
6668
|
+
const blurs = [];
|
|
6669
|
+
for (let y = 4; y < height; y += 8) for (let x = 4; x < width; x += 8) blurs.push(map.at(x, y));
|
|
6670
|
+
blurs.sort((a, b) => a - b);
|
|
6671
|
+
let F = Math.min(4, Math.max(1, Math.floor(blurs[blurs.length >> 2] / MAX_SHARP_BLUR)));
|
|
6672
|
+
while (Math.ceil(width / F) * Math.ceil(height / F) > MAX_WORK_PIXELS) F++;
|
|
6673
|
+
const w = Math.ceil(width / F);
|
|
6674
|
+
const h = Math.ceil(height / F);
|
|
6675
|
+
const obs = [
|
|
6676
|
+
new Float32Array(w * h),
|
|
6677
|
+
new Float32Array(w * h),
|
|
6678
|
+
new Float32Array(w * h)
|
|
6679
|
+
];
|
|
6680
|
+
const sigma = new Float32Array(w * h);
|
|
6681
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6682
|
+
let cnt = 0;
|
|
6683
|
+
let a0 = 0;
|
|
6684
|
+
let a1 = 0;
|
|
6685
|
+
let a2 = 0;
|
|
6686
|
+
for (let yy = y * F; yy < Math.min(height, (y + 1) * F); yy++) for (let xx = x * F; xx < Math.min(width, (x + 1) * F); xx++) {
|
|
6687
|
+
const p = yy * width + xx;
|
|
6688
|
+
a0 += space.to(ch[0][p]);
|
|
6689
|
+
a1 += space.to(ch[1][p]);
|
|
6690
|
+
a2 += space.to(ch[2][p]);
|
|
6691
|
+
cnt++;
|
|
6692
|
+
}
|
|
6693
|
+
const i = y * w + x;
|
|
6694
|
+
obs[0][i] = a0 / cnt;
|
|
6695
|
+
obs[1][i] = a1 / cnt;
|
|
6696
|
+
obs[2][i] = a2 / cnt;
|
|
6697
|
+
sigma[i] = Math.max(.3, map.at((x + .5) * F, (y + .5) * F) / F);
|
|
6698
|
+
}
|
|
6699
|
+
const seen = obs.map((c) => Float32Array.from(c, (v) => 255 * space.back(v)));
|
|
6700
|
+
const palette = flatColours(seen, w, h);
|
|
6701
|
+
if (palette.length < 2) return out;
|
|
6702
|
+
const start = new Uint8Array(w * h);
|
|
6703
|
+
for (let p = 0; p < w * h; p++) {
|
|
6704
|
+
let best = 0;
|
|
6705
|
+
let bestD = 1e400;
|
|
6706
|
+
for (let k = 0; k < palette.length; k++) {
|
|
6707
|
+
const d = (seen[0][p] - palette[k][0]) ** 2 + (seen[1][p] - palette[k][1]) ** 2 + (seen[2][p] - palette[k][2]) ** 2;
|
|
6708
|
+
if (d < bestD) bestD = d, best = k;
|
|
6709
|
+
}
|
|
6710
|
+
start[p] = best;
|
|
6711
|
+
}
|
|
6712
|
+
const kept = dropShades(seen, w, h, sigma, palette, start);
|
|
6713
|
+
if (kept.length < 2) return out;
|
|
6714
|
+
yield;
|
|
6715
|
+
const labels = yield* solve(obs, w, h, sigma, kept, start, space);
|
|
6716
|
+
const edges = boundaries(labels, w, h, sigma);
|
|
6717
|
+
yield;
|
|
6718
|
+
redraw(labels, w, h, kept, F, edges, out, width, height);
|
|
6719
|
+
return out;
|
|
6720
|
+
}
|
|
6721
|
+
/** A boundary's points are smoothed by as much as moves each no further than this share of the blur there (work px)… */
|
|
6722
|
+
const SMOOTH_PER_BLUR = .6;
|
|
6723
|
+
/** …nor than this share of the width of the thinner area beside it, which must not be pinched… */
|
|
6724
|
+
const SMOOTH_PER_WIDTH = .4;
|
|
6725
|
+
/** …but any point may move this far (work px), or the steps of a slant would stay. */
|
|
6726
|
+
const SMOOTH_MIN = .75;
|
|
6727
|
+
/** …and none by an amount that pulls the path there, wobble aside, by more than this (work px): a bend is pulled inwards, and what is put back for it swings wide beside a sharp turn. */
|
|
6728
|
+
const SMOOTH_PULL = .5;
|
|
6729
|
+
/** Areas this deep (work px) or deeper are not thin. */
|
|
6730
|
+
const THIN_REACH = 5;
|
|
6731
|
+
/** The amounts of smoothing tried (px along the boundary), and how fast the amount may change from point to point (steps of that list). */
|
|
6732
|
+
const SMOOTH_LEVELS = [
|
|
6733
|
+
1.5,
|
|
6734
|
+
3,
|
|
6735
|
+
6,
|
|
6736
|
+
12,
|
|
6737
|
+
24
|
|
6738
|
+
];
|
|
6739
|
+
const SMOOTH_EASE = .25;
|
|
6740
|
+
/** A boundary has a corner where it turns by this much (radians) between the stretches of this many points before and after. */
|
|
6741
|
+
const CORNER_TURN = .6;
|
|
6742
|
+
const CORNER_SPAN = 5;
|
|
6743
|
+
/** The stretches either side of a corner are straight: their points lie this near a line (work px, root mean square). */
|
|
6744
|
+
const CORNER_STRAIGHT = .5;
|
|
6745
|
+
/** Where those lines meet is the corner, if no further from the turn than the blur there and this (work px). */
|
|
6746
|
+
const CORNER_REACH = .75;
|
|
6747
|
+
/**
|
|
6748
|
+
* Every boundary of the label map (w × h), smoothed. The search leaves each
|
|
6749
|
+
* one wobbling by a pixel or two: a photo of print has a texture of its own,
|
|
6750
|
+
* which ripples every edge, and a map of square pixels steps along every
|
|
6751
|
+
* slant. Under a blur the photo says little about where exactly an edge runs,
|
|
6752
|
+
* so each boundary between two areas, from one meeting of three to the next,
|
|
6753
|
+
* is smoothed along its length: every point by as much as moves it no further
|
|
6754
|
+
* than a share of the blur there, and less beside a thin area, which must not
|
|
6755
|
+
* be pinched. A straight edge comes out straight and an arc smooth.
|
|
6756
|
+
*
|
|
6757
|
+
* A boundary is first cut at its corners, each side to be smoothed on its
|
|
6758
|
+
* own, and a corner is put where its two sides, run on, would meet: the
|
|
6759
|
+
* search rounds corners off. So a returned boundary's smoothed ends need not
|
|
6760
|
+
* be its stepped ones, and one closed boundary may come back in parts.
|
|
6761
|
+
*
|
|
6762
|
+
* Last, a stretch that a line fits as closely as its points may move is
|
|
6763
|
+
* drawn as that line (`straightRuns`), and two such lines meet where they
|
|
6764
|
+
* cross: smoothing leaves a slow wobble in, and a line has none.
|
|
6765
|
+
*/
|
|
6766
|
+
function boundaries(lab, w, h, sigma) {
|
|
6767
|
+
const at = (x, y) => lab[y * w + x];
|
|
6768
|
+
const across = (x, y) => x >= 0 && x < w && y >= 1 && y < h && at(x, y - 1) !== at(x, y);
|
|
6769
|
+
const down = (x, y) => x >= 1 && x < w && y >= 0 && y < h && at(x - 1, y) !== at(x, y);
|
|
6770
|
+
const seenAcross = new Uint8Array(w * (h + 1));
|
|
6771
|
+
const seenDown = new Uint8Array((w + 1) * h);
|
|
6772
|
+
const leaves = (x, y, d) => d === 0 ? across(x, y) : d === 1 ? down(x, y) : d === 2 ? across(x - 1, y) : down(x, y - 1);
|
|
6773
|
+
const degree = (x, y) => (leaves(x, y, 0) ? 1 : 0) + (leaves(x, y, 1) ? 1 : 0) + (leaves(x, y, 2) ? 1 : 0) + (leaves(x, y, 3) ? 1 : 0);
|
|
6774
|
+
const DX = [
|
|
6775
|
+
1,
|
|
6776
|
+
0,
|
|
6777
|
+
-1,
|
|
6778
|
+
0
|
|
6779
|
+
];
|
|
6780
|
+
const DY = [
|
|
6781
|
+
0,
|
|
6782
|
+
1,
|
|
6783
|
+
0,
|
|
6784
|
+
-1
|
|
6785
|
+
];
|
|
6786
|
+
const mark = (x, y, d) => {
|
|
6787
|
+
const seen = d === 0 || d === 2 ? seenAcross : seenDown;
|
|
6788
|
+
const i = d === 0 ? y * w + x : d === 2 ? y * w + x - 1 : d === 1 ? y * (w + 1) + x : (y - 1) * (w + 1) + x;
|
|
6789
|
+
if (seen[i]) return false;
|
|
6790
|
+
seen[i] = 1;
|
|
6791
|
+
return true;
|
|
6792
|
+
};
|
|
6793
|
+
const depth = new Uint16Array(w * h).fill(65535);
|
|
6794
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6795
|
+
const p = y * w + x;
|
|
6796
|
+
const l = lab[p];
|
|
6797
|
+
if (x > 0 && lab[p - 1] !== l || x + 1 < w && lab[p + 1] !== l || y > 0 && lab[p - w] !== l || y + 1 < h && lab[p + w] !== l) depth[p] = 1;
|
|
6798
|
+
}
|
|
6799
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
6800
|
+
const p = y * w + x;
|
|
6801
|
+
if (x > 0) depth[p] = Math.min(depth[p], depth[p - 1] + 1);
|
|
6802
|
+
if (y > 0) depth[p] = Math.min(depth[p], depth[p - w] + 1);
|
|
6803
|
+
}
|
|
6804
|
+
for (let y = h - 1; y >= 0; y--) for (let x = w - 1; x >= 0; x--) {
|
|
6805
|
+
const p = y * w + x;
|
|
6806
|
+
if (x + 1 < w) depth[p] = Math.min(depth[p], depth[p + 1] + 1);
|
|
6807
|
+
if (y + 1 < h) depth[p] = Math.min(depth[p], depth[p + w] + 1);
|
|
6808
|
+
}
|
|
6809
|
+
const half = (x, y) => {
|
|
6810
|
+
const cx = Math.min(w - 1, Math.max(0, x));
|
|
6811
|
+
const cy = Math.min(h - 1, Math.max(0, y));
|
|
6812
|
+
const l = at(cx, cy);
|
|
6813
|
+
let most = 1;
|
|
6814
|
+
for (let yy = Math.max(0, cy - THIN_REACH); yy <= Math.min(h - 1, cy + THIN_REACH); yy++) for (let xx = Math.max(0, cx - THIN_REACH); xx <= Math.min(w - 1, cx + THIN_REACH); xx++) if (lab[yy * w + xx] === l && depth[yy * w + xx] > most) most = depth[yy * w + xx];
|
|
6815
|
+
return Math.min(most, THIN_REACH);
|
|
6816
|
+
};
|
|
6817
|
+
const found = [];
|
|
6818
|
+
const walk = (x, y, d) => {
|
|
6819
|
+
if (!mark(x, y, d)) return;
|
|
6820
|
+
const [a, b] = d === 0 ? [at(x, y - 1), at(x, y)] : d === 2 ? [at(x - 1, y - 1), at(x - 1, y)] : d === 1 ? [at(x - 1, y), at(x, y)] : [at(x - 1, y - 1), at(x, y - 1)];
|
|
6821
|
+
const xs = [x];
|
|
6822
|
+
const ys = [y];
|
|
6823
|
+
const x0 = x;
|
|
6824
|
+
const y0 = y;
|
|
6825
|
+
for (;;) {
|
|
6826
|
+
x += DX[d];
|
|
6827
|
+
y += DY[d];
|
|
6828
|
+
xs.push(x);
|
|
6829
|
+
ys.push(y);
|
|
6830
|
+
if (x === x0 && y === y0 || degree(x, y) !== 2) break;
|
|
6831
|
+
let next = -1;
|
|
6832
|
+
for (let e = 0; e < 4; e++) if (e !== (d + 2) % 4 && leaves(x, y, e)) next = e;
|
|
6833
|
+
if (next < 0 || !mark(x, y, next)) break;
|
|
6834
|
+
d = next;
|
|
6835
|
+
}
|
|
6836
|
+
found.push({
|
|
6837
|
+
xs,
|
|
6838
|
+
ys,
|
|
6839
|
+
nx: Float32Array.from(xs),
|
|
6840
|
+
ny: Float32Array.from(ys),
|
|
6841
|
+
a,
|
|
6842
|
+
b
|
|
6843
|
+
});
|
|
6844
|
+
};
|
|
6845
|
+
for (let pass = 0; pass < 2; pass++) for (let y = 0; y <= h; y++) for (let x = 0; x <= w; x++) {
|
|
6846
|
+
const deg = degree(x, y);
|
|
6847
|
+
if (!deg || pass === 0 && deg === 2) continue;
|
|
6848
|
+
for (let d = 0; d < 4; d++) if (leaves(x, y, d)) walk(x, y, d);
|
|
6849
|
+
}
|
|
6850
|
+
const parts = [];
|
|
6851
|
+
const step = gauss1(1.5);
|
|
6852
|
+
const sr = step.length - 1 >> 1;
|
|
6853
|
+
const D = CORNER_SPAN;
|
|
6854
|
+
for (const e of found) {
|
|
6855
|
+
const n = e.xs.length - 1;
|
|
6856
|
+
const closed = e.xs[0] === e.xs[n] && e.ys[0] === e.ys[n];
|
|
6857
|
+
if (n < 20) {
|
|
6858
|
+
parts.push(e);
|
|
6859
|
+
continue;
|
|
6860
|
+
}
|
|
6861
|
+
const pick = (v, k) => closed ? v[(k % n + n) % n] : v[Math.min(n, Math.max(0, k))];
|
|
6862
|
+
const px = new Float32Array(n + 1);
|
|
6863
|
+
const py = new Float32Array(n + 1);
|
|
6864
|
+
for (let k = 0; k <= n; k++) for (let t = -sr; t <= sr; t++) {
|
|
6865
|
+
px[k] += step[t + sr] * pick(e.xs, k + t);
|
|
6866
|
+
py[k] += step[t + sr] * pick(e.ys, k + t);
|
|
6867
|
+
}
|
|
6868
|
+
const turn = new Float32Array(n + 1);
|
|
6869
|
+
for (let k = closed ? 0 : D; k <= (closed ? n - 1 : n - D); k++) {
|
|
6870
|
+
const ux = px[k] - pick(px, k - D);
|
|
6871
|
+
const uy = py[k] - pick(py, k - D);
|
|
6872
|
+
const vx = pick(px, k + D) - px[k];
|
|
6873
|
+
const vy = pick(py, k + D) - py[k];
|
|
6874
|
+
turn[k] = Math.abs(Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy));
|
|
6875
|
+
}
|
|
6876
|
+
if (closed) turn[n] = turn[0];
|
|
6877
|
+
const line = (from, to) => {
|
|
6878
|
+
let mx = 0;
|
|
6879
|
+
let my = 0;
|
|
6880
|
+
const c = to - from + 1;
|
|
6881
|
+
for (let j = from; j <= to; j++) mx += pick(e.xs, j), my += pick(e.ys, j);
|
|
6882
|
+
mx /= c;
|
|
6883
|
+
my /= c;
|
|
6884
|
+
let xx = 0;
|
|
6885
|
+
let xy = 0;
|
|
6886
|
+
let yy = 0;
|
|
6887
|
+
for (let j = from; j <= to; j++) {
|
|
6888
|
+
const dx = pick(e.xs, j) - mx;
|
|
6889
|
+
const dy = pick(e.ys, j) - my;
|
|
6890
|
+
xx += dx * dx;
|
|
6891
|
+
xy += dx * dy;
|
|
6892
|
+
yy += dy * dy;
|
|
6893
|
+
}
|
|
6894
|
+
const angle = .5 * Math.atan2(2 * xy, xx - yy);
|
|
6895
|
+
const dx = Math.cos(angle);
|
|
6896
|
+
const dy = Math.sin(angle);
|
|
6897
|
+
return {
|
|
6898
|
+
mx,
|
|
6899
|
+
my,
|
|
6900
|
+
dx,
|
|
6901
|
+
dy,
|
|
6902
|
+
off: Math.sqrt(Math.max(0, xx * dy * dy - 2 * xy * dx * dy + yy * dx * dx) / c)
|
|
6903
|
+
};
|
|
6904
|
+
};
|
|
6905
|
+
const side = (k, dir) => {
|
|
6906
|
+
for (let far = 15; far >= 10; far -= D) {
|
|
6907
|
+
const from = dir < 0 ? k - far : k + D;
|
|
6908
|
+
const to = dir < 0 ? k - D : k + far;
|
|
6909
|
+
if (!closed && (from < 0 || to > n)) continue;
|
|
6910
|
+
const l = line(from, to);
|
|
6911
|
+
if (l.off <= CORNER_STRAIGHT) return l;
|
|
6912
|
+
}
|
|
6913
|
+
return null;
|
|
6914
|
+
};
|
|
6915
|
+
const corners = [];
|
|
6916
|
+
const tips = [];
|
|
6917
|
+
for (let k = closed ? 0 : D; k <= (closed ? n - 1 : n - D); k++) {
|
|
6918
|
+
const t = turn[k];
|
|
6919
|
+
if (t < CORNER_TURN || 2 * Math.max(pick(turn, k - 10), pick(turn, k + 10)) > t) continue;
|
|
6920
|
+
let most = true;
|
|
6921
|
+
for (let j = 1; j <= D && most; j++) if (pick(turn, k - j) >= t || pick(turn, k + j) > t) most = false;
|
|
6922
|
+
if (!most) continue;
|
|
6923
|
+
const p = side(k, -1);
|
|
6924
|
+
const q = side(k, 1);
|
|
6925
|
+
if (!p || !q) continue;
|
|
6926
|
+
const cross = p.dx * q.dy - p.dy * q.dx;
|
|
6927
|
+
if (Math.abs(cross) < .2) continue;
|
|
6928
|
+
const along = ((q.mx - p.mx) * q.dy - (q.my - p.my) * q.dx) / cross;
|
|
6929
|
+
const tx = p.mx + along * p.dx;
|
|
6930
|
+
const ty = p.my + along * p.dy;
|
|
6931
|
+
const blurred = Math.min(MAX_WORK_BLUR, sigma[Math.min(h - 1, e.ys[k]) * w + Math.min(w - 1, e.xs[k])]);
|
|
6932
|
+
if (Math.hypot(tx - e.xs[k], ty - e.ys[k]) > CORNER_REACH + blurred) continue;
|
|
6933
|
+
corners.push(k);
|
|
6934
|
+
tips.push([tx, ty]);
|
|
6935
|
+
}
|
|
6936
|
+
if (!corners.length) {
|
|
6937
|
+
parts.push(e);
|
|
6938
|
+
continue;
|
|
6939
|
+
}
|
|
6940
|
+
const xs = closed ? [...e.xs.slice(corners[0], n), ...e.xs.slice(0, corners[0] + 1)] : e.xs;
|
|
6941
|
+
const ys = closed ? [...e.ys.slice(corners[0], n), ...e.ys.slice(0, corners[0] + 1)] : e.ys;
|
|
6942
|
+
const cuts = closed ? [...corners.map((c) => c - corners[0]), n] : [
|
|
6943
|
+
0,
|
|
6944
|
+
...corners,
|
|
6945
|
+
n
|
|
6946
|
+
];
|
|
6947
|
+
const ends = closed ? [...tips, tips[0]] : [
|
|
6948
|
+
null,
|
|
6949
|
+
...tips,
|
|
6950
|
+
null
|
|
6951
|
+
];
|
|
6952
|
+
const made = [];
|
|
6953
|
+
for (let i = 0; i + 1 < cuts.length; i++) {
|
|
6954
|
+
const x = xs.slice(cuts[i], cuts[i + 1] + 1);
|
|
6955
|
+
const y = ys.slice(cuts[i], cuts[i + 1] + 1);
|
|
6956
|
+
const nx = Float32Array.from(x);
|
|
6957
|
+
const ny = Float32Array.from(y);
|
|
6958
|
+
const first = ends[i];
|
|
6959
|
+
const last = ends[i + 1];
|
|
6960
|
+
if (first) nx[0] = first[0], ny[0] = first[1];
|
|
6961
|
+
if (last) nx[x.length - 1] = last[0], ny[x.length - 1] = last[1];
|
|
6962
|
+
made.push({
|
|
6963
|
+
xs: x,
|
|
6964
|
+
ys: y,
|
|
6965
|
+
nx,
|
|
6966
|
+
ny,
|
|
6967
|
+
a: e.a,
|
|
6968
|
+
b: e.b,
|
|
6969
|
+
cut: true
|
|
6970
|
+
});
|
|
6971
|
+
}
|
|
6972
|
+
for (let i = 0; i < made.length; i++) if (ends[i + 1]) made[i].next = made[(i + 1) % made.length];
|
|
6973
|
+
parts.push(...made);
|
|
6974
|
+
}
|
|
6975
|
+
for (const part of parts) {
|
|
6976
|
+
const { xs, ys, nx, ny, cut } = part;
|
|
6977
|
+
const n = xs.length - 1;
|
|
6978
|
+
const closed = !cut && xs[0] === xs[n] && ys[0] === ys[n];
|
|
6979
|
+
const past = (v, k) => {
|
|
6980
|
+
if (closed) return v[(k % n + n) % n];
|
|
6981
|
+
let base = 0;
|
|
6982
|
+
let sign = 1;
|
|
6983
|
+
while (k < 0 || k > n) {
|
|
6984
|
+
base += sign * 2 * (k < 0 ? v[0] : v[n]);
|
|
6985
|
+
k = k < 0 ? -k : 2 * n - k;
|
|
6986
|
+
sign = -sign;
|
|
6987
|
+
}
|
|
6988
|
+
return base + sign * v[k];
|
|
6989
|
+
};
|
|
6990
|
+
const ix = Float32Array.from(nx);
|
|
6991
|
+
const iy = Float32Array.from(ny);
|
|
6992
|
+
const eps = new Float32Array(n + 1);
|
|
6993
|
+
for (let k = 0; k <= n; k++) {
|
|
6994
|
+
const x = xs[k];
|
|
6995
|
+
const y = ys[k];
|
|
6996
|
+
const s = Math.min(MAX_WORK_BLUR, sigma[Math.min(h - 1, y) * w + Math.min(w - 1, x)]);
|
|
6997
|
+
const thin = Math.min(half(x - 1, y - 1), half(x, y - 1), half(x - 1, y), half(x, y));
|
|
6998
|
+
eps[k] = Math.max(SMOOTH_MIN, Math.min(SMOOTH_PER_BLUR * s, SMOOTH_PER_WIDTH * (2 * thin - 1)));
|
|
6999
|
+
}
|
|
7000
|
+
const level = new Float32Array(n + 1);
|
|
7001
|
+
const sx = [];
|
|
7002
|
+
const sy = [];
|
|
7003
|
+
const open = new Uint8Array(n + 1).fill(1);
|
|
7004
|
+
for (let li = 0; li < SMOOTH_LEVELS.length; li++) {
|
|
7005
|
+
const along = SMOOTH_LEVELS[li];
|
|
7006
|
+
if (along > n / 2) break;
|
|
7007
|
+
const k1 = gauss1(along);
|
|
7008
|
+
const r = k1.length - 1 >> 1;
|
|
7009
|
+
const smooth = (v) => {
|
|
7010
|
+
const o = new Float32Array(n + 1);
|
|
7011
|
+
for (let k = 0; k <= n; k++) {
|
|
7012
|
+
let a = 0;
|
|
7013
|
+
for (let t = -r; t <= r; t++) a += k1[t + r] * past(v, k + t);
|
|
7014
|
+
o[k] = a;
|
|
7015
|
+
}
|
|
7016
|
+
return o;
|
|
7017
|
+
};
|
|
7018
|
+
const ox = smooth(ix);
|
|
7019
|
+
const oy = smooth(iy);
|
|
7020
|
+
const ox2 = smooth(ox);
|
|
7021
|
+
const oy2 = smooth(oy);
|
|
7022
|
+
for (let k = 0; k <= n; k++) {
|
|
7023
|
+
const pull = Math.hypot(ox[k] - ox2[k], oy[k] - oy2[k]);
|
|
7024
|
+
const ax = ox[k] = 2 * ox[k] - ox2[k];
|
|
7025
|
+
const ay = oy[k] = 2 * oy[k] - oy2[k];
|
|
7026
|
+
if (!open[k]) continue;
|
|
7027
|
+
if (li > 0 && pull > SMOOTH_PULL) {
|
|
7028
|
+
open[k] = 0;
|
|
7029
|
+
continue;
|
|
7030
|
+
}
|
|
7031
|
+
if (li === 0 || Math.hypot(ax - sx[0][k], ay - sy[0][k]) <= eps[k]) level[k] = li + 1;
|
|
7032
|
+
else open[k] = 0;
|
|
7033
|
+
}
|
|
7034
|
+
sx.push(ox);
|
|
7035
|
+
sy.push(oy);
|
|
7036
|
+
}
|
|
7037
|
+
if (!sx.length) continue;
|
|
7038
|
+
for (let round = 0; round < (closed ? 2 : 1); round++) {
|
|
7039
|
+
for (let k = 1; k <= n; k++) level[k] = Math.min(level[k], level[k - 1] + SMOOTH_EASE);
|
|
7040
|
+
for (let k = n - 1; k >= 0; k--) level[k] = Math.min(level[k], level[k + 1] + SMOOTH_EASE);
|
|
7041
|
+
if (closed) level[0] = level[n] = Math.min(level[0], level[n]);
|
|
7042
|
+
}
|
|
7043
|
+
for (let k = 0; k <= n; k++) {
|
|
7044
|
+
const lv = level[k];
|
|
7045
|
+
if (lv <= 0) continue;
|
|
7046
|
+
const lo = Math.floor(lv);
|
|
7047
|
+
const f = lv - lo;
|
|
7048
|
+
const x0 = lo ? sx[lo - 1][k] : ix[k];
|
|
7049
|
+
const y0 = lo ? sy[lo - 1][k] : iy[k];
|
|
7050
|
+
const x1 = lo < sx.length ? sx[lo][k] : x0;
|
|
7051
|
+
const y1 = lo < sy.length ? sy[lo][k] : y0;
|
|
7052
|
+
nx[k] = x0 + f * (x1 - x0);
|
|
7053
|
+
ny[k] = y0 + f * (y1 - y0);
|
|
7054
|
+
}
|
|
7055
|
+
part.runs = straightRuns(sx[0], sy[0], eps);
|
|
7056
|
+
}
|
|
7057
|
+
for (const part of parts) {
|
|
7058
|
+
const p = part.runs?.at(-1);
|
|
7059
|
+
const q = part.next?.runs?.[0];
|
|
7060
|
+
if (!p || !q || p.to !== part.xs.length - 1 || q.from !== 0) continue;
|
|
7061
|
+
const v = crossing(p, q);
|
|
7062
|
+
if (!v || Math.hypot(v[0] - part.nx[p.to], v[1] - part.ny[p.to]) > LINE_MEET) continue;
|
|
7063
|
+
p.last = q.first = v;
|
|
7064
|
+
}
|
|
7065
|
+
for (const part of parts) if (part.runs) drawRuns(part.runs, part.nx, part.ny);
|
|
7066
|
+
return parts;
|
|
7067
|
+
}
|
|
7068
|
+
/** A straight run of a boundary is at least this many points long… */
|
|
7069
|
+
const LINE_MIN = 16;
|
|
7070
|
+
/** …and bows off its line by no more than this (work px) from end to end: a wobble about a line is a line, a gentle arc is not. */
|
|
7071
|
+
const LINE_BOW = .25;
|
|
7072
|
+
/** Two runs that meet at less than this angle (radians) are a bend drawn as chords: the shorter is no line, nor the longer unless twice its length. At more, they meet in a corner. */
|
|
7073
|
+
const LINE_KINK = .3;
|
|
7074
|
+
/** …or at any angle, if either bows this far (work px) the way they turn. */
|
|
7075
|
+
const LINE_ARC = .12;
|
|
7076
|
+
/** Two runs are neighbours when no more than this many points lie between them: a bend the search rounded off. */
|
|
7077
|
+
const LINE_GAP = 12;
|
|
7078
|
+
/** Either side of a corner, the runs' lines may put it this far (work px) from where it was first put. */
|
|
7079
|
+
const LINE_MEET = 1.5;
|
|
7080
|
+
/** Points over which a run's loose end eases back into the smoothed path. */
|
|
7081
|
+
const LINE_EASE = 6;
|
|
7082
|
+
/**
|
|
7083
|
+
* The straight runs of one boundary. Smoothing takes out a wobble shorter
|
|
7084
|
+
* than it reaches; a slow one, a pixel or two over a hundred, it leaves, and
|
|
7085
|
+
* under a heavy blur the search draws a straight side lumpy. But where a line
|
|
7086
|
+
* lies as near the boundary's points (`dx`, `dy`: the path with only its
|
|
7087
|
+
* pixel steps off) as each may move (`eps`), a line is the simplest thing the
|
|
7088
|
+
* photo allows. The longest such run is taken first, then the longest either
|
|
7089
|
+
* side of it. Each run's line is the best through its own points, which
|
|
7090
|
+
* places it better than either of its ends is placed.
|
|
7091
|
+
*/
|
|
7092
|
+
function straightRuns(dx, dy, eps) {
|
|
7093
|
+
const n = dx.length - 1;
|
|
7094
|
+
if (n < LINE_MIN) return [];
|
|
7095
|
+
const within = (r, bow) => {
|
|
7096
|
+
let s2 = 0;
|
|
7097
|
+
let s4 = 0;
|
|
7098
|
+
let d0 = 0;
|
|
7099
|
+
let d2 = 0;
|
|
7100
|
+
let lo = 1e400;
|
|
7101
|
+
let hi = -1e400;
|
|
7102
|
+
for (let k = r.from; k <= r.to; k++) {
|
|
7103
|
+
const px = dx[k] - r.mx;
|
|
7104
|
+
const py = dy[k] - r.my;
|
|
7105
|
+
const d = py * r.ux - px * r.uy;
|
|
7106
|
+
if (Math.abs(d) > eps[k]) return null;
|
|
7107
|
+
const t = px * r.ux + py * r.uy;
|
|
7108
|
+
s2 += t * t;
|
|
7109
|
+
s4 += t * t * t * t;
|
|
7110
|
+
d0 += d;
|
|
7111
|
+
d2 += d * t * t;
|
|
7112
|
+
if (t < lo) lo = t;
|
|
7113
|
+
if (t > hi) hi = t;
|
|
7114
|
+
}
|
|
7115
|
+
if (!bow) return r;
|
|
7116
|
+
const c = r.to - r.from + 1;
|
|
7117
|
+
const spread = s4 - s2 * s2 / c;
|
|
7118
|
+
if (!(spread > 0) || hi - lo < .6 * LINE_MIN) return null;
|
|
7119
|
+
r.bow = (d2 - d0 * s2 / c) / spread * ((hi - lo) / 2) ** 2;
|
|
7120
|
+
return Math.abs(r.bow) <= LINE_BOW ? r : null;
|
|
7121
|
+
};
|
|
7122
|
+
const fit = (from, to) => {
|
|
7123
|
+
const c = to - from + 1;
|
|
7124
|
+
let mx = 0;
|
|
7125
|
+
let my = 0;
|
|
7126
|
+
for (let k = from; k <= to; k++) mx += dx[k], my += dy[k];
|
|
7127
|
+
mx /= c;
|
|
7128
|
+
my /= c;
|
|
7129
|
+
let xx = 0;
|
|
7130
|
+
let xy = 0;
|
|
7131
|
+
let yy = 0;
|
|
7132
|
+
for (let k = from; k <= to; k++) {
|
|
7133
|
+
const px = dx[k] - mx;
|
|
7134
|
+
const py = dy[k] - my;
|
|
7135
|
+
xx += px * px;
|
|
7136
|
+
xy += px * py;
|
|
7137
|
+
yy += py * py;
|
|
7138
|
+
}
|
|
7139
|
+
const angle = .5 * Math.atan2(2 * xy, xx - yy);
|
|
7140
|
+
const way = Math.cos(angle) * (dx[to] - dx[from]) + Math.sin(angle) * (dy[to] - dy[from]) < 0 ? -1 : 1;
|
|
7141
|
+
return within({
|
|
7142
|
+
from,
|
|
7143
|
+
to,
|
|
7144
|
+
mx,
|
|
7145
|
+
my,
|
|
7146
|
+
ux: way * Math.cos(angle),
|
|
7147
|
+
uy: way * Math.sin(angle),
|
|
7148
|
+
bow: 0
|
|
7149
|
+
}, true);
|
|
7150
|
+
};
|
|
7151
|
+
const reach = (from, end) => {
|
|
7152
|
+
let to = from + LINE_MIN;
|
|
7153
|
+
if (to > end) return null;
|
|
7154
|
+
let best = fit(from, to);
|
|
7155
|
+
if (!best) return null;
|
|
7156
|
+
for (let step = 32; step >= 1; step >>= 1) while (to + step <= end) {
|
|
7157
|
+
const r = fit(from, to + step);
|
|
7158
|
+
if (!r) break;
|
|
7159
|
+
best = r;
|
|
7160
|
+
to += step;
|
|
7161
|
+
}
|
|
7162
|
+
return best;
|
|
7163
|
+
};
|
|
7164
|
+
const runs = [];
|
|
7165
|
+
const search = (lo, hi) => {
|
|
7166
|
+
let best = null;
|
|
7167
|
+
for (let from = lo; from + LINE_MIN <= hi;) {
|
|
7168
|
+
const r = reach(from, hi);
|
|
7169
|
+
if (r && (!best || r.to - r.from > best.to - best.from)) best = r;
|
|
7170
|
+
if (r && r.to === hi) break;
|
|
7171
|
+
from += r ? Math.max(2, r.to - r.from >> 3) : 2;
|
|
7172
|
+
}
|
|
7173
|
+
if (!best) return;
|
|
7174
|
+
search(lo, best.from);
|
|
7175
|
+
runs.push(best);
|
|
7176
|
+
search(best.to, hi);
|
|
7177
|
+
};
|
|
7178
|
+
search(0, n);
|
|
7179
|
+
const out = /* @__PURE__ */ new Set();
|
|
7180
|
+
for (let i = 0; i + 1 < runs.length; i++) {
|
|
7181
|
+
const p = runs[i];
|
|
7182
|
+
const q = runs[i + 1];
|
|
7183
|
+
if (q.from - p.to > LINE_GAP) continue;
|
|
7184
|
+
const turn = p.ux * q.uy - p.uy * q.ux;
|
|
7185
|
+
const bows = Math.max(p.bow, q.bow) * Math.sign(turn);
|
|
7186
|
+
if (Math.abs(turn) >= Math.sin(LINE_KINK) && bows < LINE_ARC) continue;
|
|
7187
|
+
const lp = p.to - p.from;
|
|
7188
|
+
const lq = q.to - q.from;
|
|
7189
|
+
if (lp < 2 * lq) out.add(p);
|
|
7190
|
+
if (lq < 2 * lp) out.add(q);
|
|
7191
|
+
}
|
|
7192
|
+
const kept = runs.filter((r) => !out.has(r));
|
|
7193
|
+
for (let i = 0; i + 1 < kept.length; i++) {
|
|
7194
|
+
const p = kept[i];
|
|
7195
|
+
const q = kept[i + 1];
|
|
7196
|
+
if (q.from - p.to > LINE_GAP) continue;
|
|
7197
|
+
const v = crossing(p, q);
|
|
7198
|
+
if (!v) continue;
|
|
7199
|
+
let m = -1;
|
|
7200
|
+
let near = 1e400;
|
|
7201
|
+
for (let k = p.to; k <= q.from; k++) {
|
|
7202
|
+
const d = Math.hypot(v[0] - dx[k], v[1] - dy[k]);
|
|
7203
|
+
if (d < near) near = d, m = k;
|
|
7204
|
+
}
|
|
7205
|
+
if (near > eps[m]) continue;
|
|
7206
|
+
p.to = q.from = m;
|
|
7207
|
+
p.last = q.first = v;
|
|
7208
|
+
}
|
|
7209
|
+
return kept;
|
|
7210
|
+
}
|
|
7211
|
+
/** Where two runs' lines cross, if they are at an angle. */
|
|
7212
|
+
function crossing(p, q) {
|
|
7213
|
+
const cross = p.ux * q.uy - p.uy * q.ux;
|
|
7214
|
+
if (Math.abs(cross) < Math.sin(LINE_KINK)) return null;
|
|
7215
|
+
const along = ((q.mx - p.mx) * q.uy - (q.my - p.my) * q.ux) / cross;
|
|
7216
|
+
return [p.mx + along * p.ux, p.my + along * p.uy];
|
|
7217
|
+
}
|
|
7218
|
+
/** A boundary's smoothed points (`nx`, `ny`) moved onto its straight runs. An end that meets nothing eases back into the smoothed path. */
|
|
7219
|
+
function drawRuns(runs, nx, ny) {
|
|
7220
|
+
for (const r of runs) {
|
|
7221
|
+
for (let k = r.from; k <= r.to; k++) {
|
|
7222
|
+
const t = (nx[k] - r.mx) * r.ux + (ny[k] - r.my) * r.uy;
|
|
7223
|
+
let wgt = 1;
|
|
7224
|
+
if (!r.first && k - r.from < LINE_EASE) wgt = Math.min(wgt, (k - r.from) / LINE_EASE);
|
|
7225
|
+
if (!r.last && r.to - k < LINE_EASE) wgt = Math.min(wgt, (r.to - k) / LINE_EASE);
|
|
7226
|
+
wgt = wgt * wgt * (3 - 2 * wgt);
|
|
7227
|
+
nx[k] = nx[k] + wgt * (r.mx + t * r.ux - nx[k]);
|
|
7228
|
+
ny[k] = ny[k] + wgt * (r.my + t * r.uy - ny[k]);
|
|
7229
|
+
}
|
|
7230
|
+
if (r.first) nx[r.from] = r.first[0], ny[r.from] = r.first[1];
|
|
7231
|
+
if (r.last) nx[r.to] = r.last[0], ny[r.to] = r.last[1];
|
|
7232
|
+
}
|
|
7233
|
+
}
|
|
7234
|
+
/**
|
|
7235
|
+
* The label map drawn at full size into `out` (alpha untouched), along its
|
|
7236
|
+
* smoothed boundaries. Drawn first as it is, each of its pixels a block, at
|
|
7237
|
+
* twice the output's size; then, for each boundary, the points between its
|
|
7238
|
+
* stepped path and its smoothed one change sides. Each output pixel averages
|
|
7239
|
+
* its four points, so edges come out anti-aliased like crisp art's.
|
|
7240
|
+
*/
|
|
7241
|
+
function redraw(lab, w, h, palette, F, edges, out, width, height) {
|
|
7242
|
+
const S = 2 * F;
|
|
7243
|
+
const W = 2 * width;
|
|
7244
|
+
const H = 2 * height;
|
|
7245
|
+
const big = new Uint8Array(W * H);
|
|
7246
|
+
for (let y = 0; y < H; y++) {
|
|
7247
|
+
const row = Math.min(h - 1, Math.floor(y / S)) * w;
|
|
7248
|
+
for (let x = 0; x < W; x++) big[y * W + x] = lab[row + Math.min(w - 1, Math.floor(x / S))];
|
|
7249
|
+
}
|
|
7250
|
+
const MOVED = 128;
|
|
7251
|
+
const rows = /* @__PURE__ */ new Map();
|
|
7252
|
+
const cut = (x1, y1, x2, y2) => {
|
|
7253
|
+
if (y1 === y2) return;
|
|
7254
|
+
const lo = Math.max(0, Math.ceil(Math.min(y1, y2) - .5));
|
|
7255
|
+
const hi = Math.min(H, Math.ceil(Math.max(y1, y2) - .5));
|
|
7256
|
+
for (let y = lo; y < hi; y++) {
|
|
7257
|
+
const x = x1 + (y + .5 - y1) * (x2 - x1) / (y2 - y1);
|
|
7258
|
+
const r = rows.get(y);
|
|
7259
|
+
if (r) r.push(x);
|
|
7260
|
+
else rows.set(y, [x]);
|
|
7261
|
+
}
|
|
7262
|
+
};
|
|
7263
|
+
for (const { xs, ys, nx, ny, a, b } of edges) {
|
|
7264
|
+
rows.clear();
|
|
7265
|
+
for (let k = 0; k + 1 < xs.length; k++) {
|
|
7266
|
+
cut(xs[k] * S, ys[k] * S, xs[k + 1] * S, ys[k + 1] * S);
|
|
7267
|
+
cut(nx[k] * S, ny[k] * S, nx[k + 1] * S, ny[k + 1] * S);
|
|
7268
|
+
}
|
|
7269
|
+
const n = xs.length - 1;
|
|
7270
|
+
cut(xs[0] * S, ys[0] * S, nx[0] * S, ny[0] * S);
|
|
7271
|
+
cut(xs[n] * S, ys[n] * S, nx[n] * S, ny[n] * S);
|
|
7272
|
+
for (const [y, cuts] of rows) {
|
|
7273
|
+
cuts.sort((p, q) => p - q);
|
|
7274
|
+
for (let c = 0; c + 1 < cuts.length; c += 2) for (let x = Math.max(0, Math.ceil(cuts[c] - .5)); x + .5 < cuts[c + 1] && x < W; x++) {
|
|
7275
|
+
const l = big[y * W + x];
|
|
7276
|
+
if (l === a) big[y * W + x] = b | MOVED;
|
|
7277
|
+
else if (l === b) big[y * W + x] = a | MOVED;
|
|
7278
|
+
}
|
|
7279
|
+
}
|
|
7280
|
+
}
|
|
7281
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
7282
|
+
const p = 2 * y * W + 2 * x;
|
|
7283
|
+
const c0 = palette[big[p] & 127];
|
|
7284
|
+
const c1 = palette[big[p + 1] & 127];
|
|
7285
|
+
const c2 = palette[big[p + W] & 127];
|
|
7286
|
+
const c3 = palette[big[p + W + 1] & 127];
|
|
7287
|
+
const o = (y * width + x) * 4;
|
|
7288
|
+
out[o] = (c0[0] + c1[0] + c2[0] + c3[0]) / 4;
|
|
7289
|
+
out[o + 1] = (c0[1] + c1[1] + c2[1] + c3[1]) / 4;
|
|
7290
|
+
out[o + 2] = (c0[2] + c1[2] + c2[2] + c3[2]) / 4;
|
|
7291
|
+
}
|
|
7292
|
+
}
|
|
7293
|
+
/**
|
|
7294
|
+
* A copy of the image with each transparent pixel given the colour of the
|
|
7295
|
+
* opaque pixels nearest it, ring by ring (alpha unchanged), so no blur or
|
|
7296
|
+
* look across a cut-out edge sees the black a canvas keeps under alpha 0.
|
|
7297
|
+
*/
|
|
7298
|
+
function fillTransparent(rgba, w, h) {
|
|
7299
|
+
const n = w * h;
|
|
7300
|
+
let clear = 0;
|
|
7301
|
+
for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] < 128) clear++;
|
|
7302
|
+
if (!clear || clear === n) return rgba;
|
|
7303
|
+
const src = Uint8ClampedArray.from(rgba);
|
|
7304
|
+
const known = new Uint8Array(n);
|
|
7305
|
+
for (let p = 0; p < n; p++) known[p] = src[p * 4 + 3] >= 128 ? 1 : 0;
|
|
7306
|
+
let ring = [];
|
|
7307
|
+
for (let p = 0; p < n; p++) if (known[p]) ring.push(p);
|
|
7308
|
+
while (ring.length) {
|
|
7309
|
+
const next = [];
|
|
7310
|
+
for (const p of ring) {
|
|
7311
|
+
const x = p % w;
|
|
7312
|
+
const y = (p - x) / w;
|
|
7313
|
+
for (const [dx, dy] of [
|
|
7314
|
+
[1, 0],
|
|
7315
|
+
[-1, 0],
|
|
7316
|
+
[0, 1],
|
|
7317
|
+
[0, -1]
|
|
7318
|
+
]) {
|
|
7319
|
+
const xx = x + dx;
|
|
7320
|
+
const yy = y + dy;
|
|
7321
|
+
if (xx < 0 || yy < 0 || xx >= w || yy >= h) continue;
|
|
7322
|
+
const q = yy * w + xx;
|
|
7323
|
+
if (known[q]) continue;
|
|
7324
|
+
known[q] = 1;
|
|
7325
|
+
src[q * 4] = src[p * 4];
|
|
7326
|
+
src[q * 4 + 1] = src[p * 4 + 1];
|
|
7327
|
+
src[q * 4 + 2] = src[p * 4 + 2];
|
|
7328
|
+
next.push(q);
|
|
7329
|
+
}
|
|
7330
|
+
}
|
|
7331
|
+
ring = next;
|
|
7332
|
+
}
|
|
7333
|
+
return src;
|
|
7334
|
+
}
|
|
7335
|
+
// src/smooth.ts
|
|
7336
|
+
/**
|
|
7337
|
+
* Edge-preserving smoothing for painted art, before its palette is picked.
|
|
7338
|
+
*
|
|
7339
|
+
* A painted poster's skin shadow is a soft ramp with brush and JPEG noise on
|
|
7340
|
+
* it. Labelled pixel by pixel, the noise flips each pixel between the two
|
|
7341
|
+
* nearest palette colours, and the shadow traces as ragged patches. A
|
|
7342
|
+
* bilateral filter averages each pixel with neighbours of a similar colour
|
|
7343
|
+
* only, so the noise inside a shadow evens out and the edges between colours
|
|
7344
|
+
* (an arm against the dark coat, a line on a face) stay where they are.
|
|
7345
|
+
*
|
|
7346
|
+
* On a painted film poster traced at 2× in Illustration, this turned the
|
|
7347
|
+
* blotchy arm and neck shadows into whole shapes, kept the face lines, and cut
|
|
7348
|
+
* the file from 3.3 MB to 2.1 MB; the filter took 4 s of the trace. Stronger
|
|
7349
|
+
* (radius 6, three passes at sigma 25) began to wash out lines in the hair.
|
|
7350
|
+
*/
|
|
7351
|
+
/** Neighbourhood radius, px. */
|
|
7352
|
+
const RADIUS = 4;
|
|
7353
|
+
/** Spatial falloff (Gaussian sigma, px). */
|
|
7354
|
+
const SIGMA_SPACE = 3;
|
|
7355
|
+
/** Colour falloff (Gaussian sigma, RGB distance). */
|
|
7356
|
+
const SIGMA_COLOR = 30;
|
|
7357
|
+
const PASSES = 3;
|
|
7358
|
+
/**
|
|
7359
|
+
* A smoothed copy of `rgba` (`width` × `height`, RGBA). Transparent pixels, and
|
|
7360
|
+
* any marked in `keep` (one entry per pixel, non-zero to keep), are left as
|
|
7361
|
+
* they are and never averaged into their neighbours.
|
|
7362
|
+
*/
|
|
7363
|
+
function smoothShading(rgba, width, height, keep) {
|
|
7364
|
+
const dxs = [];
|
|
7365
|
+
const dys = [];
|
|
7366
|
+
const ws = [];
|
|
7367
|
+
for (let dy = -4; dy <= RADIUS; dy++) for (let dx = -4; dx <= RADIUS; dx++) if (dx * dx + dy * dy <= 16) {
|
|
7368
|
+
dxs.push(dx);
|
|
7369
|
+
dys.push(dy);
|
|
7370
|
+
ws.push(Math.exp(-(dx * dx + dy * dy) / (2 * SIGMA_SPACE ** 2)));
|
|
7371
|
+
}
|
|
7372
|
+
const n = ws.length;
|
|
7373
|
+
const offsets = Int32Array.from(dxs, (dx, k) => (dys[k] * width + dx) * 4);
|
|
7374
|
+
const spatial = Float32Array.from(ws);
|
|
7375
|
+
const near = Float32Array.from({ length: 195076 }, (_, d2) => Math.exp(-d2 / (2 * SIGMA_COLOR ** 2)));
|
|
7376
|
+
let src = Uint8ClampedArray.from(rgba);
|
|
7377
|
+
const kept = [];
|
|
7378
|
+
if (keep) {
|
|
7379
|
+
for (let p = 0; p < width * height; p++) if (keep[p] && src[p * 4 + 3] >= 128) {
|
|
7380
|
+
kept.push(p, src[p * 4 + 3]);
|
|
7381
|
+
src[p * 4 + 3] = 0;
|
|
7382
|
+
}
|
|
7383
|
+
}
|
|
7384
|
+
for (let pass = 0; pass < PASSES; pass++) {
|
|
7385
|
+
const out = new Uint8ClampedArray(src);
|
|
7386
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
7387
|
+
const i = (y * width + x) * 4;
|
|
7388
|
+
if (src[i + 3] < 128) continue;
|
|
7389
|
+
const r = src[i];
|
|
7390
|
+
const g = src[i + 1];
|
|
7391
|
+
const b = src[i + 2];
|
|
7392
|
+
const inside = x >= RADIUS && y >= RADIUS && x < width - RADIUS && y < height - RADIUS;
|
|
7393
|
+
let sr = 0;
|
|
7394
|
+
let sg = 0;
|
|
7395
|
+
let sb = 0;
|
|
7396
|
+
let sw = 0;
|
|
7397
|
+
for (let k = 0; k < n; k++) {
|
|
7398
|
+
if (!inside) {
|
|
7399
|
+
const nx = x + dxs[k];
|
|
7400
|
+
const ny = y + dys[k];
|
|
7401
|
+
if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
|
|
7402
|
+
}
|
|
7403
|
+
const j = i + offsets[k];
|
|
7404
|
+
if (src[j + 3] < 128) continue;
|
|
7405
|
+
const dr = src[j] - r;
|
|
7406
|
+
const dg = src[j + 1] - g;
|
|
7407
|
+
const db = src[j + 2] - b;
|
|
7408
|
+
const w = spatial[k] * near[dr * dr + dg * dg + db * db];
|
|
7409
|
+
sr += w * src[j];
|
|
7410
|
+
sg += w * src[j + 1];
|
|
7411
|
+
sb += w * src[j + 2];
|
|
7412
|
+
sw += w;
|
|
7413
|
+
}
|
|
7414
|
+
out[i] = sr / sw;
|
|
7415
|
+
out[i + 1] = sg / sw;
|
|
7416
|
+
out[i + 2] = sb / sw;
|
|
7417
|
+
}
|
|
7418
|
+
src = out;
|
|
7419
|
+
}
|
|
7420
|
+
for (let k = 0; k < kept.length; k += 2) src[kept[k] * 4 + 3] = kept[k + 1];
|
|
7421
|
+
return src;
|
|
7422
|
+
}
|
|
7423
|
+
/** A line pixel is this much darker than its closing (0–255 lightness) at least. */
|
|
7424
|
+
const LINE_DEPTH = 6;
|
|
7425
|
+
/** And darkened by this many times that depth, */
|
|
7426
|
+
const LINE_GAIN = 2;
|
|
5210
7427
|
/** but by no more than this: a line already well apart from its sides (brows on skin) keeps its colour. */
|
|
5211
7428
|
const LINE_MAX = 30;
|
|
5212
7429
|
/** A line is kept only when it spans this many times the radius (bounding-box diagonal): texture is short. */
|
|
@@ -5405,6 +7622,10 @@ function coverage(pixels, palette) {
|
|
|
5405
7622
|
const outlineRadius = (scale) => Math.min(4, Math.max(2, Math.round(1.5 * scale)));
|
|
5406
7623
|
/** The trace for `image` with `options`: a preset's recipe, with any option given in place of its default. */
|
|
5407
7624
|
function tracePreset(image, options = {}) {
|
|
7625
|
+
return run(presetSteps(image, options));
|
|
7626
|
+
}
|
|
7627
|
+
/** `tracePreset` as steps (see `traceSteps`), for `traceAsync`. */
|
|
7628
|
+
function* presetSteps(image, options = {}) {
|
|
5408
7629
|
const name = options.preset ?? "logo";
|
|
5409
7630
|
const p = Object.hasOwn(presets, name) ? presets[name] : void 0;
|
|
5410
7631
|
if (!p) throw new Error(`Unknown preset "${String(name)}". Use one of: ${Object.keys(presets).join(", ")}.`);
|
|
@@ -5429,14 +7650,20 @@ function tracePreset(image, options = {}) {
|
|
|
5429
7650
|
px = flipped;
|
|
5430
7651
|
}
|
|
5431
7652
|
const threshold = o.threshold === void 0 ? "auto" : o.threshold;
|
|
5432
|
-
if (p.kind === "centerline")
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
|
|
5436
|
-
|
|
5437
|
-
|
|
5438
|
-
|
|
5439
|
-
|
|
7653
|
+
if (p.kind === "centerline") {
|
|
7654
|
+
yield {
|
|
7655
|
+
stage: "label",
|
|
7656
|
+
done: 0
|
|
7657
|
+
};
|
|
7658
|
+
return centerline(px, width, height, {
|
|
7659
|
+
...fit,
|
|
7660
|
+
threshold,
|
|
7661
|
+
closeGaps: !!o.closeGaps,
|
|
7662
|
+
scale,
|
|
7663
|
+
...o.strokeWidth ? { strokeWidth: o.strokeWidth } : {}
|
|
7664
|
+
});
|
|
7665
|
+
}
|
|
7666
|
+
return yield* traceSteps(px, width, height, {
|
|
5440
7667
|
...fit,
|
|
5441
7668
|
shapes: !!o.shapes,
|
|
5442
7669
|
mode: "binary",
|
|
@@ -5446,9 +7673,14 @@ function tracePreset(image, options = {}) {
|
|
|
5446
7673
|
});
|
|
5447
7674
|
}
|
|
5448
7675
|
if (o.grayscale && name !== "pixel" && !o.palette?.length) px = toGray(px);
|
|
7676
|
+
if (o.deblur && name !== "pixel") px = yield* deblurred(px, width, height, scale);
|
|
5449
7677
|
const lines = o.keepOutlines ? new Uint8Array(width * height) : void 0;
|
|
5450
7678
|
if (lines) px = boostLines(px, width, height, outlineRadius(scale), lines);
|
|
5451
7679
|
if (o.smoothShading) px = smoothShading(px, width, height, lines);
|
|
7680
|
+
yield {
|
|
7681
|
+
stage: "palette",
|
|
7682
|
+
done: 0
|
|
7683
|
+
};
|
|
5452
7684
|
const picker = PICKER[name];
|
|
5453
7685
|
const colors = o.colors ?? 8;
|
|
5454
7686
|
const own = o.palette?.length ? o.palette : null;
|
|
@@ -5468,12 +7700,59 @@ function tracePreset(image, options = {}) {
|
|
|
5468
7700
|
photo: picker === "quantize",
|
|
5469
7701
|
strokes: !!o.strokes && !pixels && picker !== "quantize",
|
|
5470
7702
|
gradients: gradients && !pixels,
|
|
7703
|
+
faint: !own,
|
|
5471
7704
|
closeGaps: !!o.closeGaps,
|
|
5472
7705
|
scale,
|
|
5473
7706
|
...lines ? { lines } : {}
|
|
5474
7707
|
};
|
|
5475
|
-
return
|
|
7708
|
+
return yield* traceSteps(px, width, height, raw);
|
|
5476
7709
|
}
|
|
7710
|
+
/**
|
|
7711
|
+
* `deblur`, remembering its last answer: the app traces the same pixels
|
|
7712
|
+
* again on every slider change (and the target-size search many times), and
|
|
7713
|
+
* deblurring costs seconds where the trace costs a fraction of that. Keyed by
|
|
7714
|
+
* two hashes of every byte, which take milliseconds; so the last deblurred
|
|
7715
|
+
* image stays in memory until another replaces it. As steps: a first one
|
|
7716
|
+
* before it starts, then one at each of `deblurSteps`' pauses; a single one
|
|
7717
|
+
* when the answer was remembered.
|
|
7718
|
+
*/
|
|
7719
|
+
let lastDeblurred = null;
|
|
7720
|
+
function* deblurred(px, width, height, scale) {
|
|
7721
|
+
let h1 = 2166136261;
|
|
7722
|
+
let h2 = 2538058380;
|
|
7723
|
+
for (let i = 0; i < px.length; i++) {
|
|
7724
|
+
h1 = Math.imul(h1 ^ px[i], 16777619);
|
|
7725
|
+
h2 = Math.imul(h2, 1540483477) + px[i] + (h2 >>> 15) | 0;
|
|
7726
|
+
}
|
|
7727
|
+
const key = `${width}x${height}@${scale}:${h1 >>> 0}:${h2 >>> 0}`;
|
|
7728
|
+
if (lastDeblurred?.key === key) {
|
|
7729
|
+
yield {
|
|
7730
|
+
stage: "deblur",
|
|
7731
|
+
done: 1
|
|
7732
|
+
};
|
|
7733
|
+
return lastDeblurred.out;
|
|
7734
|
+
}
|
|
7735
|
+
yield {
|
|
7736
|
+
stage: "deblur",
|
|
7737
|
+
done: 0
|
|
7738
|
+
};
|
|
7739
|
+
const steps = deblurSteps(px, width, height, void 0, scale);
|
|
7740
|
+
for (let pauses = 1;; pauses++) {
|
|
7741
|
+
const r = steps.next();
|
|
7742
|
+
if (r.done) {
|
|
7743
|
+
lastDeblurred = {
|
|
7744
|
+
key,
|
|
7745
|
+
out: r.value
|
|
7746
|
+
};
|
|
7747
|
+
return r.value;
|
|
7748
|
+
}
|
|
7749
|
+
yield {
|
|
7750
|
+
stage: "deblur",
|
|
7751
|
+
done: Math.min(1, pauses / DEBLUR_PAUSES)
|
|
7752
|
+
};
|
|
7753
|
+
}
|
|
7754
|
+
}
|
|
7755
|
+
const DEBLUR_PAUSES = 36;
|
|
5477
7756
|
/** sRGB (0–255) of the grey whose OKLab lightness is `l`: for a grey, L is the cube root of its linear light. */
|
|
5478
7757
|
const greyOf = (l) => {
|
|
5479
7758
|
const y = Math.min(1, Math.max(0, l)) ** 3;
|
|
@@ -5507,6 +7786,38 @@ function trace(a, b, c, d) {
|
|
|
5507
7786
|
function traceInlay(a, b, c, d) {
|
|
5508
7787
|
return toSvg(typeof b === "number" ? traceRaw(a, b, c, d) : tracePreset(a, b));
|
|
5509
7788
|
}
|
|
7789
|
+
/** How long, in ms, the trace runs before letting the thread do other work. */
|
|
7790
|
+
const SLICE_MS = 12;
|
|
7791
|
+
const later = () => new Promise((resolve) => globalThis.setTimeout(resolve, 0));
|
|
7792
|
+
const stop = (signal) => {
|
|
7793
|
+
if (!signal.aborted) return;
|
|
7794
|
+
if (signal.reason !== void 0) throw signal.reason;
|
|
7795
|
+
throw Object.assign(/* @__PURE__ */ new Error("The trace was aborted."), { name: "AbortError" });
|
|
7796
|
+
};
|
|
7797
|
+
/**
|
|
7798
|
+
* `trace`, but it pauses between its stages (and every few hundred edges
|
|
7799
|
+
* while fitting) to report progress and let the thread get on with other
|
|
7800
|
+
* work, and it stops when `signal` aborts. Same result as `trace`.
|
|
7801
|
+
*
|
|
7802
|
+
* const controller = new AbortController()
|
|
7803
|
+
* const result = await traceAsync(image, { preset: 'poster', signal: controller.signal, onProgress: (s) => console.log(s.stage, s.done) })
|
|
7804
|
+
*/
|
|
7805
|
+
async function traceAsync(image, options = {}) {
|
|
7806
|
+
const { signal, onProgress, ...rest } = options;
|
|
7807
|
+
if (signal) stop(signal);
|
|
7808
|
+
const steps = presetSteps(image, rest);
|
|
7809
|
+
let since = Date.now();
|
|
7810
|
+
for (;;) {
|
|
7811
|
+
const r = steps.next();
|
|
7812
|
+
if (r.done) return r.value;
|
|
7813
|
+
onProgress?.(r.value);
|
|
7814
|
+
if (Date.now() - since >= SLICE_MS) {
|
|
7815
|
+
await later();
|
|
7816
|
+
since = Date.now();
|
|
7817
|
+
}
|
|
7818
|
+
if (signal) stop(signal);
|
|
7819
|
+
}
|
|
7820
|
+
}
|
|
5510
7821
|
// src/symmetry.ts
|
|
5511
7822
|
/**
|
|
5512
7823
|
* Score every candidate symmetry: the best vertical and horizontal mirror axes
|
|
@@ -5689,4 +8000,562 @@ function detectSymmetry(rgba, w, h, options = {}) {
|
|
|
5689
8000
|
});
|
|
5690
8001
|
return out.sort((a, b) => b.score - a.score);
|
|
5691
8002
|
}
|
|
5692
|
-
|
|
8003
|
+
// src/sticker.ts
|
|
8004
|
+
/**
|
|
8005
|
+
* Stickers: a solid backing behind a trace, so it can be printed and cut out
|
|
8006
|
+
* as one piece.
|
|
8007
|
+
*
|
|
8008
|
+
* The backing's shape is either the drawing's own outline grown by a margin
|
|
8009
|
+
* ('contour', a die-cut sticker) or a plain circle, oval, square or rectangle
|
|
8010
|
+
* round it. For a contour the shapes are drawn into a mask, their holes are
|
|
8011
|
+
* filled (a sticker is one solid piece, so the inside of an O is backing
|
|
8012
|
+
* too), the mask is grown by the margin with an exact distance transform, and
|
|
8013
|
+
* tight inside corners are rounded off so a blade can follow them; then Inlay
|
|
8014
|
+
* traces the mask, so the backing is one smooth path like any other shape.
|
|
8015
|
+
*
|
|
8016
|
+
* A cut line is the backing's edge without the bleed: the backing reaches
|
|
8017
|
+
* `bleed` past it, so a cut that lands a little off the line never shows a
|
|
8018
|
+
* sliver of the background.
|
|
8019
|
+
*/
|
|
8020
|
+
/** A shape at least this share of the drawing's width and height is its background (as the app's objects.ts). */
|
|
8021
|
+
const BACKGROUND = .95;
|
|
8022
|
+
/** The mask's longer side, in cells, at most; and its cells per drawing px, at most. */
|
|
8023
|
+
const GRID = 1024;
|
|
8024
|
+
const MAX_SCALE = 4;
|
|
8025
|
+
/** The circle and ellipse as cubics: the handle length for a quarter turn. */
|
|
8026
|
+
const KAPPA = .5522847498;
|
|
8027
|
+
const num = (v) => String(Math.round(v * 100) / 100);
|
|
8028
|
+
/** The backing for a trace, and optionally its cut line. */
|
|
8029
|
+
function sticker(r, o = {}) {
|
|
8030
|
+
const shape = o.shape ?? "contour";
|
|
8031
|
+
const color = o.color ?? "#ffffff";
|
|
8032
|
+
const art = o.background === false ? r.paths : r.paths.filter((p) => !isBackground(p, r));
|
|
8033
|
+
const shapes = art.map((p) => ({
|
|
8034
|
+
subs: parsePath(p.d),
|
|
8035
|
+
stroke: p.stroke ?? 0
|
|
8036
|
+
}));
|
|
8037
|
+
const box = boundsOf(shapes);
|
|
8038
|
+
if (!box) return {
|
|
8039
|
+
backing: {
|
|
8040
|
+
d: "",
|
|
8041
|
+
fill: color
|
|
8042
|
+
},
|
|
8043
|
+
...o.cutLine ? { cutLine: "" } : {},
|
|
8044
|
+
box: {
|
|
8045
|
+
x: 0,
|
|
8046
|
+
y: 0,
|
|
8047
|
+
width: r.width,
|
|
8048
|
+
height: r.height
|
|
8049
|
+
},
|
|
8050
|
+
art
|
|
8051
|
+
};
|
|
8052
|
+
const side = Math.max(box.x1 - box.x0, box.y1 - box.y0, 1);
|
|
8053
|
+
const margin = Math.max(0, o.margin ?? .04 * side);
|
|
8054
|
+
const bleed = Math.max(0, o.bleed ?? 0);
|
|
8055
|
+
const roundOff = Math.max(0, o.roundOff ?? margin / 2);
|
|
8056
|
+
const pad = margin + bleed + roundOff + 2;
|
|
8057
|
+
const scale = Math.min(MAX_SCALE, GRID / (side + 2 * pad));
|
|
8058
|
+
const ox = box.x0 - pad;
|
|
8059
|
+
const oy = box.y0 - pad;
|
|
8060
|
+
const w = Math.ceil((box.x1 - box.x0 + 2 * pad) * scale);
|
|
8061
|
+
const h = Math.ceil((box.y1 - box.y0 + 2 * pad) * scale);
|
|
8062
|
+
const toGrid = (p) => ({
|
|
8063
|
+
x: (p.x - ox) * scale,
|
|
8064
|
+
y: (p.y - oy) * scale
|
|
8065
|
+
});
|
|
8066
|
+
const art0 = new Uint8Array(w * h);
|
|
8067
|
+
for (const s of shapes) {
|
|
8068
|
+
const rings = s.subs.map((sub) => flatten(mapPoints([sub], toGrid)[0]));
|
|
8069
|
+
if (s.stroke > 0) strokeRings(art0, w, h, rings, s.stroke / 2 * scale);
|
|
8070
|
+
else fillRings(art0, w, h, rings);
|
|
8071
|
+
}
|
|
8072
|
+
fillHoles(art0, w, h);
|
|
8073
|
+
const fromGrid = (p) => ({
|
|
8074
|
+
x: p.x / scale + ox,
|
|
8075
|
+
y: p.y / scale + oy
|
|
8076
|
+
});
|
|
8077
|
+
let backingD;
|
|
8078
|
+
let cutD;
|
|
8079
|
+
let out;
|
|
8080
|
+
if (shape === "contour") {
|
|
8081
|
+
const grown = (by) => {
|
|
8082
|
+
const m = grow(art0, w, h, (by + roundOff) * scale);
|
|
8083
|
+
if (roundOff > 0) shrink(m, w, h, roundOff * scale);
|
|
8084
|
+
fillHoles(m, w, h);
|
|
8085
|
+
return m;
|
|
8086
|
+
};
|
|
8087
|
+
const trace = (m) => {
|
|
8088
|
+
const rgba = new Uint8ClampedArray(w * h * 4);
|
|
8089
|
+
for (let i = 0; i < w * h; i++) {
|
|
8090
|
+
const v = m[i] ? 0 : 255;
|
|
8091
|
+
rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = v;
|
|
8092
|
+
rgba[i * 4 + 3] = 255;
|
|
8093
|
+
}
|
|
8094
|
+
return serializePath(traceRaw(rgba, w, h, {
|
|
8095
|
+
mode: "binary",
|
|
8096
|
+
threshold: 128,
|
|
8097
|
+
speckle: 0,
|
|
8098
|
+
tolerance: .75,
|
|
8099
|
+
cornerAngle: 60
|
|
8100
|
+
}).paths.flatMap((p) => mapPoints(parsePath(p.d), fromGrid)));
|
|
8101
|
+
};
|
|
8102
|
+
const back = grown(margin + bleed);
|
|
8103
|
+
backingD = trace(back);
|
|
8104
|
+
if (o.cutLine) cutD = bleed > 0 ? trace(grown(margin)) : backingD;
|
|
8105
|
+
out = maskBounds(back, w, h, fromGrid);
|
|
8106
|
+
} else {
|
|
8107
|
+
const hull = hullOf(art0, w, h).map(fromGrid);
|
|
8108
|
+
const make = (by) => geometric(shape, hull, box, by, o.corners ?? 0, margin);
|
|
8109
|
+
const back = make(margin + bleed);
|
|
8110
|
+
backingD = back.d;
|
|
8111
|
+
if (o.cutLine) cutD = bleed > 0 ? make(margin).d : back.d;
|
|
8112
|
+
out = back.box;
|
|
8113
|
+
}
|
|
8114
|
+
return {
|
|
8115
|
+
backing: {
|
|
8116
|
+
d: backingD,
|
|
8117
|
+
fill: color
|
|
8118
|
+
},
|
|
8119
|
+
...o.cutLine ? { cutLine: cutD ?? "" } : {},
|
|
8120
|
+
box: {
|
|
8121
|
+
x: out.x0,
|
|
8122
|
+
y: out.y0,
|
|
8123
|
+
width: out.x1 - out.x0,
|
|
8124
|
+
height: out.y1 - out.y0
|
|
8125
|
+
},
|
|
8126
|
+
art
|
|
8127
|
+
};
|
|
8128
|
+
}
|
|
8129
|
+
/**
|
|
8130
|
+
* The sticker as an SVG document: the backing (`id="sticker-backing"`), the
|
|
8131
|
+
* art over it, and the cut line on top (`id="cut-line"`, an unfilled
|
|
8132
|
+
* hairline). The page is the sticker's box, so it can reach past the
|
|
8133
|
+
* drawing's own edges.
|
|
8134
|
+
*/
|
|
8135
|
+
function stickerSvg(r, o = {}) {
|
|
8136
|
+
const s = sticker(r, o);
|
|
8137
|
+
const { x, y, width, height } = s.box;
|
|
8138
|
+
const svg = toSvg({
|
|
8139
|
+
...r,
|
|
8140
|
+
paths: s.art
|
|
8141
|
+
});
|
|
8142
|
+
const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${num(width)}" height="${num(height)}" viewBox="${num(x)} ${num(y)} ${num(width)} ${num(height)}">\n`;
|
|
8143
|
+
const backing = s.backing.d ? `<path id="sticker-backing" d="${attr(s.backing.d)}" fill="${attr(s.backing.fill)}"/>\n` : "";
|
|
8144
|
+
const cut = s.cutLine ? `\n<path id="cut-line" d="${attr(s.cutLine)}" fill="none" stroke="#ec008c" stroke-width="1" vector-effect="non-scaling-stroke"/>` : "";
|
|
8145
|
+
return svg.replace(/^<svg[^>]*>\n/, open + backing).replace(/\n<\/svg>\n$/, `${cut}\n</svg>\n`);
|
|
8146
|
+
}
|
|
8147
|
+
/** Whether a shape is the drawing's background: filled, and at least 95% of its width and height. */
|
|
8148
|
+
function isBackground(p, r) {
|
|
8149
|
+
if (p.stroke) return false;
|
|
8150
|
+
const b = boundsOf([{
|
|
8151
|
+
subs: parsePath(p.d),
|
|
8152
|
+
stroke: 0
|
|
8153
|
+
}]);
|
|
8154
|
+
return !!b && b.x1 - b.x0 >= BACKGROUND * r.width && b.y1 - b.y0 >= BACKGROUND * r.height;
|
|
8155
|
+
}
|
|
8156
|
+
/** The shapes' bounds, by their nodes and handles (a curve stays inside its handles), and half a stroke round lines. */
|
|
8157
|
+
function boundsOf(shapes) {
|
|
8158
|
+
let x0 = 1e400;
|
|
8159
|
+
let y0 = 1e400;
|
|
8160
|
+
let x1 = -1e400;
|
|
8161
|
+
let y1 = -1e400;
|
|
8162
|
+
for (const s of shapes) {
|
|
8163
|
+
const e = s.stroke / 2;
|
|
8164
|
+
for (const sub of s.subs) for (const n of sub.nodes) for (const p of [
|
|
8165
|
+
n,
|
|
8166
|
+
n.in,
|
|
8167
|
+
n.out
|
|
8168
|
+
]) {
|
|
8169
|
+
if (!p) continue;
|
|
8170
|
+
x0 = Math.min(x0, p.x - e);
|
|
8171
|
+
y0 = Math.min(y0, p.y - e);
|
|
8172
|
+
x1 = Math.max(x1, p.x + e);
|
|
8173
|
+
y1 = Math.max(y1, p.y + e);
|
|
8174
|
+
}
|
|
8175
|
+
}
|
|
8176
|
+
return x0 <= x1 ? {
|
|
8177
|
+
x0,
|
|
8178
|
+
y0,
|
|
8179
|
+
x1,
|
|
8180
|
+
y1
|
|
8181
|
+
} : null;
|
|
8182
|
+
}
|
|
8183
|
+
/** A subpath as points: each node, and along a curve a point every cell or so. Closed rings repeat their first point at the end. */
|
|
8184
|
+
function flatten(s) {
|
|
8185
|
+
const out = [];
|
|
8186
|
+
const n = s.nodes.length;
|
|
8187
|
+
if (!n) return out;
|
|
8188
|
+
out.push({
|
|
8189
|
+
x: s.nodes[0].x,
|
|
8190
|
+
y: s.nodes[0].y
|
|
8191
|
+
});
|
|
8192
|
+
const last = s.closed ? n : n - 1;
|
|
8193
|
+
for (let i = 0; i < last; i++) {
|
|
8194
|
+
const a = s.nodes[i];
|
|
8195
|
+
const b = s.nodes[(i + 1) % n];
|
|
8196
|
+
if (!a.out && !b.in) {
|
|
8197
|
+
out.push({
|
|
8198
|
+
x: b.x,
|
|
8199
|
+
y: b.y
|
|
8200
|
+
});
|
|
8201
|
+
continue;
|
|
8202
|
+
}
|
|
8203
|
+
const c1 = a.out ?? a;
|
|
8204
|
+
const c2 = b.in ?? b;
|
|
8205
|
+
const len = Math.hypot(c1.x - a.x, c1.y - a.y) + Math.hypot(c2.x - c1.x, c2.y - c1.y) + Math.hypot(b.x - c2.x, b.y - c2.y);
|
|
8206
|
+
const k = Math.min(256, Math.max(1, Math.ceil(len)));
|
|
8207
|
+
for (let j = 1; j <= k; j++) {
|
|
8208
|
+
const t = j / k;
|
|
8209
|
+
const u = 1 - t;
|
|
8210
|
+
out.push({
|
|
8211
|
+
x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,
|
|
8212
|
+
y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y
|
|
8213
|
+
});
|
|
8214
|
+
}
|
|
8215
|
+
}
|
|
8216
|
+
return out;
|
|
8217
|
+
}
|
|
8218
|
+
/** Fill one shape's rings into the mask by the nonzero rule, at cell centres. */
|
|
8219
|
+
function fillRings(mask, w, h, rings) {
|
|
8220
|
+
const rows = Array.from({ length: h }, () => []);
|
|
8221
|
+
for (const ring of rings) for (let i = 0; i < ring.length; i++) {
|
|
8222
|
+
const a = ring[i];
|
|
8223
|
+
const b = ring[(i + 1) % ring.length];
|
|
8224
|
+
if (a.y === b.y) continue;
|
|
8225
|
+
const dir = a.y < b.y ? 1 : -1;
|
|
8226
|
+
const [p, q] = a.y < b.y ? [a, b] : [b, a];
|
|
8227
|
+
const from = Math.max(0, Math.ceil(p.y - .5));
|
|
8228
|
+
const to = Math.min(h - 1, Math.ceil(q.y - .5) - 1);
|
|
8229
|
+
for (let y = from; y <= to; y++) {
|
|
8230
|
+
const cy = y + .5;
|
|
8231
|
+
rows[y].push(p.x + (cy - p.y) / (q.y - p.y) * (q.x - p.x), dir);
|
|
8232
|
+
}
|
|
8233
|
+
}
|
|
8234
|
+
for (let y = 0; y < h; y++) {
|
|
8235
|
+
const row = rows[y];
|
|
8236
|
+
if (!row.length) continue;
|
|
8237
|
+
const xs = [];
|
|
8238
|
+
for (let i = 0; i < row.length; i += 2) xs.push({
|
|
8239
|
+
x: row[i],
|
|
8240
|
+
d: row[i + 1]
|
|
8241
|
+
});
|
|
8242
|
+
xs.sort((a, b) => a.x - b.x);
|
|
8243
|
+
let wind = 0;
|
|
8244
|
+
for (let i = 0; i < xs.length - 1; i++) {
|
|
8245
|
+
wind += xs[i].d;
|
|
8246
|
+
if (!wind) continue;
|
|
8247
|
+
const from = Math.max(0, Math.ceil(xs[i].x - .5));
|
|
8248
|
+
const to = Math.min(w - 1, Math.ceil(xs[i + 1].x - .5) - 1);
|
|
8249
|
+
for (let x = from; x <= to; x++) mask[y * w + x] = 1;
|
|
8250
|
+
}
|
|
8251
|
+
}
|
|
8252
|
+
}
|
|
8253
|
+
/** Stamp a line's rings into the mask as round-capped strokes `r` cells wide each side. */
|
|
8254
|
+
function strokeRings(mask, w, h, rings, r) {
|
|
8255
|
+
const stamp = (cx, cy) => {
|
|
8256
|
+
const rr = Math.max(r, .5);
|
|
8257
|
+
for (let y = Math.max(0, Math.floor(cy - rr)); y <= Math.min(h - 1, Math.ceil(cy + rr)); y++) for (let x = Math.max(0, Math.floor(cx - rr)); x <= Math.min(w - 1, Math.ceil(cx + rr)); x++) if ((x + .5 - cx) ** 2 + (y + .5 - cy) ** 2 <= rr * rr) mask[y * w + x] = 1;
|
|
8258
|
+
};
|
|
8259
|
+
for (const ring of rings) for (let i = 0; i < ring.length; i++) {
|
|
8260
|
+
const a = ring[i];
|
|
8261
|
+
const b = ring[i + 1] ?? a;
|
|
8262
|
+
const k = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / Math.max(.5, r / 2)));
|
|
8263
|
+
for (let j = 0; j < k; j++) stamp(a.x + (b.x - a.x) * j / k, a.y + (b.y - a.y) * j / k);
|
|
8264
|
+
}
|
|
8265
|
+
}
|
|
8266
|
+
/** Fill the mask's holes: every empty cell that can't reach the edge through empty cells. */
|
|
8267
|
+
function fillHoles(mask, w, h) {
|
|
8268
|
+
const out = new Uint8Array(w * h);
|
|
8269
|
+
const stack = [];
|
|
8270
|
+
const push = (i) => {
|
|
8271
|
+
if (!mask[i] && !out[i]) {
|
|
8272
|
+
out[i] = 1;
|
|
8273
|
+
stack.push(i);
|
|
8274
|
+
}
|
|
8275
|
+
};
|
|
8276
|
+
for (let x = 0; x < w; x++) {
|
|
8277
|
+
push(x);
|
|
8278
|
+
push((h - 1) * w + x);
|
|
8279
|
+
}
|
|
8280
|
+
for (let y = 0; y < h; y++) {
|
|
8281
|
+
push(y * w);
|
|
8282
|
+
push(y * w + w - 1);
|
|
8283
|
+
}
|
|
8284
|
+
while (stack.length) {
|
|
8285
|
+
const i = stack.pop();
|
|
8286
|
+
const x = i % w;
|
|
8287
|
+
if (x > 0) push(i - 1);
|
|
8288
|
+
if (x < w - 1) push(i + 1);
|
|
8289
|
+
if (i >= w) push(i - w);
|
|
8290
|
+
if (i < w * (h - 1)) push(i + w);
|
|
8291
|
+
}
|
|
8292
|
+
for (let i = 0; i < w * h; i++) if (!out[i]) mask[i] = 1;
|
|
8293
|
+
}
|
|
8294
|
+
const INF = 0x56bc75e2d63100000;
|
|
8295
|
+
/** Squared distance from each cell to the nearest cell where `seed` is set (Felzenszwalb and Huttenlocher's exact transform). */
|
|
8296
|
+
function distance(seed, w, h) {
|
|
8297
|
+
const f = new Float64Array(w * h);
|
|
8298
|
+
for (let i = 0; i < w * h; i++) f[i] = seed(i) ? 0 : INF;
|
|
8299
|
+
const n = Math.max(w, h);
|
|
8300
|
+
const g = new Float64Array(n);
|
|
8301
|
+
const d = new Float64Array(n);
|
|
8302
|
+
const v = new Int32Array(n);
|
|
8303
|
+
const z = new Float64Array(n + 1);
|
|
8304
|
+
const pass = (len) => {
|
|
8305
|
+
let k = 0;
|
|
8306
|
+
v[0] = 0;
|
|
8307
|
+
z[0] = -0x56bc75e2d63100000;
|
|
8308
|
+
z[1] = INF;
|
|
8309
|
+
for (let q = 1; q < len; q++) {
|
|
8310
|
+
let s = (g[q] + q * q - (g[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
8311
|
+
while (s <= z[k]) {
|
|
8312
|
+
k--;
|
|
8313
|
+
s = (g[q] + q * q - (g[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
8314
|
+
}
|
|
8315
|
+
k++;
|
|
8316
|
+
v[k] = q;
|
|
8317
|
+
z[k] = s;
|
|
8318
|
+
z[k + 1] = INF;
|
|
8319
|
+
}
|
|
8320
|
+
k = 0;
|
|
8321
|
+
for (let q = 0; q < len; q++) {
|
|
8322
|
+
while (z[k + 1] < q) k++;
|
|
8323
|
+
const p = v[k];
|
|
8324
|
+
d[q] = (q - p) * (q - p) + g[p];
|
|
8325
|
+
}
|
|
8326
|
+
};
|
|
8327
|
+
for (let x = 0; x < w; x++) {
|
|
8328
|
+
for (let y = 0; y < h; y++) g[y] = f[y * w + x];
|
|
8329
|
+
pass(h);
|
|
8330
|
+
for (let y = 0; y < h; y++) f[y * w + x] = d[y];
|
|
8331
|
+
}
|
|
8332
|
+
for (let y = 0; y < h; y++) {
|
|
8333
|
+
for (let x = 0; x < w; x++) g[x] = f[y * w + x];
|
|
8334
|
+
pass(w);
|
|
8335
|
+
for (let x = 0; x < w; x++) f[y * w + x] = d[x];
|
|
8336
|
+
}
|
|
8337
|
+
return f;
|
|
8338
|
+
}
|
|
8339
|
+
/** A new mask: every cell within `r` cells of the mask. */
|
|
8340
|
+
function grow(mask, w, h, r) {
|
|
8341
|
+
const d = distance((i) => mask[i] === 1, w, h);
|
|
8342
|
+
const out = new Uint8Array(w * h);
|
|
8343
|
+
const rr = r * r;
|
|
8344
|
+
for (let i = 0; i < w * h; i++) if (d[i] <= rr) out[i] = 1;
|
|
8345
|
+
return out;
|
|
8346
|
+
}
|
|
8347
|
+
/** Shrink the mask in place: keep only cells more than `r` cells from its outside. */
|
|
8348
|
+
function shrink(mask, w, h, r) {
|
|
8349
|
+
const d = distance((i) => mask[i] === 0, w, h);
|
|
8350
|
+
const rr = r * r;
|
|
8351
|
+
for (let i = 0; i < w * h; i++) if (mask[i] && d[i] <= rr) mask[i] = 0;
|
|
8352
|
+
}
|
|
8353
|
+
/** The mask's bounds, in the drawing's px. */
|
|
8354
|
+
function maskBounds(mask, w, h, from) {
|
|
8355
|
+
let x0 = w;
|
|
8356
|
+
let y0 = h;
|
|
8357
|
+
let x1 = -1;
|
|
8358
|
+
let y1 = -1;
|
|
8359
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (mask[y * w + x]) {
|
|
8360
|
+
if (x < x0) x0 = x;
|
|
8361
|
+
if (x > x1) x1 = x;
|
|
8362
|
+
if (y < y0) y0 = y;
|
|
8363
|
+
if (y > y1) y1 = y;
|
|
8364
|
+
}
|
|
8365
|
+
const a = from({
|
|
8366
|
+
x: x0,
|
|
8367
|
+
y: y0
|
|
8368
|
+
});
|
|
8369
|
+
const b = from({
|
|
8370
|
+
x: x1 + 1,
|
|
8371
|
+
y: y1 + 1
|
|
8372
|
+
});
|
|
8373
|
+
return {
|
|
8374
|
+
x0: a.x,
|
|
8375
|
+
y0: a.y,
|
|
8376
|
+
x1: b.x,
|
|
8377
|
+
y1: b.y
|
|
8378
|
+
};
|
|
8379
|
+
}
|
|
8380
|
+
/** The convex hull of the mask's cells (their corners), in cells. */
|
|
8381
|
+
function hullOf(mask, w, h) {
|
|
8382
|
+
const pts = [];
|
|
8383
|
+
for (let y = 0; y < h; y++) {
|
|
8384
|
+
let a = -1;
|
|
8385
|
+
let b = -1;
|
|
8386
|
+
for (let x = 0; x < w; x++) if (mask[y * w + x]) {
|
|
8387
|
+
if (a < 0) a = x;
|
|
8388
|
+
b = x;
|
|
8389
|
+
}
|
|
8390
|
+
if (a < 0) continue;
|
|
8391
|
+
pts.push({
|
|
8392
|
+
x: a,
|
|
8393
|
+
y
|
|
8394
|
+
}, {
|
|
8395
|
+
x: a,
|
|
8396
|
+
y: y + 1
|
|
8397
|
+
}, {
|
|
8398
|
+
x: b + 1,
|
|
8399
|
+
y
|
|
8400
|
+
}, {
|
|
8401
|
+
x: b + 1,
|
|
8402
|
+
y: y + 1
|
|
8403
|
+
});
|
|
8404
|
+
}
|
|
8405
|
+
pts.sort((p, q) => p.x - q.x || p.y - q.y);
|
|
8406
|
+
if (pts.length < 3) return pts;
|
|
8407
|
+
const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
|
|
8408
|
+
const lower = [];
|
|
8409
|
+
for (const p of pts) {
|
|
8410
|
+
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
|
|
8411
|
+
lower.push(p);
|
|
8412
|
+
}
|
|
8413
|
+
const upper = [];
|
|
8414
|
+
for (let i = pts.length - 1; i >= 0; i--) {
|
|
8415
|
+
const p = pts[i];
|
|
8416
|
+
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
|
|
8417
|
+
upper.push(p);
|
|
8418
|
+
}
|
|
8419
|
+
return lower.slice(0, -1).concat(upper.slice(0, -1));
|
|
8420
|
+
}
|
|
8421
|
+
/** The smallest circle round the points (Welzl's, iterative; the points come shuffled by a fixed seed, so the result is repeatable). */
|
|
8422
|
+
function enclosingCircle(input) {
|
|
8423
|
+
const pts = input.slice();
|
|
8424
|
+
let seed = 1;
|
|
8425
|
+
for (let i = pts.length - 1; i > 0; i--) {
|
|
8426
|
+
seed = seed * 16807 % 2147483647;
|
|
8427
|
+
const j = seed % (i + 1);
|
|
8428
|
+
[pts[i], pts[j]] = [pts[j], pts[i]];
|
|
8429
|
+
}
|
|
8430
|
+
const inside = (c, p) => Math.hypot(p.x - c.x, p.y - c.y) <= c.r + 1e-7;
|
|
8431
|
+
const two = (a, b) => ({
|
|
8432
|
+
x: (a.x + b.x) / 2,
|
|
8433
|
+
y: (a.y + b.y) / 2,
|
|
8434
|
+
r: Math.hypot(a.x - b.x, a.y - b.y) / 2
|
|
8435
|
+
});
|
|
8436
|
+
const three = (a, b, c) => {
|
|
8437
|
+
const d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
|
|
8438
|
+
if (Math.abs(d) < 1e-12) return [
|
|
8439
|
+
two(a, b),
|
|
8440
|
+
two(a, c),
|
|
8441
|
+
two(b, c)
|
|
8442
|
+
].reduce((m, k) => k.r > m.r ? k : m);
|
|
8443
|
+
const a2 = a.x * a.x + a.y * a.y;
|
|
8444
|
+
const b2 = b.x * b.x + b.y * b.y;
|
|
8445
|
+
const c2 = c.x * c.x + c.y * c.y;
|
|
8446
|
+
const x = (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d;
|
|
8447
|
+
const y = (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d;
|
|
8448
|
+
return {
|
|
8449
|
+
x,
|
|
8450
|
+
y,
|
|
8451
|
+
r: Math.hypot(a.x - x, a.y - y)
|
|
8452
|
+
};
|
|
8453
|
+
};
|
|
8454
|
+
if (!pts.length) return {
|
|
8455
|
+
x: 0,
|
|
8456
|
+
y: 0,
|
|
8457
|
+
r: 0
|
|
8458
|
+
};
|
|
8459
|
+
let c = {
|
|
8460
|
+
x: pts[0].x,
|
|
8461
|
+
y: pts[0].y,
|
|
8462
|
+
r: 0
|
|
8463
|
+
};
|
|
8464
|
+
for (let i = 1; i < pts.length; i++) {
|
|
8465
|
+
if (inside(c, pts[i])) continue;
|
|
8466
|
+
c = {
|
|
8467
|
+
x: pts[i].x,
|
|
8468
|
+
y: pts[i].y,
|
|
8469
|
+
r: 0
|
|
8470
|
+
};
|
|
8471
|
+
for (let j = 0; j < i; j++) {
|
|
8472
|
+
if (inside(c, pts[j])) continue;
|
|
8473
|
+
c = two(pts[i], pts[j]);
|
|
8474
|
+
for (let k = 0; k < j; k++) if (!inside(c, pts[k])) c = three(pts[i], pts[j], pts[k]);
|
|
8475
|
+
}
|
|
8476
|
+
}
|
|
8477
|
+
return c;
|
|
8478
|
+
}
|
|
8479
|
+
/** An ellipse (a circle when rx = ry) as four cubics. */
|
|
8480
|
+
function ellipseD(cx, cy, rx, ry) {
|
|
8481
|
+
const kx = KAPPA * rx;
|
|
8482
|
+
const ky = KAPPA * ry;
|
|
8483
|
+
return `M${num(cx + rx)} ${num(cy)}C${num(cx + rx)} ${num(cy + ky)} ${num(cx + kx)} ${num(cy + ry)} ${num(cx)} ${num(cy + ry)}C${num(cx - kx)} ${num(cy + ry)} ${num(cx - rx)} ${num(cy + ky)} ${num(cx - rx)} ${num(cy)}C${num(cx - rx)} ${num(cy - ky)} ${num(cx - kx)} ${num(cy - ry)} ${num(cx)} ${num(cy - ry)}C${num(cx + kx)} ${num(cy - ry)} ${num(cx + rx)} ${num(cy - ky)} ${num(cx + rx)} ${num(cy)}Z`;
|
|
8484
|
+
}
|
|
8485
|
+
/** A rectangle with corners of radius `r` (sharp at 0), clockwise from the top left. */
|
|
8486
|
+
function rectD(x0, y0, x1, y1, r) {
|
|
8487
|
+
if (r <= 0) return `M${num(x0)} ${num(y0)}L${num(x1)} ${num(y0)}L${num(x1)} ${num(y1)}L${num(x0)} ${num(y1)}Z`;
|
|
8488
|
+
const k = KAPPA * r;
|
|
8489
|
+
return `M${num(x0 + r)} ${num(y0)}L${num(x1 - r)} ${num(y0)}C${num(x1 - r + k)} ${num(y0)} ${num(x1)} ${num(y0 + r - k)} ${num(x1)} ${num(y0 + r)}L${num(x1)} ${num(y1 - r)}C${num(x1)} ${num(y1 - r + k)} ${num(x1 - r + k)} ${num(y1)} ${num(x1 - r)} ${num(y1)}L${num(x0 + r)} ${num(y1)}C${num(x0 + r - k)} ${num(y1)} ${num(x0)} ${num(y1 - r + k)} ${num(x0)} ${num(y1 - r)}L${num(x0)} ${num(y0 + r)}C${num(x0)} ${num(y0 + r - k)} ${num(x0 + r - k)} ${num(y0)} ${num(x0 + r)} ${num(y0)}Z`;
|
|
8490
|
+
}
|
|
8491
|
+
/**
|
|
8492
|
+
* A plain backing round the art's hull, `by` px out. Corners are sized on the
|
|
8493
|
+
* cut (`margin` out) and grow with the bleed, so the backing's edge stays the
|
|
8494
|
+
* same distance past the cut all the way round.
|
|
8495
|
+
*/
|
|
8496
|
+
function geometric(shape, hull, box, by, corners, margin) {
|
|
8497
|
+
if (shape === "circle") {
|
|
8498
|
+
const c = enclosingCircle(hull);
|
|
8499
|
+
const r = c.r + by;
|
|
8500
|
+
return {
|
|
8501
|
+
d: ellipseD(c.x, c.y, r, r),
|
|
8502
|
+
box: {
|
|
8503
|
+
x0: c.x - r,
|
|
8504
|
+
y0: c.y - r,
|
|
8505
|
+
x1: c.x + r,
|
|
8506
|
+
y1: c.y + r
|
|
8507
|
+
}
|
|
8508
|
+
};
|
|
8509
|
+
}
|
|
8510
|
+
let x0 = 1e400;
|
|
8511
|
+
let y0 = 1e400;
|
|
8512
|
+
let x1 = -1e400;
|
|
8513
|
+
let y1 = -1e400;
|
|
8514
|
+
for (const p of hull) {
|
|
8515
|
+
x0 = Math.min(x0, p.x);
|
|
8516
|
+
y0 = Math.min(y0, p.y);
|
|
8517
|
+
x1 = Math.max(x1, p.x);
|
|
8518
|
+
y1 = Math.max(y1, p.y);
|
|
8519
|
+
}
|
|
8520
|
+
if (!(x0 <= x1)) ({x0, y0, x1, y1} = box);
|
|
8521
|
+
const cx = (x0 + x1) / 2;
|
|
8522
|
+
const cy = (y0 + y1) / 2;
|
|
8523
|
+
if (shape === "oval") {
|
|
8524
|
+
const a = Math.max((x1 - x0) / 2, 1e-6);
|
|
8525
|
+
const b = Math.max((y1 - y0) / 2, 1e-6);
|
|
8526
|
+
let k = 0;
|
|
8527
|
+
for (const p of hull) k = Math.max(k, Math.hypot((p.x - cx) / a, (p.y - cy) / b));
|
|
8528
|
+
const rx = a * k + by;
|
|
8529
|
+
const ry = b * k + by;
|
|
8530
|
+
return {
|
|
8531
|
+
d: ellipseD(cx, cy, rx, ry),
|
|
8532
|
+
box: {
|
|
8533
|
+
x0: cx - rx,
|
|
8534
|
+
y0: cy - ry,
|
|
8535
|
+
x1: cx + rx,
|
|
8536
|
+
y1: cy + ry
|
|
8537
|
+
}
|
|
8538
|
+
};
|
|
8539
|
+
}
|
|
8540
|
+
if (shape === "square") {
|
|
8541
|
+
const s = Math.max(x1 - x0, y1 - y0) / 2;
|
|
8542
|
+
x0 = cx - s;
|
|
8543
|
+
x1 = cx + s;
|
|
8544
|
+
y0 = cy - s;
|
|
8545
|
+
y1 = cy + s;
|
|
8546
|
+
}
|
|
8547
|
+
const cut = Math.min(x1 - x0, y1 - y0) / 2 + margin;
|
|
8548
|
+
const r = Math.min(1, Math.max(0, corners)) * cut;
|
|
8549
|
+
const R = r > 0 ? r + (by - margin) : 0;
|
|
8550
|
+
const b = {
|
|
8551
|
+
x0: x0 - by,
|
|
8552
|
+
y0: y0 - by,
|
|
8553
|
+
x1: x1 + by,
|
|
8554
|
+
y1: y1 + by
|
|
8555
|
+
};
|
|
8556
|
+
return {
|
|
8557
|
+
d: rectD(b.x0, b.y0, b.x1, b.y1, Math.min(R, (b.x1 - b.x0) / 2, (b.y1 - b.y0) / 2)),
|
|
8558
|
+
box: b
|
|
8559
|
+
};
|
|
8560
|
+
}
|
|
8561
|
+
export { boostLines, centerline, centerlineToSvg, deblur, detectSymmetry, edgeBlur, exactPalette, fitChain, isFlat, mapPoints, oklab, parsePath, peakPalette, pointAt, presets, quantizePalette, serializePath, smoothShading, sticker, stickerSvg, toSvg, trace, traceAsync, traceCenterline, traceInlay };
|