@expofp/wayfinding 0.0.0-experimental.2d6c681

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.
Files changed (110) hide show
  1. package/README.md +85 -0
  2. package/dist/core/createWayfindingEngine.d.ts +16 -0
  3. package/dist/core/createWayfindingEngine.js +87 -0
  4. package/dist/core/geometry/pointInPolygon.d.ts +17 -0
  5. package/dist/core/geometry/pointInPolygon.js +50 -0
  6. package/dist/core/geometry/projectPointOnSegment.d.ts +27 -0
  7. package/dist/core/geometry/projectPointOnSegment.js +21 -0
  8. package/dist/core/graph/buildGraph.d.ts +3 -0
  9. package/dist/core/graph/buildGraph.js +7 -0
  10. package/dist/core/graph/buildNGraph.d.ts +13 -0
  11. package/dist/core/graph/buildNGraph.js +24 -0
  12. package/dist/core/graph/constants.d.ts +20 -0
  13. package/dist/core/graph/constants.js +19 -0
  14. package/dist/core/graph/findShortestPath.d.ts +23 -0
  15. package/dist/core/graph/findShortestPath.js +65 -0
  16. package/dist/core/graph/graphCache.d.ts +7 -0
  17. package/dist/core/graph/graphCache.js +23 -0
  18. package/dist/core/graph/graphHelpers.d.ts +8 -0
  19. package/dist/core/graph/graphHelpers.js +63 -0
  20. package/dist/core/graph/linkCost.d.ts +13 -0
  21. package/dist/core/graph/linkCost.js +24 -0
  22. package/dist/core/graph/pathfinder/aStarPathFinder.d.ts +3 -0
  23. package/dist/core/graph/pathfinder/aStarPathFinder.js +64 -0
  24. package/dist/core/graph/pathfinder/parseNodeId.d.ts +10 -0
  25. package/dist/core/graph/pathfinder/parseNodeId.js +20 -0
  26. package/dist/core/index.d.ts +17 -0
  27. package/dist/core/index.js +12 -0
  28. package/dist/core/position/distanceToRoute.d.ts +3 -0
  29. package/dist/core/position/distanceToRoute.js +29 -0
  30. package/dist/core/position/gpsThreshold.d.ts +32 -0
  31. package/dist/core/position/gpsThreshold.js +48 -0
  32. package/dist/core/position/rerouteController.d.ts +13 -0
  33. package/dist/core/position/rerouteController.js +22 -0
  34. package/dist/core/position/snapToRoute.d.ts +9 -0
  35. package/dist/core/position/snapToRoute.js +50 -0
  36. package/dist/core/position/splitRouteByPoint.d.ts +6 -0
  37. package/dist/core/position/splitRouteByPoint.js +56 -0
  38. package/dist/core/rendering/computeTrailPoints.d.ts +12 -0
  39. package/dist/core/rendering/computeTrailPoints.js +35 -0
  40. package/dist/core/rendering/computeTransitionPoints.d.ts +35 -0
  41. package/dist/core/rendering/computeTransitionPoints.js +112 -0
  42. package/dist/core/rendering/getVisibleRouteLines.d.ts +10 -0
  43. package/dist/core/rendering/getVisibleRouteLines.js +18 -0
  44. package/dist/core/rendering/routeGeometry.d.ts +9 -0
  45. package/dist/core/rendering/routeGeometry.js +10 -0
  46. package/dist/core/routing/buildMultiPointRoute.d.ts +13 -0
  47. package/dist/core/routing/buildMultiPointRoute.js +36 -0
  48. package/dist/core/routing/buildRoute.d.ts +12 -0
  49. package/dist/core/routing/buildRoute.js +19 -0
  50. package/dist/core/routing/getRouteLength.d.ts +3 -0
  51. package/dist/core/routing/getRouteLength.js +4 -0
  52. package/dist/core/routing/graphPointResolvers.d.ts +9 -0
  53. package/dist/core/routing/graphPointResolvers.js +13 -0
  54. package/dist/core/routing/optimizeWaypointOrder.d.ts +14 -0
  55. package/dist/core/routing/optimizeWaypointOrder.js +88 -0
  56. package/dist/core/routing/resolveWaypointCandidates.d.ts +23 -0
  57. package/dist/core/routing/resolveWaypointCandidates.js +49 -0
  58. package/dist/core/routing/routeResult.d.ts +4 -0
  59. package/dist/core/routing/routeResult.js +2 -0
  60. package/dist/core/types.d.ts +102 -0
  61. package/dist/core/types.js +1 -0
  62. package/dist/createWayfinding.d.ts +81 -0
  63. package/dist/createWayfinding.js +46 -0
  64. package/dist/index.d.ts +18 -0
  65. package/dist/index.js +16 -0
  66. package/dist/renderer/createWayfindingRenderer.d.ts +8 -0
  67. package/dist/renderer/createWayfindingRenderer.js +45 -0
  68. package/dist/renderer/iconManager.d.ts +58 -0
  69. package/dist/renderer/iconManager.js +222 -0
  70. package/dist/renderer/index.d.ts +5 -0
  71. package/dist/renderer/index.js +2 -0
  72. package/dist/renderer/layerManager.d.ts +36 -0
  73. package/dist/renderer/layerManager.js +31 -0
  74. package/dist/renderer/layers.d.ts +54 -0
  75. package/dist/renderer/layers.js +66 -0
  76. package/dist/renderer/lineAnimation.d.ts +25 -0
  77. package/dist/renderer/lineAnimation.js +196 -0
  78. package/dist/renderer/routeLineManager.d.ts +45 -0
  79. package/dist/renderer/routeLineManager.js +153 -0
  80. package/dist/renderer/trailManager.d.ts +29 -0
  81. package/dist/renderer/trailManager.js +183 -0
  82. package/dist/renderer/types.d.ts +163 -0
  83. package/dist/renderer/types.js +1 -0
  84. package/dist/runtime/createWayfindingRuntime.d.ts +3 -0
  85. package/dist/runtime/createWayfindingRuntime.js +237 -0
  86. package/dist/runtime/endpointView.d.ts +19 -0
  87. package/dist/runtime/endpointView.js +44 -0
  88. package/dist/runtime/getRouteLines.d.ts +19 -0
  89. package/dist/runtime/getRouteLines.js +16 -0
  90. package/dist/runtime/index.d.ts +4 -0
  91. package/dist/runtime/index.js +2 -0
  92. package/dist/runtime/positionTrailView.d.ts +51 -0
  93. package/dist/runtime/positionTrailView.js +35 -0
  94. package/dist/runtime/positionView.d.ts +22 -0
  95. package/dist/runtime/positionView.js +34 -0
  96. package/dist/runtime/routeLinesView.d.ts +16 -0
  97. package/dist/runtime/routeLinesView.js +10 -0
  98. package/dist/runtime/routeRenderData.d.ts +31 -0
  99. package/dist/runtime/routeRenderData.js +44 -0
  100. package/dist/runtime/routeUpdate.d.ts +17 -0
  101. package/dist/runtime/routeUpdate.js +17 -0
  102. package/dist/runtime/snapPositionToRoute.d.ts +10 -0
  103. package/dist/runtime/snapPositionToRoute.js +36 -0
  104. package/dist/runtime/trailView.d.ts +19 -0
  105. package/dist/runtime/trailView.js +43 -0
  106. package/dist/runtime/transitionView.d.ts +16 -0
  107. package/dist/runtime/transitionView.js +51 -0
  108. package/dist/runtime/types.d.ts +81 -0
  109. package/dist/runtime/types.js +1 -0
  110. package/package.json +45 -0
@@ -0,0 +1,196 @@
1
+ /** How much of a segment is drawn: the whole of it, or none. */
2
+ const WHOLE = 1;
3
+ const NOTHING = 0;
4
+ /**
5
+ * Runs the chase animation over route segments that are already in the scene, **moving them in
6
+ * place**: the segments behind the head are drawn whole, the one under it is drawn part-way, and the
7
+ * ones ahead are hidden.
8
+ *
9
+ * The membership never changes, which is the point. Rebuilding the layer's children every frame —
10
+ * with a fresh def for the partial segment — remounted an instance and churned a batch slot sixty
11
+ * times a second, and the overlay lost everything but the newest chunk. `LineDef.points` is re-read
12
+ * on every update precisely so an animation can move a line instead of replacing it.
13
+ *
14
+ * Only what actually changed is reported: normally the single segment under the head, and every
15
+ * segment once per lap, when the chase wraps.
16
+ * @param segments - The defs to animate, in route order. Their `points` are moved in place.
17
+ * @param onChange - Called with the defs that changed, for the caller to commit.
18
+ * @param getPixelSize - Plan units per CSS pixel, which the speed is modulated by.
19
+ * @param startProgress - Where in the lap to resume, in `[0, 1)`.
20
+ * @returns A handle, or nothing when there is no route to animate.
21
+ */
22
+ export function animateLineSegments(segments, onChange, getPixelSize, startProgress = 0) {
23
+ let currentSegmentIndex = 0;
24
+ let segmentProgress = 0;
25
+ let lastTimestamp = null;
26
+ let animationFrameId = null;
27
+ if (!segments.length)
28
+ return;
29
+ // Captured before anything is moved: from here on a def's own `p1` is wherever the chase left it.
30
+ // Copied rather than aliased, since the def's `points` is what gets replaced; `elevation` rides
31
+ // along so a segment on a raised plane does not drop to the floor the first time it is redrawn.
32
+ const ends = segments.map((segment) => ({
33
+ p0: { x: segment.points.p0.x, y: segment.points.p0.y },
34
+ p1: { x: segment.points.p1.x, y: segment.points.p1.y },
35
+ elevation: segment.points.elevation,
36
+ }));
37
+ const segmentLengths = ends.map((end) => {
38
+ const dx = end.p1.x - end.p0.x;
39
+ const dy = end.p1.y - end.p0.y;
40
+ return Math.sqrt(dx * dx + dy * dy);
41
+ });
42
+ /**
43
+ * The fraction each segment is currently drawn at; `-1` until it has been written even once. A
44
+ * segment handed over hidden already reads as empty, so the opening render skips it.
45
+ */
46
+ const drawn = segments.map((segment) => (segment.hidden ? NOTHING : -1));
47
+ /** What the frame being rendered moved, refilled per frame so a frame allocates nothing. */
48
+ const changed = [];
49
+ const totalLength = segmentLengths.reduce((a, b) => a + b, 0);
50
+ // A zero-length route would spin the per-frame while-loop forever.
51
+ if (!totalLength)
52
+ return;
53
+ const baseSpeed = Math.max(20, Math.min(totalLength / 2, 300));
54
+ function initFromProgress(progress) {
55
+ const targetDistance = (progress % 1) * totalLength;
56
+ let accumulated = 0;
57
+ currentSegmentIndex = 0;
58
+ segmentProgress = 0;
59
+ for (let i = 0; i < segmentLengths.length; i++) {
60
+ if (accumulated + segmentLengths[i] > targetDistance) {
61
+ currentSegmentIndex = i;
62
+ segmentProgress = targetDistance - accumulated;
63
+ break;
64
+ }
65
+ accumulated += segmentLengths[i];
66
+ if (i === segmentLengths.length - 1) {
67
+ currentSegmentIndex = 0;
68
+ segmentProgress = 0;
69
+ }
70
+ }
71
+ }
72
+ /**
73
+ * Brings one segment to a fraction of its length — hidden at `0`, whole at `1`, cut short between
74
+ * — and records it as changed if that moved it. A segment already drawn at this fraction costs
75
+ * nothing, which is what keeps a frame to the one segment under the head.
76
+ *
77
+ * `points` is replaced rather than mutated, because a `LineLike`'s coordinates are readonly. The
78
+ * def stays the same object throughout, which is all the renderer keys anything on.
79
+ * @param index - The segment to draw.
80
+ * @param fraction - How much of it to draw, in `[0, 1]`.
81
+ */
82
+ function draw(index, fraction) {
83
+ if (drawn[index] === fraction)
84
+ return;
85
+ drawn[index] = fraction;
86
+ const segment = segments[index];
87
+ const end = ends[index];
88
+ segment.hidden = fraction <= NOTHING;
89
+ if (!segment.hidden) {
90
+ const { p0, p1 } = end;
91
+ segment.points =
92
+ fraction >= WHOLE
93
+ ? end
94
+ : {
95
+ p0,
96
+ p1: { x: p0.x + (p1.x - p0.x) * fraction, y: p0.y + (p1.y - p0.y) * fraction },
97
+ elevation: end.elevation,
98
+ };
99
+ }
100
+ changed.push(segment);
101
+ }
102
+ /**
103
+ * Brings every segment to the state the head's position implies: everything behind it is whole,
104
+ * the one under it is part-drawn, everything ahead of it is empty.
105
+ */
106
+ function render() {
107
+ changed.length = 0;
108
+ const head = currentSegmentIndex;
109
+ for (let i = 0; i < head; i++)
110
+ draw(i, WHOLE);
111
+ // A zero-length segment is whole the moment the head reaches it: dividing by its length gives
112
+ // `Infinity` once the head has moved, but `NaN` on the opening render, where progress is zero.
113
+ const headLength = segmentLengths[head];
114
+ draw(head, headLength ? Math.min(segmentProgress / headLength, WHOLE) : WHOLE);
115
+ for (let i = head + 1; i < segments.length; i++)
116
+ draw(i, NOTHING);
117
+ if (changed.length)
118
+ onChange(changed);
119
+ }
120
+ function animate(timestamp) {
121
+ lastTimestamp ??= timestamp;
122
+ const delta = (timestamp - lastTimestamp) / 1000;
123
+ lastTimestamp = timestamp;
124
+ const pixelSize = getPixelSize();
125
+ // A detached canvas (host element removed from the DOM on SPA navigation) reports a bogus pixel
126
+ // size (Infinity on a zero-size canvas). Anything but a positive finite value poisons
127
+ // segmentProgress and spins the loop below, freezing the tab — skip the frame until a usable one
128
+ // returns.
129
+ if (!(Number.isFinite(pixelSize) && pixelSize > 0)) {
130
+ animationFrameId = requestAnimationFrame(animate);
131
+ return;
132
+ }
133
+ const adjustedSpeed = baseSpeed * Math.sqrt(pixelSize);
134
+ segmentProgress += adjustedSpeed * delta;
135
+ // Keep progress within a single lap. totalLength > 0 is guaranteed above, so
136
+ // the loop can advance at most segments.length steps — it can never spin,
137
+ // whatever pixel size/delta the camera feeds in.
138
+ segmentProgress %= totalLength;
139
+ while (segmentProgress >= segmentLengths[currentSegmentIndex]) {
140
+ segmentProgress -= segmentLengths[currentSegmentIndex];
141
+ currentSegmentIndex++;
142
+ if (currentSegmentIndex >= segments.length) {
143
+ currentSegmentIndex = 0;
144
+ }
145
+ }
146
+ render();
147
+ animationFrameId = requestAnimationFrame(animate);
148
+ }
149
+ function start() {
150
+ stop();
151
+ if (startProgress <= 0) {
152
+ currentSegmentIndex = 0;
153
+ segmentProgress = 0;
154
+ }
155
+ lastTimestamp = null;
156
+ // Drawn now rather than on the first frame, so the segments go into the caller's commit already
157
+ // in their resumed state: a chase that waited for its first frame left the route blank for one.
158
+ render();
159
+ animationFrameId = requestAnimationFrame(animate);
160
+ }
161
+ function stop() {
162
+ if (animationFrameId) {
163
+ cancelAnimationFrame(animationFrameId);
164
+ animationFrameId = null;
165
+ lastTimestamp = null;
166
+ }
167
+ }
168
+ function getProgress() {
169
+ if (totalLength <= 0)
170
+ return 0;
171
+ let accumulated = 0;
172
+ for (let i = 0; i < currentSegmentIndex; i++) {
173
+ accumulated += segmentLengths[i];
174
+ }
175
+ accumulated += segmentProgress;
176
+ return accumulated / totalLength;
177
+ }
178
+ function handleVisibilityChange() {
179
+ if (document.visibilityState === 'visible')
180
+ start();
181
+ else
182
+ stop();
183
+ }
184
+ if (startProgress > 0) {
185
+ initFromProgress(startProgress);
186
+ }
187
+ document.addEventListener('visibilitychange', handleVisibilityChange);
188
+ start();
189
+ return {
190
+ stop: () => {
191
+ stop();
192
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
193
+ },
194
+ getProgress,
195
+ };
196
+ }
@@ -0,0 +1,45 @@
1
+ import type { LayerManager } from './layerManager.js';
2
+ import type { WayfindingLayers } from './layers.js';
3
+ import type { RendererPort, RouteColors } from './types.js';
4
+ /**
5
+ * Manages static route lines (passed + remaining) and an animated overlay
6
+ * on the remaining segment.
7
+ */
8
+ export interface RouteLineManager {
9
+ setRouteLines(passed: readonly {
10
+ readonly p0: {
11
+ x: number;
12
+ y: number;
13
+ };
14
+ readonly p1: {
15
+ x: number;
16
+ y: number;
17
+ };
18
+ }[], remaining: readonly {
19
+ readonly p0: {
20
+ x: number;
21
+ y: number;
22
+ };
23
+ readonly p1: {
24
+ x: number;
25
+ y: number;
26
+ };
27
+ }[], options?: {
28
+ readonly resetAnimation?: boolean;
29
+ }): void;
30
+ /** Stop animation, wipe both lines layers. */
31
+ clearLines(): void;
32
+ /** Alias for {@link clearLines}. */
33
+ destroy(): void;
34
+ }
35
+ /**
36
+ * Create a {@link RouteLineManager} that renders `LineDef` segments
37
+ * into layers managed by the given {@link LayerManager}.
38
+ * @param layerManager - Tracks what changed.
39
+ * @param colors - The route palette.
40
+ * @param port - The commit function the animation ticks through.
41
+ * @param layers - The two line layers to draw into.
42
+ * @returns The manager.
43
+ */
44
+ export declare function createRouteLineManager(layerManager: LayerManager, colors: RouteColors, port: RendererPort, layers: Pick<WayfindingLayers, 'lines' | 'linesAnimated'>): RouteLineManager;
45
+ //# sourceMappingURL=routeLineManager.d.ts.map
@@ -0,0 +1,153 @@
1
+ import { animateLineSegments } from './lineAnimation.js';
2
+ /**
3
+ * Builds one route line. The points are copied rather than aliased: the caller keeps its segments,
4
+ * and the animated overlay replaces its own `points` as the head travels.
5
+ * @param seg - The segment to draw.
6
+ * @param color - Stroke color.
7
+ * @returns The def.
8
+ */
9
+ function lineDef({ p0, p1 }, color) {
10
+ return { points: { p0: { x: p0.x, y: p0.y }, p1: { x: p1.x, y: p1.y } }, color, width: 10 };
11
+ }
12
+ /**
13
+ * Whether a line was built from this segment: the same endpoints, compared where
14
+ * {@link lineDef} copied them.
15
+ * @param def - The line.
16
+ * @param seg - The segment.
17
+ * @returns Whether they match.
18
+ */
19
+ function sameSegment(def, seg) {
20
+ return (def.points.p0.x === seg.p0.x &&
21
+ def.points.p0.y === seg.p0.y &&
22
+ def.points.p1.x === seg.p1.x &&
23
+ def.points.p1.y === seg.p1.y);
24
+ }
25
+ /**
26
+ * Create a {@link RouteLineManager} that renders `LineDef` segments
27
+ * into layers managed by the given {@link LayerManager}.
28
+ * @param layerManager - Tracks what changed.
29
+ * @param colors - The route palette.
30
+ * @param port - The commit function the animation ticks through.
31
+ * @param layers - The two line layers to draw into.
32
+ * @returns The manager.
33
+ */
34
+ export function createRouteLineManager(layerManager, colors, port, layers) {
35
+ const linesLayer = layers.lines;
36
+ const animatedLayer = layers.linesAnimated;
37
+ let animationHandle = null;
38
+ /**
39
+ * The pixel size the chase animation modulates its speed by. Route lines need no layout of their
40
+ * own — `LineDef.width` is already in screen pixels — so this is the one thing the animated layer's
41
+ * handler exists to deliver.
42
+ */
43
+ let currentPixelSize = 1;
44
+ /**
45
+ * Reports the pixel size to the chase animation — the animated-lines layer's `onScale`.
46
+ *
47
+ * Lays nothing out and returns nothing, so it never costs a write. It is here because the speed
48
+ * term reads a scale and there is no other channel that carries one.
49
+ * @param pixelSize - Plan units per CSS pixel.
50
+ */
51
+ function readPixelSize(pixelSize) {
52
+ currentPixelSize = pixelSize;
53
+ }
54
+ /**
55
+ * Empties one lines layer, hiding what it held first — see {@link hideDeparting}.
56
+ * @param layer - The layer to empty.
57
+ */
58
+ function wipe(layer) {
59
+ hideDeparting(layer);
60
+ layer.children = [];
61
+ layerManager.touchLayer(layer);
62
+ }
63
+ /**
64
+ * Hides every line a layer still holds, before whatever replaces them.
65
+ *
66
+ * The renderer commits a def write synchronously but defers the membership sweep — renderer's
67
+ * `useStagedChildren` (`objects/layer/mount-scheduler.ts`) pipes a layer's children through
68
+ * `useDeferredValue` — so lines that were only removed outlive the route's icons, which
69
+ * `hideIcon` hides in place, by a frame or more. That is how a cleared route's line lingered
70
+ * behind its pins. Drop this if the renderer ever hides departed defs urgently itself.
71
+ * @param layer - The layer whose current lines are on their way out.
72
+ */
73
+ function hideDeparting(layer) {
74
+ for (const def of layer.children) {
75
+ def.hidden = true;
76
+ layerManager.touchDef(def);
77
+ }
78
+ }
79
+ /**
80
+ * Whether the layers already hold exactly these segments, split at the same place. The static
81
+ * defs are never moved, so their points still read as the segments they were built from; the
82
+ * animated layer holds one def per remaining segment, which is where the split shows.
83
+ * @param passed - The segments behind the position.
84
+ * @param remaining - The segments ahead of it.
85
+ * @returns Whether the layers hold them.
86
+ */
87
+ function holdsSameLines(passed, remaining) {
88
+ const current = linesLayer.children;
89
+ if (current.length !== passed.length + remaining.length)
90
+ return false;
91
+ if (animatedLayer.children.length !== remaining.length)
92
+ return false;
93
+ return (passed.every((seg, i) => sameSegment(current[i], seg)) &&
94
+ remaining.every((seg, i) => sameSegment(current[passed.length + i], seg)));
95
+ }
96
+ return {
97
+ setRouteLines(passed, remaining, options) {
98
+ const reset = options?.resetAnimation ?? true;
99
+ // The same lines again: let the chase run on instead of remounting every def under it.
100
+ if (!reset && holdsSameLines(passed, remaining))
101
+ return;
102
+ layerManager.touchLayer(linesLayer);
103
+ layerManager.touchLayer(animatedLayer);
104
+ // Declared on every call rather than at construction: the `update(layer)` a flush performs is
105
+ // what makes the renderer register the layer under this handler.
106
+ animatedLayer.onScale = ({ pixelSize }) => readPixelSize(pixelSize);
107
+ let resumeFrom = 0;
108
+ if (animationHandle) {
109
+ if (!reset)
110
+ resumeFrom = animationHandle.getProgress();
111
+ animationHandle.stop();
112
+ animationHandle = null;
113
+ }
114
+ // Every call replaces both layers wholesale, so the lines on their way out are hidden first
115
+ // — `setRouteLines([], [])` is how a route is cleared.
116
+ hideDeparting(linesLayer);
117
+ hideDeparting(animatedLayer);
118
+ const passedDefs = passed.map((seg) => lineDef(seg, colors.passed));
119
+ const remainingDefs = remaining.map((seg) => lineDef(seg, colors.remaining));
120
+ linesLayer.children = [...passedDefs, ...remainingDefs];
121
+ if (!remainingDefs.length) {
122
+ animatedLayer.children = [];
123
+ return;
124
+ }
125
+ // Built from the segments rather than copied off `remainingDefs`, so the two never share a
126
+ // `points` object: the chase moves these in place, and the static line beneath must not move
127
+ // with them. They start hidden, and the animation shows each as the head reaches it.
128
+ const animatedDefs = remaining.map((seg) => ({
129
+ ...lineDef(seg, colors.active),
130
+ hidden: true,
131
+ }));
132
+ // Mounted once. The chase moves these defs rather than rewriting this array, so no instance is
133
+ // remounted and no batch slot churns while it runs.
134
+ animatedLayer.children = animatedDefs;
135
+ animationHandle =
136
+ animateLineSegments(animatedDefs, (changed) => port.update(...changed), () => currentPixelSize, resumeFrom) ?? null;
137
+ },
138
+ clearLines() {
139
+ if (animationHandle) {
140
+ animationHandle.stop();
141
+ animationHandle = null;
142
+ }
143
+ wipe(linesLayer);
144
+ wipe(animatedLayer);
145
+ },
146
+ destroy() {
147
+ this.clearLines();
148
+ // The layer outlives this manager, so the handler goes with it: left in place it keeps the
149
+ // manager reachable and runs on every camera step.
150
+ animatedLayer.onScale = undefined;
151
+ },
152
+ };
153
+ }
@@ -0,0 +1,29 @@
1
+ import { type Point2Like } from '@expofp/geometry';
2
+ import type { ImageDef, LayerDef } from '@expofp/renderer';
3
+ import type { LayerManager } from './layerManager.js';
4
+ import type { TrailOptions } from './types.js';
5
+ /**
6
+ * Manages named trails of evenly-spaced dots between two points.
7
+ *
8
+ * A trail's spacing is fixed in screen pixels, so zooming out does not shrink its dots — it holds
9
+ * fewer of them. That makes a camera move a **membership** change, which is why the layout rule is
10
+ * declared on the trail layer rather than on the dots: the defs that have to disappear cannot be the
11
+ * ones asked to lay themselves out.
12
+ */
13
+ export interface TrailManager {
14
+ /**
15
+ * Place, update, or remove a named trail.
16
+ * Pass `from/to = null` to remove the trail.
17
+ */
18
+ setTrail(name: string, from: Point2Like | null, to: Point2Like | null, options?: TrailOptions): void;
19
+ /** Remove all trails. */
20
+ destroy(): void;
21
+ }
22
+ /**
23
+ * Create a {@link TrailManager} that renders dot trails into the block's trail layer.
24
+ * @param layerManager - Tracks what changed.
25
+ * @param layer - The layer the dots go in.
26
+ * @returns The manager.
27
+ */
28
+ export declare function createTrailManager(layerManager: LayerManager, layer: LayerDef<ImageDef>): TrailManager;
29
+ //# sourceMappingURL=trailManager.d.ts.map
@@ -0,0 +1,183 @@
1
+ import { Rect } from '@expofp/geometry';
2
+ import { computeTrailPoints } from '../core/index.js';
3
+ import { resolveCssSize } from './iconManager.js';
4
+ /** Distance between trail dots at a pixel size of 1, in the same units as route points. */
5
+ const TRAIL_INTERVAL_AT_BASE_PIXEL_SIZE = 40;
6
+ /**
7
+ * Create a {@link TrailManager} that renders dot trails into the block's trail layer.
8
+ * @param layerManager - Tracks what changed.
9
+ * @param layer - The layer the dots go in.
10
+ * @returns The manager.
11
+ */
12
+ export function createTrailManager(layerManager, layer) {
13
+ const trails = new Map();
14
+ /**
15
+ * The pixel size the trails currently hold their spacing for.
16
+ *
17
+ * The one place the wayfinding side remembers a pixel size, and it has to: a trail's membership
18
+ * changes for two reasons and only one of them is a camera move — `setTrail` rebuilds when the
19
+ * route changes, at a moment no `onScale` is delivering a size. Seeded at `1` and corrected by the
20
+ * layer handler's first run, which registration performs before anything is drawn.
21
+ */
22
+ let currentPixelSize = 1;
23
+ /**
24
+ * Whether this manager has declared its `onScale` on the layer.
25
+ *
26
+ * Declaring the handler is not enough to be called: `useLayoutTargets` registers a layer as a
27
+ * layout target from a render, so the layer has to be committed once after the handler appears.
28
+ * That commit is a membership change, which is why it happens once rather than per redraw.
29
+ */
30
+ let wired = false;
31
+ /**
32
+ * Lays every trail on one layer out for a new pixel size — what each trail layer's `onScale`
33
+ * closure delegates to.
34
+ *
35
+ * One function per manager, not per def: what it reads is this manager's trails.
36
+ * @param pixelSize - Plan units per CSS pixel.
37
+ * @returns The dots that were written, plus the layer when the dot count changed with them.
38
+ */
39
+ function layOutTrails(pixelSize) {
40
+ currentPixelSize = pixelSize;
41
+ const changed = [];
42
+ let membershipChanged = false;
43
+ for (const record of trails.values()) {
44
+ const result = redraw(record);
45
+ changed.push(...result.changed);
46
+ membershipChanged ||= result.membershipChanged;
47
+ }
48
+ // The layer only when the dot count changed: a def write lands in this frame, a membership
49
+ // change a transition later, so a camera step that only shifts dots stays in this one.
50
+ if (membershipChanged)
51
+ changed.push(layer);
52
+ return changed.length ? changed : undefined;
53
+ }
54
+ /**
55
+ * Takes dots out of their layer, hidden first.
56
+ *
57
+ * The hide is not redundant with the removal: the renderer commits a def write synchronously and
58
+ * defers the membership sweep, so a dot that was only removed stays on screen a frame or more.
59
+ * @param record - The trail the dots belong to.
60
+ * @param dots - The dots to take out.
61
+ */
62
+ function removeDots(record, dots) {
63
+ if (!dots.length)
64
+ return;
65
+ const dropped = new Set(dots);
66
+ for (const dot of dropped)
67
+ dot.hidden = true;
68
+ layer.children = layer.children.filter((child) => !dropped.has(child));
69
+ layerManager.touchLayer(layer);
70
+ }
71
+ /** Declares this manager's `onScale` on the layer, once. */
72
+ function wireLayer() {
73
+ if (wired)
74
+ return;
75
+ layer.onScale = ({ pixelSize }) => layOutTrails(pixelSize);
76
+ wired = true;
77
+ // Committed with the layer, which is what makes the renderer register the handler.
78
+ layerManager.touchLayer(layer);
79
+ }
80
+ /**
81
+ * Lays one trail out at the current pixel size, reusing the dots it already holds.
82
+ *
83
+ * Spacing is fixed in screen pixels, so a camera step moves every dot and changes how many there
84
+ * are. Moving the survivors rather than replacing them is what keeps the common case a def write:
85
+ * only the difference in count reaches the layer's membership.
86
+ * @param record - The trail to lay out.
87
+ * @returns The dots that were written, and whether the layer's membership changed with them.
88
+ */
89
+ function redraw(record) {
90
+ wireLayer();
91
+ const interval = TRAIL_INTERVAL_AT_BASE_PIXEL_SIZE * currentPixelSize;
92
+ const points = computeTrailPoints(record.from, record.to, interval);
93
+ const canvas = record.canvas;
94
+ const size = { x: record.width * currentPixelSize, y: record.height * currentPixelSize };
95
+ const dots = record.dotDefs;
96
+ const kept = Math.min(dots.length, points.length);
97
+ const changed = [];
98
+ for (let i = 0; i < kept; i++) {
99
+ const bounds = dots[i].bounds;
100
+ bounds.set(points[i].x, points[i].y, size.x, size.y, bounds.rotation, bounds.elevation);
101
+ changed.push(dots[i]);
102
+ }
103
+ if (points.length > kept) {
104
+ const added = points
105
+ .slice(kept)
106
+ .map((point) => ({ source: canvas, bounds: new Rect({ x: point.x, y: point.y }, size) }));
107
+ layer.children.push(...added);
108
+ dots.push(...added);
109
+ layerManager.touchLayer(layer);
110
+ return { changed, membershipChanged: true };
111
+ }
112
+ if (dots.length > kept) {
113
+ const dropped = dots.splice(kept);
114
+ removeDots(record, dropped);
115
+ // Hidden, and reported with the rest: the hide is a def write, and only a def the handler
116
+ // returns is written in this frame — the removal itself lands a transition later.
117
+ changed.push(...dropped);
118
+ return { changed, membershipChanged: true };
119
+ }
120
+ return { changed, membershipChanged: false };
121
+ }
122
+ function drop(name) {
123
+ const record = trails.get(name);
124
+ if (!record)
125
+ return;
126
+ removeDots(record, record.dotDefs);
127
+ for (const dot of record.dotDefs)
128
+ layerManager.touchDef(dot);
129
+ record.dotDefs = [];
130
+ trails.delete(name);
131
+ }
132
+ /**
133
+ * Queues what a redraw wrote for the next {@link LayerManager.flush} — the buffered path only.
134
+ *
135
+ * A redraw driven by the camera reports the same defs to the renderer, which writes them in that
136
+ * frame; queuing them here as well would leave them in the dirty set for an unrelated flush to
137
+ * commit again.
138
+ * @param result - What the redraw changed.
139
+ */
140
+ function bufferRedraw(result) {
141
+ for (const def of result.changed)
142
+ layerManager.touchDef(def);
143
+ }
144
+ return {
145
+ setTrail(name, from, to, options) {
146
+ if (from === null || to === null) {
147
+ drop(name);
148
+ return;
149
+ }
150
+ if (!options)
151
+ throw new Error(`renderer: setTrail("${name}") requires options when from/to are non-null`);
152
+ const existing = trails.get(name);
153
+ if (existing) {
154
+ if (existing.canvas !== options.canvas) {
155
+ throw new Error(`renderer: trail "${name}" cannot change canvas after first call`);
156
+ }
157
+ existing.from = from;
158
+ existing.to = to;
159
+ bufferRedraw(redraw(existing));
160
+ return;
161
+ }
162
+ const { width, height } = resolveCssSize(options.canvas, options.width, options.height);
163
+ const record = {
164
+ from,
165
+ to,
166
+ canvas: options.canvas,
167
+ width,
168
+ height,
169
+ dotDefs: [],
170
+ };
171
+ trails.set(name, record);
172
+ bufferRedraw(redraw(record));
173
+ },
174
+ destroy() {
175
+ for (const trailName of [...trails.keys()])
176
+ drop(trailName);
177
+ // The layer outlives this manager, so the handler has to go with it: left in place it keeps
178
+ // the manager, its layer and its canvases reachable, and runs on every camera step.
179
+ layer.onScale = undefined;
180
+ wired = false;
181
+ },
182
+ };
183
+ }