@vitavision/stage2d 0.10.0 → 0.12.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.
- package/README.md +12 -3
- package/dist/index.d.ts +437 -36
- package/dist/index.js +1406 -338
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/AreaSet.tsx +83 -52
- package/src/components/ContourEditor.tsx +12 -3
- package/src/components/DraftShape.tsx +56 -11
- package/src/components/EllipseSet.tsx +292 -0
- package/src/components/MaskEditor.tsx +22 -9
- package/src/components/PointSet.tsx +19 -9
- package/src/components/PolylineSet.tsx +56 -15
- package/src/components/RectRoiEditor.tsx +5 -4
- package/src/components/ShapeEditor.tsx +117 -37
- package/src/components/areaBatching.ts +111 -0
- package/src/components/areaIndex.ts +7 -4
- package/src/components/ellipseIndex.ts +279 -0
- package/src/components/markerShapes.ts +3 -1
- package/src/components/shapeEdit.ts +67 -1
- package/src/components/stage/ImageStage.tsx +250 -127
- package/src/components/stage/StageSurface.tsx +117 -17
- package/src/components/stage/gesture.ts +15 -0
- package/src/components/stage/touchWatch.ts +85 -0
- package/src/components/stage/useCoarsePointer.ts +30 -0
- package/src/components/stage/view.ts +88 -20
- package/src/index.ts +20 -0
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* this is the gestures, the handles and the keyboard.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
|
|
10
|
+
import { useEffect, useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from "react";
|
|
11
11
|
|
|
12
12
|
import type { Point } from "./measureGeometry";
|
|
13
13
|
import { overlayRole } from "./overlayRole";
|
|
@@ -20,17 +20,18 @@ import {
|
|
|
20
20
|
rotationHandlePoint,
|
|
21
21
|
shapeHandleCursor,
|
|
22
22
|
shapeHandlePoint,
|
|
23
|
+
shapePress,
|
|
24
|
+
SHAPE_HANDLE_PX,
|
|
25
|
+
SHAPE_ROTATE_OFFSET_PX,
|
|
26
|
+
SHAPE_ROTATE_RADIUS_PX,
|
|
23
27
|
type RotatedShape,
|
|
24
28
|
} from "./shapeEdit";
|
|
29
|
+
import { POINTER_RADIUS_PX, TOUCH_RADIUS_PX, hitRadiusPx } from "./stage/gesture";
|
|
25
30
|
import { useStage } from "./stage/ImageStage";
|
|
31
|
+
import { useCoarsePointer } from "./stage/useCoarsePointer";
|
|
26
32
|
import { useScreenPx } from "./stage/useScreenPx";
|
|
27
33
|
import { imageViewBox } from "./stage/view";
|
|
28
34
|
|
|
29
|
-
/** Handle square side, in screen pixels. */
|
|
30
|
-
const HANDLE_PX = 9;
|
|
31
|
-
/** Rotation handle radius, and its distance past the top side, in screen pixels. */
|
|
32
|
-
const ROTATE_RADIUS_PX = 5;
|
|
33
|
-
const ROTATE_OFFSET_PX = 24;
|
|
34
35
|
/** Outline width, in screen pixels. */
|
|
35
36
|
const STROKE_PX = 1.5;
|
|
36
37
|
/** The halo under the outline (visual-language §5), in screen pixels on each side. */
|
|
@@ -66,17 +67,28 @@ export interface ShapeEditorProps {
|
|
|
66
67
|
stroke?: string | undefined;
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
type Drag =
|
|
70
|
-
| { kind: "move"; from: Point
|
|
71
|
-
| { kind: "resize"; handle: RoiHandle
|
|
72
|
-
| { kind: "rotate"
|
|
70
|
+
type Drag = (
|
|
71
|
+
| { kind: "move"; from: Point }
|
|
72
|
+
| { kind: "resize"; handle: RoiHandle }
|
|
73
|
+
| { kind: "rotate" }
|
|
74
|
+
) & { start: RotatedShape; moved: boolean; pointerId: number };
|
|
73
75
|
|
|
74
76
|
/**
|
|
75
77
|
* An editable rotated rectangle or ellipse inside an `ImageStage`.
|
|
76
78
|
*
|
|
77
79
|
* - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the
|
|
78
80
|
* pointer and the opposite side stays where it is, whatever the rotation. A shape stops at
|
|
79
|
-
* `minSize` rather than flipping. The interior moves it
|
|
81
|
+
* `minSize` rather than flipping. The interior moves it, and so does the band along its
|
|
82
|
+
* outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin
|
|
83
|
+
* or rotated shape is grabbed. The band is as wide as the device's primary pointer needs
|
|
84
|
+
* (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to
|
|
85
|
+
* 12 px outside the outline reaches the layers below instead of the editor.
|
|
86
|
+
* - **Press order.** One decision serves every part of the editor: the nearest handle first,
|
|
87
|
+
* then the interior or outline band (move), then nothing. A small shape's interior does not
|
|
88
|
+
* steal a press meant for a handle, and a press that hits none of them is not claimed, so
|
|
89
|
+
* it reaches whatever is below, or the stage.
|
|
90
|
+
* - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit
|
|
91
|
+
* cancels it (the shape reverts, nothing is committed) and is left to the stage.
|
|
80
92
|
* - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to
|
|
81
93
|
* round to 15°.
|
|
82
94
|
* - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),
|
|
@@ -104,26 +116,74 @@ export function ShapeEditor({
|
|
|
104
116
|
}: ShapeEditorProps) {
|
|
105
117
|
const stage = useStage();
|
|
106
118
|
const px = useScreenPx();
|
|
119
|
+
const coarse = useCoarsePointer();
|
|
107
120
|
const dragRef = useRef<Drag | null>(null);
|
|
108
121
|
const lastRef = useRef<RotatedShape | null>(null);
|
|
122
|
+
const stopWatchRef = useRef<(() => void) | null>(null);
|
|
109
123
|
|
|
110
124
|
const report = (next: RotatedShape) => {
|
|
111
125
|
lastRef.current = next;
|
|
112
126
|
onValueChange(next);
|
|
113
127
|
};
|
|
114
128
|
|
|
115
|
-
|
|
116
|
-
|
|
129
|
+
/** Abandon an edit in flight: the shape reverts and nothing is committed. */
|
|
130
|
+
const cancelEdit = () => {
|
|
131
|
+
const drag = dragRef.current;
|
|
132
|
+
dragRef.current = null;
|
|
133
|
+
stopWatchRef.current?.();
|
|
134
|
+
stopWatchRef.current = null;
|
|
135
|
+
if (drag && lastRef.current) onValueChange(drag.start);
|
|
136
|
+
lastRef.current = null;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// An edit still in flight when the editor goes away is cancelled, not left listening.
|
|
140
|
+
useEffect(() => () => stopWatchRef.current?.(), []);
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The one press decision for the whole editor: every target (the interior, the outline
|
|
144
|
+
* band, a handle) comes here, and the nearest handle wins over the interior. A declined
|
|
145
|
+
* press is not claimed and bubbles to the stage.
|
|
146
|
+
*/
|
|
147
|
+
const press = (event: PointerEvent<SVGElement>) => {
|
|
148
|
+
if (!value || stage.panMode) return;
|
|
149
|
+
const touch = event.pointerType === "touch";
|
|
150
|
+
if (!touch && event.button !== 0) return;
|
|
151
|
+
// A second finger while an edit is in flight cancels it (a pinch, not an edit), unclaimed.
|
|
152
|
+
if (dragRef.current) {
|
|
153
|
+
if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const at = stage.toImage({ x: event.clientX, y: event.clientY });
|
|
157
|
+
const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);
|
|
158
|
+
if (!decision) return;
|
|
117
159
|
event.stopPropagation();
|
|
118
160
|
event.preventDefault();
|
|
119
|
-
|
|
120
|
-
|
|
161
|
+
try {
|
|
162
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
163
|
+
} catch {
|
|
164
|
+
// The pointer ended before this handler ran; the edit still follows the events the editor receives.
|
|
165
|
+
}
|
|
166
|
+
const base = { start: value, moved: false, pointerId: event.pointerId };
|
|
167
|
+
dragRef.current =
|
|
168
|
+
decision.kind === "move"
|
|
169
|
+
? { ...base, kind: "move", from: at }
|
|
170
|
+
: decision.kind === "resize"
|
|
171
|
+
? { ...base, kind: "resize", handle: decision.handle }
|
|
172
|
+
: { ...base, kind: "rotate" };
|
|
121
173
|
lastRef.current = null;
|
|
174
|
+
if (touch) {
|
|
175
|
+
const id = event.pointerId;
|
|
176
|
+
const other = (e: globalThis.PointerEvent) => {
|
|
177
|
+
if (e.pointerId !== id && e.pointerType === "touch") cancelEdit();
|
|
178
|
+
};
|
|
179
|
+
window.addEventListener("pointerdown", other);
|
|
180
|
+
stopWatchRef.current = () => window.removeEventListener("pointerdown", other);
|
|
181
|
+
}
|
|
122
182
|
};
|
|
123
183
|
|
|
124
184
|
const onMove = (event: PointerEvent<SVGElement>) => {
|
|
125
185
|
const drag = dragRef.current;
|
|
126
|
-
if (!drag) return;
|
|
186
|
+
if (!drag || drag.pointerId !== event.pointerId) return;
|
|
127
187
|
event.stopPropagation();
|
|
128
188
|
const p = stage.toImage({ x: event.clientX, y: event.clientY });
|
|
129
189
|
drag.moved = true;
|
|
@@ -134,12 +194,26 @@ export function ShapeEditor({
|
|
|
134
194
|
|
|
135
195
|
const onEnd = (event: PointerEvent<SVGElement>) => {
|
|
136
196
|
const drag = dragRef.current;
|
|
137
|
-
if (!drag) return;
|
|
197
|
+
if (!drag || drag.pointerId !== event.pointerId) return;
|
|
138
198
|
event.stopPropagation();
|
|
139
199
|
dragRef.current = null;
|
|
200
|
+
stopWatchRef.current?.();
|
|
201
|
+
stopWatchRef.current = null;
|
|
140
202
|
if (drag.moved && lastRef.current) onCommit?.(lastRef.current);
|
|
141
203
|
};
|
|
142
204
|
|
|
205
|
+
/** The handlers every target of the editor shares. */
|
|
206
|
+
const gesture = {
|
|
207
|
+
onPointerDown: press,
|
|
208
|
+
onPointerMove: onMove,
|
|
209
|
+
onPointerUp: onEnd,
|
|
210
|
+
onPointerCancel: (event: PointerEvent<SVGElement>) => {
|
|
211
|
+
if (dragRef.current?.pointerId === event.pointerId) cancelEdit();
|
|
212
|
+
},
|
|
213
|
+
onLostPointerCapture: onEnd,
|
|
214
|
+
onDoubleClick: (event: { stopPropagation: () => void }) => event.stopPropagation(),
|
|
215
|
+
};
|
|
216
|
+
|
|
143
217
|
const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
|
|
144
218
|
if (!editable || value === null) return;
|
|
145
219
|
const turn = rotatable && (event.key === "[" || event.key === "]");
|
|
@@ -171,8 +245,8 @@ export function ShapeEditor({
|
|
|
171
245
|
onCommit?.(next);
|
|
172
246
|
};
|
|
173
247
|
|
|
174
|
-
const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(
|
|
175
|
-
const handleSize = px(
|
|
248
|
+
const stem = value ? { from: shapeHandlePoint(value, "n"), to: rotationHandlePoint(value, px(SHAPE_ROTATE_OFFSET_PX)) } : null;
|
|
249
|
+
const handleSize = px(SHAPE_HANDLE_PX);
|
|
176
250
|
|
|
177
251
|
return (
|
|
178
252
|
<svg
|
|
@@ -196,6 +270,25 @@ export function ShapeEditor({
|
|
|
196
270
|
opacity={0.6}
|
|
197
271
|
/>
|
|
198
272
|
)}
|
|
273
|
+
{editable && value && (
|
|
274
|
+
// The outline band: a wide transparent stroke, so a press a few pixels outside the
|
|
275
|
+
// outline still reaches the editor. Sized for the device's primary pointer (a finger's
|
|
276
|
+
// 12 px on a touch-first device, a mouse's 6 px otherwise) so a mouse press just
|
|
277
|
+
// outside the outline reaches the layers below. `press` decides with the event's own pointer.
|
|
278
|
+
<Outline
|
|
279
|
+
kind={kind}
|
|
280
|
+
shape={value}
|
|
281
|
+
data-shape-band=""
|
|
282
|
+
fill="none"
|
|
283
|
+
stroke="transparent"
|
|
284
|
+
strokeWidth={px(2 * (coarse ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX))}
|
|
285
|
+
strokeLinejoin="round"
|
|
286
|
+
aria-hidden
|
|
287
|
+
className="pointer-events-auto cursor-move"
|
|
288
|
+
style={{ pointerEvents: "stroke" }}
|
|
289
|
+
{...gesture}
|
|
290
|
+
/>
|
|
291
|
+
)}
|
|
199
292
|
{editable && value && (
|
|
200
293
|
<Outline
|
|
201
294
|
kind={kind}
|
|
@@ -206,14 +299,9 @@ export function ShapeEditor({
|
|
|
206
299
|
aria-label={`${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt((value.rotation * 180) / Math.PI)}°`}
|
|
207
300
|
aria-roledescription={kind === "rect" ? "rotated rectangle" : "ellipse"}
|
|
208
301
|
className="pointer-events-auto cursor-move outline-none focus-visible:stroke-signal"
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
212
|
-
onPointerMove={onMove}
|
|
213
|
-
onPointerUp={onEnd}
|
|
214
|
-
onLostPointerCapture={onEnd}
|
|
302
|
+
strokeWidth={px(2)}
|
|
303
|
+
{...gesture}
|
|
215
304
|
onKeyDown={onKeyDown}
|
|
216
|
-
onDoubleClick={(event) => event.stopPropagation()}
|
|
217
305
|
/>
|
|
218
306
|
)}
|
|
219
307
|
{editable && value && rotatable && stem && (
|
|
@@ -224,17 +312,13 @@ export function ShapeEditor({
|
|
|
224
312
|
data-handle="rotate"
|
|
225
313
|
cx={stem.to.x}
|
|
226
314
|
cy={stem.to.y}
|
|
227
|
-
r={px(
|
|
315
|
+
r={px(SHAPE_ROTATE_RADIUS_PX)}
|
|
228
316
|
fill={stroke}
|
|
229
317
|
stroke={HALO}
|
|
230
318
|
strokeWidth={px(1)}
|
|
231
319
|
className="pointer-events-auto"
|
|
232
320
|
style={{ cursor: "grab" }}
|
|
233
|
-
|
|
234
|
-
onPointerMove={onMove}
|
|
235
|
-
onPointerUp={onEnd}
|
|
236
|
-
onLostPointerCapture={onEnd}
|
|
237
|
-
onDoubleClick={(event) => event.stopPropagation()}
|
|
321
|
+
{...gesture}
|
|
238
322
|
/>
|
|
239
323
|
</>
|
|
240
324
|
)}
|
|
@@ -255,11 +339,7 @@ export function ShapeEditor({
|
|
|
255
339
|
strokeWidth={px(1)}
|
|
256
340
|
className="pointer-events-auto"
|
|
257
341
|
style={{ cursor: shapeHandleCursor(handle, value.rotation) }}
|
|
258
|
-
|
|
259
|
-
onPointerMove={onMove}
|
|
260
|
-
onPointerUp={onEnd}
|
|
261
|
-
onLostPointerCapture={onEnd}
|
|
262
|
-
onDoubleClick={(event) => event.stopPropagation()}
|
|
342
|
+
{...gesture}
|
|
263
343
|
/>
|
|
264
344
|
);
|
|
265
345
|
})}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How `AreaSet` groups its regions into batched paths: by appearance (state, role, colours),
|
|
3
|
+
* either one batch per appearance or consecutive runs in item order. Pure, so the keys are
|
|
4
|
+
* unit-tested without a DOM (ADR-0004 rule 1).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { areaPath, type Area, type AreaId } from "./areaIndex";
|
|
8
|
+
import type { OverlayRole } from "./overlayRole";
|
|
9
|
+
|
|
10
|
+
/** An item as batching sees it: a region and its appearance overrides. */
|
|
11
|
+
export interface BatchableArea extends Area {
|
|
12
|
+
role?: OverlayRole | undefined;
|
|
13
|
+
stroke?: string | undefined;
|
|
14
|
+
fill?: string | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The regions of one batched path. */
|
|
18
|
+
export interface AreaBatch {
|
|
19
|
+
/** The appearance key; several runs of one appearance share it under `paintOrder: "items"`. */
|
|
20
|
+
key: string;
|
|
21
|
+
/** A unique key for rendering (the appearance key, plus the run number for runs). */
|
|
22
|
+
id: string;
|
|
23
|
+
role: OverlayRole;
|
|
24
|
+
/** The outline colour when the item or the layer set one; `undefined` paints the role. */
|
|
25
|
+
stroke: string | undefined;
|
|
26
|
+
/** The fill colour when an item set one; `undefined` paints the outline colour. */
|
|
27
|
+
fill: string | undefined;
|
|
28
|
+
dim: boolean;
|
|
29
|
+
/** Item positions, ascending. */
|
|
30
|
+
indices: number[];
|
|
31
|
+
/** The outlines, concatenated (without the selected items under `selectionFill: "item"`). */
|
|
32
|
+
d: string;
|
|
33
|
+
/** Each item's own ring, aligned with `indices`, when fills are drawn apart from outlines. */
|
|
34
|
+
fills: string[] | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What decides the batches. */
|
|
38
|
+
export interface AreaBatchOptions {
|
|
39
|
+
/** The role of an item that names none. */
|
|
40
|
+
role: OverlayRole;
|
|
41
|
+
/** The layer's outline colour. */
|
|
42
|
+
stroke: string | undefined;
|
|
43
|
+
/** `"items"` makes batches consecutive runs in item order. */
|
|
44
|
+
paintOrder: "appearance" | "items";
|
|
45
|
+
/** `"evenodd"` gives every item its own fill path. */
|
|
46
|
+
fillRule: "nonzero" | "evenodd";
|
|
47
|
+
/** `"item"` keeps a selected item in its own batch, fill included. */
|
|
48
|
+
selectionFill: "selection" | "item";
|
|
49
|
+
selected: ReadonlySet<AreaId>;
|
|
50
|
+
isDimmed: (id: AreaId) => boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The appearance key of an item. Without a custom colour it is `dim|role`, as before colours
|
|
55
|
+
* existed; a custom colour appends the outline and fill it was given.
|
|
56
|
+
*
|
|
57
|
+
* @param dim - Whether the item is dimmed.
|
|
58
|
+
* @param role - The item's role.
|
|
59
|
+
* @param stroke - The outline colour, if any.
|
|
60
|
+
* @param fill - The fill colour, if any.
|
|
61
|
+
* @returns The key.
|
|
62
|
+
*/
|
|
63
|
+
export function areaBatchKey(dim: boolean, role: OverlayRole, stroke: string | undefined, fill: string | undefined): string {
|
|
64
|
+
const base = `${dim ? 1 : 0}|${role}`;
|
|
65
|
+
return stroke || fill ? `${base}|${stroke ?? ""}|${fill ?? ""}` : base;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Groups items into batches. Selected items go to `picked` (drawn on top in the selection
|
|
70
|
+
* colour), unless `selectionFill` is `"item"`: then they stay in their batch for the fill and
|
|
71
|
+
* `picked` carries only their outlines.
|
|
72
|
+
*
|
|
73
|
+
* @param items - The regions.
|
|
74
|
+
* @param options - What decides the grouping.
|
|
75
|
+
* @returns The appearance batches in paint order, and the selected overlay.
|
|
76
|
+
*/
|
|
77
|
+
export function batchAreas(items: readonly BatchableArea[], options: AreaBatchOptions): { normal: AreaBatch[]; picked: AreaBatch | null } {
|
|
78
|
+
const { role, stroke, paintOrder, fillRule, selectionFill, selected, isDimmed } = options;
|
|
79
|
+
const keepSelected = selectionFill === "item";
|
|
80
|
+
// Fills apart from outlines: needed per item for even-odd, and to leave selected outlines out.
|
|
81
|
+
const separate = fillRule === "evenodd" || keepSelected;
|
|
82
|
+
const byKey = new Map<string, AreaBatch>();
|
|
83
|
+
const runs: AreaBatch[] = [];
|
|
84
|
+
const picked: AreaBatch = { key: "selected", id: "selected", role: "selection", stroke: undefined, fill: undefined, dim: false, indices: [], d: "", fills: fillRule === "evenodd" && !keepSelected ? [] : null };
|
|
85
|
+
|
|
86
|
+
items.forEach((item, i) => {
|
|
87
|
+
const isSelected = selected.has(item.id);
|
|
88
|
+
if (isSelected) {
|
|
89
|
+
const d = areaPath(item.points);
|
|
90
|
+
picked.indices.push(i);
|
|
91
|
+
picked.d += d;
|
|
92
|
+
picked.fills?.push(d);
|
|
93
|
+
if (!keepSelected) return;
|
|
94
|
+
}
|
|
95
|
+
const itemRole = item.role ?? role;
|
|
96
|
+
const itemStroke = item.stroke ?? stroke;
|
|
97
|
+
const dim = isDimmed(item.id);
|
|
98
|
+
const key = areaBatchKey(dim, itemRole, itemStroke, item.fill);
|
|
99
|
+
let batch = paintOrder === "items" ? runs[runs.length - 1] : byKey.get(key);
|
|
100
|
+
if (!batch || batch.key !== key) {
|
|
101
|
+
batch = { key, id: paintOrder === "items" ? `${key}#${runs.length}` : key, role: itemRole, stroke: itemStroke, fill: item.fill, dim, indices: [], d: "", fills: separate ? [] : null };
|
|
102
|
+
byKey.set(key, batch);
|
|
103
|
+
runs.push(batch);
|
|
104
|
+
}
|
|
105
|
+
const d = areaPath(item.points);
|
|
106
|
+
batch.indices.push(i);
|
|
107
|
+
batch.fills?.push(d);
|
|
108
|
+
if (!(isSelected && keepSelected)) batch.d += d;
|
|
109
|
+
});
|
|
110
|
+
return { normal: runs, picked: picked.indices.length > 0 ? picked : null };
|
|
111
|
+
}
|
|
@@ -265,8 +265,11 @@ export function buildAreaIndex(items: readonly Area[], cell?: number): AreaIndex
|
|
|
265
265
|
return { items, bounds, size, cell: side, x0: minX, y0: minY, cols, rows, starts, entries };
|
|
266
266
|
}
|
|
267
267
|
|
|
268
|
-
/**
|
|
269
|
-
|
|
268
|
+
/**
|
|
269
|
+
* The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.
|
|
270
|
+
* The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.
|
|
271
|
+
*/
|
|
272
|
+
export function areaCandidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {
|
|
270
273
|
const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;
|
|
271
274
|
if (entries.length === 0) return [];
|
|
272
275
|
const cx0 = Math.max(0, Math.floor((left - x0) / cell));
|
|
@@ -306,7 +309,7 @@ export function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit
|
|
|
306
309
|
const { items, size } = index;
|
|
307
310
|
let edge: AreaHit | null = null;
|
|
308
311
|
let inner: AreaHit | null = null;
|
|
309
|
-
for (const a of
|
|
312
|
+
for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
|
|
310
313
|
const points = items[a]!.points;
|
|
311
314
|
const distance = distanceToOutline(points, p.x, p.y);
|
|
312
315
|
const inside = pointInPolygon(points, p.x, p.y);
|
|
@@ -337,7 +340,7 @@ export function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {
|
|
|
337
340
|
height: Math.abs(rect.height),
|
|
338
341
|
};
|
|
339
342
|
const out: AreaId[] = [];
|
|
340
|
-
for (const a of
|
|
343
|
+
for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {
|
|
341
344
|
if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);
|
|
342
345
|
}
|
|
343
346
|
return out;
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spatial index over many ellipses: which one is under the pointer, and which ones a
|
|
3
|
+
* rubber band touched.
|
|
4
|
+
*
|
|
5
|
+
* The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the
|
|
6
|
+
* items); a query runs the exact tests on the few ellipses whose box is near the pointer. The
|
|
7
|
+
* exact tests are in the ellipse's own frame: containment is one quadratic form, and the
|
|
8
|
+
* distance to the outline is the true Euclidean distance (a few Newton steps on the
|
|
9
|
+
* parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a
|
|
10
|
+
* round one. It imports neither React nor the DOM.
|
|
11
|
+
*
|
|
12
|
+
* An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no
|
|
13
|
+
* outline to draw or to pick.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { areaCandidates, buildAreaIndex, type AreaIndex } from "./areaIndex";
|
|
17
|
+
import type { Point } from "./measureGeometry";
|
|
18
|
+
import type { Rect } from "./stage/view";
|
|
19
|
+
|
|
20
|
+
/** An ellipse's identity. */
|
|
21
|
+
export type EllipseId = string | number;
|
|
22
|
+
|
|
23
|
+
/** One ellipse. */
|
|
24
|
+
export interface Ellipse {
|
|
25
|
+
/** Its identity, unique in the set. */
|
|
26
|
+
id: EllipseId;
|
|
27
|
+
/** Centre x, image pixels. */
|
|
28
|
+
x: number;
|
|
29
|
+
/** Centre y, image pixels. */
|
|
30
|
+
y: number;
|
|
31
|
+
/** Semi-axis along the rotated x axis, image pixels. */
|
|
32
|
+
rx: number;
|
|
33
|
+
/** Semi-axis along the rotated y axis, image pixels. */
|
|
34
|
+
ry: number;
|
|
35
|
+
/** Rotation of the `rx` axis, radians clockwise on screen (y points down). Defaults to 0. */
|
|
36
|
+
angle?: number | undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* An index built by `buildEllipseIndex`. Treat it as opaque and query it with `nearestEllipse`
|
|
41
|
+
* and `ellipsesInRect`; its layout may change.
|
|
42
|
+
*/
|
|
43
|
+
export interface EllipseIndex {
|
|
44
|
+
/** The ellipses, in the order given. */
|
|
45
|
+
readonly items: readonly Ellipse[];
|
|
46
|
+
/** The grid over their bounding boxes (an `AreaIndex` of boxes, one per ellipse). */
|
|
47
|
+
readonly grid: AreaIndex;
|
|
48
|
+
/** Per ellipse, its area `π·rx·ry`, used to prefer the smaller of nested ellipses; `NaN` for a degenerate one. */
|
|
49
|
+
readonly size: Float64Array;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The ellipse `nearestEllipse` picked. */
|
|
53
|
+
export interface EllipseHit {
|
|
54
|
+
/** Its id. */
|
|
55
|
+
id: EllipseId;
|
|
56
|
+
/** Its position in the array the index was built from. */
|
|
57
|
+
index: number;
|
|
58
|
+
/** Whether the query is inside the ellipse. */
|
|
59
|
+
inside: boolean;
|
|
60
|
+
/** The distance from the query to the ellipse's outline, in image pixels (also when inside). */
|
|
61
|
+
distance: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function usable(e: Ellipse): boolean {
|
|
65
|
+
return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The axis-aligned bounding box of an ellipse.
|
|
70
|
+
*
|
|
71
|
+
* @param e - The ellipse.
|
|
72
|
+
* @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.
|
|
73
|
+
*/
|
|
74
|
+
export function ellipseBounds(e: Ellipse): [number, number, number, number] | null {
|
|
75
|
+
if (!usable(e)) return null;
|
|
76
|
+
const c = Math.cos(e.angle ?? 0);
|
|
77
|
+
const s = Math.sin(e.angle ?? 0);
|
|
78
|
+
const hx = Math.hypot(e.rx * c, e.ry * s);
|
|
79
|
+
const hy = Math.hypot(e.rx * s, e.ry * c);
|
|
80
|
+
return [e.x - hx, e.y - hy, e.x + hx, e.y + hy];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */
|
|
84
|
+
function toFrame(e: Ellipse, x: number, y: number): Point {
|
|
85
|
+
const c = Math.cos(e.angle ?? 0);
|
|
86
|
+
const s = Math.sin(e.angle ?? 0);
|
|
87
|
+
const dx = x - e.x;
|
|
88
|
+
const dy = y - e.y;
|
|
89
|
+
return { x: c * dx + s * dy, y: -s * dx + c * dy };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Whether `(x, y)` is inside the ellipse (its outline counts as inside).
|
|
94
|
+
*
|
|
95
|
+
* @param e - The ellipse.
|
|
96
|
+
* @param x - The query's x.
|
|
97
|
+
* @param y - The query's y.
|
|
98
|
+
* @returns `false` for a degenerate ellipse.
|
|
99
|
+
*/
|
|
100
|
+
export function pointInEllipse(e: Ellipse, x: number, y: number): boolean {
|
|
101
|
+
if (!usable(e)) return false;
|
|
102
|
+
const p = toFrame(e, x, y);
|
|
103
|
+
return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */
|
|
107
|
+
const NEWTON_STEPS = 12;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The Euclidean distance from `(x, y)` to the outline of an ellipse.
|
|
111
|
+
*
|
|
112
|
+
* The query is folded into the first quadrant of the ellipse's frame and the nearest outline
|
|
113
|
+
* point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the
|
|
114
|
+
* better of a coarse scan so a thin ellipse and a query near its centre both converge.
|
|
115
|
+
*
|
|
116
|
+
* @param e - The ellipse.
|
|
117
|
+
* @param x - The query's x.
|
|
118
|
+
* @param y - The query's y.
|
|
119
|
+
* @returns The distance; `Infinity` for a degenerate ellipse.
|
|
120
|
+
*/
|
|
121
|
+
export function distanceToEllipse(e: Ellipse, x: number, y: number): number {
|
|
122
|
+
if (!usable(e)) return Infinity;
|
|
123
|
+
const p = toFrame(e, x, y);
|
|
124
|
+
const px = Math.abs(p.x);
|
|
125
|
+
const py = Math.abs(p.y);
|
|
126
|
+
const a = e.rx;
|
|
127
|
+
const b = e.ry;
|
|
128
|
+
const squared = (t: number) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;
|
|
129
|
+
// The squared distance can have two local minima in the quadrant (a query near the centre of
|
|
130
|
+
// a thin ellipse), so start from the best of a coarse scan, then polish.
|
|
131
|
+
let t = 0;
|
|
132
|
+
let best = Infinity;
|
|
133
|
+
const SCAN = 16;
|
|
134
|
+
for (let k = 0; k <= SCAN; k++) {
|
|
135
|
+
const candidate = (k / SCAN) * (Math.PI / 2);
|
|
136
|
+
const value = squared(candidate);
|
|
137
|
+
if (value < best) {
|
|
138
|
+
best = value;
|
|
139
|
+
t = candidate;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (let i = 0; i < NEWTON_STEPS; i++) {
|
|
143
|
+
const c = Math.cos(t);
|
|
144
|
+
const s = Math.sin(t);
|
|
145
|
+
// f(θ) = d/dθ of half the squared distance; f' by differentiating again.
|
|
146
|
+
const f = (b * b - a * a) * s * c + a * px * s - b * py * c;
|
|
147
|
+
const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;
|
|
148
|
+
if (!(Math.abs(df) > 1e-12)) break;
|
|
149
|
+
const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));
|
|
150
|
+
if (squared(next) > squared(t)) break; // a step that does not descend is noise
|
|
151
|
+
t = next;
|
|
152
|
+
}
|
|
153
|
+
return Math.sqrt(squared(t));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.
|
|
158
|
+
*
|
|
159
|
+
* @param cx - Centre x, image pixels.
|
|
160
|
+
* @param cy - Centre y, image pixels.
|
|
161
|
+
* @param rx - Semi-axis along the rotated x axis, image pixels.
|
|
162
|
+
* @param ry - Semi-axis along the rotated y axis, image pixels.
|
|
163
|
+
* @param angle - Rotation of the `rx` axis, radians clockwise on screen.
|
|
164
|
+
* @returns Path data, or `""` for a degenerate ellipse (a non-finite value, or a radius not above zero).
|
|
165
|
+
*/
|
|
166
|
+
export function ellipsePath(cx: number, cy: number, rx: number, ry: number, angle = 0): string {
|
|
167
|
+
if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return "";
|
|
168
|
+
const dx = rx * Math.cos(angle);
|
|
169
|
+
const dy = rx * Math.sin(angle);
|
|
170
|
+
const degrees = round((angle * 180) / Math.PI);
|
|
171
|
+
const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;
|
|
172
|
+
return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Round to 1/1000 of an image pixel. */
|
|
176
|
+
function round(value: number): number {
|
|
177
|
+
return Math.round(value * 1000) / 1000;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Index a set of ellipses.
|
|
182
|
+
*
|
|
183
|
+
* @param items - The ellipses.
|
|
184
|
+
* @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.
|
|
185
|
+
* @returns The index.
|
|
186
|
+
*/
|
|
187
|
+
export function buildEllipseIndex(items: readonly Ellipse[], cell?: number): EllipseIndex {
|
|
188
|
+
const size = new Float64Array(items.length).fill(Number.NaN);
|
|
189
|
+
const boxes = items.map((item, i) => {
|
|
190
|
+
const box = ellipseBounds(item);
|
|
191
|
+
if (box === null) return { id: i, points: [] as number[] };
|
|
192
|
+
size[i] = Math.PI * item.rx * item.ry;
|
|
193
|
+
const [x0, y0, x1, y1] = box;
|
|
194
|
+
return { id: i, points: [x0, y0, x1, y0, x1, y1, x0, y1] };
|
|
195
|
+
});
|
|
196
|
+
return { items, grid: buildAreaIndex(boxes, cell), size };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The ellipse under a point: one whose outline passes within `radius`, or else one that
|
|
201
|
+
* contains it.
|
|
202
|
+
*
|
|
203
|
+
* An outline is the more precise gesture, so it wins: among ellipses whose outline is within
|
|
204
|
+
* `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal
|
|
205
|
+
* distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside
|
|
206
|
+
* another is picked rather than the outer one, then to the earlier one.
|
|
207
|
+
*
|
|
208
|
+
* @param index - The index.
|
|
209
|
+
* @param p - The query, in image coordinates.
|
|
210
|
+
* @param radius - How far from an outline the query still picks it, in image pixels.
|
|
211
|
+
* @returns The ellipse, or `null`.
|
|
212
|
+
*/
|
|
213
|
+
export function nearestEllipse(index: EllipseIndex, p: Point, radius: number): EllipseHit | null {
|
|
214
|
+
if (!(radius >= 0)) return null;
|
|
215
|
+
const { items, size } = index;
|
|
216
|
+
let edge: EllipseHit | null = null;
|
|
217
|
+
let inner: EllipseHit | null = null;
|
|
218
|
+
for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {
|
|
219
|
+
const e = items[a]!;
|
|
220
|
+
const distance = distanceToEllipse(e, p.x, p.y);
|
|
221
|
+
const hit: EllipseHit = { id: e.id, index: a, inside: pointInEllipse(e, p.x, p.y), distance };
|
|
222
|
+
if (distance <= radius) {
|
|
223
|
+
if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;
|
|
224
|
+
} else if (hit.inside && (inner === null || size[a]! < size[inner.index]!)) {
|
|
225
|
+
inner = hit;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return edge ?? inner;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies
|
|
233
|
+
* inside the ellipse, or contains it.
|
|
234
|
+
*
|
|
235
|
+
* @param index - The index.
|
|
236
|
+
* @param rect - The band, in image coordinates. A negative extent is read as the box between
|
|
237
|
+
* its corners.
|
|
238
|
+
* @returns Their ids, in the order the ellipses were given.
|
|
239
|
+
*/
|
|
240
|
+
export function ellipsesInRect(index: EllipseIndex, rect: Rect): EllipseId[] {
|
|
241
|
+
const x0 = Math.min(rect.x, rect.x + rect.width);
|
|
242
|
+
const y0 = Math.min(rect.y, rect.y + rect.height);
|
|
243
|
+
const x1 = Math.max(rect.x, rect.x + rect.width);
|
|
244
|
+
const y1 = Math.max(rect.y, rect.y + rect.height);
|
|
245
|
+
const out: EllipseId[] = [];
|
|
246
|
+
for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {
|
|
247
|
+
const e = index.items[a]!;
|
|
248
|
+
if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Whether the filled ellipse and the rectangle share a point (both convex). */
|
|
254
|
+
function rectMeetsEllipse(e: Ellipse, x0: number, y0: number, x1: number, y1: number): boolean {
|
|
255
|
+
// The rectangle contains the ellipse (its centre is inside), the ellipse contains a corner,
|
|
256
|
+
// or an edge crosses the ellipse with both end points outside it: the three ways two convex
|
|
257
|
+
// shapes meet.
|
|
258
|
+
if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;
|
|
259
|
+
const corners: Point[] = [
|
|
260
|
+
{ x: x0, y: y0 },
|
|
261
|
+
{ x: x1, y: y0 },
|
|
262
|
+
{ x: x1, y: y1 },
|
|
263
|
+
{ x: x0, y: y1 },
|
|
264
|
+
];
|
|
265
|
+
if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;
|
|
266
|
+
// Minimise the ellipse's quadratic form along each edge, in the ellipse's frame.
|
|
267
|
+
for (let k = 0; k < 4; k++) {
|
|
268
|
+
const a = toFrame(e, corners[k]!.x, corners[k]!.y);
|
|
269
|
+
const b = toFrame(e, corners[(k + 1) % 4]!.x, corners[(k + 1) % 4]!.y);
|
|
270
|
+
const ux = (b.x - a.x) / e.rx;
|
|
271
|
+
const uy = (b.y - a.y) / e.ry;
|
|
272
|
+
const vx = a.x / e.rx;
|
|
273
|
+
const vy = a.y / e.ry;
|
|
274
|
+
const len2 = ux * ux + uy * uy;
|
|
275
|
+
const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;
|
|
276
|
+
if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;
|
|
277
|
+
}
|
|
278
|
+
return false;
|
|
279
|
+
}
|