@instruments/quadrat 0.0.0-stage → 0.1.1

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.
Files changed (77) hide show
  1. package/README.md +40 -2
  2. package/dist/analysis/analyze-surface-regions.d.ts +34 -0
  3. package/dist/analysis/analyze-surface-regions.d.ts.map +1 -0
  4. package/dist/analysis/analyze-surface-regions.js +47 -0
  5. package/dist/analysis/decode.d.ts +23 -0
  6. package/dist/analysis/decode.d.ts.map +1 -0
  7. package/dist/analysis/decode.js +48 -0
  8. package/dist/analysis/descriptors.d.ts +112 -0
  9. package/dist/analysis/descriptors.d.ts.map +1 -0
  10. package/dist/analysis/descriptors.js +248 -0
  11. package/dist/analysis/diagnostics.d.ts +45 -0
  12. package/dist/analysis/diagnostics.d.ts.map +1 -0
  13. package/dist/analysis/diagnostics.js +34 -0
  14. package/dist/analysis/index.d.ts +6 -0
  15. package/dist/analysis/index.d.ts.map +1 -0
  16. package/dist/analysis/index.js +2 -0
  17. package/dist/analysis/outline.d.ts +44 -0
  18. package/dist/analysis/outline.d.ts.map +1 -0
  19. package/dist/analysis/outline.js +301 -0
  20. package/dist/analysis/rank-suggestions.d.ts +21 -0
  21. package/dist/analysis/rank-suggestions.d.ts.map +1 -0
  22. package/dist/analysis/rank-suggestions.js +150 -0
  23. package/dist/analysis/repetition.d.ts +31 -0
  24. package/dist/analysis/repetition.d.ts.map +1 -0
  25. package/dist/analysis/repetition.js +105 -0
  26. package/dist/analysis/segmentation.d.ts +26 -0
  27. package/dist/analysis/segmentation.d.ts.map +1 -0
  28. package/dist/analysis/segmentation.js +81 -0
  29. package/dist/analysis/square-geometry.d.ts +34 -0
  30. package/dist/analysis/square-geometry.d.ts.map +1 -0
  31. package/dist/analysis/square-geometry.js +91 -0
  32. package/dist/analysis/surface-candidates.d.ts +45 -0
  33. package/dist/analysis/surface-candidates.d.ts.map +1 -0
  34. package/dist/analysis/surface-candidates.js +471 -0
  35. package/dist/analysis/thresholds.d.ts +189 -0
  36. package/dist/analysis/thresholds.d.ts.map +1 -0
  37. package/dist/analysis/thresholds.js +189 -0
  38. package/dist/analysis/types.d.ts +42 -0
  39. package/dist/analysis/types.d.ts.map +1 -0
  40. package/dist/analysis/types.js +2 -0
  41. package/dist/crops/crop-editor-state.d.ts +88 -0
  42. package/dist/crops/crop-editor-state.d.ts.map +1 -0
  43. package/dist/crops/crop-editor-state.js +121 -0
  44. package/dist/crops/crop-entries.d.ts +47 -0
  45. package/dist/crops/crop-entries.d.ts.map +1 -0
  46. package/dist/crops/crop-entries.js +46 -0
  47. package/dist/crops/crop-export.d.ts +21 -0
  48. package/dist/crops/crop-export.d.ts.map +1 -0
  49. package/dist/crops/crop-export.js +38 -0
  50. package/dist/crops/crop-geometry.d.ts +130 -0
  51. package/dist/crops/crop-geometry.d.ts.map +1 -0
  52. package/dist/crops/crop-geometry.js +271 -0
  53. package/dist/crops/crop-gesture.d.ts +175 -0
  54. package/dist/crops/crop-gesture.d.ts.map +1 -0
  55. package/dist/crops/crop-gesture.js +188 -0
  56. package/dist/crops/index.d.ts +10 -0
  57. package/dist/crops/index.d.ts.map +1 -0
  58. package/dist/crops/index.js +5 -0
  59. package/dist/index.d.ts +19 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +8 -0
  62. package/dist/surface-types.d.ts +41 -0
  63. package/dist/surface-types.d.ts.map +1 -0
  64. package/dist/surface-types.js +1 -0
  65. package/dist/worker/index.d.ts +4 -0
  66. package/dist/worker/index.d.ts.map +1 -0
  67. package/dist/worker/index.js +1 -0
  68. package/dist/worker/protocol.d.ts +28 -0
  69. package/dist/worker/protocol.d.ts.map +1 -0
  70. package/dist/worker/protocol.js +1 -0
  71. package/dist/worker/run-analysis.d.ts +21 -0
  72. package/dist/worker/run-analysis.d.ts.map +1 -0
  73. package/dist/worker/run-analysis.js +36 -0
  74. package/dist/worker/surface-worker.d.ts +2 -0
  75. package/dist/worker/surface-worker.d.ts.map +1 -0
  76. package/dist/worker/surface-worker.js +36 -0
  77. package/package.json +123 -3
@@ -0,0 +1,34 @@
1
+ /** Records an event when a collector is present; otherwise does nothing. */
2
+ export function record(diagnostics, event) {
3
+ diagnostics?.events.push(event);
4
+ }
5
+ /** What a stopwatch with no collector does: nothing, and without reading the clock. */
6
+ const idle = () => {
7
+ // Nothing is being collected.
8
+ };
9
+ /** Starts a stopwatch that reports into `diagnostics`. */
10
+ export const stopwatch = (diagnostics) => {
11
+ if (diagnostics === undefined) {
12
+ return { mark: idle, report: idle };
13
+ }
14
+ const totals = new Map();
15
+ let last = performance.now();
16
+ return {
17
+ mark: (stage) => {
18
+ const now = performance.now();
19
+ totals.set(stage, (totals.get(stage) ?? 0) + now - last);
20
+ last = now;
21
+ },
22
+ report: () => {
23
+ for (const [stage, ms] of totals) {
24
+ record(diagnostics, {
25
+ detail: { ms },
26
+ outcome: "kept",
27
+ pass: stage,
28
+ reason: "time spent",
29
+ stage: "timing",
30
+ });
31
+ }
32
+ },
33
+ };
34
+ };
@@ -0,0 +1,6 @@
1
+ export { analyzeSurfaceRegions } from "./analyze-surface-regions.js";
2
+ export type { Diagnostics, StageEvent } from "./diagnostics.js";
3
+ export { analysisSize, decodePhoto } from "./decode.js";
4
+ export type { DecodedPhoto } from "./decode.js";
5
+ export type { AnalysisImage, PercentRectangle, PixelRectangle, Rectangle, SurfaceSuggestion, } from "./types.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/analysis/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACxD,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,YAAY,EACV,aAAa,EACb,gBAAgB,EAChB,cAAc,EACd,SAAS,EACT,iBAAiB,GAClB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { analyzeSurfaceRegions } from "./analyze-surface-regions.js";
2
+ export { analysisSize, decodePhoto } from "./decode.js";
@@ -0,0 +1,44 @@
1
+ import type { RegionStats } from "./square-geometry.js";
2
+ import type { Rectangle } from "./types.js";
3
+ /** A point in analysis pixels. */
4
+ export interface Point {
5
+ x: number;
6
+ y: number;
7
+ }
8
+ /** Every stage of one outline, for drawing how a blocky mask edge becomes a smooth curve. */
9
+ export interface OutlineStages {
10
+ /** The box the two masks cover, in analysis pixels. */
11
+ box: {
12
+ x: number;
13
+ y: number;
14
+ width: number;
15
+ height: number;
16
+ };
17
+ /** The region's membership, 1 inside and 0 outside, with the crop added: the staircase. Row-major over `box`. */
18
+ mask: Float32Array;
19
+ /** The same mask after the blur that dissolves the steps. */
20
+ blurred: Float32Array;
21
+ /** The 0.5 contour of the blurred mask, one closed loop per outer edge or hole. */
22
+ loops: Point[][];
23
+ /** The loops after Ramer-Douglas-Peucker, before curves are fitted. */
24
+ simplified: Point[][];
25
+ /** The finished SVG path, in 0-100 units. */
26
+ path: string;
27
+ }
28
+ /** The same outline as `regionOutline`, with the intermediate pictures kept: the explainer draws them. */
29
+ export declare const regionOutlineStages: (labels: Int32Array, region: number, width: number, height: number, cell: number, crop: Rectangle, bounds: RegionStats) => OutlineStages;
30
+ /**
31
+ * Smooth outline of a region for an SVG with viewBox="0 0 100 100".
32
+ * The region's membership becomes a soft mask, blurred by about a window cell so cell stair-steps
33
+ * dissolve; its 0.5 iso-contour (marching squares) gives sub-pixel edges and keeps holes. Contours are
34
+ * simplified (Ramer-Douglas-Peucker) and emitted as closed Catmull-Rom curves in cubic Bezier form.
35
+ * The crop square is added to the mask before blurring so the outline hugs it, but the later blur,
36
+ * small-loop filter and curve fitting do not enforce enclosure: treat the outline as a drawing aid.
37
+ * Outer loops and holes wind in opposite directions, so the default fill rule shows holes as holes.
38
+ *
39
+ * `labels` is the per-pixel region map, `region` the label wanted, and `bounds` its bounding box; `cell` is
40
+ * half a window side and `crop` the proposed square, both in analysis pixels. Runs only for crops that
41
+ * survive ranking, because it is the costly step. The path is in 0-100 units of the whole image.
42
+ */
43
+ export declare function regionOutline(labels: Int32Array, region: number, width: number, height: number, cell: number, crop: Rectangle, bounds: RegionStats): string;
44
+ //# sourceMappingURL=outline.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outline.d.ts","sourceRoot":"","sources":["../../src/analysis/outline.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,kCAAkC;AAClC,MAAM,WAAW,KAAK;IACpB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX;AAED,6FAA6F;AAC7F,MAAM,WAAW,aAAa;IAC5B,uDAAuD;IACvD,GAAG,EAAE;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7D,iHAAiH;IACjH,IAAI,EAAE,YAAY,CAAC;IACnB,6DAA6D;IAC7D,OAAO,EAAE,YAAY,CAAC;IACtB,mFAAmF;IACnF,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC;IACjB,uEAAuE;IACvE,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;IACtB,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd;AAgFD,0GAA0G;AAC1G,eAAO,MAAM,mBAAmB,WACtB,UAAU,UACV,MAAM,SACP,MAAM,UACL,MAAM,QACR,MAAM,QACN,SAAS,UACP,WAAW,KAClB,aAC+D,CAAC;AAEnE;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,SAAS,EACf,MAAM,EAAE,WAAW,GAClB,MAAM,CAER"}
@@ -0,0 +1,301 @@
1
+ import { thresholds } from "./thresholds.js";
2
+ /** Does the work of both; `keep` says whether the unblurred mask is copied before the blur (otherwise `mask` and `blurred` are one array). */
3
+ const outline = (labels, region, width, height, cell, crop, bounds, keep) => {
4
+ const settings = thresholds.outline;
5
+ const sigma = Math.min(settings.maximumSigma, settings.sigmaCells * cell);
6
+ // Work on the region's bounding box plus the blur's reach; beyond that the mask is zero or the image edge.
7
+ const reach = Math.ceil(sigma * 3) + 2;
8
+ const x0 = Math.max(0, bounds.x0 - reach);
9
+ const y0 = Math.max(0, bounds.y0 - reach);
10
+ const x1 = Math.min(width, bounds.x1 + 1 + reach);
11
+ const y1 = Math.min(height, bounds.y1 + 1 + reach);
12
+ const w = x1 - x0;
13
+ const h = y1 - y0;
14
+ // Soft mask: 1 inside the region, 0 outside, cropped to the box above.
15
+ const mask = new Float32Array(w * h);
16
+ for (let y = 0; y < h; y++) {
17
+ for (let x = 0; x < w; x++) {
18
+ mask[y * w + x] = labels[(y + y0) * width + x + x0] === region ? 1 : 0;
19
+ }
20
+ }
21
+ for (let { y } = crop; y < crop.y + crop.height; y++) {
22
+ mask.fill(1, (y - y0) * w + crop.x - x0, (y - y0) * w + crop.x + crop.width - x0);
23
+ }
24
+ const steps = keep ? Float32Array.from(mask) : mask;
25
+ blur(mask, w, h, sigma);
26
+ const loops = contours(mask, w, h)
27
+ .filter((loop) => Math.abs(area(loop)) >= width * height * settings.minimumLoopFraction)
28
+ .map((loop) => loop.map((p) => ({ x: p.x + x0, y: p.y + y0 })));
29
+ // Analysis pixels to the SVG's 0-100 coordinates; two decimals keep the path string short.
30
+ const scaleX = 100 / width;
31
+ const scaleY = 100 / height;
32
+ const fixed = (value) => Number(value.toFixed(2));
33
+ const simplified = loops.map((loop) => simplify(loop, settings.simplifyTolerance));
34
+ const path = simplified
35
+ .map((points) => {
36
+ // Fewer points first, then a smooth curve through them, one curve segment per point.
37
+ const at = (i) => points[(i + points.length) % points.length];
38
+ let curve = `M${fixed(points[0].x * scaleX)} ${fixed(points[0].y * scaleY)}`;
39
+ for (let i = 0; i < points.length; i++) {
40
+ const a = at(i - 1);
41
+ const b = at(i);
42
+ const c = at(i + 1);
43
+ const d = at(i + 2);
44
+ // Catmull-Rom segment b to c, expressed as a cubic Bezier.
45
+ curve +=
46
+ `C${fixed((b.x + (c.x - a.x) / 6) * scaleX)} ${fixed((b.y + (c.y - a.y) / 6) * scaleY)}` +
47
+ ` ${fixed((c.x - (d.x - b.x) / 6) * scaleX)} ${fixed((c.y - (d.y - b.y) / 6) * scaleY)}` +
48
+ ` ${fixed(c.x * scaleX)} ${fixed(c.y * scaleY)}`;
49
+ }
50
+ return `${curve}Z`;
51
+ })
52
+ .join("");
53
+ return {
54
+ blurred: mask,
55
+ box: { height: h, width: w, x: x0, y: y0 },
56
+ loops,
57
+ mask: steps,
58
+ path,
59
+ simplified,
60
+ };
61
+ };
62
+ /** The same outline as `regionOutline`, with the intermediate pictures kept: the explainer draws them. */
63
+ export const regionOutlineStages = (labels, region, width, height, cell, crop, bounds) => outline(labels, region, width, height, cell, crop, bounds, true);
64
+ /**
65
+ * Smooth outline of a region for an SVG with viewBox="0 0 100 100".
66
+ * The region's membership becomes a soft mask, blurred by about a window cell so cell stair-steps
67
+ * dissolve; its 0.5 iso-contour (marching squares) gives sub-pixel edges and keeps holes. Contours are
68
+ * simplified (Ramer-Douglas-Peucker) and emitted as closed Catmull-Rom curves in cubic Bezier form.
69
+ * The crop square is added to the mask before blurring so the outline hugs it, but the later blur,
70
+ * small-loop filter and curve fitting do not enforce enclosure: treat the outline as a drawing aid.
71
+ * Outer loops and holes wind in opposite directions, so the default fill rule shows holes as holes.
72
+ *
73
+ * `labels` is the per-pixel region map, `region` the label wanted, and `bounds` its bounding box; `cell` is
74
+ * half a window side and `crop` the proposed square, both in analysis pixels. Runs only for crops that
75
+ * survive ranking, because it is the costly step. The path is in 0-100 units of the whole image.
76
+ */
77
+ export function regionOutline(labels, region, width, height, cell, crop, bounds) {
78
+ return outline(labels, region, width, height, cell, crop, bounds, false).path;
79
+ }
80
+ /** Signed polygon area; the sign follows winding. */
81
+ function area(loop) {
82
+ let total = 0;
83
+ for (let i = 0; i < loop.length; i++) {
84
+ const a = loop[i];
85
+ const b = loop[(i + 1) % loop.length];
86
+ total += a.x * b.y - b.x * a.y;
87
+ }
88
+ return total / 2;
89
+ }
90
+ /** Three box passes per axis approximate a Gaussian of the given sigma in linear time; edges are clamped. */
91
+ function blur(values, width, height, sigma) {
92
+ // Ideal box widths for three passes (Kovesi / Wells): two odd widths, `lower` and `upper`, with the
93
+ // first `small` passes using the narrower one so the combined spread matches `sigma`.
94
+ const ideal = Math.sqrt((12 * sigma * sigma) / 3 + 1);
95
+ let lower = Math.floor(ideal);
96
+ if (lower % 2 === 0) {
97
+ lower--;
98
+ }
99
+ const upper = lower + 2;
100
+ const small = Math.round((12 * sigma * sigma - 3 * lower * lower - 12 * lower - 9) /
101
+ (-4 * lower - 12));
102
+ const line = new Float32Array(Math.max(width, height));
103
+ for (let pass = 0; pass < 3; pass++) {
104
+ const radius = ((pass < small ? lower : upper) - 1) / 2;
105
+ if (radius < 1) {
106
+ continue;
107
+ }
108
+ for (let y = 0; y < height; y++) {
109
+ boxLine(values, y * width, 1, width, radius, line);
110
+ }
111
+ for (let x = 0; x < width; x++) {
112
+ boxLine(values, x, width, height, radius, line);
113
+ }
114
+ }
115
+ }
116
+ /**
117
+ * One box-blur pass over a single row or column, in place: each value becomes the average of the
118
+ * `radius` values either side (clamped at the ends). `start`, `stride` and `length` pick the line out of
119
+ * the flat array; `line` is scratch space. A running sum keeps it linear in the line length.
120
+ */
121
+ function boxLine(values, start, stride, length, radius, line) {
122
+ const at = (i) => values[start + Math.min(length - 1, Math.max(0, i)) * stride];
123
+ let sum = 0;
124
+ for (let i = -radius; i <= radius; i++) {
125
+ sum += at(i);
126
+ }
127
+ const span = radius * 2 + 1;
128
+ for (let i = 0; i < length; i++) {
129
+ line[i] = sum / span;
130
+ sum += at(i + radius + 1) - at(i - radius);
131
+ }
132
+ for (let i = 0; i < length; i++) {
133
+ values[start + i * stride] = line[i];
134
+ }
135
+ }
136
+ /**
137
+ * Marching squares at the 0.5 level over pixel centers, padded with an outside of zero so loops close
138
+ * at the image border. Segments are oriented with the inside on a fixed side, then stitched into loops.
139
+ */
140
+ function contours(field, width, height) {
141
+ const columns = width + 2;
142
+ const rows = height + 2;
143
+ const value = (x, y) => x < 1 || y < 1 || x > width || y > height
144
+ ? 0
145
+ : field[(y - 1) * width + (x - 1)];
146
+ const iso = 0.5;
147
+ // An edge point is identified by its lower-left grid node and direction, so neighboring cells share it.
148
+ const key = (x, y, vertical) => (y * columns + x) * 2 + (vertical ? 1 : 0);
149
+ const points = new Map();
150
+ const next = new Map();
151
+ const corner = [
152
+ [0, 0],
153
+ [1, 0],
154
+ [1, 1],
155
+ [0, 1],
156
+ ];
157
+ // Edges adjacent to each corner, for cutting it off in a saddle.
158
+ const cornerEdges = [
159
+ [0, 3],
160
+ [0, 1],
161
+ [1, 2],
162
+ [2, 3],
163
+ ];
164
+ // Edge e joins corners [a, b]: top, right, bottom, left.
165
+ const edges = [
166
+ [0, 1],
167
+ [1, 2],
168
+ [3, 2],
169
+ [0, 3],
170
+ ];
171
+ for (let y = 0; y < rows - 1; y++) {
172
+ for (let x = 0; x < columns - 1; x++) {
173
+ const v = corner.map(([dx, dy]) => value(x + dx, y + dy));
174
+ const inside = v.map((c) => c >= iso);
175
+ if (inside.every(Boolean) || !inside.some(Boolean)) {
176
+ continue;
177
+ }
178
+ const edgePoint = (e) => {
179
+ const [a, b] = edges[e];
180
+ const [ax, ay] = corner[a];
181
+ const [bx, by] = corner[b];
182
+ const t = (iso - v[a]) / (v[b] - v[a]);
183
+ const px = x + ax + t * (bx - ax) - 0.5;
184
+ const py = y + ay + t * (by - ay) - 0.5;
185
+ const vertical = e === 1 || e === 3;
186
+ const id = key(x + (e === 1 ? 1 : 0), y + (e === 2 ? 1 : 0), vertical);
187
+ if (!points.has(id)) {
188
+ points.set(id, { x: px, y: py });
189
+ }
190
+ return id;
191
+ };
192
+ // Edges whose end corners differ in sign are crossed. Two crossed edges give one segment; four is a saddle.
193
+ const crossed = [0, 1, 2, 3].filter((e) => inside[edges[e][0]] !== inside[edges[e][1]]);
194
+ const insideCorners = corner.filter((_, i) => inside[i]);
195
+ const centroid = {
196
+ x: insideCorners.reduce((sum, [dx]) => sum + dx, 0) /
197
+ insideCorners.length,
198
+ y: insideCorners.reduce((sum, [, dy]) => sum + dy, 0) /
199
+ insideCorners.length,
200
+ };
201
+ const segments = [];
202
+ if (crossed.length === 2) {
203
+ segments.push([crossed[0], crossed[1], centroid]);
204
+ }
205
+ else {
206
+ // Saddle: the center value decides whether the inside corners join or stay apart.
207
+ const joined = (v[0] + v[1] + v[2] + v[3]) / 4 >= iso;
208
+ for (let c = 0; c < 4; c++) {
209
+ if (inside[c] !== joined)
210
+ segments.push([
211
+ cornerEdges[c][0],
212
+ cornerEdges[c][1],
213
+ joined
214
+ ? { x: 0.5, y: 0.5 }
215
+ : { x: corner[c][0], y: corner[c][1] },
216
+ ]);
217
+ }
218
+ }
219
+ for (const [ea, eb, reference] of segments) {
220
+ const p = edgePoint(ea);
221
+ const q = edgePoint(eb);
222
+ const pa = points.get(p);
223
+ const pb = points.get(q);
224
+ const rx = x + reference.x - 0.5;
225
+ const ry = y + reference.y - 0.5;
226
+ // Keep the inside on one fixed side of every directed segment.
227
+ const side = (pb.x - pa.x) * (ry - pa.y) - (pb.y - pa.y) * (rx - pa.x);
228
+ if (side > 0) {
229
+ next.set(p, q);
230
+ }
231
+ else {
232
+ next.set(q, p);
233
+ }
234
+ }
235
+ }
236
+ }
237
+ const loops = [];
238
+ const seen = new Set();
239
+ for (const start of next.keys()) {
240
+ if (seen.has(start)) {
241
+ continue;
242
+ }
243
+ const loop = [];
244
+ let current = start;
245
+ while (!seen.has(current)) {
246
+ seen.add(current);
247
+ loop.push(points.get(current));
248
+ const following = next.get(current);
249
+ if (following === undefined) {
250
+ throw new Error("Outline contour did not close.");
251
+ }
252
+ current = following;
253
+ }
254
+ if (loop.length >= 3) {
255
+ loops.push(loop);
256
+ }
257
+ }
258
+ return loops;
259
+ }
260
+ /**
261
+ * Ramer-Douglas-Peucker on a closed loop: drops points that lie within `tolerance` (analysis pixels) of
262
+ * the straight line between their kept neighbors. The loop is split at the point farthest from the first
263
+ * so both halves are open lines.
264
+ */
265
+ function simplify(loop, tolerance) {
266
+ let far = 0;
267
+ let best = -1;
268
+ for (let i = 1; i < loop.length; i++) {
269
+ const d = (loop[i].x - loop[0].x) ** 2 + (loop[i].y - loop[0].y) ** 2;
270
+ if (d > best) {
271
+ ((best = d), (far = i));
272
+ }
273
+ }
274
+ const open = (points) => {
275
+ const a = points[0];
276
+ const b = points.at(-1);
277
+ if (points.length < 3 || b === undefined) {
278
+ return points;
279
+ }
280
+ const length = Math.hypot(b.x - a.x, b.y - a.y) || 1;
281
+ let index = 0;
282
+ let worst = -1;
283
+ for (let i = 1; i < points.length - 1; i++) {
284
+ const d = Math.abs((b.x - a.x) * (a.y - points[i].y) - (a.x - points[i].x) * (b.y - a.y)) / length;
285
+ if (d > worst) {
286
+ ((worst = d), (index = i));
287
+ }
288
+ }
289
+ if (worst <= tolerance) {
290
+ return [a, b];
291
+ }
292
+ return [
293
+ ...open(points.slice(0, index + 1)).slice(0, -1),
294
+ ...open(points.slice(index)),
295
+ ];
296
+ };
297
+ const first = open(loop.slice(0, far + 1));
298
+ const second = open([...loop.slice(far), loop[0]]);
299
+ const joined = [...first.slice(0, -1), ...second.slice(0, -1)];
300
+ return joined.length >= 3 ? joined : loop;
301
+ }
@@ -0,0 +1,21 @@
1
+ import type { Diagnostics } from "./diagnostics.js";
2
+ import type { Candidate } from "./surface-candidates.js";
3
+ import type { SurfaceSuggestion } from "./types.js";
4
+ /**
5
+ * Turns the unsorted candidates into the final suggestions, in five filters:
6
+ * 0. mixtures: a candidate holding two smaller passing candidates of different materials is dropped
7
+ * (see `holdsDistinctMaterials`), before it can push them out as overlaps; a survivor whose `maxCrop`
8
+ * would hold them falls back to its crop, so Expand cannot grow into the mixture either;
9
+ * 1. overlaps: best score first, a candidate that overlaps a kept one by more than `overlapFraction` is
10
+ * dropped, which also picks each place's window scale;
11
+ * 2. same material: one crop per material, the better representative of each, wherever the instances sit
12
+ * in the photo (see `sameMaterial`);
13
+ * 3. much smaller than the best crop (under `relativeSide` of its side) is dropped;
14
+ * 4. anything past `suggestionLimit`.
15
+ *
16
+ * Output is best score first and renumbered `surface-1`, `surface-2`, ... by that order, so ids in the
17
+ * diagnostics trace (which carry the scale, e.g. `surface-w16#42`) do not match the returned ids.
18
+ * This is also where each survivor's outline is drawn.
19
+ */
20
+ export declare function rankSuggestions(candidates: Candidate[], diagnostics?: Diagnostics): SurfaceSuggestion[];
21
+ //# sourceMappingURL=rank-suggestions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rank-suggestions.d.ts","sourceRoot":"","sources":["../../src/analysis/rank-suggestions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,KAAK,EAAoB,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA2DtE;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,EAAE,EACvB,WAAW,CAAC,EAAE,WAAW,GACxB,iBAAiB,EAAE,CAkHrB"}
@@ -0,0 +1,150 @@
1
+ // Stage 4 of the pipeline in analyze-surface-regions.ts: drops overlaps and same-material duplicates, then caps the list.
2
+ import { materialDistance } from "./descriptors.js";
3
+ import { record, stopwatch } from "./diagnostics.js";
4
+ import { overlappingCrops } from "./square-geometry.js";
5
+ import { thresholds } from "./thresholds.js";
6
+ /**
7
+ * How far apart two crops' materials are (`materialDistance`), eased by `sizeWeight` x ln of their width
8
+ * ratio, since a close-up's descriptor drifts with scale.
9
+ */
10
+ const easedDistance = (a, b) => {
11
+ const ratio = Math.max(a.suggestion.crop.width, b.suggestion.crop.width) /
12
+ Math.min(a.suggestion.crop.width, b.suggestion.crop.width);
13
+ return (materialDistance(a.signature, b.signature, a.descriptor.energy, b.descriptor.energy) -
14
+ thresholds.ranking.sizeWeight * Math.log(ratio));
15
+ };
16
+ /**
17
+ * Whether `candidate` repeats the kept `leader`: one criterion, one threshold. Material distance is
18
+ * lighting-tolerant (chromaticity, relative contrast, edge directions, lightness only lightly), so one
19
+ * material in sun and in shade reads as one. The more the two crops differ in size, the more the distance
20
+ * is eased (by `sizeWeight` x ln of the width ratio), since a close-up's descriptor drifts with scale.
21
+ * Where the two crops sit does not matter.
22
+ */
23
+ const sameMaterial = (leader, candidate) => easedDistance(leader, candidate) < thresholds.ranking.duplicateThreshold;
24
+ /**
25
+ * Whether the square `outer` (source percent) holds two smaller candidates of clearly different materials
26
+ * (`mixtureDistance`): squares that passed on their own inside it, at least `mixtureInnerSide` of its side
27
+ * and mostly inside it.
28
+ */
29
+ const holdsDistinctMaterials = (outer, candidates) => {
30
+ const { mixtureContainment, mixtureDistance, mixtureInnerSide } = thresholds.ranking;
31
+ const side = outer.width;
32
+ const inner = candidates.filter(({ suggestion }) => suggestion.crop.width < side &&
33
+ suggestion.crop.width >= side * mixtureInnerSide &&
34
+ overlappingCrops(suggestion.crop, outer) > mixtureContainment);
35
+ for (let i = 0; i < inner.length; i += 1) {
36
+ for (let j = i + 1; j < inner.length; j += 1) {
37
+ if (easedDistance(inner[i], inner[j]) > mixtureDistance) {
38
+ return true;
39
+ }
40
+ }
41
+ }
42
+ return false;
43
+ };
44
+ /**
45
+ * Turns the unsorted candidates into the final suggestions, in five filters:
46
+ * 0. mixtures: a candidate holding two smaller passing candidates of different materials is dropped
47
+ * (see `holdsDistinctMaterials`), before it can push them out as overlaps; a survivor whose `maxCrop`
48
+ * would hold them falls back to its crop, so Expand cannot grow into the mixture either;
49
+ * 1. overlaps: best score first, a candidate that overlaps a kept one by more than `overlapFraction` is
50
+ * dropped, which also picks each place's window scale;
51
+ * 2. same material: one crop per material, the better representative of each, wherever the instances sit
52
+ * in the photo (see `sameMaterial`);
53
+ * 3. much smaller than the best crop (under `relativeSide` of its side) is dropped;
54
+ * 4. anything past `suggestionLimit`.
55
+ *
56
+ * Output is best score first and renumbered `surface-1`, `surface-2`, ... by that order, so ids in the
57
+ * diagnostics trace (which carry the scale, e.g. `surface-w16#42`) do not match the returned ids.
58
+ * This is also where each survivor's outline is drawn.
59
+ */
60
+ export function rankSuggestions(candidates, diagnostics) {
61
+ // Records a ranking decision in the diagnostics trace; does nothing without a collector.
62
+ const note = ({ suggestion }, outcome, reason, twin) => {
63
+ const score = Number(suggestion.score.toFixed(3));
64
+ record(diagnostics, {
65
+ coverage: suggestion.coverage,
66
+ crop: suggestion.crop,
67
+ // A same-material rejection also names the crop it was judged a repeat of.
68
+ detail: twin === undefined ? { score } : { score, twin: twin.suggestion.id },
69
+ outcome,
70
+ pass: suggestion.id,
71
+ reason,
72
+ stage: "rank",
73
+ });
74
+ };
75
+ const clock = stopwatch(diagnostics);
76
+ const pure = [];
77
+ for (const candidate of candidates) {
78
+ const { crop, maxCrop } = candidate.suggestion;
79
+ if (holdsDistinctMaterials(crop, candidates)) {
80
+ note(candidate, "rejected", "holds distinct materials");
81
+ }
82
+ else if (maxCrop !== crop &&
83
+ holdsDistinctMaterials(maxCrop, candidates)) {
84
+ pure.push({
85
+ ...candidate,
86
+ suggestion: { ...candidate.suggestion, maxCrop: crop },
87
+ });
88
+ }
89
+ else {
90
+ pure.push(candidate);
91
+ }
92
+ }
93
+ // Spatial suppression first: scale variants of one place collapse to the best-scoring one.
94
+ const separate = [];
95
+ for (const candidate of [...pure].sort((a, b) => b.suggestion.score - a.suggestion.score)) {
96
+ if (separate.some(({ suggestion }) => overlappingCrops(suggestion.crop, candidate.suggestion.crop) >
97
+ thresholds.ranking.overlapFraction)) {
98
+ note(candidate, "rejected", "overlaps a better crop");
99
+ }
100
+ else {
101
+ separate.push(candidate);
102
+ }
103
+ }
104
+ // Then one crop per material. A candidate that repeats a kept crop replaces it when it is the better
105
+ // representative (bigger, more homogeneous, better exposed), otherwise it is dropped; the survivors are
106
+ // re-ranked by score. Comparing to kept crops only, not to every dropped member, stops long chains of
107
+ // slowly changing textures collapsing into one cluster.
108
+ let kept = [];
109
+ for (const candidate of separate) {
110
+ const twins = kept.filter((other) => sameMaterial(other, candidate));
111
+ if (twins.length === 0) {
112
+ kept.push(candidate);
113
+ }
114
+ else if (twins.every((twin) => candidate.representative > twin.representative)) {
115
+ for (const twin of twins) {
116
+ note(twin, "rejected", "same material as a better representative", candidate);
117
+ }
118
+ kept = kept.filter((other) => !twins.includes(other));
119
+ kept.push(candidate);
120
+ }
121
+ else {
122
+ note(candidate, "rejected", "same material as a better crop", twins.find((twin) => candidate.representative <= twin.representative));
123
+ }
124
+ }
125
+ // Finally the size and count limits, applied in score order (index 0 is the best crop).
126
+ kept.sort((a, b) => b.suggestion.score - a.suggestion.score);
127
+ kept = kept.filter((candidate, index) => {
128
+ if (index > 0 &&
129
+ candidate.suggestion.crop.width <
130
+ thresholds.ranking.relativeSide * kept[0].suggestion.crop.width) {
131
+ note(candidate, "rejected", "much smaller than the best crop");
132
+ return false;
133
+ }
134
+ if (index >= thresholds.ranking.suggestionLimit) {
135
+ note(candidate, "rejected", "beyond the suggestion limit");
136
+ return false;
137
+ }
138
+ note(candidate, "kept", "ranked");
139
+ return true;
140
+ });
141
+ clock.mark("Choosing");
142
+ const result = kept.map(({ suggestion, outline }, index) => ({
143
+ ...suggestion,
144
+ id: `surface-${index + 1}`,
145
+ path: outline(),
146
+ }));
147
+ clock.mark("Outlines");
148
+ clock.report();
149
+ return result;
150
+ }
@@ -0,0 +1,31 @@
1
+ import type { Rectangle } from "./types.js";
2
+ /**
3
+ * How well a square lines up with a shifted copy of itself, for every shift along a row (or, if `vertical`,
4
+ * a column) from 1 pixel up to a limit. `profile[i]` is the Pearson correlation of brightness at a shift of
5
+ * `i + 1` pixels (1 is a perfect match, 0 none). `rect` is in analysis pixels.
6
+ */
7
+ export declare const correlationProfile: (data: Uint8ClampedArray, width: number, rect: Rectangle, vertical: boolean) => number[];
8
+ /**
9
+ * The shift (in pixels) at which a correlation profile recovers to a repeat, or null when it never does.
10
+ * A recovered peak after a trough is repetition; a smooth gradient alone isn't.
11
+ * `trough` is the lowest correlation seen between a shift of 2 and the one before the candidate. A peak must be strong, rise well above
12
+ * that trough, and be a local maximum (higher than the next shift).
13
+ */
14
+ export declare const repeatPeriod: (correlations: number[]) => number | null;
15
+ /**
16
+ * Labels a square (`rect`, in analysis pixels) as repeating when its brightness pattern lines up with a
17
+ * shifted copy of itself. For each shift along a row or a column, it measures how well the square
18
+ * correlates with itself (`correlationProfile`). A repeating pattern dips as the copy slides off
19
+ * and then recovers to a peak when the shift equals the pattern's period (`repeatPeriod`); a smooth gradient never recovers.
20
+ * Either direction is enough. This only sets the suggestion's `basis`; it never proposes or rejects a crop.
21
+ */
22
+ export declare function repeatingTexture(data: Uint8ClampedArray, width: number, rect: Rectangle): boolean;
23
+ /**
24
+ * Whether a square repeats at least as strongly as `peak`: some recovered peak (one that rises
25
+ * `minimumRecovery` above the trough before it and tops the next shift) reaches `peak`, along rows or
26
+ * columns, with shifts up to half the square so a print's period fits twice. A printed or woven pattern
27
+ * reaches 0.6 and more; a blend of different materials rarely lines up with a shifted copy of itself.
28
+ * Correlations are computed shift by shift and the search stops at the first qualifying peak.
29
+ */
30
+ export declare const repeatsAtLeast: (data: Uint8ClampedArray, width: number, rect: Rectangle, peak: number) => boolean;
31
+ //# sourceMappingURL=repetition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repetition.d.ts","sourceRoot":"","sources":["../../src/analysis/repetition.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAqD5C;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,SACvB,iBAAiB,SAChB,MAAM,QACP,SAAS,YACL,OAAO,KAChB,MAAM,EAWR,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,YAAY,iBAAkB,MAAM,EAAE,KAAG,MAAM,GAAG,IAkB9D,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,iBAAiB,EACvB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,SAAS,GACd,OAAO,CAST;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,SACnB,iBAAiB,SAChB,MAAM,QACP,SAAS,QACT,MAAM,KACX,OAwBF,CAAC"}