inlaytrace 0.1.1 → 0.1.3
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 +14 -1
- package/README.md +13 -4
- package/dist/index.d.ts +85 -4
- package/dist/index.js +710 -18
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# inlaytrace
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f71beed: New `shapes` option: a closed outline that is a circle, an ellipse, a rectangle, a rounded rectangle or a regular polygon is drawn as that exact shape instead of fitted curves (on the sample badge, 0.70% → 0.54% wrong pixels). Off by default.
|
|
8
|
+
- 074cc75: `detectSymmetry(rgba, width, height, options?)` finds the likeliest mirror axes (vertical and horizontal) and rotational orders (2–8 by default) in an image, each scored by the share of the drawing that matches its reflection or turn.
|
|
9
|
+
|
|
10
|
+
## 0.1.2
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 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.
|
|
15
|
+
|
|
3
16
|
## 0.1.1
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
|
@@ -8,7 +21,7 @@
|
|
|
8
21
|
|
|
9
22
|
## 0.1.0
|
|
10
23
|
|
|
11
|
-
First published release: the tracer the [Inlay app](https://
|
|
24
|
+
First published release: the tracer the [Inlay app](https://inlaytrace.com/app/)
|
|
12
25
|
uses for logos, illustrations, line art and pixel art, built as ESM with type
|
|
13
26
|
declarations.
|
|
14
27
|
|
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@ 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://
|
|
13
|
-
|
|
12
|
+
It is the tracer behind every preset of the [Inlay app](https://inlaytrace.com/app/),
|
|
13
|
+
from logos and pixel art to photos.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -53,6 +53,7 @@ toSvg(result) // '<svg …>…</svg>'
|
|
|
53
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. |
|
|
54
54
|
| `mode: 'palette', palette, merge` | Fold colours together before regions are built, so the edge between them disappears: `{ '#from': '#into' }`. |
|
|
55
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. |
|
|
56
57
|
| `mode: 'binary', threshold` | Line art: ink darker than `threshold` (0–255), or adaptive per neighbourhood when `null`. Only the ink is drawn. |
|
|
57
58
|
|
|
58
59
|
### Also exported
|
|
@@ -62,6 +63,9 @@ toSvg(result) // '<svg …>…</svg>'
|
|
|
62
63
|
Béziers between them).
|
|
63
64
|
- `parsePath(d)` / `serializePath(subpaths)`: path data as editable nodes with
|
|
64
65
|
absolute handles, and back. Round trips are idempotent after the first pass.
|
|
66
|
+
- `detectSymmetry(rgba, width, height)`: the likeliest mirror axes and
|
|
67
|
+
rotational orders in an image, each scored by how much of the drawing
|
|
68
|
+
matches (the app offers to enforce one at 95% or more).
|
|
65
69
|
- `oklab(rgb)`: the perceptual colour space the palette and labelling use.
|
|
66
70
|
|
|
67
71
|
## How it works
|
|
@@ -91,11 +95,16 @@ every export.
|
|
|
91
95
|
## Measured
|
|
92
96
|
|
|
93
97
|
On a 640 px JPEG of a five-colour badge, scored by rendering at 4× against the
|
|
94
|
-
clean source art: 0.
|
|
95
|
-
|
|
98
|
+
clean source art: 0.54% wrong pixels with 175 nodes with `shapes` on (0.70%
|
|
99
|
+
and 177 without), against 0.85% with 271 nodes for VTracer tracing each colour
|
|
100
|
+
on its own. At 2048 px it traces in about
|
|
96
101
|
1.3 s (VTracer: 17.5 s, timed by hand). On pixel art both draw every pixel exactly; Inlay uses
|
|
97
102
|
about 14% fewer nodes and is about 4× faster on a 1024 px sprite.
|
|
98
103
|
|
|
104
|
+
On three photos (quantized palette, stacked), rendered back and compared with
|
|
105
|
+
each photo: a mean error of 11.8 against VTracer's 14.3, with 57% fewer shapes
|
|
106
|
+
and a 30% smaller file.
|
|
107
|
+
|
|
99
108
|
## License
|
|
100
109
|
|
|
101
110
|
MIT. Source, issues and the app: [mtblck/inlaytrace](https://github.com/mtblck/inlaytrace).
|
package/dist/index.d.ts
CHANGED
|
@@ -42,6 +42,11 @@ type FitOptions = {
|
|
|
42
42
|
cornerAngle: number;
|
|
43
43
|
/** Half-window in px of the smoothing over the pixel staircase (default 12). */
|
|
44
44
|
smoothing?: number;
|
|
45
|
+
/**
|
|
46
|
+
* Draw a closed outline that is a circle, an ellipse, a (rounded) rectangle
|
|
47
|
+
* or a regular polygon as that exact shape (see shapes.ts). Default false.
|
|
48
|
+
*/
|
|
49
|
+
shapes?: boolean;
|
|
45
50
|
};
|
|
46
51
|
/** A cubic Bézier: start, two handles, end. A straight line has handles on the chord. */
|
|
47
52
|
type Cubic = [Pt, Pt, Pt, Pt];
|
|
@@ -65,6 +70,17 @@ type InlayOptions = FitOptions & {
|
|
|
65
70
|
* joined into single lines.
|
|
66
71
|
*/
|
|
67
72
|
pixels?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Stacked shapes, for photos: each region is drawn whole, without the holes
|
|
75
|
+
* other regions sit in, and larger shapes come first so smaller ones paint
|
|
76
|
+
* over them. Every hole's outline is exactly the outline of what fills it,
|
|
77
|
+
* so the picture is the same as cut-out shapes, with less path data (each
|
|
78
|
+
* hole isn't drawn a second time) and no hairline seams where anti-aliased
|
|
79
|
+
* edges meet. A hole with transparency anywhere inside it, however deep, is
|
|
80
|
+
* kept, so transparency stays transparent. Default: cut out, which is what a
|
|
81
|
+
* vinyl cutter or a screen printer wants.
|
|
82
|
+
*/
|
|
83
|
+
stacked?: boolean;
|
|
68
84
|
} & (
|
|
69
85
|
/**
|
|
70
86
|
* `merge` folds colours together before any region is built, so the edge
|
|
@@ -134,9 +150,8 @@ export declare function otsu(lum: Uint8Array, alpha: Uint8Array): number;
|
|
|
134
150
|
* accepted, and holds a meaningful share of the image.
|
|
135
151
|
* 3. Stop at the requested count.
|
|
136
152
|
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
* preset keeps VTracer's quantizer.
|
|
153
|
+
* This is for logos and illustrations. Photos have no peaks (on a photo the
|
|
154
|
+
* peaks raised mean error from 9.9 to 15.3), so they use `quantizePalette`.
|
|
140
155
|
*/
|
|
141
156
|
type Rgb = [number, number, number];
|
|
142
157
|
export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number, { minDistance, minShare }?: {
|
|
@@ -144,6 +159,23 @@ export declare function peakPalette(rgba: ArrayLike<number>, maxColors: number,
|
|
|
144
159
|
minShare?: number;
|
|
145
160
|
}): string[];
|
|
146
161
|
export declare function oklab([r, g, b]: Rgb): Rgb;
|
|
162
|
+
/**
|
|
163
|
+
* A photo's palette: `maxColors` colours that best summarise it, by k-means in
|
|
164
|
+
* OKLab (so the clusters are perceptual, not RGB boxes).
|
|
165
|
+
*
|
|
166
|
+
* It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
|
|
167
|
+
* count, rather than the pixels themselves: the same answer to within a bin,
|
|
168
|
+
* at a fraction of the work. It's deterministic: the first centre is the most
|
|
169
|
+
* common colour, and each next one is the colour farthest from those chosen,
|
|
170
|
+
* weighted by how common it is (k-means++ without the dice), so a photo traces
|
|
171
|
+
* the same way every time. Each colour returned is the true mean of the pixels
|
|
172
|
+
* in its cluster, most common first. `maxColors` is rounded and taken as at
|
|
173
|
+
* least 1 (so 0 or NaN gives one colour); fewer come back when the image has
|
|
174
|
+
* fewer distinct colours, and none when every pixel is transparent.
|
|
175
|
+
*/
|
|
176
|
+
export declare function quantizePalette(rgba: ArrayLike<number>, maxColors: number, { iterations }?: {
|
|
177
|
+
iterations?: number;
|
|
178
|
+
}): string[];
|
|
147
179
|
/**
|
|
148
180
|
* Pixel art's palette: its colours exactly, most-used first. Pixel art has a
|
|
149
181
|
* handful of deliberate colours, and a one-pixel eye matters as much as the
|
|
@@ -153,4 +185,53 @@ export declare function oklab([r, g, b]: Rgb): Rgb;
|
|
|
153
185
|
*/
|
|
154
186
|
export declare function exactPalette(rgba: ArrayLike<number>, maxColors: number): string[];
|
|
155
187
|
//#endregion
|
|
156
|
-
|
|
188
|
+
//#region src/symmetry.d.ts
|
|
189
|
+
/**
|
|
190
|
+
* Symmetry: find a likely mirror axis or rotational order in a raster.
|
|
191
|
+
*
|
|
192
|
+
* Works on the image, not the trace, so the answer doesn't depend on the trace
|
|
193
|
+
* settings. The foreground is every opaque pixel that differs from the
|
|
194
|
+
* background (the most common colour around the border, or transparency). A
|
|
195
|
+
* symmetric drawing's foreground centroid lies on its mirror axis or at its
|
|
196
|
+
* centre of rotation, so only candidates near the centroid are scored, each by
|
|
197
|
+
* the share of pixels (foreground on either side) whose reflection or rotation
|
|
198
|
+
* has the same colour. A coarse pass over a sample of pixels picks the
|
|
199
|
+
* candidates; a finer one settles them.
|
|
200
|
+
*/
|
|
201
|
+
type MirrorSymmetry = {
|
|
202
|
+
kind: 'mirror';
|
|
203
|
+
/** A vertical axis splits left from right; a horizontal one top from bottom. */
|
|
204
|
+
orientation: 'vertical' | 'horizontal';
|
|
205
|
+
/** x of a vertical axis or y of a horizontal one, in pixels, to the nearest 0.5. */
|
|
206
|
+
position: number;
|
|
207
|
+
/** The share of the drawing that matches its reflection, 0–1. */
|
|
208
|
+
score: number;
|
|
209
|
+
};
|
|
210
|
+
type RotationalSymmetry = {
|
|
211
|
+
kind: 'rotation';
|
|
212
|
+
/** How many times the drawing repeats in a full turn (2 is a half turn). */
|
|
213
|
+
order: number;
|
|
214
|
+
/** The centre of rotation, in pixels. */
|
|
215
|
+
cx: number;
|
|
216
|
+
cy: number;
|
|
217
|
+
/** The share of the drawing that matches itself turned by 1/order, 0–1. */
|
|
218
|
+
score: number;
|
|
219
|
+
};
|
|
220
|
+
type Symmetry = MirrorSymmetry | RotationalSymmetry;
|
|
221
|
+
type SymmetryOptions = {
|
|
222
|
+
/** RGB distance (0–441) under which two pixels count as the same colour. Default 60. */
|
|
223
|
+
tolerance?: number;
|
|
224
|
+
/** Rotational orders to try. Default 2–8. */
|
|
225
|
+
orders?: number[];
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* Score every candidate symmetry: the best vertical and horizontal mirror axes
|
|
229
|
+
* and the best centre for each rotational order, highest score first. A clean
|
|
230
|
+
* symmetric drawing scores close to 1; around 0.95 is a reasonable bar for
|
|
231
|
+
* "likely", since JPEG noise and anti-aliasing never match exactly. A round
|
|
232
|
+
* drawing scores well for every order. Returns `[]` for an image with almost
|
|
233
|
+
* no foreground.
|
|
234
|
+
*/
|
|
235
|
+
export declare function detectSymmetry(rgba: ArrayLike<number>, w: number, h: number, options?: SymmetryOptions): Symmetry[];
|
|
236
|
+
//#endregion
|
|
237
|
+
export type { Cubic, FitOptions, InlayOptions, InlayPath, InlayResult, MirrorSymmetry, PathNode, Pt, Rgb, RotationalSymmetry, Subpath, Symmetry, SymmetryOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,294 @@
|
|
|
1
|
+
//#region src/shapes.ts
|
|
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;
|
|
4
|
+
const MAX_OFF = .85;
|
|
5
|
+
/** An ellipse whose axes differ by less than this is drawn as a circle. */
|
|
6
|
+
const ROUND = .015;
|
|
7
|
+
const KAPPA = .5522847498307936;
|
|
8
|
+
/** Area, centroid and central second moments (per unit area) of a closed polygon. */
|
|
9
|
+
function moments(pts) {
|
|
10
|
+
let a = 0;
|
|
11
|
+
let sx = 0;
|
|
12
|
+
let sy = 0;
|
|
13
|
+
let sxx = 0;
|
|
14
|
+
let syy = 0;
|
|
15
|
+
let sxy = 0;
|
|
16
|
+
for (let i = 0; i < pts.length; i++) {
|
|
17
|
+
const p = pts[i];
|
|
18
|
+
const q = pts[(i + 1) % pts.length];
|
|
19
|
+
const c = p.x * q.y - q.x * p.y;
|
|
20
|
+
a += c;
|
|
21
|
+
sx += (p.x + q.x) * c;
|
|
22
|
+
sy += (p.y + q.y) * c;
|
|
23
|
+
sxx += (p.x * p.x + p.x * q.x + q.x * q.x) * c;
|
|
24
|
+
syy += (p.y * p.y + p.y * q.y + q.y * q.y) * c;
|
|
25
|
+
sxy += (p.x * q.y + 2 * p.x * p.y + 2 * q.x * q.y + q.x * p.y) * c;
|
|
26
|
+
}
|
|
27
|
+
a /= 2;
|
|
28
|
+
if (Math.abs(a) < 1) return null;
|
|
29
|
+
const cx = sx / (6 * a);
|
|
30
|
+
const cy = sy / (6 * a);
|
|
31
|
+
return {
|
|
32
|
+
cx,
|
|
33
|
+
cy,
|
|
34
|
+
area: Math.abs(a),
|
|
35
|
+
m20: sxx / (12 * a) - cx * cx,
|
|
36
|
+
m02: syy / (12 * a) - cy * cy,
|
|
37
|
+
m11: sxy / (24 * a) - cx * cy
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** The principal axes: the larger and smaller variance and the angle of the larger. */
|
|
41
|
+
function principal(f) {
|
|
42
|
+
const d = Math.hypot((f.m20 - f.m02) / 2, f.m11);
|
|
43
|
+
const mid = (f.m20 + f.m02) / 2;
|
|
44
|
+
return {
|
|
45
|
+
big: mid + d,
|
|
46
|
+
small: mid - d,
|
|
47
|
+
angle: .5 * Math.atan2(2 * f.m11, f.m20 - f.m02)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The midpoint of every unit pixel edge of a crack outline: within ~0.35 px of the true edge. */
|
|
51
|
+
function midpoints(pts) {
|
|
52
|
+
const out = [];
|
|
53
|
+
for (let i = 0; i < pts.length; i++) {
|
|
54
|
+
const a = pts[i];
|
|
55
|
+
const b = pts[(i + 1) % pts.length];
|
|
56
|
+
const n = Math.max(1, Math.round(Math.hypot(b.x - a.x, b.y - a.y)));
|
|
57
|
+
for (let s = 0; s < n; s++) out.push({
|
|
58
|
+
x: a.x + (b.x - a.x) * (s + .5) / n,
|
|
59
|
+
y: a.y + (b.y - a.y) * (s + .5) / n
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** Whether every point is close to a shape, given its distance function. */
|
|
65
|
+
function fits(points, distance) {
|
|
66
|
+
let sum = 0;
|
|
67
|
+
for (const p of points) {
|
|
68
|
+
const d = Math.abs(distance(p));
|
|
69
|
+
if (d > MAX_OFF) return false;
|
|
70
|
+
sum += d * d;
|
|
71
|
+
}
|
|
72
|
+
return Math.sqrt(sum / points.length) <= MAX_RMS;
|
|
73
|
+
}
|
|
74
|
+
/** Into a frame centred on (cx, cy) and turned by `angle`. */
|
|
75
|
+
const local = (p, cx, cy, cos, sin) => {
|
|
76
|
+
const dx = p.x - cx;
|
|
77
|
+
const dy = p.y - cy;
|
|
78
|
+
return {
|
|
79
|
+
u: dx * cos + dy * sin,
|
|
80
|
+
v: -dx * sin + dy * cos
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
const world = (u, v, cx, cy, cos, sin) => ({
|
|
84
|
+
x: cx + u * cos - v * sin,
|
|
85
|
+
y: cy + u * sin + v * cos
|
|
86
|
+
});
|
|
87
|
+
const lineTo = (a, b) => [
|
|
88
|
+
a,
|
|
89
|
+
{
|
|
90
|
+
x: a.x + (b.x - a.x) / 3,
|
|
91
|
+
y: a.y + (b.y - a.y) / 3
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
x: a.x + (b.x - a.x) * 2 / 3,
|
|
95
|
+
y: a.y + (b.y - a.y) * 2 / 3
|
|
96
|
+
},
|
|
97
|
+
b
|
|
98
|
+
];
|
|
99
|
+
/** A quarter arc of an axis-aligned ellipse in the local frame, from angle t to t + 90°. */
|
|
100
|
+
function quarter(cx, cy, cos, sin, a, b, ox, oy, t) {
|
|
101
|
+
const c0 = Math.cos(t);
|
|
102
|
+
const s0 = Math.sin(t);
|
|
103
|
+
const c1 = Math.cos(t + Math.PI / 2);
|
|
104
|
+
const s1 = Math.sin(t + Math.PI / 2);
|
|
105
|
+
const p = (u, v) => world(ox + u, oy + v, cx, cy, cos, sin);
|
|
106
|
+
return [
|
|
107
|
+
p(a * c0, b * s0),
|
|
108
|
+
p(a * c0 - KAPPA * a * s0, b * s0 + KAPPA * b * c0),
|
|
109
|
+
p(a * c1 + KAPPA * a * s1, b * s1 - KAPPA * b * c1),
|
|
110
|
+
p(a * c1, b * s1)
|
|
111
|
+
];
|
|
112
|
+
}
|
|
113
|
+
const signedArea = (cubics) => cubics.reduce((s, [a, , , d]) => s + a.x * d.y - d.x * a.y, 0);
|
|
114
|
+
const reversed = (cubics) => cubics.map(([a, b, c, d]) => [
|
|
115
|
+
d,
|
|
116
|
+
c,
|
|
117
|
+
b,
|
|
118
|
+
a
|
|
119
|
+
]).reverse();
|
|
120
|
+
/**
|
|
121
|
+
* The exact shape a closed crack outline is, if it is one, as cubics running
|
|
122
|
+
* the same way round as the outline; otherwise null. `corners` are the corner
|
|
123
|
+
* points the fitter found on it (a polygon's vertices; usually none for a round shape).
|
|
124
|
+
*/
|
|
125
|
+
function fitShape(pts, corners) {
|
|
126
|
+
const f = moments(pts);
|
|
127
|
+
if (!f) return null;
|
|
128
|
+
const mids = midpoints(pts);
|
|
129
|
+
const p = principal(f);
|
|
130
|
+
const shape = (corners.length >= 3 ? withCorners(f, corners, mids) : null) ?? roundShape(f, p, mids);
|
|
131
|
+
if (!shape) return null;
|
|
132
|
+
let area = 0;
|
|
133
|
+
for (let i = 0; i < pts.length; i++) area += pts[i].x * pts[(i + 1) % pts.length].y - pts[(i + 1) % pts.length].x * pts[i].y;
|
|
134
|
+
if (Math.sign(signedArea(shape.cubics)) !== Math.sign(area)) shape.cubics = reversed(shape.cubics);
|
|
135
|
+
return shape;
|
|
136
|
+
}
|
|
137
|
+
function roundShape(f, p, mids) {
|
|
138
|
+
const cos = Math.cos(p.angle);
|
|
139
|
+
const sin = Math.sin(p.angle);
|
|
140
|
+
let a = 2 * Math.sqrt(Math.max(0, p.big));
|
|
141
|
+
let b = 2 * Math.sqrt(Math.max(0, p.small));
|
|
142
|
+
if (b >= 2.5) {
|
|
143
|
+
const circle = (a - b) / a < ROUND;
|
|
144
|
+
if (circle) a = b = Math.sqrt(f.area / Math.PI);
|
|
145
|
+
const off = (q) => {
|
|
146
|
+
const { u, v } = local(q, f.cx, f.cy, cos, sin);
|
|
147
|
+
const F = u * u / (a * a) + v * v / (b * b) - 1;
|
|
148
|
+
const g = 2 * Math.hypot(u / (a * a), v / (b * b));
|
|
149
|
+
return g > 1e-12 ? F / g : Infinity;
|
|
150
|
+
};
|
|
151
|
+
if (fits(mids, off)) {
|
|
152
|
+
const cubics = [
|
|
153
|
+
0,
|
|
154
|
+
1,
|
|
155
|
+
2,
|
|
156
|
+
3
|
|
157
|
+
].map((k) => quarter(f.cx, f.cy, cos, sin, a, b, 0, 0, k * Math.PI / 2));
|
|
158
|
+
return {
|
|
159
|
+
kind: circle ? "circle" : "ellipse",
|
|
160
|
+
cubics
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
let hw = 0;
|
|
165
|
+
let hh = 0;
|
|
166
|
+
for (const q of mids) {
|
|
167
|
+
const { u, v } = local(q, f.cx, f.cy, cos, sin);
|
|
168
|
+
hw = Math.max(hw, Math.abs(u));
|
|
169
|
+
hh = Math.max(hh, Math.abs(v));
|
|
170
|
+
}
|
|
171
|
+
const lost = 4 * hw * hh - f.area;
|
|
172
|
+
if (lost <= 0) return null;
|
|
173
|
+
const r = Math.sqrt(lost / (4 - Math.PI));
|
|
174
|
+
if (r < 1.5 || hw - r < 1.5 || hh - r < 1.5) return null;
|
|
175
|
+
const off = (q) => {
|
|
176
|
+
const { u, v } = local(q, f.cx, f.cy, cos, sin);
|
|
177
|
+
const qx = Math.abs(u) - (hw - r);
|
|
178
|
+
const qy = Math.abs(v) - (hh - r);
|
|
179
|
+
return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
|
|
180
|
+
};
|
|
181
|
+
if (!fits(mids, off)) return null;
|
|
182
|
+
const at = (u, v) => world(u, v, f.cx, f.cy, cos, sin);
|
|
183
|
+
const iw = hw - r;
|
|
184
|
+
const ih = hh - r;
|
|
185
|
+
const cubics = [];
|
|
186
|
+
[
|
|
187
|
+
[
|
|
188
|
+
iw,
|
|
189
|
+
ih,
|
|
190
|
+
0
|
|
191
|
+
],
|
|
192
|
+
[
|
|
193
|
+
-iw,
|
|
194
|
+
ih,
|
|
195
|
+
Math.PI / 2
|
|
196
|
+
],
|
|
197
|
+
[
|
|
198
|
+
-iw,
|
|
199
|
+
-ih,
|
|
200
|
+
Math.PI
|
|
201
|
+
],
|
|
202
|
+
[
|
|
203
|
+
iw,
|
|
204
|
+
-ih,
|
|
205
|
+
3 * Math.PI / 2
|
|
206
|
+
]
|
|
207
|
+
].forEach(([ox, oy, t], k) => {
|
|
208
|
+
const arc = quarter(f.cx, f.cy, cos, sin, r, r, ox, oy, t);
|
|
209
|
+
if (k === 0) cubics.push(lineTo(at(hw, -ih), arc[0]));
|
|
210
|
+
else cubics.push(lineTo(cubics[cubics.length - 1][3], arc[0]));
|
|
211
|
+
cubics.push(arc);
|
|
212
|
+
});
|
|
213
|
+
return {
|
|
214
|
+
kind: "rounded-rectangle",
|
|
215
|
+
cubics
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function withCorners(f, corners, mids) {
|
|
219
|
+
const k = corners.length;
|
|
220
|
+
if (k < 3 || k > 12) return null;
|
|
221
|
+
const angles = corners.map((c) => Math.atan2(c.y - f.cy, c.x - f.cx));
|
|
222
|
+
if (k === 4) {
|
|
223
|
+
let sx = 0;
|
|
224
|
+
let sy = 0;
|
|
225
|
+
for (let i = 0; i < 4; i++) {
|
|
226
|
+
const a = corners[i];
|
|
227
|
+
const b = corners[(i + 1) % 4];
|
|
228
|
+
const t = 4 * Math.atan2(b.y - a.y, b.x - a.x);
|
|
229
|
+
sx += Math.cos(t);
|
|
230
|
+
sy += Math.sin(t);
|
|
231
|
+
}
|
|
232
|
+
const angle = Math.atan2(sy, sx) / 4;
|
|
233
|
+
const cos = Math.cos(angle);
|
|
234
|
+
const sin = Math.sin(angle);
|
|
235
|
+
const vu = f.m20 * cos * cos + 2 * f.m11 * cos * sin + f.m02 * sin * sin;
|
|
236
|
+
const vv = f.m20 * sin * sin - 2 * f.m11 * cos * sin + f.m02 * cos * cos;
|
|
237
|
+
const hw = Math.sqrt(3 * vu);
|
|
238
|
+
const hh = Math.sqrt(3 * vv);
|
|
239
|
+
if (hw < 1.5 || hh < 1.5) return null;
|
|
240
|
+
const off = (q) => {
|
|
241
|
+
const { u, v } = local(q, f.cx, f.cy, cos, sin);
|
|
242
|
+
const qx = Math.abs(u) - hw;
|
|
243
|
+
const qy = Math.abs(v) - hh;
|
|
244
|
+
return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0);
|
|
245
|
+
};
|
|
246
|
+
if (!fits(mids, off)) return null;
|
|
247
|
+
const c = [
|
|
248
|
+
world(hw, -hh, f.cx, f.cy, cos, sin),
|
|
249
|
+
world(hw, hh, f.cx, f.cy, cos, sin),
|
|
250
|
+
world(-hw, hh, f.cx, f.cy, cos, sin),
|
|
251
|
+
world(-hw, -hh, f.cx, f.cy, cos, sin)
|
|
252
|
+
];
|
|
253
|
+
return {
|
|
254
|
+
kind: "rectangle",
|
|
255
|
+
cubics: c.map((a, i) => lineTo(a, c[(i + 1) % 4]))
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
const step = 2 * Math.PI / k;
|
|
259
|
+
const R = Math.sqrt(2 * f.area / (k * Math.sin(step)));
|
|
260
|
+
if (R < 4) return null;
|
|
261
|
+
for (const c of corners) if (Math.abs(Math.hypot(c.x - f.cx, c.y - f.cy) - R) > Math.max(1, .04 * R)) return null;
|
|
262
|
+
let sx = 0;
|
|
263
|
+
let sy = 0;
|
|
264
|
+
for (const a of angles) {
|
|
265
|
+
sx += Math.cos(a * k);
|
|
266
|
+
sy += Math.sin(a * k);
|
|
267
|
+
}
|
|
268
|
+
const phase = Math.atan2(sy, sx) / k;
|
|
269
|
+
const vertices = Array.from({ length: k }, (_, i) => ({
|
|
270
|
+
x: f.cx + R * Math.cos(phase + i * step),
|
|
271
|
+
y: f.cy + R * Math.sin(phase + i * step)
|
|
272
|
+
}));
|
|
273
|
+
const off = (q) => {
|
|
274
|
+
let best = Infinity;
|
|
275
|
+
for (let i = 0; i < k; i++) {
|
|
276
|
+
const a = vertices[i];
|
|
277
|
+
const b = vertices[(i + 1) % k];
|
|
278
|
+
const dx = b.x - a.x;
|
|
279
|
+
const dy = b.y - a.y;
|
|
280
|
+
const t = Math.max(0, Math.min(1, ((q.x - a.x) * dx + (q.y - a.y) * dy) / (dx * dx + dy * dy)));
|
|
281
|
+
best = Math.min(best, Math.hypot(q.x - a.x - t * dx, q.y - a.y - t * dy));
|
|
282
|
+
}
|
|
283
|
+
return best;
|
|
284
|
+
};
|
|
285
|
+
if (!fits(mids, off)) return null;
|
|
286
|
+
return {
|
|
287
|
+
kind: "polygon",
|
|
288
|
+
cubics: vertices.map((a, i) => lineTo(a, vertices[(i + 1) % k]))
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
//#endregion
|
|
1
292
|
//#region src/fit.ts
|
|
2
293
|
const R = 6;
|
|
3
294
|
const END_TRIM = 3;
|
|
@@ -59,6 +350,10 @@ function fitChain(points, closed, o) {
|
|
|
59
350
|
if (n < 2) return [];
|
|
60
351
|
if (!closed && n === 2) return [line(pts[0], pts[1])];
|
|
61
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);
|
|
353
|
+
if (closed && o.shapes) {
|
|
354
|
+
const shape = fitShape(points, corners.map((c) => c.at));
|
|
355
|
+
if (shape) return shape.cubics;
|
|
356
|
+
}
|
|
62
357
|
if (closed && corners.length === 0) {
|
|
63
358
|
if (n < 4) return polygon(pts, true);
|
|
64
359
|
let smoothed = smooth([...pts, pts[0]], true, o.smoothing ?? SMOOTH);
|
|
@@ -671,6 +966,127 @@ function oklab([r, g, b]) {
|
|
|
671
966
|
.0259040371 * l + .7827717662 * m - .808675766 * s
|
|
672
967
|
];
|
|
673
968
|
}
|
|
969
|
+
/**
|
|
970
|
+
* A photo's palette: `maxColors` colours that best summarise it, by k-means in
|
|
971
|
+
* OKLab (so the clusters are perceptual, not RGB boxes).
|
|
972
|
+
*
|
|
973
|
+
* It clusters a 5-bit-per-channel histogram, each bin weighted by its pixel
|
|
974
|
+
* count, rather than the pixels themselves: the same answer to within a bin,
|
|
975
|
+
* at a fraction of the work. It's deterministic: the first centre is the most
|
|
976
|
+
* common colour, and each next one is the colour farthest from those chosen,
|
|
977
|
+
* weighted by how common it is (k-means++ without the dice), so a photo traces
|
|
978
|
+
* the same way every time. Each colour returned is the true mean of the pixels
|
|
979
|
+
* in its cluster, most common first. `maxColors` is rounded and taken as at
|
|
980
|
+
* least 1 (so 0 or NaN gives one colour); fewer come back when the image has
|
|
981
|
+
* fewer distinct colours, and none when every pixel is transparent.
|
|
982
|
+
*/
|
|
983
|
+
function quantizePalette(rgba, maxColors, { iterations = 16 } = {}) {
|
|
984
|
+
const bins = /* @__PURE__ */ new Map();
|
|
985
|
+
for (let i = 0; i < rgba.length; i += 4) {
|
|
986
|
+
if (rgba[i + 3] < 128) continue;
|
|
987
|
+
const key = rgba[i] >> 3 << 10 | rgba[i + 1] >> 3 << 5 | rgba[i + 2] >> 3;
|
|
988
|
+
const bin = bins.get(key);
|
|
989
|
+
if (bin) {
|
|
990
|
+
bin.n++;
|
|
991
|
+
bin.r += rgba[i];
|
|
992
|
+
bin.g += rgba[i + 1];
|
|
993
|
+
bin.b += rgba[i + 2];
|
|
994
|
+
} else bins.set(key, {
|
|
995
|
+
n: 1,
|
|
996
|
+
r: rgba[i],
|
|
997
|
+
g: rgba[i + 1],
|
|
998
|
+
b: rgba[i + 2]
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
const points = [...bins.values()].sort((a, b) => b.n - a.n).map((bin) => {
|
|
1002
|
+
const rgb = [
|
|
1003
|
+
bin.r / bin.n,
|
|
1004
|
+
bin.g / bin.n,
|
|
1005
|
+
bin.b / bin.n
|
|
1006
|
+
];
|
|
1007
|
+
return {
|
|
1008
|
+
n: bin.n,
|
|
1009
|
+
rgb,
|
|
1010
|
+
lab: oklab(rgb)
|
|
1011
|
+
};
|
|
1012
|
+
});
|
|
1013
|
+
const k = Math.min(Number.isFinite(maxColors) ? Math.max(1, Math.round(maxColors)) : 1, points.length);
|
|
1014
|
+
if (!k) return [];
|
|
1015
|
+
const centres = [points[0].lab];
|
|
1016
|
+
const nearest = points.map((p) => distance2(p.lab, centres[0]));
|
|
1017
|
+
while (centres.length < k) {
|
|
1018
|
+
let best = 0;
|
|
1019
|
+
let bestScore = -1;
|
|
1020
|
+
points.forEach((p, i) => {
|
|
1021
|
+
const score = p.n * nearest[i];
|
|
1022
|
+
if (score > bestScore) {
|
|
1023
|
+
bestScore = score;
|
|
1024
|
+
best = i;
|
|
1025
|
+
}
|
|
1026
|
+
});
|
|
1027
|
+
if (bestScore <= 0) break;
|
|
1028
|
+
centres.push(points[best].lab);
|
|
1029
|
+
points.forEach((p, i) => nearest[i] = Math.min(nearest[i], distance2(p.lab, points[best].lab)));
|
|
1030
|
+
}
|
|
1031
|
+
const assign = new Int32Array(points.length);
|
|
1032
|
+
for (let it = 0; it < iterations; it++) {
|
|
1033
|
+
let moved = false;
|
|
1034
|
+
points.forEach((p, i) => {
|
|
1035
|
+
let best = 0;
|
|
1036
|
+
let bestD = Infinity;
|
|
1037
|
+
centres.forEach((c, j) => {
|
|
1038
|
+
const d = distance2(p.lab, c);
|
|
1039
|
+
if (d < bestD) {
|
|
1040
|
+
bestD = d;
|
|
1041
|
+
best = j;
|
|
1042
|
+
}
|
|
1043
|
+
});
|
|
1044
|
+
if (assign[i] !== best || it === 0) moved = true;
|
|
1045
|
+
assign[i] = best;
|
|
1046
|
+
});
|
|
1047
|
+
const sums = centres.map(() => ({
|
|
1048
|
+
n: 0,
|
|
1049
|
+
l: 0,
|
|
1050
|
+
a: 0,
|
|
1051
|
+
b: 0
|
|
1052
|
+
}));
|
|
1053
|
+
points.forEach((p, i) => {
|
|
1054
|
+
const s = sums[assign[i]];
|
|
1055
|
+
s.n += p.n;
|
|
1056
|
+
s.l += p.lab[0] * p.n;
|
|
1057
|
+
s.a += p.lab[1] * p.n;
|
|
1058
|
+
s.b += p.lab[2] * p.n;
|
|
1059
|
+
});
|
|
1060
|
+
sums.forEach((s, j) => {
|
|
1061
|
+
if (s.n) centres[j] = [
|
|
1062
|
+
s.l / s.n,
|
|
1063
|
+
s.a / s.n,
|
|
1064
|
+
s.b / s.n
|
|
1065
|
+
];
|
|
1066
|
+
});
|
|
1067
|
+
if (!moved) break;
|
|
1068
|
+
}
|
|
1069
|
+
const out = centres.map(() => ({
|
|
1070
|
+
n: 0,
|
|
1071
|
+
r: 0,
|
|
1072
|
+
g: 0,
|
|
1073
|
+
b: 0
|
|
1074
|
+
}));
|
|
1075
|
+
points.forEach((p, i) => {
|
|
1076
|
+
const o = out[assign[i]];
|
|
1077
|
+
o.n += p.n;
|
|
1078
|
+
o.r += p.rgb[0] * p.n;
|
|
1079
|
+
o.g += p.rgb[1] * p.n;
|
|
1080
|
+
o.b += p.rgb[2] * p.n;
|
|
1081
|
+
});
|
|
1082
|
+
const hexes = out.filter((o) => o.n).sort((a, b) => b.n - a.n).map((o) => toHex([
|
|
1083
|
+
o.r / o.n,
|
|
1084
|
+
o.g / o.n,
|
|
1085
|
+
o.b / o.n
|
|
1086
|
+
]));
|
|
1087
|
+
return [...new Set(hexes)];
|
|
1088
|
+
}
|
|
1089
|
+
const distance2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
|
|
674
1090
|
const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
675
1091
|
const toHex = (rgb) => `#${rgb.map((c) => Math.round(c).toString(16).padStart(2, "0")).join("")}`;
|
|
676
1092
|
/**
|
|
@@ -926,7 +1342,7 @@ function mapPoints(subs, f) {
|
|
|
926
1342
|
//#endregion
|
|
927
1343
|
//#region src/inlay.ts
|
|
928
1344
|
/**
|
|
929
|
-
* Inlay, our shared-edge tracer:
|
|
1345
|
+
* Inlay, our shared-edge tracer: every preset, from logos to photos.
|
|
930
1346
|
* Like inlaid wood, every piece is cut to fit its neighbours exactly.
|
|
931
1347
|
*
|
|
932
1348
|
* VTracer traces every colour region on its own, so an edge between two
|
|
@@ -950,7 +1366,9 @@ function mapPoints(subs, f) {
|
|
|
950
1366
|
*
|
|
951
1367
|
* Regions are 4-connected, so two pixels touching only at a corner are
|
|
952
1368
|
* 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).
|
|
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.
|
|
954
1372
|
*/
|
|
955
1373
|
const VOID = -1;
|
|
956
1374
|
/** The trace as an SVG document. */
|
|
@@ -985,20 +1403,31 @@ function trace(rgba, w, h, o) {
|
|
|
985
1403
|
reversed: true
|
|
986
1404
|
});
|
|
987
1405
|
}
|
|
988
|
-
const
|
|
989
|
-
const
|
|
990
|
-
for (const id of
|
|
991
|
-
|
|
992
|
-
if (!
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
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
|
|
996
1421
|
});
|
|
997
1422
|
}
|
|
1423
|
+
shapes.sort((a, b) => b.area - a.area);
|
|
998
1424
|
return {
|
|
999
1425
|
width: w,
|
|
1000
1426
|
height: h,
|
|
1001
|
-
paths
|
|
1427
|
+
paths: shapes.map((x) => ({
|
|
1428
|
+
d: serializePath(x.subs),
|
|
1429
|
+
fill: x.fill
|
|
1430
|
+
}))
|
|
1002
1431
|
};
|
|
1003
1432
|
}
|
|
1004
1433
|
/**
|
|
@@ -1324,15 +1753,28 @@ function components(labels, w, h, keep) {
|
|
|
1324
1753
|
compArea
|
|
1325
1754
|
};
|
|
1326
1755
|
}
|
|
1327
|
-
/**
|
|
1756
|
+
/**
|
|
1757
|
+
* Relabel every region smaller than `minArea` with the label it shares the
|
|
1758
|
+
* most edge with, smallest first, until none is left (at most eight passes).
|
|
1759
|
+
*
|
|
1760
|
+
* One pass isn't enough: when a speck has joined a slightly larger small
|
|
1761
|
+
* region, and that region then joins a third, the speck's pixels keep the
|
|
1762
|
+
* label they took and are stranded as a new speck. On photos that left
|
|
1763
|
+
* thousands of fragments, and a larger `speckle` left more, not fewer.
|
|
1764
|
+
*/
|
|
1328
1765
|
function mergeSpecks(labels, w, h, minArea) {
|
|
1329
1766
|
if (minArea <= 1) return;
|
|
1767
|
+
for (let pass = 0; pass < 8; pass++) if (!mergeSpecksOnce(labels, w, h, minArea)) return;
|
|
1768
|
+
}
|
|
1769
|
+
/** One pass of mergeSpecks; false when there was nothing left to merge. */
|
|
1770
|
+
function mergeSpecksOnce(labels, w, h, minArea) {
|
|
1330
1771
|
const { comp, compArea } = components(labels, w, h, () => true);
|
|
1331
1772
|
const small = compArea.map((a, id) => ({
|
|
1332
1773
|
a,
|
|
1333
1774
|
id
|
|
1334
1775
|
})).filter((c) => c.a < minArea);
|
|
1335
|
-
if (!small.length) return;
|
|
1776
|
+
if (!small.length) return false;
|
|
1777
|
+
let changed = false;
|
|
1336
1778
|
const start = new Int32Array(compArea.length + 1);
|
|
1337
1779
|
for (let i = 0; i < compArea.length; i++) start[i + 1] = start[i] + compArea[i];
|
|
1338
1780
|
const fill = start.slice(0, compArea.length);
|
|
@@ -1358,8 +1800,12 @@ function mergeSpecks(labels, w, h, minArea) {
|
|
|
1358
1800
|
let best = own;
|
|
1359
1801
|
let most = 0;
|
|
1360
1802
|
for (const [l, v] of votes) if (v > most) most = v, best = l;
|
|
1361
|
-
if (best !== own)
|
|
1803
|
+
if (best !== own) {
|
|
1804
|
+
for (let k = start[id]; k < start[id + 1]; k++) labels[pixels[k]] = best;
|
|
1805
|
+
changed = true;
|
|
1806
|
+
}
|
|
1362
1807
|
}
|
|
1808
|
+
return changed;
|
|
1363
1809
|
}
|
|
1364
1810
|
function findChains(comp, w, h) {
|
|
1365
1811
|
const C = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? VOID : comp[y * w + x];
|
|
@@ -1461,11 +1907,16 @@ const reverse = (cubics) => cubics.map(([a, b, c, d]) => [
|
|
|
1461
1907
|
b,
|
|
1462
1908
|
a
|
|
1463
1909
|
]).reverse();
|
|
1464
|
-
/**
|
|
1910
|
+
/** The region on the far side of a chain, as this region walks it. */
|
|
1911
|
+
const across = (c) => c.reversed ? c.left : c.right;
|
|
1912
|
+
/**
|
|
1913
|
+
* Join a region's chains into closed loops, each walked with the region on its
|
|
1914
|
+
* left, with each loop's signed area and whether anything across it is VOID.
|
|
1915
|
+
*/
|
|
1465
1916
|
function assemble(chains) {
|
|
1466
1917
|
const subs = [];
|
|
1467
1918
|
const open = [];
|
|
1468
|
-
for (const c of chains) if (c.closed) subs.push(
|
|
1919
|
+
for (const c of chains) if (c.closed) subs.push(loopOf(c.cubics, across(c) === VOID, c.pts));
|
|
1469
1920
|
else open.push(c);
|
|
1470
1921
|
const start = (c) => c.reversed ? c.to : c.from;
|
|
1471
1922
|
const end = (c) => c.reversed ? c.from : c.to;
|
|
@@ -1482,18 +1933,76 @@ function assemble(chains) {
|
|
|
1482
1933
|
for (const first of open) {
|
|
1483
1934
|
if (used.has(first)) continue;
|
|
1484
1935
|
const loop = [];
|
|
1936
|
+
const pts = [];
|
|
1937
|
+
let touchesVoid = false;
|
|
1485
1938
|
let c = first;
|
|
1486
1939
|
while (c && !used.has(c)) {
|
|
1487
1940
|
used.add(c);
|
|
1488
1941
|
loop.push(...c.cubics);
|
|
1942
|
+
pts.push(...c.reversed ? [...c.pts].reverse() : c.pts);
|
|
1943
|
+
if (across(c) === VOID) touchesVoid = true;
|
|
1489
1944
|
if (end(c) === start(first)) break;
|
|
1490
1945
|
const into = lastDir(c);
|
|
1491
1946
|
c = (byStart.get(end(c)) ?? []).filter((n) => !used.has(n)).sort((a, b) => cross(into, firstDir(a)) - cross(into, firstDir(b)))[0];
|
|
1492
1947
|
}
|
|
1493
|
-
if (loop.length) subs.push(
|
|
1948
|
+
if (loop.length) subs.push(loopOf(loop, touchesVoid, pts));
|
|
1494
1949
|
}
|
|
1495
1950
|
return subs;
|
|
1496
1951
|
}
|
|
1952
|
+
/** A loop and its signed area (shoelace over its cubics' end points: enough to rank and orient). */
|
|
1953
|
+
function loopOf(cubics, touchesVoid, pts) {
|
|
1954
|
+
let area = 0;
|
|
1955
|
+
for (const [a, , , d] of cubics) area += a.x * d.y - d.x * a.y;
|
|
1956
|
+
return {
|
|
1957
|
+
sub: toSubpath(cubics),
|
|
1958
|
+
area: area / 2,
|
|
1959
|
+
touchesVoid,
|
|
1960
|
+
pts
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
/** One pixel centre from each 4-connected area of VOID (transparent pixels) in the image. */
|
|
1964
|
+
function voidSeeds(comp, w, h) {
|
|
1965
|
+
const seen = new Uint8Array(w * h);
|
|
1966
|
+
const seeds = [];
|
|
1967
|
+
const stack = [];
|
|
1968
|
+
for (let start = 0; start < w * h; start++) {
|
|
1969
|
+
if (comp[start] !== VOID || seen[start]) continue;
|
|
1970
|
+
seeds.push({
|
|
1971
|
+
x: start % w + .5,
|
|
1972
|
+
y: Math.floor(start / w) + .5
|
|
1973
|
+
});
|
|
1974
|
+
seen[start] = 1;
|
|
1975
|
+
stack.push(start);
|
|
1976
|
+
while (stack.length) {
|
|
1977
|
+
const i = stack.pop();
|
|
1978
|
+
const x = i % w;
|
|
1979
|
+
for (const j of [
|
|
1980
|
+
x > 0 ? i - 1 : -1,
|
|
1981
|
+
x < w - 1 ? i + 1 : -1,
|
|
1982
|
+
i - w,
|
|
1983
|
+
i + w
|
|
1984
|
+
]) if (j >= 0 && j < w * h && comp[j] === VOID && !seen[j]) {
|
|
1985
|
+
seen[j] = 1;
|
|
1986
|
+
stack.push(j);
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
return seeds;
|
|
1991
|
+
}
|
|
1992
|
+
/**
|
|
1993
|
+
* Whether a point is inside a loop's pixel-crack outline (even-odd ray cast).
|
|
1994
|
+
* The outline runs along pixel edges and the point is a pixel centre, so it is
|
|
1995
|
+
* never on the line.
|
|
1996
|
+
*/
|
|
1997
|
+
function encloses(pts, p) {
|
|
1998
|
+
let inside = false;
|
|
1999
|
+
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
|
|
2000
|
+
const a = pts[i];
|
|
2001
|
+
const b = pts[j];
|
|
2002
|
+
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;
|
|
2003
|
+
}
|
|
2004
|
+
return inside;
|
|
2005
|
+
}
|
|
1497
2006
|
const neg = (p) => ({
|
|
1498
2007
|
x: -p.x,
|
|
1499
2008
|
y: -p.y
|
|
@@ -1531,4 +2040,187 @@ function toSubpath(cubics) {
|
|
|
1531
2040
|
};
|
|
1532
2041
|
}
|
|
1533
2042
|
//#endregion
|
|
1534
|
-
|
|
2043
|
+
//#region src/symmetry.ts
|
|
2044
|
+
/**
|
|
2045
|
+
* Score every candidate symmetry: the best vertical and horizontal mirror axes
|
|
2046
|
+
* and the best centre for each rotational order, highest score first. A clean
|
|
2047
|
+
* symmetric drawing scores close to 1; around 0.95 is a reasonable bar for
|
|
2048
|
+
* "likely", since JPEG noise and anti-aliasing never match exactly. A round
|
|
2049
|
+
* drawing scores well for every order. Returns `[]` for an image with almost
|
|
2050
|
+
* no foreground.
|
|
2051
|
+
*/
|
|
2052
|
+
function detectSymmetry(rgba, w, h, options = {}) {
|
|
2053
|
+
const tol2 = (options.tolerance ?? 60) ** 2;
|
|
2054
|
+
const orders = options.orders ?? [
|
|
2055
|
+
2,
|
|
2056
|
+
3,
|
|
2057
|
+
4,
|
|
2058
|
+
5,
|
|
2059
|
+
6,
|
|
2060
|
+
7,
|
|
2061
|
+
8
|
|
2062
|
+
];
|
|
2063
|
+
const n = w * h;
|
|
2064
|
+
if (!n) return [];
|
|
2065
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2066
|
+
const border = (i) => {
|
|
2067
|
+
const o = i * 4;
|
|
2068
|
+
const key = rgba[o + 3] < 128 ? -1 : rgba[o] >> 3 << 10 | rgba[o + 1] >> 3 << 5 | rgba[o + 2] >> 3;
|
|
2069
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
2070
|
+
};
|
|
2071
|
+
for (let x = 0; x < w; x++) {
|
|
2072
|
+
border(x);
|
|
2073
|
+
border((h - 1) * w + x);
|
|
2074
|
+
}
|
|
2075
|
+
for (let y = 0; y < h; y++) {
|
|
2076
|
+
border(y * w);
|
|
2077
|
+
border(y * w + w - 1);
|
|
2078
|
+
}
|
|
2079
|
+
let bgKey = -1;
|
|
2080
|
+
let most = -1;
|
|
2081
|
+
for (const [k, c] of counts) if (c > most) {
|
|
2082
|
+
most = c;
|
|
2083
|
+
bgKey = k;
|
|
2084
|
+
}
|
|
2085
|
+
const bg = bgKey < 0 ? null : [
|
|
2086
|
+
(bgKey >> 10 & 31) * 8 + 4,
|
|
2087
|
+
(bgKey >> 5 & 31) * 8 + 4,
|
|
2088
|
+
(bgKey & 31) * 8 + 4
|
|
2089
|
+
];
|
|
2090
|
+
const fg = new Uint8Array(n);
|
|
2091
|
+
let sx = 0;
|
|
2092
|
+
let sy = 0;
|
|
2093
|
+
let count = 0;
|
|
2094
|
+
for (let i = 0; i < n; i++) {
|
|
2095
|
+
const o = i * 4;
|
|
2096
|
+
if (rgba[o + 3] < 128) continue;
|
|
2097
|
+
if (bg) {
|
|
2098
|
+
const dr = rgba[o] - bg[0];
|
|
2099
|
+
const dg = rgba[o + 1] - bg[1];
|
|
2100
|
+
const db = rgba[o + 2] - bg[2];
|
|
2101
|
+
if (dr * dr + dg * dg + db * db < tol2) continue;
|
|
2102
|
+
}
|
|
2103
|
+
fg[i] = 1;
|
|
2104
|
+
sx += i % w;
|
|
2105
|
+
sy += i / w | 0;
|
|
2106
|
+
count++;
|
|
2107
|
+
}
|
|
2108
|
+
if (count < 16) return [];
|
|
2109
|
+
const cx = sx / count + .5;
|
|
2110
|
+
const cy = sy / count + .5;
|
|
2111
|
+
const same = (i, j) => {
|
|
2112
|
+
if (fg[i] !== fg[j]) return false;
|
|
2113
|
+
if (!fg[i]) return true;
|
|
2114
|
+
const a = i * 4;
|
|
2115
|
+
const b = j * 4;
|
|
2116
|
+
const dr = rgba[a] - rgba[b];
|
|
2117
|
+
const dg = rgba[a + 1] - rgba[b + 1];
|
|
2118
|
+
const db = rgba[a + 2] - rgba[b + 2];
|
|
2119
|
+
return dr * dr + dg * dg + db * db < tol2;
|
|
2120
|
+
};
|
|
2121
|
+
/** The share of sampled pixels that match their image under `map` (-1: off the picture). */
|
|
2122
|
+
const score = (map, step) => {
|
|
2123
|
+
let match = 0;
|
|
2124
|
+
let total = 0;
|
|
2125
|
+
for (let y = 0; y < h; y += step) for (let x = 0; x < w; x += step) {
|
|
2126
|
+
const i = y * w + x;
|
|
2127
|
+
const j = map(x, y);
|
|
2128
|
+
if (j < 0) {
|
|
2129
|
+
if (fg[i]) total++;
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
if (!fg[i] && !fg[j]) continue;
|
|
2133
|
+
total++;
|
|
2134
|
+
if (same(i, j)) match++;
|
|
2135
|
+
}
|
|
2136
|
+
return total ? match / total : 0;
|
|
2137
|
+
};
|
|
2138
|
+
const coarse = Math.max(1, Math.round(Math.sqrt(n / 4e4)));
|
|
2139
|
+
const fine = Math.max(1, Math.round(Math.sqrt(n / 1e5)));
|
|
2140
|
+
const mirror = (orientation, a) => orientation === "vertical" ? (x, y) => {
|
|
2141
|
+
const m = 2 * a - x - 1;
|
|
2142
|
+
return m >= 0 && m < w ? y * w + m : -1;
|
|
2143
|
+
} : (x, y) => {
|
|
2144
|
+
const m = 2 * a - y - 1;
|
|
2145
|
+
return m >= 0 && m < h ? m * w + x : -1;
|
|
2146
|
+
};
|
|
2147
|
+
const rotation = (order, ox, oy) => {
|
|
2148
|
+
const t = 2 * Math.PI / order;
|
|
2149
|
+
const cos = Math.cos(t);
|
|
2150
|
+
const sin = Math.sin(t);
|
|
2151
|
+
return (x, y) => {
|
|
2152
|
+
const px = x + .5 - ox;
|
|
2153
|
+
const py = y + .5 - oy;
|
|
2154
|
+
const rx = Math.floor(ox + px * cos - py * sin);
|
|
2155
|
+
const ry = Math.floor(oy + px * sin + py * cos);
|
|
2156
|
+
return rx >= 0 && rx < w && ry >= 0 && ry < h ? ry * w + rx : -1;
|
|
2157
|
+
};
|
|
2158
|
+
};
|
|
2159
|
+
/** Coarse-score the candidates, then re-score the best few finely. */
|
|
2160
|
+
const best = (candidates, map) => {
|
|
2161
|
+
for (const c of candidates) c.score = score(map(c), coarse);
|
|
2162
|
+
const top = [...candidates].sort((a, b) => b.score - a.score).slice(0, 3);
|
|
2163
|
+
if (fine !== coarse) for (const c of top) c.score = score(map(c), fine);
|
|
2164
|
+
return top.sort((a, b) => b.score - a.score)[0];
|
|
2165
|
+
};
|
|
2166
|
+
const out = [];
|
|
2167
|
+
const reach = Math.max(4, Math.round(Math.min(w, h) / 100));
|
|
2168
|
+
for (const orientation of ["vertical", "horizontal"]) {
|
|
2169
|
+
const centre = Math.round((orientation === "vertical" ? cx : cy) * 2) / 2;
|
|
2170
|
+
const candidates = [];
|
|
2171
|
+
for (let d = -reach; d <= reach; d += .5) candidates.push({
|
|
2172
|
+
kind: "mirror",
|
|
2173
|
+
orientation,
|
|
2174
|
+
position: centre + d,
|
|
2175
|
+
score: 0
|
|
2176
|
+
});
|
|
2177
|
+
out.push(best(candidates, (c) => mirror(c.orientation, c.position)));
|
|
2178
|
+
}
|
|
2179
|
+
const near = Math.max(2, Math.round(reach / 2));
|
|
2180
|
+
const rotations = orders.map((order) => {
|
|
2181
|
+
let top = {
|
|
2182
|
+
kind: "rotation",
|
|
2183
|
+
order,
|
|
2184
|
+
cx,
|
|
2185
|
+
cy,
|
|
2186
|
+
score: -1
|
|
2187
|
+
};
|
|
2188
|
+
for (let dy = -near; dy <= near; dy++) for (let dx = -near; dx <= near; dx++) {
|
|
2189
|
+
const s = score(rotation(order, cx + dx, cy + dy), coarse);
|
|
2190
|
+
if (s > top.score) top = {
|
|
2191
|
+
kind: "rotation",
|
|
2192
|
+
order,
|
|
2193
|
+
cx: cx + dx,
|
|
2194
|
+
cy: cy + dy,
|
|
2195
|
+
score: s
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
return top;
|
|
2199
|
+
});
|
|
2200
|
+
rotations.sort((a, b) => b.score - a.score);
|
|
2201
|
+
rotations.forEach((g, k) => {
|
|
2202
|
+
if (k > 1) return out.push(g);
|
|
2203
|
+
let top = g;
|
|
2204
|
+
for (const dy of [
|
|
2205
|
+
-.5,
|
|
2206
|
+
0,
|
|
2207
|
+
.5
|
|
2208
|
+
]) for (const dx of [
|
|
2209
|
+
-.5,
|
|
2210
|
+
0,
|
|
2211
|
+
.5
|
|
2212
|
+
]) {
|
|
2213
|
+
const c = {
|
|
2214
|
+
...g,
|
|
2215
|
+
cx: g.cx + dx,
|
|
2216
|
+
cy: g.cy + dy
|
|
2217
|
+
};
|
|
2218
|
+
c.score = score(rotation(c.order, c.cx, c.cy), fine);
|
|
2219
|
+
if (c.score > top.score || top === g) top = c;
|
|
2220
|
+
}
|
|
2221
|
+
out.push(top);
|
|
2222
|
+
});
|
|
2223
|
+
return out.sort((a, b) => b.score - a.score);
|
|
2224
|
+
}
|
|
2225
|
+
//#endregion
|
|
2226
|
+
export { detectSymmetry, 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.
|
|
3
|
+
"version": "0.1.3",
|
|
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://
|
|
8
|
+
"homepage": "https://inlaytrace.com/docs/package/",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
11
|
"url": "git+https://github.com/mtblck/inlaytrace.git",
|