inlaytrace 0.3.0 → 0.4.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,4 +1,237 @@
1
- //#region src/shapes.ts
1
+ // src/path.ts
2
+ const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
3
+ const PARAMS = {
4
+ M: 2,
5
+ L: 2,
6
+ H: 1,
7
+ V: 1,
8
+ C: 6,
9
+ S: 4,
10
+ Q: 4,
11
+ T: 2,
12
+ A: 7,
13
+ Z: 0
14
+ };
15
+ const SAME = 1e-6;
16
+ function parsePath(d) {
17
+ const tokens = d.match(TOKEN) ?? [];
18
+ const subs = [];
19
+ let sub = null;
20
+ let cur = {
21
+ x: 0,
22
+ y: 0
23
+ };
24
+ let start = {
25
+ x: 0,
26
+ y: 0
27
+ };
28
+ let lastCubic = null;
29
+ let lastQuad = null;
30
+ let i = 0;
31
+ let cmd = "";
32
+ const begin = (p) => {
33
+ sub = {
34
+ nodes: [{
35
+ x: p.x,
36
+ y: p.y,
37
+ in: null,
38
+ out: null
39
+ }],
40
+ closed: false
41
+ };
42
+ subs.push(sub);
43
+ };
44
+ const ensure = () => {
45
+ if (!sub || sub.closed) begin(cur);
46
+ return sub;
47
+ };
48
+ const lineTo = (p) => {
49
+ ensure().nodes.push({
50
+ x: p.x,
51
+ y: p.y,
52
+ in: null,
53
+ out: null
54
+ });
55
+ cur = p;
56
+ };
57
+ const at = (a, b) => a.x === b.x && a.y === b.y;
58
+ const curveTo = (c1, c2, p) => {
59
+ const s = ensure();
60
+ const prev = s.nodes[s.nodes.length - 1];
61
+ prev.out = at(c1, prev) ? null : c1;
62
+ s.nodes.push({
63
+ x: p.x,
64
+ y: p.y,
65
+ in: at(c2, p) ? null : c2,
66
+ out: null
67
+ });
68
+ cur = p;
69
+ };
70
+ while (i < tokens.length) {
71
+ const t = tokens[i];
72
+ if (/[a-z]/i.test(t)) {
73
+ cmd = t;
74
+ i++;
75
+ if (cmd === "Z" || cmd === "z") {
76
+ if (sub) close(sub);
77
+ cur = start;
78
+ lastCubic = lastQuad = null;
79
+ continue;
80
+ }
81
+ } else if (!cmd) {
82
+ i++;
83
+ continue;
84
+ }
85
+ const upper = cmd.toUpperCase();
86
+ const n = PARAMS[upper];
87
+ if (i + n > tokens.length) break;
88
+ const v = tokens.slice(i, i + n).map(Number);
89
+ if (v.some((x) => !Number.isFinite(x))) break;
90
+ i += n;
91
+ const rel = cmd !== upper;
92
+ const ox = rel ? cur.x : 0;
93
+ const oy = rel ? cur.y : 0;
94
+ let cubic = null;
95
+ let quad = null;
96
+ switch (upper) {
97
+ case "M":
98
+ cur = start = {
99
+ x: v[0] + ox,
100
+ y: v[1] + oy
101
+ };
102
+ begin(cur);
103
+ cmd = rel ? "l" : "L";
104
+ break;
105
+ case "L":
106
+ lineTo({
107
+ x: v[0] + ox,
108
+ y: v[1] + oy
109
+ });
110
+ break;
111
+ case "H":
112
+ lineTo({
113
+ x: v[0] + ox,
114
+ y: cur.y
115
+ });
116
+ break;
117
+ case "V":
118
+ lineTo({
119
+ x: cur.x,
120
+ y: v[0] + oy
121
+ });
122
+ break;
123
+ case "C":
124
+ cubic = {
125
+ x: v[2] + ox,
126
+ y: v[3] + oy
127
+ };
128
+ curveTo({
129
+ x: v[0] + ox,
130
+ y: v[1] + oy
131
+ }, cubic, {
132
+ x: v[4] + ox,
133
+ y: v[5] + oy
134
+ });
135
+ break;
136
+ case "S": {
137
+ const c1 = lastCubic ? {
138
+ x: 2 * cur.x - lastCubic.x,
139
+ y: 2 * cur.y - lastCubic.y
140
+ } : cur;
141
+ cubic = {
142
+ x: v[0] + ox,
143
+ y: v[1] + oy
144
+ };
145
+ curveTo(c1, cubic, {
146
+ x: v[2] + ox,
147
+ y: v[3] + oy
148
+ });
149
+ break;
150
+ }
151
+ case "Q":
152
+ case "T": {
153
+ const q = upper === "Q" ? {
154
+ x: v[0] + ox,
155
+ y: v[1] + oy
156
+ } : lastQuad ? {
157
+ x: 2 * cur.x - lastQuad.x,
158
+ y: 2 * cur.y - lastQuad.y
159
+ } : cur;
160
+ const p = upper === "Q" ? {
161
+ x: v[2] + ox,
162
+ y: v[3] + oy
163
+ } : {
164
+ x: v[0] + ox,
165
+ y: v[1] + oy
166
+ };
167
+ const p0 = cur;
168
+ curveTo({
169
+ x: p0.x + 2 / 3 * (q.x - p0.x),
170
+ y: p0.y + 2 / 3 * (q.y - p0.y)
171
+ }, {
172
+ x: p.x + 2 / 3 * (q.x - p.x),
173
+ y: p.y + 2 / 3 * (q.y - p.y)
174
+ }, p);
175
+ quad = q;
176
+ break;
177
+ }
178
+ case "A": lineTo({
179
+ x: v[5] + ox,
180
+ y: v[6] + oy
181
+ });
182
+ }
183
+ lastCubic = cubic;
184
+ lastQuad = quad;
185
+ }
186
+ return subs;
187
+ }
188
+ function close(sub) {
189
+ if (sub.closed) return;
190
+ sub.closed = true;
191
+ const { nodes } = sub;
192
+ if (nodes.length < 2) return;
193
+ const first = nodes[0];
194
+ const last = nodes[nodes.length - 1];
195
+ if (Math.abs(first.x - last.x) < SAME && Math.abs(first.y - last.y) < SAME) {
196
+ first.in = last.in;
197
+ nodes.pop();
198
+ }
199
+ }
200
+ const num$1 = (n) => {
201
+ const r = Math.round(n * 1e3) / 1e3;
202
+ return Object.is(r, -0) ? "0" : String(r);
203
+ };
204
+ const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
205
+ function segment(a, b) {
206
+ return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
207
+ }
208
+ function serializePath(subs) {
209
+ let d = "";
210
+ for (const s of subs) {
211
+ if (!s.nodes.length) continue;
212
+ d += `M${pt(s.nodes[0])}`;
213
+ for (let i = 1; i < s.nodes.length; i++) d += segment(s.nodes[i - 1], s.nodes[i]);
214
+ if (s.closed) {
215
+ const first = s.nodes[0];
216
+ const last = s.nodes[s.nodes.length - 1];
217
+ if (s.nodes.length > 1 && (last.out || first.in)) d += segment(last, first);
218
+ d += "Z";
219
+ }
220
+ }
221
+ return d;
222
+ }
223
+ function mapPoints(subs, f) {
224
+ const m = (p) => p ? f(p) : null;
225
+ return subs.map((s) => ({
226
+ closed: s.closed,
227
+ nodes: s.nodes.map((n) => ({
228
+ ...f(n),
229
+ in: m(n.in),
230
+ out: m(n.out)
231
+ }))
232
+ }));
233
+ }
234
+ // src/shapes.ts
2
235
  /** How closely an outline must follow a shape: RMS and worst distance, in px, of its pixel-edge midpoints. */
3
236
  const MAX_RMS$1 = .3;
4
237
  const MAX_OFF = .85;
@@ -146,7 +379,7 @@ function roundShape(f, p, mids) {
146
379
  const { u, v } = local(q, f.cx, f.cy, cos, sin);
147
380
  const F = u * u / (a * a) + v * v / (b * b) - 1;
148
381
  const g = 2 * Math.hypot(u / (a * a), v / (b * b));
149
- return g > 1e-12 ? F / g : Infinity;
382
+ return g > 1e-12 ? F / g : 1e400;
150
383
  };
151
384
  if (fits(mids, off)) {
152
385
  const cubics = [
@@ -271,7 +504,7 @@ function withCorners(f, corners, mids) {
271
504
  y: f.cy + R * Math.sin(phase + i * step)
272
505
  }));
273
506
  const off = (q) => {
274
- let best = Infinity;
507
+ let best = 1e400;
275
508
  for (let i = 0; i < k; i++) {
276
509
  const a = vertices[i];
277
510
  const b = vertices[(i + 1) % k];
@@ -288,8 +521,7 @@ function withCorners(f, corners, mids) {
288
521
  cubics: vertices.map((a, i) => lineTo(a, vertices[(i + 1) % k]))
289
522
  };
290
523
  }
291
- //#endregion
292
- //#region src/fit.ts
524
+ // src/fit.ts
293
525
  const R = 6;
294
526
  const END_TRIM = 3;
295
527
  const SMOOTH$1 = 12;
@@ -617,7 +849,7 @@ function along(pts, closed, i, ds) {
617
849
  return pts[k];
618
850
  }
619
851
  /** Px of chain available before (side -1) or after (side 1) sample i. Points are ≈ 1 px apart. */
620
- const room = (n, closed, i, side) => closed ? Infinity : side < 0 ? i : n - 1 - i;
852
+ const room = (n, closed, i, side) => closed ? 1e400 : side < 0 ? i : n - 1 - i;
621
853
  /**
622
854
  * How far the chain turns at sample i over r px each side, in degrees. Near an
623
855
  * open chain's end (a junction, where a peak often sits) it measures over what
@@ -652,7 +884,7 @@ function findCorners(pts, closed, cornerAngle, maxRounding = MAX_ROUNDING) {
652
884
  const half = interior / 2 * Math.PI / 180;
653
885
  const reachOut = 1 / Math.sin(half) - 1;
654
886
  if (!x || dist$2(x, pts[i]) > Math.min(MAX_REACH_OUT, R / 2 + maxRounding * reachOut)) continue;
655
- let d = Infinity;
887
+ let d = 1e400;
656
888
  for (let k = -6; k <= R; k++) {
657
889
  const j = closed ? ((i + k) % n + n) % n : i + k;
658
890
  if (j >= 0 && j < n) d = Math.min(d, dist$2(pts[j], x));
@@ -768,7 +1000,7 @@ function smooth(run, loop, half) {
768
1000
  if (!h || n < 4) return {
769
1001
  flat: run,
770
1002
  true: run,
771
- minRadius: Infinity,
1003
+ minRadius: 1e400,
772
1004
  radius: new Float64Array(n).fill(1e9)
773
1005
  };
774
1006
  const m = loop ? n - 1 : n;
@@ -804,7 +1036,7 @@ function smooth(run, loop, half) {
804
1036
  for (let i = 0; i < m; i++) raw[i] = Math.max(radiusAt(i, r), radiusAt(i, 15));
805
1037
  const allow = new Int32Array(m);
806
1038
  const radius = new Float64Array(loop ? m + 1 : m);
807
- let minRadius = Infinity;
1039
+ let minRadius = 1e400;
808
1040
  for (let i = 0; i < m; i++) {
809
1041
  const win = [];
810
1042
  for (let k = -3; k <= 3; k++) {
@@ -1080,8 +1312,7 @@ function newton(b, p, u) {
1080
1312
  if (Math.abs(den) < 1e-12) return u;
1081
1313
  return Math.min(1, Math.max(0, u - num / den));
1082
1314
  }
1083
- //#endregion
1084
- //#region src/palette.ts
1315
+ // src/palette.ts
1085
1316
  function peakPalette(rgba, maxColors, { minDistance = .07, minShare = .002, minDetail = 5e-4, width, minTint = .02, minFlat = .001 } = {}) {
1086
1317
  const bins = histogram(rgba);
1087
1318
  for (let i = 0; i < rgba.length; i += 4) if (rgba[i + 3] >= 128) bins.add(i);
@@ -1358,7 +1589,7 @@ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
1358
1589
  let moved = false;
1359
1590
  points.forEach((p, i) => {
1360
1591
  let best = 0;
1361
- let bestD = Infinity;
1592
+ let bestD = 1e400;
1362
1593
  centres.forEach((c, j) => {
1363
1594
  const d = distance2(p.lab, c);
1364
1595
  if (d < bestD) {
@@ -1372,304 +1603,70 @@ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
1372
1603
  const sums = centres.map(() => ({
1373
1604
  n: 0,
1374
1605
  l: 0,
1375
- a: 0,
1376
- b: 0
1377
- }));
1378
- points.forEach((p, i) => {
1379
- const s = sums[assign[i]];
1380
- s.n += p.n;
1381
- s.l += p.lab[0] * p.n;
1382
- s.a += p.lab[1] * p.n;
1383
- s.b += p.lab[2] * p.n;
1384
- });
1385
- sums.forEach((s, j) => {
1386
- if (s.n) centres[j] = [
1387
- s.l / s.n,
1388
- s.a / s.n,
1389
- s.b / s.n
1390
- ];
1391
- });
1392
- if (!moved) break;
1393
- }
1394
- const out = centres.map(() => ({
1395
- n: 0,
1396
- r: 0,
1397
- g: 0,
1398
- b: 0
1399
- }));
1400
- points.forEach((p, i) => {
1401
- const o = out[assign[i]];
1402
- o.n += p.n;
1403
- o.r += p.rgb[0] * p.n;
1404
- o.g += p.rgb[1] * p.n;
1405
- o.b += p.rgb[2] * p.n;
1406
- });
1407
- const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
1408
- o.r / o.n,
1409
- o.g / o.n,
1410
- o.b / o.n
1411
- ]));
1412
- return [...new Set(hexes)];
1413
- }
1414
- const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
1415
- const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1416
- const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
1417
- /**
1418
- * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
1419
- * handful of deliberate colours, and a one-pixel eye matters as much as the
1420
- * sky, so nothing is merged or dropped for being rare or close to another.
1421
- * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
1422
- * rarest ones take their nearest kept colour when pixels are labelled.
1423
- */
1424
- function exactPalette(rgba, maxColors) {
1425
- const counts = /* @__PURE__ */ new Map();
1426
- for (let i = 0; i < rgba.length; i += 4) {
1427
- if (rgba[i + 3] < 128) continue;
1428
- const key = rgba[i] << 16 | rgba[i + 1] << 8 | rgba[i + 2];
1429
- counts.set(key, (counts.get(key) ?? 0) + 1);
1430
- }
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")}`);
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
- ];
1439
- //#endregion
1440
- //#region src/path.ts
1441
- const TOKEN = /[MmLlHhVvCcSsQqTtAaZz]|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
1442
- const PARAMS = {
1443
- M: 2,
1444
- L: 2,
1445
- H: 1,
1446
- V: 1,
1447
- C: 6,
1448
- S: 4,
1449
- Q: 4,
1450
- T: 2,
1451
- A: 7,
1452
- Z: 0
1453
- };
1454
- const SAME = 1e-6;
1455
- function parsePath(d) {
1456
- const tokens = d.match(TOKEN) ?? [];
1457
- const subs = [];
1458
- let sub = null;
1459
- let cur = {
1460
- x: 0,
1461
- y: 0
1462
- };
1463
- let start = {
1464
- x: 0,
1465
- y: 0
1466
- };
1467
- let lastCubic = null;
1468
- let lastQuad = null;
1469
- let i = 0;
1470
- let cmd = "";
1471
- const begin = (p) => {
1472
- sub = {
1473
- nodes: [{
1474
- x: p.x,
1475
- y: p.y,
1476
- in: null,
1477
- out: null
1478
- }],
1479
- closed: false
1480
- };
1481
- subs.push(sub);
1482
- };
1483
- const ensure = () => {
1484
- if (!sub || sub.closed) begin(cur);
1485
- return sub;
1486
- };
1487
- const lineTo = (p) => {
1488
- ensure().nodes.push({
1489
- x: p.x,
1490
- y: p.y,
1491
- in: null,
1492
- out: null
1493
- });
1494
- cur = p;
1495
- };
1496
- const at = (a, b) => a.x === b.x && a.y === b.y;
1497
- const curveTo = (c1, c2, p) => {
1498
- const s = ensure();
1499
- const prev = s.nodes[s.nodes.length - 1];
1500
- prev.out = at(c1, prev) ? null : c1;
1501
- s.nodes.push({
1502
- x: p.x,
1503
- y: p.y,
1504
- in: at(c2, p) ? null : c2,
1505
- out: null
1506
- });
1507
- cur = p;
1508
- };
1509
- while (i < tokens.length) {
1510
- const t = tokens[i];
1511
- if (/[a-z]/i.test(t)) {
1512
- cmd = t;
1513
- i++;
1514
- if (cmd === "Z" || cmd === "z") {
1515
- if (sub) close(sub);
1516
- cur = start;
1517
- lastCubic = lastQuad = null;
1518
- continue;
1519
- }
1520
- } else if (!cmd) {
1521
- i++;
1522
- continue;
1523
- }
1524
- const upper = cmd.toUpperCase();
1525
- const n = PARAMS[upper];
1526
- if (i + n > tokens.length) break;
1527
- const v = tokens.slice(i, i + n).map(Number);
1528
- if (v.some((x) => !Number.isFinite(x))) break;
1529
- i += n;
1530
- const rel = cmd !== upper;
1531
- const ox = rel ? cur.x : 0;
1532
- const oy = rel ? cur.y : 0;
1533
- let cubic = null;
1534
- let quad = null;
1535
- switch (upper) {
1536
- case "M":
1537
- cur = start = {
1538
- x: v[0] + ox,
1539
- y: v[1] + oy
1540
- };
1541
- begin(cur);
1542
- cmd = rel ? "l" : "L";
1543
- break;
1544
- case "L":
1545
- lineTo({
1546
- x: v[0] + ox,
1547
- y: v[1] + oy
1548
- });
1549
- break;
1550
- case "H":
1551
- lineTo({
1552
- x: v[0] + ox,
1553
- y: cur.y
1554
- });
1555
- break;
1556
- case "V":
1557
- lineTo({
1558
- x: cur.x,
1559
- y: v[0] + oy
1560
- });
1561
- break;
1562
- case "C":
1563
- cubic = {
1564
- x: v[2] + ox,
1565
- y: v[3] + oy
1566
- };
1567
- curveTo({
1568
- x: v[0] + ox,
1569
- y: v[1] + oy
1570
- }, cubic, {
1571
- x: v[4] + ox,
1572
- y: v[5] + oy
1573
- });
1574
- break;
1575
- case "S": {
1576
- const c1 = lastCubic ? {
1577
- x: 2 * cur.x - lastCubic.x,
1578
- y: 2 * cur.y - lastCubic.y
1579
- } : cur;
1580
- cubic = {
1581
- x: v[0] + ox,
1582
- y: v[1] + oy
1583
- };
1584
- curveTo(c1, cubic, {
1585
- x: v[2] + ox,
1586
- y: v[3] + oy
1587
- });
1588
- break;
1589
- }
1590
- case "Q":
1591
- case "T": {
1592
- const q = upper === "Q" ? {
1593
- x: v[0] + ox,
1594
- y: v[1] + oy
1595
- } : lastQuad ? {
1596
- x: 2 * cur.x - lastQuad.x,
1597
- y: 2 * cur.y - lastQuad.y
1598
- } : cur;
1599
- const p = upper === "Q" ? {
1600
- x: v[2] + ox,
1601
- y: v[3] + oy
1602
- } : {
1603
- x: v[0] + ox,
1604
- y: v[1] + oy
1605
- };
1606
- const p0 = cur;
1607
- curveTo({
1608
- x: p0.x + 2 / 3 * (q.x - p0.x),
1609
- y: p0.y + 2 / 3 * (q.y - p0.y)
1610
- }, {
1611
- x: p.x + 2 / 3 * (q.x - p.x),
1612
- y: p.y + 2 / 3 * (q.y - p.y)
1613
- }, p);
1614
- quad = q;
1615
- break;
1616
- }
1617
- case "A": lineTo({
1618
- x: v[5] + ox,
1619
- y: v[6] + oy
1620
- });
1621
- }
1622
- lastCubic = cubic;
1623
- lastQuad = quad;
1624
- }
1625
- return subs;
1626
- }
1627
- function close(sub) {
1628
- if (sub.closed) return;
1629
- sub.closed = true;
1630
- const { nodes } = sub;
1631
- if (nodes.length < 2) return;
1632
- const first = nodes[0];
1633
- const last = nodes[nodes.length - 1];
1634
- if (Math.abs(first.x - last.x) < SAME && Math.abs(first.y - last.y) < SAME) {
1635
- first.in = last.in;
1636
- nodes.pop();
1637
- }
1638
- }
1639
- const num$1 = (n) => {
1640
- const r = Math.round(n * 1e3) / 1e3;
1641
- return Object.is(r, -0) ? "0" : String(r);
1642
- };
1643
- const pt = (p) => `${num$1(p.x)} ${num$1(p.y)}`;
1644
- function segment(a, b) {
1645
- return a.out || b.in ? `C${pt(a.out ?? a)} ${pt(b.in ?? b)} ${pt(b)}` : `L${pt(b)}`;
1646
- }
1647
- function serializePath(subs) {
1648
- let d = "";
1649
- for (const s of subs) {
1650
- if (!s.nodes.length) continue;
1651
- d += `M${pt(s.nodes[0])}`;
1652
- for (let i = 1; i < s.nodes.length; i++) d += segment(s.nodes[i - 1], s.nodes[i]);
1653
- if (s.closed) {
1654
- const first = s.nodes[0];
1655
- const last = s.nodes[s.nodes.length - 1];
1656
- if (s.nodes.length > 1 && (last.out || first.in)) d += segment(last, first);
1657
- d += "Z";
1658
- }
1606
+ a: 0,
1607
+ b: 0
1608
+ }));
1609
+ points.forEach((p, i) => {
1610
+ const s = sums[assign[i]];
1611
+ s.n += p.n;
1612
+ s.l += p.lab[0] * p.n;
1613
+ s.a += p.lab[1] * p.n;
1614
+ s.b += p.lab[2] * p.n;
1615
+ });
1616
+ sums.forEach((s, j) => {
1617
+ if (s.n) centres[j] = [
1618
+ s.l / s.n,
1619
+ s.a / s.n,
1620
+ s.b / s.n
1621
+ ];
1622
+ });
1623
+ if (!moved) break;
1659
1624
  }
1660
- return d;
1661
- }
1662
- function mapPoints(subs, f) {
1663
- const m = (p) => p ? f(p) : null;
1664
- return subs.map((s) => ({
1665
- closed: s.closed,
1666
- nodes: s.nodes.map((n) => ({
1667
- ...f(n),
1668
- in: m(n.in),
1669
- out: m(n.out)
1670
- }))
1625
+ const out = centres.map(() => ({
1626
+ n: 0,
1627
+ r: 0,
1628
+ g: 0,
1629
+ b: 0
1671
1630
  }));
1631
+ points.forEach((p, i) => {
1632
+ const o = out[assign[i]];
1633
+ o.n += p.n;
1634
+ o.r += p.rgb[0] * p.n;
1635
+ o.g += p.rgb[1] * p.n;
1636
+ o.b += p.rgb[2] * p.n;
1637
+ });
1638
+ const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
1639
+ o.r / o.n,
1640
+ o.g / o.n,
1641
+ o.b / o.n
1642
+ ]));
1643
+ return [...new Set(hexes)];
1644
+ }
1645
+ const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
1646
+ const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
1647
+ const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
1648
+ /**
1649
+ * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
1650
+ * handful of deliberate colours, and a one-pixel eye matters as much as the
1651
+ * sky, so nothing is merged or dropped for being rare or close to another.
1652
+ * Beyond `maxColors` distinct colours (a photo picked as pixel art), the
1653
+ * rarest ones take their nearest kept colour when pixels are labelled.
1654
+ */
1655
+ function exactPalette(rgba, maxColors) {
1656
+ const counts = /* @__PURE__ */ new Map();
1657
+ for (let i = 0; i < rgba.length; i += 4) {
1658
+ if (rgba[i + 3] < 128) continue;
1659
+ const key = rgba[i] << 16 | rgba[i + 1] << 8 | rgba[i + 2];
1660
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1661
+ }
1662
+ 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")}`);
1672
1663
  }
1664
+ /** '#rrggbb' as [r, g, b]. */
1665
+ const hexToRgb = (hex) => [
1666
+ parseInt(hex.slice(1, 3), 16),
1667
+ parseInt(hex.slice(3, 5), 16),
1668
+ parseInt(hex.slice(5, 7), 16)
1669
+ ];
1673
1670
  const sub = (a, b) => ({
1674
1671
  x: a.x - b.x,
1675
1672
  y: a.y - b.y
@@ -1874,8 +1871,7 @@ function complete(p0, t0, p1, t1, visible, straight0, straight1, hidden) {
1874
1871
  }
1875
1872
  return null;
1876
1873
  }
1877
- //#endregion
1878
- //#region src/skeleton.ts
1874
+ // src/skeleton.ts
1879
1875
  /**
1880
1876
  * Skeleton strokes: thin ink to a one-pixel skeleton and fit it as strokes
1881
1877
  * down the middle. Centerline traces a whole drawing this way; outline art
@@ -1961,7 +1957,7 @@ function regionWidths(ink, w, h, comp, m) {
1961
1957
  };
1962
1958
  }
1963
1959
  /** The eight neighbours P2…P9, clockwise from north, as offsets. */
1964
- const DX = [
1960
+ const DX$1 = [
1965
1961
  0,
1966
1962
  1,
1967
1963
  1,
@@ -1971,7 +1967,7 @@ const DX = [
1971
1967
  -1,
1972
1968
  -1
1973
1969
  ];
1974
- const DY = [
1970
+ const DY$1 = [
1975
1971
  -1,
1976
1972
  -1,
1977
1973
  0,
@@ -1984,8 +1980,8 @@ const DY = [
1984
1980
  function neighbours(img, w, h, x, y) {
1985
1981
  const p = [];
1986
1982
  for (let k = 0; k < 8; k++) {
1987
- const nx = x + DX[k];
1988
- const ny = y + DY[k];
1983
+ const nx = x + DX$1[k];
1984
+ const ny = y + DY$1[k];
1989
1985
  p.push(nx >= 0 && nx < w && ny >= 0 && ny < h ? img[ny * w + nx] : 0);
1990
1986
  }
1991
1987
  return p;
@@ -2016,7 +2012,7 @@ function pieces(p) {
2016
2012
  seen[k] = true;
2017
2013
  while (stack.length) {
2018
2014
  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) {
2015
+ for (let b = 0; b < 8; b++) if (p[b] && !seen[b] && Math.abs(DX$1[a] - DX$1[b]) <= 1 && Math.abs(DY$1[a] - DY$1[b]) <= 1) {
2020
2016
  seen[b] = true;
2021
2017
  stack.push(b);
2022
2018
  }
@@ -2055,7 +2051,7 @@ function thin(ink, w, h) {
2055
2051
  img[(y + 1) * W + x + 1] = 1;
2056
2052
  live.push((y + 1) * W + x + 1);
2057
2053
  }
2058
- const off = DX.map((dx, k) => DY[k] * W + dx);
2054
+ const off = DX$1.map((dx, k) => DY$1[k] * W + dx);
2059
2055
  const mask = (i) => {
2060
2056
  let m = 0;
2061
2057
  for (let k = 0; k < 8; k++) if (img[i + off[k]]) m |= 1 << k;
@@ -2093,13 +2089,13 @@ function thin(ink, w, h) {
2093
2089
  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
2090
  return out;
2095
2091
  }
2096
- const degree = (img, w, h, i) => neighbours(img, w, h, i % w, i / w | 0).reduce((s, v) => s + v, 0);
2092
+ const degree$1 = (img, w, h, i) => neighbours(img, w, h, i % w, i / w | 0).reduce((s, v) => s + v, 0);
2097
2093
  /** Remove branches from an end to a junction shorter than `min` pixels, until none are left. */
2098
2094
  function prune(skel, w, h, min) {
2099
2095
  for (let pass = 0; pass < 4; pass++) {
2100
2096
  let removed = false;
2101
2097
  for (let i = 0; i < skel.length; i++) {
2102
- if (!skel[i] || degree(skel, w, h, i) !== 1) continue;
2098
+ if (!skel[i] || degree$1(skel, w, h, i) !== 1) continue;
2103
2099
  const path = [i];
2104
2100
  let prev = -1;
2105
2101
  let cur = i;
@@ -2109,12 +2105,12 @@ function prune(skel, w, h, min) {
2109
2105
  const y = cur / w | 0;
2110
2106
  const next = [];
2111
2107
  for (let k = 0; k < 8; k++) {
2112
- const nx = x + DX[k];
2113
- const ny = y + DY[k];
2108
+ const nx = x + DX$1[k];
2109
+ const ny = y + DY$1[k];
2114
2110
  const j = ny * w + nx;
2115
2111
  if (nx >= 0 && nx < w && ny >= 0 && ny < h && skel[j] && j !== prev && !path.includes(j)) next.push(j);
2116
2112
  }
2117
- if (next.length !== 1 || degree(skel, w, h, next[0]) > 2) {
2113
+ if (next.length !== 1 || degree$1(skel, w, h, next[0]) > 2) {
2118
2114
  atJunction = next.length >= 1;
2119
2115
  break;
2120
2116
  }
@@ -2138,7 +2134,7 @@ function prune(skel, w, h, min) {
2138
2134
  function walk(skel, w, h) {
2139
2135
  const n = w * h;
2140
2136
  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;
2137
+ for (let i = 0; i < n; i++) if (skel[i] && degree$1(skel, w, h, i) !== 2) isNode[i] = 1;
2142
2138
  const group = new Int32Array(n).fill(-1);
2143
2139
  const centres = [];
2144
2140
  for (let i = 0; i < n; i++) {
@@ -2157,10 +2153,10 @@ function walk(skel, w, h) {
2157
2153
  const x = j % w;
2158
2154
  const y = j / w | 0;
2159
2155
  for (let k = 0; k < 8; k++) {
2160
- const nx = x + DX[k];
2161
- const ny = y + DY[k];
2156
+ const nx = x + DX$1[k];
2157
+ const ny = y + DY$1[k];
2162
2158
  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) {
2159
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && isNode[m] && group[m] < 0 && degree$1(skel, w, h, m) > 2 && degree$1(skel, w, h, j) > 2) {
2164
2160
  group[m] = g;
2165
2161
  stack.push(m);
2166
2162
  }
@@ -2189,8 +2185,8 @@ function walk(skel, w, h) {
2189
2185
  5,
2190
2186
  7
2191
2187
  ]) {
2192
- const nx = x + DX[k];
2193
- const ny = y + DY[k];
2188
+ const nx = x + DX$1[k];
2189
+ const ny = y + DY$1[k];
2194
2190
  const j = ny * w + nx;
2195
2191
  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
2192
  }
@@ -2203,8 +2199,8 @@ function walk(skel, w, h) {
2203
2199
  const x = i % w;
2204
2200
  const y = i / w | 0;
2205
2201
  for (let k = 0; k < 8; k++) {
2206
- const nx = x + DX[k];
2207
- const ny = y + DY[k];
2202
+ const nx = x + DX$1[k];
2203
+ const ny = y + DY$1[k];
2208
2204
  const j = ny * w + nx;
2209
2205
  if (nx < 0 || nx >= w || ny < 0 || ny >= h || !skel[j] || used[j]) continue;
2210
2206
  if (isNode[j]) {
@@ -2580,8 +2576,7 @@ function toSubpath$1(cubics, closed) {
2580
2576
  nodes
2581
2577
  };
2582
2578
  }
2583
- //#endregion
2584
- //#region src/gradient.ts
2579
+ // src/gradient.ts
2585
2580
  /**
2586
2581
  * Gradient fills for softly shaded regions.
2587
2582
  *
@@ -2787,8 +2782,6 @@ function shadings(rgba, w, h, comp, regions, colorOf) {
2787
2782
  ]));
2788
2783
  return out;
2789
2784
  }
2790
- /** A gradient's colour at a point. */
2791
- const colorAt = (g, x, y) => ramp(g)(x, y);
2792
2785
  /**
2793
2786
  * Whether the gradient draws any one band of the shade worse than the band's
2794
2787
  * own flat colour did: a gradient that suits the whole on average can still
@@ -2972,9 +2965,9 @@ function fitRadial(xs, ys, cs) {
2972
2965
  * from the least t to the greatest, as few as come within a level of the most.
2973
2966
  * Offsets run 0–1 over [t0, t1]. With `from`, t0 is at least that.
2974
2967
  */
2975
- function fitRamp(t, cs, from = -Infinity) {
2976
- let t0 = Infinity;
2977
- let t1 = -Infinity;
2968
+ function fitRamp(t, cs, from = -1e400) {
2969
+ let t0 = 1e400;
2970
+ let t1 = -1e400;
2978
2971
  for (const tj of t) {
2979
2972
  if (tj < t0) t0 = tj;
2980
2973
  if (tj > t1) t1 = tj;
@@ -3084,8 +3077,290 @@ function leastSquares(rows, y) {
3084
3077
  const clamp = (v) => Math.max(0, Math.min(255, v));
3085
3078
  const dist2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
3086
3079
  const round$1 = (v, places) => Math.round(v * 10 ** places) / 10 ** places;
3087
- //#endregion
3088
- //#region src/inlay.ts
3080
+ // src/gaps.ts
3081
+ /**
3082
+ * Gap closing (#145): join a line's ends across a small break, before tracing,
3083
+ * so a drawn outline that came out in pieces (a lossy save, a faint stretch of
3084
+ * pen, a stroke that stops just short of the one it meets) is one line again,
3085
+ * and a fill inside it stays inside.
3086
+ *
3087
+ * After Fourey, Tschumperlé and Revoy, "A fast and efficient semi-guided
3088
+ * algorithm for flat coloring line-arts" (VMV 2018, GIMP's "Fill by line art
3089
+ * detection"), on the skeleton rather than the ink's border:
3090
+ *
3091
+ * 1. Thin the ink and prune its spurs. Each skeleton end is a line's end; the
3092
+ * way it points is measured a few widths back along it, and so is the
3093
+ * line's own width there (a local width, not the drawing's: GIMP's lesson).
3094
+ * 2. Two ends that point at each other across a gap join. An end that points
3095
+ * at other ink close by reaches it: the T that stops short.
3096
+ * 3. A join crosses one gap only: along it, the ink of the line it starts
3097
+ * from, then paper, then the ink it reaches, and nothing else. The paper it
3098
+ * crosses is at most GAP_WIDTHS times the line's width and GAP_MAX px, so
3099
+ * a gap that's drawn (a dashed line, a box left open on purpose) stays
3100
+ * open.
3101
+ * 4. The best joins (shortest gap) are painted first, as ink the line's own
3102
+ * width; each end joins once.
3103
+ *
3104
+ * Written for this project (MIT).
3105
+ */
3106
+ /** The widest gap closed, in the line's own widths. A drawn gap (dashes, an open box) is wider. */
3107
+ const GAP_WIDTHS = 1.6;
3108
+ /** …but never less than this (px): a hairline's breaks are a pixel or two whatever its width. */
3109
+ const GAP_MIN = 2.5;
3110
+ /**
3111
+ * …and never more (px). A break from a lossy save or a faint stretch of pen
3112
+ * is a few pixels whatever the pen; on a heavy line a gap of a width is
3113
+ * plainly drawn (dashes 8 px wide with 8 px between, a chimney stopping 10 px
3114
+ * short of a roof).
3115
+ */
3116
+ const GAP_MAX = 5.5;
3117
+ /** An end's direction is measured this many of the line's widths back along it (at least END_BACK_MIN px). */
3118
+ const END_BACK = 2.5;
3119
+ const END_BACK_MIN = 4;
3120
+ /** A line shorter than this (px) has no direction to speak of: a dot, a speck. */
3121
+ const END_MIN = 3;
3122
+ /** How straight at the other end a join must point: cos 40°. */
3123
+ const FACING = Math.cos(40 * Math.PI / 180);
3124
+ const DX = [
3125
+ 0,
3126
+ 1,
3127
+ 1,
3128
+ 1,
3129
+ 0,
3130
+ -1,
3131
+ -1,
3132
+ -1
3133
+ ];
3134
+ const DY = [
3135
+ -1,
3136
+ -1,
3137
+ 0,
3138
+ 1,
3139
+ 1,
3140
+ 1,
3141
+ 0,
3142
+ -1
3143
+ ];
3144
+ /**
3145
+ * Close small gaps in `ink` (1 = ink), in place. Returns how many joins were
3146
+ * painted.
3147
+ */
3148
+ function closeGaps(ink, w, h, o = {}) {
3149
+ const k = Math.max(1, o.scale ?? 1);
3150
+ const skel = o.skel ?? thin(ink, w, h);
3151
+ const width = strokeWidthOf(skel, ink, w);
3152
+ prune(skel, w, h, Math.max(3, Math.round(width)));
3153
+ const ends = endsOf(skel, ink, w, h, width);
3154
+ if (!ends.length) return 0;
3155
+ const reachOf = (e) => Math.min(GAP_MAX * k, Math.max(GAP_MIN * k, GAP_WIDTHS * e.width));
3156
+ const cross = (ax, ay, bx, by) => crossing(ink, o.blocked, w, h, ax, ay, bx, by);
3157
+ const joins = [];
3158
+ let widest = 0;
3159
+ for (const e of ends) widest = Math.max(widest, e.width);
3160
+ const cell = Math.ceil(widest + GAP_MAX * k + 2);
3161
+ const grid = /* @__PURE__ */ new Map();
3162
+ const key = (cx, cy) => cy * 65536 + cx;
3163
+ for (const e of ends) {
3164
+ const k = key(Math.floor(e.x / cell), Math.floor(e.y / cell));
3165
+ const list = grid.get(k);
3166
+ if (list) list.push(e);
3167
+ else grid.set(k, [e]);
3168
+ }
3169
+ for (const a of ends) {
3170
+ const cx = Math.floor(a.x / cell);
3171
+ const cy = Math.floor(a.y / cell);
3172
+ for (let gy = cy - 1; gy <= cy + 1; gy++) for (let gx = cx - 1; gx <= cx + 1; gx++) for (const b of grid.get(key(gx, gy)) ?? []) {
3173
+ if (b.i <= a.i) continue;
3174
+ const vx = b.x - a.x;
3175
+ const vy = b.y - a.y;
3176
+ const d = Math.hypot(vx, vy);
3177
+ const reach = Math.min(reachOf(a), reachOf(b));
3178
+ if (d === 0 || d > (a.width + b.width) / 2 + reach + 2) continue;
3179
+ if ((a.dx * vx + a.dy * vy) / d < FACING || -(b.dx * vx + b.dy * vy) / d < FACING) continue;
3180
+ const gap = cross(a.x, a.y, b.x, b.y);
3181
+ if (gap <= 0 || gap > reach) continue;
3182
+ joins.push({
3183
+ a,
3184
+ b,
3185
+ tx: b.x,
3186
+ ty: b.y,
3187
+ gap,
3188
+ width: Math.min(a.width, b.width)
3189
+ });
3190
+ }
3191
+ }
3192
+ for (const a of ends) {
3193
+ const hit = reach(ink, o.blocked, w, h, a, reachOf(a));
3194
+ if (!hit) continue;
3195
+ joins.push({
3196
+ a,
3197
+ b: null,
3198
+ tx: hit.x,
3199
+ ty: hit.y,
3200
+ gap: hit.gap * 1.25,
3201
+ width: a.width
3202
+ });
3203
+ }
3204
+ joins.sort((p, q) => p.gap - q.gap);
3205
+ const used = /* @__PURE__ */ new Set();
3206
+ let painted = 0;
3207
+ for (const j of joins) {
3208
+ if (used.has(j.a.i) || j.b && used.has(j.b.i)) continue;
3209
+ if (cross(j.a.x, j.a.y, j.tx, j.ty) <= 0) continue;
3210
+ used.add(j.a.i);
3211
+ if (j.b) used.add(j.b.i);
3212
+ paint(ink, w, h, j.a.x, j.a.y, j.tx, j.ty, j.width / 2);
3213
+ painted++;
3214
+ }
3215
+ return painted;
3216
+ }
3217
+ /** Each skeleton end of a line long enough to have a direction: where it is, which way it points, and the line's width there. */
3218
+ function endsOf(skel, ink, w, h, width) {
3219
+ const ends = [];
3220
+ const back = Math.max(END_BACK_MIN, Math.round(END_BACK * width));
3221
+ for (let i = 0; i < skel.length; i++) {
3222
+ if (!skel[i]) continue;
3223
+ const x = i % w;
3224
+ const y = i / w | 0;
3225
+ if (degree(skel, w, h, x, y) !== 1) continue;
3226
+ const path = [i];
3227
+ let prev = -1;
3228
+ let cur = i;
3229
+ while (path.length <= back) {
3230
+ const cx = cur % w;
3231
+ const cy = cur / w | 0;
3232
+ const next = [];
3233
+ for (let k = 0; k < 8; k++) {
3234
+ const nx = cx + DX[k];
3235
+ const ny = cy + DY[k];
3236
+ const j = ny * w + nx;
3237
+ if (nx < 0 || nx >= w || ny < 0 || ny >= h || !skel[j] || j === prev || path.includes(j)) continue;
3238
+ next.push(j);
3239
+ }
3240
+ if (next.length === 2 && touch(next[0], next[1], w)) {
3241
+ const diag = (j) => j % w !== cx && (j / w | 0) !== cy;
3242
+ const [on, by] = diag(next[0]) ? [next[0], next[1]] : [next[1], next[0]];
3243
+ path.push(by);
3244
+ next.length = 0;
3245
+ next.push(on);
3246
+ }
3247
+ if (next.length !== 1) break;
3248
+ prev = cur;
3249
+ cur = next[0];
3250
+ path.push(cur);
3251
+ }
3252
+ if (path.length < END_MIN) continue;
3253
+ const bx = cur % w;
3254
+ const by = cur / w | 0;
3255
+ const l = Math.hypot(x - bx, y - by);
3256
+ if (!l) continue;
3257
+ const mid = path[Math.floor(path.length / 2)];
3258
+ ends.push({
3259
+ i,
3260
+ x: x + .5,
3261
+ y: y + .5,
3262
+ dx: (x - bx) / l,
3263
+ dy: (y - by) / l,
3264
+ width: Math.max(1, 2 * radiusAt(ink, w, h, mid % w, mid / w | 0, 2 * width + 2))
3265
+ });
3266
+ }
3267
+ return ends;
3268
+ }
3269
+ const touch = (a, b, w) => Math.abs(a % w - b % w) <= 1 && Math.abs((a / w | 0) - (b / w | 0)) <= 1;
3270
+ function degree(img, w, h, x, y) {
3271
+ let d = 0;
3272
+ for (let k = 0; k < 8; k++) {
3273
+ const nx = x + DX[k];
3274
+ const ny = y + DY[k];
3275
+ if (nx >= 0 && nx < w && ny >= 0 && ny < h && img[ny * w + nx]) d++;
3276
+ }
3277
+ return d;
3278
+ }
3279
+ /** Distance from pixel (x, y)'s centre to the nearest paper, up to `max`: half the line's width there. */
3280
+ function radiusAt(ink, w, h, x, y, max) {
3281
+ let best = max;
3282
+ const r = Math.ceil(max);
3283
+ for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) {
3284
+ const nx = x + dx;
3285
+ const ny = y + dy;
3286
+ if (nx < 0 || nx >= w || ny < 0 || ny >= h || ink[ny * w + nx]) continue;
3287
+ const d = Math.hypot(Math.max(0, Math.abs(dx) - .5), Math.max(0, Math.abs(dy) - .5));
3288
+ if (d < best) best = d;
3289
+ }
3290
+ return best;
3291
+ }
3292
+ /**
3293
+ * Along the segment from (ax, ay) to (bx, by), sampled every half pixel: the
3294
+ * length of paper crossed, when it's ink, then one stretch of paper, then
3295
+ * ink; 0 when it never leaves the ink; -1 when it crosses more than one gap
3296
+ * (another line in between) or ends on paper.
3297
+ */
3298
+ function crossing(ink, blocked, w, h, ax, ay, bx, by) {
3299
+ const d = Math.hypot(bx - ax, by - ay);
3300
+ const steps = Math.max(1, Math.ceil(d * 2));
3301
+ let state = 0;
3302
+ let out = 0;
3303
+ let back = 0;
3304
+ for (let s = 0; s <= steps; s++) {
3305
+ const t = s / steps;
3306
+ const px = Math.floor(ax + (bx - ax) * t);
3307
+ const py = Math.floor(ay + (by - ay) * t);
3308
+ if (px < 0 || px >= w || py < 0 || py >= h || blocked?.[py * w + px]) return -1;
3309
+ const on = ink[py * w + px] === 1;
3310
+ if (state === 0 && !on) {
3311
+ state = 1;
3312
+ out = s;
3313
+ } else if (state === 1 && on) {
3314
+ state = 2;
3315
+ back = s;
3316
+ } else if (state === 2 && !on) return -1;
3317
+ }
3318
+ if (state === 1) return -1;
3319
+ return state === 0 ? 0 : (back - out) * d / steps;
3320
+ }
3321
+ /** Straight on from end `e`: out of its own ink, across paper no wider than `max`, into other ink. */
3322
+ function reach(ink, blocked, w, h, e, max) {
3323
+ const step = .5;
3324
+ let left = false;
3325
+ let gap = 0;
3326
+ for (let t = step; t <= e.width + max + 1; t += step) {
3327
+ const x = e.x + e.dx * t;
3328
+ const y = e.y + e.dy * t;
3329
+ const px = Math.floor(x);
3330
+ const py = Math.floor(y);
3331
+ if (px < 0 || px >= w || py < 0 || py >= h || blocked?.[py * w + px]) return null;
3332
+ const on = ink[py * w + px] === 1;
3333
+ if (!left) {
3334
+ if (!on) left = true;
3335
+ else continue;
3336
+ }
3337
+ if (!on) {
3338
+ gap += step;
3339
+ if (gap > max) return null;
3340
+ continue;
3341
+ }
3342
+ return {
3343
+ x: x + e.dx * Math.min(1, e.width / 2),
3344
+ y: y + e.dy * Math.min(1, e.width / 2),
3345
+ gap
3346
+ };
3347
+ }
3348
+ return null;
3349
+ }
3350
+ /** Ink along the segment, `r` px either side of it (a round-capped stroke). */
3351
+ function paint(ink, w, h, ax, ay, bx, by, r) {
3352
+ const rr = Math.max(.75, r);
3353
+ const vx = bx - ax;
3354
+ const vy = by - ay;
3355
+ const len2 = vx * vx + vy * vy || 1;
3356
+ for (let y = Math.max(0, Math.floor(Math.min(ay, by) - rr)); y <= Math.min(h - 1, Math.ceil(Math.max(ay, by) + rr)); y++) for (let x = Math.max(0, Math.floor(Math.min(ax, bx) - rr)); x <= Math.min(w - 1, Math.ceil(Math.max(ax, bx) + rr)); x++) {
3357
+ const px = x + .5;
3358
+ const py = y + .5;
3359
+ const t = Math.max(0, Math.min(1, ((px - ax) * vx + (py - ay) * vy) / len2));
3360
+ if ((px - ax - vx * t) ** 2 + (py - ay - vy * t) ** 2 <= rr * rr) ink[y * w + x] = 1;
3361
+ }
3362
+ }
3363
+ // src/inlay.ts
3089
3364
  /**
3090
3365
  * Inlay, our shared-edge tracer: every preset, from logos to photos.
3091
3366
  * Like inlaid wood, every piece is cut to fit its neighbours exactly.
@@ -3149,13 +3424,11 @@ function gradientMarkup(g, id) {
3149
3424
  const stops = g.stops.map((s) => `<stop offset="${num(s.offset * 100)}%" stop-color="${attr(s.color)}"/>`).join("");
3150
3425
  return g.type === "linear" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${num(g.x1)}" y1="${num(g.y1)}" x2="${num(g.x2)}" y2="${num(g.y2)}">${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${num(g.cx)}" cy="${num(g.cy)}" r="${num(g.r)}">${stops}</radialGradient>`;
3151
3426
  }
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
3427
  /**
3155
3428
  * Trace RGBA pixels (`w` × `h`, 4 bytes a pixel, as from canvas getImageData)
3156
3429
  * into filled shapes that share their edges exactly.
3157
3430
  */
3158
- function trace(rgba, w, h, o) {
3431
+ function traceRaw(rgba, w, h, o) {
3159
3432
  const { labels, colors, drawn } = o.mode === "palette" ? labelPalette(rgba, w, h, o.palette, !o.photo) : labelBinary(rgba, w, h, o.threshold);
3160
3433
  const clean = o.mode === "palette" && !o.pixels && !o.photo && lossless(rgba, labels, w, h, colors);
3161
3434
  if (o.mode === "palette" && o.merge) mergeLabels(labels, colors, o.merge);
@@ -3163,6 +3436,7 @@ function trace(rgba, w, h, o) {
3163
3436
  if (!o.pixels && !(o.mode === "palette" && o.photo)) joinDiagonals(labels, w, h, rgba, drawn);
3164
3437
  const labs = o.mode === "palette" && !o.photo ? colors.map((c) => c ? oklab(hexToRgb(c)) : null) : void 0;
3165
3438
  mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2, labs);
3439
+ if (o.mode === "binary" && o.closeGaps && closeInkGaps(labels, w, h, o.scale)) mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
3166
3440
  if (labs && !o.pixels) mergeSlivers(labels, w, h, labs, o.lines);
3167
3441
  const lines = o.mode === "palette" && o.strokes && labs && !o.pixels ? strokesOf(rgba, labels, w, h, colors, labs, drawn, o) : [];
3168
3442
  let { comp, compLabel, compArea } = components(labels, w, h, (l) => drawn[l]);
@@ -3672,7 +3946,7 @@ function pairsOf(pal, labs) {
3672
3946
  function mixOf(rgb, lab, pairs, labs, solid) {
3673
3947
  let best;
3674
3948
  let bd = solid;
3675
- let bspan = Infinity;
3949
+ let bspan = 1e400;
3676
3950
  for (const { i, j, a, d, len, span } of pairs) {
3677
3951
  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
3952
  const m = oklab([
@@ -3717,8 +3991,8 @@ function labelPalette(rgba, w, h, palette, flat) {
3717
3991
  b
3718
3992
  ]);
3719
3993
  let best = 0;
3720
- let d1 = Infinity;
3721
- let d2 = Infinity;
3994
+ let d1 = 1e400;
3995
+ let d2 = 1e400;
3722
3996
  labs.forEach((p, k) => {
3723
3997
  const d = Math.hypot(lab[0] - p[0], lab[1] - p[1], lab[2] - p[2]);
3724
3998
  if (d < d1) {
@@ -3727,7 +4001,7 @@ function labelPalette(rgba, w, h, palette, flat) {
3727
4001
  best = k;
3728
4002
  } else if (d < d2) d2 = d;
3729
4003
  });
3730
- const between = d2 < Infinity && d1 > .4 * d2;
4004
+ const between = d2 < 1e400 && d1 > .4 * d2;
3731
4005
  if (between && pairs && d1 > MIX_FAR) best = mixOf([
3732
4006
  r,
3733
4007
  g,
@@ -3749,7 +4023,7 @@ function labelPalette(rgba, w, h, palette, flat) {
3749
4023
  rgba[i * 4 + 2]
3750
4024
  ]);
3751
4025
  let best = -1;
3752
- let bd = Infinity;
4026
+ let bd = 1e400;
3753
4027
  let kinds = 0;
3754
4028
  let seen = -1;
3755
4029
  for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
@@ -3778,6 +4052,14 @@ function labelPalette(rgba, w, h, palette, flat) {
3778
4052
  drawn: [...palette.map(() => true), false]
3779
4053
  };
3780
4054
  }
4055
+ /** Line art's ink is label 0: close its gaps (gaps.ts), the joins becoming ink. Whether anything was joined. */
4056
+ function closeInkGaps(labels, w, h, scale) {
4057
+ const ink = new Uint8Array(w * h);
4058
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
4059
+ if (!closeGaps(ink, w, h, { scale })) return false;
4060
+ for (let i = 0; i < ink.length; i++) if (ink[i]) labels[i] = 0;
4061
+ return true;
4062
+ }
3781
4063
  function labelBinary(rgba, w, h, threshold) {
3782
4064
  const n = w * h;
3783
4065
  const lum = new Uint8Array(n);
@@ -4080,13 +4362,13 @@ function mergeSpecksOnce(labels, w, h, minArea, labs) {
4080
4362
  let most = 0;
4081
4363
  const mine = labs?.[own];
4082
4364
  if (mine) {
4083
- let near = Infinity;
4365
+ let near = 1e400;
4084
4366
  for (const [l, v] of votes) {
4085
4367
  const lab = labs[l];
4086
- const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : Infinity;
4368
+ const d = lab ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : 1e400;
4087
4369
  if (d < near || d === near && v > most) near = d, most = v, best = l;
4088
4370
  }
4089
- if (near > SPECK_CONTRAST && near < Infinity && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
4371
+ if (near > SPECK_CONTRAST && near < 1e400 && end - begin >= Math.max(SPECK_MIN, minArea * SPECK_SHAPE)) continue;
4090
4372
  } else for (const [l, v] of votes) if (v > most) most = v, best = l;
4091
4373
  if (best !== own) {
4092
4374
  for (let k = begin; k < end; k++) labels[pixels[k]] = best;
@@ -4164,7 +4446,7 @@ function mergeSlivers(labels, w, h, labs, lines) {
4164
4446
  let bd = SLIVER_DISTANCE;
4165
4447
  for (const n of near) {
4166
4448
  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;
4449
+ const d = lab && ok(n) ? Math.hypot(lab[0] - mine[0], lab[1] - mine[1], lab[2] - mine[2]) : 1e400;
4168
4450
  if (d < bd) bd = d, best = label[n];
4169
4451
  }
4170
4452
  return best;
@@ -4336,7 +4618,11 @@ function strokesOf(rgba, labels, w, h, colors, labs, drawn, o) {
4336
4618
  }
4337
4619
  if (kept < LINE_SHARE * all) continue;
4338
4620
  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);
4621
+ const { subs, measured } = skeletonStrokes(ink, w, h, o, o.closeGaps && closeGaps(ink, w, h, {
4622
+ scale: k,
4623
+ blocked: line,
4624
+ skel
4625
+ }) > 0 ? void 0 : skel);
4340
4626
  if (!subs.length) continue;
4341
4627
  for (const i of beyondStroke(ink, w, h, subs, measured)) {
4342
4628
  ink[i] = 0;
@@ -4771,8 +5057,65 @@ function toSubpath(cubics) {
4771
5057
  nodes
4772
5058
  };
4773
5059
  }
4774
- //#endregion
4775
- //#region src/smooth.ts
5060
+ // src/centerline.ts
5061
+ /**
5062
+ * Centerline tracing: single strokes down the middle of the ink, for pen
5063
+ * plotters, engravers and handwriting, instead of outlines round it.
5064
+ *
5065
+ * 1. Threshold the image to ink and paper (as line art does), and fold specks
5066
+ * and pinholes into their surroundings so they don't become stray strokes
5067
+ * or little loops.
5068
+ * 2. Thin the ink to a one-pixel skeleton (Zhang and Suen, "A fast parallel
5069
+ * algorithm for thinning digital patterns", CACM 1984).
5070
+ * 3. Measure the stroke width: the ink's area over the skeleton's length.
5071
+ * 4. Prune spurs: short branches that thinning grows from bumps in the
5072
+ * outline, anything shorter than the stroke is wide.
5073
+ * 5. Walk the skeleton into chains between ends and junctions. Where strokes
5074
+ * cross or branch, chains that carry on in the same direction are joined,
5075
+ * so a plotter lifts its pen less.
5076
+ * 6. Fit each chain with the same curve fitter as outlines, and draw it as an
5077
+ * open (or, for a loop, closed) stroke with round caps and joins.
5078
+ *
5079
+ * Everything here is written for this project (MIT); no GPL tracer is used.
5080
+ */
5081
+ /**
5082
+ * Trace to an SVG string; `centerline` gives the strokes as data.
5083
+ * @deprecated Since 0.4: use `toSvg(trace(image, { preset: 'centerline' }))`.
5084
+ */
5085
+ const traceCenterline = (rgba, w, h, o) => toSvg(centerline(rgba, w, h, o));
5086
+ /** @deprecated Since 0.4: `toSvg` draws stroked paths the same way. */
5087
+ const centerlineToSvg = (r) => toSvg(r);
5088
+ const round = (n) => Math.round(n * 100) / 100;
5089
+ function centerline(rgba, w, h, o) {
5090
+ const { labels, drawn } = labelBinary(rgba, w, h, o.threshold);
5091
+ joinDiagonals(labels, w, h, rgba, drawn);
5092
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5093
+ const ink = new Uint8Array(w * h);
5094
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5095
+ const skel = o.closeGaps ? thin(ink, w, h) : void 0;
5096
+ const joined = !!skel && closeGaps(ink, w, h, {
5097
+ scale: o.scale,
5098
+ skel
5099
+ }) > 0;
5100
+ if (joined) {
5101
+ for (let i = 0; i < ink.length; i++) if (ink[i]) labels[i] = 0;
5102
+ mergeSpecks(labels, w, h, Math.max(0, Math.round(o.speckle)) ** 2);
5103
+ for (let i = 0; i < ink.length; i++) ink[i] = labels[i] === 0 ? 1 : 0;
5104
+ }
5105
+ const { subs, measured } = skeletonStrokes(ink, w, h, o, joined ? void 0 : skel);
5106
+ const width = o.strokeWidth && o.strokeWidth > 0 ? o.strokeWidth : measured;
5107
+ return {
5108
+ width: w,
5109
+ height: h,
5110
+ paths: subs.length ? [{
5111
+ d: serializePath(subs),
5112
+ fill: o.color ?? "#000000",
5113
+ stroke: round(width)
5114
+ }] : [],
5115
+ measuredWidth: round(measured)
5116
+ };
5117
+ }
5118
+ // src/smooth.ts
4776
5119
  /**
4777
5120
  * Edge-preserving smoothing for painted art, before its palette is picked.
4778
5121
  *
@@ -4957,56 +5300,214 @@ function boostLines(rgba, width, height, radius = 2, lines) {
4957
5300
  }
4958
5301
  return out;
4959
5302
  }
4960
- //#endregion
4961
- //#region src/centerline.ts
5303
+ // src/presets.ts
4962
5304
  /**
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.
5305
+ * Presets and the one-call API (#162, #163): `trace(image, { preset })`.
4979
5306
  *
4980
- * Everything here is written for this project (MIT); no GPL tracer is used.
5307
+ * Each preset is a recipe the app tuned and `npm run score` measures: how the
5308
+ * palette is picked, what runs before tracing, and the fitting defaults. Any
5309
+ * option given overrides the preset's. The app reads its presets from here,
5310
+ * so the package and the app can't drift apart.
5311
+ */
5312
+ const ILLUSTRATION = {
5313
+ kind: "colour",
5314
+ colors: 24,
5315
+ speckle: 4,
5316
+ tolerance: .75,
5317
+ cornerAngle: 60,
5318
+ shapes: true,
5319
+ layers: true,
5320
+ gradients: true
5321
+ };
5322
+ /** Every preset's defaults, as the app shows them. */
5323
+ const presets = {
5324
+ logo: {
5325
+ kind: "colour",
5326
+ colors: 8,
5327
+ speckle: 8,
5328
+ tolerance: 1,
5329
+ cornerAngle: 45,
5330
+ shapes: true,
5331
+ layers: false
5332
+ },
5333
+ illustration: ILLUSTRATION,
5334
+ outline: {
5335
+ ...ILLUSTRATION,
5336
+ strokes: true,
5337
+ closeGaps: true
5338
+ },
5339
+ lineart: {
5340
+ kind: "ink",
5341
+ threshold: "auto",
5342
+ speckle: 6,
5343
+ tolerance: 1,
5344
+ cornerAngle: 45,
5345
+ shapes: true,
5346
+ closeGaps: true
5347
+ },
5348
+ centerline: {
5349
+ kind: "centerline",
5350
+ threshold: "auto",
5351
+ speckle: 4,
5352
+ tolerance: 1,
5353
+ cornerAngle: 45,
5354
+ closeGaps: true
5355
+ },
5356
+ poster: {
5357
+ kind: "colour",
5358
+ colors: 24,
5359
+ speckle: 8,
5360
+ tolerance: .75,
5361
+ cornerAngle: 90,
5362
+ layers: true
5363
+ },
5364
+ pixel: {
5365
+ kind: "colour",
5366
+ colors: 32,
5367
+ speckle: 0,
5368
+ tolerance: .25,
5369
+ cornerAngle: 0
5370
+ }
5371
+ };
5372
+ const PICKER = {
5373
+ logo: "peak",
5374
+ illustration: "peak",
5375
+ outline: "peak",
5376
+ poster: "quantize",
5377
+ pixel: "exact"
5378
+ };
5379
+ /** Below this share of opaque pixels in its exact colours, an image isn't treated as pixel art. */
5380
+ const EXACT_COVERAGE = .9;
5381
+ /**
5382
+ * The share of opaque pixels whose colour is exactly one of `palette`, not
5383
+ * counting its first (commonest) colour. A JPEG drawing on a white page is
5384
+ * 88% white, so counting the page passed it as pixel art; its other 31
5385
+ * "exact" colours were near-whites, and the blue drawing traced as white.
4981
5386
  */
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`;
5387
+ function coverage(pixels, palette) {
5388
+ const set = new Set(palette.map((hex) => parseInt(hex.slice(1), 16)));
5389
+ const first = palette.length ? parseInt(palette[0].slice(1), 16) : -1;
5390
+ let opaque = 0;
5391
+ let hit = 0;
5392
+ for (let i = 0; i < pixels.length; i += 4) {
5393
+ if (pixels[i + 3] < 128) continue;
5394
+ const c = pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2];
5395
+ if (c === first) continue;
5396
+ opaque++;
5397
+ if (set.has(c)) hit++;
5398
+ }
5399
+ return opaque ? hit / opaque : 1;
4987
5400
  }
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)
5401
+ /**
5402
+ * How wide a painted outline is looked for, by how many times the image was
5403
+ * enlarged: 2 px at its own size (lines up to about 4 px wide), 3 px at 2×.
5404
+ */
5405
+ const outlineRadius = (scale) => Math.min(4, Math.max(2, Math.round(1.5 * scale)));
5406
+ /** The trace for `image` with `options`: a preset's recipe, with any option given in place of its default. */
5407
+ function tracePreset(image, options = {}) {
5408
+ const name = options.preset ?? "logo";
5409
+ const p = Object.hasOwn(presets, name) ? presets[name] : void 0;
5410
+ if (!p) throw new Error(`Unknown preset "${String(name)}". Use one of: ${Object.keys(presets).join(", ")}.`);
5411
+ const { width, height } = image;
5412
+ if (!(width > 0 && height > 0) || image.data.length < width * height * 4) throw new Error(`The image needs ${width} × ${height} × 4 bytes of RGBA, and has ${image.data.length}.`);
5413
+ const o = {
5414
+ ...p,
5415
+ ...defined(options)
5416
+ };
5417
+ const fit = {
5418
+ speckle: o.speckle ?? 0,
5419
+ tolerance: o.tolerance ?? 1,
5420
+ cornerAngle: o.cornerAngle ?? 45,
5421
+ ...o.smoothing !== void 0 ? { smoothing: o.smoothing } : {}
5422
+ };
5423
+ const scale = o.scale ?? 1;
5424
+ let px = image.data;
5425
+ if (p.kind !== "colour") {
5426
+ if (o.invert) {
5427
+ const flipped = Uint8ClampedArray.from(px);
5428
+ for (let i = 0; i < flipped.length; i += 4) for (let k = 0; k < 3; k++) flipped[i + k] = 255 - flipped[i + k];
5429
+ px = flipped;
5430
+ }
5431
+ const threshold = o.threshold === void 0 ? "auto" : o.threshold;
5432
+ if (p.kind === "centerline") return centerline(px, width, height, {
5433
+ ...fit,
5434
+ threshold,
5435
+ closeGaps: !!o.closeGaps,
5436
+ scale,
5437
+ ...o.strokeWidth ? { strokeWidth: o.strokeWidth } : {}
5438
+ });
5439
+ return traceRaw(px, width, height, {
5440
+ ...fit,
5441
+ shapes: !!o.shapes,
5442
+ mode: "binary",
5443
+ threshold,
5444
+ closeGaps: !!o.closeGaps,
5445
+ scale
5446
+ });
5447
+ }
5448
+ if (o.grayscale && name !== "pixel" && !o.palette?.length) px = toGray(px);
5449
+ const lines = o.keepOutlines ? new Uint8Array(width * height) : void 0;
5450
+ if (lines) px = boostLines(px, width, height, outlineRadius(scale), lines);
5451
+ if (o.smoothShading) px = smoothShading(px, width, height, lines);
5452
+ const picker = PICKER[name];
5453
+ const colors = o.colors ?? 8;
5454
+ const own = o.palette?.length ? o.palette : null;
5455
+ let palette = own ?? (picker === "exact" ? exactPalette(px, colors) : picker === "quantize" ? quantizePalette(px, colors) : peakPalette(px, colors, { width }));
5456
+ if (!own && picker === "exact" && coverage(px, palette) < EXACT_COVERAGE) palette = quantizePalette(px, colors);
5457
+ const pixels = name === "pixel";
5458
+ const merge = o.merge && Object.keys(o.merge).length ? { merge: o.merge } : {};
5459
+ const gradients = options.gradients ?? (!!p.gradients && !own && !!o.layers);
5460
+ const raw = {
5461
+ ...fit,
5462
+ mode: "palette",
5463
+ palette,
5464
+ ...merge,
5465
+ shapes: !!o.shapes && !pixels,
5466
+ pixels,
5467
+ stacked: !pixels && !!o.layers,
5468
+ photo: picker === "quantize",
5469
+ strokes: !!o.strokes && !pixels && picker !== "quantize",
5470
+ gradients: gradients && !pixels,
5471
+ closeGaps: !!o.closeGaps,
5472
+ scale,
5473
+ ...lines ? { lines } : {}
5006
5474
  };
5475
+ return traceRaw(px, width, height, raw);
5476
+ }
5477
+ /** sRGB (0–255) of the grey whose OKLab lightness is `l`: for a grey, L is the cube root of its linear light. */
5478
+ const greyOf = (l) => {
5479
+ const y = Math.min(1, Math.max(0, l)) ** 3;
5480
+ return Math.round(255 * (y <= .0031308 ? 12.92 * y : 1.055 * y ** (1 / 2.4) - .055));
5481
+ };
5482
+ /** A copy of the image in greys of each pixel's own OKLab lightness; alpha kept. */
5483
+ function toGray(px) {
5484
+ const out = new Uint8ClampedArray(px.length);
5485
+ const seen = /* @__PURE__ */ new Map();
5486
+ for (let i = 0; i < px.length; i += 4) {
5487
+ const key = px[i] << 16 | px[i + 1] << 8 | px[i + 2];
5488
+ let v = seen.get(key);
5489
+ if (v === void 0) seen.set(key, v = greyOf(oklab([
5490
+ px[i],
5491
+ px[i + 1],
5492
+ px[i + 2]
5493
+ ])[0]));
5494
+ out[i] = out[i + 1] = out[i + 2] = v;
5495
+ out[i + 3] = px[i + 3];
5496
+ }
5497
+ return out;
5498
+ }
5499
+ /** The options given, without the ones explicitly undefined (which would hide a preset's default). */
5500
+ function defined(o) {
5501
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
5502
+ }
5503
+ function trace(a, b, c, d) {
5504
+ if (typeof b === "number") return traceRaw(a, b, c, d);
5505
+ return tracePreset(a, b);
5506
+ }
5507
+ function traceInlay(a, b, c, d) {
5508
+ return toSvg(typeof b === "number" ? traceRaw(a, b, c, d) : tracePreset(a, b));
5007
5509
  }
5008
- //#endregion
5009
- //#region src/symmetry.ts
5510
+ // src/symmetry.ts
5010
5511
  /**
5011
5512
  * Score every candidate symmetry: the best vertical and horizontal mirror axes
5012
5513
  * and the best centre for each rotational order, highest score first. A clean
@@ -5188,5 +5689,4 @@ function detectSymmetry(rgba, w, h, options = {}) {
5188
5689
  });
5189
5690
  return out.sort((a, b) => b.score - a.score);
5190
5691
  }
5191
- //#endregion
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 };
5692
+ export { boostLines, centerline, centerlineToSvg, detectSymmetry, exactPalette, fitChain, isFlat, mapPoints, oklab, parsePath, peakPalette, pointAt, presets, quantizePalette, serializePath, smoothShading, toSvg, trace, traceCenterline, traceInlay };