@vitavision/overlays 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,29 +5,24 @@
5
5
  * It replaces the per-board overlays of vitavision (`ChessboardOverlay`, `CharucoOverlay`,
6
6
  * `MarkerboardOverlay`, `PuzzleboardOverlay`) and the glyph components behind them. Each part of
7
7
  * a `TargetDetection` goes to the stage2d layer that fits it, so a detection of thousands of
8
- * items is a few dozen DOM nodes (ADR-0004), and the pointer is resolved by the stage's hit-test
8
+ * items is a few dozen DOM nodes and the pointer is resolved by the stage's hit-test
9
9
  * registry, not the DOM:
10
10
  *
11
- * | Part | Layer | Glyph (visual-language §5) |
11
+ * | Part | Layer | Glyph |
12
12
  * |---|---|---|
13
13
  * | `corners` | `GridLayer` | plus; edge directions when `angle` is set; lattice edges and `i,j` labels |
14
14
  * | `markers` | `AreaSet` | quad outline and 12 % fill, corner 0 ticked, id inside |
15
15
  * | `circles` | `PointSet` | ring; a centre dot marks black |
16
16
  * | `rings` | `PointSet` + `EllipseSet` | fitted outer and inner ellipse, plus at the centre |
17
17
  * | `edgeBits` | `EllipseSet` | dot on the edge: solid for 1, dashed for 0, opacity from confidence |
18
+ * | corners' `cov` | `EllipseSet` | with `uncertainty`: the 1σ ellipse × the scale, in `model` |
18
19
  */
19
20
 
20
- import {
21
- EllipseSet,
22
- GridLayer,
23
- AreaSet,
24
- PointSet,
25
- type StagePointerEvent,
26
- } from "@vitavision/stage2d";
21
+ import { EllipseSet, GridLayer, AreaSet, PointSet, type StagePointerEvent } from "@vitavision/stage2d";
27
22
  import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
28
23
 
29
24
  import { TARGET_MARKERS } from "./glyphs";
30
- import { circlePoints, cornerNodes, edgeBitEllipses, markerAreas, ringCentres, ringEllipses } from "./layerItems";
25
+ import { circlePoints, cornerNodes, edgeBitEllipses, markerAreas, ringCentres, ringEllipses, uncertaintyEllipses } from "./layerItems";
31
26
  import type { TargetDetection, TargetHit, TargetId, TargetPart } from "./model";
32
27
 
33
28
  /** Props of `TargetOverlay`. */
@@ -61,6 +56,17 @@ export interface TargetOverlayProps {
61
56
  * opacity. They still take hover and presses. Pass a stable value: a new one re-batches.
62
57
  */
63
58
  dimmed?: boolean | Iterable<TargetId> | ((id: TargetId) => boolean) | undefined;
59
+ /**
60
+ * Draw each corner's position covariance (`cov`) as its 1σ ellipse with both semi-axes
61
+ * multiplied by `scale`, in the `model` role, under the corners. Off by default.
62
+ *
63
+ * A detector's σ is a small fraction of a pixel, so the ellipses are drawn magnified: the
64
+ * `scale` is the app's to choose and to print beside the image ("ellipses ×40"), as a
65
+ * residual's gain is. Their shape and orientation are the data's. A corner with no covariance,
66
+ * or one that is not positive definite, gets none. The ellipses take the corner's hover,
67
+ * selection and dimming, and are not picked themselves.
68
+ */
69
+ uncertainty?: { scale: number } | undefined;
64
70
  /** Prefix of the hit-test layer ids (`<prefix>-corners`, `-markers`, `-circles`, `-rings`). Defaults to generated ids. */
65
71
  layerIdPrefix?: string | undefined;
66
72
  }
@@ -97,6 +103,8 @@ function dimPredicate(dimmed: TargetOverlayProps["dimmed"]): ((id: TargetId) =>
97
103
  * - **Callbacks** report `{ id, part }` with the id from the detection. A press and a hover move
98
104
  * between layers (a corner, then the marker under it) without a flicker: the change is reported
99
105
  * once.
106
+ * - **Uncertainty** (opt-in, `uncertainty`): each corner's covariance as a 1σ ellipse × the
107
+ * given scale, under the corners.
100
108
  *
101
109
  * The layers it renders carry their own accessible names ("Corners: 54 points, 0 selected").
102
110
  */
@@ -109,6 +117,7 @@ export function TargetOverlay({
109
117
  onHoverChange,
110
118
  onItemPress,
111
119
  dimmed,
120
+ uncertainty,
112
121
  layerIdPrefix,
113
122
  }: TargetOverlayProps) {
114
123
  const nodes = useMemo(() => cornerNodes(detection), [detection]);
@@ -118,6 +127,11 @@ export function TargetOverlay({
118
127
  const ringPoints = useMemo(() => ringCentres(rings ?? []), [rings]);
119
128
  const ringShapes = useMemo(() => ringEllipses(rings ?? []), [rings]);
120
129
  const bits = useMemo(() => edgeBitEllipses(detection.edgeBits ?? []), [detection.edgeBits]);
130
+ const uncertaintyScale = uncertainty?.scale;
131
+ const covEllipses = useMemo(
132
+ () => (uncertaintyScale === undefined ? [] : uncertaintyEllipses(detection.corners ?? [], uncertaintyScale)),
133
+ [detection.corners, uncertaintyScale],
134
+ );
121
135
  const ids = useMemo(() => idsByPart(detection), [detection]);
122
136
 
123
137
  // Selection and hover are by id; each layer is given the ids it owns, so its count is right.
@@ -139,21 +153,24 @@ export function TargetOverlay({
139
153
  useLayoutEffect(() => {
140
154
  onHoverChangeRef.current = onHoverChange;
141
155
  });
142
- const hoverFrom = useCallback((part: TargetPart) => (id: TargetId | null) => {
143
- if (id !== null) hoverRef.current = { id, part };
144
- else if (hoverRef.current?.part === part) hoverRef.current = null;
145
- setOwnHover(hoverRef.current);
146
- if (scheduledRef.current) return;
147
- scheduledRef.current = true;
148
- queueMicrotask(() => {
149
- scheduledRef.current = false;
150
- const now = hoverRef.current;
151
- const before = reportedRef.current;
152
- if (now?.id === before?.id && now?.part === before?.part) return;
153
- reportedRef.current = now;
154
- onHoverChangeRef.current?.(now);
155
- });
156
- }, []);
156
+ const hoverFrom = useCallback(
157
+ (part: TargetPart) => (id: TargetId | null) => {
158
+ if (id !== null) hoverRef.current = { id, part };
159
+ else if (hoverRef.current?.part === part) hoverRef.current = null;
160
+ setOwnHover(hoverRef.current);
161
+ if (scheduledRef.current) return;
162
+ scheduledRef.current = true;
163
+ queueMicrotask(() => {
164
+ scheduledRef.current = false;
165
+ const now = hoverRef.current;
166
+ const before = reportedRef.current;
167
+ if (now?.id === before?.id && now?.part === before?.part) return;
168
+ reportedRef.current = now;
169
+ onHoverChangeRef.current?.(now);
170
+ });
171
+ },
172
+ [],
173
+ );
157
174
  const hoverOf = (part: TargetPart): TargetId | null => {
158
175
  if (hoveredId !== undefined) return hoveredId !== null && ids[part].has(hoveredId) ? hoveredId : null;
159
176
  return ownHover?.part === part ? ownHover.id : null;
@@ -190,7 +207,14 @@ export function TargetOverlay({
190
207
  <>
191
208
  <EllipseSet items={ringShapes.outer} hoveredId={hoverOf("ring")} selectedIds={selected.ring} dimmed={isDimmed} pickable={false} />
192
209
  {ringShapes.inner.length > 0 && (
193
- <EllipseSet items={ringShapes.inner} role="model" hoveredId={hoverOf("ring")} selectedIds={selected.ring} dimmed={isDimmed} pickable={false} />
210
+ <EllipseSet
211
+ items={ringShapes.inner}
212
+ role="model"
213
+ hoveredId={hoverOf("ring")}
214
+ selectedIds={selected.ring}
215
+ dimmed={isDimmed}
216
+ pickable={false}
217
+ />
194
218
  )}
195
219
  <PointSet
196
220
  items={ringPoints}
@@ -207,6 +231,17 @@ export function TargetOverlay({
207
231
  />
208
232
  </>
209
233
  )}
234
+ {covEllipses.length > 0 && (
235
+ <EllipseSet
236
+ items={covEllipses}
237
+ role="model"
238
+ hoveredId={hoverOf("corner")}
239
+ selectedIds={selected.corner}
240
+ dimmed={isDimmed}
241
+ pickable={false}
242
+ label={`Position uncertainty: 1σ ellipses ×${uncertaintyScale}`}
243
+ />
244
+ )}
210
245
  {hasCorners && (
211
246
  <GridLayer
212
247
  nodes={nodes}
@@ -0,0 +1,361 @@
1
+ /**
2
+ * calib-targets results to `TargetDetection`: the one mapping from what the
3
+ * `@vitavision/calib-targets` WASM detectors return to what `TargetOverlay` draws.
4
+ *
5
+ * The input types below are the minimal structure the mapping reads, written to be satisfied by
6
+ * the package's own result types (`ChessboardDetection`, `CharucoDetection`,
7
+ * `MarkerBoardDetection`, `PuzzleBoardDetection`, `Corner`, and the `diagnose_*` payloads), so this
8
+ * package takes no dependency on it. Every field the mapping does not read is ignored, and every
9
+ * field a newer calib-targets adds is optional here, so results with and without it both fit.
10
+ *
11
+ * Pure: no React, no DOM.
12
+ */
13
+
14
+ import type { TargetCircle, TargetCorner, TargetDetection, TargetKind, TargetMarker } from "./model";
15
+ import { edgeBitsFromPuzzleboard, type PuzzleboardEdge } from "./puzzleboard";
16
+
17
+ /** An image point `[x, y]`, pixels with the centre of pixel `i` at `i` (calib-targets' `Point2`). */
18
+ export type CalibTargetsPoint = readonly [x: number, y: number];
19
+
20
+ /** A position covariance, image pixels squared (calib-targets' `position_covariance`). */
21
+ export interface CalibTargetsCovariance {
22
+ /** Variance along x. */
23
+ xx: number;
24
+ /** Covariance of x and y. */
25
+ xy: number;
26
+ /** Variance along y. */
27
+ yy: number;
28
+ }
29
+
30
+ /** An integer lattice coordinate (calib-targets' `Coord`): `u` along the first board axis, `v` the second. */
31
+ export interface CalibTargetsCoord {
32
+ /** First axis, rightwards on the board. */
33
+ u: number;
34
+ /** Second axis, downwards on the board. */
35
+ v: number;
36
+ }
37
+
38
+ /** A labelled board corner: what `ChessboardCorner`, `CharucoCorner`, `MarkerBoardCorner` and `PuzzleBoardCorner` share. */
39
+ export interface CalibTargetsLabeledCorner {
40
+ /** Sub-pixel image position. */
41
+ position: CalibTargetsPoint;
42
+ /** Lattice label; `null` for a corner with no place on the board. */
43
+ grid: CalibTargetsCoord | null;
44
+ /** The detector's score, higher is better. */
45
+ score: number;
46
+ /** Position covariance, when the detector reports one. */
47
+ position_covariance?: CalibTargetsCovariance | null | undefined;
48
+ }
49
+
50
+ /** One axis estimate of a raw corner (calib-targets' `AxisEstimate`). */
51
+ export interface CalibTargetsAxis {
52
+ /** Direction of the axis, radians in the image frame (clockwise on screen). */
53
+ angle: number;
54
+ }
55
+
56
+ /** A raw ChESS corner, as `detect_corners` returns it (calib-targets' `Corner`). */
57
+ export interface CalibTargetsCorner {
58
+ /** Sub-pixel image position. */
59
+ position: CalibTargetsPoint;
60
+ /** The two grid axes through the corner. */
61
+ axes: readonly [CalibTargetsAxis, CalibTargetsAxis];
62
+ /** Corner response, higher is stronger. */
63
+ strength: number;
64
+ /** Position covariance, when the detector reports one. */
65
+ position_covariance?: CalibTargetsCovariance | null | undefined;
66
+ }
67
+
68
+ /** A chessboard detection (`ChessboardDetection`). */
69
+ export interface CalibTargetsChessboardDetection {
70
+ /** The labelled corners. */
71
+ corners: readonly CalibTargetsLabeledCorner[];
72
+ }
73
+
74
+ /** A decoded ArUco marker of a ChArUco detection (`MarkerDetection`). */
75
+ export interface CalibTargetsMarker {
76
+ /** The marker's dictionary id. */
77
+ id: number;
78
+ /** Its four corners in the image, in the marker's own order; `null` when they were not projected. */
79
+ corners_img: readonly [CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint, CalibTargetsPoint] | null;
80
+ }
81
+
82
+ /** A ChArUco detection (`CharucoDetection`). */
83
+ export interface CalibTargetsCharucoDetection {
84
+ /** The labelled corners. */
85
+ corners: readonly CalibTargetsLabeledCorner[];
86
+ /** The markers consistent with the board alignment. */
87
+ markers: readonly CalibTargetsMarker[];
88
+ }
89
+
90
+ /** A checkerboard marker board detection (`MarkerBoardDetection`). */
91
+ export interface CalibTargetsMarkerBoardDetection {
92
+ /** The labelled corners. */
93
+ corners: readonly CalibTargetsLabeledCorner[];
94
+ }
95
+
96
+ /** A scored circle hypothesis of a marker board (`CircleCandidate`). */
97
+ export interface CalibTargetsCircleCandidate {
98
+ /** Centre of the circle in the image. */
99
+ center_img: CalibTargetsPoint;
100
+ }
101
+
102
+ /** A board circle paired with a detected one (`CircleMatch`). */
103
+ export interface CalibTargetsCircleMatch {
104
+ /** The circle the board layout expects: its cell and printed polarity. */
105
+ expected: { cell: { i: number; j: number }; polarity: "white" | "black" };
106
+ /** Index into `circle_candidates` of the circle that matched it, or `null` for none. */
107
+ matched_index: number | null;
108
+ }
109
+
110
+ /** The part of `diagnose_marker_board`'s `diagnostics` the overlay draws (`MarkerBoardDiagnostics`). */
111
+ export interface CalibTargetsMarkerBoardDiagnostics {
112
+ /** The circle hypotheses. */
113
+ circle_candidates: readonly CalibTargetsCircleCandidate[];
114
+ /** The board's circles and the candidates they matched. */
115
+ circle_matches: readonly CalibTargetsCircleMatch[];
116
+ }
117
+
118
+ /** A grid alignment (`GridAlignment`): `master = matrix · local + translation`. */
119
+ export interface CalibTargetsAlignment {
120
+ /** Row-major integer matrix, applied to local `(u, v)` before the translation. */
121
+ matrix: readonly [readonly [number, number], readonly [number, number]];
122
+ /** Integer translation, grid units. */
123
+ translation: readonly [number, number];
124
+ }
125
+
126
+ /** A PuzzleBoard detection (`PuzzleBoardDetection`); its corners carry master labels. */
127
+ export interface CalibTargetsPuzzleBoardDetection {
128
+ /** The labelled corners, `grid` in the master frame. */
129
+ corners: readonly CalibTargetsLabeledCorner[];
130
+ /** The map from the decoder's local frame to the master frame. */
131
+ alignment: CalibTargetsAlignment;
132
+ }
133
+
134
+ /** One observed edge bit, in the decoder's local frame (`PuzzleBoardObservedEdge`). */
135
+ export interface CalibTargetsObservedEdge {
136
+ /** Row of the edge's first corner. */
137
+ row: number;
138
+ /** Column of the edge's first corner. */
139
+ col: number;
140
+ /** Which neighbour the edge runs to. */
141
+ orientation: "horizontal" | "vertical";
142
+ /** The observed bit, 0 or 1. */
143
+ bit: number;
144
+ /** Per-bit confidence, [0, 1]. */
145
+ confidence: number;
146
+ }
147
+
148
+ /** The part of `diagnose_puzzleboard`'s `diagnostics` the overlay draws (`PuzzleBoardDiagnostics`). */
149
+ export interface CalibTargetsPuzzleBoardDiagnostics {
150
+ /** Every sampled edge, before alignment. */
151
+ observed_edges: readonly CalibTargetsObservedEdge[];
152
+ }
153
+
154
+ /** A PuzzlePole detection: a PuzzleBoard wrapped round a cylinder; `grid` is (axial, around). */
155
+ export interface CalibTargetsPuzzlePoleDetection {
156
+ /** The labelled corners. */
157
+ corners: readonly CalibTargetsLabeledCorner[];
158
+ }
159
+
160
+ /**
161
+ * One calib-targets result, tagged with the detector that produced it.
162
+ *
163
+ * A board detector returns `null` (or, from `diagnose_*`, `undefined`) when it finds nothing;
164
+ * pass that through as `detection` and the result is an empty detection of the same kind.
165
+ * `diagnostics` is the `diagnostics` of the matching `diagnose_*` call: it carries what the plain
166
+ * result does not (the marker-board circles, the PuzzleBoard edge bits). Convert a `diagnose_*`
167
+ * payload to plain objects first if your binding returns `Map`s.
168
+ */
169
+ export type CalibTargetsResult =
170
+ | {
171
+ /** Raw ChESS corners, from `detect_corners`. */
172
+ kind: "corners";
173
+ /** The corners. */
174
+ corners: readonly CalibTargetsCorner[];
175
+ }
176
+ | {
177
+ /** A chessboard, from `detect_chessboard`. */
178
+ kind: "chessboard";
179
+ /** The detection, or `null` when none was found. */
180
+ detection: CalibTargetsChessboardDetection | null | undefined;
181
+ }
182
+ | {
183
+ /** A ChArUco board, from `detect_charuco` or `diagnose_charuco`. */
184
+ kind: "charuco";
185
+ /** The detection, or `null` when none was found. */
186
+ detection: CalibTargetsCharucoDetection | null | undefined;
187
+ }
188
+ | {
189
+ /** A checkerboard marker board, from `detect_marker_board` or `diagnose_marker_board`. */
190
+ kind: "markerboard";
191
+ /** The detection, or `null` when none was found. */
192
+ detection: CalibTargetsMarkerBoardDetection | null | undefined;
193
+ /** `diagnose_marker_board`'s diagnostics, for the matched circles. */
194
+ diagnostics?: CalibTargetsMarkerBoardDiagnostics | null | undefined;
195
+ }
196
+ | {
197
+ /** A PuzzleBoard, from `detect_puzzleboard` or `diagnose_puzzleboard`. */
198
+ kind: "puzzleboard";
199
+ /** The detection, or `null` when none was found. */
200
+ detection: CalibTargetsPuzzleBoardDetection | null | undefined;
201
+ /** `diagnose_puzzleboard`'s diagnostics, for the edge bits. */
202
+ diagnostics?: CalibTargetsPuzzleBoardDiagnostics | null | undefined;
203
+ }
204
+ | {
205
+ /** A PuzzlePole. Drawn as a PuzzleBoard lattice, without edge bits. */
206
+ kind: "puzzlepole";
207
+ /** The detection, or `null` when none was found. */
208
+ detection: CalibTargetsPuzzlePoleDetection | null | undefined;
209
+ };
210
+
211
+ /** The overlay kind of each calib-targets result kind. */
212
+ const OVERLAY_KIND: Readonly<Record<CalibTargetsResult["kind"], TargetKind>> = {
213
+ corners: "corners",
214
+ chessboard: "chessboard",
215
+ charuco: "charuco",
216
+ markerboard: "markerboard",
217
+ puzzleboard: "puzzleboard",
218
+ puzzlepole: "puzzleboard",
219
+ };
220
+
221
+ /** A covariance as `TargetCorner.cov`, or `undefined` when there is none or it is not finite. */
222
+ function covOf(cov: CalibTargetsCovariance | null | undefined): TargetCorner["cov"] {
223
+ if (!cov) return undefined;
224
+ const { xx, xy, yy } = cov;
225
+ return Number.isFinite(xx + xy + yy) ? [xx, xy, yy] : undefined;
226
+ }
227
+
228
+ /** A labelled corner as a `TargetCorner`, id `corner-<index>`; `(u, v)` becomes `(i, j)`. */
229
+ function labeledCorner(corner: CalibTargetsLabeledCorner, index: number): TargetCorner {
230
+ const out: TargetCorner = { id: `corner-${index}`, x: corner.position[0], y: corner.position[1], score: corner.score };
231
+ if (corner.grid) {
232
+ out.i = corner.grid.u;
233
+ out.j = corner.grid.v;
234
+ }
235
+ const cov = covOf(corner.position_covariance);
236
+ if (cov) out.cov = cov;
237
+ return out;
238
+ }
239
+
240
+ /** A raw corner as a `TargetCorner` with both axis directions, id `corner-<index>`, labelled with its index. */
241
+ function rawCorner(corner: CalibTargetsCorner, index: number): TargetCorner {
242
+ const out: TargetCorner = {
243
+ id: `corner-${index}`,
244
+ x: corner.position[0],
245
+ y: corner.position[1],
246
+ score: corner.strength,
247
+ angle: corner.axes[0].angle,
248
+ angle2: corner.axes[1].angle,
249
+ label: String(index),
250
+ };
251
+ const cov = covOf(corner.position_covariance);
252
+ if (cov) out.cov = cov;
253
+ return out;
254
+ }
255
+
256
+ /** The markers with a projected quad, id `marker-<index>`, labelled with the dictionary id. */
257
+ function markersOf(markers: readonly CalibTargetsMarker[]): TargetMarker[] {
258
+ const out: TargetMarker[] = [];
259
+ markers.forEach((marker, index) => {
260
+ if (!marker.corners_img) return;
261
+ out.push({ id: `marker-${index}`, corners: marker.corners_img.flatMap(([x, y]) => [x, y]), label: String(marker.id) });
262
+ });
263
+ return out;
264
+ }
265
+
266
+ /**
267
+ * The matched circles of a marker board, id `circle-<index>` (index into `circle_matches`): at
268
+ * the matched candidate's centre, with the board's cell and printed polarity. An unmatched board
269
+ * circle is not drawn, nor is a candidate no board circle matched.
270
+ */
271
+ function circlesOf(diagnostics: CalibTargetsMarkerBoardDiagnostics): TargetCircle[] {
272
+ const out: TargetCircle[] = [];
273
+ diagnostics.circle_matches.forEach((match, index) => {
274
+ const candidate = match.matched_index === null ? undefined : diagnostics.circle_candidates[match.matched_index];
275
+ if (!candidate) return;
276
+ out.push({
277
+ id: `circle-${index}`,
278
+ x: candidate.center_img[0],
279
+ y: candidate.center_img[1],
280
+ polarity: match.expected.polarity,
281
+ i: match.expected.cell.i,
282
+ j: match.expected.cell.j,
283
+ });
284
+ });
285
+ return out;
286
+ }
287
+
288
+ /** The observed edges as `edgeBitsFromPuzzleboard` takes them: a nonzero bit is 1. */
289
+ function edgesOf(edges: readonly CalibTargetsObservedEdge[]): PuzzleboardEdge[] {
290
+ return edges.map((edge) => ({
291
+ row: edge.row,
292
+ col: edge.col,
293
+ orientation: edge.orientation,
294
+ bit: edge.bit === 0 ? 0 : 1,
295
+ confidence: edge.confidence,
296
+ }));
297
+ }
298
+
299
+ /**
300
+ * The `TargetDetection` of a calib-targets result.
301
+ *
302
+ * - **Kinds.** `chessboard`, `charuco`, `markerboard`, `puzzleboard` and raw `corners` map to the
303
+ * overlay kind of the same name; a `puzzlepole` is drawn as a `puzzleboard` lattice.
304
+ * - **Corners.** Positions pass through unchanged (calib-targets reports the centre of pixel `i`
305
+ * at `i`, as the overlay expects). A labelled corner's grid `(u, v)` becomes `(i, j)`, so a
306
+ * board draws its lattice and labels corners `i,j`. A raw corner draws its two axes (`angle`,
307
+ * `angle2`) and is labelled with its index; its `strength` is the `score`.
308
+ * - **Covariance.** A corner's `position_covariance`, when present and finite, becomes `cov`;
309
+ * `TargetOverlay` draws it with `uncertainty`.
310
+ * - **Markers** (ChArUco) are the quads of `corners_img`, labelled with the dictionary id; a
311
+ * marker without a projected quad is left out.
312
+ * - **Circles** (marker board, from `diagnostics`) are the board circles a candidate matched,
313
+ * at the candidate's centre with the board's cell and polarity.
314
+ * - **Edge bits** (PuzzleBoard, from `diagnostics`) are the observed edges placed through the
315
+ * alignment with `edgeBitsFromPuzzleboard`.
316
+ *
317
+ * Ids are `corner-<n>`, `marker-<n>` and `circle-<n>`, where `n` is the index into the result's
318
+ * `corners`, `markers` or `circle_matches`, so a hover or a press maps straight back to it.
319
+ *
320
+ * @param result - The result, tagged with its kind.
321
+ * @returns The detection for `TargetOverlay`. Parts with no items are left out.
322
+ */
323
+ export function fromCalibTargets(result: CalibTargetsResult): TargetDetection {
324
+ const detection: TargetDetection = { kind: OVERLAY_KIND[result.kind] };
325
+
326
+ if (result.kind === "corners") {
327
+ if (result.corners.length > 0) detection.corners = result.corners.map(rawCorner);
328
+ return detection;
329
+ }
330
+ if (!result.detection) return detection;
331
+
332
+ const corners = result.detection.corners.map(labeledCorner);
333
+ if (corners.length > 0) detection.corners = corners;
334
+
335
+ switch (result.kind) {
336
+ case "charuco": {
337
+ const markers = markersOf(result.detection.markers);
338
+ if (markers.length > 0) detection.markers = markers;
339
+ break;
340
+ }
341
+ case "markerboard": {
342
+ const circles = result.diagnostics ? circlesOf(result.diagnostics) : [];
343
+ if (circles.length > 0) detection.circles = circles;
344
+ break;
345
+ }
346
+ case "puzzleboard": {
347
+ if (!result.diagnostics) break;
348
+ const { matrix, translation } = result.detection.alignment;
349
+ const alignment = {
350
+ transform: { a: matrix[0][0], b: matrix[0][1], c: matrix[1][0], d: matrix[1][1] },
351
+ translation: [translation[0], translation[1]] as const,
352
+ };
353
+ const edgeBits = edgeBitsFromPuzzleboard(edgesOf(result.diagnostics.observed_edges), corners, alignment);
354
+ if (edgeBits.length > 0) detection.edgeBits = edgeBits;
355
+ break;
356
+ }
357
+ default:
358
+ break;
359
+ }
360
+ return detection;
361
+ }
package/src/glyphs.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * The glyphs of a calibration-target overlay, as path generators.
3
3
  *
4
4
  * A glyph is a `MarkerShape` for `@vitavision/stage2d`'s `PointSet`: a pure function from a
5
- * position to SVG path data, so a layer appends thousands of them into one `<path>` (ADR-0004).
5
+ * position to SVG path data, so a layer appends thousands of them into one `<path>`.
6
6
  * They are registered under the names in `TARGET_MARKERS`, which `TargetOverlay` passes as
7
7
  * `markers`. Sizes are screen pixels, from `unit` (image pixels per screen pixel).
8
8
  *
package/src/index.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * One component, `TargetOverlay`, draws a `TargetDetection` (a chessboard, ChArUco, marker
5
5
  * board, PuzzleBoard, ring grid or loose corners) through stage2d's batched layers, in the
6
6
  * overlay grammar's roles and glyphs. The input model, the lattice builders and the glyph path
7
- * generators are exported too, for an app that composes the layers itself.
7
+ * generators are exported too, for an app that composes the layers itself. `fromCalibTargets`
8
+ * maps a calib-targets result to the input model.
8
9
  */
9
10
 
10
11
  export { TargetOverlay, type TargetOverlayProps } from "./TargetOverlay";
@@ -41,20 +42,40 @@ export {
41
42
  type MarkerPolygon,
42
43
  } from "./lattice";
43
44
 
44
- export {
45
- PUZZLEBOARD_PERIOD,
46
- edgeBitsFromPuzzleboard,
47
- type PuzzleboardAlignment,
48
- type PuzzleboardEdge,
49
- } from "./puzzleboard";
45
+ export { PUZZLEBOARD_PERIOD, edgeBitsFromPuzzleboard, type PuzzleboardAlignment, type PuzzleboardEdge } from "./puzzleboard";
50
46
 
51
47
  export { TARGET_MARKERS } from "./glyphs";
52
48
 
53
49
  export {
54
50
  circlePoints,
55
51
  cornerNodes,
52
+ covarianceEllipse,
56
53
  edgeBitEllipses,
57
54
  markerAreas,
58
55
  ringCentres,
59
56
  ringEllipses,
57
+ uncertaintyEllipses,
60
58
  } from "./layerItems";
59
+
60
+ export {
61
+ fromCalibTargets,
62
+ type CalibTargetsAlignment,
63
+ type CalibTargetsAxis,
64
+ type CalibTargetsCharucoDetection,
65
+ type CalibTargetsChessboardDetection,
66
+ type CalibTargetsCircleCandidate,
67
+ type CalibTargetsCircleMatch,
68
+ type CalibTargetsCoord,
69
+ type CalibTargetsCorner,
70
+ type CalibTargetsCovariance,
71
+ type CalibTargetsLabeledCorner,
72
+ type CalibTargetsMarker,
73
+ type CalibTargetsMarkerBoardDetection,
74
+ type CalibTargetsMarkerBoardDiagnostics,
75
+ type CalibTargetsObservedEdge,
76
+ type CalibTargetsPoint,
77
+ type CalibTargetsPuzzleBoardDetection,
78
+ type CalibTargetsPuzzleBoardDiagnostics,
79
+ type CalibTargetsPuzzlePoleDetection,
80
+ type CalibTargetsResult,
81
+ } from "./calibTargets";
package/src/lattice.ts CHANGED
@@ -127,9 +127,7 @@ export function cornerGrid(corners: readonly TargetCorner[]): CornerGrid {
127
127
  }
128
128
 
129
129
  const ordered = (groups: Map<number, number[]>, by: "i" | "j") =>
130
- [...groups.entries()]
131
- .sort(([a], [b]) => a - b)
132
- .map(([, group]) => group.sort((p, q) => nodes[p]![by] - nodes[q]![by]));
130
+ [...groups.entries()].sort(([a], [b]) => a - b).map(([, group]) => group.sort((p, q) => nodes[p]![by] - nodes[q]![by]));
133
131
  return { nodes, byIndex, rows: ordered(rowMap, "j"), cols: ordered(colMap, "i"), bounds };
134
132
  }
135
133
 
package/src/layerItems.ts CHANGED
@@ -10,7 +10,15 @@
10
10
  import type { AreaSetItem, EllipseSetItem, GridNode, PointSetItem } from "@vitavision/stage2d";
11
11
 
12
12
  import { markerPolygons } from "./lattice";
13
- import { isLatticeKind, type TargetCircle, type TargetCorner, type TargetDetection, type TargetEdgeBit, type TargetRing } from "./model";
13
+ import {
14
+ isLatticeKind,
15
+ type TargetCircle,
16
+ type TargetCorner,
17
+ type TargetDetection,
18
+ type TargetEdgeBit,
19
+ type TargetEllipse,
20
+ type TargetRing,
21
+ } from "./model";
14
22
 
15
23
  /** The label of a corner: its own, else the lattice index on a board, else the id. */
16
24
  function cornerLabel(corner: TargetCorner, lattice: boolean): string {
@@ -145,3 +153,53 @@ export function edgeBitEllipses(bits: readonly TargetEdgeBit[]): EllipseSetItem[
145
153
  opacity: BIT_OPACITY_MIN + (1 - BIT_OPACITY_MIN) * Math.min(1, Math.max(0, bit.confidence)),
146
154
  }));
147
155
  }
156
+
157
+ /**
158
+ * The ellipse of a 2×2 position covariance: `scale` standard deviations along each principal
159
+ * axis.
160
+ *
161
+ * The semi-axes are `scale · √λ` for the matrix's two eigenvalues `λ₁ ≥ λ₂`, and `angle` is the
162
+ * direction of the eigenvector of `λ₁` (radians, clockwise on screen, in `(-π/2, π/2]`). At
163
+ * `scale = 1` this is the 1σ ellipse: the curve `dᵀ Σ⁻¹ d = 1`.
164
+ *
165
+ * @param cov - The covariance `[xx, xy, yy]`, image pixels squared.
166
+ * @param scale - The gain applied to both semi-axes. Defaults to 1.
167
+ * @returns The ellipse, or `null` when the matrix is not finite and positive definite, or the
168
+ * scale is not a finite positive number: there is no ellipse to draw.
169
+ */
170
+ export function covarianceEllipse(cov: readonly [xx: number, xy: number, yy: number], scale = 1): TargetEllipse | null {
171
+ const [xx, xy, yy] = cov;
172
+ if (!Number.isFinite(xx + xy + yy) || !(Number.isFinite(scale) && scale > 0)) return null;
173
+ const det = xx * yy - xy * xy;
174
+ // Positive definite: a positive diagonal and a positive determinant.
175
+ if (!(xx > 0 && yy > 0 && det > 0)) return null;
176
+ const mean = 0.5 * (xx + yy);
177
+ const spread = Math.hypot(0.5 * (xx - yy), xy);
178
+ const major = mean + spread;
179
+ // λ₁λ₂ = det: the smaller eigenvalue from the product rather than from `mean - spread`.
180
+ const minor = det / major;
181
+ const half = 0.5 * Math.atan2(2 * xy, xx - yy);
182
+ // `atan2(-0, x < 0)` is -π: keep the axis in (-π/2, π/2].
183
+ const angle = half <= -Math.PI / 2 ? half + Math.PI : half;
184
+ return { rx: scale * Math.sqrt(major), ry: scale * Math.sqrt(minor), angle };
185
+ }
186
+
187
+ /**
188
+ * The ellipses of the uncertainty layer: each corner's position covariance as a 1σ ellipse,
189
+ * both semi-axes multiplied by `scale`, centred on the corner and sharing its id, in the `model`
190
+ * role. A corner with no covariance, or one that is not positive definite, has none.
191
+ *
192
+ * @param corners - The corners.
193
+ * @param scale - The gain on the semi-axes. A detector's σ is a fraction of a pixel, so it is
194
+ * drawn magnified; print the gain beside the image ("ellipses ×40").
195
+ * @returns One ellipse per corner with a drawable covariance, in order.
196
+ */
197
+ export function uncertaintyEllipses(corners: readonly TargetCorner[], scale: number): EllipseSetItem[] {
198
+ const out: EllipseSetItem[] = [];
199
+ for (const corner of corners) {
200
+ if (!corner.cov) continue;
201
+ const ellipse = covarianceEllipse(corner.cov, scale);
202
+ if (ellipse) out.push({ id: corner.id, x: corner.x, y: corner.y, ...ellipse, role: "model" });
203
+ }
204
+ return out;
205
+ }