@vitavision/overlays 0.1.0 → 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.
package/dist/index.js ADDED
@@ -0,0 +1,870 @@
1
+ import { AreaSet, GridLayer, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PointSet, circlePath, imageViewBox, latticeEdges, overlayRole, useScreenPx, useStage } from "@vitavision/stage2d";
2
+ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ //#region src/glyphs.ts
5
+ /**
6
+ * The glyphs of a calibration-target overlay, as path generators.
7
+ *
8
+ * A glyph is a `MarkerShape` for `@vitavision/stage2d`'s `PointSet`: a pure function from a
9
+ * position to SVG path data, so a layer appends thousands of them into one `<path>` (ADR-0004).
10
+ * They are registered under the names in `TARGET_MARKERS`, which `TargetOverlay` passes as
11
+ * `markers`. Sizes are screen pixels, from `unit` (image pixels per screen pixel).
12
+ *
13
+ * `MarkerShape.path` receives one number per item, `angle`. A corner with two edge directions
14
+ * needs two, so `packAxes` folds both into that one number (see below); that is the only reason
15
+ * the packing exists.
16
+ *
17
+ * Pure: no React, no DOM.
18
+ */
19
+ /** Round to 1/1000 of an image pixel. */
20
+ function round(value) {
21
+ return Math.round(value * 1e3) / 1e3;
22
+ }
23
+ /** Quantisation steps per half turn when two axes share one number: 2²⁶, so about 4.7e-8 rad. */
24
+ const STEPS = 2 ** 26;
25
+ /** Packed values start here; a plain angle (normalised to [0, π)) is always below it. */
26
+ const PACKED_FLOOR = 8;
27
+ /** An angle as a direction of a line: modulo π, in [0, π). */
28
+ function lineAngle(angle) {
29
+ const wrapped = angle % Math.PI;
30
+ return wrapped < 0 ? wrapped + Math.PI : wrapped;
31
+ }
32
+ /**
33
+ * Fold one or two edge directions into the single `angle` number a `MarkerShape` receives.
34
+ *
35
+ * Directions are lines (`θ` and `θ + π` are the same line), so each is taken modulo π. With one
36
+ * direction the result is that angle in [0, π). With two they are quantised to 2⁻²⁶ of a half
37
+ * turn (4.7e-8 rad, under a millionth of a screen pixel on a 10 px glyph) and packed into one
38
+ * integer-valued double above 8, which stays exact because it is below 2⁵³. `unpackAxes` is the
39
+ * inverse.
40
+ *
41
+ * @param angle - The first direction, radians.
42
+ * @param angle2 - The second direction, radians. Optional.
43
+ * @returns A number to put in `PointSetItem.angle` for the `directed` marker.
44
+ */
45
+ function packAxes(angle, angle2) {
46
+ if (angle2 === void 0) return lineAngle(angle);
47
+ const q = (a) => Math.round(lineAngle(a) / Math.PI * STEPS) % STEPS;
48
+ return PACKED_FLOOR + q(angle) * STEPS + q(angle2);
49
+ }
50
+ /**
51
+ * The directions folded into `angle` by `packAxes`.
52
+ *
53
+ * @param packed - A value from `packAxes`, or a plain angle in radians.
54
+ * @returns One direction for a plain angle, two for a packed value; each in [0, π).
55
+ */
56
+ function unpackAxes(packed) {
57
+ if (!Number.isFinite(packed)) return [];
58
+ if (packed < PACKED_FLOOR) return [lineAngle(packed)];
59
+ const rest = packed - PACKED_FLOOR;
60
+ const first = Math.floor(rest / STEPS);
61
+ return [first / STEPS * Math.PI, (rest - first * STEPS) / STEPS * Math.PI];
62
+ }
63
+ /** Half-length of a directed corner's axes, and the gap left at its centre, in screen pixels. */
64
+ const AXIS_REACH = 8;
65
+ const AXIS_GAP = 2;
66
+ /**
67
+ * A corner with its edge directions: one or two lines through the point, 8 px each way with a
68
+ * 2 px gap at the centre, so the corner itself stays visible. Give it `angle: packAxes(a, b)`.
69
+ */
70
+ const directed = {
71
+ paint: "line",
72
+ size: AXIS_REACH,
73
+ path: (x, y, unit, packed) => {
74
+ let d = "";
75
+ for (const angle of unpackAxes(packed)) {
76
+ const c = Math.cos(angle);
77
+ const s = Math.sin(angle);
78
+ const near = AXIS_GAP * unit;
79
+ const far = AXIS_REACH * unit;
80
+ d += `M${round(x - far * c)} ${round(y - far * s)}L${round(x - near * c)} ${round(y - near * s)}M${round(x + near * c)} ${round(y + near * s)}L${round(x + far * c)} ${round(y + far * s)}`;
81
+ }
82
+ return d;
83
+ }
84
+ };
85
+ /** Radius of a matched circle's glyph, screen pixels. */
86
+ const CIRCLE_RADIUS = 5.5;
87
+ /** Radius of the centre mark of a black circle, screen pixels; stroked, it reads as a filled dot. */
88
+ const CENTRE_RADIUS = .8;
89
+ /** The marker names `TargetOverlay` uses, to pass to `PointSet`'s `markers`. */
90
+ const TARGET_MARKERS = {
91
+ /** Edge directions of a corner; see `packAxes`. */
92
+ directed,
93
+ /** A white matched circle. */
94
+ "circle-white": {
95
+ paint: "line",
96
+ size: CIRCLE_RADIUS,
97
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit)
98
+ },
99
+ /** A black matched circle. */
100
+ "circle-black": {
101
+ paint: "line",
102
+ size: CIRCLE_RADIUS,
103
+ path: (x, y, unit) => circlePath(x, y, CIRCLE_RADIUS * unit) + circlePath(x, y, CENTRE_RADIUS * unit)
104
+ }
105
+ };
106
+ /**
107
+ * An ellipse as two arcs, exactly: no polygon approximation, so it stays round at any zoom.
108
+ *
109
+ * @param cx - Centre x, image pixels.
110
+ * @param cy - Centre y, image pixels.
111
+ * @param rx - Semi-axis along the rotated x axis, image pixels.
112
+ * @param ry - Semi-axis along the rotated y axis, image pixels.
113
+ * @param angle - Rotation of the `rx` axis, radians clockwise on screen.
114
+ * @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
115
+ */
116
+ function ellipsePath(cx, cy, rx, ry, angle = 0) {
117
+ if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
118
+ const dx = rx * Math.cos(angle);
119
+ const dy = rx * Math.sin(angle);
120
+ const degrees = round(angle * 180 / Math.PI);
121
+ const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
122
+ return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
123
+ }
124
+ //#endregion
125
+ //#region src/EllipseSet.tsx
126
+ /**
127
+ * Many ellipses over the image whose size is data: fitted ring edges, edge-bit dots.
128
+ *
129
+ * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
130
+ * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
131
+ * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
132
+ * It is not picked: pair it with a `PointSet` at the centres, which is what `TargetOverlay` does.
133
+ */
134
+ const HALO = overlayRole("halo");
135
+ /** The outline of an item, its semi-axes raised to `floor` image pixels. */
136
+ function outlineOf(item, floor) {
137
+ return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);
138
+ }
139
+ /** The concatenated outlines of the items at `indices`. */
140
+ function batchPath(items, indices, floor) {
141
+ let d = "";
142
+ for (const i of indices) d += outlineOf(items[i], floor);
143
+ return d;
144
+ }
145
+ /**
146
+ * A batched set of ellipses inside an `ImageStage`.
147
+ *
148
+ * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
149
+ * the stroke is a screen constant.
150
+ * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
151
+ * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
152
+ * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
153
+ *
154
+ * The SVG carries `data-ellipses` (the count).
155
+ */
156
+ function EllipseSet({ items, role = "feature", hoveredId = null, selectedIds, dimmed, halo = true, minRadius, selectionStroke = overlayRole("selection"), label }) {
157
+ const stage = useStage();
158
+ const px = useScreenPx();
159
+ const unit = px(1);
160
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
161
+ const isDimmed = useMemo(() => {
162
+ if (typeof dimmed === "function") return dimmed;
163
+ const set = new Set(dimmed ?? []);
164
+ return (id) => set.has(id);
165
+ }, [dimmed]);
166
+ const batches = useMemo(() => {
167
+ const normal = /* @__PURE__ */ new Map();
168
+ const picked = {
169
+ key: "selected",
170
+ role: "selection",
171
+ dashed: false,
172
+ opacity: 1,
173
+ dim: false,
174
+ indices: []
175
+ };
176
+ items.forEach((item, i) => {
177
+ if (selectedSet.has(item.id)) {
178
+ picked.indices.push(i);
179
+ return;
180
+ }
181
+ const itemRole = item.role ?? role;
182
+ const dashed = item.dashed ?? false;
183
+ const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;
184
+ const dim = isDimmed(item.id);
185
+ const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? "dashed" : "solid"}|${opacity}`;
186
+ let batch = normal.get(key);
187
+ if (!batch) {
188
+ batch = {
189
+ key,
190
+ role: itemRole,
191
+ dashed,
192
+ opacity,
193
+ dim,
194
+ indices: []
195
+ };
196
+ normal.set(key, batch);
197
+ }
198
+ batch.indices.push(i);
199
+ });
200
+ return {
201
+ normal: [...normal.values()],
202
+ picked: picked.indices.length > 0 ? picked : null
203
+ };
204
+ }, [
205
+ items,
206
+ role,
207
+ selectedSet,
208
+ isDimmed
209
+ ]);
210
+ const floor = minRadius !== void 0 ? minRadius * unit : 0;
211
+ const normalPaths = useMemo(() => batches.normal.map((batch) => ({
212
+ batch,
213
+ d: batchPath(items, batch.indices, floor)
214
+ })), [
215
+ batches,
216
+ items,
217
+ floor
218
+ ]);
219
+ const pickedPath = useMemo(() => batches.picked ? batchPath(items, batches.picked.indices, floor) : "", [
220
+ batches,
221
+ items,
222
+ floor
223
+ ]);
224
+ const hoverPositions = [];
225
+ if (hoveredId !== null) items.forEach((item, i) => {
226
+ if (item.id === hoveredId) hoverPositions.push(i);
227
+ });
228
+ const hoverSelected = hoveredId !== null && selectedSet.has(hoveredId);
229
+ const widthOf = (itemRole, state) => {
230
+ const thin = itemRole === "model" || itemRole === "structure";
231
+ return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== "selected" ? .5 : 0));
232
+ };
233
+ const dash = `${px(4)} ${px(3)}`;
234
+ return /* @__PURE__ */ jsx("svg", {
235
+ viewBox: imageViewBox(stage.image),
236
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
237
+ ...label !== void 0 ? {
238
+ role: "img",
239
+ "aria-label": label
240
+ } : { "aria-hidden": true },
241
+ "data-ellipses": items.length,
242
+ children: /* @__PURE__ */ jsxs("g", {
243
+ fill: "none",
244
+ strokeLinecap: "round",
245
+ strokeLinejoin: "round",
246
+ children: [
247
+ normalPaths.map(({ batch, d }) => /* @__PURE__ */ jsxs("g", {
248
+ opacity: batch.dim ? OVERLAY_STATE_OPACITY.dimmed : void 0,
249
+ children: [halo && /* @__PURE__ */ jsx("path", {
250
+ d,
251
+ stroke: HALO,
252
+ strokeWidth: widthOf(batch.role, "default") + px(2),
253
+ strokeDasharray: batch.dashed ? dash : void 0,
254
+ opacity: .6 * batch.opacity
255
+ }), /* @__PURE__ */ jsx("path", {
256
+ "data-batch": batch.key,
257
+ d,
258
+ stroke: overlayRole(batch.role),
259
+ strokeWidth: widthOf(batch.role, "default"),
260
+ strokeDasharray: batch.dashed ? dash : void 0,
261
+ opacity: batch.opacity
262
+ })]
263
+ }, batch.key)),
264
+ batches.picked && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
265
+ d: pickedPath,
266
+ stroke: HALO,
267
+ strokeWidth: widthOf("selection", "selected") + px(2)
268
+ }), /* @__PURE__ */ jsx("path", {
269
+ "data-selected-ellipses": "",
270
+ d: pickedPath,
271
+ stroke: selectionStroke,
272
+ strokeWidth: widthOf("selection", "selected")
273
+ })] }),
274
+ hoverPositions.map((position) => {
275
+ const item = items[position];
276
+ const itemRole = item.role ?? role;
277
+ const state = hoverSelected ? "selected" : "hover";
278
+ return /* @__PURE__ */ jsxs("g", { children: [halo && /* @__PURE__ */ jsx("path", {
279
+ d: outlineOf(item, floor),
280
+ stroke: HALO,
281
+ strokeWidth: widthOf(itemRole, state) + px(2)
282
+ }), /* @__PURE__ */ jsx("path", {
283
+ "data-hovered-ellipse": "",
284
+ d: outlineOf(item, floor),
285
+ stroke: hoverSelected ? selectionStroke : overlayRole(itemRole),
286
+ strokeWidth: widthOf(itemRole, state)
287
+ })] }, position);
288
+ })
289
+ ]
290
+ })
291
+ });
292
+ }
293
+ //#endregion
294
+ //#region src/lattice.ts
295
+ /**
296
+ * The lattice of a detected board: which corner sits at which `(i, j)`, which corners are
297
+ * neighbours, and the polygons of the markers.
298
+ *
299
+ * Ported from vitavision's `overlayData.ts` (`buildCornerGrid`, `buildGridEdges`,
300
+ * `buildFeatureIdByGrid`, `buildMarkerPolygons`), where ChArUco, chessboard, marker board and
301
+ * PuzzleBoard each carried a copy (PuzzleBoard's `buildPuzzleGrid` was a fourth). One
302
+ * implementation now serves all four, on the normalised `TargetDetection` input.
303
+ *
304
+ * Pure: no React, no DOM.
305
+ */
306
+ /**
307
+ * The key of a lattice position, as `idByGrid` and `CornerGrid.byIndex` use.
308
+ *
309
+ * @param i - Index along the first axis.
310
+ * @param j - Index along the second axis.
311
+ * @returns `"i:j"`.
312
+ */
313
+ function gridKey(i, j) {
314
+ return `${i}:${j}`;
315
+ }
316
+ /** Whether a corner carries an integer lattice index. */
317
+ function isGridCorner(corner) {
318
+ return Number.isInteger(corner.i) && Number.isInteger(corner.j);
319
+ }
320
+ /**
321
+ * Index a board's corners by lattice position.
322
+ *
323
+ * Corners without an integer `(i, j)` are not part of the grid. When two corners claim one
324
+ * position the first wins, as it does in `latticeEdges`.
325
+ *
326
+ * @param corners - The detected corners, in any order, with gaps allowed.
327
+ * @returns The grid.
328
+ */
329
+ function cornerGrid(corners) {
330
+ const nodes = [];
331
+ const byIndex = /* @__PURE__ */ new Map();
332
+ const rowMap = /* @__PURE__ */ new Map();
333
+ const colMap = /* @__PURE__ */ new Map();
334
+ let bounds = null;
335
+ for (const corner of corners) {
336
+ if (!isGridCorner(corner)) continue;
337
+ const key = gridKey(corner.i, corner.j);
338
+ if (byIndex.has(key)) continue;
339
+ const position = nodes.length;
340
+ nodes.push(corner);
341
+ byIndex.set(key, position);
342
+ const row = rowMap.get(corner.i);
343
+ if (row) row.push(position);
344
+ else rowMap.set(corner.i, [position]);
345
+ const col = colMap.get(corner.j);
346
+ if (col) col.push(position);
347
+ else colMap.set(corner.j, [position]);
348
+ bounds = bounds ? {
349
+ minI: Math.min(bounds.minI, corner.i),
350
+ maxI: Math.max(bounds.maxI, corner.i),
351
+ minJ: Math.min(bounds.minJ, corner.j),
352
+ maxJ: Math.max(bounds.maxJ, corner.j)
353
+ } : {
354
+ minI: corner.i,
355
+ maxI: corner.i,
356
+ minJ: corner.j,
357
+ maxJ: corner.j
358
+ };
359
+ }
360
+ const ordered = (groups, by) => [...groups.entries()].sort(([a], [b]) => a - b).map(([, group]) => group.sort((p, q) => nodes[p][by] - nodes[q][by]));
361
+ return {
362
+ nodes,
363
+ byIndex,
364
+ rows: ordered(rowMap, "j"),
365
+ cols: ordered(colMap, "i"),
366
+ bounds
367
+ };
368
+ }
369
+ /**
370
+ * The edges between neighbouring corners of a grid: `(i, j)` to `(i, j + 1)` are the row edges,
371
+ * `(i, j)` to `(i + 1, j)` the column edges. A missed corner leaves a gap, never a long edge.
372
+ * It is `latticeEdges` from `@vitavision/stage2d` with positions attached.
373
+ *
374
+ * @param grid - From `cornerGrid`.
375
+ * @returns The two edge lists.
376
+ */
377
+ function gridEdges(grid) {
378
+ const rowEdges = [];
379
+ const colEdges = [];
380
+ for (const edge of latticeEdges(grid.nodes)) {
381
+ const a = grid.nodes[edge.a];
382
+ const b = grid.nodes[edge.b];
383
+ (edge.axis === "j" ? rowEdges : colEdges).push({
384
+ a: a.id,
385
+ b: b.id,
386
+ x1: a.x,
387
+ y1: a.y,
388
+ x2: b.x,
389
+ y2: b.y
390
+ });
391
+ }
392
+ return {
393
+ rowEdges,
394
+ colEdges
395
+ };
396
+ }
397
+ /**
398
+ * The id of the corner at each lattice position, to map a board cell back to an app's feature.
399
+ *
400
+ * @param corners - The detected corners.
401
+ * @returns Ids by `gridKey(i, j)`. A corner without an integer index is left out; the first of two sharing a position wins.
402
+ */
403
+ function idByGrid(corners) {
404
+ const map = /* @__PURE__ */ new Map();
405
+ for (const corner of corners) {
406
+ if (!isGridCorner(corner)) continue;
407
+ const key = gridKey(corner.i, corner.j);
408
+ if (!map.has(key)) map.set(key, corner.id);
409
+ }
410
+ return map;
411
+ }
412
+ /**
413
+ * The markers as polygons, with their centres.
414
+ *
415
+ * @param markers - The detected markers.
416
+ * @returns A polygon per marker that has at least three finite vertices; the others are dropped.
417
+ */
418
+ function markerPolygons(markers) {
419
+ const out = [];
420
+ for (const marker of markers) {
421
+ const n = marker.corners.length;
422
+ if (n < 6 || n % 2 !== 0 || !marker.corners.every(Number.isFinite)) continue;
423
+ let sx = 0;
424
+ let sy = 0;
425
+ for (let k = 0; k < n; k += 2) {
426
+ sx += marker.corners[k];
427
+ sy += marker.corners[k + 1];
428
+ }
429
+ const polygon = {
430
+ id: marker.id,
431
+ points: [...marker.corners],
432
+ centre: {
433
+ x: sx / (n / 2),
434
+ y: sy / (n / 2)
435
+ }
436
+ };
437
+ if (marker.label !== void 0) polygon.label = marker.label;
438
+ out.push(polygon);
439
+ }
440
+ return out;
441
+ }
442
+ //#endregion
443
+ //#region src/model.ts
444
+ /** Every `TargetKind`. */
445
+ const TARGET_KINDS = [
446
+ "chessboard",
447
+ "charuco",
448
+ "markerboard",
449
+ "puzzleboard",
450
+ "ringgrid",
451
+ "corners",
452
+ "circles"
453
+ ];
454
+ /** The kinds whose corners form a lattice, so their neighbours are joined by edges. */
455
+ const LATTICE_KINDS = /* @__PURE__ */ new Set([
456
+ "chessboard",
457
+ "charuco",
458
+ "markerboard",
459
+ "puzzleboard"
460
+ ]);
461
+ /**
462
+ * Whether a detection of this kind draws lattice edges between corner neighbours.
463
+ *
464
+ * @param kind - The detection's kind.
465
+ * @returns `true` for the four calibration boards, `false` for loose corners, circles and rings.
466
+ */
467
+ function isLatticeKind(kind) {
468
+ return LATTICE_KINDS.has(kind);
469
+ }
470
+ //#endregion
471
+ //#region src/layerItems.ts
472
+ /** The label of a corner: its own, else the lattice index on a board, else the id. */
473
+ function cornerLabel(corner, lattice) {
474
+ if (corner.label !== void 0) return corner.label;
475
+ if (lattice && Number.isInteger(corner.i) && Number.isInteger(corner.j)) return `${corner.i},${corner.j}`;
476
+ return String(corner.id);
477
+ }
478
+ /**
479
+ * The nodes of the corner layer.
480
+ *
481
+ * A corner with an `angle` is a `directed` marker (its edge directions, one or two), any other a
482
+ * `plus`. On a board kind the lattice indices are kept, so `GridLayer` joins neighbours; on any
483
+ * other kind they are `NaN`, which `latticeEdges` reads as "not part of a lattice", so no edge is
484
+ * drawn.
485
+ *
486
+ * @param detection - The detection.
487
+ * @returns One node per corner, in order.
488
+ */
489
+ function cornerNodes(detection) {
490
+ const lattice = isLatticeKind(detection.kind);
491
+ return (detection.corners ?? []).map((corner) => {
492
+ const node = {
493
+ id: corner.id,
494
+ x: corner.x,
495
+ y: corner.y,
496
+ i: lattice && Number.isInteger(corner.i) ? corner.i : NaN,
497
+ j: lattice && Number.isInteger(corner.j) ? corner.j : NaN,
498
+ label: cornerLabel(corner, lattice)
499
+ };
500
+ if (corner.angle !== void 0) {
501
+ node.kind = "directed";
502
+ node.angle = packAxes(corner.angle, corner.angle2);
503
+ }
504
+ return node;
505
+ });
506
+ }
507
+ /**
508
+ * The regions of the marker layer: each marker's quad, labelled with its text or its id.
509
+ *
510
+ * @param detection - The detection.
511
+ * @returns One area per marker with a usable quad.
512
+ */
513
+ function markerAreas(detection) {
514
+ return markerPolygons(detection.markers ?? []).map((polygon) => ({
515
+ id: polygon.id,
516
+ points: polygon.points,
517
+ label: polygon.label ?? String(polygon.id)
518
+ }));
519
+ }
520
+ /** The label of a circle: its own, else `(i, j)` when it matched a cell. */
521
+ function circleLabel(circle) {
522
+ if (circle.label !== void 0) return circle.label;
523
+ return Number.isInteger(circle.i) && Number.isInteger(circle.j) ? `(${circle.i}, ${circle.j})` : void 0;
524
+ }
525
+ /**
526
+ * The points of the circle layer. Polarity picks the glyph: `circle-white` is a hollow ring,
527
+ * `circle-black` a ring with a dot.
528
+ *
529
+ * @param detection - The detection.
530
+ * @returns One point per circle.
531
+ */
532
+ function circlePoints(detection) {
533
+ return (detection.circles ?? []).map((circle) => {
534
+ const item = {
535
+ id: circle.id,
536
+ x: circle.x,
537
+ y: circle.y,
538
+ kind: `circle-${circle.polarity}`
539
+ };
540
+ const label = circleLabel(circle);
541
+ if (label !== void 0) item.label = label;
542
+ return item;
543
+ });
544
+ }
545
+ /**
546
+ * The points of the ring layer: a `plus` at each centre, picked anywhere inside the outer ellipse
547
+ * (`pickRadius` is the larger semi-axis), labelled with the ring's text or its id.
548
+ *
549
+ * @param rings - The rings.
550
+ * @returns One point per ring.
551
+ */
552
+ function ringCentres(rings) {
553
+ return rings.map((ring) => ({
554
+ id: ring.id,
555
+ x: ring.x,
556
+ y: ring.y,
557
+ kind: "plus",
558
+ pickRadius: Math.max(ring.outer.rx, ring.outer.ry),
559
+ label: ring.label ?? String(ring.id)
560
+ }));
561
+ }
562
+ /**
563
+ * The ellipses of the rings' two edges. The outer is `feature`, the inner `model` (a fitted
564
+ * second edge), and the smaller inner one is told from the outer by size as well as by colour.
565
+ *
566
+ * @param rings - The rings.
567
+ * @returns The outer ellipses, and the inner ones of the rings that have one.
568
+ */
569
+ function ringEllipses(rings) {
570
+ const outer = [];
571
+ const inner = [];
572
+ for (const ring of rings) {
573
+ outer.push({
574
+ id: ring.id,
575
+ x: ring.x,
576
+ y: ring.y,
577
+ rx: ring.outer.rx,
578
+ ry: ring.outer.ry,
579
+ angle: ring.outer.angle,
580
+ role: "feature"
581
+ });
582
+ if (ring.inner) inner.push({
583
+ id: ring.id,
584
+ x: ring.x,
585
+ y: ring.y,
586
+ rx: ring.inner.rx,
587
+ ry: ring.inner.ry,
588
+ angle: ring.inner.angle,
589
+ role: "model"
590
+ });
591
+ }
592
+ return {
593
+ outer,
594
+ inner
595
+ };
596
+ }
597
+ /** Opacity of a dot at confidence 0 and at confidence 1: a weak bit is visible, a sure one is solid. */
598
+ const BIT_OPACITY_MIN = .35;
599
+ /**
600
+ * The dots of the edge-bit layer: bit 1 is a solid `feature` circle, bit 0 a dashed `model`
601
+ * one, and the opacity runs from 35 % at confidence 0 to 100 % at confidence 1.
602
+ *
603
+ * @param bits - The edge bits.
604
+ * @returns One ellipse (a circle) per bit.
605
+ */
606
+ function edgeBitEllipses(bits) {
607
+ return bits.map((bit) => ({
608
+ id: bit.id,
609
+ x: bit.x,
610
+ y: bit.y,
611
+ rx: bit.radius,
612
+ ry: bit.radius,
613
+ role: bit.bit === 1 ? "feature" : "model",
614
+ dashed: bit.bit === 0,
615
+ opacity: BIT_OPACITY_MIN + .65 * Math.min(1, Math.max(0, bit.confidence))
616
+ }));
617
+ }
618
+ //#endregion
619
+ //#region src/TargetOverlay.tsx
620
+ /**
621
+ * A calibration-target detection over the image: one component for a chessboard, ChArUco,
622
+ * marker board, PuzzleBoard, ring grid or a loose set of corners.
623
+ *
624
+ * It replaces the per-board overlays of vitavision (`ChessboardOverlay`, `CharucoOverlay`,
625
+ * `MarkerboardOverlay`, `PuzzleboardOverlay`) and the glyph components behind them. Each part of
626
+ * a `TargetDetection` goes to the stage2d layer that fits it, so a detection of thousands of
627
+ * items is a few dozen DOM nodes (ADR-0004), and the pointer is resolved by the stage's hit-test
628
+ * registry, not the DOM:
629
+ *
630
+ * | Part | Layer | Glyph (visual-language §5) |
631
+ * |---|---|---|
632
+ * | `corners` | `GridLayer` | plus; edge directions when `angle` is set; lattice edges and `i,j` labels |
633
+ * | `markers` | `AreaSet` | quad outline and 12 % fill, corner 0 ticked, id inside |
634
+ * | `circles` | `PointSet` | ring; a centre dot marks black |
635
+ * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
636
+ * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
637
+ */
638
+ /** The ids of each part, to route a hovered or selected id to the layers that have it. */
639
+ function idsByPart(detection) {
640
+ const ids = (items) => new Set((items ?? []).map((item) => item.id));
641
+ return {
642
+ corner: ids(detection.corners),
643
+ marker: ids(detection.markers),
644
+ circle: ids(detection.circles),
645
+ ring: ids(detection.rings)
646
+ };
647
+ }
648
+ /** The `dimmed` prop as the predicate the layers take, or `undefined` for none. */
649
+ function dimPredicate(dimmed) {
650
+ if (dimmed === void 0 || dimmed === false) return void 0;
651
+ if (dimmed === true) return () => true;
652
+ if (typeof dimmed === "function") return dimmed;
653
+ const set = new Set(dimmed);
654
+ return (id) => set.has(id);
655
+ }
656
+ /**
657
+ * A detected calibration target inside an `ImageStage`.
658
+ *
659
+ * - **Batched**: one path per appearance in each layer, picking through spatial indices. Labels
660
+ * appear only where items are 24 screen px apart, at most 200 at a time.
661
+ * - **States**: hover 2 px, selected 2.5 px in the selection colour with a ring, dimmed at 35 %.
662
+ * - **Colour**: roles only (`feature`, `model`, `structure`, `selection`). Scores are never drawn
663
+ * as red, amber or green; polarity and bits are carried by shape (hollow or dotted, solid or
664
+ * dashed), not by hue.
665
+ * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
666
+ * between layers (a corner, then the marker under it) without a flicker: the change is reported
667
+ * once.
668
+ *
669
+ * The layers it renders carry their own accessible names ("Corners: 54 points, 0 selected").
670
+ */
671
+ function TargetOverlay({ detection, showEdges = true, showLabels = true, hoveredId, selectedIds, onHoverChange, onItemPress, dimmed, layerIdPrefix }) {
672
+ const nodes = useMemo(() => cornerNodes(detection), [detection]);
673
+ const areas = useMemo(() => markerAreas(detection), [detection]);
674
+ const circles = useMemo(() => circlePoints(detection), [detection]);
675
+ const rings = detection.rings;
676
+ const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);
677
+ const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);
678
+ const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);
679
+ const ids = useMemo(() => idsByPart(detection), [detection]);
680
+ const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);
681
+ const selected = useMemo(() => {
682
+ const pick = (part) => new Set([...selectedSet].filter((id) => ids[part].has(id)));
683
+ return {
684
+ corner: pick("corner"),
685
+ marker: pick("marker"),
686
+ circle: pick("circle"),
687
+ ring: pick("ring")
688
+ };
689
+ }, [selectedSet, ids]);
690
+ const isDimmed = useMemo(() => dimPredicate(dimmed), [dimmed]);
691
+ const [ownHover, setOwnHover] = useState(null);
692
+ const hoverRef = useRef(null);
693
+ const reportedRef = useRef(null);
694
+ const scheduledRef = useRef(false);
695
+ const onHoverChangeRef = useRef(onHoverChange);
696
+ useLayoutEffect(() => {
697
+ onHoverChangeRef.current = onHoverChange;
698
+ });
699
+ const hoverFrom = useCallback((part) => (id) => {
700
+ if (id !== null) hoverRef.current = {
701
+ id,
702
+ part
703
+ };
704
+ else if (hoverRef.current?.part === part) hoverRef.current = null;
705
+ setOwnHover(hoverRef.current);
706
+ if (scheduledRef.current) return;
707
+ scheduledRef.current = true;
708
+ queueMicrotask(() => {
709
+ scheduledRef.current = false;
710
+ const now = hoverRef.current;
711
+ const before = reportedRef.current;
712
+ if (now?.id === before?.id && now?.part === before?.part) return;
713
+ reportedRef.current = now;
714
+ onHoverChangeRef.current?.(now);
715
+ });
716
+ }, []);
717
+ const hoverOf = (part) => {
718
+ if (hoveredId !== void 0) return hoveredId !== null && ids[part].has(hoveredId) ? hoveredId : null;
719
+ return ownHover?.part === part ? ownHover.id : null;
720
+ };
721
+ const pressFrom = (part) => onItemPress ? (id, event) => onItemPress({
722
+ id,
723
+ part
724
+ }, event) : void 0;
725
+ const layerId = (name) => layerIdPrefix === void 0 ? void 0 : `${layerIdPrefix}-${name}`;
726
+ const hasCorners = nodes.length > 0;
727
+ const hasMarkers = areas.length > 0;
728
+ const hasCircles = circles.length > 0;
729
+ const hasRings = ringPoints.length > 0;
730
+ const edgeStyle = { visible: showEdges };
731
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
732
+ hasMarkers && /* @__PURE__ */ jsx(AreaSet, {
733
+ items: areas,
734
+ firstVertexTick: true,
735
+ labels: showLabels,
736
+ hoveredId: hoverOf("marker"),
737
+ selectedIds: selected.marker,
738
+ dimmed: isDimmed,
739
+ onHoverChange: hoverFrom("marker"),
740
+ onItemPress: pressFrom("marker"),
741
+ layerId: layerId("markers"),
742
+ label: "Markers"
743
+ }),
744
+ bits.length > 0 && /* @__PURE__ */ jsx(EllipseSet, {
745
+ items: bits,
746
+ minRadius: 3,
747
+ dimmed: isDimmed
748
+ }),
749
+ hasRings && /* @__PURE__ */ jsxs(Fragment, { children: [
750
+ /* @__PURE__ */ jsx(EllipseSet, {
751
+ items: ringShapes.outer,
752
+ hoveredId: hoverOf("ring"),
753
+ selectedIds: selected.ring,
754
+ dimmed: isDimmed
755
+ }),
756
+ ringShapes.inner.length > 0 && /* @__PURE__ */ jsx(EllipseSet, {
757
+ items: ringShapes.inner,
758
+ role: "model",
759
+ hoveredId: hoverOf("ring"),
760
+ selectedIds: selected.ring,
761
+ dimmed: isDimmed
762
+ }),
763
+ /* @__PURE__ */ jsx(PointSet, {
764
+ items: ringPoints,
765
+ kind: "plus",
766
+ markers: TARGET_MARKERS,
767
+ labels: showLabels,
768
+ hoveredId: hoverOf("ring"),
769
+ selectedIds: selected.ring,
770
+ dimmed: isDimmed,
771
+ onHoverChange: hoverFrom("ring"),
772
+ onItemPress: pressFrom("ring"),
773
+ layerId: layerId("rings"),
774
+ label: "Rings"
775
+ })
776
+ ] }),
777
+ hasCorners && /* @__PURE__ */ jsx(GridLayer, {
778
+ nodes,
779
+ markers: TARGET_MARKERS,
780
+ edges: {
781
+ i: edgeStyle,
782
+ j: {
783
+ ...edgeStyle,
784
+ dashed: true
785
+ }
786
+ },
787
+ labels: showLabels,
788
+ hoveredId: hoverOf("corner"),
789
+ selectedIds: selected.corner,
790
+ dimmed: isDimmed,
791
+ onHoverChange: hoverFrom("corner"),
792
+ onItemPress: pressFrom("corner"),
793
+ layerId: layerId("corners"),
794
+ label: "Corners"
795
+ }),
796
+ hasCircles && /* @__PURE__ */ jsx(PointSet, {
797
+ items: circles,
798
+ markers: TARGET_MARKERS,
799
+ labels: showLabels,
800
+ hoveredId: hoverOf("circle"),
801
+ selectedIds: selected.circle,
802
+ dimmed: isDimmed,
803
+ onHoverChange: hoverFrom("circle"),
804
+ onItemPress: pressFrom("circle"),
805
+ layerId: layerId("circles"),
806
+ label: "Circles"
807
+ })
808
+ ] });
809
+ }
810
+ //#endregion
811
+ //#region src/puzzleboard.ts
812
+ /**
813
+ * PuzzleBoard edge bits: from a decoder's observed edges to the dots the overlay draws.
814
+ *
815
+ * A PuzzleBoard encodes its position in the bumps along the edges between corners. The decoder
816
+ * reports each observed edge in the image's own local frame (`row`, `col`), and the alignment
817
+ * that maps that frame into the board's master frame, which is periodic with period 501. The
818
+ * corners are labelled with master indices, so an edge's two corners are found by mapping its
819
+ * local end points through the alignment, modulo the period. This is the arithmetic of
820
+ * vitavision's `PuzzleboardOverlay.buildEdgeMarkers`, as a pure function over structural types,
821
+ * so no detector package is imported.
822
+ *
823
+ * Pure: no React, no DOM.
824
+ */
825
+ /** The period of the PuzzleBoard master pattern. */
826
+ const PUZZLEBOARD_PERIOD = 501;
827
+ /** `value` modulo `period`, in `[0, period)` for any sign. */
828
+ function wrap(value, period) {
829
+ return (value % period + period) % period;
830
+ }
831
+ /**
832
+ * The edge bits of a PuzzleBoard decode, placed on the image.
833
+ *
834
+ * An edge is dropped when either of its corners was not detected. Each dot sits at the midpoint
835
+ * of its edge with a radius of a quarter of the edge's length (the bump is about half an edge
836
+ * wide); its opacity is the app's to take from `confidence`.
837
+ *
838
+ * @param edges - The observed edges.
839
+ * @param corners - The labelled corners, whose `i` and `j` are **master** indices.
840
+ * @param alignment - The local-to-master map.
841
+ * @param period - The master pattern's period. Defaults to 501.
842
+ * @returns One `TargetEdgeBit` per edge whose corners were both found, in input order. Empty when there is no alignment.
843
+ */
844
+ function edgeBitsFromPuzzleboard(edges, corners, alignment, period = 501) {
845
+ if (!alignment || edges.length === 0 || corners.length === 0) return [];
846
+ const byMaster = /* @__PURE__ */ new Map();
847
+ for (const corner of corners) if (Number.isInteger(corner.i) && Number.isInteger(corner.j)) byMaster.set(gridKey(corner.i, corner.j), corner);
848
+ const { a, b, c, d } = alignment.transform;
849
+ const [tx, ty] = alignment.translation;
850
+ const toMaster = (i, j) => gridKey(wrap(a * i + b * j + tx, period), wrap(c * i + d * j + ty, period));
851
+ const out = [];
852
+ edges.forEach((edge, index) => {
853
+ const from = byMaster.get(toMaster(edge.col, edge.row));
854
+ const to = byMaster.get(edge.orientation === "horizontal" ? toMaster(edge.col + 1, edge.row) : toMaster(edge.col, edge.row + 1));
855
+ if (!from || !to) return;
856
+ out.push({
857
+ id: `${edge.orientation}-${edge.row}-${edge.col}-${index}`,
858
+ x: .5 * (from.x + to.x),
859
+ y: .5 * (from.y + to.y),
860
+ radius: .25 * Math.hypot(to.x - from.x, to.y - from.y),
861
+ bit: edge.bit,
862
+ confidence: Math.min(1, Math.max(0, edge.confidence))
863
+ });
864
+ });
865
+ return out;
866
+ }
867
+ //#endregion
868
+ export { EllipseSet, PUZZLEBOARD_PERIOD, TARGET_KINDS, TARGET_MARKERS, TargetOverlay, circlePoints, cornerGrid, cornerNodes, edgeBitEllipses, edgeBitsFromPuzzleboard, ellipsePath, gridEdges, gridKey, idByGrid, isLatticeKind, markerAreas, markerPolygons, packAxes, ringCentres, ringEllipses, unpackAxes };
869
+
870
+ //# sourceMappingURL=index.js.map