@vitavision/stage2d 0.14.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -1
- package/dist/index.d.ts +333 -2
- package/dist/index.js +875 -34
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/ContourLayer.tsx +211 -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/stage/ImageLayer.tsx +63 -4
- package/src/components/vectorGeometry.ts +159 -0
- package/src/index.ts +16 -0
package/dist/index.js
CHANGED
|
@@ -2169,6 +2169,8 @@ function CompareLayer({ a, b, mode, split, defaultSplit = .5, onSplitChange, ori
|
|
|
2169
2169
|
* - **Pixelated past a zoom.** Above about 4× the browser's smoothing paints detail the
|
|
2170
2170
|
* sensor never recorded; on a metrology bench the sensor's own samples are what is worth
|
|
2171
2171
|
* looking at.
|
|
2172
|
+
* - **A display tone curve.** A dark or low-contrast frame is read with a gain and a gamma
|
|
2173
|
+
* applied on screen only (`gain`, `gamma`): the pixels the app measures are untouched.
|
|
2172
2174
|
*/
|
|
2173
2175
|
/**
|
|
2174
2176
|
* The photograph at its natural size inside an `ImageStage`, with an optional preview tier
|
|
@@ -2178,12 +2180,17 @@ function CompareLayer({ a, b, mode, split, defaultSplit = .5, onSplitChange, ori
|
|
|
2178
2180
|
* With a `preview`, the full image is wanted once the stage would magnify the preview, and
|
|
2179
2181
|
* `onFullNeeded` says so; `src` can be supplied then rather than up front.
|
|
2180
2182
|
*
|
|
2183
|
+
* With a `gain` or `gamma` other than 1, both images are drawn through one SVG tone-curve filter
|
|
2184
|
+
* (sRGB values, per channel) and carry `data-adjusted`.
|
|
2185
|
+
*
|
|
2181
2186
|
* Each image carries `data-tier` (`preview` or `full`); the full image carries `data-loaded`
|
|
2182
2187
|
* once it has loaded, the preview carries `data-wants-full` from the moment the full image is
|
|
2183
2188
|
* wanted until it has loaded, and both carry `data-pixelated` while pixelated.
|
|
2184
2189
|
*/
|
|
2185
|
-
function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded, onLoad, onError, className }) {
|
|
2190
|
+
function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded, onLoad, onError, gain, gamma, className }) {
|
|
2186
2191
|
const stage = useStage();
|
|
2192
|
+
const curve = toneCurve(gain, gamma);
|
|
2193
|
+
const filterId = `stage-image-tone-${useId().replace(/[^A-Za-z0-9_-]/g, "")}`;
|
|
2187
2194
|
const scale = stage.view.scale;
|
|
2188
2195
|
const measured = stage.box.width > 0;
|
|
2189
2196
|
const previewSrc = preview?.src ?? null;
|
|
@@ -2206,32 +2213,86 @@ function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded, onLoa
|
|
|
2206
2213
|
const fullReady = src !== void 0 && loaded === src;
|
|
2207
2214
|
const pixelated = scale >= pixelatedAbove;
|
|
2208
2215
|
const shared = cn("pointer-events-none absolute inset-0 h-full w-full select-none", className);
|
|
2209
|
-
const
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2216
|
+
const style = {
|
|
2217
|
+
imageRendering: pixelated ? "pixelated" : void 0,
|
|
2218
|
+
filter: curve ? `url(#${filterId})` : void 0
|
|
2219
|
+
};
|
|
2220
|
+
const adjusted = curve ? "" : void 0;
|
|
2221
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
2222
|
+
curve && /* @__PURE__ */ jsx("svg", {
|
|
2223
|
+
"aria-hidden": "true",
|
|
2224
|
+
width: "0",
|
|
2225
|
+
height: "0",
|
|
2226
|
+
className: "pointer-events-none absolute",
|
|
2227
|
+
focusable: "false",
|
|
2228
|
+
children: /* @__PURE__ */ jsx("filter", {
|
|
2229
|
+
id: filterId,
|
|
2230
|
+
colorInterpolationFilters: "sRGB",
|
|
2231
|
+
"data-tone-curve": "",
|
|
2232
|
+
children: /* @__PURE__ */ jsxs("feComponentTransfer", { children: [
|
|
2233
|
+
/* @__PURE__ */ jsx("feFuncR", {
|
|
2234
|
+
type: "gamma",
|
|
2235
|
+
amplitude: curve.amplitude,
|
|
2236
|
+
exponent: curve.exponent,
|
|
2237
|
+
offset: 0
|
|
2238
|
+
}),
|
|
2239
|
+
/* @__PURE__ */ jsx("feFuncG", {
|
|
2240
|
+
type: "gamma",
|
|
2241
|
+
amplitude: curve.amplitude,
|
|
2242
|
+
exponent: curve.exponent,
|
|
2243
|
+
offset: 0
|
|
2244
|
+
}),
|
|
2245
|
+
/* @__PURE__ */ jsx("feFuncB", {
|
|
2246
|
+
type: "gamma",
|
|
2247
|
+
amplitude: curve.amplitude,
|
|
2248
|
+
exponent: curve.exponent,
|
|
2249
|
+
offset: 0
|
|
2250
|
+
})
|
|
2251
|
+
] })
|
|
2252
|
+
})
|
|
2253
|
+
}),
|
|
2254
|
+
preview && !fullReady && /* @__PURE__ */ jsx("img", {
|
|
2255
|
+
src: preview.src,
|
|
2256
|
+
alt: showFull ? "" : alt,
|
|
2257
|
+
"aria-hidden": showFull ? true : void 0,
|
|
2258
|
+
draggable: false,
|
|
2259
|
+
"data-tier": "preview",
|
|
2260
|
+
"data-wants-full": wanted ? "" : void 0,
|
|
2261
|
+
"data-pixelated": pixelated ? "" : void 0,
|
|
2262
|
+
"data-adjusted": adjusted,
|
|
2263
|
+
className: shared,
|
|
2264
|
+
style
|
|
2265
|
+
}),
|
|
2266
|
+
showFull && /* @__PURE__ */ jsx("img", {
|
|
2267
|
+
src,
|
|
2268
|
+
alt,
|
|
2269
|
+
draggable: false,
|
|
2270
|
+
"data-tier": "full",
|
|
2271
|
+
"data-loaded": fullReady ? "" : void 0,
|
|
2272
|
+
"data-pixelated": pixelated ? "" : void 0,
|
|
2273
|
+
"data-adjusted": adjusted,
|
|
2274
|
+
onLoad: () => {
|
|
2275
|
+
setLoaded(src);
|
|
2276
|
+
onLoad?.();
|
|
2277
|
+
},
|
|
2278
|
+
onError: () => onError?.(),
|
|
2279
|
+
className: cn(shared, preview && !fullReady && "opacity-0"),
|
|
2280
|
+
style
|
|
2281
|
+
})
|
|
2282
|
+
] });
|
|
2283
|
+
}
|
|
2284
|
+
/**
|
|
2285
|
+
* The `feFuncX type="gamma"` parameters (`amplitude × v^exponent`) for a gain and a gamma, or
|
|
2286
|
+
* `null` when the curve is the identity and no filter is needed.
|
|
2287
|
+
*/
|
|
2288
|
+
function toneCurve(gain, gamma) {
|
|
2289
|
+
const amplitude = gain === void 0 || !Number.isFinite(gain) ? 1 : Math.max(0, gain);
|
|
2290
|
+
const g = gamma === void 0 || !(gamma > 0) || !Number.isFinite(gamma) ? 1 : gamma;
|
|
2291
|
+
if (amplitude === 1 && g === 1) return null;
|
|
2292
|
+
return {
|
|
2293
|
+
amplitude,
|
|
2294
|
+
exponent: 1 / g
|
|
2295
|
+
};
|
|
2235
2296
|
}
|
|
2236
2297
|
//#endregion
|
|
2237
2298
|
//#region src/components/stage/StageToolbar.tsx
|
|
@@ -4667,7 +4728,7 @@ function range(from, to) {
|
|
|
4667
4728
|
*/
|
|
4668
4729
|
const HALO$8 = overlayRole("halo");
|
|
4669
4730
|
/** Dash, gap, outline width and vertex dot size, in screen pixels. */
|
|
4670
|
-
const DASH = 6;
|
|
4731
|
+
const DASH$1 = 6;
|
|
4671
4732
|
const GAP = 4;
|
|
4672
4733
|
const STROKE_PX$2 = 1.5;
|
|
4673
4734
|
const VERTEX_PX = 6;
|
|
@@ -4691,7 +4752,7 @@ function DraftShape({ shape, role = "selection", stroke, halo = true }) {
|
|
|
4691
4752
|
const stage = useStage();
|
|
4692
4753
|
const px = useScreenPx();
|
|
4693
4754
|
const colour = stroke ?? overlayRole(role);
|
|
4694
|
-
const dash = `${px(DASH)} ${px(GAP)}`;
|
|
4755
|
+
const dash = `${px(DASH$1)} ${px(GAP)}`;
|
|
4695
4756
|
const width = px(STROKE_PX$2);
|
|
4696
4757
|
const parts = shape ? draftParts(shape, px(1)) : null;
|
|
4697
4758
|
return /* @__PURE__ */ jsx("svg", {
|
|
@@ -6049,7 +6110,7 @@ const MARKER_SHAPES = {
|
|
|
6049
6110
|
* plus at most 200 labels.
|
|
6050
6111
|
*/
|
|
6051
6112
|
/** Past this many points, outlines are generated for the visible part only. */
|
|
6052
|
-
const CULL_ABOVE = 3e3;
|
|
6113
|
+
const CULL_ABOVE$1 = 3e3;
|
|
6053
6114
|
/** How much bigger than a marker its selection ring is, in screen pixels. */
|
|
6054
6115
|
const RING_GAP = 4;
|
|
6055
6116
|
const HALO$5 = overlayRole("halo");
|
|
@@ -6171,7 +6232,7 @@ function PointSet({ items, kind = "dot", markers, hoveredId, onHoverChange, sele
|
|
|
6171
6232
|
selectedSet,
|
|
6172
6233
|
isDimmed
|
|
6173
6234
|
]);
|
|
6174
|
-
const cull = cullWindow(stage.view, stage.box, items.length);
|
|
6235
|
+
const cull = cullWindow$1(stage.view, stage.box, items.length);
|
|
6175
6236
|
const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
|
|
6176
6237
|
const build = (batches) => batches.map((batch) => ({
|
|
6177
6238
|
batch,
|
|
@@ -6322,8 +6383,8 @@ function batchPath$1(batch, items, unit, cull, cullKey) {
|
|
|
6322
6383
|
* The window outlines are generated for: the viewport plus half a viewport on every side,
|
|
6323
6384
|
* snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.
|
|
6324
6385
|
*/
|
|
6325
|
-
function cullWindow(view, box, count) {
|
|
6326
|
-
if (count <= CULL_ABOVE) return null;
|
|
6386
|
+
function cullWindow$1(view, box, count) {
|
|
6387
|
+
if (count <= CULL_ABOVE$1) return null;
|
|
6327
6388
|
const visible = visibleRect(view, box);
|
|
6328
6389
|
if (visible === null) return null;
|
|
6329
6390
|
const sx = visible.width / 2;
|
|
@@ -7834,6 +7895,786 @@ function colourPlane(plane, colormap, range, channel) {
|
|
|
7834
7895
|
height: plane.height
|
|
7835
7896
|
};
|
|
7836
7897
|
}
|
|
7898
|
+
/**
|
|
7899
|
+
* The levels to draw.
|
|
7900
|
+
*
|
|
7901
|
+
* @param spec - Explicit levels (non-finite ones are dropped, duplicates merged), or `{ step }`:
|
|
7902
|
+
* every multiple of `step` (offset by `origin`) inside `[min, max]`. If that gives more than
|
|
7903
|
+
* `MAX_LEVELS` levels the step is multiplied by a whole number until it does not.
|
|
7904
|
+
* @param min - The field's smallest finite value, for a step.
|
|
7905
|
+
* @param max - The field's largest finite value.
|
|
7906
|
+
* @returns Ascending, distinct levels.
|
|
7907
|
+
*/
|
|
7908
|
+
function resolveLevels(spec, min, max) {
|
|
7909
|
+
if (Array.isArray(spec) || ArrayBuffer.isView(spec)) return [...new Set(spec.filter(Number.isFinite))].sort((a, b) => a - b);
|
|
7910
|
+
const { step, origin = 0 } = spec;
|
|
7911
|
+
if (!(step > 0) || !Number.isFinite(step) || !Number.isFinite(min) || !Number.isFinite(max) || max < min) return [];
|
|
7912
|
+
let use = step;
|
|
7913
|
+
while ((max - min) / use > 64) use += step;
|
|
7914
|
+
const first = Math.ceil((min - origin) / use - 1e-9);
|
|
7915
|
+
const last = Math.floor((max - origin) / use + 1e-9);
|
|
7916
|
+
const levels = [];
|
|
7917
|
+
for (let k = first; k <= last; k++) levels.push(origin + k * use);
|
|
7918
|
+
return levels;
|
|
7919
|
+
}
|
|
7920
|
+
/** The finite extent of one channel of a plane, `null` when it has no finite value. */
|
|
7921
|
+
function channelExtent(plane, channel = 0) {
|
|
7922
|
+
const size = plane.width * plane.height;
|
|
7923
|
+
const base = channel * size;
|
|
7924
|
+
let min = Infinity;
|
|
7925
|
+
let max = -Infinity;
|
|
7926
|
+
for (let k = 0; k < size; k++) {
|
|
7927
|
+
const v = plane.values[base + k];
|
|
7928
|
+
if (v < min) min = v;
|
|
7929
|
+
if (v > max) max = v;
|
|
7930
|
+
}
|
|
7931
|
+
return min <= max && Number.isFinite(min) && Number.isFinite(max) ? [min, max] : null;
|
|
7932
|
+
}
|
|
7933
|
+
/** 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. */
|
|
7934
|
+
const T = 0;
|
|
7935
|
+
const R = 1;
|
|
7936
|
+
const B = 2;
|
|
7937
|
+
const L = 3;
|
|
7938
|
+
const CASES = [
|
|
7939
|
+
[],
|
|
7940
|
+
[[L, B]],
|
|
7941
|
+
[[B, R]],
|
|
7942
|
+
[[L, R]],
|
|
7943
|
+
[[T, R]],
|
|
7944
|
+
[],
|
|
7945
|
+
[[T, B]],
|
|
7946
|
+
[[T, L]],
|
|
7947
|
+
[[T, L]],
|
|
7948
|
+
[[T, B]],
|
|
7949
|
+
[],
|
|
7950
|
+
[[T, R]],
|
|
7951
|
+
[[L, R]],
|
|
7952
|
+
[[B, R]],
|
|
7953
|
+
[[L, B]],
|
|
7954
|
+
[]
|
|
7955
|
+
];
|
|
7956
|
+
/**
|
|
7957
|
+
* The iso-lines of one channel at one level.
|
|
7958
|
+
*
|
|
7959
|
+
* @param values - The samples, row-major within the channel (`plane.values`).
|
|
7960
|
+
* @param width - Columns (nodes).
|
|
7961
|
+
* @param height - Rows.
|
|
7962
|
+
* @param level - The level.
|
|
7963
|
+
* @param offset - Index of the channel's first sample. Default 0.
|
|
7964
|
+
* @returns The lines, in a deterministic order (by the first cell, row-major, each line starting
|
|
7965
|
+
* at its first segment). Empty for a plane under 2×2 nodes.
|
|
7966
|
+
*/
|
|
7967
|
+
function contourAtLevel(values, width, height, level, offset = 0) {
|
|
7968
|
+
if (!(width >= 2 && height >= 2) || !Number.isFinite(level)) return [];
|
|
7969
|
+
const edgeId = (i, j, edge) => {
|
|
7970
|
+
switch (edge) {
|
|
7971
|
+
case T: return 2 * (j * width + i);
|
|
7972
|
+
case B: return 2 * ((j + 1) * width + i);
|
|
7973
|
+
case L: return 2 * (j * width + i) + 1;
|
|
7974
|
+
default: return 2 * (j * width + i + 1) + 1;
|
|
7975
|
+
}
|
|
7976
|
+
};
|
|
7977
|
+
const segments = [];
|
|
7978
|
+
for (let j = 0; j < height - 1; j++) for (let i = 0; i < width - 1; i++) {
|
|
7979
|
+
const a = values[offset + j * width + i];
|
|
7980
|
+
const b = values[offset + j * width + i + 1];
|
|
7981
|
+
const c = values[offset + (j + 1) * width + i + 1];
|
|
7982
|
+
const d = values[offset + (j + 1) * width + i];
|
|
7983
|
+
if (!(Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(c) && Number.isFinite(d))) continue;
|
|
7984
|
+
const index = (a >= level ? 8 : 0) | (b >= level ? 4 : 0) | (c >= level ? 2 : 0) | (d >= level ? 1 : 0);
|
|
7985
|
+
let pairs = CASES[index];
|
|
7986
|
+
if (index === 5 || index === 10) {
|
|
7987
|
+
const joined = (a + b + c + d) / 4 >= level;
|
|
7988
|
+
pairs = index === 5 ? joined ? [[T, L], [B, R]] : [[T, R], [L, B]] : joined ? [[T, R], [L, B]] : [[T, L], [B, R]];
|
|
7989
|
+
}
|
|
7990
|
+
for (const [e0, e1] of pairs) segments.push([edgeId(i, j, e0), edgeId(i, j, e1)]);
|
|
7991
|
+
}
|
|
7992
|
+
if (segments.length === 0) return [];
|
|
7993
|
+
const at = /* @__PURE__ */ new Map();
|
|
7994
|
+
segments.forEach(([p, q], s) => {
|
|
7995
|
+
for (const id of [p, q]) {
|
|
7996
|
+
const list = at.get(id);
|
|
7997
|
+
if (list) list.push(s);
|
|
7998
|
+
else at.set(id, [s]);
|
|
7999
|
+
}
|
|
8000
|
+
});
|
|
8001
|
+
const crossing = (id) => {
|
|
8002
|
+
const vertical = id % 2 === 1;
|
|
8003
|
+
const node = (id - (vertical ? 1 : 0)) / 2;
|
|
8004
|
+
const i = node % width;
|
|
8005
|
+
const j = (node - i) / width;
|
|
8006
|
+
const v0 = values[offset + node];
|
|
8007
|
+
const v1 = values[offset + node + (vertical ? width : 1)];
|
|
8008
|
+
const t = Math.min(1, Math.max(0, (level - v0) / (v1 - v0)));
|
|
8009
|
+
return vertical ? [i, j + t] : [i + t, j];
|
|
8010
|
+
};
|
|
8011
|
+
const used = new Uint8Array(segments.length);
|
|
8012
|
+
const lines = [];
|
|
8013
|
+
for (let s = 0; s < segments.length; s++) {
|
|
8014
|
+
if (used[s]) continue;
|
|
8015
|
+
used[s] = 1;
|
|
8016
|
+
const ids = [segments[s][0], segments[s][1]];
|
|
8017
|
+
walk(ids, at, segments, used, true);
|
|
8018
|
+
walk(ids, at, segments, used, false);
|
|
8019
|
+
const closed = ids.length > 2 && ids[0] === ids[ids.length - 1];
|
|
8020
|
+
if (closed) ids.pop();
|
|
8021
|
+
const points = [];
|
|
8022
|
+
for (const id of ids) points.push(...crossing(id));
|
|
8023
|
+
lines.push({
|
|
8024
|
+
level,
|
|
8025
|
+
points,
|
|
8026
|
+
closed
|
|
8027
|
+
});
|
|
8028
|
+
}
|
|
8029
|
+
return lines;
|
|
8030
|
+
}
|
|
8031
|
+
/** Extends a chain of edge ids at its tail (`forward`) or head by the unused segments meeting there. */
|
|
8032
|
+
function walk(ids, at, segments, used, forward) {
|
|
8033
|
+
for (;;) {
|
|
8034
|
+
const end = forward ? ids[ids.length - 1] : ids[0];
|
|
8035
|
+
if (ids.length > 2 && ids[0] === ids[ids.length - 1]) return;
|
|
8036
|
+
const next = at.get(end).find((other) => !used[other]);
|
|
8037
|
+
if (next === void 0) return;
|
|
8038
|
+
used[next] = 1;
|
|
8039
|
+
const [p, q] = segments[next];
|
|
8040
|
+
const far = p === end ? q : p;
|
|
8041
|
+
if (forward) ids.push(far);
|
|
8042
|
+
else ids.unshift(far);
|
|
8043
|
+
}
|
|
8044
|
+
}
|
|
8045
|
+
/**
|
|
8046
|
+
* The iso-lines of a plane's channel at every level, lowest level first.
|
|
8047
|
+
*
|
|
8048
|
+
* @param plane - The field; `NaN` is "no data".
|
|
8049
|
+
* @param channel - Which channel. Default 0; out of range gives no lines.
|
|
8050
|
+
* @param levels - See `resolveLevels`; the lines of each level, in turn.
|
|
8051
|
+
*/
|
|
8052
|
+
function contourPaths(plane, channel, levels) {
|
|
8053
|
+
if (!Number.isInteger(channel) || channel < 0 || channel >= plane.channels) return [];
|
|
8054
|
+
const offset = channel * plane.width * plane.height;
|
|
8055
|
+
return levels.flatMap((level) => contourAtLevel(plane.values, plane.width, plane.height, level, offset));
|
|
8056
|
+
}
|
|
8057
|
+
/** Total length of a polyline (closing segment included for a closed line), in nodes. */
|
|
8058
|
+
function lineLength(line) {
|
|
8059
|
+
const p = line.points;
|
|
8060
|
+
let length = 0;
|
|
8061
|
+
for (let k = 2; k < p.length; k += 2) length += Math.hypot(p[k] - p[k - 2], p[k + 1] - p[k - 1]);
|
|
8062
|
+
if (line.closed && p.length >= 4) length += Math.hypot(p[0] - p[p.length - 2], p[1] - p[p.length - 1]);
|
|
8063
|
+
return length;
|
|
8064
|
+
}
|
|
8065
|
+
/**
|
|
8066
|
+
* Points along a line at fractions of its length, for placing labels.
|
|
8067
|
+
*
|
|
8068
|
+
* @param line - The line.
|
|
8069
|
+
* @param count - How many labels; they sit at `(k + 0.5) / count` of the arc length.
|
|
8070
|
+
* @returns `[x, y]` per label, in nodes.
|
|
8071
|
+
*/
|
|
8072
|
+
function pointsAlong(line, count) {
|
|
8073
|
+
const p = line.points;
|
|
8074
|
+
const n = p.length / 2;
|
|
8075
|
+
if (n === 0 || count < 1) return [];
|
|
8076
|
+
const total = lineLength(line);
|
|
8077
|
+
if (n === 1 || total === 0) return [[p[0], p[1]]];
|
|
8078
|
+
const out = [];
|
|
8079
|
+
const segs = line.closed ? n : n - 1;
|
|
8080
|
+
for (let k = 0; k < count; k++) {
|
|
8081
|
+
let target = (k + .5) / count * total;
|
|
8082
|
+
for (let s = 0; s < segs; s++) {
|
|
8083
|
+
const x0 = p[2 * s];
|
|
8084
|
+
const y0 = p[2 * s + 1];
|
|
8085
|
+
const t = (s + 1) % n;
|
|
8086
|
+
const x1 = p[2 * t];
|
|
8087
|
+
const y1 = p[2 * t + 1];
|
|
8088
|
+
const len = Math.hypot(x1 - x0, y1 - y0);
|
|
8089
|
+
if (target <= len || s === segs - 1) {
|
|
8090
|
+
const f = len === 0 ? 0 : Math.min(1, target / len);
|
|
8091
|
+
out.push([x0 + f * (x1 - x0), y0 + f * (y1 - y0)]);
|
|
8092
|
+
break;
|
|
8093
|
+
}
|
|
8094
|
+
target -= len;
|
|
8095
|
+
}
|
|
8096
|
+
}
|
|
8097
|
+
return out;
|
|
8098
|
+
}
|
|
8099
|
+
//#endregion
|
|
8100
|
+
//#region src/components/ContourLayer.tsx
|
|
8101
|
+
/**
|
|
8102
|
+
* Iso-lines of a scalar field over the image: the level sets of a distortion map, a residual field,
|
|
8103
|
+
* a support boundary.
|
|
8104
|
+
*
|
|
8105
|
+
* The lines are found by marching squares over the plane's nodes (see `contourPaths`), drawn as one
|
|
8106
|
+
* path per style (a halo, the solid levels, the dashed ones), never one element per line, and
|
|
8107
|
+
* stroked at screen-constant width. The layer takes no pointer events.
|
|
8108
|
+
*/
|
|
8109
|
+
/** A line is labelled only when it is at least this long on screen, in CSS pixels. */
|
|
8110
|
+
const MIN_LABELLED_LENGTH = 90;
|
|
8111
|
+
/** A long line is labelled again every this many screen pixels. */
|
|
8112
|
+
const LABEL_EVERY = 280;
|
|
8113
|
+
/** Dash and gap of a dashed level, in screen pixels. */
|
|
8114
|
+
const DASH = [5, 3];
|
|
8115
|
+
const defaultFormat = (level) => String(Number(level.toPrecision(3)));
|
|
8116
|
+
const sameLevel = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
|
|
8117
|
+
/**
|
|
8118
|
+
* Contour lines inside an `ImageStage`.
|
|
8119
|
+
*
|
|
8120
|
+
* - **Lines**: marching squares per level over the plane's nodes (pixel centres), linear along
|
|
8121
|
+
* edges; a saddle is resolved by the mean of its four corners. They are computed once per
|
|
8122
|
+
* change of `plane`, `channel` and `levels`, not on pan or zoom.
|
|
8123
|
+
* - **No data**: a cell touching a `NaN` node has no line, so a line stops at a hole.
|
|
8124
|
+
* - **Styles**: solid levels in one path, dashed ones in another, each over a halo.
|
|
8125
|
+
* - **Labels**: optional, by zoom (see `labels`).
|
|
8126
|
+
* - **Input**: none. The layer is decorative; the numbers are read from the plane (`valueAt`),
|
|
8127
|
+
* and a legend or `labels` carry the levels as text.
|
|
8128
|
+
*
|
|
8129
|
+
* The SVG carries `data-count` (lines) and `data-levels` (the levels drawn).
|
|
8130
|
+
*/
|
|
8131
|
+
function ContourLayer({ plane, channel = 0, levels, dashedLevels, labels = false, rect, role = "structure", color, halo = true, visible = true, label = "Contours" }) {
|
|
8132
|
+
const stage = useStage();
|
|
8133
|
+
const px = useScreenPx();
|
|
8134
|
+
const unit = px(1);
|
|
8135
|
+
const levelsKey = Array.isArray(levels) ? `l:${levels.join(",")}` : `s:${levels.step}:${levels.origin ?? 0}`;
|
|
8136
|
+
const dashedKey = (dashedLevels ?? []).join(",");
|
|
8137
|
+
const drawn = useMemo(() => {
|
|
8138
|
+
if (!visible) return {
|
|
8139
|
+
lines: [],
|
|
8140
|
+
levels: [],
|
|
8141
|
+
dashed: []
|
|
8142
|
+
};
|
|
8143
|
+
const extent = Array.isArray(levels) ? null : channelExtent(plane, channel);
|
|
8144
|
+
const base = Array.isArray(levels) ? resolveLevels(levels, 0, 0) : extent ? resolveLevels(levels, extent[0], extent[1]) : [];
|
|
8145
|
+
const dashed = (dashedLevels ?? []).filter(Number.isFinite);
|
|
8146
|
+
const all = [...base];
|
|
8147
|
+
for (const level of dashed) if (!all.some((l) => sameLevel(l, level))) all.push(level);
|
|
8148
|
+
all.sort((a, b) => a - b);
|
|
8149
|
+
return {
|
|
8150
|
+
lines: contourPaths(plane, channel, all),
|
|
8151
|
+
levels: all,
|
|
8152
|
+
dashed
|
|
8153
|
+
};
|
|
8154
|
+
}, [
|
|
8155
|
+
visible,
|
|
8156
|
+
plane,
|
|
8157
|
+
channel,
|
|
8158
|
+
levelsKey,
|
|
8159
|
+
dashedKey
|
|
8160
|
+
]);
|
|
8161
|
+
const box = rect ?? {
|
|
8162
|
+
x: -.5,
|
|
8163
|
+
y: -.5,
|
|
8164
|
+
width: stage.image.width,
|
|
8165
|
+
height: stage.image.height
|
|
8166
|
+
};
|
|
8167
|
+
const sx = plane.width > 0 ? box.width / plane.width : 1;
|
|
8168
|
+
const sy = plane.height > 0 ? box.height / plane.height : 1;
|
|
8169
|
+
const paths = useMemo(() => {
|
|
8170
|
+
let solid = "";
|
|
8171
|
+
let dashed = "";
|
|
8172
|
+
for (const line of drawn.lines) {
|
|
8173
|
+
let d = "";
|
|
8174
|
+
const p = line.points;
|
|
8175
|
+
for (let k = 0; k < p.length; k += 2) d += `${k === 0 ? "M" : "L"}${(box.x + (p[k] + .5) * sx).toFixed(2)} ${(box.y + (p[k + 1] + .5) * sy).toFixed(2)}`;
|
|
8176
|
+
if (line.closed) d += "Z";
|
|
8177
|
+
if (drawn.dashed.some((level) => sameLevel(level, line.level))) dashed += d;
|
|
8178
|
+
else solid += d;
|
|
8179
|
+
}
|
|
8180
|
+
return {
|
|
8181
|
+
solid,
|
|
8182
|
+
dashed
|
|
8183
|
+
};
|
|
8184
|
+
}, [
|
|
8185
|
+
drawn,
|
|
8186
|
+
box.x,
|
|
8187
|
+
box.y,
|
|
8188
|
+
sx,
|
|
8189
|
+
sy
|
|
8190
|
+
]);
|
|
8191
|
+
const format = typeof labels === "function" ? labels : defaultFormat;
|
|
8192
|
+
const view = visibleRect(stage.view, stage.box);
|
|
8193
|
+
const labelled = useMemo(() => {
|
|
8194
|
+
if (labels === false) return [];
|
|
8195
|
+
const out = [];
|
|
8196
|
+
for (const line of drawn.lines) {
|
|
8197
|
+
const screen = lineLength(line) * Math.hypot(sx, sy) / Math.SQRT2 / unit;
|
|
8198
|
+
if (screen < MIN_LABELLED_LENGTH) continue;
|
|
8199
|
+
const count = Math.max(1, Math.floor(screen / LABEL_EVERY));
|
|
8200
|
+
for (const [x, y] of pointsAlong(line, count)) {
|
|
8201
|
+
const ix = box.x + (x + .5) * sx;
|
|
8202
|
+
const iy = box.y + (y + .5) * sy;
|
|
8203
|
+
if (view && (ix < view.x || ix > view.x + view.width || iy < view.y || iy > view.y + view.height)) continue;
|
|
8204
|
+
out.push({
|
|
8205
|
+
x: ix,
|
|
8206
|
+
y: iy,
|
|
8207
|
+
text: format(line.level)
|
|
8208
|
+
});
|
|
8209
|
+
if (out.length >= 200) return out;
|
|
8210
|
+
}
|
|
8211
|
+
}
|
|
8212
|
+
return out;
|
|
8213
|
+
}, [
|
|
8214
|
+
labels,
|
|
8215
|
+
drawn,
|
|
8216
|
+
box.x,
|
|
8217
|
+
box.y,
|
|
8218
|
+
sx,
|
|
8219
|
+
sy,
|
|
8220
|
+
unit,
|
|
8221
|
+
view?.x,
|
|
8222
|
+
view?.y,
|
|
8223
|
+
view?.width,
|
|
8224
|
+
view?.height
|
|
8225
|
+
]);
|
|
8226
|
+
if (!visible) return null;
|
|
8227
|
+
const tone = color ?? overlayRole(role);
|
|
8228
|
+
const HALO = overlayRole("halo");
|
|
8229
|
+
const width = px(OVERLAY_STATE_WIDTH.default);
|
|
8230
|
+
const dash = `${px(DASH[0])} ${px(DASH[1])}`;
|
|
8231
|
+
const levelsText = drawn.levels.slice(0, 6).map(defaultFormat).join(", ") + (drawn.levels.length > 6 ? ", …" : "");
|
|
8232
|
+
return /* @__PURE__ */ jsxs("svg", {
|
|
8233
|
+
viewBox: imageViewBox(stage.image),
|
|
8234
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
8235
|
+
role: "img",
|
|
8236
|
+
"aria-label": `${label}: ${drawn.lines.length} ${drawn.lines.length === 1 ? "line" : "lines"}${levelsText ? ` at ${levelsText}` : ""}`,
|
|
8237
|
+
"data-count": drawn.lines.length,
|
|
8238
|
+
"data-levels": drawn.levels.join(","),
|
|
8239
|
+
children: [/* @__PURE__ */ jsxs("g", {
|
|
8240
|
+
fill: "none",
|
|
8241
|
+
strokeLinecap: "round",
|
|
8242
|
+
strokeLinejoin: "round",
|
|
8243
|
+
children: [
|
|
8244
|
+
halo && paths.solid !== "" && /* @__PURE__ */ jsx("path", {
|
|
8245
|
+
"data-halo": "",
|
|
8246
|
+
d: paths.solid,
|
|
8247
|
+
stroke: HALO,
|
|
8248
|
+
strokeWidth: width + px(2),
|
|
8249
|
+
opacity: .6
|
|
8250
|
+
}),
|
|
8251
|
+
halo && paths.dashed !== "" && /* @__PURE__ */ jsx("path", {
|
|
8252
|
+
"data-halo": "",
|
|
8253
|
+
d: paths.dashed,
|
|
8254
|
+
stroke: HALO,
|
|
8255
|
+
strokeWidth: width + px(2),
|
|
8256
|
+
opacity: .6
|
|
8257
|
+
}),
|
|
8258
|
+
paths.solid !== "" && /* @__PURE__ */ jsx("path", {
|
|
8259
|
+
"data-contours": "solid",
|
|
8260
|
+
d: paths.solid,
|
|
8261
|
+
stroke: tone,
|
|
8262
|
+
strokeWidth: width
|
|
8263
|
+
}),
|
|
8264
|
+
paths.dashed !== "" && /* @__PURE__ */ jsx("path", {
|
|
8265
|
+
"data-contours": "dashed",
|
|
8266
|
+
d: paths.dashed,
|
|
8267
|
+
stroke: tone,
|
|
8268
|
+
strokeWidth: width,
|
|
8269
|
+
strokeDasharray: dash,
|
|
8270
|
+
strokeLinecap: "butt"
|
|
8271
|
+
})
|
|
8272
|
+
]
|
|
8273
|
+
}), labelled.length > 0 && /* @__PURE__ */ jsx("g", {
|
|
8274
|
+
"data-labels": "",
|
|
8275
|
+
fontSize: px(11),
|
|
8276
|
+
className: "font-mono",
|
|
8277
|
+
stroke: HALO,
|
|
8278
|
+
strokeWidth: px(3),
|
|
8279
|
+
paintOrder: "stroke",
|
|
8280
|
+
strokeLinejoin: "round",
|
|
8281
|
+
fill: overlayRole("label"),
|
|
8282
|
+
textAnchor: "middle",
|
|
8283
|
+
dominantBaseline: "central",
|
|
8284
|
+
children: labelled.map((entry) => /* @__PURE__ */ jsx("text", {
|
|
8285
|
+
x: entry.x,
|
|
8286
|
+
y: entry.y,
|
|
8287
|
+
children: entry.text
|
|
8288
|
+
}, `${entry.x},${entry.y},${entry.text}`))
|
|
8289
|
+
})]
|
|
8290
|
+
});
|
|
8291
|
+
}
|
|
8292
|
+
//#endregion
|
|
8293
|
+
//#region src/components/vectorGeometry.ts
|
|
8294
|
+
/**
|
|
8295
|
+
* The length of vector `i`, or `NaN` when it is absent.
|
|
8296
|
+
*
|
|
8297
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
8298
|
+
* @param i - The vector's index.
|
|
8299
|
+
* @returns `hypot(dx, dy)`, or `NaN` for a non-finite component.
|
|
8300
|
+
*/
|
|
8301
|
+
function vectorMagnitude(vectors, i) {
|
|
8302
|
+
const dx = vectors[2 * i];
|
|
8303
|
+
const dy = vectors[2 * i + 1];
|
|
8304
|
+
if (dx === void 0 || dy === void 0 || !Number.isFinite(dx) || !Number.isFinite(dy)) return NaN;
|
|
8305
|
+
return Math.hypot(dx, dy);
|
|
8306
|
+
}
|
|
8307
|
+
/**
|
|
8308
|
+
* The magnitudes of every vector, `NaN` for an absent one.
|
|
8309
|
+
*
|
|
8310
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
8311
|
+
* @returns One magnitude per vector.
|
|
8312
|
+
*/
|
|
8313
|
+
function vectorMagnitudes(vectors) {
|
|
8314
|
+
const count = Math.floor(vectors.length / 2);
|
|
8315
|
+
const out = new Float64Array(count);
|
|
8316
|
+
for (let i = 0; i < count; i++) out[i] = vectorMagnitude(vectors, i);
|
|
8317
|
+
return out;
|
|
8318
|
+
}
|
|
8319
|
+
/**
|
|
8320
|
+
* A magnitude's rank statistic over the present vectors.
|
|
8321
|
+
*
|
|
8322
|
+
* @param magnitudes - As `vectorMagnitudes` returns them; `NaN` entries are ignored.
|
|
8323
|
+
* @param p - The fraction in `[0, 1]` (clamped): `1` is the longest, `0.5` the median.
|
|
8324
|
+
* @returns The nearest-rank value, or `0` when no vector is present.
|
|
8325
|
+
*/
|
|
8326
|
+
function magnitudePercentile(magnitudes, p) {
|
|
8327
|
+
const live = [];
|
|
8328
|
+
for (let i = 0; i < magnitudes.length; i++) {
|
|
8329
|
+
const m = magnitudes[i];
|
|
8330
|
+
if (Number.isFinite(m)) live.push(m);
|
|
8331
|
+
}
|
|
8332
|
+
if (live.length === 0) return 0;
|
|
8333
|
+
live.sort((a, b) => a - b);
|
|
8334
|
+
return live[Math.max(0, Math.ceil((Number.isFinite(p) ? Math.min(1, Math.max(0, p)) : 1) * live.length) - 1)];
|
|
8335
|
+
}
|
|
8336
|
+
/**
|
|
8337
|
+
* The scale in image pixels per data unit.
|
|
8338
|
+
*
|
|
8339
|
+
* @param scale - See `VectorScale`.
|
|
8340
|
+
* @param referenceMagnitude - The reference vector's length in data units, for an automatic scale.
|
|
8341
|
+
* @param imagePerScreenPx - Image pixels covered by one screen pixel at the current zoom.
|
|
8342
|
+
* @returns Image pixels per data unit; `0` when an automatic scale has no vector to measure.
|
|
8343
|
+
*/
|
|
8344
|
+
function imagePerUnit(scale, referenceMagnitude, imagePerScreenPx) {
|
|
8345
|
+
if (typeof scale === "number") return Number.isFinite(scale) && scale > 0 ? scale : 0;
|
|
8346
|
+
if (!(referenceMagnitude > 0) || !(scale.length > 0)) return 0;
|
|
8347
|
+
return scale.length * imagePerScreenPx / referenceMagnitude;
|
|
8348
|
+
}
|
|
8349
|
+
/**
|
|
8350
|
+
* A round length for a key: the largest of 1, 2 and 5 times a power of ten that is at most `max`.
|
|
8351
|
+
*
|
|
8352
|
+
* @param max - The upper bound, in data units.
|
|
8353
|
+
* @returns The round length, or `0` for a non-positive `max`.
|
|
8354
|
+
*/
|
|
8355
|
+
function niceLength(max) {
|
|
8356
|
+
if (!(max > 0) || !Number.isFinite(max)) return 0;
|
|
8357
|
+
const power = 10 ** Math.floor(Math.log10(max));
|
|
8358
|
+
for (const m of [
|
|
8359
|
+
5,
|
|
8360
|
+
2,
|
|
8361
|
+
1
|
|
8362
|
+
]) if (m * power <= max * (1 + 1e-12)) return m * power;
|
|
8363
|
+
return power;
|
|
8364
|
+
}
|
|
8365
|
+
const r = (v) => String(Math.round(v * 1e3) / 1e3);
|
|
8366
|
+
/**
|
|
8367
|
+
* The path data of one arrow: a shaft and a filled head.
|
|
8368
|
+
*
|
|
8369
|
+
* The head is capped at 45 % of the arrow's length, so a short arrow is a small wedge rather
|
|
8370
|
+
* than a head on no shaft. Lengths are in the units of `(x, y)` (image pixels); `unit` converts
|
|
8371
|
+
* the style's screen pixels to them.
|
|
8372
|
+
*
|
|
8373
|
+
* @param x - The anchor's x.
|
|
8374
|
+
* @param y - The anchor's y.
|
|
8375
|
+
* @param dx - The displacement's x, already scaled to image pixels.
|
|
8376
|
+
* @param dy - The displacement's y, already scaled to image pixels.
|
|
8377
|
+
* @param unit - Image pixels per screen pixel.
|
|
8378
|
+
* @param style - The arrow's shape.
|
|
8379
|
+
* @returns Path data, or `""` when the arrow is absent or shorter than `style.minLength`.
|
|
8380
|
+
*/
|
|
8381
|
+
function arrowPath(x, y, dx, dy, unit, style) {
|
|
8382
|
+
const len = Math.hypot(dx, dy);
|
|
8383
|
+
if (!(len > 0) || len < style.minLength * unit) return "";
|
|
8384
|
+
const ux = dx / len;
|
|
8385
|
+
const uy = dy / len;
|
|
8386
|
+
const head = Math.min(style.head * unit, .45 * len);
|
|
8387
|
+
const half = head * style.headWidth / 2;
|
|
8388
|
+
const tx = x + dx;
|
|
8389
|
+
const ty = y + dy;
|
|
8390
|
+
const bx = tx - ux * head;
|
|
8391
|
+
const by = ty - uy * head;
|
|
8392
|
+
return `M${r(x)} ${r(y)}L${r(bx)} ${r(by)}M${r(tx)} ${r(ty)}L${r(bx - uy * half)} ${r(by + ux * half)}L${r(bx + uy * half)} ${r(by - ux * half)}Z`;
|
|
8393
|
+
}
|
|
8394
|
+
/** The number of colour steps a magnitude-coloured field is quantised into: one path each. */
|
|
8395
|
+
const VECTOR_COLOR_BINS = 24;
|
|
8396
|
+
/**
|
|
8397
|
+
* The colour bin of a magnitude.
|
|
8398
|
+
*
|
|
8399
|
+
* @param magnitude - The vector's length.
|
|
8400
|
+
* @param low - The magnitude drawn in the map's first colour.
|
|
8401
|
+
* @param high - The magnitude drawn in the map's last colour.
|
|
8402
|
+
* @param bins - The number of bins. Defaults to `VECTOR_COLOR_BINS`.
|
|
8403
|
+
* @returns An integer in `[0, bins - 1]`; a degenerate range puts everything in bin `0`.
|
|
8404
|
+
*/
|
|
8405
|
+
function colorBin(magnitude, low, high, bins = 24) {
|
|
8406
|
+
if (!(high > low)) return 0;
|
|
8407
|
+
const t = (magnitude - low) / (high - low);
|
|
8408
|
+
return Math.min(bins - 1, Math.max(0, Math.floor(t * bins)));
|
|
8409
|
+
}
|
|
8410
|
+
//#endregion
|
|
8411
|
+
//#region src/components/VectorField.tsx
|
|
8412
|
+
/**
|
|
8413
|
+
* Many vectors over the image: a displacement, a flow, a gradient, a residual direction.
|
|
8414
|
+
*
|
|
8415
|
+
* Drawn as a handful of batched paths (one halo, then one per colour step), never one element per
|
|
8416
|
+
* vector; the pointer is resolved through the stage's hit registry from a spatial index over the
|
|
8417
|
+
* anchors, never by the DOM; arrowheads and strokes are sized in screen pixels. A field of 10,000
|
|
8418
|
+
* vectors is a dozen DOM nodes.
|
|
8419
|
+
*/
|
|
8420
|
+
/** The arrow's shape, in screen pixels. */
|
|
8421
|
+
const ARROW = {
|
|
8422
|
+
head: 6,
|
|
8423
|
+
headWidth: .7,
|
|
8424
|
+
minLength: 1
|
|
8425
|
+
};
|
|
8426
|
+
/** Past this many vectors, paths are generated for the visible part only. */
|
|
8427
|
+
const CULL_ABOVE = 3e3;
|
|
8428
|
+
/** The reference vector of the default scale: the 95th percentile spans this many screen pixels. */
|
|
8429
|
+
const DEFAULT_SCALE = {
|
|
8430
|
+
length: 28,
|
|
8431
|
+
percentile: .95
|
|
8432
|
+
};
|
|
8433
|
+
/**
|
|
8434
|
+
* The reference vector of a scale and the scale it gives, shared by the layer and its key.
|
|
8435
|
+
*
|
|
8436
|
+
* @param vectors - Flat `[dx0, dy0, …]`.
|
|
8437
|
+
* @param scale - See `VectorScale`.
|
|
8438
|
+
* @returns The reference magnitude in data units, and image pixels per data unit.
|
|
8439
|
+
*/
|
|
8440
|
+
function useVectorScale(vectors, scale = DEFAULT_SCALE) {
|
|
8441
|
+
const unit = useScreenPx()(1);
|
|
8442
|
+
const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
|
|
8443
|
+
const percentile = typeof scale === "number" ? 1 : scale.percentile ?? 1;
|
|
8444
|
+
const reference = useMemo(() => magnitudePercentile(mags, percentile), [mags, percentile]);
|
|
8445
|
+
return {
|
|
8446
|
+
reference,
|
|
8447
|
+
perUnit: imagePerUnit(scale, reference, unit)
|
|
8448
|
+
};
|
|
8449
|
+
}
|
|
8450
|
+
/** `rgb(r g b)` of a map's colour, channels rounded and clamped. */
|
|
8451
|
+
function css(colormap, t) {
|
|
8452
|
+
const [r, g, b] = colormap(t);
|
|
8453
|
+
const c = (v) => Math.min(255, Math.max(0, Math.round(v)));
|
|
8454
|
+
return `rgb(${c(r)} ${c(g)} ${c(b)})`;
|
|
8455
|
+
}
|
|
8456
|
+
/**
|
|
8457
|
+
* A field of arrows inside an `ImageStage`.
|
|
8458
|
+
*
|
|
8459
|
+
* - **Scale**: see `VectorScale`. The same `vectors` and `scale` given to `VectorFieldKey` draw a
|
|
8460
|
+
* reference length at exactly this scale.
|
|
8461
|
+
* - **Colour**: one tone (`color` or `role`), or by magnitude through `colormap` over `range`.
|
|
8462
|
+
* - **Absent data**: an anchor or vector with a non-finite number, or shorter than one screen
|
|
8463
|
+
* pixel, is not drawn.
|
|
8464
|
+
* - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here, and
|
|
8465
|
+
* `useStageHitTest` for an app that arbitrates between layers. The hovered arrow is redrawn
|
|
8466
|
+
* at 2.5 screen px in the selection colour.
|
|
8467
|
+
*
|
|
8468
|
+
* Arrowheads and strokes are screen-constant; their paths are regenerated when the zoom changes,
|
|
8469
|
+
* and past 3,000 vectors only those near the viewport are generated. The SVG carries
|
|
8470
|
+
* `data-hovered` (the hovered id) and `data-count` (the vectors drawn).
|
|
8471
|
+
*/
|
|
8472
|
+
function VectorField({ anchors, vectors, scale = DEFAULT_SCALE, color, role = "feature", colormap, range, ids, hoveredId, onHoverChange, onItemPress, halo = true, pickable = true, layerId, priority = STAGE_HIT_PRIORITY.point, label = "Vectors" }) {
|
|
8473
|
+
const stage = useStage();
|
|
8474
|
+
const px = useScreenPx();
|
|
8475
|
+
const unit = px(1);
|
|
8476
|
+
const count = Math.min(Math.floor(anchors.length / 2), Math.floor(vectors.length / 2));
|
|
8477
|
+
const mags = useMemo(() => vectorMagnitudes(vectors), [vectors]);
|
|
8478
|
+
const { perUnit } = useVectorScale(vectors, scale);
|
|
8479
|
+
const index = useMemo(() => buildPointIndex(anchors, { ids }), [anchors, ids]);
|
|
8480
|
+
const [ownHover, setOwnHover] = useState(null);
|
|
8481
|
+
const hoverId = hoveredId !== void 0 ? hoveredId : ownHover;
|
|
8482
|
+
useStageHitLayer({
|
|
8483
|
+
layerId,
|
|
8484
|
+
priority,
|
|
8485
|
+
enabled: pickable,
|
|
8486
|
+
pick: (point, radius) => {
|
|
8487
|
+
const hit = nearestPoint(index, point.x, point.y, radius);
|
|
8488
|
+
return hit && hit.index < count && Number.isFinite(mags[hit.index]) ? {
|
|
8489
|
+
id: hit.id,
|
|
8490
|
+
dist: hit.dist
|
|
8491
|
+
} : null;
|
|
8492
|
+
},
|
|
8493
|
+
onHover: (id) => {
|
|
8494
|
+
setOwnHover(id);
|
|
8495
|
+
onHoverChange?.(id);
|
|
8496
|
+
},
|
|
8497
|
+
onPress: onItemPress
|
|
8498
|
+
});
|
|
8499
|
+
const colourRange = useMemo(() => {
|
|
8500
|
+
if (!colormap) return null;
|
|
8501
|
+
if (range) return range;
|
|
8502
|
+
let high = 0;
|
|
8503
|
+
for (let i = 0; i < count; i++) if (mags[i] > high) high = mags[i];
|
|
8504
|
+
return {
|
|
8505
|
+
low: 0,
|
|
8506
|
+
high
|
|
8507
|
+
};
|
|
8508
|
+
}, [
|
|
8509
|
+
colormap,
|
|
8510
|
+
range,
|
|
8511
|
+
mags,
|
|
8512
|
+
count
|
|
8513
|
+
]);
|
|
8514
|
+
const cull = cullWindow(stage.view, stage.box, count, mags, perUnit);
|
|
8515
|
+
const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : "";
|
|
8516
|
+
const built = useMemo(() => {
|
|
8517
|
+
const parts = new Array(colormap && colourRange ? 24 : 1).fill("");
|
|
8518
|
+
let drawn = 0;
|
|
8519
|
+
for (let i = 0; i < count; i++) {
|
|
8520
|
+
const m = mags[i];
|
|
8521
|
+
const x = anchors[2 * i];
|
|
8522
|
+
const y = anchors[2 * i + 1];
|
|
8523
|
+
if (!Number.isFinite(m) || !Number.isFinite(x) || !Number.isFinite(y)) continue;
|
|
8524
|
+
if (cull && (x < cull.x || x > cull.x + cull.width || y < cull.y || y > cull.y + cull.height)) continue;
|
|
8525
|
+
const d = arrowPath(x, y, vectors[2 * i] * perUnit, vectors[2 * i + 1] * perUnit, unit, ARROW);
|
|
8526
|
+
if (d === "") continue;
|
|
8527
|
+
const bin = colormap && colourRange ? colorBin(m, colourRange.low, colourRange.high) : 0;
|
|
8528
|
+
parts[bin] += d;
|
|
8529
|
+
drawn++;
|
|
8530
|
+
}
|
|
8531
|
+
return {
|
|
8532
|
+
parts,
|
|
8533
|
+
batches: parts.flatMap((d, bin) => d === "" ? [] : [{
|
|
8534
|
+
bin,
|
|
8535
|
+
d
|
|
8536
|
+
}]),
|
|
8537
|
+
drawn
|
|
8538
|
+
};
|
|
8539
|
+
}, [
|
|
8540
|
+
anchors,
|
|
8541
|
+
vectors,
|
|
8542
|
+
mags,
|
|
8543
|
+
count,
|
|
8544
|
+
perUnit,
|
|
8545
|
+
unit,
|
|
8546
|
+
colormap,
|
|
8547
|
+
colourRange,
|
|
8548
|
+
cullKey
|
|
8549
|
+
]);
|
|
8550
|
+
const all = useMemo(() => built.parts.join(""), [built]);
|
|
8551
|
+
const hoverIndex = hoverId === null ? -1 : findIndex(index, hoverId, count);
|
|
8552
|
+
const hoverPath = hoverIndex >= 0 && Number.isFinite(mags[hoverIndex]) ? arrowPath(anchors[2 * hoverIndex], anchors[2 * hoverIndex + 1], vectors[2 * hoverIndex] * perUnit, vectors[2 * hoverIndex + 1] * perUnit, unit, ARROW) : "";
|
|
8553
|
+
const tone = color ?? overlayRole(role);
|
|
8554
|
+
const width = px(OVERLAY_STATE_WIDTH.default);
|
|
8555
|
+
const hoverWidth = px(OVERLAY_STATE_WIDTH.selected);
|
|
8556
|
+
const HALO = overlayRole("halo");
|
|
8557
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
8558
|
+
viewBox: imageViewBox(stage.image),
|
|
8559
|
+
className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
|
|
8560
|
+
role: "img",
|
|
8561
|
+
"aria-label": `${label}: ${built.drawn} ${built.drawn === 1 ? "vector" : "vectors"}`,
|
|
8562
|
+
"data-hovered": hoverId ?? void 0,
|
|
8563
|
+
"data-count": built.drawn,
|
|
8564
|
+
children: /* @__PURE__ */ jsxs("g", {
|
|
8565
|
+
fill: "none",
|
|
8566
|
+
strokeLinecap: "butt",
|
|
8567
|
+
strokeLinejoin: "round",
|
|
8568
|
+
children: [
|
|
8569
|
+
halo && all !== "" && /* @__PURE__ */ jsx("path", {
|
|
8570
|
+
"data-halo": "",
|
|
8571
|
+
d: all,
|
|
8572
|
+
stroke: HALO,
|
|
8573
|
+
fill: HALO,
|
|
8574
|
+
strokeWidth: width + px(2),
|
|
8575
|
+
opacity: .6
|
|
8576
|
+
}),
|
|
8577
|
+
built.batches.map(({ bin, d }) => /* @__PURE__ */ jsx("path", {
|
|
8578
|
+
"data-batch": bin,
|
|
8579
|
+
d,
|
|
8580
|
+
stroke: colormap ? css(colormap, (bin + .5) / 24) : tone,
|
|
8581
|
+
fill: colormap ? css(colormap, (bin + .5) / 24) : tone,
|
|
8582
|
+
strokeWidth: width
|
|
8583
|
+
}, bin)),
|
|
8584
|
+
hoverPath !== "" && /* @__PURE__ */ jsxs(Fragment, { children: [halo && /* @__PURE__ */ jsx("path", {
|
|
8585
|
+
d: hoverPath,
|
|
8586
|
+
stroke: HALO,
|
|
8587
|
+
fill: HALO,
|
|
8588
|
+
strokeWidth: hoverWidth + px(2)
|
|
8589
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
8590
|
+
"data-hovered-vector": "",
|
|
8591
|
+
d: hoverPath,
|
|
8592
|
+
stroke: overlayRole("selection"),
|
|
8593
|
+
fill: overlayRole("selection"),
|
|
8594
|
+
strokeWidth: hoverWidth
|
|
8595
|
+
})] })
|
|
8596
|
+
]
|
|
8597
|
+
})
|
|
8598
|
+
});
|
|
8599
|
+
}
|
|
8600
|
+
/** The index of the vector with id `id`, or `-1`. */
|
|
8601
|
+
function findIndex(index, id, count) {
|
|
8602
|
+
if (index.ids === null) return typeof id === "number" && id >= 0 && id < count && Number.isInteger(id) ? id : -1;
|
|
8603
|
+
for (let i = 0; i < Math.min(count, index.ids.length); i++) if (index.ids[i] === id) return i;
|
|
8604
|
+
return -1;
|
|
8605
|
+
}
|
|
8606
|
+
/**
|
|
8607
|
+
* The window paths are generated for: the viewport plus the longest arrow on every side, snapped
|
|
8608
|
+
* outward to half-viewport steps so panning rebuilds it once per half screen. `null` for a small
|
|
8609
|
+
* field, or an unmeasured stage.
|
|
8610
|
+
*/
|
|
8611
|
+
function cullWindow(view, box, count, mags, perUnit) {
|
|
8612
|
+
if (count <= CULL_ABOVE) return null;
|
|
8613
|
+
const visible = visibleRect(view, box);
|
|
8614
|
+
if (visible === null) return null;
|
|
8615
|
+
let longest = 0;
|
|
8616
|
+
for (let i = 0; i < count; i++) if (mags[i] > longest) longest = mags[i];
|
|
8617
|
+
const sx = visible.width / 2;
|
|
8618
|
+
const sy = visible.height / 2;
|
|
8619
|
+
const reach = Math.min(longest * perUnit, visible.width, visible.height);
|
|
8620
|
+
const left = Math.floor((visible.x - sx - reach) / sx) * sx;
|
|
8621
|
+
const top = Math.floor((visible.y - sy - reach) / sy) * sy;
|
|
8622
|
+
const right = Math.ceil((visible.x + visible.width + sx + reach) / sx) * sx;
|
|
8623
|
+
const bottom = Math.ceil((visible.y + visible.height + sy + reach) / sy) * sy;
|
|
8624
|
+
return {
|
|
8625
|
+
x: left,
|
|
8626
|
+
y: top,
|
|
8627
|
+
width: right - left,
|
|
8628
|
+
height: bottom - top
|
|
8629
|
+
};
|
|
8630
|
+
}
|
|
8631
|
+
//#endregion
|
|
8632
|
+
//#region src/components/VectorFieldKey.tsx
|
|
8633
|
+
/**
|
|
8634
|
+
* The reference length of a `VectorField`: an arrow of a round length with its value, so a
|
|
8635
|
+
* reader can turn arrow lengths back into data units.
|
|
8636
|
+
*/
|
|
8637
|
+
const KEY_ARROW = {
|
|
8638
|
+
head: 5,
|
|
8639
|
+
headWidth: .7,
|
|
8640
|
+
minLength: 1
|
|
8641
|
+
};
|
|
8642
|
+
/** The key is not drawn wider than this, in screen pixels. */
|
|
8643
|
+
const MAX_WIDTH = 160;
|
|
8644
|
+
/**
|
|
8645
|
+
* An arrow of a known length and its value ("0.1 px"). Pass it as `ImageStage`'s `readout`, or
|
|
8646
|
+
* as the `extra` of a `StageReadout` with `bare`; it reads the stage's zoom through `useStage`, so it stays
|
|
8647
|
+
* true as the view changes, and draws nothing while the field has no scale or the arrow would
|
|
8648
|
+
* be wider than 160 screen pixels.
|
|
8649
|
+
*
|
|
8650
|
+
* On its own it is drawn in the readout's light-on-dark chip, so it sits on the image like the readout does.
|
|
8651
|
+
*/
|
|
8652
|
+
function VectorFieldKey({ vectors, scale, length, unit, format = (value) => String(Number(value.toPrecision(3))), bare = false, className }) {
|
|
8653
|
+
const stage = useStage();
|
|
8654
|
+
const { reference, perUnit } = useVectorScale(vectors, scale);
|
|
8655
|
+
const value = length ?? niceLength(reference);
|
|
8656
|
+
const width = value * perUnit * stage.view.scale;
|
|
8657
|
+
if (!(value > 0) || !(width >= 1) || width > MAX_WIDTH) return null;
|
|
8658
|
+
return /* @__PURE__ */ jsxs("span", {
|
|
8659
|
+
className: cn("inline-flex items-center gap-1.5 align-middle font-mono text-[10px] tabular-nums", !bare && "rounded-control bg-black/60 px-1.5 py-0.5 text-white", className),
|
|
8660
|
+
"data-vector-key": "",
|
|
8661
|
+
title: `Arrow length: ${unit ? `${format(value)} ${unit}` : format(value)}`,
|
|
8662
|
+
children: [/* @__PURE__ */ jsx("svg", {
|
|
8663
|
+
"aria-hidden": true,
|
|
8664
|
+
width: width + 2,
|
|
8665
|
+
height: 10,
|
|
8666
|
+
viewBox: `-1 -5 ${width + 2} 10`,
|
|
8667
|
+
className: "shrink-0 overflow-visible",
|
|
8668
|
+
children: /* @__PURE__ */ jsx("path", {
|
|
8669
|
+
d: arrowPath(0, 0, width, 0, 1, KEY_ARROW),
|
|
8670
|
+
fill: "currentColor",
|
|
8671
|
+
stroke: "currentColor",
|
|
8672
|
+
strokeWidth: 1.5,
|
|
8673
|
+
strokeLinejoin: "round"
|
|
8674
|
+
})
|
|
8675
|
+
}), /* @__PURE__ */ jsx("span", { children: unit ? `${format(value)} ${unit}` : format(value) })]
|
|
8676
|
+
});
|
|
8677
|
+
}
|
|
7837
8678
|
//#endregion
|
|
7838
8679
|
//#region src/components/ShapeEditor.tsx
|
|
7839
8680
|
/**
|
|
@@ -8784,6 +9625,6 @@ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius =
|
|
|
8784
9625
|
})] });
|
|
8785
9626
|
}
|
|
8786
9627
|
//#endregion
|
|
8787
|
-
export { AreaSet, CompareLayer, ContourEditor, DATUM_ARM_PX, DATUM_HANDLE_PX, DATUM_RING_PX, DatumEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcLengths, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampToImage, clampView, contentUnder, crossSegments, datumAxes, datumPress, decodePlane, deformContour, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, eraseArc, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imageViewBox, initialView, insideImage, isFit, latticeEdges, measurePrimitiveDistance, moveDatum, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestMeasurePrimitive, nearestPoint, nearestPolyline, normalAtArc, normalizeAngle, overlayRole, paintMask, planeRange, pointAtArc, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, projectToArc, rasterizePlane, rectFromCorners, resizeRect, resizeShape, roiHandlePoint, rotateDatum, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, segmentsPath, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, snapAngle, steppedScale, strokeWidthFor, subPath, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, valueAt, valuesAt, zoomAbout, zoomAt };
|
|
9628
|
+
export { AreaSet, CompareLayer, ContourEditor, ContourLayer, DATUM_ARM_PX, DATUM_HANDLE_PX, DATUM_RING_PX, DatumEditor, DraftShape, EllipseSet, FULL_TIER_ZOOM, GridLayer, HeatmapLayer, ImageLayer, ImageStage, MARKER_SHAPES, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MarqueeRect, MaskEditor, MeasureOverlay, OVERLAY_ROLES, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, PIXEL_CENTRE, PlaneFormatError, PointSet, PolylineSet, RESET_VIEW, ROI_HANDLES, ROI_HANDLE_CURSOR, RectRoiEditor, STAGE_HIT_PRIORITY, ShapeEditor, StageButton, StageLayersMenu, StageReadout, StageSurface, StageToolbar, StageToolbarDivider, VECTOR_COLOR_BINS, VectorField, VectorFieldKey, ZoomPanCanvas, arcLengths, arcPath, areaCentre, areaPath, areasInRect, arrowHeadPoints, arrowPath, buildAreaIndex, buildEllipseIndex, buildPointIndex, buildPointIndexFrom, buildPolylineIndex, caliperArrow, caliperCorners, circlePath, clampRect, clampToImage, clampView, colorBin, contentUnder, contourPaths, crossSegments, datumAxes, datumPress, decodePlane, deformContour, dimensionGeometry, ellipseBounds, ellipsePath, ellipsesInRect, eraseArc, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, fromShapeFrame, imageLengthFor, imagePerUnit, imageViewBox, initialView, insideImage, isFit, latticeEdges, magnitudePercentile, measurePrimitiveDistance, moveDatum, moveRect, moveShape, nativeZoomFor, nearestArea, nearestContourSegment, nearestEllipse, nearestMeasurePrimitive, nearestPoint, nearestPolyline, niceLength, normalAtArc, normalizeAngle, overlayRole, paintMask, planeRange, pointAtArc, pointInEllipse, pointInPolygon, pointsInRect, polygonPath, polylineBounds, polylinePath, polylinesInRect, preserveCenter, projectToArc, rasterizePlane, rectFromCorners, resizeRect, resizeShape, resolveLevels, roiHandlePoint, rotateDatum, rotatePoint, rotateShape, rotationHandlePoint, sameRect, sameShape, scaleRange, segmentsPath, shapeCorner, shapeFromCorner, shapeHandleCursor, shapeHandlePoint, snapAngle, steppedScale, strokeWidthFor, subPath, thinPoints, toImage, toScreen, toShapeFrame, translatePoints, useScreenPx, useShapeDrag, useStage, useStageDrag, useStageHitLayer, useStageHitTest, useVectorScale, valueAt, valuesAt, vectorMagnitude, vectorMagnitudes, zoomAbout, zoomAt };
|
|
8788
9629
|
|
|
8789
9630
|
//# sourceMappingURL=index.js.map
|