mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main through #1641 into the renderer seam
Takes main's per-point mesh floor readings (#1642) onto the seam's port-based sampler: a spot refused only while the cell's DEM prior was cold is probed again, each spot is recorded once, a cell keeps at most sixteen readings, and grounded flights read the floor at the contact held inside its sticky cell.
This commit is contained in:
commit
077576ed99
79 files changed
+2721
-230
No files matched your search
Vendored
+37
-4
@@ -1,5 +1,6 @@
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { STATUS_POLL_MS } from './policy.js';
|
||||
import { ACTIVATION_ENTER_ALTITUDE_M, STATUS_POLL_MS } from './policy.js';
|
||||
import { GBFS_CITY_REGISTRY } from './registry.js';
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
const methods = {
|
||||
@@ -13,6 +14,14 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
updateInterval: STATUS_POLL_MS,
|
||||
|
||||
/**
|
||||
* Kept so camera moves can repaint the row before the next status poll.
|
||||
* @param {object} dataManager DataLayerManager instance.
|
||||
*/
|
||||
attachDataManager(dataManager) {
|
||||
layerState._dataManager = dataManager;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a sampled array of detectable station objects for HUD overlay rendering.
|
||||
* @param {Object} [options] - Sampling options (maxCount, seed).
|
||||
@@ -57,15 +66,39 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Return current layer statistics for the UI status display.
|
||||
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean }}
|
||||
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean, status?: string, statusMessage?: string }}
|
||||
*/
|
||||
getStats() {
|
||||
// A city in range without points is loading even before its fetch
|
||||
// starts: the row repaints on entry, ahead of beginLoading().
|
||||
const loading =
|
||||
layerState._loading ||
|
||||
[...layerState._activeCityIds].some(
|
||||
(cityId) =>
|
||||
!layerState._cityRuntime.has(cityId) &&
|
||||
!layerState._failedCityIds.has(cityId),
|
||||
);
|
||||
const stats = {
|
||||
count: layerState._count,
|
||||
lastUpdate: layerState._lastUpdate,
|
||||
loading: layerState._loading,
|
||||
loading,
|
||||
};
|
||||
if (layerState._loading) {
|
||||
// No system in range: the camera is too high or no system is near. A
|
||||
// failed city also leaves range empty and reports its failure below.
|
||||
if (
|
||||
layerState._enabled &&
|
||||
!loading &&
|
||||
layerState._activeCityIds.size === 0 &&
|
||||
layerState._failedCityIds.size === 0
|
||||
) {
|
||||
// English: the analyst's empty note and the row's prompt, both shown
|
||||
// through translateStatusMessage (ui/statusText.js).
|
||||
const note = layerState._altitudeGateEnabled
|
||||
? `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`
|
||||
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered city`;
|
||||
return { ...stats, status: 'zoom-in', statusMessage: note };
|
||||
}
|
||||
if (loading) {
|
||||
stats.loadingLabel =
|
||||
layerState._activeCityIds.size > 0
|
||||
? t('syncing {count} city feeds...', {
|
||||
|
||||
@@ -146,6 +146,7 @@ export function createLifecycle({
|
||||
detachCamera();
|
||||
parts.ingestion.abortAllInFlight();
|
||||
parts.rendering.detachSets();
|
||||
layerState._dataManager = null;
|
||||
layerState._viewer = null;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
// Bike Share's Layers row. With no system in range it says why instead of
|
||||
// "never" and keeps no date for data it no longer draws. After the camera
|
||||
// settles, the last row the panel painted must match what the layer reports
|
||||
// now. Each case drives the real viewport,
|
||||
// ingestion, rendering and controls; the manager is a spy that records the
|
||||
// row text (LayerPanel._buildMetaText) at every refreshLayerStats() call.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CITY_BY_ID, GBFS_CITY_REGISTRY } from './registry.js';
|
||||
import { createState } from './state.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createViewport } from './viewport.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
const BOSTON_ID = 'boston-bluebikes';
|
||||
const TORONTO_ID = 'toronto-bike-share';
|
||||
const BUFFALO_ID = 'buffalo-reddy';
|
||||
const LONDON = { lat: 51.5072, lon: -0.1276 };
|
||||
const BOSTON = { lat: 42.3601, lon: -71.0589 };
|
||||
const BOSTON_NUDGED = { lat: 42.37, lon: -71.05 };
|
||||
const BETWEEN = { lat: 43.25, lon: -79.1 };
|
||||
const TORONTO_ONLY = { lat: 43.7, lon: -79.6 };
|
||||
const LOW_M = 10_000;
|
||||
|
||||
globalThis.document ??= {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function makeSource() {
|
||||
const cityOf = (url) => {
|
||||
for (const [id, city] of CITY_BY_ID) {
|
||||
if (url === city.stationInformationUrl) return { id, kind: 'info' };
|
||||
if (url === city.stationStatusUrl) return { id, kind: 'status' };
|
||||
}
|
||||
throw new Error(`unexpected GBFS url ${url}`);
|
||||
};
|
||||
const source = {
|
||||
dead: new Set(),
|
||||
/** `${cityId}:${kind}` → deferred that gates the answer. */
|
||||
gates: new Map(),
|
||||
async getStations(url, { signal } = {}) {
|
||||
const { id, kind } = cityOf(url);
|
||||
const gate = source.gates.get(`${id}:${kind}`);
|
||||
if (gate) {
|
||||
await new Promise((resolve, reject) => {
|
||||
gate.promise.then(resolve);
|
||||
signal?.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
);
|
||||
});
|
||||
} else {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
if (source.dead.has(id)) throw new Error('GBFS HTTP 503');
|
||||
const city = CITY_BY_ID.get(id);
|
||||
if (kind === 'info') {
|
||||
return {
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: `${id}-1`,
|
||||
name: `${id} dock`,
|
||||
lat: city.centerLat,
|
||||
lon: city.centerLon,
|
||||
capacity: 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
stations: [
|
||||
{
|
||||
station_id: `${id}-1`,
|
||||
num_bikes_available: 3,
|
||||
num_docks_available: 7,
|
||||
is_installed: true,
|
||||
is_renting: true,
|
||||
is_returning: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return source;
|
||||
}
|
||||
|
||||
/** The row as the panel draws it: state chip, count, meta text. */
|
||||
const rowText = (raw) => {
|
||||
const stats = {
|
||||
count: 0,
|
||||
lastUpdate: null,
|
||||
...raw,
|
||||
loading: raw.loading === true,
|
||||
};
|
||||
const meta = LayerPanel.prototype._buildMetaText({
|
||||
id: 'bikeshare',
|
||||
source: 'GBFS',
|
||||
enabled: true,
|
||||
lifecycleState: 'enabled',
|
||||
stats,
|
||||
});
|
||||
return `${layerFeedState(stats)} | ${stats.count || '—'} | ${meta}`;
|
||||
};
|
||||
|
||||
function makeLiveLayer() {
|
||||
const source = makeSource();
|
||||
const services = {
|
||||
render: { governorRequestRender() {} },
|
||||
overlays: {
|
||||
setOverlayEntries() {},
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource() {},
|
||||
},
|
||||
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
|
||||
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
|
||||
};
|
||||
const state = createState({ services });
|
||||
const parts = {};
|
||||
const context = { state, services, parts, source };
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.model = createModel(context);
|
||||
parts.viewport = createViewport(context);
|
||||
parts.rendering = createRendering(context);
|
||||
parts.selection = {
|
||||
_installClickHandler() {},
|
||||
_clearSelection() {},
|
||||
_onKeyDown() {},
|
||||
};
|
||||
parts.queries = { collectDetectableStations: () => [] };
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
const { methods: controls } = createControls(context);
|
||||
|
||||
const camera = { ...LONDON, height: LOW_M };
|
||||
const viewer = {};
|
||||
bindFakeDraw(viewer, {
|
||||
camera: {
|
||||
pose: () => ({ lon: camera.lon, lat: camera.lat, height: camera.height }),
|
||||
viewRectangle: () => null,
|
||||
on: () => () => {},
|
||||
},
|
||||
});
|
||||
parts.lifecycle.methods.init(viewer);
|
||||
|
||||
const painted = [];
|
||||
controls.attachDataManager({
|
||||
refreshLayerStats() {
|
||||
painted.push(rowText(controls.getStats()));
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
state,
|
||||
source,
|
||||
painted,
|
||||
lastPainted: () => painted.at(-1),
|
||||
stats: () => controls.getStats(),
|
||||
live: () => rowText(controls.getStats()),
|
||||
moveTo(place, height = LOW_M) {
|
||||
Object.assign(camera, place, { height });
|
||||
return parts.viewport.runProximityCheck();
|
||||
},
|
||||
async enable() {
|
||||
parts.lifecycle.methods.enable(viewer);
|
||||
await settle();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function settle() {
|
||||
for (let i = 0; i < 5; i += 1)
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
}
|
||||
|
||||
test('entering a city paints the loading row, not "never"', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
const info = deferred();
|
||||
layer.source.gates.set(`${BOSTON_ID}:info`, info);
|
||||
await layer.enable();
|
||||
const before = layer.painted.length;
|
||||
const entering = layer.moveTo(BOSTON);
|
||||
assert.ok(layer.painted.length > before, 'entering repainted');
|
||||
const atEntry = layer.lastPainted();
|
||||
const liveAfter = layer.live();
|
||||
info.resolve();
|
||||
await entering;
|
||||
await settle();
|
||||
assert.match(liveAfter, /syncing 1 city feeds/);
|
||||
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
|
||||
assert.doesNotMatch(atEntry, /never/);
|
||||
});
|
||||
test('re-entering a city with cached station info paints loading', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
await layer.enable();
|
||||
await layer.moveTo(BOSTON);
|
||||
await settle();
|
||||
await layer.moveTo(LONDON);
|
||||
await settle();
|
||||
const status = deferred();
|
||||
layer.source.gates.set(`${BOSTON_ID}:status`, status);
|
||||
const entering = layer.moveTo(BOSTON);
|
||||
const atEntry = layer.lastPainted();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const liveAfter = layer.live();
|
||||
status.resolve();
|
||||
await entering;
|
||||
await settle();
|
||||
assert.match(liveAfter, /syncing 1 city feeds/);
|
||||
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
|
||||
assert.doesNotMatch(atEntry, /never/);
|
||||
});
|
||||
|
||||
test('leaving a city mid-load does not leave the row on LOADING', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
layer.source.gates.set(`${BOSTON_ID}:info`, deferred());
|
||||
await layer.enable();
|
||||
const entering = layer.moveTo(BOSTON);
|
||||
await settle();
|
||||
assert.equal(layer.state._loading, true);
|
||||
|
||||
await layer.moveTo(LONDON);
|
||||
await entering;
|
||||
await settle();
|
||||
assert.equal(layer.state._loading, false);
|
||||
assert.match(layer.live(), /No bike share here yet/);
|
||||
assert.equal(layer.lastPainted(), layer.live());
|
||||
});
|
||||
|
||||
test('a camera nudge during the first load still repaints the drawn stations', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
const status = deferred();
|
||||
layer.source.gates.set(`${BOSTON_ID}:status`, status);
|
||||
await layer.enable();
|
||||
const entering = layer.moveTo(BOSTON);
|
||||
await settle();
|
||||
assert.ok(layer.state._cityRuntime.has(BOSTON_ID), 'points are drawn');
|
||||
|
||||
await layer.moveTo(BOSTON_NUDGED);
|
||||
status.resolve();
|
||||
await entering;
|
||||
await settle();
|
||||
assert.equal(layer.state._count, 1, 'one station on the map');
|
||||
assert.equal(layer.lastPainted(), layer.live());
|
||||
});
|
||||
|
||||
test('leaving a city whose load failed repaints the error away', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
layer.source.dead.add(BOSTON_ID);
|
||||
await layer.enable();
|
||||
await layer.moveTo(BOSTON);
|
||||
await settle();
|
||||
assert.match(layer.lastPainted(), /GBFS fetch error/i);
|
||||
|
||||
await layer.moveTo(LONDON);
|
||||
await settle();
|
||||
assert.match(layer.live(), /No bike share here yet/);
|
||||
assert.equal(layer.lastPainted(), layer.live());
|
||||
});
|
||||
|
||||
test('leaving the failed city of two repaints DEGRADED away', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
layer.source.dead.add(BUFFALO_ID);
|
||||
await layer.enable();
|
||||
await layer.moveTo(BETWEEN);
|
||||
await settle();
|
||||
assert.match(layer.lastPainted(), /^degraded/);
|
||||
|
||||
await layer.moveTo(TORONTO_ONLY);
|
||||
await settle();
|
||||
assert.doesNotMatch(layer.live(), /^degraded/);
|
||||
assert.equal(layer.lastPainted(), layer.live());
|
||||
});
|
||||
|
||||
test('above the altitude gate the row says how low to fly', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
await layer.enable();
|
||||
await layer.moveTo(LONDON, 2_000_000);
|
||||
const stats = layer.stats();
|
||||
assert.equal(stats.status, 'zoom-in');
|
||||
assert.equal(stats.statusMessage, 'Fly below 48 km to a covered city');
|
||||
assert.equal(stats.error, undefined);
|
||||
});
|
||||
|
||||
test('a city with no system says so and counts the ones there are', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
await layer.enable();
|
||||
const stats = layer.stats();
|
||||
assert.equal(stats.status, 'zoom-in');
|
||||
assert.equal(
|
||||
stats.statusMessage,
|
||||
`No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`,
|
||||
);
|
||||
assert.equal(stats.count, 0);
|
||||
});
|
||||
|
||||
test('a city in range, loading, failed or a disabled layer gets no prompt', async () => {
|
||||
const layer = makeLiveLayer();
|
||||
assert.equal(layer.stats().status, undefined, 'disabled');
|
||||
|
||||
const info = deferred();
|
||||
layer.source.gates.set(`${BOSTON_ID}:info`, info);
|
||||
await layer.enable();
|
||||
const entering = layer.moveTo(BOSTON);
|
||||
assert.equal(layer.stats().status, undefined, 'loading');
|
||||
info.resolve();
|
||||
await entering;
|
||||
await settle();
|
||||
assert.equal(layer.stats().status, undefined, 'loaded');
|
||||
|
||||
// Left mid-load: range is empty, but the aborted load still owns the row.
|
||||
const leaving = makeLiveLayer();
|
||||
leaving.source.gates.set(`${BOSTON_ID}:info`, deferred());
|
||||
await leaving.enable();
|
||||
const loading = leaving.moveTo(BOSTON);
|
||||
await settle();
|
||||
const left = leaving.moveTo(LONDON);
|
||||
assert.equal(leaving.state._activeCityIds.size, 0);
|
||||
assert.equal(leaving.stats().loading, true);
|
||||
assert.equal(leaving.stats().status, undefined, 'leaving mid-load');
|
||||
await Promise.all([loading, left]);
|
||||
|
||||
const failed = makeLiveLayer();
|
||||
failed.source.dead.add(BOSTON_ID);
|
||||
await failed.enable();
|
||||
await failed.moveTo(BOSTON);
|
||||
await settle();
|
||||
assert.equal(failed.stats().status, undefined, 'failed');
|
||||
assert.equal(failed.stats().error, 'GBFS fetch error');
|
||||
});
|
||||
|
||||
test('leaving every system behind drops the date of the data it drew', async () => {
|
||||
for (const height of [LOW_M, 2_000_000]) {
|
||||
const layer = makeLiveLayer();
|
||||
await layer.enable();
|
||||
await layer.moveTo(BOSTON);
|
||||
await settle();
|
||||
assert.ok(layer.stats().lastUpdate, 'Boston is dated');
|
||||
|
||||
await layer.moveTo(LONDON, height);
|
||||
assert.equal(layer.stats().lastUpdate, null, `at ${height} m`);
|
||||
}
|
||||
});
|
||||
@@ -19,6 +19,10 @@ export function createState({ services }) {
|
||||
|
||||
layerState._viewer = null;
|
||||
|
||||
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} Manager that repaints the layer's row. */
|
||||
|
||||
layerState._dataManager = null;
|
||||
|
||||
/** Draw set of the station dots (`drawOf(viewer).points`), or null. */
|
||||
|
||||
layerState._stationSet = null;
|
||||
|
||||
@@ -115,6 +115,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
parts.rendering.removeCityPoints(cityId);
|
||||
}
|
||||
|
||||
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
|
||||
function refreshRow() {
|
||||
layerState._dataManager?.refreshLayerStats?.('bikeshare');
|
||||
}
|
||||
|
||||
/** Deactivate all currently active cities and clear the active set. */
|
||||
|
||||
function deactivateAllCities() {
|
||||
@@ -124,6 +129,8 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
// A failure belongs to a city in range; none are once everything is off.
|
||||
layerState._failedCityIds.clear();
|
||||
layerState._count = 0;
|
||||
// Nothing is left on the map to date.
|
||||
layerState._lastUpdate = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -202,9 +209,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
|
||||
const generation = ++layerState._proximityGeneration;
|
||||
const altitude = getCameraAltitude(layerState._viewer);
|
||||
const wasGateEnabled = layerState._altitudeGateEnabled;
|
||||
// Altitude gate: disable all cities when camera is too high
|
||||
if (!shouldActivateAtAltitude(altitude)) {
|
||||
deactivateAllCities();
|
||||
if (wasGateEnabled) refreshRow();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -219,15 +228,25 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
}
|
||||
// A failure never outlives its city's range.
|
||||
let failureCleared = false;
|
||||
for (const cityId of layerState._failedCityIds) {
|
||||
if (!nextActive.has(cityId)) layerState._failedCityIds.delete(cityId);
|
||||
if (!nextActive.has(cityId)) {
|
||||
layerState._failedCityIds.delete(cityId);
|
||||
failureCleared = true;
|
||||
}
|
||||
}
|
||||
|
||||
const changed =
|
||||
!wasGateEnabled ||
|
||||
failureCleared ||
|
||||
nextActive.size !== layerState._activeCityIds.size ||
|
||||
[...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId));
|
||||
layerState._activeCityIds = nextActive;
|
||||
if (layerState._activeCityIds.size === 0) {
|
||||
if (nextActive.size === 0) {
|
||||
layerState._count = 0;
|
||||
return;
|
||||
layerState._lastUpdate = null;
|
||||
}
|
||||
if (changed) refreshRow();
|
||||
|
||||
// Only activate cities that don't already have rendered points
|
||||
const toActivate = [];
|
||||
@@ -239,6 +258,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
await Promise.all(
|
||||
toActivate.map((cityId) => activateCity(cityId, generation)),
|
||||
);
|
||||
// Superseded loads repaint too: a newer check may have painted the row
|
||||
// while this one was still loading, or found nothing to load itself.
|
||||
if (layerState._enabled) refreshRow();
|
||||
}
|
||||
|
||||
/** Schedule a debounced proximity check after camera movement. */
|
||||
|
||||
@@ -394,7 +394,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
// Photoreal regime. Sampling is delegated to the shared coarse-cell
|
||||
// sampler. It remains event-driven, one-shot per cell, and keeps its
|
||||
// sampler. It remains event-driven, a few probes per cell, and keeps its
|
||||
// existing acceptance window; CCTV adds no rooftop rejection policy.
|
||||
if (sampleGround && parts.model.projectionTilesReady()) {
|
||||
record.groundMeshSampleRequestCount =
|
||||
|
||||
@@ -76,6 +76,22 @@ const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
|
||||
/** Where a flights record carries its reported speed and track. */
|
||||
const RECORD_FIELDS = { speed: 'velocity', track: 'true_track' };
|
||||
|
||||
/** Half a coarse floor cell (0.001°), less a margin so rounding keeps a
|
||||
* clamped coordinate inside the cell. */
|
||||
const HALF_CELL_DEG = 0.00049;
|
||||
|
||||
/**
|
||||
* A coordinate held within half a cell of the cell's centre (the short way
|
||||
* round for longitude), so a read lands in the given cell.
|
||||
* @param {number} deg @param {number} centreDeg
|
||||
* @returns {number}
|
||||
*/
|
||||
function clampToCell(deg, centreDeg) {
|
||||
let d = deg - centreDeg;
|
||||
d -= 360 * Math.round(d / 360);
|
||||
return centreDeg + Math.max(-HALF_CELL_DEG, Math.min(HALF_CELL_DEG, d));
|
||||
}
|
||||
|
||||
export function createMotion({
|
||||
flightState,
|
||||
services,
|
||||
@@ -828,12 +844,15 @@ export function createMotion({
|
||||
const carto = toCartographicRadians(pos);
|
||||
// Boundary hysteresis: a position jittering across a cell edge would flip
|
||||
// floors at fleet-tick rate (see stickyFloorCell).
|
||||
const cell = stickyFloorCell(
|
||||
toDegrees(carto.lat),
|
||||
toDegrees(carto.lon),
|
||||
state?.cell,
|
||||
const latDeg = toDegrees(carto.lat);
|
||||
const lonDeg = toDegrees(carto.lon);
|
||||
const cell = stickyFloorCell(latDeg, lonDeg, state?.cell);
|
||||
// A cell holds rendered-surface readings at the points they were taken,
|
||||
// so the floor is read where the contact is, held inside its sticky cell.
|
||||
const floor = cachedGroundFloor(
|
||||
clampToCell(latDeg, cell.lat),
|
||||
clampToCell(lonDeg, cell.lon),
|
||||
);
|
||||
const floor = cachedGroundFloor(cell.lat, cell.lon);
|
||||
const next = state || {
|
||||
cell,
|
||||
in: vec(),
|
||||
|
||||
@@ -233,8 +233,8 @@ export function createFlightSnapshotRenderer({
|
||||
// floor cells collected in the loop (fire-and-forget, single-flight;
|
||||
// read synchronously by NEXT poll's clamp — the military-layer pattern).
|
||||
warmGroundFloor(floorWarmPoints);
|
||||
// Round 4: sample the RENDERED mesh for those same cells (one-shot per
|
||||
// cell, budget-capped, viewer-proximate, google-3d regime only). Own
|
||||
// Round 4: sample the RENDERED mesh for those same cells (a few probes
|
||||
// per cell, budget-capped, viewer-proximate, google-3d regime only). Own
|
||||
// billboards/models are excluded so a vertical probe can't land on an
|
||||
// aircraft instead of the pavement.
|
||||
rendering._sampleMeshFloor(floorWarmPoints, viewerLatDeg, viewerLonDeg);
|
||||
|
||||
@@ -147,8 +147,8 @@ export function createMilitarySnapshotRenderer({
|
||||
// Round 6: re-floor STALE grounded contacts (mirror of flights.js); the
|
||||
// motion part owns the positions it rewrites.
|
||||
motion._refloorStaleGroundedContacts(currentIcaos);
|
||||
// Round 4: sample the RENDERED mesh for those cells (one-shot per cell,
|
||||
// budget-capped, viewer-proximate, google-3d regime only), excluding
|
||||
// Round 4: sample the RENDERED mesh for those cells (a few probes per
|
||||
// cell, budget-capped, viewer-proximate, google-3d regime only), excluding
|
||||
// this layer's own icons/models from the probe.
|
||||
{
|
||||
const pose = findCamera(flightState._viewer)?.pose() ?? null;
|
||||
|
||||
@@ -107,7 +107,14 @@ export function createHeight({ state, services, parts }) {
|
||||
const cells = new Map();
|
||||
const collect = (point, answer) => {
|
||||
if (!onGround) return;
|
||||
if (!cells.has(answer.cell))
|
||||
// A cell keeps the last point offered in it: the path is walked
|
||||
// oldest first, so that is where the vehicle is now or about to be,
|
||||
// and the mesh sampler reads the surface there.
|
||||
const held = cells.get(answer.cell);
|
||||
if (held) {
|
||||
held.lat = point.lat;
|
||||
held.lon = point.lon;
|
||||
} else
|
||||
cells.set(answer.cell, {
|
||||
lat: point.lat,
|
||||
lon: point.lon,
|
||||
@@ -119,6 +126,13 @@ export function createHeight({ state, services, parts }) {
|
||||
const newest = entry.fixes.at(-1);
|
||||
const answer = requestHeight(newest.lat, newest.lon, entry);
|
||||
entry.heightCell = answer.cell;
|
||||
// The selected vehicle's path also offers its history, newest segment
|
||||
// first; the vehicle's own cell is read where its newest fix is.
|
||||
const own = cells.get(answer.cell);
|
||||
if (own) {
|
||||
own.lat = newest.lat;
|
||||
own.lon = newest.lon;
|
||||
}
|
||||
if (answer.height !== null) {
|
||||
entry.heightM = answer.height;
|
||||
entry.heightResolved = true;
|
||||
|
||||
@@ -401,7 +401,13 @@ export function createIngestion({ state, services, parts, source }) {
|
||||
);
|
||||
}
|
||||
if (state._viewer)
|
||||
registerDynamicCredit(state._viewer, transitFeedCredit(feed));
|
||||
registerDynamicCredit(
|
||||
state._viewer,
|
||||
transitFeedCredit(feed, {
|
||||
feedTimestamp: snapshot?.feedTimestamp,
|
||||
fetchedAt,
|
||||
}),
|
||||
);
|
||||
if (
|
||||
state._selectedKey &&
|
||||
state._vehicles.get(state._selectedKey)?.feedId === feed.id
|
||||
|
||||
@@ -3122,6 +3122,118 @@ test('mesh refinement reaches all 100 retained DEM cells within five poll budget
|
||||
assert.equal(probed.size, 100);
|
||||
});
|
||||
|
||||
test('mesh refinement probes the latest point the path offers in a cell', async (t) => {
|
||||
const { createHeight } = await import('./height.js');
|
||||
// Three points along one cell's stretch of path, oldest first.
|
||||
const path = [
|
||||
{ lat: 42.3611, lon: -71.0751 },
|
||||
{ lat: 42.3612, lon: -71.0753 },
|
||||
{ lat: 42.3614, lon: -71.0754 },
|
||||
];
|
||||
const entry = { key: 'train', to: path[0], fixes: [path.at(-1)] };
|
||||
const probed = [];
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_selectedKey: null,
|
||||
_visible: new Set([entry]),
|
||||
_vehicles: new Map([[entry.key, entry]]),
|
||||
_floorCursor: 0,
|
||||
_heightDirty: new Set(),
|
||||
_viewer: {},
|
||||
};
|
||||
const height = createHeight({
|
||||
state,
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
ground: {
|
||||
coarseFloorCoord: (lat, lon) => ({
|
||||
lat: Number(lat.toFixed(3)),
|
||||
lon: Number(lon.toFixed(3)),
|
||||
}),
|
||||
cachedGroundFloor: () => 10,
|
||||
GROUND_FLOOR_LIFT_M: 1.5,
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
trails: {
|
||||
prepareEntry(e, collect) {
|
||||
if (collect)
|
||||
for (const point of path)
|
||||
collect(point, height.requestHeight(point.lat, point.lon));
|
||||
},
|
||||
},
|
||||
rendering: {
|
||||
requestVisibility() {},
|
||||
cameraHeightM: () => 100,
|
||||
globeSurface: () => 'none',
|
||||
sampleMeshFloors(points) {
|
||||
probed.push(...points.map((p) => [p.lat, p.lon]));
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => height.clear());
|
||||
height.anchorFloors();
|
||||
assert.deepEqual(probed, [[42.3614, -71.0754]]);
|
||||
});
|
||||
|
||||
test('the selected vehicle is probed at its newest fix in its own cell', async (t) => {
|
||||
const { createHeight } = await import('./height.js');
|
||||
// The selected path offers its active corridor first, then its history
|
||||
// newest segment first, so the last offer in the cell is an older point.
|
||||
const newest = { lat: 42.3614, lon: -71.0754 };
|
||||
const offers = [
|
||||
newest,
|
||||
{ lat: 42.3612, lon: -71.0753 },
|
||||
{ lat: 42.3611, lon: -71.0751 },
|
||||
];
|
||||
const entry = { key: 'train', to: offers[0], fixes: [newest] };
|
||||
const probed = [];
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_selectedKey: entry.key,
|
||||
_visible: new Set([entry]),
|
||||
_vehicles: new Map([[entry.key, entry]]),
|
||||
_floorCursor: 0,
|
||||
_heightDirty: new Set(),
|
||||
_viewer: {},
|
||||
};
|
||||
const height = createHeight({
|
||||
state,
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
ground: {
|
||||
coarseFloorCoord: (lat, lon) => ({
|
||||
lat: Number(lat.toFixed(3)),
|
||||
lon: Number(lon.toFixed(3)),
|
||||
}),
|
||||
cachedGroundFloor: () => 10,
|
||||
GROUND_FLOOR_LIFT_M: 1.5,
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
trails: {
|
||||
prepareEntry(e, collect) {
|
||||
if (collect)
|
||||
for (const point of offers)
|
||||
collect(point, height.requestHeight(point.lat, point.lon));
|
||||
},
|
||||
},
|
||||
rendering: {
|
||||
requestVisibility() {},
|
||||
cameraHeightM: () => 100,
|
||||
globeSurface: () => 'none',
|
||||
sampleMeshFloors(points) {
|
||||
probed.push(...points.map((p) => [p.lat, p.lon]));
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => height.clear());
|
||||
height.anchorFloors();
|
||||
assert.deepEqual(probed, [[42.3614, -71.0754]]);
|
||||
});
|
||||
|
||||
test('selection churn releases past geometry on every retained vehicle', async (t) => {
|
||||
const app = harness(t, { floorAt: () => 10 });
|
||||
const { mergeHistory, seek } = await import('../../data/contactPlayback.js');
|
||||
@@ -4262,3 +4374,54 @@ test('parked transit reprojects held and reported courses at the bounded camera
|
||||
'selected unknown course also stays screen-up',
|
||||
);
|
||||
});
|
||||
|
||||
test('a view with no feed reads its coverage prompt, not an undated feed', async (t) => {
|
||||
const app = harness(t);
|
||||
app.serve('mbta', () => ({
|
||||
status: 200,
|
||||
body: snapshot(
|
||||
'mbta',
|
||||
'MBTA',
|
||||
[vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)],
|
||||
{ fetchedAt: Date.now() },
|
||||
),
|
||||
}));
|
||||
app.layer.enable(app.viewer);
|
||||
await app.layer.update();
|
||||
assert.ok(app.layer.getStats().lastUpdate, 'Boston has a dated snapshot');
|
||||
|
||||
// London has no registered feed: the row prompts instead of dating Boston's
|
||||
// last snapshot over an empty map.
|
||||
app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 });
|
||||
app.advance(1_000);
|
||||
const away = app.layer.getStats();
|
||||
assert.equal(away.status, 'zoom-in');
|
||||
assert.equal(away.count, 0);
|
||||
assert.equal(away.lastUpdate, null);
|
||||
assert.match(
|
||||
away.statusMessage,
|
||||
/^No feed here yet · \d+ regions available$/,
|
||||
);
|
||||
assert.equal(away.coverage, away.statusMessage);
|
||||
|
||||
// Above the altitude gate the prompt says how low to fly.
|
||||
app.viewer.camera.positionCartographic.height = 10_000_000;
|
||||
app.lookAt({ west: -0.2, south: 51.45, east: -0.05, north: 51.55 });
|
||||
app.advance(1_000);
|
||||
assert.equal(
|
||||
app.layer.getStats().statusMessage,
|
||||
'Fly below 2,850 km to a covered region',
|
||||
);
|
||||
});
|
||||
|
||||
test('the prompt names the altitude the gate opens at, not 3,000 km', async (t) => {
|
||||
// 2,900 km is under ACTIVATION_ALTITUDE_M but above the enter threshold.
|
||||
const app = harness(t, { altitude: 2_900_000 });
|
||||
app.layer.enable(app.viewer);
|
||||
await app.layer.update();
|
||||
assert.deepEqual(app.requested, [], 'nothing loads over Boston');
|
||||
assert.equal(
|
||||
app.layer.getStats().statusMessage,
|
||||
'Fly below 2,850 km to a covered region',
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
ACTIVATION_ALTITUDE_M,
|
||||
ACTIVATION_ENTER_ALTITUDE_M,
|
||||
FEED_STALE_AFTER_MS,
|
||||
aggregateTransitFeedHealth,
|
||||
transitDetectionClass,
|
||||
@@ -245,17 +245,19 @@ export function createQueries({ state, parts }) {
|
||||
const health = aggregateTransitFeedHealth(statuses, now);
|
||||
const count = state._vehicles.size;
|
||||
if (state._enabled && active.length === 0) {
|
||||
// English: the analyst's empty note and the row's prompt, both shown
|
||||
// through translateStatusMessage (ui/statusText.js).
|
||||
const note = state._altitudeGateOpen
|
||||
? `No feed here yet · ${TRANSIT_REGION_COUNT} regions available`
|
||||
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`;
|
||||
return {
|
||||
count: 0,
|
||||
lastUpdate: state._lastUpdate,
|
||||
error: null,
|
||||
source: 'GTFS-RT',
|
||||
status: 'zoom-in',
|
||||
// English data (the analyst's empty note to the model); the voice
|
||||
// card shows it through NOTE_PATTERNS (voice/resultDisplay.js).
|
||||
coverage: state._altitudeGateOpen
|
||||
? `No feed here yet · ${TRANSIT_REGION_COUNT} regions available`
|
||||
: `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`,
|
||||
statusMessage: note,
|
||||
coverage: note,
|
||||
};
|
||||
}
|
||||
// Age is shown by the same rule the row state uses, so the text and the
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// Transit: a manager tick that failed over Boston must not keep its error on
|
||||
// the row the coverage repaint draws after the camera leaves for London.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createState } from './state.js';
|
||||
import { createViewport } from './viewport.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { LayerLifecycle } from '../../data/lifecycle.js';
|
||||
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
|
||||
const LONDON = { lat: 51.5072, lon: -0.1276 };
|
||||
const BOSTON = { lat: 42.3601, lon: -71.0589 };
|
||||
|
||||
/** A viewer double whose camera port stands at `at`, `height` metres up. */
|
||||
function viewer(at, height) {
|
||||
const host = {};
|
||||
bindRenderer(host, {
|
||||
camera: {
|
||||
pose: () => ({ lon: at.lon, lat: at.lat, height }),
|
||||
viewRectangle: () => null,
|
||||
on: () => () => {},
|
||||
},
|
||||
});
|
||||
return host;
|
||||
}
|
||||
|
||||
test('leaving a feed whose tick failed repaints its error away', async () => {
|
||||
const services = {
|
||||
overlays: {
|
||||
setOverlayEntries() {},
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource() {},
|
||||
},
|
||||
render: { governorRequestRender() {} },
|
||||
};
|
||||
const state = createState({ services });
|
||||
const feedStatus = (feedId) => {
|
||||
if (!state._feedStatus.has(feedId))
|
||||
state._feedStatus.set(feedId, { count: 0, error: null, loading: false });
|
||||
return state._feedStatus.get(feedId);
|
||||
};
|
||||
const parts = {
|
||||
ingestion: {
|
||||
feedStatus,
|
||||
// As pollFeed's catch does when the proxy answers 503.
|
||||
pollFeed(feed) {
|
||||
Object.assign(feedStatus(feed.id), {
|
||||
error: `${feed.name} feed unavailable`,
|
||||
loading: false,
|
||||
});
|
||||
return Promise.resolve();
|
||||
},
|
||||
removeFeedVehicles() {},
|
||||
sweepAgedVehicles() {},
|
||||
},
|
||||
rendering: { requestVisibility() {}, syncRenderHold() {} },
|
||||
};
|
||||
parts.viewport = createViewport({ state, services, parts });
|
||||
const queries = createQueries({ state, parts }).methods;
|
||||
state._enabled = true;
|
||||
|
||||
const lifecycle = new LayerLifecycle(null);
|
||||
lifecycle.register({
|
||||
id: 'transit',
|
||||
name: 'Transit',
|
||||
source: 'GTFS-RT',
|
||||
getStats: () => queries.getStats(),
|
||||
async update() {},
|
||||
});
|
||||
const entry = lifecycle.layers.get('transit');
|
||||
entry.enabled = true;
|
||||
entry.lifecycleState = 'enabled';
|
||||
entry.initialized = true;
|
||||
|
||||
const row = () => {
|
||||
const layer = lifecycle.getAll()[0];
|
||||
return `${layerFeedState(layer.stats)} | ${LayerPanel.prototype._buildMetaText(layer)}`;
|
||||
};
|
||||
const painted = [];
|
||||
state._dataManager = {
|
||||
refreshLayerStats(layerId) {
|
||||
lifecycle.refreshLayerStats(layerId);
|
||||
painted.push(row());
|
||||
},
|
||||
};
|
||||
|
||||
state._viewer = viewer(BOSTON, 4_000);
|
||||
parts.viewport.runProximityCheck();
|
||||
await lifecycle.refreshLayer('transit');
|
||||
assert.match(row(), /feed unavailable/, 'the tick recorded the failure');
|
||||
|
||||
const before = painted.length;
|
||||
state._viewer = viewer(LONDON, 4_000);
|
||||
parts.viewport.runProximityCheck();
|
||||
assert.equal(queries.getStats().status, 'zoom-in');
|
||||
assert.ok(painted.length > before, 'leaving Boston repainted the row');
|
||||
assert.doesNotMatch(painted.at(-1), /feed unavailable/);
|
||||
});
|
||||
@@ -116,7 +116,7 @@ export function createState({ services }) {
|
||||
state._cockpitVision = false;
|
||||
/** @type {Array<[string, EventListener]>} window listeners to remove on destroy. */
|
||||
state._styleListeners = [];
|
||||
/** @type {{ refreshLayerStats?: () => void }|null} */
|
||||
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} */
|
||||
state._dataManager = null;
|
||||
/** @type {number|null} */
|
||||
state._lastUpdate = null;
|
||||
|
||||
@@ -73,7 +73,9 @@ export function createViewport({ state, services, parts }) {
|
||||
if (!state._enabled || !state._viewer) return;
|
||||
refreshViewBounds();
|
||||
const altitude = getCameraAltitude();
|
||||
const wasGateOpen = state._altitudeGateOpen;
|
||||
state._altitudeGateOpen = altitudeGateOpen(altitude);
|
||||
let changed = state._altitudeGateOpen !== wasGateOpen;
|
||||
const center = state._altitudeGateOpen ? getCameraCenterLatLon() : null;
|
||||
const desired = new Map();
|
||||
if (center) {
|
||||
@@ -96,17 +98,23 @@ export function createViewport({ state, services, parts }) {
|
||||
state._activeFeeds.delete(feedId);
|
||||
state._feedStatus.delete(feedId);
|
||||
parts.ingestion.removeFeedVehicles(feedId);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Nothing is left on the map to date.
|
||||
if (desired.size === 0) state._lastUpdate = null;
|
||||
for (const [feedId, feed] of desired) {
|
||||
if (!state._activeFeeds.has(feedId)) {
|
||||
state._activeFeeds.set(feedId, feed);
|
||||
void parts.ingestion.pollFeed(feed, state._generation);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
parts.ingestion.sweepAgedVehicles(Date.now());
|
||||
parts.rendering.syncRenderHold();
|
||||
governorRequestRender('transit-proximity');
|
||||
// Repaint now: the row follows the camera, the manager tick is 15 s.
|
||||
if (changed) state._dataManager?.refreshLayerStats?.('transit');
|
||||
}
|
||||
|
||||
function onCameraChanged() {
|
||||
|
||||
Reference in new issue
Block a user