drone-path 0.0.0 → 0.8.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/CHANGELOG.md +186 -0
- package/LICENSE +21 -0
- package/README.md +83 -6
- package/THIRD-PARTY-NOTICES.md +77 -0
- package/app/main.mjs +496 -0
- package/app/preload.cjs +31 -0
- package/app/update-policy.d.mts +6 -0
- package/app/update-policy.mjs +6 -0
- package/app/update.d.mts +10 -0
- package/app/update.mjs +54 -0
- package/bin/drone-path.mjs +5 -0
- package/dist/appassets.js +44 -0
- package/dist/apppaths.js +28 -0
- package/dist/appsession.js +128 -0
- package/dist/appstate.js +109 -0
- package/dist/assets.js +67 -0
- package/dist/cammeta.js +292 -0
- package/dist/changeset-gate.js +46 -0
- package/dist/cli.js +156 -0
- package/dist/config.js +469 -0
- package/dist/configfile.js +81 -0
- package/dist/decimate.js +94 -0
- package/dist/errors.js +4 -0
- package/dist/exportjob.js +106 -0
- package/dist/ff.js +121 -0
- package/dist/fftools.js +65 -0
- package/dist/geo.js +70 -0
- package/dist/inputs.js +59 -0
- package/dist/manual/anchors.js +23 -0
- package/dist/manual/build.js +78 -0
- package/dist/manual/cliref.js +36 -0
- package/dist/manual/links.js +76 -0
- package/dist/manual/markdown.js +101 -0
- package/dist/manual/model.js +4 -0
- package/dist/manual/module.js +8 -0
- package/dist/manual/nav.js +13 -0
- package/dist/manual/reference.js +26 -0
- package/dist/page.js +108 -0
- package/dist/paths.js +28 -0
- package/dist/plan.js +119 -0
- package/dist/png.js +52 -0
- package/dist/proto.js +102 -0
- package/dist/range.js +58 -0
- package/dist/render.js +408 -0
- package/dist/renderer/boot.js +7 -0
- package/dist/renderer/dom.js +132 -0
- package/dist/renderer/framemath.js +34 -0
- package/dist/renderer/leaflet.js +5 -0
- package/dist/renderer/scene.js +358 -0
- package/dist/renderer/theme.js +34 -0
- package/dist/renderer/tilesources.js +34 -0
- package/dist/renderer/trail.js +53 -0
- package/dist/restyle.js +24 -0
- package/dist/run.js +446 -0
- package/dist/serve.js +70 -0
- package/dist/srt.js +76 -0
- package/dist/summary.js +22 -0
- package/dist/telemetry-math.js +302 -0
- package/dist/telemetry.js +38 -0
- package/dist/tilecache.js +26 -0
- package/dist/tiles.js +241 -0
- package/dist/tracing.js +208 -0
- package/dist/version.js +3 -0
- package/package.json +94 -8
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// Pure telemetry math: turns time-stamped samples into per-frame values
|
|
2
|
+
// (position, speed, heading) plus the track statistics. No I/O lives here,
|
|
3
|
+
// so the loader shell and the unit tests drive it directly with in-memory
|
|
4
|
+
// samples.
|
|
5
|
+
import { bearingDeg, circularMeanDeg, haversineM } from './geo.js';
|
|
6
|
+
const MAX_INTERPOLATION_GAP_S = 3; // hold the earlier fix across longer gaps
|
|
7
|
+
const SPEED_SMOOTHING_SPAN = 5; // +-N samples moving average for the HUD
|
|
8
|
+
const HEADING_MIN_MOVE_M = 1.5; // ignore bearings from sub-meter displacement
|
|
9
|
+
const HEADING_HALF_WINDOW_S = 0.35; // preferred course baseline half-width
|
|
10
|
+
const HEADING_MAX_BASELINE_S = 3; // widened baseline for slow flights
|
|
11
|
+
const HEADING_MIN_SPEED_MPS = 0.5; // below this the course is meaningless
|
|
12
|
+
const HEADING_SMOOTHING_SPAN = 4; // +-N samples circular mean
|
|
13
|
+
function isFixSample(sample) {
|
|
14
|
+
return sample.fix !== null;
|
|
15
|
+
}
|
|
16
|
+
// The fix-bearing samples in order, with their indices; the pipeline works
|
|
17
|
+
// from these instead of re-deriving who carries a fix.
|
|
18
|
+
function fixRefs(samples) {
|
|
19
|
+
const refs = [];
|
|
20
|
+
samples.forEach((sample, index) => {
|
|
21
|
+
if (isFixSample(sample))
|
|
22
|
+
refs.push({ ...sample, index });
|
|
23
|
+
});
|
|
24
|
+
return refs;
|
|
25
|
+
}
|
|
26
|
+
function altitudeOf(sample) {
|
|
27
|
+
return sample.relAlt ?? sample.absAlt ?? null;
|
|
28
|
+
}
|
|
29
|
+
function positionOfSample(sample) {
|
|
30
|
+
return { fix: sample.fix, alt: altitudeOf(sample) };
|
|
31
|
+
}
|
|
32
|
+
function interpolateAltitude(a, b, fraction) {
|
|
33
|
+
const altA = altitudeOf(a);
|
|
34
|
+
const altB = altitudeOf(b);
|
|
35
|
+
if (altA === null)
|
|
36
|
+
return altB;
|
|
37
|
+
if (altB === null)
|
|
38
|
+
return altA;
|
|
39
|
+
return altA + (altB - altA) * fraction;
|
|
40
|
+
}
|
|
41
|
+
// Nearest sample with a GPS fix at or beyond idx in the given direction.
|
|
42
|
+
function nearestFix(samples, idx, direction) {
|
|
43
|
+
let i = idx;
|
|
44
|
+
while (i >= 0 && i < samples.length) {
|
|
45
|
+
const sample = samples[i];
|
|
46
|
+
if (isFixSample(sample))
|
|
47
|
+
return sample;
|
|
48
|
+
i += direction;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
// Position at time t (seconds). Gaps of missing fixes longer than maxGapSec
|
|
53
|
+
// are bridged by holding the earlier fix instead of interpolating across them.
|
|
54
|
+
function positionAt(samples, t, maxGapSec = MAX_INTERPOLATION_GAP_S) {
|
|
55
|
+
const n = samples.length;
|
|
56
|
+
if (n === 0)
|
|
57
|
+
return { fix: null, alt: null };
|
|
58
|
+
if (t <= samples[0].tSec)
|
|
59
|
+
return positionOfSample(samples[0]);
|
|
60
|
+
if (t >= samples[n - 1].tSec)
|
|
61
|
+
return positionOfSample(samples[n - 1]);
|
|
62
|
+
const lo = sampleIndexBefore(samples, t);
|
|
63
|
+
const hi = lo + 1;
|
|
64
|
+
const a = nearestFix(samples, lo, -1);
|
|
65
|
+
const b = nearestFix(samples, hi, 1);
|
|
66
|
+
if (a !== null && b === null)
|
|
67
|
+
return positionOfSample(a);
|
|
68
|
+
if (a === null && b !== null)
|
|
69
|
+
return positionOfSample(b);
|
|
70
|
+
if (a === null || b === null)
|
|
71
|
+
return { fix: null, alt: null };
|
|
72
|
+
const dt = b.tSec - a.tSec;
|
|
73
|
+
const gapOk = dt > 0 && dt <= maxGapSec;
|
|
74
|
+
const fraction = gapOk ? (t - a.tSec) / dt : 0;
|
|
75
|
+
return {
|
|
76
|
+
fix: {
|
|
77
|
+
lat: a.fix.lat + (b.fix.lat - a.fix.lat) * fraction,
|
|
78
|
+
lon: a.fix.lon + (b.fix.lon - a.fix.lon) * fraction,
|
|
79
|
+
},
|
|
80
|
+
alt: interpolateAltitude(a, b, fraction),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
// t before the first sample yields index 0.
|
|
84
|
+
function sampleIndexBefore(samples, t) {
|
|
85
|
+
let lo = 0;
|
|
86
|
+
let hi = samples.length - 1;
|
|
87
|
+
while (hi - lo > 1) {
|
|
88
|
+
const mid = (lo + hi) >> 1;
|
|
89
|
+
if (samples[mid].tSec <= t)
|
|
90
|
+
lo = mid;
|
|
91
|
+
else
|
|
92
|
+
hi = mid;
|
|
93
|
+
}
|
|
94
|
+
return lo;
|
|
95
|
+
}
|
|
96
|
+
function nearestSampleIndex(samples, t) {
|
|
97
|
+
const lo = sampleIndexBefore(samples, t);
|
|
98
|
+
const hi = Math.min(lo + 1, samples.length - 1);
|
|
99
|
+
return t - samples[lo].tSec <= samples[hi].tSec - t ? lo : hi;
|
|
100
|
+
}
|
|
101
|
+
function computeTrackStats(fixes) {
|
|
102
|
+
const bbox = {
|
|
103
|
+
minLat: Infinity,
|
|
104
|
+
maxLat: -Infinity,
|
|
105
|
+
minLon: Infinity,
|
|
106
|
+
maxLon: -Infinity,
|
|
107
|
+
};
|
|
108
|
+
let trackDistanceM = 0;
|
|
109
|
+
let prev = null;
|
|
110
|
+
for (const { fix } of fixes) {
|
|
111
|
+
bbox.minLat = Math.min(bbox.minLat, fix.lat);
|
|
112
|
+
bbox.maxLat = Math.max(bbox.maxLat, fix.lat);
|
|
113
|
+
bbox.minLon = Math.min(bbox.minLon, fix.lon);
|
|
114
|
+
bbox.maxLon = Math.max(bbox.maxLon, fix.lon);
|
|
115
|
+
if (prev !== null) {
|
|
116
|
+
trackDistanceM += haversineM(prev, fix);
|
|
117
|
+
}
|
|
118
|
+
prev = fix;
|
|
119
|
+
}
|
|
120
|
+
return { bbox, trackDistanceM };
|
|
121
|
+
}
|
|
122
|
+
// Centered difference over neighboring fixes (m/s), smoothed with a moving
|
|
123
|
+
// average to tame GPS jitter for the HUD. Values live on the sample indexes
|
|
124
|
+
// so any sample can answer a frame's nearest-sample lookup.
|
|
125
|
+
function computeSpeedBySample(sampleCount, fixes) {
|
|
126
|
+
const rawSpeed = new Array(fixes.length).fill(null);
|
|
127
|
+
for (let k = 1; k < fixes.length - 1; k++) {
|
|
128
|
+
const dt = fixes[k + 1].tSec - fixes[k - 1].tSec;
|
|
129
|
+
if (dt > 0.001) {
|
|
130
|
+
rawSpeed[k] = haversineM(fixes[k - 1].fix, fixes[k + 1].fix) / dt;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// Endpoints reuse the adjacent centered value.
|
|
134
|
+
rawSpeed[0] = rawSpeed[1] ?? 0;
|
|
135
|
+
rawSpeed[fixes.length - 1] = rawSpeed[fixes.length - 2] ?? 0;
|
|
136
|
+
const speedBySample = new Array(sampleCount).fill(0);
|
|
137
|
+
for (let k = 0; k < fixes.length; k++) {
|
|
138
|
+
const lo = Math.max(0, k - SPEED_SMOOTHING_SPAN);
|
|
139
|
+
const hi = Math.min(fixes.length - 1, k + SPEED_SMOOTHING_SPAN);
|
|
140
|
+
let sum = 0;
|
|
141
|
+
let count = 0;
|
|
142
|
+
for (let j = lo; j <= hi; j++) {
|
|
143
|
+
const v = rawSpeed[j];
|
|
144
|
+
if (v !== null) {
|
|
145
|
+
sum += v;
|
|
146
|
+
count++;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
speedBySample[fixes[k].index] = count ? sum / count : 0;
|
|
150
|
+
}
|
|
151
|
+
return speedBySample;
|
|
152
|
+
}
|
|
153
|
+
// Preferred source: drone body yaw (DVTM EulerAngle, deci-degrees) - valid
|
|
154
|
+
// even while hovering. Fallback: course over ground measured across a moving
|
|
155
|
+
// baseline (consecutive fixes are only centimeters apart at 60 fps, so
|
|
156
|
+
// neighbor bearings are pure GPS jitter). Held while truly stationary.
|
|
157
|
+
function computeHeadingBySample(samples, fixes, speedBySample) {
|
|
158
|
+
const hasYaw = samples.some((sample) => sample.yawDeg !== null);
|
|
159
|
+
const headingMode = hasYaw ? 'yaw' : 'cog';
|
|
160
|
+
const rawHeading = new Array(fixes.length).fill(null);
|
|
161
|
+
if (hasYaw) {
|
|
162
|
+
fillYawHeadings(fixes, rawHeading);
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
fillCourseOverGroundHeadings(fixes, speedBySample, rawHeading);
|
|
166
|
+
}
|
|
167
|
+
fillHeadingGaps(rawHeading);
|
|
168
|
+
// Samples without a fix carry the default so the array is fully populated.
|
|
169
|
+
const defaultHeading = rawHeading[0] ?? firstKnownHeading(rawHeading) ?? 0;
|
|
170
|
+
const headingBySample = new Array(samples.length).fill(defaultHeading);
|
|
171
|
+
for (let k = 0; k < fixes.length; k++) {
|
|
172
|
+
const lo = Math.max(0, k - HEADING_SMOOTHING_SPAN);
|
|
173
|
+
const hi = Math.min(fixes.length - 1, k + HEADING_SMOOTHING_SPAN);
|
|
174
|
+
const window = [];
|
|
175
|
+
for (let j = lo; j <= hi; j++) {
|
|
176
|
+
window.push(rawHeading[j] ?? defaultHeading);
|
|
177
|
+
}
|
|
178
|
+
headingBySample[fixes[k].index] = circularMeanDeg(window);
|
|
179
|
+
}
|
|
180
|
+
return { headingBySample, headingMode };
|
|
181
|
+
}
|
|
182
|
+
function fillYawHeadings(fixes, rawHeading) {
|
|
183
|
+
for (let k = 0; k < fixes.length; k++) {
|
|
184
|
+
const yaw = fixes[k].yawDeg;
|
|
185
|
+
if (yaw !== null && Number.isFinite(yaw))
|
|
186
|
+
rawHeading[k] = ((yaw % 360) + 360) % 360;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function fillCourseOverGroundHeadings(fixes, speedBySample, rawHeading) {
|
|
190
|
+
for (let k = 0; k < fixes.length; k++) {
|
|
191
|
+
const tk = fixes[k].tSec;
|
|
192
|
+
if ((speedBySample[fixes[k].index] ?? 0) < HEADING_MIN_SPEED_MPS)
|
|
193
|
+
continue;
|
|
194
|
+
// Grow the baseline until the pair clears the GPS jitter floor: slow
|
|
195
|
+
// flights get a wider window instead of losing their heading to holds.
|
|
196
|
+
let ka = k;
|
|
197
|
+
let kb = k;
|
|
198
|
+
let displacement = 0;
|
|
199
|
+
for (const half of [HEADING_HALF_WINDOW_S, HEADING_MAX_BASELINE_S]) {
|
|
200
|
+
ka = k;
|
|
201
|
+
kb = k;
|
|
202
|
+
while (ka > 0 && fixes[ka].tSec > tk - half)
|
|
203
|
+
ka--;
|
|
204
|
+
while (kb < fixes.length - 1 && fixes[kb].tSec < tk + half)
|
|
205
|
+
kb++;
|
|
206
|
+
displacement = haversineM(fixes[ka].fix, fixes[kb].fix);
|
|
207
|
+
if (displacement >= HEADING_MIN_MOVE_M)
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
if (displacement >= HEADING_MIN_MOVE_M) {
|
|
211
|
+
rawHeading[k] = bearingDeg(fixes[ka].fix, fixes[kb].fix);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// The leading unknowns are back-filled from the FIRST known heading, never
|
|
216
|
+
// the flight's final heading, which would point the arrow the wrong way on
|
|
217
|
+
// clips that start hovering and turn later.
|
|
218
|
+
function fillHeadingGaps(rawHeading) {
|
|
219
|
+
let last = null;
|
|
220
|
+
for (let k = 0; k < rawHeading.length; k++) {
|
|
221
|
+
if (rawHeading[k] !== null)
|
|
222
|
+
last = rawHeading[k];
|
|
223
|
+
else
|
|
224
|
+
rawHeading[k] = last;
|
|
225
|
+
}
|
|
226
|
+
const firstKnown = firstKnownHeading(rawHeading);
|
|
227
|
+
if (firstKnown !== null) {
|
|
228
|
+
for (let k = 0; k < rawHeading.length; k++) {
|
|
229
|
+
if (rawHeading[k] === null)
|
|
230
|
+
rawHeading[k] = firstKnown;
|
|
231
|
+
else
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
for (let k = 0; k < rawHeading.length; k++) {
|
|
236
|
+
rawHeading[k] ??= firstKnown ?? 0;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function firstKnownHeading(rawHeading) {
|
|
240
|
+
for (const heading of rawHeading) {
|
|
241
|
+
if (heading !== null)
|
|
242
|
+
return heading;
|
|
243
|
+
}
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
function buildFrameData(samples, frames, fpsValue, speedBySample, headingBySample) {
|
|
247
|
+
const frameData = [];
|
|
248
|
+
for (let frame = 0; frame < frames; frame++) {
|
|
249
|
+
const t = frame / fpsValue;
|
|
250
|
+
const pos = positionAt(samples, t);
|
|
251
|
+
const si = nearestSampleIndex(samples, t);
|
|
252
|
+
frameData.push({
|
|
253
|
+
fix: pos.fix,
|
|
254
|
+
alt: pos.alt,
|
|
255
|
+
speed: Math.round(speedBySample[si] * 10) / 10,
|
|
256
|
+
headingDeg: Math.round(headingBySample[si] * 10) / 10,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
return frameData;
|
|
260
|
+
}
|
|
261
|
+
// Bridge fully-missing frame positions at the very ends: frames before the
|
|
262
|
+
// first fix hold the first fix, frames after the last fix hold the last fix
|
|
263
|
+
// (the hold-earlier policy from positionAt, applied past its ends).
|
|
264
|
+
function bridgeMissingFramePositions(frameData) {
|
|
265
|
+
const first = frameData.find((d) => d.fix !== null);
|
|
266
|
+
const last = [...frameData].reverse().find((d) => d.fix !== null);
|
|
267
|
+
if (!first || !last)
|
|
268
|
+
return;
|
|
269
|
+
let lead = 0;
|
|
270
|
+
while (lead < frameData.length && frameData[lead].fix === null) {
|
|
271
|
+
frameData[lead].fix = first.fix;
|
|
272
|
+
lead++;
|
|
273
|
+
}
|
|
274
|
+
let trail = frameData.length - 1;
|
|
275
|
+
while (trail >= lead && frameData[trail].fix === null) {
|
|
276
|
+
frameData[trail].fix = last.fix;
|
|
277
|
+
trail--;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
// The pure pipeline: samples in, per-frame telemetry and track stats out.
|
|
281
|
+
export function buildTelemetry(loaded, timing) {
|
|
282
|
+
const { samples, source, method, noLock } = loaded;
|
|
283
|
+
const fixes = fixRefs(samples);
|
|
284
|
+
if (fixes.length < 2)
|
|
285
|
+
throw new Error('telemetry has fewer than 2 GPS fixes');
|
|
286
|
+
const { bbox, trackDistanceM } = computeTrackStats(fixes);
|
|
287
|
+
const speedBySample = computeSpeedBySample(samples.length, fixes);
|
|
288
|
+
const { headingBySample, headingMode } = computeHeadingBySample(samples, fixes, speedBySample);
|
|
289
|
+
const frameData = buildFrameData(samples, timing.frames, timing.fpsValue, speedBySample, headingBySample);
|
|
290
|
+
bridgeMissingFramePositions(frameData);
|
|
291
|
+
return {
|
|
292
|
+
source,
|
|
293
|
+
method,
|
|
294
|
+
headingMode,
|
|
295
|
+
sampleCount: samples.length,
|
|
296
|
+
fixCount: fixes.length,
|
|
297
|
+
noLock,
|
|
298
|
+
frames: frameData,
|
|
299
|
+
bbox,
|
|
300
|
+
trackDistanceM,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// The telemetry I/O shell: discovers and parses a recording's telemetry
|
|
2
|
+
// sources (.SRT sidecar, embedded CAM meta) and hands the samples to the pure
|
|
3
|
+
// pipeline in src/telemetry-math.ts. The math is reachable without files so
|
|
4
|
+
// unit tests can drive it with in-memory samples.
|
|
5
|
+
import { parseSrt } from './srt.js';
|
|
6
|
+
import { parseCamMeta } from './cammeta.js';
|
|
7
|
+
import { findSrtSidecar } from './inputs.js';
|
|
8
|
+
import { buildTelemetry } from './telemetry-math.js';
|
|
9
|
+
// The .SRT sidecar takes precedence over the embedded CAM-meta stream.
|
|
10
|
+
async function loadSamples(tools, videoPath, durationSec) {
|
|
11
|
+
const srtPath = findSrtSidecar(videoPath);
|
|
12
|
+
if (srtPath) {
|
|
13
|
+
const parsed = await parseSrt(srtPath);
|
|
14
|
+
if (parsed.count === 0)
|
|
15
|
+
throw new Error(`SRT sidecar has no cues: ${srtPath}`);
|
|
16
|
+
return {
|
|
17
|
+
samples: parsed.cues.map((cue) => ({
|
|
18
|
+
tSec: cue.tSec,
|
|
19
|
+
fix: cue.fix,
|
|
20
|
+
relAlt: cue.relAlt,
|
|
21
|
+
absAlt: cue.absAlt,
|
|
22
|
+
yawDeg: null,
|
|
23
|
+
})),
|
|
24
|
+
source: 'srt',
|
|
25
|
+
method: 'srt-cues',
|
|
26
|
+
noLock: parsed.noLock,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const cam = await parseCamMeta(tools, videoPath, durationSec);
|
|
30
|
+
if (!cam || cam.samples.length === 0) {
|
|
31
|
+
throw new Error('no telemetry found: no .SRT sidecar and no GPS pairs in the CAM meta stream');
|
|
32
|
+
}
|
|
33
|
+
return { samples: cam.samples, source: 'cammeta', method: cam.method, noLock: cam.noLock };
|
|
34
|
+
}
|
|
35
|
+
export async function loadTelemetry(videoPath, { frames, fpsValue, durationSec, tools, }) {
|
|
36
|
+
const loaded = await loadSamples(tools, videoPath, durationSec);
|
|
37
|
+
return buildTelemetry(loaded, { frames, fpsValue });
|
|
38
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The one tile cache layout and tile URL parsing, shared by the prefetcher,
|
|
2
|
+
// the render server and the app server so they can never disagree about
|
|
3
|
+
// where a tile lives or which URLs are tiles at all.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { TILE_SOURCES } from './renderer/tilesources.js';
|
|
6
|
+
function cacheKeyFor(style) {
|
|
7
|
+
return TILE_SOURCES[style].cacheKey;
|
|
8
|
+
}
|
|
9
|
+
export function parseTilePathname(pathname) {
|
|
10
|
+
const m = /^\/tiles\/([a-z0-9_-]+)\/(\d+)\/(\d+)\/(\d+)\.png$/.exec(pathname);
|
|
11
|
+
if (!m)
|
|
12
|
+
return null;
|
|
13
|
+
// The URL regex admits any slug; only vocabulary styles are tiles, so the
|
|
14
|
+
// returned style is never a cast lie the callers must re-check.
|
|
15
|
+
const style = Object.hasOwn(TILE_SOURCES, m[1]) ? m[1] : null;
|
|
16
|
+
return style === null
|
|
17
|
+
? null
|
|
18
|
+
: { style, tile: { z: Number(m[2]), x: Number(m[3]), y: Number(m[4]) } };
|
|
19
|
+
}
|
|
20
|
+
export function tilePaths(cacheDir, style, tile) {
|
|
21
|
+
const dir = path.join(cacheDir, cacheKeyFor(style), String(tile.z), String(tile.x));
|
|
22
|
+
return {
|
|
23
|
+
file: path.join(dir, `${tile.y}.png`),
|
|
24
|
+
placeholder: path.join(dir, `${tile.y}.placeholder.png`),
|
|
25
|
+
};
|
|
26
|
+
}
|
package/dist/tiles.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// The polite tile download policy in one home: every request start - retries
|
|
2
|
+
// included - is spaced REQUEST_INTERVAL_MS apart (2.0 req/s) and at most
|
|
3
|
+
// DOWNLOAD_WORKERS downloads run at once, whichever entry point drives them.
|
|
4
|
+
// createTileTraffic (the app: on-demand tiles and exports on one queue) and
|
|
5
|
+
// prefetchTiles (the CLI's bulk prefetch, its own queue as it runs alone) are
|
|
6
|
+
// thin wrappers whose priorities decide ordering and sharing.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { errorMessage } from './errors.js';
|
|
10
|
+
import { solidPng } from './png.js';
|
|
11
|
+
import { tilePaths } from './tilecache.js';
|
|
12
|
+
import { TILE_SOURCES } from './renderer/tilesources.js';
|
|
13
|
+
import { VERSION } from './version.js';
|
|
14
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
|
+
const USER_AGENT = `drone-path/${VERSION} (flight-path map renderer; https://github.com/MrManny/drone-path)`;
|
|
16
|
+
const DOWNLOAD_ATTEMPTS = 2;
|
|
17
|
+
const DOWNLOAD_WORKERS = 2;
|
|
18
|
+
const REQUEST_INTERVAL_MS = 500;
|
|
19
|
+
const RETRY_DELAY_MS = 500;
|
|
20
|
+
const FETCH_TIMEOUT_MS = 20000;
|
|
21
|
+
function createRequestGate() {
|
|
22
|
+
// Waiters release in arrival order - the queue's priorities decide who
|
|
23
|
+
// acquires first - and the stamp lands at the actual release with every
|
|
24
|
+
// turn re-checking after sleeping: a late event-loop wake can never
|
|
25
|
+
// squeeze the next start inside the previous release's interval.
|
|
26
|
+
let nextFreeAt = 0;
|
|
27
|
+
let tail = Promise.resolve();
|
|
28
|
+
return () => {
|
|
29
|
+
const turn = tail.then(async () => {
|
|
30
|
+
for (;;) {
|
|
31
|
+
const now = Date.now();
|
|
32
|
+
if (now >= nextFreeAt) {
|
|
33
|
+
nextFreeAt = now + REQUEST_INTERVAL_MS;
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
await sleep(nextFreeAt - now);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
tail = turn.catch(() => { });
|
|
40
|
+
return turn;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function tileUrl(style, tile) {
|
|
44
|
+
const source = TILE_SOURCES[style];
|
|
45
|
+
const subdomain = source.subdomains.length
|
|
46
|
+
? source.subdomains[(tile.x + tile.y) % source.subdomains.length]
|
|
47
|
+
: '';
|
|
48
|
+
return source.url
|
|
49
|
+
.replace('{s}', subdomain)
|
|
50
|
+
.replace('{z}', String(tile.z))
|
|
51
|
+
.replace('{x}', String(tile.x))
|
|
52
|
+
.replace('{y}', String(tile.y));
|
|
53
|
+
}
|
|
54
|
+
// A canceled download is not a failed one: no placeholder is written and the
|
|
55
|
+
// tile stays uncached, so a later request may fetch the real tile.
|
|
56
|
+
function canceledError(signal) {
|
|
57
|
+
return new Error('tile download canceled', { cause: signal.reason });
|
|
58
|
+
}
|
|
59
|
+
// The network half of one tile: its body after a successful attempt, null
|
|
60
|
+
// when the attempts run out. The download retry is for network problems
|
|
61
|
+
// only; cache writes live in writeCacheFile and fail fast.
|
|
62
|
+
async function downloadTile(url, acquire, signal) {
|
|
63
|
+
for (let attempt = 0; attempt < DOWNLOAD_ATTEMPTS; attempt++) {
|
|
64
|
+
await acquire();
|
|
65
|
+
try {
|
|
66
|
+
const res = await fetch(url, {
|
|
67
|
+
headers: { 'User-Agent': USER_AGENT },
|
|
68
|
+
signal: signal
|
|
69
|
+
? AbortSignal.any([AbortSignal.timeout(FETCH_TIMEOUT_MS), signal])
|
|
70
|
+
: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
71
|
+
});
|
|
72
|
+
if (res.ok)
|
|
73
|
+
return Buffer.from(await res.arrayBuffer());
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
if (signal?.aborted)
|
|
77
|
+
throw canceledError(signal);
|
|
78
|
+
await sleep(RETRY_DELAY_MS);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
// An fs failure while writing the cache is the cache's fault, not the
|
|
84
|
+
// network's: it fails the tile's job instead of being retried as a download,
|
|
85
|
+
// and names the cache so the log and Open errors read it as a cache failure.
|
|
86
|
+
function writeCacheFile(cachePath, data) {
|
|
87
|
+
try {
|
|
88
|
+
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
|
|
89
|
+
fs.writeFileSync(cachePath, data);
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
throw new Error(`cache write failed: ${cachePath}: ${errorMessage(e)}`, { cause: e });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// Placeholder PNGs are pure derivations of the tile source's background
|
|
96
|
+
// color; memoizing per downloader keeps repeat failures cheap without any
|
|
97
|
+
// module-level mutable state.
|
|
98
|
+
function createPlaceholderSource() {
|
|
99
|
+
const cache = new Map();
|
|
100
|
+
return (style) => {
|
|
101
|
+
let png = cache.get(style);
|
|
102
|
+
if (!png) {
|
|
103
|
+
png = solidPng(TILE_SOURCES[style].placeholderBg);
|
|
104
|
+
cache.set(style, png);
|
|
105
|
+
}
|
|
106
|
+
return png;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
// The full cache dance for one tile: hit, download, or placeholder. The
|
|
110
|
+
// placeholder is served as a fallback so a missing tile is retried on a later
|
|
111
|
+
// run instead of being cached as missing.
|
|
112
|
+
async function fetchTileToCache(ctx, style, tile, signal) {
|
|
113
|
+
const paths = tilePaths(ctx.cacheDir, style, tile);
|
|
114
|
+
if (fs.existsSync(paths.file))
|
|
115
|
+
return { file: paths.file, status: 'cached' };
|
|
116
|
+
const body = await downloadTile(tileUrl(style, tile), ctx.acquire, signal);
|
|
117
|
+
if (body) {
|
|
118
|
+
writeCacheFile(paths.file, body);
|
|
119
|
+
return { file: paths.file, status: 'downloaded' };
|
|
120
|
+
}
|
|
121
|
+
writeCacheFile(paths.placeholder, ctx.placeholderPng(style));
|
|
122
|
+
return { file: paths.placeholder, status: 'failed' };
|
|
123
|
+
}
|
|
124
|
+
function createDownloader(cacheDir, placeholderPng) {
|
|
125
|
+
const ctx = { cacheDir, acquire: createRequestGate(), placeholderPng };
|
|
126
|
+
const inFlight = new Map();
|
|
127
|
+
const queue = [];
|
|
128
|
+
let active = 0;
|
|
129
|
+
function pump() {
|
|
130
|
+
while (active < DOWNLOAD_WORKERS) {
|
|
131
|
+
const job = queue.shift();
|
|
132
|
+
if (!job)
|
|
133
|
+
break;
|
|
134
|
+
if (job.signal?.aborted) {
|
|
135
|
+
job.detach();
|
|
136
|
+
job.fail(canceledError(job.signal));
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
active++;
|
|
140
|
+
void (async () => {
|
|
141
|
+
try {
|
|
142
|
+
job.settle(await fetchTileToCache(ctx, job.style, job.tile, job.signal));
|
|
143
|
+
}
|
|
144
|
+
catch (e) {
|
|
145
|
+
job.fail(e);
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
job.detach();
|
|
149
|
+
active--;
|
|
150
|
+
pump();
|
|
151
|
+
}
|
|
152
|
+
})();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
enqueue(style, tile, options = {}) {
|
|
157
|
+
const priority = options.priority ?? 'background';
|
|
158
|
+
const key = `${priority}:${tilePaths(cacheDir, style, tile).file}`;
|
|
159
|
+
// A canceled stream's downloads must never be handed to the next one:
|
|
160
|
+
// sharing follows the abort signal of the download it joins.
|
|
161
|
+
const shared = inFlight.get(key);
|
|
162
|
+
if (shared && shared.signal === options.signal)
|
|
163
|
+
return shared.promise;
|
|
164
|
+
const task = new Promise((resolve, reject) => {
|
|
165
|
+
const job = {
|
|
166
|
+
style,
|
|
167
|
+
tile,
|
|
168
|
+
signal: options.signal,
|
|
169
|
+
settle: resolve,
|
|
170
|
+
fail: reject,
|
|
171
|
+
detach: () => { },
|
|
172
|
+
};
|
|
173
|
+
const signal = options.signal;
|
|
174
|
+
if (signal) {
|
|
175
|
+
const onAbort = () => {
|
|
176
|
+
const at = queue.indexOf(job);
|
|
177
|
+
if (at < 0)
|
|
178
|
+
return;
|
|
179
|
+
queue.splice(at, 1);
|
|
180
|
+
job.detach();
|
|
181
|
+
reject(canceledError(signal));
|
|
182
|
+
};
|
|
183
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
184
|
+
job.detach = () => signal.removeEventListener('abort', onAbort);
|
|
185
|
+
}
|
|
186
|
+
if (priority === 'now')
|
|
187
|
+
queue.unshift(job);
|
|
188
|
+
else
|
|
189
|
+
queue.push(job);
|
|
190
|
+
pump();
|
|
191
|
+
});
|
|
192
|
+
const entry = { promise: task, signal: options.signal };
|
|
193
|
+
const clear = () => {
|
|
194
|
+
if (inFlight.get(key) === entry)
|
|
195
|
+
inFlight.delete(key);
|
|
196
|
+
};
|
|
197
|
+
void task.then(clear, clear);
|
|
198
|
+
inFlight.set(key, entry);
|
|
199
|
+
return task;
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
// The app's tile traffic on one polite queue: on-demand tiles jump ahead of
|
|
204
|
+
// the queued prefetch, and both stay inside the same 2.0 req/s budget.
|
|
205
|
+
export function createTileTraffic(cacheDir) {
|
|
206
|
+
const downloader = createDownloader(cacheDir, createPlaceholderSource());
|
|
207
|
+
return {
|
|
208
|
+
ensure(style, tile) {
|
|
209
|
+
return downloader.enqueue(style, tile, { priority: 'now' }).then((result) => result.file);
|
|
210
|
+
},
|
|
211
|
+
stream(options) {
|
|
212
|
+
const { style, tiles, log = () => { }, onTile = () => { }, signal } = options;
|
|
213
|
+
const missing = [];
|
|
214
|
+
for (const tile of tiles) {
|
|
215
|
+
if (fs.existsSync(tilePaths(cacheDir, style, tile).file))
|
|
216
|
+
onTile('cached');
|
|
217
|
+
else
|
|
218
|
+
missing.push(tile);
|
|
219
|
+
}
|
|
220
|
+
if (missing.length === 0) {
|
|
221
|
+
return Promise.resolve({ downloaded: 0, failed: 0, total: tiles.length });
|
|
222
|
+
}
|
|
223
|
+
log(`tiles: ${tiles.length} needed, ${missing.length} to download (${style})`);
|
|
224
|
+
let downloaded = 0;
|
|
225
|
+
let failed = 0;
|
|
226
|
+
return Promise.all(missing.map((tile) => downloader.enqueue(style, tile, { priority: 'background', signal }).then((result) => {
|
|
227
|
+
if (result.status === 'downloaded')
|
|
228
|
+
downloaded++;
|
|
229
|
+
else if (result.status === 'failed')
|
|
230
|
+
failed++;
|
|
231
|
+
onTile(result.status);
|
|
232
|
+
}))).then(() => ({ downloaded, failed, total: tiles.length }));
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
// Polite bulk fetching for the pipeline: 2 concurrent workers, 2.0 req/s. It
|
|
237
|
+
// settles once per tile (cached, downloaded or failed) through onTile and
|
|
238
|
+
// rejects with 'tile download canceled' when a signal aborts it.
|
|
239
|
+
export function prefetchTiles(options) {
|
|
240
|
+
return createTileTraffic(options.cacheDir).stream(options);
|
|
241
|
+
}
|