@vitavision/stage2d 0.6.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.
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The arithmetic behind `MeasureOverlay`: everything that can be silently wrong, factored
3
+ * out so it can be tested without a DOM.
4
+ *
5
+ * Every primitive `MeasureOverlay` draws is given in **source-image pixel coordinates** —
6
+ * the same frame `ZoomPanCanvas`'s `nativeWidth`/`nativeHeight` describe, and the same one
7
+ * `api/mapValues.ts`'s `u`/`v` fractions index into. Nothing here measures the DOM or knows
8
+ * about zoom directly; `strokeWidthFor` is the one function that turns a *scale factor* a
9
+ * caller already knows (or computes once from a `ZoomPanCanvas` `View`) into a stroke width
10
+ * that reads as constant on screen.
11
+ */
12
+
13
+ /** A 2D point — in image pixels unless a signature says otherwise. */
14
+ export interface Point {
15
+ /** Horizontal coordinate, increasing rightward. */
16
+ x: number;
17
+ /** Vertical coordinate, increasing downward. */
18
+ y: number;
19
+ }
20
+
21
+ /**
22
+ * The on-screen-constant stroke width for a shape drawn in native-pixel units.
23
+ *
24
+ * `MeasureOverlay` is rendered as an SVG whose `viewBox` is the native image size, sitting
25
+ * inside `ZoomPanCanvas`'s own `scale(zoom)` transform. A stroke declared as `1` in that
26
+ * SVG's user units is `1` *native pixel*, which is `strokeScale` screen pixels once both
27
+ * transforms are applied (`strokeScale` = the SVG's own fit ratio × the canvas zoom, or
28
+ * just the zoom when the overlay is already at native resolution). Dividing by it is what
29
+ * keeps a 1px caliper edge looking like 1px at any zoom, rather than growing with it the
30
+ * way a shape's own geometry does.
31
+ *
32
+ * `vector-effect="non-scaling-stroke"` addresses only the SVG's *internal* transforms and
33
+ * is inconsistently applied across browsers once a CSS transform sits above the `<svg>`
34
+ * itself (exactly the situation inside `ZoomPanCanvas`), so this is computed explicitly
35
+ * rather than left to the renderer.
36
+ */
37
+ export function strokeWidthFor(strokeScale: number, screenPixels = 1): number {
38
+ if (!Number.isFinite(strokeScale) || strokeScale <= 0) return screenPixels;
39
+ return screenPixels / strokeScale;
40
+ }
41
+
42
+ /** Rotate `(x, y)` about the origin by `angle` radians. */
43
+ export function rotatePoint(x: number, y: number, angle: number): Point {
44
+ const c = Math.cos(angle);
45
+ const s = Math.sin(angle);
46
+ return { x: x * c - y * s, y: x * s + y * c };
47
+ }
48
+
49
+ /** `M x,y L x,y … Z` through `points`, or `""` for fewer than two of them. */
50
+ export function polygonPath(points: readonly Point[]): string {
51
+ if (points.length < 2) return "";
52
+ const [first, ...rest] = points;
53
+ const p0 = first as Point;
54
+ const commands = [`M${p0.x.toFixed(2)} ${p0.y.toFixed(2)}`];
55
+ for (const point of rest) commands.push(`L${point.x.toFixed(2)} ${point.y.toFixed(2)}`);
56
+ commands.push("Z");
57
+ return commands.join(" ");
58
+ }
59
+
60
+ /** The two line segments of a cross mark centred on `(x, y)`, each `2·size` long. */
61
+ export function crossSegments(x: number, y: number, size: number): [[Point, Point], [Point, Point]] {
62
+ return [
63
+ [{ x: x - size, y }, { x: x + size, y }],
64
+ [{ x, y: y - size }, { x, y: y + size }],
65
+ ];
66
+ }
67
+
68
+ /**
69
+ * The angular sweep from `startAngle` to `endAngle`, going forward.
70
+ *
71
+ * Two angles alone cannot distinguish "no sweep at all" from "swept exactly one full turn"
72
+ * — both have `endAngle - startAngle ≡ 0 (mod 2π)`. The raw (un-normalized) difference is
73
+ * what carries that distinction: genuinely equal angles have a raw difference near zero,
74
+ * while a caller asking for a full circle passes a raw difference of `2π` (or a multiple of
75
+ * it). So only a raw difference near zero is treated as "nothing to draw"; every other
76
+ * multiple of a full turn normalizes to `2π` itself rather than collapsing to `0`.
77
+ */
78
+ function sweepAngle(startAngle: number, endAngle: number): number {
79
+ const turn = Math.PI * 2;
80
+ const EPSILON = 1e-9;
81
+ const raw = endAngle - startAngle;
82
+ if (Math.abs(raw) < EPSILON) return 0;
83
+ const delta = raw % turn;
84
+ return delta <= EPSILON ? delta + turn : delta;
85
+ }
86
+
87
+ /**
88
+ * An SVG arc path centred at `(cx, cy)` with radius `r`, sweeping forward from `startAngle`
89
+ * to `endAngle` (radians, standard `x = cx + r·cos(a)`, `y = cy + r·sin(a)` convention —
90
+ * clockwise on screen, since image-pixel `y` increases downward).
91
+ *
92
+ * A single SVG `A` command cannot express a full circle (its start and end point coincide,
93
+ * which most renderers treat as a zero-length arc), so a sweep that reaches all the way
94
+ * around is split into two half-circle arcs instead.
95
+ */
96
+ export function arcPath(cx: number, cy: number, r: number, startAngle: number, endAngle: number): string {
97
+ if (!(r > 0)) return "";
98
+
99
+ const start = { x: cx + r * Math.cos(startAngle), y: cy + r * Math.sin(startAngle) };
100
+ const sweep = sweepAngle(startAngle, endAngle);
101
+ const FULL_TURN_EPSILON = 1e-9;
102
+
103
+ if (sweep < FULL_TURN_EPSILON) {
104
+ // A zero (or effectively zero) sweep is a point, not an arc.
105
+ return "";
106
+ }
107
+ if (sweep >= Math.PI * 2 - FULL_TURN_EPSILON) {
108
+ const mid = { x: cx + r * Math.cos(startAngle + Math.PI), y: cy + r * Math.sin(startAngle + Math.PI) };
109
+ return (
110
+ `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +
111
+ `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${mid.x.toFixed(2)} ${mid.y.toFixed(2)} ` +
112
+ `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${start.x.toFixed(2)} ${start.y.toFixed(2)}`
113
+ );
114
+ }
115
+
116
+ const end = { x: cx + r * Math.cos(endAngle), y: cy + r * Math.sin(endAngle) };
117
+ const largeArc = sweep > Math.PI ? 1 : 0;
118
+ return (
119
+ `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +
120
+ `A${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${end.x.toFixed(2)} ${end.y.toFixed(2)}`
121
+ );
122
+ }
123
+
124
+ /**
125
+ * The four corners of a caliper box: a rectangle `width` (along its own measurement axis)
126
+ * by `height`, centred at `(cx, cy)` and rotated by `angle` radians. Corner order is
127
+ * suitable for `polygonPath` — around the box, not crossed.
128
+ */
129
+ export function caliperCorners(
130
+ cx: number,
131
+ cy: number,
132
+ width: number,
133
+ height: number,
134
+ angle: number,
135
+ ): [Point, Point, Point, Point] {
136
+ const hw = width / 2;
137
+ const hh = height / 2;
138
+ const local: [number, number][] = [
139
+ [-hw, -hh],
140
+ [hw, -hh],
141
+ [hw, hh],
142
+ [-hw, hh],
143
+ ];
144
+ const [a, b, c, d] = local.map(([lx, ly]) => {
145
+ const r = rotatePoint(lx, ly, angle);
146
+ return { x: cx + r.x, y: cy + r.y };
147
+ });
148
+ return [a as Point, b as Point, c as Point, d as Point];
149
+ }
150
+
151
+ /**
152
+ * The direction arrow for a caliper box: from its centre to just past its `+local-x` edge,
153
+ * along the box's own measurement axis. What the arrow points at is the scan direction the
154
+ * caliper was evaluated in, not merely a decoration on the box.
155
+ */
156
+ export function caliperArrow(
157
+ cx: number,
158
+ cy: number,
159
+ width: number,
160
+ angle: number,
161
+ ): { from: Point; to: Point } {
162
+ const reach = width / 2 + Math.max(4, width * 0.2);
163
+ const tip = rotatePoint(reach, 0, angle);
164
+ return { from: { x: cx, y: cy }, to: { x: cx + tip.x, y: cy + tip.y } };
165
+ }
166
+
167
+ /**
168
+ * A small open chevron at `tip`, pointing along `angle` (radians), for a caliper's
169
+ * direction arrow. Three points — left-back, tip, right-back — meant for an unfilled
170
+ * `<polyline>`, which keeps the arrowhead's colour exactly the stroke colour of the line it
171
+ * caps without the fill-vs-stroke bookkeeping a filled triangle would need per tone.
172
+ */
173
+ export function arrowHeadPoints(tip: Point, angle: number, size: number): [Point, Point, Point] {
174
+ const back = size * 1.6;
175
+ const spread = size;
176
+ const left = rotatePoint(-back, spread, angle);
177
+ const right = rotatePoint(-back, -spread, angle);
178
+ return [
179
+ { x: tip.x + left.x, y: tip.y + left.y },
180
+ tip,
181
+ { x: tip.x + right.x, y: tip.y + right.y },
182
+ ];
183
+ }
184
+
185
+ /** What `dimensionGeometry` computes: the lines and label placement of a dimension annotation. */
186
+ export interface DimensionGeometry {
187
+ /** From the first measured point out to the dimension line. */
188
+ extensionLine1: [Point, Point];
189
+ /** From the second measured point out to the dimension line. */
190
+ extensionLine2: [Point, Point];
191
+ /** The offset line spanning the measured distance, parallel to the measured segment. */
192
+ dimensionLine: [Point, Point];
193
+ /** Midpoint of the dimension line — where the label sits. */
194
+ labelAnchor: Point;
195
+ /** The dimension line's own direction, in degrees, for an upright label rotation. */
196
+ angleDegrees: number;
197
+ }
198
+
199
+ /**
200
+ * The leader geometry for a dimension annotation between two measured points, offset by
201
+ * `offset` native pixels to the line's left (so a positive offset with a left-to-right
202
+ * measurement draws the dimension line above it, consistent with `y` increasing downward).
203
+ *
204
+ * Degenerate input (`x1 === x2 && y1 === y2`) falls back to an arbitrary rightward normal
205
+ * rather than dividing by zero, so a caller need not special-case a zero-length dimension.
206
+ */
207
+ export function dimensionGeometry(
208
+ x1: number,
209
+ y1: number,
210
+ x2: number,
211
+ y2: number,
212
+ offset: number,
213
+ ): DimensionGeometry {
214
+ const dx = x2 - x1;
215
+ const dy = y2 - y1;
216
+ const length = Math.hypot(dx, dy);
217
+ const [ux, uy] = length > 1e-9 ? [dx / length, dy / length] : [1, 0];
218
+ // The left-hand normal of the measured direction in a y-down frame: for a rightward
219
+ // measurement (u = (1, 0)) this is (0, -1), i.e. "up" on screen, which is what makes a
220
+ // positive offset draw the dimension line above a left-to-right span rather than below.
221
+ const nx = uy;
222
+ const ny = -ux;
223
+
224
+ const p1: Point = { x: x1 + nx * offset, y: y1 + ny * offset };
225
+ const p2: Point = { x: x2 + nx * offset, y: y2 + ny * offset };
226
+
227
+ return {
228
+ extensionLine1: [{ x: x1, y: y1 }, p1],
229
+ extensionLine2: [{ x: x2, y: y2 }, p2],
230
+ dimensionLine: [p1, p2],
231
+ labelAnchor: { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 },
232
+ angleDegrees: (Math.atan2(dy, dx) * 180) / Math.PI,
233
+ };
234
+ }