@vitavision/stage2d 0.15.0 → 0.16.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 +16 -0
- package/dist/index.d.ts +382 -1
- package/dist/index.js +944 -10
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/ContourLayer.tsx +211 -0
- package/src/components/PointMarquee.tsx +229 -0
- package/src/components/VectorField.tsx +302 -0
- package/src/components/VectorFieldKey.tsx +91 -0
- package/src/components/contour.ts +270 -0
- package/src/components/vectorGeometry.ts +159 -0
- package/src/index.ts +23 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Many vectors over the image: a displacement, a flow, a gradient, a residual direction.
|
|
3
|
+
*
|
|
4
|
+
* Drawn as a handful of batched paths (one halo, then one per colour step), never one element per
|
|
5
|
+
* vector; the pointer is resolved through the stage's hit registry from a spatial index over the
|
|
6
|
+
* anchors, never by the DOM; arrowheads and strokes are sized in screen pixels. A field of 10,000
|
|
7
|
+
* vectors is a dozen DOM nodes.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { useMemo, useState } from "react";
|
|
11
|
+
|
|
12
|
+
import type { Colormap, ValueRange } from "./heatmapRaster";
|
|
13
|
+
import { visibleRect } from "./labelLod";
|
|
14
|
+
import { overlayRole, OVERLAY_STATE_WIDTH, type OverlayRole } from "./overlayRole";
|
|
15
|
+
import { buildPointIndex, nearestPoint, type PointId } from "./pointIndex";
|
|
16
|
+
import { useStage } from "./stage/ImageStage";
|
|
17
|
+
import type { StagePointerEvent } from "./stage/hitContext";
|
|
18
|
+
import { STAGE_HIT_PRIORITY } from "./stage/hitTest";
|
|
19
|
+
import { useStageHitLayer } from "./stage/useStageHitTest";
|
|
20
|
+
import { useScreenPx } from "./stage/useScreenPx";
|
|
21
|
+
import { imageViewBox, type Rect } from "./stage/view";
|
|
22
|
+
import {
|
|
23
|
+
arrowPath,
|
|
24
|
+
colorBin,
|
|
25
|
+
imagePerUnit,
|
|
26
|
+
magnitudePercentile,
|
|
27
|
+
vectorMagnitudes,
|
|
28
|
+
VECTOR_COLOR_BINS,
|
|
29
|
+
type ArrowStyle,
|
|
30
|
+
type VectorScale,
|
|
31
|
+
} from "./vectorGeometry";
|
|
32
|
+
|
|
33
|
+
/** The arrow's shape, in screen pixels. */
|
|
34
|
+
const ARROW: ArrowStyle = { head: 6, headWidth: 0.7, minLength: 1 };
|
|
35
|
+
/** Past this many vectors, paths are generated for the visible part only. */
|
|
36
|
+
const CULL_ABOVE = 3000;
|
|
37
|
+
/** The reference vector of the default scale: the 95th percentile spans this many screen pixels. */
|
|
38
|
+
const DEFAULT_SCALE: VectorScale = { length: 28, percentile: 0.95 };
|
|
39
|
+
|
|
40
|
+
/** Props of `VectorField`. */
|
|
41
|
+
export interface VectorFieldProps {
|
|
42
|
+
/** The anchors, flat `[x0, y0, x1, y1, …]` in image coordinates. A non-finite anchor is skipped. */
|
|
43
|
+
anchors: ArrayLike<number>;
|
|
44
|
+
/**
|
|
45
|
+
* The vectors, flat `[dx0, dy0, dx1, dy1, …]` in data units, one per anchor. A non-finite
|
|
46
|
+
* component, or a missing entry, skips the vector.
|
|
47
|
+
*/
|
|
48
|
+
vectors: ArrayLike<number>;
|
|
49
|
+
/**
|
|
50
|
+
* How data units become image pixels: a number is image pixels per data unit and zooms with
|
|
51
|
+
* the image; `{ length, percentile }` makes the `percentile` vector (default `1`, the longest)
|
|
52
|
+
* span `length` screen pixels at every zoom. Defaults to the 95th-percentile vector at 28 screen
|
|
53
|
+
* pixels, so a few outliers do not shrink the rest to nothing.
|
|
54
|
+
*/
|
|
55
|
+
scale?: VectorScale | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* One CSS colour for every arrow (`#hex`, `var(--x)`; used as given). Ignored with `colormap`.
|
|
58
|
+
* Defaults to the `role`'s colour.
|
|
59
|
+
*/
|
|
60
|
+
color?: string | undefined;
|
|
61
|
+
/** The overlay role the arrows are painted in without a `color`. Defaults to `"feature"`. */
|
|
62
|
+
role?: OverlayRole | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* Colour each arrow by its magnitude through this map: a position in `[0, 1]` to `[r, g, b]`
|
|
65
|
+
* (the maps of `@vitavision/charts` fit, as for `HeatmapLayer`). Pass a stable function.
|
|
66
|
+
* Magnitudes are quantised into 24 steps, one path each.
|
|
67
|
+
*/
|
|
68
|
+
colormap?: Colormap | undefined;
|
|
69
|
+
/** The magnitudes mapped onto `colormap`. Defaults to `0` to the longest vector. */
|
|
70
|
+
range?: ValueRange | undefined;
|
|
71
|
+
/** Ids by vector index. Defaults to the index. */
|
|
72
|
+
ids?: ArrayLike<PointId> | undefined;
|
|
73
|
+
/** The hovered id, when the app controls hover. */
|
|
74
|
+
hoveredId?: PointId | null | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Called when the vector under the pointer changes; `null` when it leaves every vector. A
|
|
77
|
+
* vector is picked at its anchor. Not called while `pickable` is off.
|
|
78
|
+
*/
|
|
79
|
+
onHoverChange?: ((id: PointId | null) => void) | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* A press landed on a vector's anchor. Setting it makes the layer claim presses there, so the
|
|
82
|
+
* stage does not pan from them.
|
|
83
|
+
*/
|
|
84
|
+
onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | undefined;
|
|
85
|
+
/** Draw the dark band under every arrow. On by default; off for a fast, flat layer. */
|
|
86
|
+
halo?: boolean | undefined;
|
|
87
|
+
/** Whether the layer takes part in the stage's hit-test. On by default. */
|
|
88
|
+
pickable?: boolean | undefined;
|
|
89
|
+
/** The id hit-tests report for this layer. Defaults to a generated one. */
|
|
90
|
+
layerId?: string | undefined;
|
|
91
|
+
/** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.point`. */
|
|
92
|
+
priority?: number | undefined;
|
|
93
|
+
/** The layer's accessible name. Defaults to "Vectors". */
|
|
94
|
+
label?: string | undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The reference vector of a scale and the scale it gives, shared by the layer and its key.
|
|
99
|
+
*
|
|
100
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
101
|
+
* @param scale - See `VectorScale`.
|
|
102
|
+
* @returns The reference magnitude in data units, and image pixels per data unit.
|
|
103
|
+
*/
|
|
104
|
+
export function useVectorScale(vectors: ArrayLike<number>, scale: VectorScale = DEFAULT_SCALE): { reference: number; perUnit: number } {
|
|
105
|
+
const unit = useScreenPx()(1);
|
|
106
|
+
const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
|
|
107
|
+
const percentile = typeof scale === "number" ? 1 : (scale.percentile ?? 1);
|
|
108
|
+
const reference = useMemo(() => magnitudePercentile(mags, percentile), [mags, percentile]);
|
|
109
|
+
return { reference, perUnit: imagePerUnit(scale, reference, unit) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `rgb(r g b)` of a map's colour, channels rounded and clamped. */
|
|
113
|
+
function css(colormap: Colormap, t: number): string {
|
|
114
|
+
const [r, g, b] = colormap(t);
|
|
115
|
+
const c = (v: number) => Math.min(255, Math.max(0, Math.round(v)));
|
|
116
|
+
return `rgb(${c(r)} ${c(g)} ${c(b)})`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A field of arrows inside an `ImageStage`.
|
|
121
|
+
*
|
|
122
|
+
* - **Scale**: see `VectorScale`. The same `vectors` and `scale` given to `VectorFieldKey` draw a
|
|
123
|
+
* reference length at exactly this scale.
|
|
124
|
+
* - **Colour**: one tone (`color` or `role`), or by magnitude through `colormap` over `range`.
|
|
125
|
+
* - **Absent data**: an anchor or vector with a non-finite number, or shorter than one screen
|
|
126
|
+
* pixel, is not drawn.
|
|
127
|
+
* - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here, and
|
|
128
|
+
* `useStageHitTest` for an app that arbitrates between layers. The hovered arrow is redrawn
|
|
129
|
+
* at 2.5 screen px in the selection colour.
|
|
130
|
+
*
|
|
131
|
+
* Arrowheads and strokes are screen-constant; their paths are regenerated when the zoom changes,
|
|
132
|
+
* and past 3,000 vectors only those near the viewport are generated. The SVG carries
|
|
133
|
+
* `data-hovered` (the hovered id) and `data-count` (the vectors drawn).
|
|
134
|
+
*/
|
|
135
|
+
export function VectorField({
|
|
136
|
+
anchors,
|
|
137
|
+
vectors,
|
|
138
|
+
scale = DEFAULT_SCALE,
|
|
139
|
+
color,
|
|
140
|
+
role = "feature",
|
|
141
|
+
colormap,
|
|
142
|
+
range,
|
|
143
|
+
ids,
|
|
144
|
+
hoveredId,
|
|
145
|
+
onHoverChange,
|
|
146
|
+
onItemPress,
|
|
147
|
+
halo = true,
|
|
148
|
+
pickable = true,
|
|
149
|
+
layerId,
|
|
150
|
+
priority = STAGE_HIT_PRIORITY.point,
|
|
151
|
+
label = "Vectors",
|
|
152
|
+
}: VectorFieldProps) {
|
|
153
|
+
const stage = useStage();
|
|
154
|
+
const px = useScreenPx();
|
|
155
|
+
const unit = px(1);
|
|
156
|
+
const count = Math.min(Math.floor(anchors.length / 2), Math.floor(vectors.length / 2));
|
|
157
|
+
|
|
158
|
+
const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
|
|
159
|
+
const { perUnit } = useVectorScale(vectors, scale);
|
|
160
|
+
const index = useMemo(() => buildPointIndex(anchors, { ids }), [anchors, ids]);
|
|
161
|
+
|
|
162
|
+
const [ownHover, setOwnHover] = useState<PointId | null>(null);
|
|
163
|
+
const hoverId = hoveredId !== undefined ? hoveredId : ownHover;
|
|
164
|
+
|
|
165
|
+
useStageHitLayer({
|
|
166
|
+
layerId,
|
|
167
|
+
priority,
|
|
168
|
+
enabled: pickable,
|
|
169
|
+
pick: (point, radius) => {
|
|
170
|
+
const hit = nearestPoint(index, point.x, point.y, radius);
|
|
171
|
+
return hit && hit.index < count && Number.isFinite(mags[hit.index]) ? { id: hit.id, dist: hit.dist } : null;
|
|
172
|
+
},
|
|
173
|
+
onHover: (id) => {
|
|
174
|
+
setOwnHover(id);
|
|
175
|
+
onHoverChange?.(id);
|
|
176
|
+
},
|
|
177
|
+
onPress: onItemPress,
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
const colourRange = useMemo(() => {
|
|
181
|
+
if (!colormap) return null;
|
|
182
|
+
if (range) return range;
|
|
183
|
+
let high = 0;
|
|
184
|
+
for (let i = 0; i < count; i++) if (mags[i]! > high) high = mags[i]!;
|
|
185
|
+
return { low: 0, high };
|
|
186
|
+
}, [colormap, range, mags, count]);
|
|
187
|
+
|
|
188
|
+
const cull = cullWindow(stage.view, stage.box, count, mags, perUnit);
|
|
189
|
+
const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
|
|
190
|
+
|
|
191
|
+
const built = useMemo(() => {
|
|
192
|
+
const bins = colormap && colourRange ? VECTOR_COLOR_BINS : 1;
|
|
193
|
+
const parts: string[] = new Array<string>(bins).fill("");
|
|
194
|
+
let drawn = 0;
|
|
195
|
+
for (let i = 0; i < count; i++) {
|
|
196
|
+
const m = mags[i]!;
|
|
197
|
+
const x = anchors[2 * i]!;
|
|
198
|
+
const y = anchors[2 * i + 1]!;
|
|
199
|
+
if (!Number.isFinite(m) || !Number.isFinite(x) || !Number.isFinite(y)) continue;
|
|
200
|
+
if (cull && (x < cull.x || x > cull.x + cull.width || y < cull.y || y > cull.y + cull.height)) continue;
|
|
201
|
+
const d = arrowPath(x, y, vectors[2 * i]! * perUnit, vectors[2 * i + 1]! * perUnit, unit, ARROW);
|
|
202
|
+
if (d === "") continue;
|
|
203
|
+
const bin = colormap && colourRange ? colorBin(m, colourRange.low, colourRange.high) : 0;
|
|
204
|
+
parts[bin] += d;
|
|
205
|
+
drawn++;
|
|
206
|
+
}
|
|
207
|
+
const batches = parts.flatMap((d, bin) => (d === "" ? [] : [{ bin, d }]));
|
|
208
|
+
return { parts, batches, drawn };
|
|
209
|
+
// `cullKey` stands for `cull`, which is a new object each render.
|
|
210
|
+
// oxlint-disable-next-line react-hooks/exhaustive-deps
|
|
211
|
+
}, [anchors, vectors, mags, count, perUnit, unit, colormap, colourRange, cullKey]);
|
|
212
|
+
|
|
213
|
+
const all = useMemo(() => built.parts.join(""), [built]);
|
|
214
|
+
const hoverIndex = hoverId === null ? -1 : findIndex(index, hoverId, count);
|
|
215
|
+
const hoverPath =
|
|
216
|
+
hoverIndex >= 0 && Number.isFinite(mags[hoverIndex])
|
|
217
|
+
? arrowPath(
|
|
218
|
+
anchors[2 * hoverIndex]!,
|
|
219
|
+
anchors[2 * hoverIndex + 1]!,
|
|
220
|
+
vectors[2 * hoverIndex]! * perUnit,
|
|
221
|
+
vectors[2 * hoverIndex + 1]! * perUnit,
|
|
222
|
+
unit,
|
|
223
|
+
ARROW,
|
|
224
|
+
)
|
|
225
|
+
: "";
|
|
226
|
+
|
|
227
|
+
const tone = color ?? overlayRole(role);
|
|
228
|
+
const width = px(OVERLAY_STATE_WIDTH.default);
|
|
229
|
+
const hoverWidth = px(OVERLAY_STATE_WIDTH.selected);
|
|
230
|
+
const HALO = overlayRole("halo");
|
|
231
|
+
|
|
232
|
+
return (
|
|
233
|
+
<svg
|
|
234
|
+
viewBox={imageViewBox(stage.image)}
|
|
235
|
+
className="pointer-events-none absolute inset-0 h-full w-full overflow-visible"
|
|
236
|
+
role="img"
|
|
237
|
+
aria-label={`${label}: ${built.drawn} ${built.drawn === 1 ? "vector" : "vectors"}`}
|
|
238
|
+
data-hovered={hoverId ?? undefined}
|
|
239
|
+
data-count={built.drawn}
|
|
240
|
+
>
|
|
241
|
+
<g fill="none" strokeLinecap="butt" strokeLinejoin="round">
|
|
242
|
+
{halo && all !== "" && <path data-halo="" d={all} stroke={HALO} fill={HALO} strokeWidth={width + px(2)} opacity={0.6} />}
|
|
243
|
+
{built.batches.map(({ bin, d }) => (
|
|
244
|
+
<path
|
|
245
|
+
key={bin}
|
|
246
|
+
data-batch={bin}
|
|
247
|
+
d={d}
|
|
248
|
+
stroke={colormap ? css(colormap, (bin + 0.5) / VECTOR_COLOR_BINS) : tone}
|
|
249
|
+
fill={colormap ? css(colormap, (bin + 0.5) / VECTOR_COLOR_BINS) : tone}
|
|
250
|
+
strokeWidth={width}
|
|
251
|
+
/>
|
|
252
|
+
))}
|
|
253
|
+
{hoverPath !== "" && (
|
|
254
|
+
<>
|
|
255
|
+
{halo && <path d={hoverPath} stroke={HALO} fill={HALO} strokeWidth={hoverWidth + px(2)} />}
|
|
256
|
+
<path
|
|
257
|
+
data-hovered-vector=""
|
|
258
|
+
d={hoverPath}
|
|
259
|
+
stroke={overlayRole("selection")}
|
|
260
|
+
fill={overlayRole("selection")}
|
|
261
|
+
strokeWidth={hoverWidth}
|
|
262
|
+
/>
|
|
263
|
+
</>
|
|
264
|
+
)}
|
|
265
|
+
</g>
|
|
266
|
+
</svg>
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The index of the vector with id `id`, or `-1`. */
|
|
271
|
+
function findIndex(index: { ids: ArrayLike<PointId> | null }, id: PointId, count: number): number {
|
|
272
|
+
if (index.ids === null) return typeof id === "number" && id >= 0 && id < count && Number.isInteger(id) ? id : -1;
|
|
273
|
+
for (let i = 0; i < Math.min(count, index.ids.length); i++) if (index.ids[i] === id) return i;
|
|
274
|
+
return -1;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* The window paths are generated for: the viewport plus the longest arrow on every side, snapped
|
|
279
|
+
* outward to half-viewport steps so panning rebuilds it once per half screen. `null` for a small
|
|
280
|
+
* field, or an unmeasured stage.
|
|
281
|
+
*/
|
|
282
|
+
function cullWindow(
|
|
283
|
+
view: { scale: number; tx: number; ty: number },
|
|
284
|
+
box: { width: number; height: number },
|
|
285
|
+
count: number,
|
|
286
|
+
mags: ArrayLike<number>,
|
|
287
|
+
perUnit: number,
|
|
288
|
+
): Rect | null {
|
|
289
|
+
if (count <= CULL_ABOVE) return null;
|
|
290
|
+
const visible = visibleRect(view, box);
|
|
291
|
+
if (visible === null) return null;
|
|
292
|
+
let longest = 0;
|
|
293
|
+
for (let i = 0; i < count; i++) if (mags[i]! > longest) longest = mags[i]!;
|
|
294
|
+
const sx = visible.width / 2;
|
|
295
|
+
const sy = visible.height / 2;
|
|
296
|
+
const reach = Math.min(longest * perUnit, visible.width, visible.height);
|
|
297
|
+
const left = Math.floor((visible.x - sx - reach) / sx) * sx;
|
|
298
|
+
const top = Math.floor((visible.y - sy - reach) / sy) * sy;
|
|
299
|
+
const right = Math.ceil((visible.x + visible.width + sx + reach) / sx) * sx;
|
|
300
|
+
const bottom = Math.ceil((visible.y + visible.height + sy + reach) / sy) * sy;
|
|
301
|
+
return { x: left, y: top, width: right - left, height: bottom - top };
|
|
302
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The reference length of a `VectorField`: an arrow of a round length with its value, so a
|
|
3
|
+
* reader can turn arrow lengths back into data units.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { cn } from "@vitavision/ui";
|
|
7
|
+
|
|
8
|
+
import { useStage } from "./stage/ImageStage";
|
|
9
|
+
import { arrowPath, niceLength, type ArrowStyle, type VectorScale } from "./vectorGeometry";
|
|
10
|
+
import { useVectorScale } from "./VectorField";
|
|
11
|
+
|
|
12
|
+
/** Props of `VectorFieldKey`. */
|
|
13
|
+
export interface VectorFieldKeyProps {
|
|
14
|
+
/** The field's `vectors`: the scale of an automatic `scale` depends on them. */
|
|
15
|
+
vectors: ArrayLike<number>;
|
|
16
|
+
/** The field's `scale`, so the key is drawn at exactly the field's scale. Defaults as `VectorField` does. */
|
|
17
|
+
scale?: VectorScale | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* The length the key shows, in data units. Defaults to the largest 1, 2 or 5 times a power of
|
|
20
|
+
* ten that is at most the field's reference vector.
|
|
21
|
+
*/
|
|
22
|
+
length?: number | undefined;
|
|
23
|
+
/** The data unit, written after the value (`px`, `m/s`). */
|
|
24
|
+
unit?: string | undefined;
|
|
25
|
+
/** Formats the value. Defaults to at most 3 significant figures, without trailing zeros. */
|
|
26
|
+
format?: ((value: number) => string) | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* Draw without its own dark chip, for a place that has one already: the `extra` of a
|
|
29
|
+
* `StageReadout`. Off by default.
|
|
30
|
+
*/
|
|
31
|
+
bare?: boolean | undefined;
|
|
32
|
+
/** Merged onto the key with `cn`. */
|
|
33
|
+
className?: string | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const KEY_ARROW: ArrowStyle = { head: 5, headWidth: 0.7, minLength: 1 };
|
|
37
|
+
/** The key is not drawn wider than this, in screen pixels. */
|
|
38
|
+
const MAX_WIDTH = 160;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* An arrow of a known length and its value ("0.1 px"). Pass it as `ImageStage`'s `readout`, or
|
|
42
|
+
* as the `extra` of a `StageReadout` with `bare`; it reads the stage's zoom through `useStage`, so it stays
|
|
43
|
+
* true as the view changes, and draws nothing while the field has no scale or the arrow would
|
|
44
|
+
* be wider than 160 screen pixels.
|
|
45
|
+
*
|
|
46
|
+
* On its own it is drawn in the readout's light-on-dark chip, so it sits on the image like the readout does.
|
|
47
|
+
*/
|
|
48
|
+
export function VectorFieldKey({
|
|
49
|
+
vectors,
|
|
50
|
+
scale,
|
|
51
|
+
length,
|
|
52
|
+
unit,
|
|
53
|
+
format = (value) => String(Number(value.toPrecision(3))),
|
|
54
|
+
bare = false,
|
|
55
|
+
className,
|
|
56
|
+
}: VectorFieldKeyProps) {
|
|
57
|
+
const stage = useStage();
|
|
58
|
+
const { reference, perUnit } = useVectorScale(vectors, scale);
|
|
59
|
+
const value = length ?? niceLength(reference);
|
|
60
|
+
const width = value * perUnit * stage.view.scale;
|
|
61
|
+
if (!(value > 0) || !(width >= 1) || width > MAX_WIDTH) return null;
|
|
62
|
+
const pad = 1;
|
|
63
|
+
return (
|
|
64
|
+
<span
|
|
65
|
+
className={cn(
|
|
66
|
+
"inline-flex items-center gap-1.5 align-middle font-mono text-[10px] tabular-nums",
|
|
67
|
+
!bare && "rounded-control bg-black/60 px-1.5 py-0.5 text-white",
|
|
68
|
+
className,
|
|
69
|
+
)}
|
|
70
|
+
data-vector-key=""
|
|
71
|
+
title={`Arrow length: ${unit ? `${format(value)} ${unit}` : format(value)}`}
|
|
72
|
+
>
|
|
73
|
+
<svg
|
|
74
|
+
aria-hidden
|
|
75
|
+
width={width + 2 * pad}
|
|
76
|
+
height={10}
|
|
77
|
+
viewBox={`${-pad} -5 ${width + 2 * pad} 10`}
|
|
78
|
+
className="shrink-0 overflow-visible"
|
|
79
|
+
>
|
|
80
|
+
<path
|
|
81
|
+
d={arrowPath(0, 0, width, 0, 1, KEY_ARROW)}
|
|
82
|
+
fill="currentColor"
|
|
83
|
+
stroke="currentColor"
|
|
84
|
+
strokeWidth={1.5}
|
|
85
|
+
strokeLinejoin="round"
|
|
86
|
+
/>
|
|
87
|
+
</svg>
|
|
88
|
+
<span>{unit ? `${format(value)} ${unit}` : format(value)}</span>
|
|
89
|
+
</span>
|
|
90
|
+
);
|
|
91
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Iso-lines of a scalar field: marching squares over a `ValuePlane` channel.
|
|
3
|
+
*
|
|
4
|
+
* Pure and deterministic. The plane's samples are nodes (at pixel centres); a cell is the four nodes
|
|
5
|
+
* of a 2×2 block. A node is *above* a level when its value is `>=` the level. Each cell that mixes
|
|
6
|
+
* above and below nodes holds one segment (two in a saddle), its ends at the linear crossings of the
|
|
7
|
+
* cell's edges. A cell with a `NaN` (or infinite) node holds none, so a line stops at a hole and
|
|
8
|
+
* never bridges it. Segments are chained into polylines through the edge they share.
|
|
9
|
+
*
|
|
10
|
+
* Coordinates are in nodes: `(i, j)` is the centre of the plane's pixel `(i, j)`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { ValuePlane } from "../api/mapValues";
|
|
14
|
+
|
|
15
|
+
/** One iso-line: a polyline at a level. */
|
|
16
|
+
export interface ContourLine {
|
|
17
|
+
/** The level it lies on. */
|
|
18
|
+
level: number;
|
|
19
|
+
/** Flat `[x0, y0, x1, y1, …]` in nodes. For a closed line the first point is not repeated. */
|
|
20
|
+
points: number[];
|
|
21
|
+
/** Whether it returns to its start. */
|
|
22
|
+
closed: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The most levels a `step` is allowed to produce; a finer step is widened by whole multiples. */
|
|
26
|
+
export const MAX_LEVELS = 64;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The levels to draw.
|
|
30
|
+
*
|
|
31
|
+
* @param spec - Explicit levels (non-finite ones are dropped, duplicates merged), or `{ step }`:
|
|
32
|
+
* every multiple of `step` (offset by `origin`) inside `[min, max]`. If that gives more than
|
|
33
|
+
* `MAX_LEVELS` levels the step is multiplied by a whole number until it does not.
|
|
34
|
+
* @param min - The field's smallest finite value, for a step.
|
|
35
|
+
* @param max - The field's largest finite value.
|
|
36
|
+
* @returns Ascending, distinct levels.
|
|
37
|
+
*/
|
|
38
|
+
export function resolveLevels(spec: readonly number[] | { step: number; origin?: number | undefined }, min: number, max: number): number[] {
|
|
39
|
+
if (Array.isArray(spec) || ArrayBuffer.isView(spec)) {
|
|
40
|
+
return [...new Set((spec as readonly number[]).filter(Number.isFinite))].sort((a, b) => a - b);
|
|
41
|
+
}
|
|
42
|
+
const { step, origin = 0 } = spec as { step: number; origin?: number | undefined };
|
|
43
|
+
if (!(step > 0) || !Number.isFinite(step) || !Number.isFinite(min) || !Number.isFinite(max) || max < min) return [];
|
|
44
|
+
let use = step;
|
|
45
|
+
while ((max - min) / use > MAX_LEVELS) use += step;
|
|
46
|
+
const first = Math.ceil((min - origin) / use - 1e-9);
|
|
47
|
+
const last = Math.floor((max - origin) / use + 1e-9);
|
|
48
|
+
const levels: number[] = [];
|
|
49
|
+
for (let k = first; k <= last; k++) levels.push(origin + k * use);
|
|
50
|
+
return levels;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The finite extent of one channel of a plane, `null` when it has no finite value. */
|
|
54
|
+
export function channelExtent(plane: ValuePlane, channel = 0): [number, number] | null {
|
|
55
|
+
const size = plane.width * plane.height;
|
|
56
|
+
const base = channel * size;
|
|
57
|
+
let min = Infinity;
|
|
58
|
+
let max = -Infinity;
|
|
59
|
+
for (let k = 0; k < size; k++) {
|
|
60
|
+
const v = plane.values[base + k]!;
|
|
61
|
+
if (v < min) min = v;
|
|
62
|
+
if (v > max) max = v;
|
|
63
|
+
}
|
|
64
|
+
return min <= max && Number.isFinite(min) && Number.isFinite(max) ? [min, max] : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Edge ids: a horizontal edge from node (i, j) to (i + 1, j) is `2 (j w + i)`, a vertical edge from
|
|
68
|
+
// (i, j) to (i, j + 1) is `2 (j w + i) + 1`. One crossing lies on each edge, so segments of
|
|
69
|
+
// neighbouring cells meet at equal ids.
|
|
70
|
+
|
|
71
|
+
/** Segment endpoints (as edges `T`op, `R`ight, `B`ottom, `L`eft) for each case; corners a b c d clockwise from top-left, a = 8. */
|
|
72
|
+
const T = 0;
|
|
73
|
+
const R = 1;
|
|
74
|
+
const B = 2;
|
|
75
|
+
const L = 3;
|
|
76
|
+
const CASES: readonly (readonly (readonly [number, number])[])[] = [
|
|
77
|
+
[],
|
|
78
|
+
[[L, B]],
|
|
79
|
+
[[B, R]],
|
|
80
|
+
[[L, R]],
|
|
81
|
+
[[T, R]],
|
|
82
|
+
[], // saddle, below
|
|
83
|
+
[[T, B]],
|
|
84
|
+
[[T, L]],
|
|
85
|
+
[[T, L]],
|
|
86
|
+
[[T, B]],
|
|
87
|
+
[], // saddle, below
|
|
88
|
+
[[T, R]],
|
|
89
|
+
[[L, R]],
|
|
90
|
+
[[B, R]],
|
|
91
|
+
[[L, B]],
|
|
92
|
+
[],
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The iso-lines of one channel at one level.
|
|
97
|
+
*
|
|
98
|
+
* @param values - The samples, row-major within the channel (`plane.values`).
|
|
99
|
+
* @param width - Columns (nodes).
|
|
100
|
+
* @param height - Rows.
|
|
101
|
+
* @param level - The level.
|
|
102
|
+
* @param offset - Index of the channel's first sample. Default 0.
|
|
103
|
+
* @returns The lines, in a deterministic order (by the first cell, row-major, each line starting
|
|
104
|
+
* at its first segment). Empty for a plane under 2×2 nodes.
|
|
105
|
+
*/
|
|
106
|
+
export function contourAtLevel(values: ArrayLike<number>, width: number, height: number, level: number, offset = 0): ContourLine[] {
|
|
107
|
+
if (!(width >= 2 && height >= 2) || !Number.isFinite(level)) return [];
|
|
108
|
+
const edgeId = (i: number, j: number, edge: number): number => {
|
|
109
|
+
switch (edge) {
|
|
110
|
+
case T:
|
|
111
|
+
return 2 * (j * width + i);
|
|
112
|
+
case B:
|
|
113
|
+
return 2 * ((j + 1) * width + i);
|
|
114
|
+
case L:
|
|
115
|
+
return 2 * (j * width + i) + 1;
|
|
116
|
+
default:
|
|
117
|
+
return 2 * (j * width + i + 1) + 1;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const segments: [number, number][] = [];
|
|
122
|
+
for (let j = 0; j < height - 1; j++) {
|
|
123
|
+
for (let i = 0; i < width - 1; i++) {
|
|
124
|
+
const a = values[offset + j * width + i]!;
|
|
125
|
+
const b = values[offset + j * width + i + 1]!;
|
|
126
|
+
const c = values[offset + (j + 1) * width + i + 1]!;
|
|
127
|
+
const d = values[offset + (j + 1) * width + i]!;
|
|
128
|
+
// `NaN` fails every comparison; an infinity has no finite crossing. Either leaves the cell empty.
|
|
129
|
+
if (!(Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(c) && Number.isFinite(d))) continue;
|
|
130
|
+
const index = (a >= level ? 8 : 0) | (b >= level ? 4 : 0) | (c >= level ? 2 : 0) | (d >= level ? 1 : 0);
|
|
131
|
+
let pairs = CASES[index]!;
|
|
132
|
+
if (index === 5 || index === 10) {
|
|
133
|
+
// A saddle. The cell's mean decides whether the above corners are joined through the middle.
|
|
134
|
+
const joined = (a + b + c + d) / 4 >= level;
|
|
135
|
+
pairs =
|
|
136
|
+
index === 5
|
|
137
|
+
? joined
|
|
138
|
+
? [
|
|
139
|
+
[T, L],
|
|
140
|
+
[B, R],
|
|
141
|
+
]
|
|
142
|
+
: [
|
|
143
|
+
[T, R],
|
|
144
|
+
[L, B],
|
|
145
|
+
]
|
|
146
|
+
: joined
|
|
147
|
+
? [
|
|
148
|
+
[T, R],
|
|
149
|
+
[L, B],
|
|
150
|
+
]
|
|
151
|
+
: [
|
|
152
|
+
[T, L],
|
|
153
|
+
[B, R],
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
for (const [e0, e1] of pairs) segments.push([edgeId(i, j, e0), edgeId(i, j, e1)]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (segments.length === 0) return [];
|
|
160
|
+
|
|
161
|
+
// Each edge id has at most two segments.
|
|
162
|
+
const at = new Map<number, number[]>();
|
|
163
|
+
segments.forEach(([p, q], s) => {
|
|
164
|
+
for (const id of [p, q]) {
|
|
165
|
+
const list = at.get(id);
|
|
166
|
+
if (list) list.push(s);
|
|
167
|
+
else at.set(id, [s]);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const crossing = (id: number): [number, number] => {
|
|
172
|
+
const vertical = id % 2 === 1;
|
|
173
|
+
const node = (id - (vertical ? 1 : 0)) / 2;
|
|
174
|
+
const i = node % width;
|
|
175
|
+
const j = (node - i) / width;
|
|
176
|
+
const v0 = values[offset + node]!;
|
|
177
|
+
const v1 = values[offset + node + (vertical ? width : 1)]!;
|
|
178
|
+
const t = Math.min(1, Math.max(0, (level - v0) / (v1 - v0)));
|
|
179
|
+
return vertical ? [i, j + t] : [i + t, j];
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const used = new Uint8Array(segments.length);
|
|
183
|
+
const lines: ContourLine[] = [];
|
|
184
|
+
for (let s = 0; s < segments.length; s++) {
|
|
185
|
+
if (used[s]) continue;
|
|
186
|
+
used[s] = 1;
|
|
187
|
+
const ids = [segments[s]![0], segments[s]![1]];
|
|
188
|
+
// Forward from the tail, then backward from the head, until a loop closes or the line ends.
|
|
189
|
+
walk(ids, at, segments, used, true);
|
|
190
|
+
walk(ids, at, segments, used, false);
|
|
191
|
+
const closed = ids.length > 2 && ids[0] === ids[ids.length - 1];
|
|
192
|
+
if (closed) ids.pop();
|
|
193
|
+
const points: number[] = [];
|
|
194
|
+
for (const id of ids) points.push(...crossing(id));
|
|
195
|
+
lines.push({ level, points, closed });
|
|
196
|
+
}
|
|
197
|
+
return lines;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Extends a chain of edge ids at its tail (`forward`) or head by the unused segments meeting there. */
|
|
201
|
+
function walk(ids: number[], at: Map<number, number[]>, segments: readonly [number, number][], used: Uint8Array, forward: boolean): void {
|
|
202
|
+
for (;;) {
|
|
203
|
+
const end = forward ? ids[ids.length - 1]! : ids[0]!;
|
|
204
|
+
if (ids.length > 2 && ids[0] === ids[ids.length - 1]) return;
|
|
205
|
+
const next = at.get(end)!.find((other) => !used[other]);
|
|
206
|
+
if (next === undefined) return;
|
|
207
|
+
used[next] = 1;
|
|
208
|
+
const [p, q] = segments[next]!;
|
|
209
|
+
const far = p === end ? q : p;
|
|
210
|
+
if (forward) ids.push(far);
|
|
211
|
+
else ids.unshift(far);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The iso-lines of a plane's channel at every level, lowest level first.
|
|
217
|
+
*
|
|
218
|
+
* @param plane - The field; `NaN` is "no data".
|
|
219
|
+
* @param channel - Which channel. Default 0; out of range gives no lines.
|
|
220
|
+
* @param levels - See `resolveLevels`; the lines of each level, in turn.
|
|
221
|
+
*/
|
|
222
|
+
export function contourPaths(plane: ValuePlane, channel: number, levels: readonly number[]): ContourLine[] {
|
|
223
|
+
if (!Number.isInteger(channel) || channel < 0 || channel >= plane.channels) return [];
|
|
224
|
+
const offset = channel * plane.width * plane.height;
|
|
225
|
+
return levels.flatMap((level) => contourAtLevel(plane.values, plane.width, plane.height, level, offset));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Total length of a polyline (closing segment included for a closed line), in nodes. */
|
|
229
|
+
export function lineLength(line: ContourLine): number {
|
|
230
|
+
const p = line.points;
|
|
231
|
+
let length = 0;
|
|
232
|
+
for (let k = 2; k < p.length; k += 2) length += Math.hypot(p[k]! - p[k - 2]!, p[k + 1]! - p[k - 1]!);
|
|
233
|
+
if (line.closed && p.length >= 4) length += Math.hypot(p[0]! - p[p.length - 2]!, p[1]! - p[p.length - 1]!);
|
|
234
|
+
return length;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Points along a line at fractions of its length, for placing labels.
|
|
239
|
+
*
|
|
240
|
+
* @param line - The line.
|
|
241
|
+
* @param count - How many labels; they sit at `(k + 0.5) / count` of the arc length.
|
|
242
|
+
* @returns `[x, y]` per label, in nodes.
|
|
243
|
+
*/
|
|
244
|
+
export function pointsAlong(line: ContourLine, count: number): [number, number][] {
|
|
245
|
+
const p = line.points;
|
|
246
|
+
const n = p.length / 2;
|
|
247
|
+
if (n === 0 || count < 1) return [];
|
|
248
|
+
const total = lineLength(line);
|
|
249
|
+
if (n === 1 || total === 0) return [[p[0]!, p[1]!]];
|
|
250
|
+
const out: [number, number][] = [];
|
|
251
|
+
const segs = line.closed ? n : n - 1;
|
|
252
|
+
for (let k = 0; k < count; k++) {
|
|
253
|
+
let target = ((k + 0.5) / count) * total;
|
|
254
|
+
for (let s = 0; s < segs; s++) {
|
|
255
|
+
const x0 = p[2 * s]!;
|
|
256
|
+
const y0 = p[2 * s + 1]!;
|
|
257
|
+
const t = (s + 1) % n;
|
|
258
|
+
const x1 = p[2 * t]!;
|
|
259
|
+
const y1 = p[2 * t + 1]!;
|
|
260
|
+
const len = Math.hypot(x1 - x0, y1 - y0);
|
|
261
|
+
if (target <= len || s === segs - 1) {
|
|
262
|
+
const f = len === 0 ? 0 : Math.min(1, target / len);
|
|
263
|
+
out.push([x0 + f * (x1 - x0), y0 + f * (y1 - y0)]);
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
target -= len;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return out;
|
|
270
|
+
}
|