inlaytrace 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,20 @@
1
1
  # inlaytrace
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 679659c: Photos: `quantizePalette(rgba, n)` picks a photo's colours by k-means in OKLab (deterministic), and the `stacked` option draws each shape whole, larger shapes first, instead of cutting holes (same picture, less path data, no hairline seams). Also fixes speck merging, which could strand fragments of merged specks as new specks: on photos that left thousands of extra shapes, and a larger `speckle` gave more shapes rather than fewer.
8
+
9
+ ## 0.1.1
10
+
11
+ ### Patch Changes
12
+
13
+ - The npm page says the package has no dependencies or install scripts, and that releases carry provenance. No code changes.
14
+
3
15
  ## 0.1.0
4
16
 
5
- First published release: the tracer the [Inlay app](https://mattblack.space/tools/img-to-svg/)
17
+ First published release: the tracer the [Inlay app](https://inlaytrace.com/app/)
6
18
  uses for logos, illustrations, line art and pixel art, built as ESM with type
7
19
  declarations.
8
20
 
package/README.md CHANGED
@@ -9,7 +9,7 @@ curves. Pixel art keeps its exact staircase.
9
9
  Pure TypeScript with no DOM and no WebAssembly: it runs in browsers, Web
10
10
  Workers and Node. MIT licensed.
11
11
 
12
- It is the tracer behind the [Inlay app](https://mattblack.space/tools/img-to-svg/)
12
+ It is the tracer behind the [Inlay app](https://inlaytrace.com/app/)
13
13
  for logos, illustrations, line art and pixel art.
14
14
 
15
15
  ## Install
@@ -19,7 +19,10 @@ npm install inlaytrace
19
19
  ```
20
20
 
21
21
  ESM only, with type declarations. Node 20 or newer, any current browser, and
22
- Web Workers. No dependencies.
22
+ Web Workers. No dependencies and no install scripts. Each release is published
23
+ from this repo's release workflow with
24
+ [provenance](https://docs.npmjs.com/generating-provenance-statements), so npm
25
+ shows which commit built it.
23
26
 
24
27
  Versions are 0.x while the API settles: a minor version (0.1 → 0.2) may change
25
28
  it, and the [changelog](https://github.com/mtblck/inlaytrace/blob/main/packages/inlay/CHANGELOG.md)
@@ -50,6 +53,7 @@ toSvg(result) // '<svg …>…</svg>'
50
53
  | `mode: 'palette', palette` | Flat colour art. `palette` is the colours to label pixels with: `peakPalette(rgba, n)` takes the sharp peaks of the histogram (flat art's real colours); `exactPalette(rgba, n)` takes the image's exact colours, most-used first. |
51
54
  | `mode: 'palette', palette, merge` | Fold colours together before regions are built, so the edge between them disappears: `{ '#from': '#into' }`. |
52
55
  | `mode: 'palette', palette: exactPalette(…), pixels: true` | Pixel art: no clean-up of lone pixels, no curve fitting; every boundary is its pixel staircase with straight runs joined. |
56
+ | `mode: 'palette', palette: quantizePalette(…), stacked: true` | Photos as flat colour bands. `quantizePalette(rgba, n)` clusters the image's colours (k-means in OKLab, deterministic); `stacked` draws each shape whole, larger first, instead of cutting holes. |
53
57
  | `mode: 'binary', threshold` | Line art: ink darker than `threshold` (0–255), or adaptive per neighbourhood when `null`. Only the ink is drawn. |
54
58
 
55
59
  ### Also exported
@@ -93,6 +97,10 @@ nodes for VTracer tracing each colour on its own. At 2048 px it traces in about
93
97
  1.3 s (VTracer: 17.5 s, timed by hand). On pixel art both draw every pixel exactly; Inlay uses
94
98
  about 14% fewer nodes and is about 4× faster on a 1024 px sprite.
95
99
 
100
+ On three photos (quantized palette, stacked), rendered back and compared with
101
+ each photo: a mean error of 11.8 against VTracer's 14.3, with 57% fewer shapes
102
+ and a 30% smaller file.
103
+
96
104
  ## License
97
105
 
98
106
  MIT. Source, issues and the app: [mtblck/inlaytrace](https://github.com/mtblck/inlaytrace).
package/dist/index.d.ts CHANGED
@@ -65,6 +65,17 @@ type InlayOptions = FitOptions & {
65
65
  * joined into single lines.
66
66
  */
67
67
  pixels?: boolean;
68
+ /**
69
+ * Stacked shapes, for photos: each region is drawn whole, without the holes
70
+ * other regions sit in, and larger shapes come first so smaller ones paint
71
+ * over them. Every hole's outline is exactly the outline of what fills it,
72
+ * so the picture is the same as cut-out shapes, with less path data (each
73
+ * hole isn't drawn a second time) and no hairline seams where anti-aliased
74
+ * edges meet. A hole with transparency anywhere inside it, however deep, is
75
+ * kept, so transparency stays transparent. Default: cut out, which is what a
76
+ * vinyl cutter or a screen printer wants.
77
+ */
78
+ stacked?: boolean;
68
79
  } & (
69
80
  /**
70
81
  * `merge` folds colours together before any region is built, so the edge
@@ -134,9 +145,8 @@ export declare function otsu(lum: Uint8Array, alpha: Uint8Array): number;
134
145
  * accepted, and holds a meaningful share of the image.
135
146
  * 3. Stop at the requested count.
136
147
  *
137
- * The result is passed to VTracer as a fixed palette, which it matches in OKLab.
138
- * This is for logos and illustrations; photos have no peaks, so the poster
139
- * preset keeps VTracer's quantizer.
148
+ * This is for logos and illustrations. Photos have no peaks (on a photo the
149
+ * peaks raised mean error from 9.9 to 15.3), so they use `quantizePalette`.
140
150
  */
141
151
  type Rgb = [number, number, number];
142
152
  export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number, { minDistance, minShare }?: {
@@ -144,6 +154,23 @@ export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number,
144
154
  minShare?: number;
145
155
  }): string[];
146
156
  export declare function oklab([r, g, b]: Rgb): Rgb;
157
+ /**
158
+ * A photo's palette: `maxColors` colours that best summarise it, by k-means in
159
+ * OKLab (so the clusters are perceptual, not RGB boxes).
160
+ *
161
+ * It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
162
+ * count, rather than the pixels themselves: the same answer to within a bin,
163
+ * at a fraction of the work. It's deterministic: the first centre is the most
164
+ * common colour, and each next one is the colour farthest from those chosen,
165
+ * weighted by how common it is (k-means++ without the dice), so a photo traces
166
+ * the same way every time. Each colour returned is the true mean of the pixels
167
+ * in its cluster, most common first. `maxColors` is rounded and taken as at
168
+ * least 1 (so 0 or NaN gives one colour); fewer come back when the image has
169
+ * fewer distinct colours, and none when every pixel is transparent.
170
+ */
171
+ export declare function quantizePalette(rgba: ArrayLike<number>, maxColors: number, { iterations }?: {
172
+ iterations?: number;
173
+ }): string[];
147
174
  /**
148
175
  * Pixel art's palette: its colours exactly, most-used first. Pixel art has a
149
176
  * handful of deliberate colours, and a one-pixel eye matters as much as the
package/dist/index.js CHANGED
@@ -671,6 +671,127 @@ function oklab([r, g, b]) {
671
671
  .0259040371 * l + .7827717662 * m - .808675766 * s
672
672
  ];
673
673
  }
674
+ /**
675
+ * A photo's palette: `maxColors` colours that best summarise it, by k-means in
676
+ * OKLab (so the clusters are perceptual, not RGB boxes).
677
+ *
678
+ * It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
679
+ * count, rather than the pixels themselves: the same answer to within a bin,
680
+ * at a fraction of the work. It's deterministic: the first centre is the most
681
+ * common colour, and each next one is the colour farthest from those chosen,
682
+ * weighted by how common it is (k-means++ without the dice), so a photo traces
683
+ * the same way every time. Each colour returned is the true mean of the pixels
684
+ * in its cluster, most common first. `maxColors` is rounded and taken as at
685
+ * least 1 (so 0 or NaN gives one colour); fewer come back when the image has
686
+ * fewer distinct colours, and none when every pixel is transparent.
687
+ */
688
+ function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
689
+ const bins = /* @__PURE__ */ new Map();
690
+ for (let i = 0; i < rgba.length; i += 4) {
691
+ if (rgba[i + 3] < 128) continue;
692
+ const key = rgba[i] >> 3 << 10 | rgba[i + 1] >> 3 << 5 | rgba[i + 2] >> 3;
693
+ const bin = bins.get(key);
694
+ if (bin) {
695
+ bin.n++;
696
+ bin.r += rgba[i];
697
+ bin.g += rgba[i + 1];
698
+ bin.b += rgba[i + 2];
699
+ } else bins.set(key, {
700
+ n: 1,
701
+ r: rgba[i],
702
+ g: rgba[i + 1],
703
+ b: rgba[i + 2]
704
+ });
705
+ }
706
+ const points = [...bins.values()].sort((a, b) => b.n - a.n).map((bin) => {
707
+ const rgb = [
708
+ bin.r / bin.n,
709
+ bin.g / bin.n,
710
+ bin.b / bin.n
711
+ ];
712
+ return {
713
+ n: bin.n,
714
+ rgb,
715
+ lab: oklab(rgb)
716
+ };
717
+ });
718
+ const k = Math.min(Number.isFinite(maxColors) ? Math.max(1, Math.round(maxColors)) : 1, points.length);
719
+ if (!k) return [];
720
+ const centres = [points[0].lab];
721
+ const nearest = points.map((p) => distance2(p.lab, centres[0]));
722
+ while (centres.length < k) {
723
+ let best = 0;
724
+ let bestScore = -1;
725
+ points.forEach((p, i) => {
726
+ const score = p.n * nearest[i];
727
+ if (score > bestScore) {
728
+ bestScore = score;
729
+ best = i;
730
+ }
731
+ });
732
+ if (bestScore <= 0) break;
733
+ centres.push(points[best].lab);
734
+ points.forEach((p, i) => nearest[i] = Math.min(nearest[i], distance2(p.lab, points[best].lab)));
735
+ }
736
+ const assign = new Int32Array(points.length);
737
+ for (let it = 0; it < iterations; it++) {
738
+ let moved = false;
739
+ points.forEach((p, i) => {
740
+ let best = 0;
741
+ let bestD = Infinity;
742
+ centres.forEach((c, j) => {
743
+ const d = distance2(p.lab, c);
744
+ if (d < bestD) {
745
+ bestD = d;
746
+ best = j;
747
+ }
748
+ });
749
+ if (assign[i] !== best || it === 0) moved = true;
750
+ assign[i] = best;
751
+ });
752
+ const sums = centres.map(() => ({
753
+ n: 0,
754
+ l: 0,
755
+ a: 0,
756
+ b: 0
757
+ }));
758
+ points.forEach((p, i) => {
759
+ const s = sums[assign[i]];
760
+ s.n += p.n;
761
+ s.l += p.lab[0] * p.n;
762
+ s.a += p.lab[1] * p.n;
763
+ s.b += p.lab[2] * p.n;
764
+ });
765
+ sums.forEach((s, j) => {
766
+ if (s.n) centres[j] = [
767
+ s.l / s.n,
768
+ s.a / s.n,
769
+ s.b / s.n
770
+ ];
771
+ });
772
+ if (!moved) break;
773
+ }
774
+ const out = centres.map(() => ({
775
+ n: 0,
776
+ r: 0,
777
+ g: 0,
778
+ b: 0
779
+ }));
780
+ points.forEach((p, i) => {
781
+ const o = out[assign[i]];
782
+ o.n += p.n;
783
+ o.r += p.rgb[0] * p.n;
784
+ o.g += p.rgb[1] * p.n;
785
+ o.b += p.rgb[2] * p.n;
786
+ });
787
+ const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
788
+ o.r / o.n,
789
+ o.g / o.n,
790
+ o.b / o.n
791
+ ]));
792
+ return [...new Set(hexes)];
793
+ }
794
+ const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
674
795
  const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
675
796
  const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
676
797
  /**
@@ -926,7 +1047,7 @@ function mapPoints(subs, f) {
926
1047
  //#endregion
927
1048
  //#region src/inlay.ts
928
1049
  /**
929
- * Inlay, our shared-edge tracer: Logo, Illustration, Line art and Pixel art.
1050
+ * Inlay, our shared-edge tracer: every preset, from logos to photos.
930
1051
  * Like inlaid wood, every piece is cut to fit its neighbours exactly.
931
1052
  *
932
1053
  * VTracer traces every colour region on its own, so an edge between two
@@ -950,7 +1071,9 @@ function mapPoints(subs, f) {
950
1071
  *
951
1072
  * Regions are 4-connected, so two pixels touching only at a corner are
952
1073
  * separate shapes, and each region is one <path> (its outline plus its holes,
953
- * wound oppositely so the default nonzero fill rule cuts the holes).
1074
+ * wound oppositely so the default nonzero fill rule cuts the holes). With
1075
+ * `stacked`, a region keeps only its outline (and any holes onto
1076
+ * transparency), and paint order does the rest.
954
1077
  */
955
1078
  const VOID = -1;
956
1079
  /** The trace as an SVG document. */
@@ -985,20 +1108,31 @@ function trace(rgba, w, h, o) {
985
1108
  reversed: true
986
1109
  });
987
1110
  }
988
- const order = [...byComp.keys()].sort((a, b) => compArea[b] - compArea[a]);
989
- const paths = [];
990
- for (const id of order) {
991
- const subs = assemble(byComp.get(id));
992
- if (!subs.length) continue;
993
- paths.push({
994
- d: serializePath(subs),
995
- fill: colors[compLabel[id]]
1111
+ const voids = o.stacked ? voidSeeds(comp, w, h) : [];
1112
+ const shapes = [];
1113
+ for (const [id, chains] of byComp) {
1114
+ let loops = assemble(chains);
1115
+ if (!loops.length) continue;
1116
+ let area = compArea[id];
1117
+ if (o.stacked) {
1118
+ const outer = loops.reduce((a, b) => Math.abs(b.area) > Math.abs(a.area) ? b : a);
1119
+ loops = loops.filter((l) => l === outer || l.touchesVoid || voids.some((p) => encloses(l.pts, p)));
1120
+ area = Math.abs(outer.area);
1121
+ }
1122
+ shapes.push({
1123
+ subs: loops.map((l) => l.sub),
1124
+ fill: colors[compLabel[id]],
1125
+ area
996
1126
  });
997
1127
  }
1128
+ shapes.sort((a, b) => b.area - a.area);
998
1129
  return {
999
1130
  width: w,
1000
1131
  height: h,
1001
- paths
1132
+ paths: shapes.map((x) => ({
1133
+ d: serializePath(x.subs),
1134
+ fill: x.fill
1135
+ }))
1002
1136
  };
1003
1137
  }
1004
1138
  /**
@@ -1324,15 +1458,28 @@ function components(labels, w, h, keep) {
1324
1458
  compArea
1325
1459
  };
1326
1460
  }
1327
- /** Relabel every region smaller than `minArea` with the label it shares the most edge with. Smallest first. */
1461
+ /**
1462
+ * Relabel every region smaller than `minArea` with the label it shares the
1463
+ * most edge with, smallest first, until none is left (at most eight passes).
1464
+ *
1465
+ * One pass isn't enough: when a speck has joined a slightly larger small
1466
+ * region, and that region then joins a third, the speck's pixels keep the
1467
+ * label they took and are stranded as a new speck. On photos that left
1468
+ * thousands of fragments, and a larger `speckle` left more, not fewer.
1469
+ */
1328
1470
  function mergeSpecks(labels, w, h, minArea) {
1329
1471
  if (minArea <= 1) return;
1472
+ for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea)) return;
1473
+ }
1474
+ /** One pass of mergeSpecks; false when there was nothing left to merge. */
1475
+ function mergeSpecksOnce(labels, w, h, minArea) {
1330
1476
  const { comp, compArea } = components(labels, w, h, () => true);
1331
1477
  const small = compArea.map((a, id) => ({
1332
1478
  a,
1333
1479
  id
1334
1480
  })).filter((c) => c.a < minArea);
1335
- if (!small.length) return;
1481
+ if (!small.length) return false;
1482
+ let changed = false;
1336
1483
  const start = new Int32Array(compArea.length + 1);
1337
1484
  for (let i = 0; i < compArea.length; i++) start[i + 1] = start[i] + compArea[i];
1338
1485
  const fill = start.slice(0, compArea.length);
@@ -1358,8 +1505,12 @@ function mergeSpecks(labels, w, h, minArea) {
1358
1505
  let best = own;
1359
1506
  let most = 0;
1360
1507
  for (const [l, v] of votes) if (v > most) most = v, best = l;
1361
- if (best !== own) for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
1508
+ if (best !== own) {
1509
+ for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
1510
+ changed = true;
1511
+ }
1362
1512
  }
1513
+ return changed;
1363
1514
  }
1364
1515
  function findChains(comp, w, h) {
1365
1516
  const C = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? VOID : comp[y * w + x];
@@ -1461,11 +1612,16 @@ const reverse = (cubics) => cubics.map(([a, b, c, d]) => [
1461
1612
  b,
1462
1613
  a
1463
1614
  ]).reverse();
1464
- /** Join a region's chains into closed loops, each walked with the region on its left. */
1615
+ /** The region on the far side of a chain, as this region walks it. */
1616
+ const across = (c) => c.reversed ? c.left : c.right;
1617
+ /**
1618
+ * Join a region's chains into closed loops, each walked with the region on its
1619
+ * left, with each loop's signed area and whether anything across it is VOID.
1620
+ */
1465
1621
  function assemble(chains) {
1466
1622
  const subs = [];
1467
1623
  const open = [];
1468
- for (const c of chains) if (c.closed) subs.push(toSubpath(c.cubics));
1624
+ for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts));
1469
1625
  else open.push(c);
1470
1626
  const start = (c) => c.reversed ? c.to : c.from;
1471
1627
  const end = (c) => c.reversed ? c.from : c.to;
@@ -1482,18 +1638,76 @@ function assemble(chains) {
1482
1638
  for (const first of open) {
1483
1639
  if (used.has(first)) continue;
1484
1640
  const loop = [];
1641
+ const pts = [];
1642
+ let touchesVoid = false;
1485
1643
  let c = first;
1486
1644
  while (c && !used.has(c)) {
1487
1645
  used.add(c);
1488
1646
  loop.push(...c.cubics);
1647
+ pts.push(...c.reversed ? [...c.pts].reverse() : c.pts);
1648
+ if (across(c) === VOID) touchesVoid = true;
1489
1649
  if (end(c) === start(first)) break;
1490
1650
  const into = lastDir(c);
1491
1651
  c = (byStart.get(end(c)) ?? []).filter((n) => !used.has(n)).sort((a, b) => cross(into, firstDir(a)) - cross(into, firstDir(b)))[0];
1492
1652
  }
1493
- if (loop.length) subs.push(toSubpath(loop));
1653
+ if (loop.length) subs.push(loopOf(loop, touchesVoid, pts));
1494
1654
  }
1495
1655
  return subs;
1496
1656
  }
1657
+ /** A loop and its signed area (shoelace over its cubics' end points: enough to rank and orient). */
1658
+ function loopOf(cubics, touchesVoid, pts) {
1659
+ let area = 0;
1660
+ for (const [a, , , d] of cubics) area += a.x * d.y - d.x * a.y;
1661
+ return {
1662
+ sub: toSubpath(cubics),
1663
+ area: area / 2,
1664
+ touchesVoid,
1665
+ pts
1666
+ };
1667
+ }
1668
+ /** One pixel centre from each 4-connected area of VOID (transparent pixels) in the image. */
1669
+ function voidSeeds(comp, w, h) {
1670
+ const seen = new Uint8Array(w * h);
1671
+ const seeds = [];
1672
+ const stack = [];
1673
+ for (let start = 0; start < w * h; start++) {
1674
+ if (comp[start] !== VOID || seen[start]) continue;
1675
+ seeds.push({
1676
+ x: start % w + .5,
1677
+ y: Math.floor(start / w) + .5
1678
+ });
1679
+ seen[start] = 1;
1680
+ stack.push(start);
1681
+ while (stack.length) {
1682
+ const i = stack.pop();
1683
+ const x = i % w;
1684
+ for (const j of [
1685
+ x > 0 ? i - 1 : -1,
1686
+ x < w - 1 ? i + 1 : -1,
1687
+ i - w,
1688
+ i + w
1689
+ ]) if (j >= 0 && j < w * h && comp[j] === VOID && !seen[j]) {
1690
+ seen[j] = 1;
1691
+ stack.push(j);
1692
+ }
1693
+ }
1694
+ }
1695
+ return seeds;
1696
+ }
1697
+ /**
1698
+ * Whether a point is inside a loop's pixel-crack outline (even-odd ray cast).
1699
+ * The outline runs along pixel edges and the point is a pixel centre, so it is
1700
+ * never on the line.
1701
+ */
1702
+ function encloses(pts, p) {
1703
+ let inside = false;
1704
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
1705
+ const a = pts[i];
1706
+ const b = pts[j];
1707
+ if (a.y > p.y !== b.y > p.y && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) inside = !inside;
1708
+ }
1709
+ return inside;
1710
+ }
1497
1711
  const neg = (p) => ({
1498
1712
  x: -p.x,
1499
1713
  y: -p.y
@@ -1531,4 +1745,4 @@ function toSubpath(cubics) {
1531
1745
  };
1532
1746
  }
1533
1747
  //#endregion
1534
- export { exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, serializePath, staircase, toSvg, trace, traceInlay };
1748
+ export { exactPalette, fitChain, isFlat, mapPoints, mergeLabels, oklab, otsu, parsePath, peakPalette, pointAt, quantizePalette, serializePath, staircase, toSvg, trace, traceInlay };
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "inlaytrace",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Trace images into SVG shapes that share their edges exactly: no gaps, no overlaps. Pure TypeScript, no WebAssembly.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Matt Black (https://mattblack.space)",
8
- "homepage": "https://github.com/mtblck/inlaytrace/tree/main/packages/inlay#readme",
8
+ "homepage": "https://inlaytrace.com/docs/package/",
9
9
  "repository": {
10
10
  "type": "git",
11
11
  "url": "git+https://github.com/mtblck/inlaytrace.git",