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:
Bilawal Sidhu authored and GitHub committed 2026-09-15 05:18:30 -05:00
1 parent 1ad565c8af
commit 76c20be277
78 files changed
+19842 -186

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
import * as Cesium from 'cesium';
import { createHistoryBudget } from '../../data/contactPlayback.js';
/**
* One Transit layer's mutable scene state. Every field lives on the instance,
* so two layers built from this factory never share a viewer, a primitive
* collection, a request map or a height cache.
* @param {{services: object}} context
* @returns {object}
*/
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
services.overlays;
const state = {};
state._historyBudget = createHistoryBudget();
state.DEFAULT_OVERLAY_HOST = Object.freeze({
setEntries: setOverlayEntries,
setVisible: setOverlaySourceVisible,
clearSource: clearOverlaySource,
});
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
/** @type {Cesium.Viewer|null} */
state._viewer = null;
/** @type {Cesium.BillboardCollection|null} */
state._markers = null;
state._animatedMarkers = null;
state._visible = new Set();
state._visibilityTimer = null;
state._maintenanceTimer = null;
state._detectBuiltAt = -Infinity;
state._cameraRevision = 0;
state._rotationRevision = -1;
state._enabled = false;
state._generation = 0;
state._cameraChangedAttached = false;
state._cameraDebounceTimer = null;
state._altitudeGateOpen = false;
/** Camera sensitivity as we found it, so disable() can hand it back. */
state._priorPercentageChanged = null;
/** The value this layer actually wrote, for an identity-guarded restore. */
state._appliedPercentageChanged = null;
/** @type {(() => void)|null} */
state._preRenderRemove = null;
state._renderHeld = false;
/** @type {Cesium.ScreenSpaceEventHandler|null} */
state._clickHandler = null;
/**
* The vehicles currently mid-glide. The per-frame pass walks THIS, not the
* whole fleet, and the render hold is derived from it together with the
* height queue — so both track work that exists rather than a window of time
* the layer hoped would contain some.
* @type {Set<object>}
*/
state._moving = new Set();
/** Vehicles whose sampled height landed after they were drawn. @type {Set<object>} */
state._heightDirty = new Set();
/**
* Inflated camera view bounds in degrees, or null before the first camera
* read. Decides which vehicles are worth animating frame by frame.
* @type {{south:number,north:number,west:number,east:number}|null}
*/
state._viewBounds = null;
/** How many vehicles are currently drawn, as opposed to held. */
state._shownCount = 0;
/** Deferred shown/hidden sweep bookkeeping. */
state._visibilityDirty = true;
state._visibilityAt = 0;
/** Throttle bookkeeping for the screen-space rotation pass. */
state._rotationAt = 0;
state._rotationPose = null;
state._rotationDirty = false;
/** @type {Map<string, object>} feedId → registry entry currently polled */
state._activeFeeds = new Map();
/** @type {Map<string, {count:number, lastUpdate:number|null, error:string|null, stale:boolean, pollSeq:number, loading:boolean}>} */
state._feedStatus = new Map();
/** @type {Map<string, {controller: AbortController, promise: Promise<void>}>} */
state._inFlight = new Map();
/** @type {Map<string, object>} vehicle key → runtime entry */
state._vehicles = new Map();
/** Timer for the floor re-read cycle, and how many it has spent. */
state._floorTimer = null;
state._floorAttempts = 0;
/** Where the next warm window starts among the cold cells: no cell waits for ever. */
state._floorCursor = 0;
/** @type {string|null} */
state._selectedKey = null;
state._selectedCardAt = 0;
/** The card text last published, so an unchanged card is not re-sent. */
state._selectedCardText = null;
/**
* Bumped whenever the set of vehicles DETECT may see could have changed —
* a poll, a visibility sweep, a removal, a selection — so the candidate
* list is rebuilt on change rather than on every paint.
*/
state._detectRevision = 0;
/** The candidate list DETECT was last handed, and the revision it was built at. */
state._detectCache = null;
/**
* Active post-FX style the sprites are drawn for. Read from the document
* at init and followed through the style and cockpit-vision events; a
* cockpit override wins over the map style while it lasts.
*/
state._stylePreset = 'normal';
state._cockpitVision = false;
/** @type {Array<[string, EventListener]>} window listeners to remove on destroy. */
state._styleListeners = [];
/** @type {{ refreshLayerStats?: () => void }|null} */
state._dataManager = null;
/** @type {number|null} */
state._lastUpdate = null;
/** @type {string|null} */
state._error = null;
state._limitWarned = false;
state._scratchCartesian = new Cesium.Cartesian3();
return state;
}