mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-05 19:04:02 +00:00
feat(transit): live public-transit vehicles from open GTFS-Realtime feeds (#587)
Supersedes #218 by @spcpza, ported onto the current component layout with fixes from review. Verified before merge: format, package boundaries, unit suite, build, and the browser tracking suite; a browser harness for the change where one applies; adversarial review applied. Contributor: @spcpza. His original commit is the base of this branch, and his own re-port onto main (2026-09-15, `5b69011`) was consulted while finishing the height work. That port reads every vehicle's surface from the app's shared ground-floor system (`cachedGroundFloor` / `warmGroundFloor` / `GROUND_FLOOR_LIFT_M`) rather than sampling the scene per layer, keeps a vehicle hidden until its cell answers, warms a bounded batch per poll on a timer instead of per frame, and renders at the ellipsoid above the altitude gate. That is the sounder primitive — one floor system for the app, with the rooftop-versus-street question already settled against a datum-correct DEM prior — and this branch's height work was rebuilt on it, replacing a bespoke cell cache, ground prior and rooftop rule written here. Credit for that direction is his. Future work (not in this PR), both written up in docs/CURRENT-STATE.md: - Readable route names. The realtime feeds carry only `route_id`; `route_short_name` / `route_long_name` live in each operator's static GTFS `routes.txt`, and headsigns in `trips.txt`. Doing it properly wants a server-side metadata loader beside the transit proxy with fixed registered static sources, bounded indexes built once and persisted, a slow conditional refresh, and a versioned route dictionary the browser caches. Shipped here: ids are never rewritten, and a cut one carries an ellipsis instead of reading as a typo. - Below-ground rendering. Subway vehicles are drawn on the surface directly above themselves, because the feeds carry no depth and a train nobody can see is not worth drawing; the card says so plainly. Real treatment wants OSM tunnel geometry per city and a ghosted sprite tethered to the surface. The owner recorded it and left it. Round four and after (2026-09-15). The owner tested round three under FLIR and NVG, and then asked for the design to be taken further: elegant in performance, beautiful on camera, trails with a cache for public transport, Cesium-native, and a core other moving layers can adopt. Codex Astra reviewed the plan (it confirmed the speed fault: a glide started from the drawn position at receipt time but spanned the gap between report times, so with MBTA reporting every ~10 s against a 15 s poll every second glide ran at 1.5x; it rejected a queued-segment patch), then wrote the design, then implemented it in commit-sized passes with adversarial review between them and real-browser harness runs by the integrator. What this PR now contains beyond the contributor's original port: - Delayed playback in a contact-agnostic core (`src/data/contactPlayback.js`): each vehicle keeps a typed, bounded fix history and a display clock that runs at one second per second through it, a feed-derived lag behind real time, holding at its newest fix rather than extrapolating and never sprinting to catch up. Marker, course, motion word, card and trail all read the same displayed sample. The clock has an explicit time-offset and seek API so a rewind is a later feature, not a rewrite; flights and vessels are untouched. - A selected-vehicle trail (`src/data/contactTrailRenderer.js`, `src/layers/transit/trails.js`): the retained history drawn with batched Cesium primitives, clipped at display time so the head is exactly the sprite, faded by age, in the mode colour (white under sensor presets), on the same surface path as the marker. - Bounded proxy-side history (`server/providers/transitHistory.js`): fifteen minutes and at most 128 fixes per vehicle with hard byte ceilings, MBTA only for now (opt-in per feed), served by a small endpoint that never fetches upstream, so a selected trail survives a browser reload while the server keeps running. - Scene work bounded to what is visible and moving, an occluder, cached DETECT candidates, holds on the render loop only while something visible moves. - Sensor presets: white-hot haloed sprites under NVG/FLIR/noir (black-hot inverts), saturated mode colours under CRT, per-mode bracket tiers in every theme, the selected card keeping its mode colour. - A discriminating browser harness (`scripts/qa-transit.mjs`) that samples postRender frames, reads the real card anchor, and measures fleet budgets at 800 and 3,000 vehicles. Not built, recorded as follow-ups: curated route display names (lowest priority per the owner), fleet-wide tails, route snapping, a rewind UI, adoption of the playback core by flights and vessels. Verified at merge (2026-09-15 morning): unit suite 3,896 passing, build clean, format and boundary gates clean, tracking regression 109/109, browser harness keyless 200 pass / 0 fail (13 sensor checks unexercised because the live view offered fewer than six isolated sprites; every judged sprite passed), keyed on Google 3D tiles 198 pass with the per-frame allocation gate as the only failure. Follow-ups recorded: the keyed build's playback sampler still allocates per frame (CPU and frame time stay within budget; the 3,000-vehicle metro view sits at a 27.6 ms frame interval against a 25 ms budget), the shared detection overlay's per-paint allocation, friendlier route names, fleet-wide tails, a rewind UI, and adopting the playback core for vessels and flights. Co-authored-by: spcpza <[email protected]>
This commit is contained in:
1 parent
1ad565c8af
commit
76c20be277
78 files changed
+19842
-186
No files matched your search
@@ -0,0 +1,303 @@
|
||||
import { destroyTrack } from '../../data/contactPlayback.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
claimCameraSensitivity,
|
||||
releaseCameraSensitivity,
|
||||
} from '../../data/cameraSensitivity.js';
|
||||
import {
|
||||
CAMERA_PERCENTAGE_CHANGED,
|
||||
TRANSIT_SELECTED_OVERLAY_SOURCE_ID,
|
||||
} from './policy.js';
|
||||
import { TRANSIT_ENABLED_FEEDS } from '../../data/transitFeeds.js';
|
||||
|
||||
/**
|
||||
* Init / enable / disable / update / destroy for one Transit layer instance.
|
||||
* Everything acquired here is released here — primitives, listeners, the sprite
|
||||
* registration, the pick owner, the render hold, and the camera sensitivity
|
||||
* this layer borrowed.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createLifecycle({ state, services, parts }) {
|
||||
const {
|
||||
registerSpriteCollection,
|
||||
unregisterSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
} = services.sprites;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
|
||||
/**
|
||||
* Borrow the camera's change sensitivity through the shared claim ledger.
|
||||
*
|
||||
* `camera.changed` fires on a percentage of the view moving, and this layer
|
||||
* needs a finer trigger than the default to notice it has entered a feed's
|
||||
* coverage. It is a single shared number, so the claim is registered by name
|
||||
* rather than written directly: comparing the VALUE on the way out could not
|
||||
* tell this layer's 0.05 from anybody else's, and handing back the coarse
|
||||
* default while Bikeshare was still relying on a fine one was exactly the
|
||||
* bug that produced.
|
||||
*/
|
||||
function borrowCameraSensitivity(viewer) {
|
||||
claimCameraSensitivity(
|
||||
viewer?.camera,
|
||||
'transit',
|
||||
CAMERA_PERCENTAGE_CHANGED,
|
||||
);
|
||||
}
|
||||
|
||||
/** Give the claim up. The camera keeps whatever anyone else still asks for. */
|
||||
function returnCameraSensitivity(viewer) {
|
||||
releaseCameraSensitivity(viewer?.camera, 'transit');
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the active post-FX style so the sprites can be restyled for it.
|
||||
* The map style arrives on `gev:style-change`; a cockpit vision override
|
||||
* (NVG/thermal inside the cockpit view, which sets no map style) arrives on
|
||||
* `gev:vision-change` with the effective style and wins while it lasts.
|
||||
* Bound once per instance and removed on destroy. Read the document's
|
||||
* current style first: a persisted style restores before layers register.
|
||||
*/
|
||||
function bindStyleEvents() {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (state._styleListeners.length > 0) return;
|
||||
parts.rendering.setStylePreset(
|
||||
document?.documentElement?.dataset?.gevStyle || 'normal',
|
||||
);
|
||||
const onStyle = (event) => {
|
||||
if (state._cockpitVision) return;
|
||||
parts.rendering.setStylePreset(event?.detail?.style);
|
||||
};
|
||||
const onVision = (event) => {
|
||||
state._cockpitVision = event?.detail?.cockpit === true;
|
||||
parts.rendering.setStylePreset(event?.detail?.style);
|
||||
};
|
||||
window.addEventListener('gev:style-change', onStyle);
|
||||
window.addEventListener('gev:vision-change', onVision);
|
||||
state._styleListeners.push(
|
||||
['gev:style-change', onStyle],
|
||||
['gev:vision-change', onVision],
|
||||
);
|
||||
}
|
||||
|
||||
function unbindStyleEvents() {
|
||||
if (typeof window === 'undefined') return;
|
||||
for (const [name, listener] of state._styleListeners) {
|
||||
window.removeEventListener(name, listener);
|
||||
}
|
||||
state._styleListeners.length = 0;
|
||||
state._cockpitVision = false;
|
||||
}
|
||||
|
||||
let visibilityDocument = null,
|
||||
hidden = false;
|
||||
function onVisibilityChange() {
|
||||
if (visibilityDocument.visibilityState === 'hidden') hidden = true;
|
||||
else if (hidden) {
|
||||
hidden = false;
|
||||
parts.rendering.resumePlayback();
|
||||
}
|
||||
}
|
||||
function bindVisibility() {
|
||||
if (visibilityDocument || typeof document === 'undefined') return;
|
||||
visibilityDocument = document;
|
||||
hidden = document.visibilityState === 'hidden';
|
||||
visibilityDocument.addEventListener('visibilitychange', onVisibilityChange);
|
||||
}
|
||||
function unbindVisibility() {
|
||||
visibilityDocument?.removeEventListener(
|
||||
'visibilitychange',
|
||||
onVisibilityChange,
|
||||
);
|
||||
visibilityDocument = null;
|
||||
hidden = false;
|
||||
}
|
||||
|
||||
const methods = {
|
||||
id: 'transit',
|
||||
name: 'Transit',
|
||||
icon: '🚌',
|
||||
source: 'GTFS-RT',
|
||||
|
||||
/**
|
||||
* Create the point collection. Called once at bootstrap.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
*/
|
||||
init(viewer) {
|
||||
state._viewer = viewer;
|
||||
state._markers = new Cesium.BillboardCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
});
|
||||
viewer.scene.primitives.add(state._markers);
|
||||
registerSpriteCollection('transit', state._markers);
|
||||
state._animatedMarkers = new Cesium.BillboardCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
});
|
||||
viewer.scene.primitives.add(state._animatedMarkers);
|
||||
registerSpriteCollection('transit-motion', state._animatedMarkers);
|
||||
state._animatedMarkers.show = false;
|
||||
state._markers.show = false;
|
||||
state._enabled = false;
|
||||
state._activeFeeds.clear();
|
||||
state._feedStatus.clear();
|
||||
state._inFlight.clear();
|
||||
for (const entry of state._vehicles.values()) {
|
||||
entry.detectContact = null;
|
||||
parts.rendering.cancelWake(entry);
|
||||
destroyTrack(entry.track);
|
||||
}
|
||||
state._vehicles.clear();
|
||||
parts.height.clear();
|
||||
state._selectedKey = null;
|
||||
state._lastUpdate = null;
|
||||
state._error = null;
|
||||
state._limitWarned = false;
|
||||
state._altitudeGateOpen = false;
|
||||
state._moving.clear();
|
||||
state._heightDirty.clear();
|
||||
state._rotationPose = null;
|
||||
state._rotationDirty = false;
|
||||
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
|
||||
restoreSpriteOrder(viewer);
|
||||
bindStyleEvents();
|
||||
console.log(
|
||||
`[Data:Transit] Initialized with ${TRANSIT_ENABLED_FEEDS.length} GTFS-RT feeds`,
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Show vehicles, watch the camera, and poll every feed in range.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
*/
|
||||
enable(viewer) {
|
||||
state._enabled = true;
|
||||
bindVisibility();
|
||||
state._generation += 1;
|
||||
state._error = null;
|
||||
state._markers.show = true;
|
||||
state._animatedMarkers.show = true;
|
||||
state._maintenanceTimer = setInterval(
|
||||
parts.rendering.maintainPresentation,
|
||||
250,
|
||||
);
|
||||
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, true);
|
||||
parts.selection.installClickHandler(viewer);
|
||||
registerPickOwner('transit', (pickedId) => state._vehicles.has(pickedId));
|
||||
if (!state._cameraChangedAttached) {
|
||||
viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged);
|
||||
borrowCameraSensitivity(viewer);
|
||||
state._cameraChangedAttached = true;
|
||||
}
|
||||
if (!state._preRenderRemove) {
|
||||
state._preRenderRemove = viewer.scene.preRender.addEventListener(
|
||||
parts.rendering.onPreRender,
|
||||
);
|
||||
}
|
||||
parts.viewport.runProximityCheck();
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
* Hide everything, stop polling, drop all vehicles.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
*/
|
||||
disable(viewer) {
|
||||
state._enabled = false;
|
||||
unbindVisibility();
|
||||
parts.testing._stopTransitProbeForTest();
|
||||
state._qaFixtureFloors?.clear();
|
||||
state._generation += 1;
|
||||
clearInterval(state._maintenanceTimer);
|
||||
state._maintenanceTimer = null;
|
||||
clearTimeout(state._visibilityTimer);
|
||||
state._visibilityTimer = null;
|
||||
state._detectCache = null;
|
||||
state._detectBuiltAt = -Infinity;
|
||||
state._visible.clear();
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = null;
|
||||
parts.selection.clearSelection();
|
||||
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
|
||||
parts.selection.removeClickHandler();
|
||||
unregisterPickOwner('transit');
|
||||
if (state._cameraChangedAttached) {
|
||||
viewer.camera.changed.removeEventListener(
|
||||
parts.viewport.onCameraChanged,
|
||||
);
|
||||
returnCameraSensitivity(viewer);
|
||||
state._cameraChangedAttached = false;
|
||||
}
|
||||
if (state._preRenderRemove) {
|
||||
state._preRenderRemove();
|
||||
state._preRenderRemove = null;
|
||||
}
|
||||
parts.ingestion.abortAllInFlight();
|
||||
state._activeFeeds.clear();
|
||||
state._feedStatus.clear();
|
||||
for (const entry of state._vehicles.values()) {
|
||||
entry.detectContact = null;
|
||||
parts.rendering.cancelWake(entry);
|
||||
destroyTrack(entry.track);
|
||||
}
|
||||
state._vehicles.clear();
|
||||
parts.height.clear();
|
||||
state._markers?.removeAll();
|
||||
state._animatedMarkers?.removeAll();
|
||||
if (state._animatedMarkers) state._animatedMarkers.show = false;
|
||||
if (state._markers) state._markers.show = false;
|
||||
state._altitudeGateOpen = false;
|
||||
state._moving.clear();
|
||||
state._heightDirty.clear();
|
||||
state._rotationPose = null;
|
||||
state._rotationDirty = false;
|
||||
if (state._renderHeld) {
|
||||
releaseContinuousRender('transit');
|
||||
state._renderHeld = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Manager tick (every TRANSIT_POLL_MS): re-poll every active feed, and
|
||||
* sweep aged vehicles even when nothing is active, so a layer left over a
|
||||
* quiet region does not keep an old fleet on screen.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async update() {
|
||||
if (!state._enabled) return;
|
||||
parts.ingestion.sweepAgedVehicles(Date.now());
|
||||
if (state._activeFeeds.size === 0) return;
|
||||
const generation = state._generation;
|
||||
await Promise.all(
|
||||
[...state._activeFeeds.values()].map((feed) =>
|
||||
parts.ingestion.pollFeed(feed, generation),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Tear down the collection entirely and release every shared registration.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
*/
|
||||
destroy(viewer) {
|
||||
this.disable(viewer);
|
||||
if (state._markers) {
|
||||
unregisterSpriteCollection('transit', state._markers);
|
||||
viewer?.scene?.primitives?.remove(state._markers);
|
||||
state._markers = null;
|
||||
}
|
||||
if (state._animatedMarkers) {
|
||||
unregisterSpriteCollection('transit-motion', state._animatedMarkers);
|
||||
viewer?.scene?.primitives?.remove(state._animatedMarkers);
|
||||
state._animatedMarkers = null;
|
||||
}
|
||||
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
|
||||
parts.height.clear();
|
||||
unbindStyleEvents();
|
||||
state._dataManager = null;
|
||||
state._viewer = null;
|
||||
},
|
||||
};
|
||||
|
||||
return { methods };
|
||||
}
|
||||
Reference in new issue
Block a user