Merge main and switch Cesium and Navara in place through Vue

Preserve the camera, map source and layer selection across engine sessions. Restore the previous engine if startup fails and retain local history navigation.
This commit is contained in:
German Khokhlov committed 2026-11-02 13:10:36 +04:00
commit b8f4d097c4
1691 files changed
+225876 -41594

No files matched your search

@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApplicationRequestServices } from './requests.js';
test('unknown capability replies recover after backoff', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 100_000 });
for (const first of [
() => Response.json({ wrong: true }),
() => new Response('bad', { status: 503 }),
]) {
let probes = 0;
let queries = 0;
const services = createApplicationRequestServices({
boundaryProbe: { timeoutMs: 1000, retryMs: 1000 },
fetchImpl: async (url) => {
if (url.endsWith('/status'))
return ++probes === 1
? first()
: Response.json({ configured: false });
queries++;
return Response.json({ elements: [] });
},
});
assert.deepEqual(await services.boundaries.query('fixture'), []);
assert.deepEqual(await services.boundaries.query('fixture'), []);
assert.equal(probes, 1, 'unknown reply is not re-probed inside backoff');
t.mock.timers.tick(1000);
assert.equal(
(await services.boundaries.query('fixture')).code,
'OVERPASS_NOT_CONFIGURED',
);
assert.equal(
(await services.boundaries.query('fixture')).code,
'OVERPASS_NOT_CONFIGURED',
);
assert.equal(probes, 2);
assert.equal(queries, 2);
}
});
+18 -11
View File
@@ -204,12 +204,16 @@ export function createGroundFloor({ terrain, signal }) {
* @returns {{lat: number, lon: number}} The cell to read.
*/
function stickyFloorCell(lat, lon, previousCell) {
if (
previousCell &&
Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG &&
Math.abs(lon - previousCell.lon) <= 0.0005 + CELL_HYSTERESIS_DEG
) {
return previousCell;
if (previousCell) {
// The short way round, so a contact on the 180° seam keeps its cell.
let dLon = lon - previousCell.lon;
dLon -= 360 * Math.round(dLon / 360);
if (
Math.abs(lat - previousCell.lat) <= 0.0005 + CELL_HYSTERESIS_DEG &&
Math.abs(dLon) <= 0.0005 + CELL_HYSTERESIS_DEG
) {
return previousCell;
}
}
return coarseFloorCoord(lat, lon);
}
@@ -269,17 +273,20 @@ export function createGroundFloor({ terrain, signal }) {
const a = points[s];
const b = points[s + 1];
if (![a?.lat, a?.lon, b?.lat, b?.lon].every(Number.isFinite)) continue;
// The short way round, so a segment across 180° walks across it.
let dLon = b.lon - a.lon;
dLon -= 360 * Math.round(dLon / 360);
const steps = Math.ceil(
Math.max(Math.abs(b.lat - a.lat), Math.abs(b.lon - a.lon)) /
Math.max(Math.abs(b.lat - a.lat), Math.abs(dLon)) /
CORRIDOR_WALK_STEP_DEG,
);
for (let i = 1; i <= steps; i++) {
if (out.length >= prefixLimit) break walk;
const t = i / steps;
const cell = coarseFloorCoord(
a.lat + (b.lat - a.lat) * t,
a.lon + (b.lon - a.lon) * t,
);
let lon = a.lon + dLon * t;
if (lon > 180) lon -= 360;
else if (lon < -180) lon += 360;
const cell = coarseFloorCoord(a.lat + (b.lat - a.lat) * t, lon);
const key = `${cell.lat},${cell.lon}`;
if (seen.has(key) || key === destKey) continue;
seen.add(key);
+12 -2
View File
@@ -304,10 +304,20 @@ export function createGroundSnap({ groundFloor }) {
}
const now = Date.now();
const entry = entries.get(icao);
if (entry && now < entry.nextRetryMs) return heldSnapM(entry, surfacePos); // backoff in force
// Backoff in force, unless it ends further off than any backoff can:
// a retry stamped before the clock stepped back would otherwise wait for
// the clock to catch up.
if (
entry &&
now < entry.nextRetryMs &&
entry.nextRetryMs - now <= RETRY_MAX_MS
)
return heldSnapM(entry, surfacePos);
// Per-window budget: deny WITHOUT a retry stamp so the overflow simply
// tries again next tick instead of waiting out a backoff it didn't earn.
if (now - windowStartMs > SAMPLE_WINDOW_MS) {
// A clock that stepped back also opens a new window, or none would open
// until it caught up.
if (now < windowStartMs || now - windowStartMs > SAMPLE_WINDOW_MS) {
windowStartMs = now;
windowCount = 0;
}
+46
View File
@@ -82,3 +82,49 @@ test('a coarse tile answer or only terrain is a miss; a viewer reaches its engin
}
assert.equal(snap.heightFor({}, 'd4', KAUS), null, 'no engine: no sample');
});
const atDenverAirport = geo.cartesian3.fromDegrees(-104.6737, 39.8561, 0);
function timedEngine() {
const engine = createFakeEngine();
engine.fake.script('sampleHeight', () => 1650);
return engine;
}
test('a clock that steps back opens a new sample window instead of denying samples until it catches up', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
const viewer = timedEngine();
const snap = createGroundSnap({ groundFloor: groundFloor() });
const icaos = ['a00001', 'a00002', 'a00003', 'a00004', 'a00005', 'a00006'];
for (const icao of icaos) snap.heightFor(viewer, icao, atDenverAirport);
assert.equal(
viewer.fake.callsOf('surface.sampleHeightDetailed').length,
4,
'four samples per 250 ms window',
);
t.mock.timers.setTime(1_000_000 - 60_000);
for (const icao of icaos) snap.heightFor(viewer, icao, atDenverAirport);
assert.equal(
viewer.fake.callsOf('surface.sampleHeightDetailed').length,
6,
'the two denied aircraft sample in the new window',
);
});
test('a retry backoff stamped before the clock stepped back does not wait for it to catch up', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 10_000_000 });
const viewer = timedEngine();
const snap = createGroundSnap({ groundFloor: groundFloor() });
// Tiles still streaming: a miss, backed off for 2 s.
viewer.fake.script('tilesLoaded', false);
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
viewer.fake.script('tilesLoaded', true);
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
assert.equal(
viewer.fake.callsOf('surface.sampleHeightDetailed').length,
0,
'the backoff holds',
);
// The clock steps back an hour: the stamp is an hour off, past any backoff.
t.mock.timers.setTime(10_000_000 - 3_600_000);
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650);
assert.equal(viewer.fake.callsOf('surface.sampleHeightDetailed').length, 1);
});
+3 -1
View File
@@ -12,6 +12,7 @@ import { acceptedSurfaceHeight } from '../globe/surfaceDetail.js';
* only leaves the DEM prior in place. Cesium does not size its answers, so
* its gates are the camera height and tilesLoaded below. */
export const MAX_FLOOR_TILE_SIZE_M = 1000;
import { approxDistanceKm } from '../data/approxDistance.js';
/** Construct an instance-owned meshFloorSampler service with explicit dependencies. */
export function createMeshFloorSampler({
@@ -127,7 +128,8 @@ export function createMeshFloorSampler({
if (
Number.isFinite(viewerLat) &&
Number.isFinite(viewerLon) &&
_approxKm(viewerLat, viewerLon, cell.lat, cell.lon) > MAX_SAMPLE_DIST_KM
approxDistanceKm(viewerLat, viewerLon, cell.lat, cell.lon) >
MAX_SAMPLE_DIST_KM
) {
continue; // too far: tiles not streamed there, probe would be a guaranteed miss
}
+27 -6
View File
@@ -66,11 +66,12 @@ export function createApplicationRequestServices({
throw new Error(`${label} unavailable (${response.status})`);
return response.data;
}
// Learn once per page whether the server has an Overpass instance, so an
// Remember valid capability decisions for the page, so an
// unconfigured server is never asked (and never answers with an error).
// Discovery is bounded; a failed or timed-out probe is forgotten and not
// Discovery is bounded; failed, malformed or timed-out probes are forgotten and not
// retried for a short backoff, during which queries go to the server as
// they would against an older server without the probe.
let summaryCapability = null;
let boundaryCapability = null;
let boundaryProbeRetryAt = 0;
function boundariesConfigured() {
@@ -79,10 +80,13 @@ export function createApplicationRequestServices({
boundaryCapability = request(`${urls.boundaries}/status`, {
signal: AbortSignal.timeout(boundaryProbe.timeoutMs),
}).then(
(response) =>
response.ok && typeof response.data?.configured === 'boolean'
? response.data.configured
: null, // an older server: fall back to asking per query
(response) => {
if (response.ok && typeof response.data?.configured === 'boolean')
return response.data.configured;
boundaryCapability = null;
boundaryProbeRetryAt = Date.now() + boundaryProbe.retryMs;
return null; // capability unknown: let this query ask the server
},
(error) => {
boundaryCapability = null;
if (lifetime?.aborted) throw error;
@@ -172,6 +176,23 @@ export function createApplicationRequestServices({
},
},
summary: {
// The capability probe, asked once per page: true or false from a
// server that answers it, null (unknown) from one that does not.
configured() {
summaryCapability ??= request(`${urls.summary}/status`, {
signal: AbortSignal.timeout(3000),
}).then(
(response) =>
response.ok && typeof response.data?.configured === 'boolean'
? response.data.configured
: null,
(error) => {
if (lifetime?.aborted) throw error;
return null;
},
);
return summaryCapability;
},
async summarize(context, { signal } = {}) {
return request(urls.summary, {
method: 'POST',
+21
View File
@@ -94,3 +94,24 @@ test('a failed probe is retried after its backoff, not on every query', async ()
'GET /api/overpass/status',
]);
});
test('the summary capability probe is asked once and unknown when unanswered', async () => {
for (const [answer, expected] of [
[() => Response.json({ configured: false }), false],
[() => Response.json({ configured: true }), true],
[() => new Response('missing', { status: 404 }), null],
[() => Response.json({ configured: 'yes' }), null],
[() => { throw new TypeError('offline'); }, null],
]) {
const seen = [];
const services = createApplicationRequestServices({
fetchImpl: async (url, init) => {
seen.push(`${init.method || 'GET'} ${url}`);
return answer();
},
});
assert.equal(await services.summary.configured(), expected);
assert.equal(await services.summary.configured(), expected);
assert.deepEqual(seen, ['GET /api/openai/hud-summary/status']);
}
});
+10 -12
View File
@@ -272,28 +272,26 @@ export function createTerrainHeights({
const uncached = [];
const seenKeys = new Set();
const now = Date.now();
// What this call resolved or found warm, so the assembly below can report a
// point even if a later chunk's writes pushed it past CACHE_MAX_ENTRIES.
// Without it a batch big enough to evict its own entries would report
// points as unresolved that it had in fact resolved.
const resolvedThisCall = new Map();
for (const item of work) {
const entry = cache.get(item.key);
const entry = cacheTouch(item.key);
const fallbackCooling =
entry?.source === 'geoid-fallback' &&
Number.isFinite(entry.retryAt) &&
now < entry.retryAt;
if (
(entry && entry.source === 'reearth') ||
fallbackCooling ||
seenKeys.has(item.key)
)
if ((entry && entry.source === 'reearth') || fallbackCooling) {
resolvedThisCall.set(item.key, entry);
continue;
}
if (seenKeys.has(item.key)) continue;
seenKeys.add(item.key);
uncached.push(item);
}
// What this call resolved, so the assembly below can report a point even
// if a later chunk's writes pushed it past CACHE_MAX_ENTRIES. Without it a
// batch big enough to evict its own earlier chunks would report points as
// unresolved that it had in fact just resolved.
const resolvedThisCall = new Map();
// Resolve the network path in sequential <=CHUNK_SIZE chunks. Each chunk's
// failure is isolated to that chunk's points (geoid fallback), so a single
// bad chunk doesn't lose results for the rest of a large batch.
+41
View File
@@ -114,6 +114,47 @@ test('a batch larger than the cache bound still reports every point it resolved'
assert.equal(warm.length, 4);
});
test('warm batch consumers retain their terrain cells ahead of unused cells', async () => {
let calls = 0;
const terrain = createTerrainHeights({
maxCacheEntries: 2,
source: {
async getHeights(points) {
calls++;
return points.map((p) => ({ ellipsoid: 100 + p.lon }));
},
},
});
const p = (lon) => ({ lat: 0, lon });
await terrain.resolveEllipsoidalGround([p(1)]);
await terrain.resolveEllipsoidalGround([p(2)]);
await terrain.resolveEllipsoidalGround([p(1)]);
assert.equal(calls, 2);
await terrain.resolveEllipsoidalGround([p(3)]);
assert.equal(terrain.cachedEllipsoidalGround(0, 1), 101);
assert.equal(terrain.cachedEllipsoidalGround(0, 2), null);
assert.equal(calls, 3);
});
test('a batch still reports its warm points after its own fetches evict them', async () => {
const terrain = createTerrainHeights({
source: stubSource(),
maxCacheEntries: 2,
});
await terrain.resolveEllipsoidalGround([pointAt(0)]);
const results = await terrain.resolveEllipsoidalGround([
pointAt(0),
pointAt(1),
pointAt(2),
]);
results.forEach((result, i) => {
assert.equal(result.source, 'reearth', `point ${i} reported resolved`);
assert.equal(result.ellipsoid, heightAt(lonAt(i)));
});
});
test('an out-of-range cache bound falls back to the default instead of disabling the cache', async () => {
for (const maxCacheEntries of [0, -1, Number.NaN, undefined]) {
const terrain = createTerrainHeights({