inlaytrace 0.1.3 → 0.3.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/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  //#region src/shapes.ts
2
2
  /** How closely an outline must follow a shape: RMS and worst distance, in px, of its pixel-edge midpoints. */
3
- const MAX_RMS = .3;
3
+ const MAX_RMS$1 = .3;
4
4
  const MAX_OFF = .85;
5
5
  /** An ellipse whose axes differ by less than this is drawn as a circle. */
6
6
  const ROUND = .015;
@@ -69,7 +69,7 @@ function fits(points, distance) {
69
69
  if (d > MAX_OFF) return false;
70
70
  sum += d * d;
71
71
  }
72
- return Math.sqrt(sum / points.length) <= MAX_RMS;
72
+ return Math.sqrt(sum / points.length) <= MAX_RMS$1;
73
73
  }
74
74
  /** Into a frame centred on (cx, cy) and turned by `angle`. */
75
75
  const local = (p, cx, cy, cos, sin) => {
@@ -292,14 +292,14 @@ function withCorners(f, corners, mids) {
292
292
  //#region src/fit.ts
293
293
  const R = 6;
294
294
  const END_TRIM = 3;
295
- const SMOOTH = 12;
295
+ const SMOOTH$1 = 12;
296
296
  /**
297
297
  * A straight line is accepted at 1.5× the curve tolerance. Straight edges are
298
298
  * common in flat art, and a ripple along one is almost always JPEG noise (its
299
299
  * colour is stored in 16 px blocks), not a shape the artist drew.
300
300
  */
301
301
  const LINE_BIAS = 1.5;
302
- const sub = (a, b) => ({
302
+ const sub$1 = (a, b) => ({
303
303
  x: a.x - b.x,
304
304
  y: a.y - b.y
305
305
  });
@@ -323,49 +323,85 @@ const norm = (a) => {
323
323
  y: 0
324
324
  };
325
325
  };
326
- const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
326
+ const dist$2 = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
327
327
  const line = (a, b) => [
328
328
  a,
329
- add(a, mul(sub(b, a), 1 / 3)),
330
- add(a, mul(sub(b, a), 2 / 3)),
329
+ add(a, mul(sub$1(b, a), 1 / 3)),
330
+ add(a, mul(sub$1(b, a), 2 / 3)),
331
331
  b
332
332
  ];
333
333
  /** A cubic whose handles sit on its chord (within 0.15 px, and between the ends) is a line. */
334
334
  function isFlat([p0, c1, c2, p3]) {
335
- const d = sub(p3, p0);
335
+ const d = sub$1(p3, p0);
336
336
  const l = len(d);
337
337
  if (l < 1e-9) return true;
338
338
  const off = (p) => Math.abs((p.x - p0.x) * d.y - (p.y - p0.y) * d.x) / l;
339
- const t = (p) => dot(sub(p, p0), d) / (l * l);
339
+ const t = (p) => dot(sub$1(p, p0), d) / (l * l);
340
340
  return off(c1) < .15 && off(c2) < .15 && t(c1) >= -.01 && t(c1) <= 1.01 && t(c2) >= -.01 && t(c2) <= 1.01;
341
341
  }
342
342
  /**
343
343
  * Fit a chain. Open: from points[0] to the last point, which stay fixed.
344
344
  * Closed: points[0] is not repeated at the end; the result is a loop that starts
345
- * at a corner if there is one.
345
+ * at a corner if there is one. `fine`, if given, is the same chain placed more
346
+ * exactly (between pixels) and is what gets fitted, exact shapes included;
347
+ * `points` stays the pixel outline that the area check measures.
346
348
  */
347
- function fitChain(points, closed, o) {
348
- const pts = resample(points, closed);
349
+ function fitChain(points, closed, o, fine) {
350
+ const out = fitOnce(points, closed, o, false, fine);
351
+ if (!closed || !out.length) return out;
352
+ const want = Math.abs(loopArea(points));
353
+ if (Math.abs(loopArea(sampled(out))) >= want / 2) return out;
354
+ const loop = fitOnce(points, closed, o, true, fine);
355
+ if (loop.length && Math.abs(loopArea(sampled(loop))) >= want / 2) return loop;
356
+ return polygon(turns(points), true);
357
+ }
358
+ /** Shoelace area of a closed polygon (points[0] not repeated). */
359
+ function loopArea(pts) {
360
+ let a = 0;
361
+ for (let i = 0; i < pts.length; i++) {
362
+ const p = pts[i];
363
+ const q = pts[(i + 1) % pts.length];
364
+ a += p.x * q.y - q.x * p.y;
365
+ }
366
+ return a / 2;
367
+ }
368
+ /** A fitted loop as points, four along each cubic. */
369
+ const sampled = (cubics) => cubics.flatMap((c) => [
370
+ 0,
371
+ .25,
372
+ .5,
373
+ .75
374
+ ].map((t) => pointAt(c, t)));
375
+ /** The points of a closed outline where it changes direction. */
376
+ function turns(pts) {
377
+ const n = pts.length;
378
+ const dir = (a, b) => Math.atan2(b.y - a.y, b.x - a.x);
379
+ const out = pts.filter((p, i) => Math.abs(dir(pts[(i - 1 + n) % n], p) - dir(p, pts[(i + 1) % n])) > 1e-9);
380
+ return out.length >= 3 ? out : pts;
381
+ }
382
+ function fitOnce(points, closed, o, smoothLoop, fine) {
383
+ const pts = resample(fine ?? points, closed);
349
384
  const n = pts.length;
350
385
  if (n < 2) return [];
351
386
  if (!closed && n === 2) return [line(pts[0], pts[1])];
352
- const corners = findCorners(pts, closed, o.cornerAngle).filter((c) => closed || dist(c.at, pts[0]) >= MIN_GAP && dist(c.at, pts[n - 1]) >= MIN_GAP);
387
+ 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);
353
388
  if (closed && o.shapes) {
354
- const shape = fitShape(points, corners.map((c) => c.at));
389
+ const shape = fitShape(fine ?? points, corners.map((c) => c.at));
355
390
  if (shape) return shape.cubics;
356
391
  }
357
392
  if (closed && corners.length === 0) {
358
393
  if (n < 4) return polygon(pts, true);
359
- let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH);
394
+ let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH$1);
360
395
  const first = straights(smoothed.true, smoothed.radius, o.tolerance)[0];
361
396
  if (first && first[0] > 0 && first[0] < n) {
362
397
  const k = first[0];
363
398
  const turned = [...pts.slice(k), ...pts.slice(0, k)];
364
- smoothed = smooth([...turned, turned[0]], true, o.smoothing ?? SMOOTH);
399
+ smoothed = smooth([...turned, turned[0]], true, o.smoothing ?? SMOOTH$1);
365
400
  }
366
401
  const run = smoothed.true;
367
- const t = norm(sub(run[1], run[run.length - 2]));
368
- return flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
402
+ const t = norm(sub$1(run[1], run[run.length - 2]));
403
+ const loop = flatten(fitMixed(smoothed, o.tolerance, t, mul(t, -1), 0));
404
+ return o.snap === false ? loop : snapLines(loop, true);
369
405
  }
370
406
  const breaks = corners.map((c) => ({
371
407
  index: c.index,
@@ -395,14 +431,148 @@ function fitChain(points, closed, o) {
395
431
  }
396
432
  run[0] = from.at;
397
433
  run[run.length - 1] = to.at;
398
- out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH), o.tolerance));
434
+ out.push(...fitBetween(smooth(run, false, o.smoothing ?? SMOOTH$1), o.tolerance));
399
435
  }
400
- return flatten(out);
436
+ return o.snap === false ? flatten(out) : snapLines(flatten(out), closed);
401
437
  }
402
438
  /** Straight runs written as exact lines, so they serialise as L, not C. */
403
439
  function flatten(cubics) {
404
440
  return cubics.map((c) => isFlat(c) ? line(c[0], c[3]) : c);
405
441
  }
442
+ /** Lines within this many degrees of horizontal, vertical or 45° are made exactly that... */
443
+ const SNAP = 1;
444
+ /** ...if they are at least this long (px)... */
445
+ const SNAP_MIN = 8;
446
+ /** ...and no node moves further than this (px). */
447
+ const SNAP_MOVE = 1.5;
448
+ /**
449
+ * Make nearly horizontal, vertical and 45° lines exact. People draw those
450
+ * with a snap, and a fit to the pixels leaves them a fraction of a degree
451
+ * off (more after JPEG), which shows as a slant on a long edge and as nodes
452
+ * a hair apart when the shape is edited. Each such line is turned about its
453
+ * middle, or about an open chain's end, which stays fixed so the edge is
454
+ * still shared exactly; consecutive lines in one direction become one line;
455
+ * each node then moves to where its snapped lines meet, or onto its one
456
+ * snapped line, carrying the curve handle beside it, turned with the line.
457
+ * A needle's two sides, snapped opposite ways, are left as they were. Two lines either side
458
+ * of a junction that both snap pass through the same point, so they are
459
+ * collinear too.
460
+ */
461
+ function snapLines(cubics, closed) {
462
+ const n = cubics.length;
463
+ if (!n) return cubics;
464
+ const nodes = closed ? n : n + 1;
465
+ const node = (k) => k < n ? cubics[k][0] : cubics[n - 1][3];
466
+ const fixed = (k) => !closed && (k === 0 || k === n);
467
+ const end = (k) => closed ? (k + 1) % n : k + 1;
468
+ const prev = (k) => closed ? (k - 1 + n) % n : k - 1;
469
+ const was = cubics.map((c) => Math.atan2(c[3].y - c[0].y, c[3].x - c[0].x));
470
+ const angle = cubics.map((c, k) => {
471
+ if (!isFlat(c) || dist$2(c[0], c[3]) < SNAP_MIN) return null;
472
+ const to = Math.round(was[k] / (Math.PI / 4)) * (Math.PI / 4);
473
+ return Math.abs(was[k] - to) < SNAP * Math.PI / 180 ? to : null;
474
+ });
475
+ for (let round = 0; round <= n; round++) {
476
+ const same = (i, j) => angle[i] !== null && angle[j] !== null && Math.cos(angle[i] - angle[j]) > 1 - 1e-9;
477
+ const group = new Array(n).fill(-1);
478
+ const groups = [];
479
+ const drop = /* @__PURE__ */ new Set();
480
+ for (let k = 0; k < n; k++) {
481
+ if (angle[k] === null || group[k] >= 0) continue;
482
+ let first = k;
483
+ if (closed) for (let i = 1; i < n && same(prev(first), k) && prev(first) !== k; i++) first = prev(first);
484
+ const members = [];
485
+ for (let j = first; members.length < n && j < n && same(j, k) && group[j] < 0; j = closed ? (j + 1) % n : j + 1) {
486
+ group[j] = groups.length;
487
+ members.push(j);
488
+ }
489
+ const ends = [...new Set(members.flatMap((j) => [j, end(j)]))];
490
+ const dir = {
491
+ x: Math.cos(angle[k]),
492
+ y: Math.sin(angle[k])
493
+ };
494
+ const pinned = ends.filter(fixed).map(node);
495
+ const across = (p) => p.x * -dir.y + p.y * dir.x;
496
+ if (pinned.length > 1 && Math.abs(across(pinned[0]) - across(pinned[1])) > 1e-6) members.forEach((j) => drop.add(j));
497
+ const pts = pinned.length ? pinned : ends.map(node);
498
+ groups.push({
499
+ dir,
500
+ at: mul(pts.reduce(add, {
501
+ x: 0,
502
+ y: 0
503
+ }), 1 / pts.length),
504
+ members
505
+ });
506
+ }
507
+ const live = (j) => j >= 0 && group[j] >= 0 && !drop.has(j);
508
+ const onto = (g, p) => add(g.at, mul(g.dir, dot(sub$1(p, g.at), g.dir)));
509
+ const moved = [];
510
+ for (let k = 0; k < nodes; k++) {
511
+ const p = node(k);
512
+ const sides = [prev(k), k < n ? k : -1].filter(live);
513
+ const gs = [...new Set(sides.map((j) => group[j]))].map((i) => groups[i]);
514
+ let q = p;
515
+ if (fixed(k) || !gs.length) q = p;
516
+ else if (gs.length === 1) q = onto(gs[0], p);
517
+ else {
518
+ const meet = intersect(gs[0].at, add(gs[0].at, gs[0].dir), gs[1].at, add(gs[1].at, gs[1].dir));
519
+ if (!meet) for (const j of sides) groups[group[j]].members.forEach((m) => drop.add(m));
520
+ q = meet ?? p;
521
+ }
522
+ if (dist$2(p, q) > SNAP_MOVE) for (const j of sides) groups[group[j]].members.forEach((m) => drop.add(m));
523
+ moved.push(q);
524
+ }
525
+ for (let k = 0; k < n; k++) if (live(k) && dot(sub$1(moved[end(k) % nodes], moved[k]), sub$1(cubics[k][3], cubics[k][0])) <= 0) groups[group[k]].members.forEach((m) => drop.add(m));
526
+ if (drop.size) {
527
+ drop.forEach((j) => angle[j] = null);
528
+ continue;
529
+ }
530
+ const turned = (h, at, j) => {
531
+ if (!live(j)) return sub$1(h, at);
532
+ const t = angle[j] - was[j];
533
+ const v = sub$1(h, at);
534
+ return {
535
+ x: v.x * Math.cos(t) - v.y * Math.sin(t),
536
+ y: v.x * Math.sin(t) + v.y * Math.cos(t)
537
+ };
538
+ };
539
+ const out = [];
540
+ for (let k = 0; k < n; k++) {
541
+ const [p0, c1, c2, p3] = cubics[k];
542
+ const a = moved[k];
543
+ const b = moved[end(k) % nodes];
544
+ if (live(k)) out.push({
545
+ c: line(a, b),
546
+ g: group[k]
547
+ });
548
+ else if (isFlat(cubics[k])) out.push({
549
+ c: line(a, b),
550
+ g: -1
551
+ });
552
+ else out.push({
553
+ c: [
554
+ a,
555
+ add(a, turned(c1, p0, prev(k))),
556
+ add(b, turned(c2, p3, end(k) < n ? end(k) : -1)),
557
+ b
558
+ ],
559
+ g: -1
560
+ });
561
+ }
562
+ if (closed && out.length > 1 && out[0].g >= 0 && out[0].g === out[out.length - 1].g) {
563
+ const k = out.findIndex((o) => o.g !== out[0].g);
564
+ if (k > 0) out.push(...out.splice(0, k));
565
+ }
566
+ const merged = [];
567
+ for (const o of out) {
568
+ const last = merged[merged.length - 1];
569
+ if (last && o.g >= 0 && last.g === o.g) last.c = line(last.c[0], o.c[3]);
570
+ else merged.push({ ...o });
571
+ }
572
+ return merged.map((o) => o.c);
573
+ }
574
+ return cubics;
575
+ }
406
576
  function polygon(pts, closed) {
407
577
  const out = [];
408
578
  for (let i = 0; i < pts.length - (closed ? 0 : 1); i++) out.push(line(pts[i], pts[(i + 1) % pts.length]));
@@ -415,8 +585,8 @@ function resample(points, closed) {
415
585
  for (let i = 0; i < m; i++) {
416
586
  const a = points[i];
417
587
  const b = points[(i + 1) % points.length];
418
- if (dist(a, b) < 1e-9) continue;
419
- const k = Math.max(1, Math.ceil(dist(a, b)));
588
+ if (dist$2(a, b) < 1e-9) continue;
589
+ const k = Math.max(1, Math.ceil(dist$2(a, b)));
420
590
  for (let s = 0; s < k; s++) out.push({
421
591
  x: a.x + (b.x - a.x) * s / k,
422
592
  y: a.y + (b.y - a.y) * s / k
@@ -439,8 +609,8 @@ function along(pts, closed, i, ds) {
439
609
  if (!closed && (next < 0 || next >= n)) return null;
440
610
  const a = pts[k];
441
611
  const b = pts[(next + n) % n];
442
- const l = dist(a, b);
443
- if (l >= left) return add(a, mul(sub(b, a), left / l));
612
+ const l = dist$2(a, b);
613
+ if (l >= left) return add(a, mul(sub$1(b, a), left / l));
444
614
  left -= l;
445
615
  k = (next + n) % n;
446
616
  }
@@ -453,15 +623,15 @@ const room = (n, closed, i, side) => closed ? Infinity : side < 0 ? i : n - 1 -
453
623
  * open chain's end (a junction, where a peak often sits) it measures over what
454
624
  * is there, down to MIN_REACH px; null when even that is missing.
455
625
  */
456
- function turn(pts, closed, i, r) {
626
+ function turn$1(pts, closed, i, r) {
457
627
  const p = pts[i];
458
628
  const reach = Math.min(r, room(pts.length, closed, i, -1), room(pts.length, closed, i, 1));
459
629
  if (reach < Math.min(r, MIN_REACH)) return null;
460
630
  const before = along(pts, closed, i, -reach);
461
631
  const after = along(pts, closed, i, reach);
462
632
  if (!before || !after) return null;
463
- const a = norm(sub(p, before));
464
- const b = norm(sub(after, p));
633
+ const a = norm(sub$1(p, before));
634
+ const b = norm(sub$1(after, p));
465
635
  return Math.acos(Math.max(-1, Math.min(1, dot(a, b)))) * 180 / Math.PI;
466
636
  }
467
637
  function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
@@ -470,7 +640,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
470
640
  const meet = new Array(n).fill(null);
471
641
  const sm = lightly(pts, closed);
472
642
  for (let i = 0; i < n; i++) {
473
- const wide = turn(pts, closed, i, R);
643
+ const wide = turn$1(pts, closed, i, R);
474
644
  if (wide === null || wide < cornerAngle) continue;
475
645
  const a = arm(sm, closed, i, -1);
476
646
  const b = arm(sm, closed, i, 1);
@@ -481,13 +651,14 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
481
651
  const x = intersect(a.at, add(a.at, a.dir), b.at, add(b.at, b.dir));
482
652
  const half = interior / 2 * Math.PI / 180;
483
653
  const reachOut = 1 / Math.sin(half) - 1;
484
- if (!x || dist(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
654
+ if (!x || dist$2(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
485
655
  let d = Infinity;
486
656
  for (let k = -6; k <= R; k++) {
487
657
  const j = closed ? ((i + k) % n + n) % n : i + k;
488
- if (j >= 0 && j < n) d = Math.min(d, dist(pts[j], x));
658
+ if (j >= 0 && j < n) d = Math.min(d, dist$2(pts[j], x));
489
659
  }
490
660
  if (d / Math.max(1e-6, reachOut) > maxRounding && d > .75) continue;
661
+ if (d > .5 / Math.tan(half) + 1) continue;
491
662
  score[i] = bend;
492
663
  meet[i] = x;
493
664
  }
@@ -507,7 +678,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
507
678
  at: meet[i]
508
679
  });
509
680
  }
510
- return corners.filter((c) => !corners.some((o) => o !== c && dist(o.at, c.at) < R && (score[o.index] > score[c.index] || score[o.index] === score[c.index] && o.index < c.index)));
681
+ return corners.filter((c) => !corners.some((o) => o !== c && dist$2(o.at, c.at) < R && (score[o.index] > score[c.index] || score[o.index] === score[c.index] && o.index < c.index)));
511
682
  }
512
683
  /** ±2-point moving average; an open chain keeps its ends. Same length and indices as the input. */
513
684
  function lightly(pts, closed) {
@@ -566,12 +737,12 @@ function arm(pts, closed, i, side) {
566
737
  x: Math.cos(theta),
567
738
  y: Math.sin(theta)
568
739
  };
569
- const outward = sub(sample[sample.length - 1], sample[0]);
740
+ const outward = sub$1(sample[sample.length - 1], sample[0]);
570
741
  if (dot(dir, outward) < 0) dir = mul(dir, -1);
571
742
  const rms = Math.sqrt(sample.reduce((s, p) => s + ((p.x - cx) * dir.y - (p.y - cy) * dir.x) ** 2, 0) / sample.length);
572
743
  const mid = Math.floor(sample.length / 2);
573
- const near = norm(sub(sample[mid], sample[0]));
574
- const far = norm(sub(sample[sample.length - 1], sample[mid]));
744
+ const near = norm(sub$1(sample[mid], sample[0]));
745
+ const far = norm(sub$1(sample[sample.length - 1], sample[mid]));
575
746
  const bend = Math.acos(Math.max(-1, Math.min(1, dot(near, far)))) * 180 / Math.PI;
576
747
  return {
577
748
  at: {
@@ -584,8 +755,8 @@ function arm(pts, closed, i, side) {
584
755
  };
585
756
  }
586
757
  function intersect(a0, a1, b0, b1) {
587
- const d1 = sub(a1, a0);
588
- const d2 = sub(b1, b0);
758
+ const d1 = sub$1(a1, a0);
759
+ const d2 = sub$1(b1, b0);
589
760
  const den = d1.x * d2.y - d1.y * d2.x;
590
761
  if (Math.abs(den) < 1e-9) return null;
591
762
  const t = ((b0.x - a0.x) * d2.y - (b0.y - a0.y) * d2.x) / den;
@@ -624,8 +795,8 @@ function smooth(run, loop, half) {
624
795
  const light = avg(() => Math.min(h, 2));
625
796
  const lat = (i) => light[loop ? (i % m + m) % m : Math.max(0, Math.min(m - 1, i))];
626
797
  const radiusAt = (i, span) => {
627
- const a = norm(sub(lat(i), lat(i - span)));
628
- const b = norm(sub(lat(i + span), lat(i)));
798
+ const a = norm(sub$1(lat(i), lat(i - span)));
799
+ const b = norm(sub$1(lat(i + span), lat(i)));
629
800
  const turn = Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
630
801
  return turn > 1e-6 ? span / turn : 1e9;
631
802
  };
@@ -694,11 +865,12 @@ function fitMixed(s, tolerance, t1, t2, skipEnds) {
694
865
  let tFrom = t1;
695
866
  let fromAt = curve[0];
696
867
  for (const [i, j] of lines) {
697
- const isStub = (p, q) => dist(curve[p], curve[q]) < MIN_GAP && Math.abs(q - p) < 12;
698
- const short = i > from && isStub(from, i);
868
+ const isStub = (p, q) => dist$2(curve[p], curve[q]) < MIN_GAP && Math.abs(q - p) < 12;
869
+ const back = dot(tFrom, norm(sub$1(curve[j], curve[i]))) < 0;
870
+ const short = i > from && isStub(from, i) && !back;
699
871
  const a = short ? fromAt : curve[i];
700
872
  const b = curve[j];
701
- const dir = norm(sub(b, a));
873
+ const dir = norm(sub$1(b, a));
702
874
  if (i > from && !short) {
703
875
  const piece = curve.slice(from, i + 1);
704
876
  piece[0] = fromAt;
@@ -710,7 +882,7 @@ function fitMixed(s, tolerance, t1, t2, skipEnds) {
710
882
  fromAt = b;
711
883
  tFrom = dir;
712
884
  }
713
- if (from < n - 1 && out.length && dist(fromAt, curve[n - 1]) < MIN_GAP && n - 1 - from < 12) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
885
+ if (from < n - 1 && out.length && dist$2(fromAt, curve[n - 1]) < MIN_GAP && n - 1 - from < 12) out[out.length - 1] = line(out[out.length - 1][0], curve[n - 1]);
714
886
  else if (from < n - 1) {
715
887
  const piece = curve.slice(from);
716
888
  piece[0] = fromAt;
@@ -731,7 +903,7 @@ function straights(exact, radius, tolerance) {
731
903
  const n = exact.length;
732
904
  const straight = (i, j) => {
733
905
  const a = exact[i];
734
- const d = norm(sub(exact[j], a));
906
+ const d = norm(sub$1(exact[j], a));
735
907
  let worst = 0;
736
908
  let bow = 0;
737
909
  for (let k = i + 1; k < j; k++) {
@@ -751,7 +923,7 @@ function straights(exact, radius, tolerance) {
751
923
  }
752
924
  while (j + 1 < n && straight(i, j + 1)) j++;
753
925
  const a = exact[i];
754
- const d = norm(sub(exact[j], a));
926
+ const d = norm(sub$1(exact[j], a));
755
927
  const off = (p) => Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x);
756
928
  let s = i;
757
929
  let e = j;
@@ -761,17 +933,17 @@ function straights(exact, radius, tolerance) {
761
933
  const own = [...radius.slice(s + 1, e)].sort((x, y) => x - y)[Math.floor((e - s - 1) / 2)] ?? 1e9;
762
934
  const context = beside.length ? Math.min(own, Math.max(...beside)) : own;
763
935
  const needed = 2.5 * Math.sqrt(Math.min(1e6, context));
764
- if (e - s >= MIN_LINE && dist(exact[s], exact[e]) >= needed) found.push([s, e]);
936
+ if (e - s >= MIN_LINE && dist$2(exact[s], exact[e]) >= needed) found.push([s, e]);
765
937
  i = j;
766
938
  }
767
939
  return found;
768
940
  }
769
941
  function maxOffLine(run, a, b) {
770
- const d = sub(b, a);
942
+ const d = sub$1(b, a);
771
943
  const l = len(d);
772
944
  let worst = 0;
773
945
  for (const p of run) {
774
- const off = l < 1e-9 ? dist(p, a) : Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x) / l;
946
+ const off = l < 1e-9 ? dist$2(p, a) : Math.abs((p.x - a.x) * d.y - (p.y - a.y) * d.x) / l;
775
947
  if (off > worst) worst = off;
776
948
  }
777
949
  return worst;
@@ -786,13 +958,13 @@ const curveTolerance = (tolerance, minRadius) => Math.min(tolerance, Math.max(.3
786
958
  function endTangent(run, atEnd) {
787
959
  const n = run.length;
788
960
  const k = Math.min(n - 1, R);
789
- return atEnd ? norm(sub(run[n - 1 - k], run[n - 1])) : norm(sub(run[k], run[0]));
961
+ return atEnd ? norm(sub$1(run[n - 1 - k], run[n - 1])) : norm(sub$1(run[k], run[0]));
790
962
  }
791
963
  /** Schneider's recursive fit: one cubic, or split at the worst point and recurse. */
792
964
  function fitRun(pts, t1, t2, tolerance, depth = 0, skipStart = 0, skipEnd = 0) {
793
965
  const n = pts.length;
794
966
  if (n === 2) {
795
- const d = dist(pts[0], pts[1]) / 3;
967
+ const d = dist$2(pts[0], pts[1]) / 3;
796
968
  return [[
797
969
  pts[0],
798
970
  add(pts[0], mul(t1, d)),
@@ -800,34 +972,38 @@ function fitRun(pts, t1, t2, tolerance, depth = 0, skipStart = 0, skipEnd = 0) {
800
972
  pts[1]
801
973
  ]];
802
974
  }
803
- if (Math.acos(Math.max(-1, Math.min(1, -dot(t1, t2)))) * 180 / Math.PI > MAX_SWEEP && n >= 8 && depth <= 12 && dist(pts[0], pts[n - 1]) >= 8) {
975
+ if (Math.acos(Math.max(-1, Math.min(1, -dot(t1, t2)))) * 180 / Math.PI > MAX_SWEEP && n >= 8 && depth <= 12 && dist$2(pts[0], pts[n - 1]) >= 8) {
804
976
  const mid = Math.floor(n / 2);
805
977
  const span = Math.min(3, mid, n - 1 - mid);
806
- const tm = norm(sub(pts[mid - span], pts[mid + span]));
978
+ const tm = norm(sub$1(pts[mid - span], pts[mid + span]));
807
979
  return [...fitRun(pts.slice(0, mid + 1), t1, tm, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(mid), mul(tm, -1), t2, tolerance, depth + 1, 0, skipEnd)];
808
980
  }
809
- let u = chordParams(pts);
810
- let bez = generate(pts, u, t1, t2);
981
+ let { u, arc } = chordParams(pts);
982
+ let bez = generate(pts, u, t1, t2, arc);
811
983
  let { error, split } = maxError(pts, bez, u, skipStart, skipEnd);
812
984
  const tol2 = tolerance * tolerance;
813
985
  if (error <= tol2) return [bez];
814
986
  if (error <= tol2 * 4) for (let it = 0; it < 4; it++) {
815
987
  u = u.map((ui, i) => newton(bez, pts[i], ui));
816
- bez = generate(pts, u, t1, t2);
988
+ bez = generate(pts, u, t1, t2, arc);
817
989
  ({error, split} = maxError(pts, bez, u, skipStart, skipEnd));
818
990
  if (error <= tol2) return [bez];
819
991
  }
820
992
  if (depth > 12 || n < 4) return [bez];
821
993
  split = Math.min(n - 2, Math.max(1, split));
822
994
  const span = Math.min(3, split, n - 1 - split);
823
- const tc = norm(sub(pts[split - span], pts[split + span]));
995
+ const tc = norm(sub$1(pts[split - span], pts[split + span]));
824
996
  return [...fitRun(pts.slice(0, split + 1), t1, tc, tolerance, depth + 1, skipStart, 0), ...fitRun(pts.slice(split), mul(tc, -1), t2, tolerance, depth + 1, 0, skipEnd)];
825
997
  }
998
+ /** Each point's share of the way along the run, and the run's length. */
826
999
  function chordParams(pts) {
827
1000
  const u = [0];
828
- for (let i = 1; i < pts.length; i++) u.push(u[i - 1] + dist(pts[i], pts[i - 1]));
829
- const total = u[u.length - 1] || 1;
830
- return u.map((x) => x / total);
1001
+ for (let i = 1; i < pts.length; i++) u.push(u[i - 1] + dist$2(pts[i], pts[i - 1]));
1002
+ const arc = u[u.length - 1];
1003
+ return {
1004
+ u: u.map((x) => x / (arc || 1)),
1005
+ arc
1006
+ };
831
1007
  }
832
1008
  const B = [
833
1009
  (t) => (1 - t) ** 3,
@@ -838,8 +1014,8 @@ const B = [
838
1014
  function pointAt(b, t) {
839
1015
  return add(add(mul(b[0], B[0](t)), mul(b[1], B[1](t))), add(mul(b[2], B[2](t)), mul(b[3], B[3](t))));
840
1016
  }
841
- /** Least-squares handle lengths along the given tangents (Schneider's GenerateBezier). */
842
- function generate(pts, u, t1, t2) {
1017
+ /** Least-squares handle lengths along the given tangents (Schneider's GenerateBezier); `arc` is the run's length. */
1018
+ function generate(pts, u, t1, t2, arc) {
843
1019
  const p0 = pts[0];
844
1020
  const p3 = pts[pts.length - 1];
845
1021
  let c00 = 0;
@@ -853,15 +1029,15 @@ function generate(pts, u, t1, t2) {
853
1029
  c00 += dot(a1, a1);
854
1030
  c01 += dot(a1, a2);
855
1031
  c11 += dot(a2, a2);
856
- const tmp = sub(pts[i], add(mul(p0, B[0](u[i]) + B[1](u[i])), mul(p3, B[2](u[i]) + B[3](u[i]))));
1032
+ const tmp = sub$1(pts[i], add(mul(p0, B[0](u[i]) + B[1](u[i])), mul(p3, B[2](u[i]) + B[3](u[i]))));
857
1033
  x0 += dot(a1, tmp);
858
1034
  x1 += dot(a2, tmp);
859
1035
  }
860
1036
  const det = c00 * c11 - c01 * c01;
861
1037
  let alpha1 = Math.abs(det) > 1e-12 ? (x0 * c11 - x1 * c01) / det : 0;
862
1038
  let alpha2 = Math.abs(det) > 1e-12 ? (c00 * x1 - c01 * x0) / det : 0;
863
- const seg = dist(p0, p3);
864
- if (alpha1 < 1e-6 * seg || alpha2 < 1e-6 * seg) alpha1 = alpha2 = seg / 3;
1039
+ const seg = dist$2(p0, p3);
1040
+ if (alpha1 < 1e-6 * seg || alpha2 < 1e-6 * seg || alpha1 > arc || alpha2 > arc) alpha1 = alpha2 = seg / 3;
865
1041
  return [
866
1042
  p0,
867
1043
  add(p0, mul(t1, alpha1)),
@@ -891,67 +1067,198 @@ function maxError(pts, b, u, skipStart = 0, skipEnd = 0) {
891
1067
  /** One Newton–Raphson step towards the parameter of the point on `b` nearest `p`. */
892
1068
  function newton(b, p, u) {
893
1069
  const d1 = [
894
- mul(sub(b[1], b[0]), 3),
895
- mul(sub(b[2], b[1]), 3),
896
- mul(sub(b[3], b[2]), 3)
1070
+ mul(sub$1(b[1], b[0]), 3),
1071
+ mul(sub$1(b[2], b[1]), 3),
1072
+ mul(sub$1(b[3], b[2]), 3)
897
1073
  ];
898
- const d2 = [mul(sub(d1[1], d1[0]), 2), mul(sub(d1[2], d1[1]), 2)];
1074
+ const d2 = [mul(sub$1(d1[1], d1[0]), 2), mul(sub$1(d1[2], d1[1]), 2)];
899
1075
  const q = pointAt(b, u);
900
1076
  const q1 = add(add(mul(d1[0], (1 - u) ** 2), mul(d1[1], 2 * u * (1 - u))), mul(d1[2], u * u));
901
1077
  const q2 = add(mul(d2[0], 1 - u), mul(d2[1], u));
902
- const num = dot(sub(q, p), q1);
903
- const den = dot(q1, q1) + dot(sub(q, p), q2);
1078
+ const num = dot(sub$1(q, p), q1);
1079
+ const den = dot(q1, q1) + dot(sub$1(q, p), q2);
904
1080
  if (Math.abs(den) < 1e-12) return u;
905
1081
  return Math.min(1, Math.max(0, u - num / den));
906
1082
  }
907
1083
  //#endregion
908
1084
  //#region src/palette.ts
909
- function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002 } = {}) {
910
- const bins = /* @__PURE__ */ new Map();
911
- let opaque = 0;
912
- for (let i = 0; i < rgba.length; i += 4) {
913
- if (rgba[i + 3] < 128) continue;
914
- const r = rgba[i];
915
- const g = rgba[i + 1];
916
- const b = rgba[i + 2];
917
- const key = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
918
- const bin = bins.get(key);
919
- if (bin) {
920
- bin.n++;
921
- bin.r += r;
922
- bin.g += g;
923
- bin.b += b;
924
- } else bins.set(key, {
925
- n: 1,
926
- r,
927
- g,
928
- b
929
- });
930
- opaque++;
931
- }
932
- const sorted = [...bins.values()].sort((a, b) => b.n - a.n);
1085
+ function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minDetail = 5e-4, width, minTint = .02, minFlat = .001 } = {}) {
1086
+ const bins = histogram(rgba);
1087
+ for (let i = 0; i < rgba.length; i += 4) if (rgba[i + 3] >= 128) bins.add(i);
1088
+ const opaque = bins.total;
1089
+ const flat = width ? flatBins(rgba, width) : null;
1090
+ const items = bins.keys.map((key) => {
1091
+ const rgb = bins.mean(key);
1092
+ return {
1093
+ n: bins.n[key],
1094
+ flat: flat?.n[key] ?? 0,
1095
+ rgb,
1096
+ lab: oklab(rgb),
1097
+ weight: 0,
1098
+ flatWeight: 0,
1099
+ peak: true
1100
+ };
1101
+ });
1102
+ weigh(items, minDistance / 2);
1103
+ const sorted = items.filter((it) => it.peak).sort((a, b) => b.weight - a.weight || b.n - a.n);
933
1104
  const picked = [];
934
- for (const bin of sorted) {
1105
+ for (const it of sorted) {
935
1106
  if (picked.length >= maxColors) break;
936
- if (bin.n / opaque < minShare && picked.length > 0) break;
937
- const rgb = [
938
- bin.r / bin.n,
939
- bin.g / bin.n,
940
- bin.b / bin.n
941
- ];
942
- const lab = oklab(rgb);
943
- if (picked.every((p) => distance(p.lab, lab) >= minDistance)) picked.push({
944
- lab,
945
- rgb
1107
+ const share = it.weight / opaque;
1108
+ if (share < minDetail && picked.length > 0) break;
1109
+ if (!picked.every((p) => distance(p.lab, it.lab) >= minDistance)) continue;
1110
+ if ((share < minShare || flat !== null && share < EDGE_SHARE && it.flatWeight < EDGE_FLAT * it.weight) && isBlend(it.rgb, it.lab, picked, minDistance)) continue;
1111
+ picked.push({
1112
+ lab: it.lab,
1113
+ rgb: it.rgb
946
1114
  });
947
1115
  }
1116
+ if (flat && picked.length < maxColors) picked.push(...flatTints(flat, opaque, picked, maxColors - picked.length, minTint, minFlat));
948
1117
  return picked.map((p) => toHex(p.rgb));
949
1118
  }
950
- function oklab([r, g, b]) {
951
- const lin = (c) => {
952
- c /= 255;
953
- return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
1119
+ /** Below this share of flat pixels, a colour is an edge's, not a fill's. */
1120
+ const EDGE_FLAT = .05;
1121
+ /**
1122
+ * But only below this share of the image: 1 px grey rules or a dithered fill
1123
+ * are never flat either, and at 8% of a logo they are a colour of their own.
1124
+ */
1125
+ const EDGE_SHARE = .02;
1126
+ /**
1127
+ * Pixels binned at 5 bits per channel (a 15-bit key), with each bin's colour
1128
+ * sums for its true mean. Typed arrays, not a Map: with the flat pass this
1129
+ * took a third less time on a 2048 px logo. `keys`
1130
+ * lists the used bins in the order first seen, as a Map would iterate them.
1131
+ */
1132
+ function histogram(rgba) {
1133
+ const n = /* @__PURE__ */ new Uint32Array(32768);
1134
+ const sum = /* @__PURE__ */ new Float64Array(98304);
1135
+ const keys = [];
1136
+ const bins = {
1137
+ n,
1138
+ keys,
1139
+ total: 0,
1140
+ add(i) {
1141
+ const key = rgba[i] >> 3 << 10 | rgba[i + 1] >> 3 << 5 | rgba[i + 2] >> 3;
1142
+ if (!n[key]++) keys.push(key);
1143
+ sum[key * 3] += rgba[i];
1144
+ sum[key * 3 + 1] += rgba[i + 1];
1145
+ sum[key * 3 + 2] += rgba[i + 2];
1146
+ bins.total++;
1147
+ },
1148
+ mean: (key) => [
1149
+ sum[key * 3] / n[key],
1150
+ sum[key * 3 + 1] / n[key],
1151
+ sum[key * 3 + 2] / n[key]
1152
+ ]
954
1153
  };
1154
+ return bins;
1155
+ }
1156
+ /**
1157
+ * The image's flat pixels, binned as peakPalette bins them. A pixel is flat
1158
+ * when its four neighbours are within 8 of it in every channel: inside a fill,
1159
+ * never on an anti-aliased edge or in JPEG ringing.
1160
+ */
1161
+ function flatBins(rgba, w) {
1162
+ const h = Math.floor(rgba.length / 4 / w);
1163
+ const bins = histogram(rgba);
1164
+ const near = new Uint8Array(w * h);
1165
+ const close = (i, j) => rgba[i + 3] >= 128 && rgba[j + 3] >= 128 && Math.abs(rgba[i] - rgba[j]) <= 8 && Math.abs(rgba[i + 1] - rgba[j + 1]) <= 8 && Math.abs(rgba[i + 2] - rgba[j + 2]) <= 8;
1166
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
1167
+ const p = y * w + x;
1168
+ near[p] = (x < w - 1 && close(p * 4, p * 4 + 4) ? 1 : 0) | (y < h - 1 && close(p * 4, (p + w) * 4) ? 2 : 0);
1169
+ }
1170
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
1171
+ const p = y * w + x;
1172
+ if ((near[p] & 3) === 3 && near[p - 1] & 1 && near[p - w] & 2) bins.add(p * 4);
1173
+ }
1174
+ return bins;
1175
+ }
1176
+ /**
1177
+ * Each item's weight (the pixels of every bin within `radius` of it in OKLab)
1178
+ * and flat weight, and whether it is a local peak (no bin within
1179
+ * `radius` has more). A grid of `radius` cells keeps it near linear.
1180
+ */
1181
+ function weigh(items, radius) {
1182
+ radius = Math.max(radius, .001);
1183
+ const cell = (v) => Math.floor(v / radius);
1184
+ const grid = /* @__PURE__ */ new Map();
1185
+ for (const it of items) {
1186
+ const k = `${cell(it.lab[0])},${cell(it.lab[1])},${cell(it.lab[2])}`;
1187
+ const list = grid.get(k);
1188
+ if (list) list.push(it);
1189
+ else grid.set(k, [it]);
1190
+ }
1191
+ for (const it of items) {
1192
+ const [cl, ca, cb] = it.lab.map(cell);
1193
+ 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) {
1194
+ it.weight += o.n;
1195
+ it.flatWeight += o.flat;
1196
+ if (o.n > it.n) it.peak = false;
1197
+ }
1198
+ }
1199
+ }
1200
+ /**
1201
+ * Pale tints: flat colours at least `minTint` from every colour picked, each
1202
+ * flat over at least `minFlat` of the image, heaviest first. On a
1203
+ * sinking-ship illustration (blue outlines on white, the ship and moon filled
1204
+ * with pale blues) this found the three fills and nothing else.
1205
+ */
1206
+ /**
1207
+ * Tints are pale (OKLab lightness): a photo's smooth sky or skin is flat too,
1208
+ * and its dark shades filled Illustration's 16 colours with near-copies that
1209
+ * doubled the SVG. The fills tints exist for are light washes behind ink.
1210
+ */
1211
+ const TINT_LIGHTNESS = .85;
1212
+ function flatTints(flat, opaque, picked, room, minTint, minFlat) {
1213
+ const items = flat.keys.map((key) => {
1214
+ const rgb = flat.mean(key);
1215
+ return {
1216
+ n: flat.n[key],
1217
+ flat: flat.n[key],
1218
+ rgb,
1219
+ lab: oklab(rgb),
1220
+ weight: 0,
1221
+ flatWeight: 0,
1222
+ peak: true
1223
+ };
1224
+ });
1225
+ weigh(items, minTint / 2);
1226
+ const out = [];
1227
+ const tint = (it) => it.peak && it.lab[0] >= TINT_LIGHTNESS && it.weight >= minFlat * opaque;
1228
+ for (const it of items.filter(tint).sort((a, b) => b.weight - a.weight)) {
1229
+ if (out.length >= room) break;
1230
+ if ([...picked, ...out].every((p) => distance(p.lab, it.lab) >= minTint)) out.push({
1231
+ lab: it.lab,
1232
+ rgb: it.rgb
1233
+ });
1234
+ }
1235
+ return out;
1236
+ }
1237
+ /**
1238
+ * Whether a colour lies near the line between two picked colours, mixed as a
1239
+ * renderer mixes them (in sRGB): the nearest mix is within `tolerance` (OKLab).
1240
+ */
1241
+ function isBlend(rgb, lab, picked, tolerance) {
1242
+ for (let i = 0; i < picked.length; i++) for (let j = i + 1; j < picked.length; j++) {
1243
+ const a = picked[i].rgb;
1244
+ const b = picked[j].rgb;
1245
+ const d = [
1246
+ b[0] - a[0],
1247
+ b[1] - a[1],
1248
+ b[2] - a[2]
1249
+ ];
1250
+ const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
1251
+ if (!len) continue;
1252
+ 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));
1253
+ if (distance(oklab([
1254
+ a[0] + t * d[0],
1255
+ a[1] + t * d[1],
1256
+ a[2] + t * d[2]
1257
+ ]), lab) < tolerance) return true;
1258
+ }
1259
+ return false;
1260
+ }
1261
+ function oklab([r, g, b]) {
955
1262
  const [lr, lg, lb] = [
956
1263
  lin(r),
957
1264
  lin(g),
@@ -966,6 +1273,24 @@ function oklab([r, g, b]) {
966
1273
  .0259040371 * l + .7827717662 * m - .808675766 * s
967
1274
  ];
968
1275
  }
1276
+ const linear = (c) => {
1277
+ c /= 255;
1278
+ return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
1279
+ };
1280
+ /**
1281
+ * sRGB to linear light, from a table at 1/16 steps: labelling reads hundreds of
1282
+ * mixes per in-between colour (every pair of a 24-colour palette), and the
1283
+ * power was half its time. Interpolated, it is within 1e-7 of the formula.
1284
+ */
1285
+ const LIN_STEPS = 16;
1286
+ const LIN = Float64Array.from({ length: 4082 }, (_, i) => linear(i / LIN_STEPS));
1287
+ function lin(c) {
1288
+ if (!(c > 0)) return 0;
1289
+ if (c >= 255) return linear(c);
1290
+ const x = c * LIN_STEPS;
1291
+ const i = Math.floor(x);
1292
+ return LIN[i] + (LIN[i + 1] - LIN[i]) * (x - i);
1293
+ }
969
1294
  /**
970
1295
  * A photo's palette: `maxColors` colours that best summarise it, by k-means in
971
1296
  * OKLab (so the clusters are perceptual, not RGB boxes).
@@ -1105,6 +1430,12 @@ function exactPalette(rgba, maxColors) {
1105
1430
  }
1106
1431
  return [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0]).slice(0, Math.max(1, maxColors)).map(([k]) => `#${k.toString(16).padStart(6, "0")}`);
1107
1432
  }
1433
+ /** '#rrggbb' as [r, g, b]. */
1434
+ const hexToRgb = (hex) => [
1435
+ parseInt(hex.slice(1, 3), 16),
1436
+ parseInt(hex.slice(3, 5), 16),
1437
+ parseInt(hex.slice(5, 7), 16)
1438
+ ];
1108
1439
  //#endregion
1109
1440
  //#region src/path.ts
1110
1441
  const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
@@ -1305,11 +1636,11 @@ function close(sub) {
1305
1636
  nodes.pop();
1306
1637
  }
1307
1638
  }
1308
- const num = (n) => {
1639
+ const num$1 = (n) => {
1309
1640
  const r = Math.round(n * 1e3) / 1e3;
1310
1641
  return Object.is(r, -0) ? "0" : String(r);
1311
1642
  };
1312
- const pt = (p) => `${num(p.x)} ${num(p.y)}`;
1643
+ const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
1313
1644
  function segment(a, b) {
1314
1645
  return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
1315
1646
  }
@@ -1339,167 +1670,2031 @@ function mapPoints(subs, f) {
1339
1670
  }))
1340
1671
  }));
1341
1672
  }
1342
- //#endregion
1343
- //#region src/inlay.ts
1344
- /**
1345
- * Inlay, our shared-edge tracer: every preset, from logos to photos.
1346
- * Like inlaid wood, every piece is cut to fit its neighbours exactly.
1347
- *
1348
- * VTracer traces every colour region on its own, so an edge between two
1349
- * regions is traced twice. Fitting the two copies separately leaves hairline
1350
- * gaps and slivers; leaving them to VTracer's spline fitter gives the wobbly
1351
- * lines and rounded corners this replaces. Instead:
1352
- *
1353
- * 1. Label every pixel with a palette colour (or ink / paper for line art).
1354
- * Anti-aliased pixels, which sit between two colours, take the closest
1355
- * colour *among their neighbours*, so an edge between red and blue never
1356
- * grows a one-pixel purple sliver.
1357
- * 2. Merge specks smaller than `speckle`² pixels into whatever surrounds them.
1358
- * 3. Walk the cracks between differently labelled pixels. Where three or more
1359
- * regions meet (or two meet diagonally) is a junction; every boundary
1360
- * between two junctions is one chain, with one region on each side.
1361
- * 4. Fit each chain once (src/lib/fit.ts): corners first, then straight lines
1362
- * where they fit and curves where they don't.
1363
- * 5. Build each region's outline from its chains, reversing the ones it sees
1364
- * from the other side. Neighbours share the exact same fitted edge: no
1365
- * gaps, no overlaps, which is also what a vinyl cutter wants.
1366
- *
1367
- * Regions are 4-connected, so two pixels touching only at a corner are
1368
- * separate shapes, and each region is one <path> (its outline plus its holes,
1369
- * wound oppositely so the default nonzero fill rule cuts the holes). With
1370
- * `stacked`, a region keeps only its outline (and any holes onto
1371
- * transparency), and paint order does the rest.
1372
- */
1373
- const VOID = -1;
1374
- /** The trace as an SVG document. */
1375
- function toSvg(r) {
1376
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${r.width}" height="${r.height}" viewBox="0 0 ${r.width} ${r.height}">\n${r.paths.map((p) => `<path d="${p.d}" fill="${p.fill}"/>`).join("\n")}\n</svg>\n`;
1673
+ const sub = (a, b) => ({
1674
+ x: a.x - b.x,
1675
+ y: a.y - b.y
1676
+ });
1677
+ const dist$1 = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
1678
+ const unit = (a) => {
1679
+ const l = Math.hypot(a.x, a.y);
1680
+ return l > 1e-9 ? {
1681
+ x: a.x / l,
1682
+ y: a.y / l
1683
+ } : null;
1684
+ };
1685
+ /** The direction a run of cubics leaves its first point in. */
1686
+ function startDir(cubics) {
1687
+ const [a, b, c, d] = cubics[0];
1688
+ return unit(sub(b, a)) ?? unit(sub(c, a)) ?? unit(sub(d, a));
1377
1689
  }
1378
- /** Trace to an SVG string; `trace` gives the shapes as data. */
1379
- const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
1380
- /**
1381
- * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
1382
- * into filled shapes that share their edges exactly.
1383
- */
1384
- function trace(rgba, w, h, o) {
1385
- const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette) : labelBinary(rgba, w, h, o.threshold);
1386
- if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
1387
- if (!o.pixels) despur(labels, w, h);
1388
- mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
1389
- const { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
1390
- const chains = findChains(comp, w, h);
1391
- const byComp = /* @__PURE__ */ new Map();
1392
- for (const c of chains) {
1393
- const cubics = o.pixels ? staircase(c.pts, c.closed) : fitChain(c.pts, c.closed, o);
1394
- if (!cubics.length) continue;
1395
- if (c.left !== VOID) addOriented(byComp, c.left, {
1396
- ...c,
1397
- cubics,
1398
- reversed: false
1399
- });
1400
- if (c.right !== VOID) addOriented(byComp, c.right, {
1401
- ...c,
1402
- cubics: reverse(cubics),
1403
- reversed: true
1404
- });
1405
- }
1406
- const voids = o.stacked ? voidSeeds(comp, w, h) : [];
1407
- const shapes = [];
1408
- for (const [id, chains] of byComp) {
1409
- let loops = assemble(chains);
1410
- if (!loops.length) continue;
1411
- let area = compArea[id];
1412
- if (o.stacked) {
1413
- const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
1414
- loops = loops.filter((l) => l === outer || l.touchesVoid || voids.some((p) => encloses(l.pts, p)));
1415
- area = Math.abs(outer.area);
1416
- }
1417
- shapes.push({
1418
- subs: loops.map((l) => l.sub),
1419
- fill: colors[compLabel[id]],
1420
- area
1421
- });
1690
+ /** The direction a run of cubics arrives at its last point in. */
1691
+ function endDir(cubics) {
1692
+ const [a, b, c, d] = cubics[cubics.length - 1];
1693
+ return unit(sub(d, c)) ?? unit(sub(d, b)) ?? unit(sub(d, a));
1694
+ }
1695
+ /** How far (degrees) an outline arriving along `u` turns to leave along `v`: 0 is straight on. */
1696
+ function turn(u, v) {
1697
+ return Math.acos(Math.max(-1, Math.min(1, u.x * v.x + u.y * v.y))) * 180 / Math.PI;
1698
+ }
1699
+ /** Whether a cubic's end is straight: its last (or first) cubic is flat. */
1700
+ const straightEnd = (cubics, atEnd) => isFlat(cubics[atEnd ? cubics.length - 1 : 0]);
1701
+ /** The least-squares circle through `pts` (Kåsa's algebraic fit), or null if they are near a line. */
1702
+ function fitCircle(pts) {
1703
+ if (pts.length < 5) return null;
1704
+ let mx = 0;
1705
+ let my = 0;
1706
+ for (const p of pts) mx += p.x, my += p.y;
1707
+ mx /= pts.length;
1708
+ my /= pts.length;
1709
+ let suu = 0;
1710
+ let suv = 0;
1711
+ let svv = 0;
1712
+ let suuu = 0;
1713
+ let svvv = 0;
1714
+ let suvv = 0;
1715
+ let svuu = 0;
1716
+ for (const p of pts) {
1717
+ const u = p.x - mx;
1718
+ const v = p.y - my;
1719
+ suu += u * u;
1720
+ suv += u * v;
1721
+ svv += v * v;
1722
+ suuu += u * u * u;
1723
+ svvv += v * v * v;
1724
+ suvv += u * v * v;
1725
+ svuu += v * u * u;
1422
1726
  }
1423
- shapes.sort((a, b) => b.area - a.area);
1727
+ const det = suu * svv - suv * suv;
1728
+ if (Math.abs(det) < 1e-9) return null;
1729
+ const bu = (suuu + suvv) / 2;
1730
+ const bv = (svvv + svuu) / 2;
1731
+ const uc = (bu * svv - bv * suv) / det;
1732
+ const vc = (bv * suu - bu * suv) / det;
1733
+ const r = Math.sqrt(uc * uc + vc * vc + (suu + svv) / pts.length);
1424
1734
  return {
1425
- width: w,
1426
- height: h,
1427
- paths: shapes.map((x) => ({
1428
- d: serializePath(x.subs),
1429
- fill: x.fill
1430
- }))
1735
+ cx: uc + mx,
1736
+ cy: vc + my,
1737
+ r
1431
1738
  };
1432
1739
  }
1433
- /**
1434
- * A chain as its exact pixel boundary: a line between each pair of turns.
1435
- * The points are pixel corners about a pixel apart, so a run of them in one
1436
- * direction is one straight edge. A closed loop starts at a turn, so its seam
1437
- * isn't a node in the middle of an edge.
1438
- */
1439
- function staircase(pts, closed) {
1440
- const n = pts.length;
1441
- if (n < 2) return [];
1442
- const dir = (a, b) => `${Math.sign(b.x - a.x)},${Math.sign(b.y - a.y)}`;
1443
- const isTurn = (i) => {
1444
- const a = pts[(i - 1 + n) % n];
1445
- const b = pts[i];
1446
- const c = pts[(i + 1) % n];
1447
- return dir(a, b) !== dir(b, c);
1448
- };
1449
- const keep = [];
1450
- if (closed) {
1451
- const start = pts.findIndex((_, i) => isTurn(i));
1452
- if (start < 0) return [];
1453
- for (let k = 0; k < n; k++) {
1454
- const i = (start + k) % n;
1455
- if (isTurn(i)) keep.push(pts[i]);
1456
- }
1457
- keep.push(keep[0]);
1458
- } else {
1459
- keep.push(pts[0]);
1460
- for (let i = 1; i < n - 1; i++) if (isTurn(i)) keep.push(pts[i]);
1461
- keep.push(pts[n - 1]);
1462
- }
1740
+ /** An arc of `c` from p0 to p1, leaving p0 along `t0`, as cubics of at most a quarter turn each. */
1741
+ function arc(c, p0, p1, t0) {
1742
+ const a0 = Math.atan2(p0.y - c.cy, p0.x - c.cx);
1743
+ const a1 = Math.atan2(p1.y - c.cy, p1.x - c.cx);
1744
+ const dir = -Math.sin(a0) * t0.x + Math.cos(a0) * t0.y >= 0 ? 1 : -1;
1745
+ let sweep = dir * (a1 - a0);
1746
+ while (sweep <= 0) sweep += 2 * Math.PI;
1747
+ while (sweep > 2 * Math.PI) sweep -= 2 * Math.PI;
1748
+ const n = Math.max(1, Math.ceil(sweep / (Math.PI / 2) - 1e-6));
1749
+ const step = dir * sweep / n;
1750
+ const k = 4 / 3 * Math.tan(step / 4);
1751
+ const at = (a) => ({
1752
+ x: c.cx + c.r * Math.cos(a),
1753
+ y: c.cy + c.r * Math.sin(a)
1754
+ });
1463
1755
  const out = [];
1464
- for (let i = 1; i < keep.length; i++) {
1465
- const a = keep[i - 1];
1466
- const b = keep[i];
1756
+ for (let i = 0; i < n; i++) {
1757
+ const s = a0 + i * step;
1758
+ const e = s + step;
1759
+ const ps = i === 0 ? p0 : at(s);
1760
+ const pe = i === n - 1 ? p1 : at(e);
1467
1761
  out.push([
1468
- a,
1762
+ ps,
1469
1763
  {
1470
- x: a.x + (b.x - a.x) / 3,
1471
- y: a.y + (b.y - a.y) / 3
1764
+ x: ps.x - k * c.r * Math.sin(s),
1765
+ y: ps.y + k * c.r * Math.cos(s)
1472
1766
  },
1473
1767
  {
1474
- x: a.x + (b.x - a.x) * 2 / 3,
1475
- y: a.y + (b.y - a.y) * 2 / 3
1768
+ x: pe.x + k * c.r * Math.sin(e),
1769
+ y: pe.y - k * c.r * Math.cos(e)
1476
1770
  },
1477
- b
1771
+ pe
1478
1772
  ]);
1479
1773
  }
1480
1774
  return out;
1481
1775
  }
1482
- /** Relabel merged colours as their targets, following chains, in place. */
1483
- function mergeLabels(labels, colors, merge) {
1484
- const index = new Map(colors.map((c, i) => [c, i]));
1485
- const remap = colors.map((c, i) => {
1486
- let to = c;
1487
- let at = i;
1488
- const seen = /* @__PURE__ */ new Set();
1489
- while (merge[to] && !seen.has(to)) {
1490
- seen.add(to);
1491
- to = merge[to].toLowerCase();
1492
- const k = index.get(to);
1493
- if (k !== void 0) at = k;
1776
+ /** Where the line on from p0 along t0 meets the line back from p1 along t1, if ahead of both. */
1777
+ function meet(p0, t0, p1, t1) {
1778
+ const den = t0.x * t1.y - t0.y * t1.x;
1779
+ if (Math.abs(den) < .05) return null;
1780
+ const d = sub(p1, p0);
1781
+ const s = (d.x * t1.y - d.y * t1.x) / den;
1782
+ const u = (t0.x * d.y - t0.y * d.x) / den;
1783
+ const span = dist$1(p0, p1);
1784
+ if (s < .5 || u < .5 || s > 4 * span + 4 || u > 4 * span + 4) return null;
1785
+ return {
1786
+ x: p0.x + s * t0.x,
1787
+ y: p0.y + s * t0.y
1788
+ };
1789
+ }
1790
+ /** How a circle fits `pts`: RMS and worst distance from it. */
1791
+ function circleError(c, pts) {
1792
+ let sq = 0;
1793
+ let worst = 0;
1794
+ for (const p of pts) {
1795
+ const e = Math.abs(Math.hypot(p.x - c.cx, p.y - c.cy) - c.r);
1796
+ sq += e * e;
1797
+ worst = Math.max(worst, e);
1798
+ }
1799
+ return {
1800
+ rms: Math.sqrt(sq / pts.length),
1801
+ worst
1802
+ };
1803
+ }
1804
+ /** The angle (radians) the points span round a centre: 2π less the widest gap between them. */
1805
+ function spanned(c, pts) {
1806
+ const a = pts.map((p) => Math.atan2(p.y - c.cy, p.x - c.cx)).sort((x, y) => x - y);
1807
+ let gap = a[0] + 2 * Math.PI - a[a.length - 1];
1808
+ for (let i = 1; i < a.length; i++) gap = Math.max(gap, a[i] - a[i - 1]);
1809
+ return 2 * Math.PI - gap;
1810
+ }
1811
+ /** Points along cubics, about a pixel apart. */
1812
+ function sample(cubics) {
1813
+ const out = [];
1814
+ for (const c of cubics) {
1815
+ 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])));
1816
+ for (let i = 0; i < n; i++) out.push(pointAt(c, i / n));
1817
+ }
1818
+ return out;
1819
+ }
1820
+ /** A circle must fit the visible outline this closely (px)... */
1821
+ const CIRCLE_RMS = .5;
1822
+ const CIRCLE_WORST = 1.5;
1823
+ /** ...and the visible outline span at least this much of it (radians). */
1824
+ const CIRCLE_SPAN = Math.PI / 2;
1825
+ /** A completion may stray outside the shapes in front by this share of its length (fitting error near the ends). */
1826
+ const STRAY = .05;
1827
+ /**
1828
+ * The hidden part of an outline, from p0 (where it goes under a shape in
1829
+ * front, arriving along t0) to p1 (where it comes out, leaving along t1), or
1830
+ * null if no continuation stays hidden. `visible` is the rest of the outline;
1831
+ * `straight0`/`straight1` say whether it is straight where it goes under and
1832
+ * comes out; `hidden(p)` whether a point is under a shape in front.
1833
+ */
1834
+ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
1835
+ const candidates = [];
1836
+ if (!straight0 && !straight1) {
1837
+ const c = fitCircle(visible);
1838
+ if (c && c.r > 2) {
1839
+ const e = circleError(c, visible);
1840
+ const ends = Math.max(Math.abs(dist$1(p0, {
1841
+ x: c.cx,
1842
+ y: c.cy
1843
+ }) - c.r), Math.abs(dist$1(p1, {
1844
+ x: c.cx,
1845
+ y: c.cy
1846
+ }) - c.r));
1847
+ if (e.rms < CIRCLE_RMS && e.worst < CIRCLE_WORST && ends < CIRCLE_WORST && spanned(c, visible) >= CIRCLE_SPAN) candidates.push(arc(c, p0, p1, t0));
1494
1848
  }
1495
- return at;
1496
- });
1497
- if (remap.every((t, i) => t === i)) return;
1498
- for (let i = 0; i < labels.length; i++) labels[i] = remap[labels[i]];
1849
+ }
1850
+ if (straight0 && straight1) {
1851
+ const q = meet(p0, t0, p1, t1);
1852
+ if (q) candidates.push([line(p0, q), line(q, p1)]);
1853
+ else if (turn(t0, t1) < 20 && turn(t0, unit(sub(p1, p0)) ?? t0) < 20) candidates.push([line(p0, p1)]);
1854
+ }
1855
+ const l = dist$1(p0, p1) / 3;
1856
+ if (l > 0) candidates.push([[
1857
+ p0,
1858
+ {
1859
+ x: p0.x + t0.x * l,
1860
+ y: p0.y + t0.y * l
1861
+ },
1862
+ {
1863
+ x: p1.x - t1.x * l,
1864
+ y: p1.y - t1.y * l
1865
+ },
1866
+ p1
1867
+ ]]);
1868
+ for (const c of candidates) {
1869
+ if (!c) continue;
1870
+ const pts = sample(c);
1871
+ let out = 0;
1872
+ for (const p of pts) if (!hidden(p)) out++;
1873
+ if (out <= STRAY * pts.length) return c;
1874
+ }
1875
+ return null;
1499
1876
  }
1500
- function labelPalette(rgba, w, h, palette) {
1501
- const pal = palette.map(hexToRgb);
1502
- const labs = pal.map(oklab);
1877
+ //#endregion
1878
+ //#region src/skeleton.ts
1879
+ /**
1880
+ * Skeleton strokes: thin ink to a one-pixel skeleton and fit it as strokes
1881
+ * down the middle. Centerline traces a whole drawing this way; outline art
1882
+ * (`strokes` in the colour tracer) traces just its thin lines.
1883
+ *
1884
+ * 1. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
1885
+ * algorithm for thinning digital patterns", CACM 1984).
1886
+ * 2. Measure the stroke width: the ink's area over the skeleton's length.
1887
+ * 3. Prune spurs: short branches that thinning grows from bumps in the
1888
+ * outline, anything shorter than the stroke is wide.
1889
+ * 4. Walk the skeleton into chains between ends and junctions. Thinning bends
1890
+ * the skeleton toward each junction, so within a stroke width of one the
1891
+ * arms are dropped and drawn straight on to where their own lines meet.
1892
+ * Where strokes cross or branch, chains that carry on in the same
1893
+ * direction are joined, so a plotter lifts its pen less. Thinning also
1894
+ * rounds a sharp corner off, turning inside it, so a corner's arms are
1895
+ * drawn straight on to where they meet.
1896
+ * 5. Fit each chain with the same curve fitter as outlines.
1897
+ */
1898
+ /** The ink's skeleton as fitted subpaths (open, or closed for a loop), and the stroke width measured from the ink. `thinned` is the skeleton, if already thinned; it is pruned in place. */
1899
+ function skeletonStrokes(ink, w, h, o, thinned) {
1900
+ const skel = thinned ?? thin(ink, w, h);
1901
+ const measured = strokeWidthOf(skel, ink, w);
1902
+ prune(skel, w, h, Math.max(3, Math.round(measured)));
1903
+ const subs = [];
1904
+ for (const c of joinStraight(refitJunctions(walk(skel, w, h), measured)).map((c) => refitCorners(c, measured, ink, w, h))) {
1905
+ if (c.pts.length < 2) continue;
1906
+ const cubics = c.pts.length < 4 ? polyline(c.pts) : fitChain(c.pts, c.closed, {
1907
+ tolerance: o.tolerance,
1908
+ cornerAngle: o.cornerAngle,
1909
+ smoothing: 6
1910
+ });
1911
+ if (cubics.length) subs.push(toSubpath$1(cubics, c.closed));
1912
+ }
1913
+ return {
1914
+ subs,
1915
+ measured
1916
+ };
1917
+ }
1918
+ /**
1919
+ * The stroke width: the ink's area over the skeleton's length. (The distance
1920
+ * transform's median is out by a pixel on even widths, where the skeleton
1921
+ * can't sit on the middle.)
1922
+ */
1923
+ function strokeWidthOf(skel, ink, w) {
1924
+ let area = 0;
1925
+ let length = 0;
1926
+ for (let i = 0; i < ink.length; i++) {
1927
+ area += ink[i];
1928
+ if (!skel[i]) continue;
1929
+ const x = i % w;
1930
+ if (x + 1 < w && skel[i + 1]) length += 1;
1931
+ if (skel[i + w]) length += 1;
1932
+ if (x + 1 < w && skel[i + w + 1]) length += Math.SQRT2;
1933
+ if (x > 0 && skel[i + w - 1]) length += Math.SQRT2;
1934
+ }
1935
+ return length > 0 ? Math.max(1, area / length) : 1;
1936
+ }
1937
+ /**
1938
+ * Each of `m` regions of the ink (`comp`, VOID outside): its skeleton's length
1939
+ * and its stroke width (and the skeleton itself, thinning being local to each region), measured as `strokeWidthOf` does (0 where it thins to
1940
+ * a single pixel, which no stroke can be drawn along).
1941
+ */
1942
+ function regionWidths(ink, w, h, comp, m) {
1943
+ const skel = thin(ink, w, h);
1944
+ const area = new Float64Array(m);
1945
+ const length = new Float64Array(m);
1946
+ for (let i = 0; i < ink.length; i++) {
1947
+ const c = comp[i];
1948
+ if (!ink[i] || c < 0) continue;
1949
+ area[c]++;
1950
+ if (!skel[i]) continue;
1951
+ const x = i % w;
1952
+ if (x + 1 < w && skel[i + 1]) length[c] += 1;
1953
+ if (skel[i + w]) length[c] += 1;
1954
+ if (x + 1 < w && skel[i + w + 1]) length[c] += Math.SQRT2;
1955
+ if (x > 0 && skel[i + w - 1]) length[c] += Math.SQRT2;
1956
+ }
1957
+ return {
1958
+ width: area.map((a, c) => length[c] > 0 ? Math.max(1, a / length[c]) : 0),
1959
+ length,
1960
+ skel
1961
+ };
1962
+ }
1963
+ /** The eight neighbours P2…P9, clockwise from north, as offsets. */
1964
+ const DX = [
1965
+ 0,
1966
+ 1,
1967
+ 1,
1968
+ 1,
1969
+ 0,
1970
+ -1,
1971
+ -1,
1972
+ -1
1973
+ ];
1974
+ const DY = [
1975
+ -1,
1976
+ -1,
1977
+ 0,
1978
+ 1,
1979
+ 1,
1980
+ 1,
1981
+ 0,
1982
+ -1
1983
+ ];
1984
+ function neighbours(img, w, h, x, y) {
1985
+ const p = [];
1986
+ for (let k = 0; k < 8; k++) {
1987
+ const nx = x + DX[k];
1988
+ const ny = y + DY[k];
1989
+ p.push(nx >= 0 && nx < w && ny >= 0 && ny < h ? img[ny * w + nx] : 0);
1990
+ }
1991
+ return p;
1992
+ }
1993
+ /** 0 → 1 transitions round the neighbourhood: 1 on a line or an end, 3+ at a junction. */
1994
+ const crossings = (p) => {
1995
+ let n = 0;
1996
+ for (let k = 0; k < 8; k++) if (!p[k] && p[(k + 1) % 8]) n++;
1997
+ return n;
1998
+ };
1999
+ /** How many 8-connected groups the set neighbours form among themselves. */
2000
+ function pieces(p) {
2001
+ const seen = [
2002
+ false,
2003
+ false,
2004
+ false,
2005
+ false,
2006
+ false,
2007
+ false,
2008
+ false,
2009
+ false
2010
+ ];
2011
+ let groups = 0;
2012
+ for (let k = 0; k < 8; k++) {
2013
+ if (!p[k] || seen[k]) continue;
2014
+ groups++;
2015
+ const stack = [k];
2016
+ seen[k] = true;
2017
+ while (stack.length) {
2018
+ const a = stack.pop();
2019
+ for (let b = 0; b < 8; b++) if (p[b] && !seen[b] && Math.abs(DX[a] - DX[b]) <= 1 && Math.abs(DY[a] - DY[b]) <= 1) {
2020
+ seen[b] = true;
2021
+ stack.push(b);
2022
+ }
2023
+ }
2024
+ }
2025
+ return groups;
2026
+ }
2027
+ /** A neighbourhood as a byte: bit k set when neighbour P(k+2) (clockwise from north) is ink. */
2028
+ const unbits = (m) => [
2029
+ 0,
2030
+ 1,
2031
+ 2,
2032
+ 3,
2033
+ 4,
2034
+ 5,
2035
+ 6,
2036
+ 7
2037
+ ].map((k) => m >> k & 1);
2038
+ /** For every neighbourhood: removable on Zhang–Suen's first and second sub-pass, and redundant afterwards. */
2039
+ const ZS1 = /* @__PURE__ */ new Uint8Array(256);
2040
+ const ZS2 = /* @__PURE__ */ new Uint8Array(256);
2041
+ const SPARE = /* @__PURE__ */ new Uint8Array(256);
2042
+ for (let m = 0; m < 256; m++) {
2043
+ const p = unbits(m);
2044
+ const b = p.reduce((s, v) => s + v, 0);
2045
+ const ok = b >= 2 && b <= 6 && crossings(p) === 1;
2046
+ ZS1[m] = ok && !(p[0] * p[2] * p[4]) && !(p[2] * p[4] * p[6]) ? 1 : 0;
2047
+ ZS2[m] = ok && !(p[0] * p[2] * p[6]) && !(p[0] * p[4] * p[6]) ? 1 : 0;
2048
+ SPARE[m] = b >= 2 && pieces(p) === 1 ? 1 : 0;
2049
+ }
2050
+ function thin(ink, w, h) {
2051
+ const W = w + 2;
2052
+ const img = new Uint8Array(W * (h + 2));
2053
+ const live = [];
2054
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (ink[y * w + x]) {
2055
+ img[(y + 1) * W + x + 1] = 1;
2056
+ live.push((y + 1) * W + x + 1);
2057
+ }
2058
+ const off = DX.map((dx, k) => DY[k] * W + dx);
2059
+ const mask = (i) => {
2060
+ let m = 0;
2061
+ for (let k = 0; k < 8; k++) if (img[i + off[k]]) m |= 1 << k;
2062
+ return m;
2063
+ };
2064
+ const stamp = new Int32Array(img.length);
2065
+ const gone = [];
2066
+ let edge = live.filter((i) => mask(i) !== 255);
2067
+ for (let round = 0, quiet = 0; quiet < 2 && edge.length; round++) {
2068
+ const table = round % 2 ? ZS2 : ZS1;
2069
+ gone.length = 0;
2070
+ for (const i of edge) if (img[i] && table[mask(i)]) gone.push(i);
2071
+ for (const i of gone) img[i] = 0;
2072
+ quiet = gone.length ? 0 : quiet + 1;
2073
+ const next = [];
2074
+ const add = (i) => {
2075
+ if (img[i] && stamp[i] !== round + 1) {
2076
+ stamp[i] = round + 1;
2077
+ next.push(i);
2078
+ }
2079
+ };
2080
+ for (const i of edge) add(i);
2081
+ for (const i of gone) for (let k = 0; k < 8; k++) add(i + off[k]);
2082
+ edge = next;
2083
+ }
2084
+ edge.sort((a, b) => a - b);
2085
+ for (let changed = true; changed;) {
2086
+ changed = false;
2087
+ for (const i of edge) if (img[i] && SPARE[mask(i)]) {
2088
+ img[i] = 0;
2089
+ changed = true;
2090
+ }
2091
+ }
2092
+ const out = new Uint8Array(w * h);
2093
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) out[y * w + x] = img[(y + 1) * W + x + 1];
2094
+ return out;
2095
+ }
2096
+ const degree = (img, w, h, i) => neighbours(img, w, h, i % w, i / w | 0).reduce((s, v) => s + v, 0);
2097
+ /** Remove branches from an end to a junction shorter than `min` pixels, until none are left. */
2098
+ function prune(skel, w, h, min) {
2099
+ for (let pass = 0; pass < 4; pass++) {
2100
+ let removed = false;
2101
+ for (let i = 0; i < skel.length; i++) {
2102
+ if (!skel[i] || degree(skel, w, h, i) !== 1) continue;
2103
+ const path = [i];
2104
+ let prev = -1;
2105
+ let cur = i;
2106
+ let atJunction = false;
2107
+ while (path.length <= min) {
2108
+ const x = cur % w;
2109
+ const y = cur / w | 0;
2110
+ const next = [];
2111
+ for (let k = 0; k < 8; k++) {
2112
+ const nx = x + DX[k];
2113
+ const ny = y + DY[k];
2114
+ const j = ny * w + nx;
2115
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && skel[j] && j !== prev && !path.includes(j)) next.push(j);
2116
+ }
2117
+ if (next.length !== 1 || degree(skel, w, h, next[0]) > 2) {
2118
+ atJunction = next.length >= 1;
2119
+ break;
2120
+ }
2121
+ prev = cur;
2122
+ cur = next[0];
2123
+ path.push(cur);
2124
+ }
2125
+ if (atJunction && path.length <= min) {
2126
+ for (const j of path) skel[j] = 0;
2127
+ removed = true;
2128
+ }
2129
+ }
2130
+ if (!removed) break;
2131
+ }
2132
+ }
2133
+ /**
2134
+ * Walk the skeleton into chains. Nodes are ends (one neighbour) and junction
2135
+ * pixels (three or more); adjacent junction pixels form one junction, met at
2136
+ * its centre. What's left once every chain from a node is walked is loops.
2137
+ */
2138
+ function walk(skel, w, h) {
2139
+ const n = w * h;
2140
+ const isNode = new Uint8Array(n);
2141
+ for (let i = 0; i < n; i++) if (skel[i] && degree(skel, w, h, i) !== 2) isNode[i] = 1;
2142
+ const group = new Int32Array(n).fill(-1);
2143
+ const centres = [];
2144
+ for (let i = 0; i < n; i++) {
2145
+ if (!isNode[i] || group[i] >= 0) continue;
2146
+ const g = centres.length;
2147
+ const stack = [i];
2148
+ group[i] = g;
2149
+ let sx = 0;
2150
+ let sy = 0;
2151
+ let c = 0;
2152
+ while (stack.length) {
2153
+ const j = stack.pop();
2154
+ sx += j % w + .5;
2155
+ sy += (j / w | 0) + .5;
2156
+ c++;
2157
+ const x = j % w;
2158
+ const y = j / w | 0;
2159
+ for (let k = 0; k < 8; k++) {
2160
+ const nx = x + DX[k];
2161
+ const ny = y + DY[k];
2162
+ const m = ny * w + nx;
2163
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && isNode[m] && group[m] < 0 && degree(skel, w, h, m) > 2 && degree(skel, w, h, j) > 2) {
2164
+ group[m] = g;
2165
+ stack.push(m);
2166
+ }
2167
+ }
2168
+ }
2169
+ centres.push({
2170
+ x: sx / c,
2171
+ y: sy / c
2172
+ });
2173
+ }
2174
+ const used = new Uint8Array(n);
2175
+ const centre = (i) => ({
2176
+ x: i % w + .5,
2177
+ y: (i / w | 0) + .5
2178
+ });
2179
+ const next = (i, from) => {
2180
+ const x = i % w;
2181
+ const y = i / w | 0;
2182
+ for (const k of [
2183
+ 0,
2184
+ 2,
2185
+ 4,
2186
+ 6,
2187
+ 1,
2188
+ 3,
2189
+ 5,
2190
+ 7
2191
+ ]) {
2192
+ const nx = x + DX[k];
2193
+ const ny = y + DY[k];
2194
+ const j = ny * w + nx;
2195
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && skel[j] && j !== from && !used[j] && !(isNode[j] && group[j] === group[from] && group[from] >= 0)) return j;
2196
+ }
2197
+ return -1;
2198
+ };
2199
+ const chains = [];
2200
+ const linked = /* @__PURE__ */ new Set();
2201
+ for (let i = 0; i < n; i++) {
2202
+ if (!isNode[i]) continue;
2203
+ const x = i % w;
2204
+ const y = i / w | 0;
2205
+ for (let k = 0; k < 8; k++) {
2206
+ const nx = x + DX[k];
2207
+ const ny = y + DY[k];
2208
+ const j = ny * w + nx;
2209
+ if (nx < 0 || nx >= w || ny < 0 || ny >= h || !skel[j] || used[j]) continue;
2210
+ if (isNode[j]) {
2211
+ if (group[j] === group[i]) continue;
2212
+ const key = [group[i], group[j]].sort().join(",");
2213
+ if (linked.has(key)) continue;
2214
+ linked.add(key);
2215
+ chains.push({
2216
+ pts: [centres[group[i]], centres[group[j]]],
2217
+ closed: false
2218
+ });
2219
+ continue;
2220
+ }
2221
+ const pts = [centres[group[i]]];
2222
+ let prev = i;
2223
+ let cur = j;
2224
+ while (cur >= 0 && !isNode[cur]) {
2225
+ used[cur] = 1;
2226
+ pts.push(centre(cur));
2227
+ const nxt = next(cur, prev);
2228
+ prev = cur;
2229
+ cur = nxt;
2230
+ }
2231
+ if (cur >= 0) {
2232
+ if (group[cur] === group[i] && pts.length <= 3) continue;
2233
+ pts.push(centres[group[cur]]);
2234
+ }
2235
+ chains.push({
2236
+ pts,
2237
+ closed: false
2238
+ });
2239
+ }
2240
+ }
2241
+ for (let i = 0; i < n; i++) {
2242
+ if (!skel[i] || used[i] || isNode[i]) continue;
2243
+ const pts = [];
2244
+ let prev = -1;
2245
+ let cur = i;
2246
+ while (cur >= 0 && !used[cur]) {
2247
+ used[cur] = 1;
2248
+ pts.push(centre(cur));
2249
+ const nxt = next(cur, prev);
2250
+ prev = cur;
2251
+ cur = nxt;
2252
+ }
2253
+ chains.push({
2254
+ pts,
2255
+ closed: pts.length > 2
2256
+ });
2257
+ }
2258
+ return chains;
2259
+ }
2260
+ /**
2261
+ * Thinning pulls the skeleton toward a junction: a T's stem bends to meet the
2262
+ * bar, and an X's two strokes run together for a stroke's width at the
2263
+ * crossing. Within `width` of a junction the skeleton is the junction's shape,
2264
+ * not the strokes', so each arm is cut back there, its direction measured just
2265
+ * outside, and all the arms are drawn straight on to the point nearest every
2266
+ * arm's line (least squares), which is where the strokes really meet. If the
2267
+ * arms are near parallel, or that point is further than `width` from the
2268
+ * junction, the junction's centre stays.
2269
+ */
2270
+ function refitJunctions(chains, width) {
2271
+ const key = (p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
2272
+ const ends = /* @__PURE__ */ new Map();
2273
+ for (const c of chains) if (!c.closed) for (const atStart of [true, false]) {
2274
+ const k = key(atStart ? c.pts[0] : c.pts[c.pts.length - 1]);
2275
+ ends.set(k, [...ends.get(k) ?? [], {
2276
+ chain: c,
2277
+ atStart
2278
+ }]);
2279
+ }
2280
+ const cut = Math.max(2, width);
2281
+ const reach = Math.max(6, width);
2282
+ const cuts = /* @__PURE__ */ new Map();
2283
+ for (const [, list] of ends) {
2284
+ if (list.length < 3) continue;
2285
+ const at = list[0].atStart ? list[0].chain.pts[0] : list[0].chain.pts[list[0].chain.pts.length - 1];
2286
+ const arms = [];
2287
+ for (const e of list) {
2288
+ const pts = e.atStart ? e.chain.pts : [...e.chain.pts].reverse();
2289
+ if (e.chain.pts[0] === e.chain.pts[e.chain.pts.length - 1] || key(e.chain.pts[0]) === key(e.chain.pts[e.chain.pts.length - 1])) continue;
2290
+ const from = pts.findIndex((p) => Math.hypot(p.x - at.x, p.y - at.y) >= cut);
2291
+ const to = pts.findIndex((p) => Math.hypot(p.x - at.x, p.y - at.y) >= cut + reach);
2292
+ if (from < 0 || to < 0 || to >= pts.length - 1) continue;
2293
+ const a = pts[from];
2294
+ const b = pts[to];
2295
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2296
+ arms.push({
2297
+ end: e,
2298
+ from,
2299
+ a,
2300
+ d: {
2301
+ x: (b.x - a.x) / l,
2302
+ y: (b.y - a.y) / l
2303
+ }
2304
+ });
2305
+ }
2306
+ if (arms.length < 2) continue;
2307
+ let [m00, m01, m11, v0, v1] = [
2308
+ 0,
2309
+ 0,
2310
+ 0,
2311
+ 0,
2312
+ 0
2313
+ ];
2314
+ for (const { a, d } of arms) {
2315
+ const [p00, p01, p11] = [
2316
+ 1 - d.x * d.x,
2317
+ -d.x * d.y,
2318
+ 1 - d.y * d.y
2319
+ ];
2320
+ m00 += p00;
2321
+ m01 += p01;
2322
+ m11 += p11;
2323
+ v0 += p00 * a.x + p01 * a.y;
2324
+ v1 += p01 * a.x + p11 * a.y;
2325
+ }
2326
+ const det = m00 * m11 - m01 * m01;
2327
+ let meet = at;
2328
+ if (det > .05 * arms.length * arms.length) {
2329
+ const p = {
2330
+ x: (m11 * v0 - m01 * v1) / det,
2331
+ y: (m00 * v1 - m01 * v0) / det
2332
+ };
2333
+ if (Math.hypot(p.x - at.x, p.y - at.y) <= cut) meet = p;
2334
+ }
2335
+ for (const { end, from } of arms) {
2336
+ const c = cuts.get(end.chain) ?? {};
2337
+ if (end.atStart) {
2338
+ c.start = from;
2339
+ c.startAt = meet;
2340
+ } else {
2341
+ c.end = from;
2342
+ c.endAt = meet;
2343
+ }
2344
+ cuts.set(end.chain, c);
2345
+ }
2346
+ for (const e of list) if (!arms.some((x) => x.end === e)) {
2347
+ const c = cuts.get(e.chain) ?? {};
2348
+ if (e.atStart) {
2349
+ c.start ??= 0;
2350
+ c.startAt = meet;
2351
+ } else {
2352
+ c.end ??= 0;
2353
+ c.endAt = meet;
2354
+ }
2355
+ cuts.set(e.chain, c);
2356
+ }
2357
+ }
2358
+ return chains.map((c) => {
2359
+ const k = cuts.get(c);
2360
+ if (!k) return c;
2361
+ const n = c.pts.length;
2362
+ const s = k.start ?? 0;
2363
+ const e = n - 1 - (k.end ?? 0);
2364
+ const pts = e > s ? c.pts.slice(s, e + 1) : [...c.pts];
2365
+ const cutStart = e > s && s > 0;
2366
+ const cutEnd = e > s && e < n - 1;
2367
+ if (k.startAt) cutStart ? pts.unshift(k.startAt) : pts[0] = k.startAt;
2368
+ if (k.endAt) cutEnd ? pts.push(k.endAt) : pts[pts.length - 1] = k.endAt;
2369
+ return {
2370
+ pts,
2371
+ closed: false
2372
+ };
2373
+ });
2374
+ }
2375
+ /** A chain turns this much (radians) across a corner before it's redrawn as one: 60°. */
2376
+ const CORNER_TURN = Math.PI / 3;
2377
+ /**
2378
+ * Sharp corners drawn sharp. Thinning a stroke that turns sharply cuts the
2379
+ * corner: the skeleton turns inside it, short of the point by up to a few
2380
+ * stroke widths (a flag's swallowtail comes out rounded). Where the chain's
2381
+ * direction just before a point and just after it (measured outside a stroke
2382
+ * width of it, as at junctions) differs by more than CORNER_TURN, the points
2383
+ * within a stroke width are replaced by where the two arms' lines meet, if
2384
+ * the ink runs on toward that point past where the stroke's edge would be.
2385
+ * A rounded corner or a small ring turns as much, but its ink stops half a
2386
+ * width out, so it keeps its shape.
2387
+ */
2388
+ function refitCorners(c, width, ink, w, h) {
2389
+ const pts = c.pts;
2390
+ const n = pts.length;
2391
+ const cut = Math.max(2, width);
2392
+ const reach = Math.max(6, width);
2393
+ if (n < 4) return c;
2394
+ const s = [0];
2395
+ for (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y));
2396
+ const at = (t) => {
2397
+ let lo = 1;
2398
+ let hi = n - 1;
2399
+ while (lo < hi) {
2400
+ const mid = lo + hi >> 1;
2401
+ if (s[mid] < t) lo = mid + 1;
2402
+ else hi = mid;
2403
+ }
2404
+ const j = lo;
2405
+ const f = s[j] > s[j - 1] ? (t - s[j - 1]) / (s[j] - s[j - 1]) : 0;
2406
+ return {
2407
+ x: pts[j - 1].x + f * (pts[j].x - pts[j - 1].x),
2408
+ y: pts[j - 1].y + f * (pts[j].y - pts[j - 1].y)
2409
+ };
2410
+ };
2411
+ const unit = (a, b) => {
2412
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2413
+ return {
2414
+ x: (b.x - a.x) / l,
2415
+ y: (b.y - a.y) / l
2416
+ };
2417
+ };
2418
+ const isInk = (p) => {
2419
+ const x = Math.floor(p.x);
2420
+ const y = Math.floor(p.y);
2421
+ return x >= 0 && y >= 0 && x < w && y < h && ink[y * w + x] === 1;
2422
+ };
2423
+ const found = [];
2424
+ for (let i = 1; i < n - 1; i++) {
2425
+ if (s[i] - cut - reach < 0 || s[i] + cut + reach > s[n - 1]) continue;
2426
+ const pa = at(s[i] - cut);
2427
+ const d1 = unit(at(s[i] - cut - reach), pa);
2428
+ const qa = at(s[i] + cut);
2429
+ const d2 = unit(qa, at(s[i] + cut + reach));
2430
+ const turn = Math.acos(Math.max(-1, Math.min(1, d1.x * d2.x + d1.y * d2.y)));
2431
+ if (turn < CORNER_TURN) continue;
2432
+ const det = d1.x * -d2.y - d1.y * -d2.x;
2433
+ if (Math.abs(det) < 1e-6) continue;
2434
+ const u = ((qa.x - pa.x) * -d2.y - (qa.y - pa.y) * -d2.x) / det;
2435
+ if (u < 0) continue;
2436
+ const apex = {
2437
+ x: pa.x + u * d1.x,
2438
+ y: pa.y + u * d1.y
2439
+ };
2440
+ const off = Math.hypot(apex.x - pts[i].x, apex.y - pts[i].y);
2441
+ if (off < .5 || off > 3 * width || !isInk(apex)) continue;
2442
+ const past = width / 2 + 1.5;
2443
+ if (!isInk({
2444
+ x: pts[i].x + (apex.x - pts[i].x) / off * past,
2445
+ y: pts[i].y + (apex.y - pts[i].y) / off * past
2446
+ })) continue;
2447
+ const last = found[found.length - 1];
2448
+ if (last && s[i] - s[last.i] < 2 * cut) {
2449
+ if (turn > last.turn) found[found.length - 1] = {
2450
+ i,
2451
+ turn,
2452
+ apex
2453
+ };
2454
+ } else found.push({
2455
+ i,
2456
+ turn,
2457
+ apex
2458
+ });
2459
+ }
2460
+ if (!found.length) return c;
2461
+ const out = [];
2462
+ let k = 0;
2463
+ for (let i = 0; i < n; i++) {
2464
+ const f = found[k];
2465
+ if (f && s[i] > s[f.i] - cut) {
2466
+ if (s[i] < s[f.i] + cut) continue;
2467
+ out.push(f.apex);
2468
+ k++;
2469
+ i--;
2470
+ continue;
2471
+ }
2472
+ out.push(pts[i]);
2473
+ }
2474
+ for (; k < found.length; k++) out.push(found[k].apex);
2475
+ return {
2476
+ ...c,
2477
+ pts: out
2478
+ };
2479
+ }
2480
+ /** The direction a chain leaves its start, measured a few pixels along it. */
2481
+ function leaving(pts) {
2482
+ const a = pts[0];
2483
+ const b = pts[Math.min(pts.length - 1, 6)];
2484
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1;
2485
+ return {
2486
+ x: (b.x - a.x) / l,
2487
+ y: (b.y - a.y) / l
2488
+ };
2489
+ }
2490
+ /**
2491
+ * Join chains that meet end to end and carry straight on (within 30°), so a
2492
+ * line through a crossing is one stroke. Each end joins at most once.
2493
+ */
2494
+ function joinStraight(chains) {
2495
+ const key = (p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
2496
+ const live = new Set(chains.filter((c) => !c.closed));
2497
+ const ends = /* @__PURE__ */ new Map();
2498
+ const addEnds = (c) => {
2499
+ for (const atStart of [true, false]) {
2500
+ const k = key(atStart ? c.pts[0] : c.pts[c.pts.length - 1]);
2501
+ const list = ends.get(k) ?? [];
2502
+ list.push({
2503
+ chain: c,
2504
+ atStart
2505
+ });
2506
+ ends.set(k, list);
2507
+ }
2508
+ };
2509
+ live.forEach(addEnds);
2510
+ const out = chains.filter((c) => c.closed);
2511
+ const outward = (e) => leaving(e.atStart ? e.chain.pts : [...e.chain.pts].reverse());
2512
+ for (const [, list] of ends) for (;;) {
2513
+ const here = list.filter((e) => live.has(e.chain));
2514
+ let best = null;
2515
+ let bestDot = -Math.cos(150 * Math.PI / 180);
2516
+ for (let a = 0; a < here.length; a++) for (let b = a + 1; b < here.length; b++) {
2517
+ if (here[a].chain === here[b].chain) continue;
2518
+ const da = outward(here[a]);
2519
+ const db = outward(here[b]);
2520
+ const dot = da.x * db.x + da.y * db.y;
2521
+ if (dot < -bestDot) {
2522
+ bestDot = -dot;
2523
+ best = [here[a], here[b]];
2524
+ }
2525
+ }
2526
+ if (!best) break;
2527
+ const [ea, eb] = best;
2528
+ const a = ea.atStart ? [...ea.chain.pts].reverse() : ea.chain.pts;
2529
+ const b = eb.atStart ? eb.chain.pts : [...eb.chain.pts].reverse();
2530
+ const joined = {
2531
+ pts: [...a, ...b.slice(1)],
2532
+ closed: false
2533
+ };
2534
+ live.delete(ea.chain);
2535
+ live.delete(eb.chain);
2536
+ live.add(joined);
2537
+ addEnds(joined);
2538
+ if (key(joined.pts[0]) === key(joined.pts[joined.pts.length - 1]) && joined.pts.length > 3) {
2539
+ live.delete(joined);
2540
+ out.push({
2541
+ pts: joined.pts.slice(0, -1),
2542
+ closed: true
2543
+ });
2544
+ }
2545
+ }
2546
+ return [...out, ...live];
2547
+ }
2548
+ const polyline = (pts) => pts.slice(1).map((b, i) => [
2549
+ pts[i],
2550
+ pts[i],
2551
+ b,
2552
+ b
2553
+ ]);
2554
+ function toSubpath$1(cubics, closed) {
2555
+ const r = (p) => ({
2556
+ x: Math.round(p.x * 100) / 100,
2557
+ y: Math.round(p.y * 100) / 100
2558
+ });
2559
+ const nodes = [];
2560
+ for (const c of cubics) {
2561
+ if (!nodes.length) nodes.push({
2562
+ ...r(c[0]),
2563
+ in: null,
2564
+ out: null
2565
+ });
2566
+ const flat = isFlat(c);
2567
+ if (!flat) nodes[nodes.length - 1].out = r(c[1]);
2568
+ nodes.push({
2569
+ ...r(c[3]),
2570
+ in: flat ? null : r(c[2]),
2571
+ out: null
2572
+ });
2573
+ }
2574
+ if (closed && nodes.length > 1) {
2575
+ const last = nodes.pop();
2576
+ nodes[0].in = last.in;
2577
+ }
2578
+ return {
2579
+ closed,
2580
+ nodes
2581
+ };
2582
+ }
2583
+ //#endregion
2584
+ //#region src/gradient.ts
2585
+ /**
2586
+ * Gradient fills for softly shaded regions.
2587
+ *
2588
+ * A palette splits a smooth shade into bands of flat tints, each traced as
2589
+ * its own shape. Here the bands are found again and put back together: two
2590
+ * neighbouring regions whose boundary is soft (the image barely changes
2591
+ * across it, though their colours differ) are one shaded region, and if a
2592
+ * linear or radial gradient explains its colours much better than one flat
2593
+ * colour, and no worse than the bands did, it becomes one shape with that
2594
+ * gradient.
2595
+ *
2596
+ * The fits are closed-form least squares in sRGB, which is what SVG
2597
+ * interpolates in:
2598
+ * - linear: each channel as a plane in x and y; the planes' dominant
2599
+ * direction is the gradient's axis.
2600
+ * - radial: the colour's main component as a + bx + cy + d(x² + y²), whose
2601
+ * vertex is the centre, refined as a + k·r by Gauss–Newton.
2602
+ * Along the axis (or the radius), each channel is then piecewise linear
2603
+ * between a few evenly spaced stops, as few as fit.
2604
+ */
2605
+ /** A boundary is soft when the image changes by less than this share of its two colours' difference across it. */
2606
+ const SOFT = .4;
2607
+ /** …or by less than this (RGB levels), however alike the colours: JPEG noise alone moves a pixel about this much. */
2608
+ const SOFT_NOISE = 10;
2609
+ /** Pixels either side of a crack whose step is measured: three pixels apart, so anti-aliasing counts as a hard edge. */
2610
+ const SPAN = 1;
2611
+ /** A soft boundary needs at least this many cracks, so a few pixels touching don't join two regions. */
2612
+ const SOFT_MIN = 6;
2613
+ /** Smallest shaded region (pixels) worth a gradient. */
2614
+ const MIN_AREA = 64;
2615
+ /** One flat colour must be at least this far off (RMS, RGB levels) for a gradient to be worth it. */
2616
+ const FLAT_MIN = 6;
2617
+ /** The gradient must at least halve the flat colour's error… */
2618
+ const GAIN = .5;
2619
+ /** …and come within this of the bands' own error. */
2620
+ const BANDS_SLACK = 1.1;
2621
+ /**
2622
+ * …and stay this close to the image (RMS, RGB levels). Soft shading fits to
2623
+ * within noise; a fit this far off is smearing distinct shapes together (a
2624
+ * face and the hair beside it on a painted poster, whose palette is far off
2625
+ * both, so the bands' error is no guide).
2626
+ */
2627
+ const MAX_RMS = 20;
2628
+ /** A band with at least this many sampled pixels must be drawn no worse by the gradient than by its own colour. */
2629
+ const BAND_MIN = 16;
2630
+ /** A radial fit replaces the linear one only when this much closer. */
2631
+ const RADIAL_GAIN = .8;
2632
+ /** Pixels a shade is fitted on, at most. */
2633
+ const SAMPLE = 4e3;
2634
+ /** Weight of the tie between neighbouring stops: next to nothing beside a pixel's weight of 1. */
2635
+ const TIE = .001;
2636
+ /** Most stops along a gradient. */
2637
+ const MAX_STOPS = 5;
2638
+ /**
2639
+ * Groups of regions that are one soft shade, each with the gradient that
2640
+ * draws it. `comp` is each pixel's region (negative: none), `colorOf` each
2641
+ * region's flat colour.
2642
+ */
2643
+ function shadings(rgba, w, h, comp, regions, colorOf) {
2644
+ const step = /* @__PURE__ */ new Map();
2645
+ const count = /* @__PURE__ */ new Map();
2646
+ const rgb = (i) => [
2647
+ rgba[i * 4],
2648
+ rgba[i * 4 + 1],
2649
+ rgba[i * 4 + 2]
2650
+ ];
2651
+ const d3 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
2652
+ const colors = Array.from({ length: regions }, (_, id) => colorOf(id));
2653
+ const crack = (a, b, before, after) => {
2654
+ const ca = comp[a];
2655
+ const cb = comp[b];
2656
+ if (ca < 0 || cb < 0 || ca === cb) return;
2657
+ const key = Math.min(ca, cb) * regions + Math.max(ca, cb);
2658
+ const p = before * 4;
2659
+ const q = after * 4;
2660
+ 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]));
2661
+ count.set(key, (count.get(key) ?? 0) + 1);
2662
+ };
2663
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
2664
+ const i = y * w + x;
2665
+ if (x + 1 < w) crack(i, i + 1, y * w + Math.max(0, x - SPAN), y * w + Math.min(w - 1, x + 1 + SPAN));
2666
+ if (y + 1 < h) crack(i, i + w, Math.max(0, y - SPAN) * w + x, Math.min(h - 1, y + 1 + SPAN) * w + x);
2667
+ }
2668
+ const parent = Array.from({ length: regions }, (_, i) => i);
2669
+ const find = (i) => parent[i] === i ? i : parent[i] = find(parent[i]);
2670
+ for (const [key, n] of count) {
2671
+ const a = Math.floor(key / regions);
2672
+ const b = key % regions;
2673
+ if (n < SOFT_MIN || step.get(key) >= n * Math.max(SOFT * d3(colors[a], colors[b]), SOFT_NOISE)) continue;
2674
+ parent[find(a)] = find(b);
2675
+ }
2676
+ const groups = /* @__PURE__ */ new Map();
2677
+ for (let id = 0; id < regions; id++) {
2678
+ const r = find(id);
2679
+ const g = groups.get(r);
2680
+ if (g) g.push(id);
2681
+ else groups.set(r, [id]);
2682
+ }
2683
+ const root = new Int32Array(regions);
2684
+ for (let id = 0; id < regions; id++) root[id] = groups.get(find(id)).length > 1 ? find(id) : -1;
2685
+ const inner = /* @__PURE__ */ new Map();
2686
+ const rootAt = (i) => comp[i] >= 0 ? root[comp[i]] : -1;
2687
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
2688
+ const i = y * w + x;
2689
+ const r = rootAt(i);
2690
+ if (r < 0 || rootAt(i - 1) !== r || rootAt(i + 1) !== r || rootAt(i - w) !== r || rootAt(i + w) !== r) continue;
2691
+ const list = inner.get(r);
2692
+ if (list) list.push(i);
2693
+ else inner.set(r, [i]);
2694
+ }
2695
+ const out = [];
2696
+ for (const [r, all] of inner) {
2697
+ if (all.length < MIN_AREA) continue;
2698
+ const stride = Math.max(1, Math.floor(all.length / SAMPLE));
2699
+ const xs = [];
2700
+ const ys = [];
2701
+ const cs = [];
2702
+ const bands = [];
2703
+ const ids = [];
2704
+ for (let k = 0; k < all.length; k += stride) {
2705
+ const i = all[k];
2706
+ xs.push(i % w + .5);
2707
+ ys.push(Math.floor(i / w) + .5);
2708
+ cs.push(rgb(i));
2709
+ bands.push(colors[comp[i]]);
2710
+ ids.push(comp[i]);
2711
+ }
2712
+ const g = fitShading(xs, ys, cs);
2713
+ if (!g) continue;
2714
+ const n = cs.length;
2715
+ const mean = [
2716
+ 0,
2717
+ 1,
2718
+ 2
2719
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2720
+ const rms = (f) => Math.sqrt(cs.reduce((s, c, j) => s + d3(c, f(j)) ** 2, 0) / n);
2721
+ const flat = rms(() => mean);
2722
+ const banded = rms((j) => bands[j]);
2723
+ if (flat < FLAT_MIN || g.rms > MAX_RMS || g.rms > GAIN * flat || g.rms > BANDS_SLACK * banded) continue;
2724
+ if (worseOnABand(g.gradient, xs, ys, cs, bands, ids)) continue;
2725
+ out.push({
2726
+ comps: [...groups.get(r)],
2727
+ gradient: g.gradient,
2728
+ mean: ""
2729
+ });
2730
+ }
2731
+ const shadeOf = new Int32Array(regions).fill(-1);
2732
+ out.forEach((s, k) => s.comps.forEach((id) => shadeOf[id] = k));
2733
+ const near = /* @__PURE__ */ new Map();
2734
+ for (const key of count.keys()) {
2735
+ const a = Math.floor(key / regions);
2736
+ const b = key % regions;
2737
+ for (const [x, y] of [[a, b], [b, a]]) if (shadeOf[x] >= 0 && shadeOf[y] < 0) {
2738
+ const set = near.get(y);
2739
+ if (set) set.add(shadeOf[x]);
2740
+ else near.set(y, /* @__PURE__ */ new Set([shadeOf[x]]));
2741
+ }
2742
+ }
2743
+ if (near.size) {
2744
+ const ramps = out.map((s) => ramp(s.gradient));
2745
+ const flatErr = new Float64Array(regions);
2746
+ const area = new Float64Array(regions);
2747
+ const gradErr = /* @__PURE__ */ new Map();
2748
+ for (const id of near.keys()) gradErr.set(id, new Float64Array(out.length));
2749
+ for (let i = 0; i < w * h; i++) {
2750
+ const id = comp[i];
2751
+ const errs = id >= 0 ? gradErr.get(id) : void 0;
2752
+ if (!errs) continue;
2753
+ const c = rgb(i);
2754
+ area[id]++;
2755
+ flatErr[id] += dist2(c, colors[id]);
2756
+ for (const k of near.get(id)) errs[k] += dist2(c, ramps[k](i % w + .5, Math.floor(i / w) + .5));
2757
+ }
2758
+ for (const [id, ks] of near) {
2759
+ const errs = gradErr.get(id);
2760
+ const k = [...ks].reduce((a, b) => errs[b] < errs[a] ? b : a);
2761
+ const flat = flatErr[id] < FLAT_MIN ** 2 * area[id];
2762
+ if (errs[k] <= flatErr[id] && (!flat || area[id] < MIN_AREA)) {
2763
+ out[k].comps.push(id);
2764
+ shadeOf[id] = k;
2765
+ }
2766
+ }
2767
+ }
2768
+ const sums = out.map(() => [
2769
+ 0,
2770
+ 0,
2771
+ 0,
2772
+ 0
2773
+ ]);
2774
+ for (let i = 0; i < w * h; i++) {
2775
+ const k = comp[i] >= 0 ? shadeOf[comp[i]] : -1;
2776
+ if (k < 0) continue;
2777
+ const s = sums[k];
2778
+ s[0] += rgba[i * 4];
2779
+ s[1] += rgba[i * 4 + 1];
2780
+ s[2] += rgba[i * 4 + 2];
2781
+ s[3]++;
2782
+ }
2783
+ out.forEach((s, k) => s.mean = toHex([
2784
+ sums[k][0] / sums[k][3],
2785
+ sums[k][1] / sums[k][3],
2786
+ sums[k][2] / sums[k][3]
2787
+ ]));
2788
+ return out;
2789
+ }
2790
+ /** A gradient's colour at a point. */
2791
+ const colorAt = (g, x, y) => ramp(g)(x, y);
2792
+ /**
2793
+ * Whether the gradient draws any one band of the shade worse than the band's
2794
+ * own flat colour did: a gradient that suits the whole on average can still
2795
+ * paint one member (a shirt's fold shadow, a strand of hair) the wrong colour.
2796
+ */
2797
+ function worseOnABand(g, xs, ys, cs, bands, ids) {
2798
+ const at = ramp(g);
2799
+ const err = /* @__PURE__ */ new Map();
2800
+ cs.forEach((c, j) => {
2801
+ const e = err.get(ids[j]) ?? [
2802
+ 0,
2803
+ 0,
2804
+ 0
2805
+ ];
2806
+ e[0] += dist2(c, at(xs[j], ys[j]));
2807
+ e[1] += dist2(c, bands[j]);
2808
+ e[2]++;
2809
+ err.set(ids[j], e);
2810
+ });
2811
+ for (const [grad, band, n] of err.values()) if (n >= BAND_MIN && grad > BANDS_SLACK ** 2 * band) return true;
2812
+ return false;
2813
+ }
2814
+ /** A gradient as a function of the point, its stops parsed once. */
2815
+ function ramp(g) {
2816
+ const offsets = g.stops.map((s) => s.offset);
2817
+ const colors = g.stops.map((s) => hexToRgb(s.color));
2818
+ const last = colors.length - 1;
2819
+ const dx = g.type === "linear" ? g.x2 - g.x1 : 0;
2820
+ const dy = g.type === "linear" ? g.y2 - g.y1 : 0;
2821
+ const len2 = dx * dx + dy * dy || 1;
2822
+ return (x, y) => {
2823
+ const t = g.type === "linear" ? ((x - g.x1) * dx + (y - g.y1) * dy) / len2 : Math.hypot(x - g.cx, y - g.cy) / g.r;
2824
+ if (t <= offsets[0]) return colors[0];
2825
+ for (let k = 1; k <= last; k++) if (t <= offsets[k]) {
2826
+ const a = colors[k - 1];
2827
+ const b = colors[k];
2828
+ const f = (t - offsets[k - 1]) / (offsets[k] - offsets[k - 1] || 1);
2829
+ return [
2830
+ a[0] + f * (b[0] - a[0]),
2831
+ a[1] + f * (b[1] - a[1]),
2832
+ a[2] + f * (b[2] - a[2])
2833
+ ];
2834
+ }
2835
+ return colors[last];
2836
+ };
2837
+ }
2838
+ /** The better of a linear and a radial gradient through these pixels, with its RMS error. */
2839
+ function fitShading(xs, ys, cs) {
2840
+ const lin = fitLinear(xs, ys, cs);
2841
+ const rad = fitRadial(xs, ys, cs);
2842
+ if (rad && (!lin || rad.rms < RADIAL_GAIN * lin.rms)) return rad;
2843
+ return lin;
2844
+ }
2845
+ function fitLinear(xs, ys, cs) {
2846
+ const n = xs.length;
2847
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
2848
+ const my = ys.reduce((a, b) => a + b, 0) / n;
2849
+ let sxx = 0;
2850
+ let sxy = 0;
2851
+ let syy = 0;
2852
+ const sx = [
2853
+ 0,
2854
+ 0,
2855
+ 0
2856
+ ];
2857
+ const sy = [
2858
+ 0,
2859
+ 0,
2860
+ 0
2861
+ ];
2862
+ const cm = [
2863
+ 0,
2864
+ 1,
2865
+ 2
2866
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2867
+ for (let j = 0; j < n; j++) {
2868
+ const dx = xs[j] - mx;
2869
+ const dy = ys[j] - my;
2870
+ sxx += dx * dx;
2871
+ sxy += dx * dy;
2872
+ syy += dy * dy;
2873
+ for (let k = 0; k < 3; k++) {
2874
+ sx[k] += dx * (cs[j][k] - cm[k]);
2875
+ sy[k] += dy * (cs[j][k] - cm[k]);
2876
+ }
2877
+ }
2878
+ const det = sxx * syy - sxy * sxy;
2879
+ if (!(det > 0)) return null;
2880
+ const gx = sx.map((_, k) => (syy * sx[k] - sxy * sy[k]) / det);
2881
+ const gy = sx.map((_, k) => (sxx * sy[k] - sxy * sx[k]) / det);
2882
+ const a = gx.reduce((s, v) => s + v * v, 0);
2883
+ const b = gx.reduce((s, v, k) => s + v * gy[k], 0);
2884
+ const c = gy.reduce((s, v) => s + v * v, 0);
2885
+ const theta = .5 * Math.atan2(2 * b, a - c);
2886
+ const ux = Math.cos(theta);
2887
+ const uy = Math.sin(theta);
2888
+ const ramp = fitRamp(xs.map((x, j) => (x - mx) * ux + (ys[j] - my) * uy), cs);
2889
+ if (!ramp) return null;
2890
+ const { t0, t1, stops, rms } = ramp;
2891
+ return {
2892
+ gradient: {
2893
+ type: "linear",
2894
+ x1: mx + t0 * ux,
2895
+ y1: my + t0 * uy,
2896
+ x2: mx + t1 * ux,
2897
+ y2: my + t1 * uy,
2898
+ stops
2899
+ },
2900
+ rms
2901
+ };
2902
+ }
2903
+ function fitRadial(xs, ys, cs) {
2904
+ const n = xs.length;
2905
+ const mx = xs.reduce((a, b) => a + b, 0) / n;
2906
+ const my = ys.reduce((a, b) => a + b, 0) / n;
2907
+ const scale = Math.sqrt(xs.reduce((s, x, j) => s + (x - mx) ** 2 + (ys[j] - my) ** 2, 0) / n) || 1;
2908
+ const cm = [
2909
+ 0,
2910
+ 1,
2911
+ 2
2912
+ ].map((k) => cs.reduce((s, c) => s + c[k], 0) / n);
2913
+ const axis = mainAxis(cs, cm);
2914
+ const s = cs.map((c) => (c[0] - cm[0]) * axis[0] + (c[1] - cm[1]) * axis[1] + (c[2] - cm[2]) * axis[2]);
2915
+ const rows = xs.map((x, j) => {
2916
+ const u = (x - mx) / scale;
2917
+ const v = (ys[j] - my) / scale;
2918
+ return [
2919
+ 1,
2920
+ u,
2921
+ v,
2922
+ u * u + v * v
2923
+ ];
2924
+ });
2925
+ const q = leastSquares(rows, s);
2926
+ if (!q || Math.abs(q[3]) < 1e-9) return null;
2927
+ let cx = -q[1] / (2 * q[3]);
2928
+ let cy = -q[2] / (2 * q[3]);
2929
+ if (Math.hypot(cx, cy) > 3) return null;
2930
+ let a = 0;
2931
+ let k = 0;
2932
+ for (let it = 0; it < 8; it++) {
2933
+ const r = rows.map(([, u, v]) => Math.hypot(u - cx, v - cy));
2934
+ const ak = leastSquares(r.map((ri) => [1, ri]), s);
2935
+ if (!ak) return null;
2936
+ [a, k] = ak;
2937
+ const delta = leastSquares(rows.map(([, u, v], j) => {
2938
+ const ri = Math.max(r[j], 1e-6);
2939
+ return [
2940
+ 1,
2941
+ r[j],
2942
+ -k * (u - cx) / ri,
2943
+ -k * (v - cy) / ri
2944
+ ];
2945
+ }), s.map((sj, j) => sj - (a + k * r[j])));
2946
+ if (!delta) break;
2947
+ cx += delta[2];
2948
+ cy += delta[3];
2949
+ if (Math.hypot(delta[2], delta[3]) < 1e-4) break;
2950
+ }
2951
+ if (Math.hypot(cx, cy) > 3) return null;
2952
+ const px = mx + cx * scale;
2953
+ const py = my + cy * scale;
2954
+ const ramp = fitRamp(xs.map((x, j) => Math.hypot(x - px, ys[j] - py)), cs, 0);
2955
+ if (!ramp || ramp.t1 <= 0) return null;
2956
+ return {
2957
+ gradient: {
2958
+ type: "radial",
2959
+ cx: px,
2960
+ cy: py,
2961
+ r: ramp.t1,
2962
+ stops: ramp.stops.map((st) => ({
2963
+ ...st,
2964
+ offset: round$1((ramp.t0 + st.offset * (ramp.t1 - ramp.t0)) / ramp.t1, 3)
2965
+ }))
2966
+ },
2967
+ rms: ramp.rms
2968
+ };
2969
+ }
2970
+ /**
2971
+ * Colour as a function of t: piecewise linear between evenly spaced stops
2972
+ * from the least t to the greatest, as few as come within a level of the most.
2973
+ * Offsets run 0–1 over [t0, t1]. With `from`, t0 is at least that.
2974
+ */
2975
+ function fitRamp(t, cs, from = -Infinity) {
2976
+ let t0 = Infinity;
2977
+ let t1 = -Infinity;
2978
+ for (const tj of t) {
2979
+ if (tj < t0) t0 = tj;
2980
+ if (tj > t1) t1 = tj;
2981
+ }
2982
+ t0 = Math.max(from, t0);
2983
+ if (!(t1 > t0)) return null;
2984
+ const fits = [];
2985
+ for (let m = 2; m <= MAX_STOPS; m++) {
2986
+ const at = (tj) => Math.min(m - 1, Math.max(0, (tj - t0) / (t1 - t0) * (m - 1)));
2987
+ const rows = t.map((tj) => {
2988
+ const p = at(tj);
2989
+ const i = Math.min(m - 2, Math.floor(p));
2990
+ const f = p - i;
2991
+ const row = new Array(m).fill(0);
2992
+ row[i] = 1 - f;
2993
+ row[i + 1] = f;
2994
+ return row;
2995
+ });
2996
+ const ties = Array.from({ length: m - 1 }, (_, i) => {
2997
+ const row = new Array(m).fill(0);
2998
+ row[i] = TIE;
2999
+ row[i + 1] = -.001;
3000
+ return row;
3001
+ });
3002
+ const chans = [
3003
+ 0,
3004
+ 1,
3005
+ 2
3006
+ ].map((k) => leastSquares([...rows, ...ties], [...cs.map((c) => c[k]), ...ties.map(() => 0)]));
3007
+ if (chans.some((c) => !c)) continue;
3008
+ const colorAt = (row) => [
3009
+ 0,
3010
+ 1,
3011
+ 2
3012
+ ].map((k) => clamp(row.reduce((s, v, i) => s + v * chans[k][i], 0)));
3013
+ const stopColors = Array.from({ length: m }, (_, i) => [
3014
+ 0,
3015
+ 1,
3016
+ 2
3017
+ ].map((k) => clamp(chans[k][i])));
3018
+ const rms = Math.sqrt(rows.reduce((s, row, j) => s + dist2(colorAt(row), cs[j]), 0) / t.length);
3019
+ fits.push({
3020
+ stops: stopColors.map((c, i) => ({
3021
+ offset: round$1(i / (m - 1), 3),
3022
+ color: toHex(c)
3023
+ })),
3024
+ rms
3025
+ });
3026
+ }
3027
+ if (!fits.length) return null;
3028
+ const least = Math.min(...fits.map((f) => f.rms));
3029
+ return {
3030
+ t0,
3031
+ t1,
3032
+ ...fits.find((f) => f.rms <= least + 1)
3033
+ };
3034
+ }
3035
+ /** The main axis of a set of colours (power iteration on their covariance). */
3036
+ function mainAxis(cs, cm) {
3037
+ const cov = [
3038
+ 0,
3039
+ 1,
3040
+ 2
3041
+ ].map(() => [
3042
+ 0,
3043
+ 0,
3044
+ 0
3045
+ ]);
3046
+ for (const c of cs) for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) cov[i][j] += (c[i] - cm[i]) * (c[j] - cm[j]);
3047
+ let v = [
3048
+ 0,
3049
+ 1,
3050
+ 2
3051
+ ].map((i) => cov[i][i]);
3052
+ v = cov[v.indexOf(Math.max(...v))].slice();
3053
+ for (let it = 0; it < 30; it++) {
3054
+ const next = cov.map((row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2]);
3055
+ const len = Math.hypot(...next) || 1;
3056
+ v = next.map((x) => x / len);
3057
+ }
3058
+ return v;
3059
+ }
3060
+ /** Least squares through the normal equations (small systems only). */
3061
+ function leastSquares(rows, y) {
3062
+ const m = rows[0]?.length ?? 0;
3063
+ const A = Array.from({ length: m }, () => new Array(m + 1).fill(0));
3064
+ rows.forEach((row, j) => {
3065
+ for (let a = 0; a < m; a++) {
3066
+ if (!row[a]) continue;
3067
+ for (let b = 0; b < m; b++) A[a][b] += row[a] * row[b];
3068
+ A[a][m] += row[a] * y[j];
3069
+ }
3070
+ });
3071
+ for (let c = 0; c < m; c++) {
3072
+ let p = c;
3073
+ for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
3074
+ if (Math.abs(A[p][c]) < 1e-12) return null;
3075
+ [A[c], A[p]] = [A[p], A[c]];
3076
+ for (let r = 0; r < m; r++) {
3077
+ if (r === c) continue;
3078
+ const f = A[r][c] / A[c][c];
3079
+ for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k];
3080
+ }
3081
+ }
3082
+ return A.map((row, i) => row[m] / row[i]);
3083
+ }
3084
+ const clamp = (v) => Math.max(0, Math.min(255, v));
3085
+ const dist2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
3086
+ const round$1 = (v, places) => Math.round(v * 10 ** places) / 10 ** places;
3087
+ //#endregion
3088
+ //#region src/inlay.ts
3089
+ /**
3090
+ * Inlay, our shared-edge tracer: every preset, from logos to photos.
3091
+ * Like inlaid wood, every piece is cut to fit its neighbours exactly.
3092
+ *
3093
+ * VTracer traces every colour region on its own, so an edge between two
3094
+ * regions is traced twice. Fitting the two copies separately leaves hairline
3095
+ * gaps and slivers; leaving them to VTracer's spline fitter gives the wobbly
3096
+ * lines and rounded corners this replaces. Instead:
3097
+ *
3098
+ * 1. Label every pixel with a palette colour (or ink / paper for line art).
3099
+ * Anti-aliased pixels, which sit between two colours, take the closest
3100
+ * colour *among their neighbours*, so an edge between red and blue never
3101
+ * grows a one-pixel purple sliver.
3102
+ * 2. Merge specks smaller than `speckle`² pixels into whatever surrounds them.
3103
+ * 3. Walk the cracks between differently labelled pixels. Where three or more
3104
+ * regions meet (or two meet diagonally) is a junction; every boundary
3105
+ * between two junctions is one chain, with one region on each side.
3106
+ * 4. Fit each chain once (src/lib/fit.ts): corners first, then straight lines
3107
+ * where they fit and curves where they don't.
3108
+ * 5. Build each region's outline from its chains, reversing the ones it sees
3109
+ * from the other side. Neighbours share the exact same fitted edge: no
3110
+ * gaps, no overlaps, which is also what a vinyl cutter wants.
3111
+ *
3112
+ * Regions are 4-connected, so two pixels touching only at a corner are
3113
+ * separate shapes, and each region is one <path> (its outline plus its holes,
3114
+ * wound oppositely so the default nonzero fill rule cuts the holes). With
3115
+ * `stacked`, a region keeps only its outline (and any holes onto
3116
+ * transparency), and paint order does the rest; for flat art, a region behind
3117
+ * another is also completed where it is hidden (layers.ts).
3118
+ */
3119
+ const VOID = -1;
3120
+ /**
3121
+ * A value made safe inside a double-quoted attribute. Colours come from the
3122
+ * caller's palette as given, so a stray quote mustn't end the attribute.
3123
+ */
3124
+ const attr = (v) => String(v).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
3125
+ /** The trace as an SVG document. */
3126
+ function toSvg(r) {
3127
+ const defs = [];
3128
+ const tag = r.paths.some((p) => p.gradient) ? fnv(r.paths.map((p) => p.d + (p.gradient ? JSON.stringify(p.gradient) : "")).join("|")) : "";
3129
+ const path = (p) => {
3130
+ if (p.stroke) return `<path d="${attr(p.d)}" fill="none" stroke="${attr(p.fill)}" stroke-width="${attr(p.stroke)}" stroke-linecap="round" stroke-linejoin="round"/>`;
3131
+ if (!p.gradient) return `<path d="${attr(p.d)}" fill="${attr(p.fill)}"/>`;
3132
+ const id = `g${tag}-${defs.length}`;
3133
+ defs.push(gradientMarkup(p.gradient, id));
3134
+ return `<path d="${attr(p.d)}" fill="url(#${id}) ${attr(p.fill)}"/>`;
3135
+ };
3136
+ const body = r.paths.map(path).join("\n");
3137
+ const head = defs.length ? `<defs>\n${defs.join("\n")}\n</defs>\n` : "";
3138
+ 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`;
3139
+ }
3140
+ const num = (v) => String(Math.round(v * 100) / 100);
3141
+ /** A short hash (FNV-1a, base 36). */
3142
+ function fnv(s) {
3143
+ let h = 2166136261;
3144
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
3145
+ return (h >>> 0).toString(36);
3146
+ }
3147
+ /** A gradient element, in the drawing's pixels. */
3148
+ function gradientMarkup(g, id) {
3149
+ const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
3150
+ 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>`;
3151
+ }
3152
+ /** Trace to an SVG string; `trace` gives the shapes as data. */
3153
+ const traceInlay = (rgba, w, h, o) => toSvg(trace(rgba, w, h, o));
3154
+ /**
3155
+ * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
3156
+ * into filled shapes that share their edges exactly.
3157
+ */
3158
+ function trace(rgba, w, h, o) {
3159
+ const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette, !o.photo) : labelBinary(rgba, w, h, o.threshold);
3160
+ const clean = o.mode === "palette" && !o.pixels && !o.photo && lossless(rgba, labels, w, h, colors);
3161
+ if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
3162
+ if (!o.pixels) despur(labels, w, h);
3163
+ if (!o.pixels && !(o.mode === "palette" && o.photo)) joinDiagonals(labels, w, h, rgba, drawn);
3164
+ const labs = o.mode === "palette" && !o.photo ? colors.map((c) => c ? oklab(hexToRgb(c)) : null) : void 0;
3165
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2, labs);
3166
+ if (labs && !o.pixels) mergeSlivers(labels, w, h, labs, o.lines);
3167
+ const lines = o.mode === "palette" && o.strokes && labs && !o.pixels ? strokesOf(rgba, labels, w, h, colors, labs, drawn, o) : [];
3168
+ let { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
3169
+ const gradientOf = /* @__PURE__ */ new Map();
3170
+ if (o.gradients && o.mode === "palette" && !o.pixels) {
3171
+ const found = shadings(rgba, w, h, comp, compLabel.length, (id) => hexToRgb(colors[compLabel[id]]));
3172
+ if (found.length) {
3173
+ const relabel = new Int32Array(compLabel.length).fill(-1);
3174
+ for (const s of found) {
3175
+ const l = colors.length;
3176
+ colors.push(s.mean);
3177
+ drawn.push(true);
3178
+ gradientOf.set(l, s.gradient);
3179
+ for (const id of s.comps) relabel[id] = l;
3180
+ }
3181
+ for (let i = 0; i < labels.length; i++) if (comp[i] !== VOID && relabel[comp[i]] >= 0) labels[i] = relabel[comp[i]];
3182
+ ({comp, compLabel, compArea} = components(labels, w, h, (l) => drawn[l]));
3183
+ }
3184
+ }
3185
+ const chains = findChains(comp, w, h);
3186
+ const rgbOf = clean ? (id) => hexToRgb(colors[compLabel[id]]) : null;
3187
+ const flatSides = (c) => !gradientOf.has(compLabel[c.left]) && !gradientOf.has(compLabel[c.right]);
3188
+ const fitted = [];
3189
+ const chainsOf = /* @__PURE__ */ new Map();
3190
+ for (const c of chains) {
3191
+ 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);
3192
+ if (!cubics.length) continue;
3193
+ const i = fitted.push({
3194
+ chain: c,
3195
+ cubics,
3196
+ back: reverse(cubics)
3197
+ }) - 1;
3198
+ for (const id of /* @__PURE__ */ new Set([c.left, c.right])) if (id !== VOID) {
3199
+ const list = chainsOf.get(id);
3200
+ if (list) list.push(i);
3201
+ else chainsOf.set(id, [i]);
3202
+ }
3203
+ }
3204
+ /** The outline of a set of regions: the chains with exactly one side in it, walked with the set on the left. */
3205
+ const outline = (inSet, ids) => {
3206
+ const seen = /* @__PURE__ */ new Set();
3207
+ const out = [];
3208
+ for (const id of ids) for (const i of chainsOf.get(id) ?? []) {
3209
+ if (seen.has(i)) continue;
3210
+ seen.add(i);
3211
+ const { chain, cubics, back } = fitted[i];
3212
+ const l = chain.left !== VOID && inSet(chain.left);
3213
+ if (l !== (chain.right !== VOID && inSet(chain.right))) out.push({
3214
+ ...chain,
3215
+ cubics: l ? cubics : back,
3216
+ reversed: !l,
3217
+ i
3218
+ });
3219
+ }
3220
+ return assemble(out);
3221
+ };
3222
+ const shapes = [];
3223
+ const paint = (id) => ({
3224
+ fill: colors[compLabel[id]],
3225
+ ...gradientOf.has(compLabel[id]) ? { gradient: gradientOf.get(compLabel[id]) } : {}
3226
+ });
3227
+ if (!o.stacked) for (const id of chainsOf.keys()) {
3228
+ const loops = outline((r) => r === id, [id]);
3229
+ if (loops.length) shapes.push({
3230
+ subs: loops.map((l) => l.sub),
3231
+ ...paint(id),
3232
+ area: compArea[id]
3233
+ });
3234
+ }
3235
+ else if (o.mode === "palette" && !o.photo && !o.pixels) {
3236
+ const loopsOf = /* @__PURE__ */ new Map();
3237
+ for (const id of chainsOf.keys()) {
3238
+ const loops = outline((r) => r === id, [id]);
3239
+ if (loops.length) loopsOf.set(id, loops);
3240
+ }
3241
+ const layered = layerShapes(loopsOf, comp, w, h, voidSeeds(comp, w, h));
3242
+ layered.forEach(({ id, subs }, k) => shapes.push({
3243
+ subs,
3244
+ ...paint(id),
3245
+ area: layered.length - k
3246
+ }));
3247
+ } else {
3248
+ const own = /* @__PURE__ */ new Map();
3249
+ for (const id of chainsOf.keys()) {
3250
+ const loops = outline((r) => r === id, [id]);
3251
+ if (loops.length) own.set(id, Math.max(...loops.map((l) => Math.abs(l.area))));
3252
+ }
3253
+ const order = [...own.keys()].sort((a, b) => own.get(b) - own.get(a) || a - b);
3254
+ const rank = new Map(order.map((id, i) => [id, i]));
3255
+ const voids = voidSeeds(comp, w, h);
3256
+ for (const id of order) {
3257
+ const set = /* @__PURE__ */ new Set([id]);
3258
+ for (const i of chainsOf.get(id)) {
3259
+ const { left, right } = fitted[i].chain;
3260
+ const other = left === id ? right : left;
3261
+ if (other !== VOID && rank.has(other) && rank.get(other) > rank.get(id)) set.add(other);
3262
+ }
3263
+ const loops = outline((r) => set.has(r), set);
3264
+ if (!loops.length) continue;
3265
+ const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
3266
+ const kept = loops.filter((l) => l === outer || l.touchesVoid || [...l.across].some((r) => r !== VOID && rank.get(r) < rank.get(id)) || voids.some((p) => encloses(l.pts, p)));
3267
+ shapes.push({
3268
+ subs: kept.map((l) => l.sub),
3269
+ ...paint(id),
3270
+ area: own.get(id)
3271
+ });
3272
+ }
3273
+ }
3274
+ shapes.sort((a, b) => b.area - a.area);
3275
+ return {
3276
+ width: w,
3277
+ height: h,
3278
+ paths: [...shapes.map((x) => ({
3279
+ d: serializePath(x.subs),
3280
+ fill: x.fill,
3281
+ ...x.gradient ? { gradient: x.gradient } : {}
3282
+ })), ...lines]
3283
+ };
3284
+ }
3285
+ /**
3286
+ * Flat art, stacked: each region whole, back to front. Which of two touching
3287
+ * regions is in front is voted at the ends of the boundary between them (the
3288
+ * one whose outline carries straight on is in front), and each run of a back
3289
+ * region's outline that a front one hides is replaced by its continuation
3290
+ * (layers.ts). Then, as for photos, a hole is dropped when the shapes in it
3291
+ * are all painted later and cover it, so a background is one whole shape.
3292
+ */
3293
+ function layerShapes(loopsOf, comp, w, h, voids) {
3294
+ const turns = /* @__PURE__ */ new Map();
3295
+ const chains = /* @__PURE__ */ new Map();
3296
+ for (const [id, loops] of loopsOf) for (const l of loops) {
3297
+ for (const c of l.chains) chains.set(c.i, c);
3298
+ const n = l.chains.length;
3299
+ if (n < 2) continue;
3300
+ for (let k = 0; k < n; k++) {
3301
+ const c = l.chains[k];
3302
+ const next = l.chains[(k + 1) % n];
3303
+ const u = endDir(c.cubics);
3304
+ const v = startDir(next.cubics);
3305
+ if (!u || !v) continue;
3306
+ const at = c.reversed ? c.from : c.to;
3307
+ const t = turn(u, v);
3308
+ turns.set(`${c.i}:${at}:${id}`, t);
3309
+ turns.set(`${next.i}:${at}:${id}`, t);
3310
+ }
3311
+ }
3312
+ const votes = /* @__PURE__ */ new Map();
3313
+ const vote = (a, b) => votes.set(`${a}>${b}`, (votes.get(`${a}>${b}`) ?? 0) + 1);
3314
+ for (const c of chains.values()) {
3315
+ if (c.closed || c.left === VOID || c.right === VOID) continue;
3316
+ for (const at of [c.from, c.to]) {
3317
+ const tl = turns.get(`${c.i}:${at}:${c.left}`);
3318
+ const tr = turns.get(`${c.i}:${at}:${c.right}`);
3319
+ if (tl === void 0 || tr === void 0) continue;
3320
+ if (tl < 20 && tr > 40) vote(c.left, c.right);
3321
+ else if (tr < 20 && tl > 40) vote(c.right, c.left);
3322
+ }
3323
+ }
3324
+ const inFront = (a, b) => (votes.get(`${a}>${b}`) ?? 0) > 0 && !votes.get(`${b}>${a}`);
3325
+ const size = new Map([...loopsOf].map(([id, loops]) => [id, Math.max(...loops.map((l) => Math.abs(l.area)))]));
3326
+ const ids = [...loopsOf.keys()].sort((a, b) => size.get(b) - size.get(a) || a - b);
3327
+ const behind = new Map(ids.map((id) => [id, []]));
3328
+ const before = new Map(ids.map((id) => [id, 0]));
3329
+ for (const key of votes.keys()) {
3330
+ const [a, b] = key.split(">").map(Number);
3331
+ if (!inFront(a, b) || !behind.has(a) || !behind.has(b)) continue;
3332
+ behind.get(b).push(a);
3333
+ before.set(a, before.get(a) + 1);
3334
+ }
3335
+ const order = [];
3336
+ const done = /* @__PURE__ */ new Set();
3337
+ while (order.length < ids.length) {
3338
+ const next = ids.find((id) => !done.has(id) && before.get(id) === 0) ?? ids.find((id) => !done.has(id));
3339
+ done.add(next);
3340
+ order.push(next);
3341
+ for (const a of behind.get(next)) before.set(a, before.get(a) - 1);
3342
+ }
3343
+ const rank = new Map(order.map((id, k) => [id, k]));
3344
+ const under = (id, fronts) => {
3345
+ if ([...fronts].some((f) => rank.get(f) < rank.get(id))) return null;
3346
+ const at = (x, y) => x >= 0 && y >= 0 && x < w && y < h && fronts.has(comp[y * w + x]);
3347
+ return {
3348
+ hidden: (p) => at(Math.floor(p.x), Math.floor(p.y)),
3349
+ covered: (poly) => {
3350
+ let inside = 0;
3351
+ let under = 0;
3352
+ const y0 = Math.max(0, Math.floor(Math.min(...poly.map((p) => p.y))));
3353
+ const y1 = Math.min(h - 1, Math.ceil(Math.max(...poly.map((p) => p.y))));
3354
+ for (let y = y0; y <= y1; y++) {
3355
+ const cy = y + .5;
3356
+ const xs = [];
3357
+ for (let i = 0; i < poly.length; i++) {
3358
+ const a = poly[i];
3359
+ const b = poly[(i + 1) % poly.length];
3360
+ if (a.y <= cy !== b.y <= cy) xs.push(a.x + (cy - a.y) / (b.y - a.y) * (b.x - a.x));
3361
+ }
3362
+ xs.sort((a, b) => a - b);
3363
+ for (let k = 0; k + 1 < xs.length; k += 2) for (let x = Math.max(0, Math.ceil(xs[k] - .5)); x <= Math.min(w - 1, Math.floor(xs[k + 1] - .5)); x++) {
3364
+ inside++;
3365
+ if (at(x, y)) under++;
3366
+ }
3367
+ }
3368
+ return inside ? under / inside : 1;
3369
+ }
3370
+ };
3371
+ };
3372
+ return order.map((id) => {
3373
+ const loops = loopsOf.get(id);
3374
+ const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
3375
+ return {
3376
+ id,
3377
+ subs: loops.filter((l) => l === outer || l.touchesVoid || [...l.across].some((r) => r !== VOID && rank.get(r) < rank.get(id)) || voids.some((p) => encloses(l.pts, p))).map((l) => l === outer ? completeLoop(l, id, inFront, under) : l.sub)
3378
+ };
3379
+ });
3380
+ }
3381
+ /** The share of what a completion adds that must be under the shapes in front. */
3382
+ const COVERED = .95;
3383
+ /** A loop with each run of chains hidden by a region in front replaced by its continuation. */
3384
+ function completeLoop(l, id, inFront, under) {
3385
+ const cs = l.chains;
3386
+ const n = cs.length;
3387
+ const hiddenAt = cs.map((c) => across(c) !== VOID && inFront(across(c), id));
3388
+ const start = hiddenAt.indexOf(false);
3389
+ if (start < 0 || !hiddenAt.some(Boolean)) return l.sub;
3390
+ const visible = sample(cs.filter((_, k) => !hiddenAt[k]).flatMap((c) => c.cubics));
3391
+ const out = [];
3392
+ const joins = /* @__PURE__ */ new Set();
3393
+ let changed = false;
3394
+ for (let j = 0; j < n;) {
3395
+ const k = (start + j) % n;
3396
+ if (!hiddenAt[k]) {
3397
+ out.push(...cs[k].cubics);
3398
+ j++;
3399
+ continue;
3400
+ }
3401
+ let e = j;
3402
+ while (e < n && hiddenAt[(start + e) % n]) e++;
3403
+ const run = Array.from({ length: e - j }, (_, q) => cs[(start + j + q) % n]);
3404
+ const prev = cs[(start + j - 1 + n) % n];
3405
+ const next = cs[(start + e) % n];
3406
+ const t0 = endDir(prev.cubics);
3407
+ const t1 = startDir(next.cubics);
3408
+ const p0 = run[0].cubics[0][0];
3409
+ const last = run[run.length - 1].cubics;
3410
+ const p1 = last[last.length - 1][3];
3411
+ const front = under(id, new Set(run.map(across)));
3412
+ let fill = t0 && t1 && front ? complete(p0, t0, p1, t1, visible, straightEnd(prev.cubics, true), straightEnd(next.cubics, false), front.hidden) : null;
3413
+ if (fill && front.covered([...sample(fill), ...sample(run.flatMap((c) => c.cubics)).reverse()]) < COVERED) fill = null;
3414
+ if (fill) {
3415
+ joins.add(out.length);
3416
+ out.push(...fill);
3417
+ joins.add(out.length);
3418
+ changed = true;
3419
+ } else for (const c of run) out.push(...c.cubics);
3420
+ j = e;
3421
+ }
3422
+ if (!changed) return l.sub;
3423
+ const merged = [];
3424
+ out.forEach((c, k) => {
3425
+ const last = merged[merged.length - 1];
3426
+ if (k > 0 && joins.has(k) && collinear(last, c)) merged[merged.length - 1] = line(last[0], c[3]);
3427
+ else merged.push(c);
3428
+ });
3429
+ if (merged.length > 2 && joins.has(out.length) && collinear(merged[merged.length - 1], merged[0])) merged[0] = line(merged.pop()[0], merged[0][3]);
3430
+ return toSubpath(merged);
3431
+ }
3432
+ /** Two flat cubics, end to start, along one line (within a degree). */
3433
+ function collinear(a, b) {
3434
+ if (!isFlat(a) || !isFlat(b)) return false;
3435
+ const u = {
3436
+ x: a[3].x - a[0].x,
3437
+ y: a[3].y - a[0].y
3438
+ };
3439
+ const v = {
3440
+ x: b[3].x - b[0].x,
3441
+ y: b[3].y - b[0].y
3442
+ };
3443
+ const lu = Math.hypot(u.x, u.y);
3444
+ const lv = Math.hypot(v.x, v.y);
3445
+ return lu > 0 && lv > 0 && (u.x * v.x + u.y * v.y) / (lu * lv) > Math.cos(Math.PI / 180);
3446
+ }
3447
+ /** The share of solid pixels within SOLID of their colour, from which an image counts as saved without loss. */
3448
+ const LOSSLESS = .99;
3449
+ /**
3450
+ * Whether an image looks saved without loss: the pixels inside each region
3451
+ * (all four neighbours the same colour) are its colour, within SOLID. In the
3452
+ * score's drawings saved as PNG, 99.99% are; as JPEG q72, 84–97%. JPEG's
3453
+ * noise skews the blends at edges, and edges read from them moved the wrong
3454
+ * way (on the overlap fixture, 0.18% wrong became 0.19%).
3455
+ */
3456
+ function lossless(rgba, labels, w, h, colors) {
3457
+ const pal = colors.map((c) => c ? hexToRgb(c) : null);
3458
+ let inside = 0;
3459
+ let exact = 0;
3460
+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) {
3461
+ const i = y * w + x;
3462
+ const l = labels[i];
3463
+ const c = pal[l];
3464
+ if (!c || labels[i - 1] !== l || labels[i + 1] !== l || labels[i - w] !== l || labels[i + w] !== l) continue;
3465
+ inside++;
3466
+ if (Math.abs(rgba[i * 4] - c[0]) <= SOLID && Math.abs(rgba[i * 4 + 1] - c[1]) <= SOLID && Math.abs(rgba[i * 4 + 2] - c[2]) <= SOLID) exact++;
3467
+ }
3468
+ return inside > 0 && exact >= LOSSLESS * inside;
3469
+ }
3470
+ /** How far (px) an edge point may move off its pixel crack. */
3471
+ const SUBPIXEL = .35;
3472
+ /** Runs of cracks at least this long either side of a turn make it a corner. */
3473
+ const CORNER_RUN = 3;
3474
+ /** A pixel within this much (per channel, 0–255) of its colour is solid. */
3475
+ const SOLID = 3;
3476
+ /** Two colours closer than this (RGB) are too alike to place an edge between by blending. */
3477
+ const SUBPIXEL_CONTRAST = 48;
3478
+ /**
3479
+ * A chain's points at sub-pixel precision: each pixel corner along it, moved
3480
+ * across to where the anti-aliasing puts the edge. A pixel between
3481
+ * colours A and B is a blend, a share α of A; with A's pixel and B's pixel
3482
+ * either side of the crack, the edge is α_A + α_B − 1 px from the crack, into
3483
+ * B (Open Vectorizer's reading of anti-aliasing as coverage). The ends stay on
3484
+ * their junctions, so neighbours still share them.
3485
+ */
3486
+ function edgePoints(c, comp, w, rgba, rgbOf) {
3487
+ if (c.left === VOID || c.right === VOID) return void 0;
3488
+ const A = rgbOf(c.left);
3489
+ const B = rgbOf(c.right);
3490
+ const d = [
3491
+ B[0] - A[0],
3492
+ B[1] - A[1],
3493
+ B[2] - A[2]
3494
+ ];
3495
+ const len2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
3496
+ if (len2 < 2304) return void 0;
3497
+ const dLum = .299 * d[0] + .587 * d[1] + .114 * d[2];
3498
+ const share = (x, y, id) => {
3499
+ const i = y * w + x;
3500
+ if (comp[i] !== id) return null;
3501
+ const p = [
3502
+ rgba[i * 4] - A[0],
3503
+ rgba[i * 4 + 1] - A[1],
3504
+ rgba[i * 4 + 2] - A[2]
3505
+ ];
3506
+ let t = (p[0] * d[0] + p[1] * d[1] + p[2] * d[2]) / len2;
3507
+ if (Math.hypot(p[0] - t * d[0], p[1] - t * d[1], p[2] - t * d[2]) > Math.sqrt(len2) / 4) return null;
3508
+ if (Math.abs(dLum) >= SUBPIXEL_CONTRAST) t = (.299 * p[0] + .587 * p[1] + .114 * p[2]) / dLum;
3509
+ return 1 - Math.min(1, Math.max(0, t));
3510
+ };
3511
+ const pts = c.pts;
3512
+ const cracks = [];
3513
+ let good = 0;
3514
+ const m = c.closed ? pts.length : pts.length - 1;
3515
+ for (let k = 0; k < m; k++) {
3516
+ const a = pts[k];
3517
+ const b = pts[(k + 1) % pts.length];
3518
+ const L = Math.abs(b.x - a.x) + Math.abs(b.y - a.y);
3519
+ const dx = Math.sign(b.x - a.x);
3520
+ const dy = Math.sign(b.y - a.y);
3521
+ const nx = -dy;
3522
+ const ny = dx;
3523
+ for (let s = 0; s < L; s++) {
3524
+ const mx = a.x + dx * (s + .5);
3525
+ const my = a.y + dy * (s + .5);
3526
+ const l = share(Math.floor(mx - nx / 2), Math.floor(my - ny / 2), c.left);
3527
+ const r = share(Math.floor(mx + nx / 2), Math.floor(my + ny / 2), c.right);
3528
+ const solid = (depth, id, C) => {
3529
+ const x = Math.floor(mx + nx * depth / 2);
3530
+ const y = Math.floor(my + ny * depth / 2);
3531
+ if (x < 0 || y < 0 || x >= w || y >= comp.length / w) return false;
3532
+ const i = (y * w + x) * 4;
3533
+ return comp[i / 4] === id && Math.abs(rgba[i] - C[0]) <= SOLID && Math.abs(rgba[i + 1] - C[1]) <= SOLID && Math.abs(rgba[i + 2] - C[2]) <= SOLID;
3534
+ };
3535
+ const ok = l !== null && r !== null && solid(-3, c.left, A) && solid(3, c.right, B) && solid(-5, c.left, A) && solid(5, c.right, B);
3536
+ if (ok) good++;
3537
+ cracks.push({
3538
+ x: mx,
3539
+ y: my,
3540
+ nx,
3541
+ ny,
3542
+ e: ok ? Math.max(-.35, Math.min(SUBPIXEL, l + r - 1)) : NaN,
3543
+ run: L
3544
+ });
3545
+ }
3546
+ const run = cracks.slice(cracks.length - L);
3547
+ const measured = run.map((q) => q.e);
3548
+ run.forEach((q, s) => {
3549
+ if (!Number.isNaN(q.e)) return;
3550
+ let best = NaN;
3551
+ for (let step = 1; step < L && Number.isNaN(best); step++) best = [measured[s - step], measured[s + step]].find((e) => e !== void 0 && !Number.isNaN(e)) ?? NaN;
3552
+ q.e = Number.isNaN(best) ? 0 : best;
3553
+ });
3554
+ }
3555
+ if (good < cracks.length / 2) return void 0;
3556
+ const out = c.closed ? [] : [pts[0]];
3557
+ const n = cracks.length;
3558
+ cracks.forEach((q, k) => {
3559
+ const p = cracks[(k - 1 + n) % n];
3560
+ if ((c.closed || k > 0) && (p.nx !== q.nx || p.ny !== q.ny) && p.run >= CORNER_RUN && q.run >= CORNER_RUN) out.push({
3561
+ x: q.x - q.ny / 2 + p.nx * p.e + q.nx * q.e,
3562
+ y: q.y + q.nx / 2 + p.ny * p.e + q.ny * q.e
3563
+ });
3564
+ out.push({
3565
+ x: q.x + q.nx * q.e,
3566
+ y: q.y + q.ny * q.e
3567
+ });
3568
+ });
3569
+ if (!c.closed) out.push(pts[pts.length - 1]);
3570
+ return out;
3571
+ }
3572
+ /**
3573
+ * A chain as its exact pixel boundary: a line between each pair of turns.
3574
+ * The points are pixel corners about a pixel apart, so a run of them in one
3575
+ * direction is one straight edge. A closed loop starts at a turn, so its seam
3576
+ * isn't a node in the middle of an edge.
3577
+ */
3578
+ function staircase(pts, closed) {
3579
+ const n = pts.length;
3580
+ if (n < 2) return [];
3581
+ const dir = (a, b) => `${Math.sign(b.x - a.x)},${Math.sign(b.y - a.y)}`;
3582
+ const isTurn = (i) => {
3583
+ const a = pts[(i - 1 + n) % n];
3584
+ const b = pts[i];
3585
+ const c = pts[(i + 1) % n];
3586
+ return dir(a, b) !== dir(b, c);
3587
+ };
3588
+ const keep = [];
3589
+ if (closed) {
3590
+ const start = pts.findIndex((_, i) => isTurn(i));
3591
+ if (start < 0) return [];
3592
+ for (let k = 0; k < n; k++) {
3593
+ const i = (start + k) % n;
3594
+ if (isTurn(i)) keep.push(pts[i]);
3595
+ }
3596
+ keep.push(keep[0]);
3597
+ } else {
3598
+ keep.push(pts[0]);
3599
+ for (let i = 1; i < n - 1; i++) if (isTurn(i)) keep.push(pts[i]);
3600
+ keep.push(pts[n - 1]);
3601
+ }
3602
+ const out = [];
3603
+ for (let i = 1; i < keep.length; i++) {
3604
+ const a = keep[i - 1];
3605
+ const b = keep[i];
3606
+ out.push([
3607
+ a,
3608
+ {
3609
+ x: a.x + (b.x - a.x) / 3,
3610
+ y: a.y + (b.y - a.y) / 3
3611
+ },
3612
+ {
3613
+ x: a.x + (b.x - a.x) * 2 / 3,
3614
+ y: a.y + (b.y - a.y) * 2 / 3
3615
+ },
3616
+ b
3617
+ ]);
3618
+ }
3619
+ return out;
3620
+ }
3621
+ /** Relabel merged colours as their targets, following chains, in place. */
3622
+ function mergeLabels(labels, colors, merge) {
3623
+ const index = new Map(colors.map((c, i) => [c, i]));
3624
+ const remap = colors.map((c, i) => {
3625
+ let to = c;
3626
+ let at = i;
3627
+ const seen = /* @__PURE__ */ new Set();
3628
+ while (merge[to] && !seen.has(to)) {
3629
+ seen.add(to);
3630
+ to = merge[to].toLowerCase();
3631
+ const k = index.get(to);
3632
+ if (k !== void 0) at = k;
3633
+ }
3634
+ return at;
3635
+ });
3636
+ if (remap.every((t, i) => t === i)) return;
3637
+ for (let i = 0; i < labels.length; i++) labels[i] = remap[labels[i]];
3638
+ }
3639
+ /**
3640
+ * The colour an in-between pixel holds most of, read as an anti-aliased mix
3641
+ * of two palette colours (mixed as a renderer mixes them, in sRGB): the
3642
+ * pair whose mix comes nearest the pixel, if nearer than any one colour
3643
+ * (`solid`). Nearest-colour alone took the pale edge of a grey letter for
3644
+ * light blue, the palette's only colour that light. Only for a pixel more
3645
+ * than `MIX_FAR` from every colour: a pale blue fill lies on the line from
3646
+ * white to the blue ink too, and read as a mix a pale "+" eroded to white.
3647
+ */
3648
+ const MIX_FAR = .05;
3649
+ /** Every pair of palette colours, with what mixOf needs of each. */
3650
+ function pairsOf(pal, labs) {
3651
+ const pairs = [];
3652
+ for (let i = 0; i < pal.length; i++) for (let j = i + 1; j < pal.length; j++) {
3653
+ const a = pal[i];
3654
+ const d = [
3655
+ pal[j][0] - a[0],
3656
+ pal[j][1] - a[1],
3657
+ pal[j][2] - a[2]
3658
+ ];
3659
+ const len = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
3660
+ const span = Math.hypot(labs[i][0] - labs[j][0], labs[i][1] - labs[j][1], labs[i][2] - labs[j][2]);
3661
+ if (len) pairs.push({
3662
+ i,
3663
+ j,
3664
+ a,
3665
+ d,
3666
+ len,
3667
+ span
3668
+ });
3669
+ }
3670
+ return pairs;
3671
+ }
3672
+ function mixOf(rgb, lab, pairs, labs, solid) {
3673
+ let best;
3674
+ let bd = solid;
3675
+ let bspan = Infinity;
3676
+ for (const { i, j, a, d, len, span } of pairs) {
3677
+ 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));
3678
+ const m = oklab([
3679
+ a[0] + t * d[0],
3680
+ a[1] + t * d[1],
3681
+ a[2] + t * d[2]
3682
+ ]);
3683
+ const e = Math.hypot(m[0] - lab[0], m[1] - lab[1], m[2] - lab[2]);
3684
+ if (e < bd - .001 || best !== void 0 && e < bd + .001 && span < bspan) {
3685
+ bd = Math.min(bd, e);
3686
+ bspan = span;
3687
+ const di = Math.hypot(lab[0] - labs[i][0], lab[1] - labs[i][1], lab[2] - labs[i][2]);
3688
+ const dj = Math.hypot(lab[0] - labs[j][0], lab[1] - labs[j][1], lab[2] - labs[j][2]);
3689
+ best = t < .5 ? i : t > .5 ? j : di <= dj ? i : j;
3690
+ }
3691
+ }
3692
+ return best;
3693
+ }
3694
+ function labelPalette(rgba, w, h, palette, flat) {
3695
+ const pal = palette.map(hexToRgb);
3696
+ const labs = pal.map(oklab);
3697
+ const pairs = flat ? pairsOf(pal, labs) : null;
1503
3698
  const n = w * h;
1504
3699
  const labels = new Int32Array(n);
1505
3700
  const unsure = new Uint8Array(n);
@@ -1532,7 +3727,13 @@ function labelPalette(rgba, w, h, palette) {
1532
3727
  best = k;
1533
3728
  } else if (d < d2) d2 = d;
1534
3729
  });
1535
- hit = best | (d2 < Infinity && d1 > .4 * d2 ? 256 : 0);
3730
+ const between = d2 < Infinity && d1 > .4 * d2;
3731
+ if (between && pairs && d1 > MIX_FAR) best = mixOf([
3732
+ r,
3733
+ g,
3734
+ b
3735
+ ], lab, pairs, labs, d1) ?? best;
3736
+ hit = best | (between ? 256 : 0);
1536
3737
  cache.set(key, hit);
1537
3738
  }
1538
3739
  labels[i] = hit & 255;
@@ -1549,6 +3750,8 @@ function labelPalette(rgba, w, h, palette) {
1549
3750
  ]);
1550
3751
  let best = -1;
1551
3752
  let bd = Infinity;
3753
+ let kinds = 0;
3754
+ let seen = -1;
1552
3755
  for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
1553
3756
  const nx = x + dx;
1554
3757
  const ny = y + dy;
@@ -1556,7 +3759,9 @@ function labelPalette(rgba, w, h, palette) {
1556
3759
  const j = ny * w + nx;
1557
3760
  if (unsure[j]) continue;
1558
3761
  const l = labels[j];
1559
- if (l === transparent || l === best) continue;
3762
+ if (l === transparent) continue;
3763
+ if (l !== seen) seen = l, kinds++;
3764
+ if (l === best) continue;
1560
3765
  const p = labs[l];
1561
3766
  const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
1562
3767
  if (d < bd) {
@@ -1564,6 +3769,7 @@ function labelPalette(rgba, w, h, palette) {
1564
3769
  best = l;
1565
3770
  }
1566
3771
  }
3772
+ if (flat && kinds === 1 && best !== labels[i]) continue;
1567
3773
  if (best >= 0) fixed[i] = best;
1568
3774
  }
1569
3775
  return {
@@ -1581,8 +3787,10 @@ function labelBinary(rgba, w, h, threshold) {
1581
3787
  alpha[i] = rgba[i * 4 + 3] >= 128 ? 1 : 0;
1582
3788
  }
1583
3789
  const labels = new Int32Array(n);
1584
- if (threshold !== null) for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < threshold ? 0 : 1;
1585
- else {
3790
+ if (threshold !== null) {
3791
+ const t = threshold === "auto" ? autoThreshold(lum, alpha) : threshold;
3792
+ for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < t ? 0 : 1;
3793
+ } else {
1586
3794
  const global = otsu(lum, alpha);
1587
3795
  const mean = boxMean(lum, w, h, Math.max(7, Math.round(Math.min(w, h) / 32)));
1588
3796
  for (let i = 0; i < n; i++) labels[i] = alpha[i] && lum[i] < mean[i] - 12 && lum[i] < global + 32 ? 0 : 1;
@@ -1616,6 +3824,31 @@ function boxMean(v, w, h, r) {
1616
3824
  }
1617
3825
  return out;
1618
3826
  }
3827
+ /** Below this gap between the two sides' mean luminance, Otsu has split one population. */
3828
+ const MIN_INK_CONTRAST = 40;
3829
+ /**
3830
+ * Otsu's split, unless it falls inside a single population: a blank page
3831
+ * photographed with some noise splits down its own middle, and half of it
3832
+ * would trace as ink. Then the fixed 128 it replaced.
3833
+ */
3834
+ function autoThreshold(lum, alpha) {
3835
+ const t = otsu(lum, alpha);
3836
+ let dark = 0;
3837
+ let darkSum = 0;
3838
+ let light = 0;
3839
+ let lightSum = 0;
3840
+ for (let i = 0; i < lum.length; i++) {
3841
+ if (!alpha[i]) continue;
3842
+ if (lum[i] < t) {
3843
+ dark++;
3844
+ darkSum += lum[i];
3845
+ } else {
3846
+ light++;
3847
+ lightSum += lum[i];
3848
+ }
3849
+ }
3850
+ return dark && light && lightSum / light - darkSum / dark >= MIN_INK_CONTRAST ? t : 128;
3851
+ }
1619
3852
  /** Otsu's threshold over opaque pixels: the split that best separates two populations. */
1620
3853
  function otsu(lum, alpha) {
1621
3854
  const hist = new Array(256).fill(0);
@@ -1646,11 +3879,6 @@ function otsu(lum, alpha) {
1646
3879
  }
1647
3880
  return best;
1648
3881
  }
1649
- const hexToRgb = (hex) => [
1650
- parseInt(hex.slice(1, 3), 16),
1651
- parseInt(hex.slice(3, 5), 16),
1652
- parseInt(hex.slice(5, 7), 16)
1653
- ];
1654
3882
  /**
1655
3883
  * A pixel whose eight neighbours are at least seven of one other colour takes
1656
3884
  * that colour: a lone pixel jutting out of an edge, or a one-pixel nick in one.
@@ -1681,6 +3909,39 @@ function despur(labels, w, h) {
1681
3909
  }
1682
3910
  }
1683
3911
  }
3912
+ /**
3913
+ * Regions are 4-connected, so a line one pixel wide that runs diagonally, a
3914
+ * staircase of pixels touching only at corners, fell apart into specks, and
3915
+ * mergeSpecks then erased them: a 1 px outline at a slant traced as dashes or
3916
+ * not at all. Where two pixels of a colour touch only at a corner, across two
3917
+ * of another (a 2 × 2 checkerboard), one pair has to be joined. Join the pair
3918
+ * that isn't the background (the commonest label, or one that isn't drawn),
3919
+ * so the paper parts and the line goes on; between two inks, the pair whose
3920
+ * colour the corner pixel is nearer. The corner pixel that joins them is the
3921
+ * one whose colour is nearer the pair's: the anti-aliased half of the step.
3922
+ */
3923
+ function joinDiagonals(labels, w, h, rgba, drawn) {
3924
+ const count = /* @__PURE__ */ new Map();
3925
+ for (let i = 0; i < labels.length; i++) count.set(labels[i], (count.get(labels[i]) ?? 0) + 1);
3926
+ let paper = -1;
3927
+ for (const [l, c] of count) if (paper < 0 || c > count.get(paper)) paper = l;
3928
+ const back = (l) => l === paper || !drawn[l];
3929
+ const far = (i, a, b) => Math.hypot(rgba[i * 4] - (rgba[a * 4] + rgba[b * 4]) / 2, rgba[i * 4 + 1] - (rgba[a * 4 + 1] + rgba[b * 4 + 1]) / 2, rgba[i * 4 + 2] - (rgba[a * 4 + 2] + rgba[b * 4 + 2]) / 2);
3930
+ for (let y = 0; y < h - 1; y++) for (let x = 0; x < w - 1; x++) {
3931
+ const tl = y * w + x;
3932
+ const tr = tl + 1;
3933
+ const bl = tl + w;
3934
+ const br = bl + 1;
3935
+ if (labels[tl] !== labels[br] || labels[tr] !== labels[bl] || labels[tl] === labels[tr]) continue;
3936
+ const a = labels[tl];
3937
+ const b = labels[tr];
3938
+ let joinMain;
3939
+ if (back(a) !== back(b)) joinMain = back(b);
3940
+ else joinMain = Math.min(far(tr, tl, br), far(bl, tl, br)) <= Math.min(far(tl, tr, bl), far(br, tr, bl));
3941
+ if (joinMain) labels[far(tr, tl, br) <= far(bl, tl, br) ? tr : bl] = a;
3942
+ else labels[far(tl, tr, bl) <= far(br, tr, bl) ? tl : br] = b;
3943
+ }
3944
+ }
1684
3945
  const NEIGHBOURS = [
1685
3946
  [-1, -1],
1686
3947
  [0, -1],
@@ -1762,12 +4023,25 @@ function components(labels, w, h, keep) {
1762
4023
  * label they took and are stranded as a new speck. On photos that left
1763
4024
  * thousands of fragments, and a larger `speckle` left more, not fewer.
1764
4025
  */
1765
- function mergeSpecks(labels, w, h, minArea) {
4026
+ function mergeSpecks(labels, w, h, minArea, labs) {
1766
4027
  if (minArea <= 1) return;
1767
- for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea)) return;
4028
+ for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea, labs)) return;
1768
4029
  }
4030
+ /**
4031
+ * A speck at least this far (OKLab) from every colour around it is a shape,
4032
+ * not noise: a letter or a dot on paper. Ringing and anti-aliasing specks are
4033
+ * blends, close to a neighbour; grey text on white is 0.47 from it.
4034
+ */
4035
+ const SPECK_CONTRAST = .25;
4036
+ /**
4037
+ * But only from this share of the speck size up, and never under 6 px, so
4038
+ * raising Speckle still clears dust and text: at the default 8 (64 px) a
4039
+ * letter of 1.5 px strokes (10–40 px) stays and a 2 × 2 dot goes.
4040
+ */
4041
+ const SPECK_SHAPE = 1 / 8;
4042
+ const SPECK_MIN = 6;
1769
4043
  /** One pass of mergeSpecks; false when there was nothing left to merge. */
1770
- function mergeSpecksOnce(labels, w, h, minArea) {
4044
+ function mergeSpecksOnce(labels, w, h, minArea, labs) {
1771
4045
  const { comp, compArea } = components(labels, w, h, () => true);
1772
4046
  const small = compArea.map((a, id) => ({
1773
4047
  a,
@@ -1782,31 +4056,488 @@ function mergeSpecksOnce(labels, w, h, minArea) {
1782
4056
  for (let i = 0; i < w * h; i++) pixels[fill[comp[i]]++] = i;
1783
4057
  small.sort((p, q) => p.a - q.a);
1784
4058
  for (const { id } of small) {
1785
- const own = labels[pixels[start[id]]];
4059
+ const begin = start[id];
4060
+ const end = start[id + 1];
4061
+ const own = labels[pixels[begin]];
1786
4062
  const votes = /* @__PURE__ */ new Map();
1787
- for (let k = start[id]; k < start[id + 1]; k++) {
4063
+ let joined = false;
4064
+ for (let k = begin; k < end; k++) {
1788
4065
  const i = pixels[k];
1789
4066
  const x = i % w;
1790
4067
  const y = (i - x) / w;
1791
4068
  const vote = (j) => {
1792
4069
  const l = labels[j];
1793
4070
  if (l !== own) votes.set(l, (votes.get(l) ?? 0) + 1);
4071
+ else if (comp[j] !== id) joined = true;
1794
4072
  };
1795
4073
  if (x > 0) vote(i - 1);
1796
4074
  if (x < w - 1) vote(i + 1);
1797
4075
  if (y > 0) vote(i - w);
1798
4076
  if (y < h - 1) vote(i + w);
1799
4077
  }
4078
+ if (joined && labs) continue;
1800
4079
  let best = own;
1801
4080
  let most = 0;
1802
- for (const [l, v] of votes) if (v > most) most = v, best = l;
4081
+ const mine = labs?.[own];
4082
+ if (mine) {
4083
+ let near = Infinity;
4084
+ for (const [l, v] of votes) {
4085
+ const lab = labs[l];
4086
+ const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4087
+ if (d < near || d === near && v > most) near = d, most = v, best = l;
4088
+ }
4089
+ if (near > SPECK_CONTRAST && near < Infinity && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
4090
+ } else for (const [l, v] of votes) if (v > most) most = v, best = l;
1803
4091
  if (best !== own) {
1804
- for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
4092
+ for (let k = begin; k < end; k++) labels[pixels[k]] = best;
1805
4093
  changed = true;
1806
4094
  }
1807
4095
  }
1808
4096
  return changed;
1809
4097
  }
4098
+ /** Regions narrower than this on average (2 × area / perimeter, px) are slivers. */
4099
+ const SLIVER_WIDTH = 2;
4100
+ /** A sliver joins a neighbour only this close in colour (OKLab): two shades of one ink (0.08–0.11 apart), not a grey hairline on white (#d4d4d4 is 0.13 from it). */
4101
+ const SLIVER_DISTANCE = .12;
4102
+ /** A painted line's piece spans this many px (bounding-box diagonal) before it is kept from folding into a shape. */
4103
+ const LINE_PIECE_SPAN = 16;
4104
+ /**
4105
+ * Fold slivers into a neighbour of nearly the same colour. JPEG and WebP
4106
+ * smear a thin stroke into two shades of its ink (a 3 px letter stem came
4107
+ * out dark at its edges and lighter down the middle), and a one-pixel strip
4108
+ * of one shade inside the other fitted as a spike shooting out of the
4109
+ * letter. A hairline of a colour of its own has no neighbour that close, so
4110
+ * it stays. Within a pass a sliver waits if a neighbour has already moved, so
4111
+ * two side by side don't just swap colours.
4112
+ *
4113
+ * A region mostly on a painted line marked in `lines` folds only into another
4114
+ * such region, sliver or not: a dark outline between two dark shapes is
4115
+ * nearly their colour, and folding it in joined them, but one line labels as
4116
+ * several dark shades along its length, and keeping each piece apart cost a
4117
+ * painted film poster a third of its shapes. A line piece shorter than
4118
+ * LINE_PIECE_SPAN is too short to part anything, and folds as any sliver.
4119
+ */
4120
+ function mergeSlivers(labels, w, h, labs, lines) {
4121
+ for (let pass = 0; pass < 4; pass++) {
4122
+ const { comp, compArea } = components(labels, w, h, () => true);
4123
+ const m = compArea.length;
4124
+ const perimeter = new Int32Array(m);
4125
+ const label = new Int32Array(m);
4126
+ const onLine = new Int32Array(m);
4127
+ const x0 = new Int32Array(m).fill(w);
4128
+ const x1 = new Int32Array(m).fill(-1);
4129
+ const y0 = new Int32Array(m).fill(h);
4130
+ const y1 = new Int32Array(m).fill(-1);
4131
+ const around = /* @__PURE__ */ new Map();
4132
+ const touch = (a, b) => {
4133
+ const id = comp[a];
4134
+ perimeter[id]++;
4135
+ let c = around.get(id);
4136
+ if (!c) around.set(id, c = /* @__PURE__ */ new Set());
4137
+ c.add(comp[b]);
4138
+ };
4139
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
4140
+ const i = y * w + x;
4141
+ const c = comp[i];
4142
+ label[c] = labels[i];
4143
+ if (lines?.[i]) {
4144
+ onLine[c]++;
4145
+ if (x < x0[c]) x0[c] = x;
4146
+ if (x > x1[c]) x1[c] = x;
4147
+ if (y < y0[c]) y0[c] = y;
4148
+ if (y > y1[c]) y1[c] = y;
4149
+ }
4150
+ if (x < w - 1 && comp[i + 1] !== comp[i]) touch(i, i + 1), touch(i + 1, i);
4151
+ if (y < h - 1 && comp[i + w] !== comp[i]) touch(i, i + w), touch(i + w, i);
4152
+ }
4153
+ const to = new Int32Array(m).fill(-1);
4154
+ let changed = false;
4155
+ const onALine = (id) => 2 * onLine[id] > compArea[id];
4156
+ for (const [id, near] of [...around].sort((a, b) => compArea[a[0]] - compArea[b[0]])) {
4157
+ const sliver = 2 * compArea[id] / perimeter[id] < SLIVER_WIDTH;
4158
+ const line = onALine(id);
4159
+ if (!sliver && !line) continue;
4160
+ const mine = labs[label[id]];
4161
+ if (!mine || [...near].some((n) => to[n] >= 0)) continue;
4162
+ const nearest = (ok) => {
4163
+ let best = -1;
4164
+ let bd = SLIVER_DISTANCE;
4165
+ for (const n of near) {
4166
+ const lab = labs[label[n]];
4167
+ const d = lab && ok(n) ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4168
+ if (d < bd) bd = d, best = label[n];
4169
+ }
4170
+ return best;
4171
+ };
4172
+ const sides = new Set([...near].filter((n) => !onALine(n)).map((n) => label[n]));
4173
+ let best = nearest(line ? (n) => onALine(n) && !sides.has(label[n]) : () => true);
4174
+ if (best < 0 && line && sliver && Math.hypot(x1[id] - x0[id], y1[id] - y0[id]) < LINE_PIECE_SPAN) best = nearest(() => true);
4175
+ if (best < 0) continue;
4176
+ to[id] = best;
4177
+ changed = true;
4178
+ }
4179
+ if (!changed) return;
4180
+ for (let i = 0; i < w * h; i++) if (to[comp[i]] >= 0) labels[i] = to[comp[i]];
4181
+ }
4182
+ }
4183
+ /** A part of a region is thin enough to be a line up to this wide (px), times `scale`. */
4184
+ const LINE_WIDEST = 8;
4185
+ /** And long enough: at least this many times as long as it is wide, so a dot stays a shape. */
4186
+ const LINE_LENGTH = 3;
4187
+ /** A colour is drawn as lines when at least this share of it is in thin, long parts. */
4188
+ const LINE_SHARE = .3;
4189
+ /** A line colour is at least this far (OKLab) from the paper. */
4190
+ const LINE_CONTRAST = .25;
4191
+ /** Lines measured thinner than this (px, times `scale`) stay shapes: a centreline can't follow small lettering. */
4192
+ const LINE_WIDTH = 2.5;
4193
+ /** Pieces of a colour's ink more than this many times wider or thinner than its usual width stay shapes. */
4194
+ const LINE_SPREAD = 1.2;
4195
+ /** And pieces shorter than this many times their width stay shapes: a letter's skeleton is all branches. */
4196
+ const LINE_PIECE = 8;
4197
+ /** How far off the line–paper blend (a share of the distance between them) its shades and edges may stray. */
4198
+ const LINE_OFF = .15;
4199
+ /**
4200
+ * The thin, long parts of the `keep` labels' 4-connected regions, as a mask,
4201
+ * and their thick parts. A pixel is thick when it lies within a disc wider
4202
+ * than `widest` that fits inside its region (a solid area, a dot, a heading's
4203
+ * strokes); what remains of each region falls into parts, and a part is thin
4204
+ * when no wider than `widest` and at least LINE_LENGTH times as long as wide.
4205
+ * So an outline that runs into a solid area of the same ink is still a line.
4206
+ * Depths are in thirds of a pixel, by a 3-4 chamfer distance from the edge.
4207
+ */
4208
+ function thinParts(labels, w, h, keep, widest) {
4209
+ const n = w * h;
4210
+ const comp = new Int32Array(n);
4211
+ for (let i = 0; i < n; i++) comp[i] = keep(labels[i]) ? labels[i] : VOID;
4212
+ const depth = chamfer(comp, w, h, 1);
4213
+ const core = 1.5 * (widest + 1);
4214
+ const reach = new Int32Array(n);
4215
+ for (let i = 0; i < n; i++) if (comp[i] !== VOID && depth[i] > core) reach[i] = depth[i];
4216
+ chamfer(comp, w, h, -1, reach);
4217
+ const thick = new Uint8Array(n);
4218
+ const rest = new Int32Array(n).fill(-1);
4219
+ for (let i = 0; i < n; i++) {
4220
+ if (comp[i] === VOID) continue;
4221
+ if (reach[i] > 0) thick[i] = 1;
4222
+ else rest[i] = labels[i];
4223
+ }
4224
+ const parts = components(rest, w, h, (l) => l >= 0);
4225
+ const deepest = new Int32Array(parts.compArea.length);
4226
+ for (let i = 0; i < n; i++) if (parts.comp[i] !== VOID && depth[i] > deepest[parts.comp[i]]) deepest[parts.comp[i]] = depth[i];
4227
+ const thinPart = deepest.map((d, id) => {
4228
+ const wide = 2 * d / 3 - 1;
4229
+ return wide <= widest && parts.compArea[id] >= LINE_LENGTH * wide ** 2 ? 1 : 0;
4230
+ });
4231
+ const thin = new Uint8Array(n);
4232
+ for (let i = 0; i < n; i++) if (parts.comp[i] !== VOID && thinPart[parts.comp[i]]) thin[i] = 1;
4233
+ return {
4234
+ thin,
4235
+ thick
4236
+ };
4237
+ }
4238
+ /**
4239
+ * A 3-4 chamfer pass over `comp`'s regions, two sweeps. With `sign` 1 it is
4240
+ * each pixel's distance in from its region's edge; with −1 it spreads `into`
4241
+ * outwards, falling by the distance, so each pixel gets the most any pixel
4242
+ * reaches it with (a disc of that radius round each start).
4243
+ */
4244
+ function chamfer(comp, w, h, sign, into) {
4245
+ const n = w * h;
4246
+ const d = into ?? new Int32Array(n);
4247
+ if (!into) for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
4248
+ const i = y * w + x;
4249
+ const c = comp[i];
4250
+ d[i] = c === VOID || x === 0 || y === 0 || x === w - 1 || y === h - 1 || comp[i - 1] !== c || comp[i + 1] !== c || comp[i - w] !== c || comp[i + w] !== c ? 3 : 1 << 30;
4251
+ }
4252
+ const s = sign;
4253
+ for (let i = 0; i < n; i++) d[i] *= s;
4254
+ const sweep = (i, j, step) => {
4255
+ const c = comp[i];
4256
+ if (c !== VOID && comp[j] === c) {
4257
+ const v = d[j] + step;
4258
+ if (v < d[i]) d[i] = v;
4259
+ }
4260
+ };
4261
+ for (let y = 1; y < h - 1; y++) for (let x = 1, i = y * w + 1; x < w - 1; x++, i++) {
4262
+ sweep(i, i - 1, 3);
4263
+ sweep(i, i - w, 3);
4264
+ sweep(i, i - w - 1, 4);
4265
+ sweep(i, i - w + 1, 4);
4266
+ }
4267
+ for (let y = h - 2; y > 0; y--) for (let x = w - 2, i = y * w + x; x > 0; x--, i--) {
4268
+ sweep(i, i + 1, 3);
4269
+ sweep(i, i + w, 3);
4270
+ sweep(i, i + w + 1, 4);
4271
+ sweep(i, i + w - 1, 4);
4272
+ }
4273
+ for (let i = 0; i < n; i++) d[i] *= s;
4274
+ return d;
4275
+ }
4276
+ /**
4277
+ * Outline art's lines. Finds the colours that are mostly thin, long parts (an
4278
+ * outline 3 px wide), traces those parts down their middle as strokes (one
4279
+ * path a colour, at the width measured from its ink), and hands their pixels
4280
+ * to the shapes either side, which meet under the line's middle. The paper is
4281
+ * never a line, however thin its gaps.
4282
+ */
4283
+ function strokesOf(rgba, labels, w, h, colors, labs, drawn, o) {
4284
+ const n = w * h;
4285
+ const k = Math.max(1, o.scale ?? 1);
4286
+ const widest = LINE_WIDEST * k;
4287
+ const { thin } = thinParts(labels, w, h, (l) => drawn[l], widest);
4288
+ const total = /* @__PURE__ */ new Map();
4289
+ const inLines = /* @__PURE__ */ new Map();
4290
+ let clear = 0;
4291
+ for (let i = 0; i < n; i++) {
4292
+ const l = labels[i];
4293
+ if (!drawn[l]) {
4294
+ clear++;
4295
+ continue;
4296
+ }
4297
+ total.set(l, (total.get(l) ?? 0) + 1);
4298
+ if (thin[i]) inLines.set(l, (inLines.get(l) ?? 0) + 1);
4299
+ }
4300
+ const [commonest, most] = [...total].reduce((a, b) => b[1] > a[1] ? b : a, [-1, -1]);
4301
+ const paper = most >= clear ? commonest : -1;
4302
+ const contrasts = (l) => paper < 0 || dist(labs[l], labs[paper]) >= LINE_CONTRAST;
4303
+ const lineColours = [...inLines].filter(([l, a]) => l !== paper && contrasts(l) && a >= LINE_SHARE * total.get(l)).map(([l]) => l);
4304
+ if (!lineColours.length) return [];
4305
+ const line = new Uint8Array(n);
4306
+ const out = [];
4307
+ const lab = labCache(rgba);
4308
+ for (const l of lineColours.sort((a, b) => inLines.get(b) - inLines.get(a))) {
4309
+ const ground = paper >= 0 ? labs[paper] : labs[l][0] > .5 ? [
4310
+ 0,
4311
+ 0,
4312
+ 0
4313
+ ] : [
4314
+ 1,
4315
+ 0,
4316
+ 0
4317
+ ];
4318
+ const inky = blendTest(labs[l], ground);
4319
+ const like = labs.map((c, j) => j === l || j !== paper && drawn[j] && !!c && inky(c));
4320
+ const mask = new Int32Array(n);
4321
+ for (let i = 0; i < n; i++) mask[i] = like[labels[i]] && !line[i] ? 1 : 0;
4322
+ const parts = thinParts(mask, w, h, (v) => v === 1, widest);
4323
+ const ink = new Uint8Array(n);
4324
+ for (let i = 0; i < n; i++) if (!line[i] && (thin[i] && like[labels[i]] || parts.thin[i])) ink[i] = 1;
4325
+ edgesOf(ink, (i) => line[i] === 1 || parts.thick[i] === 1, w, (i) => rgba[i * 4 + 3] >= 128 && inky(lab(i)));
4326
+ const pieces = components(Int32Array.from(ink), w, h, (v) => v === 1);
4327
+ const { width, length, skel } = regionWidths(ink, w, h, pieces.comp, pieces.compArea.length);
4328
+ const long = (c) => width[c] >= LINE_WIDTH * k && length[c] >= LINE_PIECE * width[c];
4329
+ const usual = weightedMedian(width, pieces.compArea, (c) => long(c));
4330
+ const fits = (c) => long(c) && width[c] >= usual / LINE_SPREAD && width[c] <= usual * LINE_SPREAD;
4331
+ let kept = 0;
4332
+ let all = 0;
4333
+ for (let c = 0; c < pieces.compArea.length; c++) {
4334
+ all += pieces.compArea[c];
4335
+ if (fits(c)) kept += pieces.compArea[c];
4336
+ }
4337
+ if (kept < LINE_SHARE * all) continue;
4338
+ for (let i = 0; i < n; i++) if (ink[i] && !fits(pieces.comp[i])) ink[i] = skel[i] = 0;
4339
+ const { subs, measured } = skeletonStrokes(ink, w, h, o, skel);
4340
+ if (!subs.length) continue;
4341
+ for (const i of beyondStroke(ink, w, h, subs, measured)) {
4342
+ ink[i] = 0;
4343
+ labels[i] = l;
4344
+ }
4345
+ out.push({
4346
+ d: serializePath(subs),
4347
+ fill: colors[l],
4348
+ stroke: Math.round(measured * 100) / 100
4349
+ });
4350
+ for (let i = 0; i < n; i++) if (ink[i]) line[i] = 1;
4351
+ }
4352
+ if (!out.length) return out;
4353
+ const taken = new Uint8Array(n);
4354
+ const queued = new Uint8Array(n);
4355
+ for (let i = 0; i < n; i++) if (!line[i]) taken[i] = 1;
4356
+ let front = [];
4357
+ const push = (j, to) => {
4358
+ if (taken[j] || queued[j]) return;
4359
+ queued[j] = 1;
4360
+ to.push(j);
4361
+ };
4362
+ for (let i = 0; i < n; i++) {
4363
+ if (!taken[i]) continue;
4364
+ const x = i % w;
4365
+ if (x > 0) push(i - 1, front);
4366
+ if (x < w - 1) push(i + 1, front);
4367
+ if (i >= w) push(i - w, front);
4368
+ if (i + w < n) push(i + w, front);
4369
+ }
4370
+ while (front.length) {
4371
+ const grown = [];
4372
+ for (const i of front) {
4373
+ const x = i % w;
4374
+ const from = x > 0 && taken[i - 1] ? i - 1 : x < w - 1 && taken[i + 1] ? i + 1 : i >= w && taken[i - w] ? i - w : i + w < n && taken[i + w] ? i + w : -1;
4375
+ if (from < 0) continue;
4376
+ labels[i] = labels[from];
4377
+ grown.push(i);
4378
+ }
4379
+ const next = [];
4380
+ for (const i of grown) taken[i] = 1;
4381
+ for (const i of grown) {
4382
+ const x = i % w;
4383
+ if (x > 0) push(i - 1, next);
4384
+ if (x < w - 1) push(i + 1, next);
4385
+ if (i >= w) push(i - w, next);
4386
+ if (i + w < n) push(i + w, next);
4387
+ }
4388
+ front = next;
4389
+ }
4390
+ return out;
4391
+ }
4392
+ /** Ink past a stroke's edge (px) before it counts as ink the stroke misses: anti-aliasing and fitting stay within it. */
4393
+ const BEYOND = .75;
4394
+ /** A piece of missed ink is kept only if this many pixels or more; less is the edge's noise. */
4395
+ const BEYOND_AREA = 6;
4396
+ /**
4397
+ * The ink a stroke of `width` along `subs` doesn't cover at the stroke's open
4398
+ * ends, in pieces of at least BEYOND_AREA pixels, each with the ink within
4399
+ * half the width of it so it comes out solid: a dot drawn on a line's end.
4400
+ * Missed ink elsewhere (the tip of a sharp corner, which a centreline turns
4401
+ * inside) is left to the line: as a shape it reads as a blob, not a point.
4402
+ */
4403
+ function beyondStroke(ink, w, h, subs, width) {
4404
+ const n = w * h;
4405
+ const covered = new Uint8Array(n);
4406
+ const r = width / 2 + BEYOND;
4407
+ const stamp = (p) => {
4408
+ for (let y = Math.max(0, Math.floor(p.y - r)); y <= Math.min(h - 1, Math.ceil(p.y + r)); y++) for (let x = Math.max(0, Math.floor(p.x - r)); x <= Math.min(w - 1, Math.ceil(p.x + r)); x++) if ((x + .5 - p.x) ** 2 + (y + .5 - p.y) ** 2 <= r * r) covered[y * w + x] = 1;
4409
+ };
4410
+ for (const sp of subs) {
4411
+ const m = sp.nodes.length;
4412
+ if (m === 1) stamp(sp.nodes[0]);
4413
+ for (let i = 0; i < (sp.closed ? m : m - 1); i++) {
4414
+ const a = sp.nodes[i];
4415
+ const b = sp.nodes[(i + 1) % m];
4416
+ const c = [
4417
+ a,
4418
+ a.out ?? a,
4419
+ b.in ?? b,
4420
+ b
4421
+ ];
4422
+ const steps = Math.max(2, Math.ceil(2 * (Math.hypot(c[1].x - c[0].x, c[1].y - c[0].y) + Math.hypot(c[2].x - c[1].x, c[2].y - c[1].y) + Math.hypot(c[3].x - c[2].x, c[3].y - c[2].y))));
4423
+ for (let k = 0; k <= steps; k++) stamp(pointAt(c, k / steps));
4424
+ }
4425
+ }
4426
+ const missed = new Int32Array(n);
4427
+ for (let i = 0; i < n; i++) missed[i] = ink[i] && !covered[i] ? 1 : 0;
4428
+ const pieces = components(missed, w, h, (v) => v === 1);
4429
+ const ends = subs.filter((sp) => !sp.closed && sp.nodes.length > 1).flatMap((sp) => [sp.nodes[0], sp.nodes[sp.nodes.length - 1]]);
4430
+ const atEnd = new Uint8Array(pieces.compArea.length);
4431
+ const near = width + 1;
4432
+ for (let i = 0; i < n; i++) if (missed[i] && !atEnd[pieces.comp[i]]) {
4433
+ const x = i % w + .5;
4434
+ const y = Math.floor(i / w) + .5;
4435
+ if (ends.some((e) => (e.x - x) ** 2 + (e.y - y) ** 2 <= near * near)) atEnd[pieces.comp[i]] = 1;
4436
+ }
4437
+ const out = [];
4438
+ const taken = new Uint8Array(n);
4439
+ for (let i = 0; i < n; i++) if (missed[i] && atEnd[pieces.comp[i]] && pieces.compArea[pieces.comp[i]] >= BEYOND_AREA) {
4440
+ taken[i] = 1;
4441
+ out.push(i);
4442
+ }
4443
+ let front = out.slice();
4444
+ for (let step = 0; step < Math.round(width / 2) && front.length; step++) {
4445
+ const next = [];
4446
+ for (const i of front) {
4447
+ const x = i % w;
4448
+ for (const j of [
4449
+ x > 0 ? i - 1 : -1,
4450
+ x < w - 1 ? i + 1 : -1,
4451
+ i - w,
4452
+ i + w
4453
+ ]) if (j >= 0 && j < n && ink[j] && !taken[j]) {
4454
+ taken[j] = 1;
4455
+ next.push(j);
4456
+ out.push(j);
4457
+ }
4458
+ }
4459
+ front = next;
4460
+ }
4461
+ return out;
4462
+ }
4463
+ /** The median of `values` weighted by `weights`, over the indices `ok` takes; 0 if none. */
4464
+ function weightedMedian(values, weights, ok) {
4465
+ const order = [];
4466
+ let total = 0;
4467
+ for (let i = 0; i < values.length; i++) if (ok(i)) {
4468
+ order.push(i);
4469
+ total += weights[i];
4470
+ }
4471
+ order.sort((a, b) => values[a] - values[b]);
4472
+ let run = 0;
4473
+ for (const i of order) if ((run += weights[i]) >= total / 2) return values[i];
4474
+ return 0;
4475
+ }
4476
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
4477
+ /** OKLab of each pixel, cached by its colour (a drawing has few). */
4478
+ function labCache(rgba) {
4479
+ const cache = /* @__PURE__ */ new Map();
4480
+ return (i) => {
4481
+ const key = rgba[i * 4] << 16 | rgba[i * 4 + 1] << 8 | rgba[i * 4 + 2];
4482
+ let v = cache.get(key);
4483
+ if (!v) cache.set(key, v = oklab([
4484
+ rgba[i * 4],
4485
+ rgba[i * 4 + 1],
4486
+ rgba[i * 4 + 2]
4487
+ ]));
4488
+ return v;
4489
+ };
4490
+ }
4491
+ /** Whether a colour lies between the paper and the line (or beyond, darker), nearer the line. */
4492
+ function blendTest(line, paper) {
4493
+ const span = [
4494
+ line[0] - paper[0],
4495
+ line[1] - paper[1],
4496
+ line[2] - paper[2]
4497
+ ];
4498
+ const len2 = span[0] ** 2 + span[1] ** 2 + span[2] ** 2;
4499
+ return (lab) => {
4500
+ if (!len2) return false;
4501
+ const d = [
4502
+ lab[0] - paper[0],
4503
+ lab[1] - paper[1],
4504
+ lab[2] - paper[2]
4505
+ ];
4506
+ const t = (d[0] * span[0] + d[1] * span[1] + d[2] * span[2]) / len2;
4507
+ const off = (d[0] - t * span[0]) ** 2 + (d[1] - t * span[1]) ** 2 + (d[2] - t * span[2]) ** 2;
4508
+ return t >= .5 && t <= 2 && off <= LINE_OFF ** 2 * len2;
4509
+ };
4510
+ }
4511
+ /**
4512
+ * Grows a line's ink into every touching opaque pixel that passes `inky`,
4513
+ * short of `blocked` ones: its anti-aliased edges, and stretches the palette
4514
+ * gave a darker shade. Without them a line comes out broken and thinner than
4515
+ * drawn.
4516
+ */
4517
+ function edgesOf(ink, blocked, w, inky) {
4518
+ const n = ink.length;
4519
+ const seen = ink.slice();
4520
+ let front = [];
4521
+ for (let i = 0; i < n; i++) if (ink[i]) front.push(i);
4522
+ const visit = (j, to) => {
4523
+ if (seen[j]) return;
4524
+ seen[j] = 1;
4525
+ if (blocked(j) || !inky(j)) return;
4526
+ ink[j] = 1;
4527
+ to.push(j);
4528
+ };
4529
+ while (front.length) {
4530
+ const next = [];
4531
+ for (const i of front) {
4532
+ const x = i % w;
4533
+ if (x > 0) visit(i - 1, next);
4534
+ if (x < w - 1) visit(i + 1, next);
4535
+ if (i >= w) visit(i - w, next);
4536
+ if (i + w < n) visit(i + w, next);
4537
+ }
4538
+ front = next;
4539
+ }
4540
+ }
1810
4541
  function findChains(comp, w, h) {
1811
4542
  const C = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? VOID : comp[y * w + x];
1812
4543
  const W1 = w + 1;
@@ -1896,11 +4627,6 @@ function findChains(comp, w, h) {
1896
4627
  for (let y = 0; y < h; y++) for (let x = 0; x <= w; x++) if (vEdge[y * W1 + x]) walk(x, y, 1);
1897
4628
  return chains;
1898
4629
  }
1899
- function addOriented(map, id, c) {
1900
- const list = map.get(id);
1901
- if (list) list.push(c);
1902
- else map.set(id, [c]);
1903
- }
1904
4630
  const reverse = (cubics) => cubics.map(([a, b, c, d]) => [
1905
4631
  d,
1906
4632
  c,
@@ -1916,7 +4642,7 @@ const across = (c) => c.reversed ? c.left : c.right;
1916
4642
  function assemble(chains) {
1917
4643
  const subs = [];
1918
4644
  const open = [];
1919
- for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts));
4645
+ for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts, /* @__PURE__ */ new Set([across(c)]), [c]));
1920
4646
  else open.push(c);
1921
4647
  const start = (c) => c.reversed ? c.to : c.from;
1922
4648
  const end = (c) => c.reversed ? c.from : c.to;
@@ -1935,29 +4661,35 @@ function assemble(chains) {
1935
4661
  const loop = [];
1936
4662
  const pts = [];
1937
4663
  let touchesVoid = false;
4664
+ const acrossIds = /* @__PURE__ */ new Set();
4665
+ const seq = [];
1938
4666
  let c = first;
1939
4667
  while (c && !used.has(c)) {
1940
4668
  used.add(c);
4669
+ seq.push(c);
1941
4670
  loop.push(...c.cubics);
1942
4671
  pts.push(...c.reversed ? [...c.pts].reverse() : c.pts);
1943
4672
  if (across(c) === VOID) touchesVoid = true;
4673
+ acrossIds.add(across(c));
1944
4674
  if (end(c) === start(first)) break;
1945
4675
  const into = lastDir(c);
1946
4676
  c = (byStart.get(end(c)) ?? []).filter((n) => !used.has(n)).sort((a, b) => cross(into, firstDir(a)) - cross(into, firstDir(b)))[0];
1947
4677
  }
1948
- if (loop.length) subs.push(loopOf(loop, touchesVoid, pts));
4678
+ if (loop.length) subs.push(loopOf(loop, touchesVoid, pts, acrossIds, seq));
1949
4679
  }
1950
4680
  return subs;
1951
4681
  }
1952
4682
  /** A loop and its signed area (shoelace over its cubics' end points: enough to rank and orient). */
1953
- function loopOf(cubics, touchesVoid, pts) {
4683
+ function loopOf(cubics, touchesVoid, pts, acrossIds, chains) {
1954
4684
  let area = 0;
1955
4685
  for (const [a, , , d] of cubics) area += a.x * d.y - d.x * a.y;
1956
4686
  return {
1957
4687
  sub: toSubpath(cubics),
1958
4688
  area: area / 2,
1959
4689
  touchesVoid,
1960
- pts
4690
+ pts,
4691
+ across: acrossIds,
4692
+ chains
1961
4693
  };
1962
4694
  }
1963
4695
  /** One pixel centre from each 4-connected area of VOID (transparent pixels) in the image. */
@@ -2040,6 +4772,240 @@ function toSubpath(cubics) {
2040
4772
  };
2041
4773
  }
2042
4774
  //#endregion
4775
+ //#region src/smooth.ts
4776
+ /**
4777
+ * Edge-preserving smoothing for painted art, before its palette is picked.
4778
+ *
4779
+ * A painted poster's skin shadow is a soft ramp with brush and JPEG noise on
4780
+ * it. Labelled pixel by pixel, the noise flips each pixel between the two
4781
+ * nearest palette colours, and the shadow traces as ragged patches. A
4782
+ * bilateral filter averages each pixel with neighbours of a similar colour
4783
+ * only, so the noise inside a shadow evens out and the edges between colours
4784
+ * (an arm against the dark coat, a line on a face) stay where they are.
4785
+ *
4786
+ * On a painted film poster traced at 2× in Illustration, this turned the
4787
+ * blotchy arm and neck shadows into whole shapes, kept the face lines, and cut
4788
+ * the file from 3.3 MB to 2.1 MB; the filter took 4 s of the trace. Stronger
4789
+ * (radius 6, three passes at sigma 25) began to wash out lines in the hair.
4790
+ */
4791
+ /** Neighbourhood radius, px. */
4792
+ const RADIUS = 4;
4793
+ /** Spatial falloff (Gaussian sigma, px). */
4794
+ const SIGMA_SPACE = 3;
4795
+ /** Colour falloff (Gaussian sigma, RGB distance). */
4796
+ const SIGMA_COLOR = 30;
4797
+ const PASSES = 3;
4798
+ /**
4799
+ * A smoothed copy of `rgba` (`width` × `height`, RGBA). Transparent pixels, and
4800
+ * any marked in `keep` (one entry per pixel, non-zero to keep), are left as
4801
+ * they are and never averaged into their neighbours.
4802
+ */
4803
+ function smoothShading(rgba, width, height, keep) {
4804
+ const dxs = [];
4805
+ const dys = [];
4806
+ const ws = [];
4807
+ for (let dy = -4; dy <= RADIUS; dy++) for (let dx = -4; dx <= RADIUS; dx++) if (dx * dx + dy * dy <= 16) {
4808
+ dxs.push(dx);
4809
+ dys.push(dy);
4810
+ ws.push(Math.exp(-(dx * dx + dy * dy) / (2 * SIGMA_SPACE ** 2)));
4811
+ }
4812
+ const n = ws.length;
4813
+ const offsets = Int32Array.from(dxs, (dx, k) => (dys[k] * width + dx) * 4);
4814
+ const spatial = Float32Array.from(ws);
4815
+ const near = Float32Array.from({ length: 195076 }, (_, d2) => Math.exp(-d2 / (2 * SIGMA_COLOR ** 2)));
4816
+ let src = Uint8ClampedArray.from(rgba);
4817
+ const kept = [];
4818
+ if (keep) {
4819
+ for (let p = 0; p < width * height; p++) if (keep[p] && src[p * 4 + 3] >= 128) {
4820
+ kept.push(p, src[p * 4 + 3]);
4821
+ src[p * 4 + 3] = 0;
4822
+ }
4823
+ }
4824
+ for (let pass = 0; pass < PASSES; pass++) {
4825
+ const out = new Uint8ClampedArray(src);
4826
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4827
+ const i = (y * width + x) * 4;
4828
+ if (src[i + 3] < 128) continue;
4829
+ const r = src[i];
4830
+ const g = src[i + 1];
4831
+ const b = src[i + 2];
4832
+ const inside = x >= RADIUS && y >= RADIUS && x < width - RADIUS && y < height - RADIUS;
4833
+ let sr = 0;
4834
+ let sg = 0;
4835
+ let sb = 0;
4836
+ let sw = 0;
4837
+ for (let k = 0; k < n; k++) {
4838
+ if (!inside) {
4839
+ const nx = x + dxs[k];
4840
+ const ny = y + dys[k];
4841
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
4842
+ }
4843
+ const j = i + offsets[k];
4844
+ if (src[j + 3] < 128) continue;
4845
+ const dr = src[j] - r;
4846
+ const dg = src[j + 1] - g;
4847
+ const db = src[j + 2] - b;
4848
+ const w = spatial[k] * near[dr * dr + dg * dg + db * db];
4849
+ sr += w * src[j];
4850
+ sg += w * src[j + 1];
4851
+ sb += w * src[j + 2];
4852
+ sw += w;
4853
+ }
4854
+ out[i] = sr / sw;
4855
+ out[i + 1] = sg / sw;
4856
+ out[i + 2] = sb / sw;
4857
+ }
4858
+ src = out;
4859
+ }
4860
+ for (let k = 0; k < kept.length; k += 2) src[kept[k] * 4 + 3] = kept[k + 1];
4861
+ return src;
4862
+ }
4863
+ /** A line pixel is this much darker than its closing (0–255 lightness) at least. */
4864
+ const LINE_DEPTH = 6;
4865
+ /** And darkened by this many times that depth, */
4866
+ const LINE_GAIN = 2;
4867
+ /** but by no more than this: a line already well apart from its sides (brows on skin) keeps its colour. */
4868
+ const LINE_MAX = 30;
4869
+ /** A line is kept only when it spans this many times the radius (bounding-box diagonal): texture is short. */
4870
+ const LINE_SPAN = 4;
4871
+ /**
4872
+ * Painted outlines made plain, before the palette is picked. A painter's line
4873
+ * between two near-equal colours (a mouth on a shadowed face, dark trousers
4874
+ * against a dark background) is only a few levels darker than either side, so
4875
+ * it labels as one of them and is lost. A black-hat filter (the image's
4876
+ * closing minus the image, over `radius` px) finds lines up to about twice
4877
+ * that wide that are darker than both sides; each is darkened by twice its
4878
+ * depth, at most LINE_MAX, colour kept, so it labels apart from both sides.
4879
+ * Only lines that run a while are kept: brick, foliage and brush texture are
4880
+ * dark too, but short. When `lines` (one entry per pixel) is given, each
4881
+ * pixel darkened is marked in it with 1, for `smoothShading`'s `keep` and
4882
+ * the tracer's `lines`, which leave them be.
4883
+ *
4884
+ * On a painted film poster at 2× (radius 3), with smoothing, this brought back
4885
+ * the mouth, eyes, brows and jaw lines Illustration lost, and the outline
4886
+ * parting dark trousers from a dark background, for twice the paths (2.1 to
4887
+ * 3.6 MB). The trousers merged with the background until the lines were marked:
4888
+ * the outline was found, but smoothing blurred it back into its sides, and,
4889
+ * left unsmoothed, it labelled as the near-black of the trousers, close
4890
+ * enough to the dark grey on either side to be folded in as a sliver.
4891
+ */
4892
+ function boostLines(rgba, width, height, radius = 2, lines) {
4893
+ const n = width * height;
4894
+ const out = Uint8ClampedArray.from(rgba);
4895
+ const lum = new Float32Array(n);
4896
+ for (let i = 0; i < n; i++) lum[i] = .299 * out[i * 4] + .587 * out[i * 4 + 1] + .114 * out[i * 4 + 2];
4897
+ const sweep = (src, max) => {
4898
+ const across = new Float32Array(n);
4899
+ const down = new Float32Array(n);
4900
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4901
+ let v = src[y * width + x];
4902
+ for (let k = Math.max(0, x - radius); k <= Math.min(width - 1, x + radius); k++) v = max ? Math.max(v, src[y * width + k]) : Math.min(v, src[y * width + k]);
4903
+ across[y * width + x] = v;
4904
+ }
4905
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
4906
+ let v = across[y * width + x];
4907
+ for (let k = Math.max(0, y - radius); k <= Math.min(height - 1, y + radius); k++) v = max ? Math.max(v, across[k * width + x]) : Math.min(v, across[k * width + x]);
4908
+ down[y * width + x] = v;
4909
+ }
4910
+ return down;
4911
+ };
4912
+ const closed = sweep(sweep(lum, true), false);
4913
+ const depth = new Float32Array(n);
4914
+ for (let i = 0; i < n; i++) if (out[i * 4 + 3] >= 128 && closed[i] - lum[i] > LINE_DEPTH) depth[i] = closed[i] - lum[i];
4915
+ const seen = new Uint8Array(n);
4916
+ const stack = [];
4917
+ const piece = [];
4918
+ const span = LINE_SPAN * radius;
4919
+ for (let s = 0; s < n; s++) {
4920
+ if (!depth[s] || seen[s]) continue;
4921
+ seen[s] = 1;
4922
+ stack.push(s);
4923
+ piece.length = 0;
4924
+ let x0 = width;
4925
+ let x1 = 0;
4926
+ let y0 = height;
4927
+ let y1 = 0;
4928
+ while (stack.length) {
4929
+ const i = stack.pop();
4930
+ piece.push(i);
4931
+ const x = i % width;
4932
+ const y = (i - x) / width;
4933
+ x0 = Math.min(x0, x);
4934
+ x1 = Math.max(x1, x);
4935
+ y0 = Math.min(y0, y);
4936
+ y1 = Math.max(y1, y);
4937
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
4938
+ const nx = x + dx;
4939
+ const ny = y + dy;
4940
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
4941
+ const j = ny * width + nx;
4942
+ if (depth[j] && !seen[j]) {
4943
+ seen[j] = 1;
4944
+ stack.push(j);
4945
+ }
4946
+ }
4947
+ }
4948
+ if (Math.hypot(x1 - x0, y1 - y0) < span) continue;
4949
+ for (const i of piece) {
4950
+ const target = Math.max(0, lum[i] - Math.min(LINE_MAX, LINE_GAIN * depth[i]));
4951
+ const f = lum[i] > 0 ? target / lum[i] : 0;
4952
+ out[i * 4] *= f;
4953
+ out[i * 4 + 1] *= f;
4954
+ out[i * 4 + 2] *= f;
4955
+ if (lines) lines[i] = 1;
4956
+ }
4957
+ }
4958
+ return out;
4959
+ }
4960
+ //#endregion
4961
+ //#region src/centerline.ts
4962
+ /**
4963
+ * Centerline tracing: single strokes down the middle of the ink, for pen
4964
+ * plotters, engravers and handwriting, instead of outlines round it.
4965
+ *
4966
+ * 1. Threshold the image to ink and paper (as line art does), and fold specks
4967
+ * and pinholes into their surroundings so they don't become stray strokes
4968
+ * or little loops.
4969
+ * 2. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
4970
+ * algorithm for thinning digital patterns", CACM 1984).
4971
+ * 3. Measure the stroke width: the ink's area over the skeleton's length.
4972
+ * 4. Prune spurs: short branches that thinning grows from bumps in the
4973
+ * outline, anything shorter than the stroke is wide.
4974
+ * 5. Walk the skeleton into chains between ends and junctions. Where strokes
4975
+ * cross or branch, chains that carry on in the same direction are joined,
4976
+ * so a plotter lifts its pen less.
4977
+ * 6. Fit each chain with the same curve fitter as outlines, and draw it as an
4978
+ * open (or, for a loop, closed) stroke with round caps and joins.
4979
+ *
4980
+ * Everything here is written for this project (MIT); no GPL tracer is used.
4981
+ */
4982
+ /** Trace to an SVG string; `centerline` gives the strokes as data. */
4983
+ const traceCenterline = (rgba, w, h, o) => centerlineToSvg(centerline(rgba, w, h, o));
4984
+ function centerlineToSvg(r) {
4985
+ const paths = r.paths.map((p) => `<path d="${attr(p.d)}" fill="none" stroke="${attr(p.stroke)}" stroke-width="${attr(round(p.strokeWidth))}" stroke-linecap="round" stroke-linejoin="round"/>`);
4986
+ 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${paths.join("\n")}\n</svg>\n`;
4987
+ }
4988
+ const round = (n) => Math.round(n * 100) / 100;
4989
+ function centerline(rgba, w, h, o) {
4990
+ const { labels, drawn } = labelBinary(rgba, w, h, o.threshold);
4991
+ joinDiagonals(labels, w, h, rgba, drawn);
4992
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
4993
+ const ink = new Uint8Array(w * h);
4994
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
4995
+ const { subs, measured } = skeletonStrokes(ink, w, h, o);
4996
+ const width = o.strokeWidth && o.strokeWidth > 0 ? o.strokeWidth : measured;
4997
+ return {
4998
+ width: w,
4999
+ height: h,
5000
+ paths: subs.length ? [{
5001
+ d: serializePath(subs),
5002
+ stroke: o.color ?? "#000000",
5003
+ strokeWidth: round(width)
5004
+ }] : [],
5005
+ measuredWidth: round(measured)
5006
+ };
5007
+ }
5008
+ //#endregion
2043
5009
  //#region src/symmetry.ts
2044
5010
  /**
2045
5011
  * Score every candidate symmetry: the best vertical and horizontal mirror axes
@@ -2223,4 +5189,4 @@ function detectSymmetry(rgba, w, h, options = {}) {
2223
5189
  return out.sort((a, b) => b.score - a.score);
2224
5190
  }
2225
5191
  //#endregion
2226
- export { detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, staircase, toSvg, trace, traceInlay };
5192
+ export { boostLines, centerline, centerlineToSvg, colorAt, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, smoothShading, staircase, toSvg, trace, traceCenterline, traceInlay };