Merge origin/main into the renderer seam

Brings in main up to f24abfc88: cockpit subject providers, the render
failure notice, aircraft drawn in their own mesh colours, airport ground
vehicles, and an aircraft with no ground track facing its true heading.

Under the seam:
- The render failure notice lives in the Cesium adapter
  (src/render/cesium/renderFailure.js) and is the application hook
  renderFailureNotice({allowReload, store}); its private Cesium fields
  (Event's raise queue, the widget's render loop flag) are read through
  internals.js. The inline panel's timer waits while the frame port reports
  the loop stopped, and goes on after a Retry.
- Ordinary aircraft models draw white with the 'highlight' colour blend
  through the draw port; tracked and emergency colours tint the mesh.
- Held trains and transit vehicles hide their route set and markers through
  the draw port; the fleet model test fakes answer loads through the fake
  draw port instead of Cesium's glTF loader.
- The Cockpit's subject view follows and places the camera through the
  camera port.
This commit is contained in:
Sameh Khamis committed 2026-11-14 09:59:55 -08:00
commit 866a9816f2
142 files changed
+9067 -308

No files matched your search

+23 -10
View File
@@ -1,5 +1,9 @@
import { aircraftModelSpec, fleetModelSet } from '../../data/fleetModels.js';
import { MODEL_COLOR_BLEND_AMOUNT } from './policy.js';
import {
aircraftCallsignRule,
aircraftModelByCallsign,
aircraftModelSpec,
fleetModelSet,
} from '../../data/fleetModels.js';
/**
* What an aircraft draws with before the fleet model set has loaded: no
@@ -17,7 +21,6 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
bellyM: 0,
elevationM: 0,
tinted: false,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
visualCenterNative: Object.freeze([0, 0, 0]),
trailAnchorNative: Object.freeze([0, 0, 0]),
key: 'unloaded',
@@ -25,12 +28,14 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
/**
* The fleet model, life-size scale and measured geometry an aircraft draws
* with, chosen by its ICAO type and emitter category (`fleetModels.js`).
* with, chosen by its ICAO type and emitter category, and by its callsign
* for the types that pick by callsign (`fleetModels.js`).
* Shared by the Flights, Military Flights and Local ADS-B layers so all three
* draw the same model for the same aircraft. `bellyM` is the model's scaled
* clearance: how far a grounded aircraft's origin stands above the ground.
* @param {{typeCode?: string|null, type?: string|null,
* category?: string|number|null}|null|undefined} aircraft
* category?: string|number|null,
* callsign?: string|null}|null|undefined} aircraft
* @param {object|null} [set] The loaded fleet model set.
* @returns {object} The spec, or {@link UNLOADED_AIRCRAFT_MODEL_SPEC} before
* the set has loaded.
@@ -40,17 +45,17 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
// Layers ask on every tick; each type and category is resolved once per set.
let cache = specCaches.get(set);
if (!cache) specCaches.set(set, (cache = new Map()));
const key = aircraftModelSpecCacheKey(aircraft);
const key = aircraftModelSpecCacheKey(aircraft, set);
let layerSpec = cache.get(key);
if (!layerSpec) {
const spec = aircraftModelSpec(set, {
typeCode: aircraft?.typeCode ?? aircraft?.type ?? null,
category: aircraft?.category ?? null,
callsign: aircraft?.callsign ?? null,
});
layerSpec = Object.freeze({
...spec,
bellyM: spec.clearanceM,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
});
cache.set(key, layerSpec);
}
@@ -61,10 +66,18 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
const specCaches = new WeakMap();
/**
* Cache key of an aircraft's model spec: what selects its model.
* Cache key of an aircraft's model spec: what selects its model. For a type
* that picks its model by callsign (an airport vehicle) the key adds the
* rule its callsign matches, or `type` for none, so such a type caches at
* most one entry per rule and one for its own model.
* @param {object|null|undefined} aircraft
* @param {object|null} [set] The loaded fleet model set.
* @returns {string}
*/
export function aircraftModelSpecCacheKey(aircraft) {
return `${aircraft?.typeCode ?? aircraft?.type ?? ''}|${aircraft?.category ?? ''}`;
export function aircraftModelSpecCacheKey(aircraft, set = fleetModelSet()) {
const type = aircraft?.typeCode ?? aircraft?.type ?? '';
const key = `${type}|${aircraft?.category ?? ''}`;
if (!set || !aircraftModelByCallsign(set.types, type)) return key;
const rule = aircraftCallsignRule(set.types, type, aircraft?.callsign);
return `${key}|${rule >= 0 ? `r${rule}` : 'type'}`;
}
+2 -3
View File
@@ -84,10 +84,9 @@ export const MODEL_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite the renderer's heading 0
// Owner launch-polish direction: models should read as clean light silhouettes,
// with only a weak diffuse contribution from the models' own colours.
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
/** A model's colour where it draws its mesh's own (`aircraftModelBlend`). */
export const MODEL_WHITE = rgba('#FFFFFF');
/** The tracked contact's tint, and its billboard once a model takes over. */
export const TRACKED_CYAN = rgba('#00FFFF');
+62 -3
View File
@@ -5,6 +5,11 @@ import {
} from '../../data/renderAltitude.js';
import { classifyAircraft } from '../../data/aircraftClass.js';
import { aircraftEmergency } from '../../data/aircraftEmergency.js';
import {
aircraftCallsignRule,
aircraftModelSpec,
fleetModelSet,
} from '../../data/fleetModels.js';
import {
approxDistanceKm,
GROUND_FLOOR_CLAMP_RADIUS_KM,
@@ -21,6 +26,7 @@ export class FlightRecords {
cachedGroundFloor,
floorAltitudeM,
now = () => Date.now(),
fleetModels = fleetModelSet,
}) {
this.services = {
geoidHeight,
@@ -29,6 +35,8 @@ export class FlightRecords {
};
/** The time records are judged at: the layer's clock. */
this.now = now;
/** The loaded fleet model set, or null before it loads. */
this.fleetModels = fleetModels;
this.data = new Map();
// Facts about an airframe, not a moment, kept across a reset.
this.airframes = new Map();
@@ -92,7 +100,6 @@ export class FlightRecords {
verticalRateMps: vertical_rate,
} = observation;
const onGround = on_ground === true;
this.missingPolls.delete(icao24);
// Sticky merge: OpenSky intermittently drops callsign/velocity/track for
// aircraft it still positions — hold last-known-good instead of
@@ -102,6 +109,27 @@ export class FlightRecords {
// The airframe's facts: this record's, or those kept across a reset.
const airframe = prevMeta ?? this.airframes.get(icao24);
this.airframes.delete(icao24);
// A ground vehicle or ground station (a feed's ZVEH or GRND: a model
// built standing, catalog category `other`) takes the feed's own type,
// which no airframe lookup knows; every other aircraft keeps waiting for
// its looked-up type. With no altitude at all it stands on the ground,
// where it is, instead of at the airborne default.
const groundModel = (typeCode) =>
drawnAsGroundModel(
this.fleetModels(),
typeCode,
category,
stickyText(callsign, prevMeta?.callsign),
);
const feedType = observation.typeCode || null;
const typeCode =
airframe?.typeCode ??
(feedType && groundModel(feedType) ? feedType : null);
const onGround =
on_ground === true ||
(!Number.isFinite(baro_alt) &&
!Number.isFinite(geo_alt) &&
groundModel(typeCode));
// Grounded planes with no baro reading sit at 0 m, not the 10 km
// airborne default (a parked plane must never float).
// NOTE (height-datum fix): `alt` stays the AVIATION field — the sticky
@@ -319,8 +347,9 @@ export class FlightRecords {
prevMeta?.lastContactEpochMs,
null,
),
// adsbdb enrichment — written by the enrichment callbacks, carried across polls:
typeCode: airframe?.typeCode ?? null,
// adsbdb enrichment — written by the enrichment callbacks, carried
// across polls; a ground vehicle's or station's from the feed:
typeCode,
typeName: airframe?.typeName ?? null,
registration: airframe?.registration ?? null,
airline: routeHeld ? (airframe.airline ?? null) : null,
@@ -408,3 +437,33 @@ export class FlightRecords {
this.geoidNCache.delete(id);
}
}
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
const groundModelCaches = new WeakMap();
/**
* Whether an aircraft of this type, emitter category and callsign is drawn
* with a model built standing on the ground (catalog category `other`: an
* airport vehicle, a ground station's mast). False before the set loads.
* Answered once per type, category and callsign rule matched.
* @param {object|null} set The loaded fleet model set.
* @param {string|null} typeCode
* @param {string|number|null} category
* @param {string|null} callsign
* @returns {boolean}
*/
function drawnAsGroundModel(set, typeCode, category, callsign) {
if (!set || !typeCode) return false;
let cache = groundModelCaches.get(set);
if (!cache) groundModelCaches.set(set, (cache = new Map()));
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
const key = `${typeCode}|${category ?? ''}|${rule}`;
let ground = cache.get(key);
if (ground === undefined) {
ground =
aircraftModelSpec(set, { typeCode, category, callsign }).category ===
'other';
cache.set(key, ground);
}
return ground;
}
+60 -1
View File
@@ -1,13 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { FlightRecords } from './records.js';
function records() {
const FLEET = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../public/models/fleet',
);
const fleetSet = {
catalog: JSON.parse(
fs.readFileSync(path.join(FLEET, 'catalog.json'), 'utf8'),
),
types: JSON.parse(fs.readFileSync(path.join(FLEET, 'types.json'), 'utf8')),
};
function records(fleetModels = () => null) {
return new FlightRecords({
geoidHeight: () => 40,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
approxDistanceKm: () => 0,
fleetModels,
});
}
const view = () => ({
@@ -260,3 +275,47 @@ test('a repeated fix time marks the contact as not updated; removal is unchanged
store.forget('abc123');
assert.equal(store.fixRepeated.has('abc123'), false);
});
test('a ground vehicle or station with no altitude stands on the ground; an aircraft does not', () => {
const store = records(() => fleetSet);
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
const vehicle = store.receive(
observation({
id: 'v1',
typeCode: 'ZVEH',
callsign: 'FIRE 2',
...noAltitude,
}),
view(),
).meta;
assert.equal(vehicle.onGround, true);
assert.equal(vehicle.typeCode, 'ZVEH');
assert.equal(vehicle.altitude, 0);
const mast = store.receive(
observation({ id: 'm1', typeCode: 'GRND', callsign: 'RX5', ...noAltitude }),
view(),
).meta;
assert.equal(mast.onGround, true);
assert.equal(mast.typeCode, 'GRND');
// An airliner with no altitude keeps the airborne default, and its feed
// type still waits for the airframe lookup.
const plane = store.receive(
observation({ id: 'p1', typeCode: 'A320', ...noAltitude }),
view(),
).meta;
assert.equal(plane.onGround, false);
assert.equal(plane.altitude, 10000);
assert.equal(plane.typeCode, null);
// A vehicle reporting an altitude is placed by it.
const reported = store.receive(
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }),
view(),
).meta;
assert.equal(reported.onGround, false);
// Before the model set loads nothing is grounded by its model.
const unloaded = records().receive(
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
view(),
).meta;
assert.equal(unloaded.onGround, false);
});
+3 -2
View File
@@ -82,11 +82,12 @@ export function createRendering({
const _iconKind = (icao24, klass) =>
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
/** Model tint, mirroring the billboard color rules. */
/** Model colour: the mesh's own (white), tinted cyan while tracked and red
* while broadcasting an emergency. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return TRACKED_CYAN;
return _fleetBillboardColor(icao24);
return _isEmergency(icao24) ? EMERGENCY_TINT : policy.MODEL_WHITE;
}
const models = createAircraftModels({
-1
View File
@@ -770,7 +770,6 @@ export function createLocalAdsbLayer({
camera: findCamera(viewer),
setId: `${prefix}:models`,
seeThrough: [sets.markers.id, sets.rings.id],
color: LOCAL_ADSB_COLOR,
resolveAsset,
groundSnap: services.groundSnap?.createGroundSnap?.() || null,
});
+7 -3
View File
@@ -576,7 +576,7 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o
assert.equal(queries.length, 2, 'each key is asked for once');
});
test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t) => {
test('the DISPLAY 3D toggle gives local aircraft their fleet models in their mesh colours', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const display = { models3d: true, models3dMode: 'proximity' };
@@ -598,8 +598,12 @@ test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t
);
assert.ok(model().gltf instanceof Uint8Array, 'built from the loaded set');
assert.equal(model().scale, spec.scale, 'drawn life size');
assert.deepEqual(model().tint, MAGENTA);
assert.deepEqual(model().colorBlend, { mode: 'mix', amount: 0.94 });
assert.deepEqual(
model().tint,
[1, 1, 1, 1],
'the mesh draws its own colours',
);
assert.deepEqual(model().colorBlend, { mode: 'highlight' });
assert.equal(model().environmentMap, false);
const heli = () => iconOf(draw, 'local-adsb:a0b702');
assert.equal(heli().show, true, 'the icon until the model is ready');
+12 -9
View File
@@ -7,7 +7,6 @@ import {
RADIANS_PER_DEGREE,
sub,
} from '../../geo/vector.js';
import { cssColor } from '../../render/color.js';
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js';
import {
@@ -22,7 +21,12 @@ import {
MODEL_PROX_ADD_M,
MODEL_PROX_KEEP_M,
} from '../flights/policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from '../../data/aircraftModelLighting.js';
const WHITE = Object.freeze([1, 1, 1, 1]);
/** Whether `point` is inside the eye's view cone (`pose`), a metre's slack. */
function inView(pose, point) {
@@ -42,6 +46,7 @@ const specOf = (marker) =>
aircraftLayerModelSpec({
typeCode: marker?.typeCode,
category: marker?.category,
callsign: marker?.record?.callsign,
});
/**
@@ -51,8 +56,8 @@ const specOf = (marker) =>
* Mirrors the public Flights fleet: models only below the altitude ceiling,
* the same proximity/all caps and add/keep radii, the same visible-first
* eligibility (`selectModelEligible`), the same fleet model per type, life
* size (`aircraftLayerModelSpec`) and the same tint path (a MIX colour blend,
* here magenta, as Flights tints military amber). A billboard stays the
* size (`aircraftLayerModelSpec`) and the same colours: the mesh's own
* (`aircraftModelBlend`). A billboard stays the
* visual until its model is ready (the set's `ready`) AND placed; a grounded
* aircraft's model rides the one-shot ground snap plus the model's clearance,
* and without a resolved ground it stays a billboard. Models move and turn in
@@ -67,7 +72,6 @@ const specOf = (marker) =>
* @param {string} options.setId The models set's id.
* @param {string[]} [options.seeThrough] The layer's other set ids ground
* samples see through (its markers).
* @param {string} options.color Model tint, a CSS colour.
* @param {(url: string) => string} options.resolveAsset
* @param {object|null} [options.groundSnap] `createGroundSnap()` instance.
* @returns {object|null} Null where the renderer draws no models.
@@ -78,12 +82,10 @@ export function createLocalAdsbModels({
camera,
setId,
seeThrough = [],
color,
resolveAsset,
groundSnap = null,
}) {
if (typeof draw?.models !== 'function' || !camera) return null;
const tint = cssColor(color) ?? color;
void loadFleetModelSet({ resolveAsset }).catch(() => {
/* aircraft stay billboards */
});
@@ -262,8 +264,9 @@ export function createLocalAdsbModels({
},
scale: spec.scale,
minPixelSize: MODEL_MIN_PX,
tint,
colorBlend: { mode: 'mix', amount: spec.blendAmount },
// The mesh's own colours (white, multiplied).
tint: WHITE,
colorBlend: aircraftModelBlend(false),
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
show: shown,
});
+3 -4
View File
@@ -39,6 +39,9 @@ export const TRACKED_ICON_COLOR = rgba('#FFD166');
export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
/** A model's colour where it draws its mesh's own (`aircraftModelBlend`). */
export const MODEL_WHITE = rgba('#FFFFFF');
// --- Ground traffic (owner reversal 2026-07-03; mirror of flights.js) ---------------
// adsb.lol/readsb flags ground traffic with alt_baro === "ground" (no separate
// boolean). Such aircraft are RENDERED instead of floating at the 3 km altitude
@@ -101,10 +104,6 @@ export const MODEL_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite Cesium heading 0
// Preserve the layer's amber identity while reducing the models' own colours
// to a weak diffuse hint, matching civilian launch presentation.
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
+5 -4
View File
@@ -11,7 +11,7 @@ import {
MIL_ICON_COLOR,
TRACKED_ICON_COLOR,
EMERGENCY_ICON_COLOR,
MODEL_COLOR_BLEND_AMOUNT,
MODEL_WHITE,
} from './policy.js';
import * as policy from './policy.js';
import { createAircraftModels } from '../../data/aircraftModelLayer.js';
@@ -34,7 +34,6 @@ export function createRendering({
const base = aircraftLayerModelSpec(meta);
spec = Object.freeze({
...base,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
});
// Not cached before the model set loads: the answer changes once it has.
@@ -62,11 +61,13 @@ export function createRendering({
const _iconKind = (icao24, klass) =>
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
/** Model tint, mirroring the billboard color rules (amber instead of cyan/white). */
/** Model colour: the mesh's own (white), tinted amber while tracked and red
* while broadcasting an emergency. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return TRACKED_ICON_COLOR;
return _fleetBillboardColor(icao24);
const info = flightState.records.data.get(icao24);
return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MODEL_WHITE;
}
/** Fleet (untracked) tint: red while the latest poll broadcast an emergency,
+340
View File
@@ -0,0 +1,340 @@
import { pointAtS } from '../../data/railPaths.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
import { displayMotion } from '../transit/movement.js';
/** Each line's read-only copy for a snapshot's `path.line` (lineOf). */
const lines = new WeakMap();
/**
* A line as a snapshot hands it out: a frozen copy of the layer's path, its
* number arrays frozen arrays, built once per line. `pointAtS` and
* `projectOnPath` read it as they read the path, and nothing written to it
* reaches the layer.
*/
function lineOf(path) {
let line = lines.get(path);
if (!line) {
const copy = {};
for (const [name, value] of Object.entries(path))
copy[name] = ArrayBuffer.isView(value)
? Object.freeze(Array.from(value))
: value;
line = Object.freeze(copy);
lines.set(path, line);
}
return line;
}
const NO_STOPS = Object.freeze([]);
/** Each stops list's frozen copy for a snapshot's `stops` (stopsOf). */
const stopLists = new WeakMap();
/** Whether `copy` still holds each of `list`'s stops, field by field. */
function sameStops(copy, list) {
if (copy.length !== list.length) return false;
for (let i = 0; i < list.length; i++) {
const stop = list[i];
const kept = copy[i];
if (
!stop ||
typeof stop !== 'object' ||
!kept ||
typeof kept !== 'object'
) {
if (!Object.is(stop, kept)) return false;
continue;
}
const names = Object.keys(stop);
if (names.length !== Object.keys(kept).length) return false;
for (const name of names)
if (!Object.is(stop[name], kept[name])) return false;
}
return true;
}
/**
* A trip's stops as a snapshot hands them out: a frozen array of frozen
* copies, kept per list the stops provider returns while that list still
* holds the same stops, so a provider that updates its list in place is
* copied again.
*/
function stopsOf(list) {
if (!Array.isArray(list)) return NO_STOPS;
let stops = stopLists.get(list);
if (!stops || !sameStops(stops, list)) {
stops = Object.freeze(
list.map((stop) =>
stop && typeof stop === 'object' ? Object.freeze({ ...stop }) : stop,
),
);
stopLists.set(list, stops);
}
return stops;
}
/**
* `previous` when it holds each of `next`'s values, else a frozen copy of
* `next`: a part of a snapshot that did not change is the one read before.
* `next` is a draft, filled again on every read.
*/
function reuse(previous, next) {
if (!previous) return Object.freeze({ ...next });
for (const name in next)
if (!Object.is(previous[name], next[name]))
return Object.freeze({ ...next });
return previous;
}
/**
* Read access to one train, and a hold on it for a first-person view.
*
* `getSelectedTrain()` and `getCockpitSubject()` describe the selected train
* and the held one as a frozen snapshot, read again on each call: where it is
* along its line, how fast it moves and how that is known, and its stops. A
* call while nothing in it changed returns the snapshot it returned before,
* and a part that did not change (its feed, its line, its stops) is the same
* object in the next one, so a view can read it on every frame. `path.line`
* is a frozen copy of the train's line for `pointAtS` and `projectOnPath`.
* `setCockpitSubject(key)` holds a train: its marker, 3D model, card and
* selected line are hidden, it stays selected (so its stops stay fresh and its feed stays
* polled at any distance) and clicks and Escape no longer change the
* selection. A held train keeps moving, hidden, and keeps the selection when
* its category is turned off, and is the copy of its train drawn though
* another feed's copy would outrank it (dedupe.js). Released, it is a train
* like any other: one in a category turned off is deselected and stops, and
* a better copy takes over at the next poll. The hold ends with
* `setCockpitSubject(null)`, and on its own when the train is removed or the
* layer is turned off. A train removed while held leaves its feed polled
* until the next `setCockpitSubject` call, so a view that waits for it holds
* it again if the feed lists it again.
* `focusTrain(key)` selects a train and hands it the camera, as a click does.
* A snapshot's `selectedAtMs` is when the user last selected the selected
* train (a click, or `focusTrain`), even again, for a view's entry to tell a
* re-selection. It is null for any other train, after a deselection, and for
* a train selected only by a hold: a hold is not a user's selection.
*
* @param {object} context The layer's state, parts, services and timetable.
* @returns {{methods: object}}
*/
export function createRailCockpitSubject({
state,
parts,
services,
timetable,
}) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
const scratch = {};
/** Each train's last snapshot, returned again while nothing in it changed. */
const views = new WeakMap();
/** The drafts trainView fills on every read (reuse). */
const draft = {
view: {},
feed: {},
position: {},
path: {},
motion: {},
provenance: {},
};
/** The catalog's public entry for a feed, else the registry's. */
function feedOf(feedId, previous) {
const listed = state._catalog?.find((feed) => feed.id === feedId);
const feed = listed ?? getRegisteredRailFeed(feedId);
if (!feed) return null;
const next = draft.feed;
next.id = feed.id;
next.name = feed.name ?? null;
next.operator = feed.operator ?? null;
next.region = feed.region ?? null;
next.positions = listed?.positions ?? feed.positions ?? 'gps';
next.tripUpdates =
typeof listed?.tripUpdates === 'boolean'
? listed.tripUpdates
: typeof feed.tripUpdatesUrl === 'string';
next.attribution = feed.attribution ?? null;
next.license = feed.license ?? null;
next.licenseUrl = feed.licenseUrl ?? null;
return reuse(previous, next);
}
/** The route's short (else long) name in the feed's timetable, or null. */
function routeNameOf(entry) {
const routeId = entry.record?.routeId;
if (!routeId) return null;
const schedule = timetable?.scheduleFor?.(entry.feedId);
const route = schedule?.routes?.[routeId];
const name = route?.short || route?.long;
return typeof name === 'string' && name ? name : null;
}
/**
* Which way the train runs along its shape: as its binding learnt it from
* successive reports, else from its drawn course against the line's
* bearing there; 0 while neither tells.
*/
function directionOf(entry) {
const binding = entry.path;
if (binding.direction === 1 || binding.direction === -1)
return binding.direction;
const course = finiteOrNull(entry.courseDeg);
const point = pointAtS(binding.path, binding.drawS, scratch);
if (course === null || !Number.isFinite(point?.bearingDeg)) return 0;
const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180);
return turn > 90 ? -1 : 1;
}
/** The train as a frozen snapshot (see the module comment), or null. */
function trainView(entry) {
if (!entry?.record) return null;
const previous = views.get(entry);
const record = entry.record;
const sample = entry.sample ?? null;
const drawn = entry.drawnHeight ?? null;
const binding = entry.path ?? null;
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const trip = state._selectedKey === entry.key ? state._trip : null;
const status = state._feedStatus.get(entry.feedId);
const position = draft.position;
position.latitude =
finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat;
position.longitude =
finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon;
position.railHeightM = Number.isFinite(drawn?.h) ? drawn.h - liftM : null;
position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0;
position.atMs = finiteOrNull(drawn?.at);
let path = null;
if (binding && binding.path) {
path = draft.path;
path.shapeIndex = binding.shapeIndex;
path.s = binding.drawS;
path.direction = directionOf(entry);
path.lengthM = binding.path.length;
path.via = binding.via;
path.builtAt = state._pathPacks.get(entry.feedId)?.pack?.builtAt ?? null;
path.line = lineOf(binding.path);
}
const motion = draft.motion;
motion.reportedSpeedMps = reported;
motion.derivedSpeedMps = derived;
motion.speedSource =
reported !== null ? 'reported' : derived !== null ? 'derived' : null;
motion.courseDeg = finiteOrNull(entry.courseDeg);
motion.phase = sample?.phase ?? null;
motion.word = displayMotion(entry, Date.now()).word;
motion.reportAgeMs = finiteOrNull(sample?.latestReportAgeMs);
motion.shownBehindMs = finiteOrNull(sample?.actualDelayMs);
motion.feedStale = status?.stale === true;
const provenance = draft.provenance;
provenance.positionSource = record.positionSource ?? 'gps';
provenance.timestampSource = record.timestampSource ?? null;
const view = draft.view;
view.key = entry.key;
view.feedId = entry.feedId;
view.selectedAtMs =
state._selectedKey === entry.key ? state._selectedAtMs : null;
view.id = String(record.id ?? '');
view.tripId = record.tripId || null;
view.routeId = record.routeId || null;
view.routeName = routeNameOf(entry);
view.label = record.label || null;
view.trainNumber = record.trainNumber || null;
view.headsign = trip?.headsign || null;
view.category = entry.category ?? null;
view.mode = entry.railMode ?? null;
view.feed = feedOf(entry.feedId, previous?.feed);
view.position = reuse(previous?.position, position);
view.path = path && reuse(previous?.path, path);
view.motion = reuse(previous?.motion, motion);
view.provenance = reuse(previous?.provenance, provenance);
view.stops = stopsOf(trip?.stops);
view.match = trip?.match ?? null;
const snapshot = reuse(previous, view);
views.set(entry, snapshot);
return snapshot;
}
/** A train's marker and playback again, after a hold on it began or ended. */
function replay(entry) {
parts.rendering.paint(entry);
parts.rendering.schedulePlayback(entry);
parts.rendering.syncRenderHold();
}
const methods = {
/** The selected train (see createRailCockpitSubject), or null. */
getSelectedTrain() {
return trainView(state._trains.get(state._selectedKey));
},
/** The held train, or null when none is held. */
getCockpitSubject() {
return trainView(state._trains.get(state._cockpitSubjectKey));
},
/**
* Hold the train `key` for a first-person view, or release the hold with
* null. A train it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a key the layer does not list. A listed
* train is held even when its category is off or another feed's copy
* is drawn: the held copy is then the one drawn. Releasing returns true.
*/
setCockpitSubject(key) {
const previous = state._trains.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
if (previous) {
// Its category turned off meanwhile: deselected, as the toggle
// does to any other train (controls.js).
if (
previous.key === state._selectedKey &&
state._categories[previous.category] === false
)
parts.selection.clearSelection();
replay(previous);
}
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
}
const entry = state._trains.get(key);
if (!entry) return false;
if (state._selectedKey !== key) {
parts.selection.selectTrain(key);
// A hold is not a selection the user made (selectedAtMs).
state._selectedAtMs = null;
}
state._cockpitSubjectKey = key;
state._cockpitLostFeedId = null;
// Another feed's copy drew it: the held copy is drawn now (dedupe.js).
if (entry.duplicate === true) parts.ingestion.duplicates?.refresh();
if (previous && previous !== entry) replay(previous);
replay(entry);
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
},
/**
* Select the train `key` and hand it the camera, as a click on it does.
* @param {string} key
* @returns {boolean} False for a train the layer does not show: gone, in
* a category turned off, or a copy another feed draws (dedupe.js).
*/
focusTrain(key) {
const entry = state._trains.get(key);
if (!entry || !parts.rendering.categoryShown(entry)) return false;
parts.selection.selectAndFocusTrain(key);
return true;
},
};
return { methods, trainView };
}
+513
View File
@@ -0,0 +1,513 @@
// The Rail layer's read API for a first-person view: the selected or held
// train as a snapshot (where it is along its line and which way it runs, its
// speed and how that is known, its feed's credit, its stops), and a hold that
// hides its marker and card, keeps it selected and ends when it goes.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
RAIL_POLL_MS,
STOP_REFRESH_MS,
railTrainFollowable,
railTrainKey,
} from './policy.js';
import {
BOSTON,
railLayerHarness as harness,
railTrain as train,
} from '../../testSupport/railLayerHarness.mjs';
import { RAIL_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
import { publicRailCatalog } from '../../data/railFeeds.js';
import { pointAtS } from '../../data/railPaths.js';
import { fleetModelFakes } from '../../testSupport/fleetModelFakes.mjs';
const M_PER_DEG = 111_320;
const LAT = 42.36;
const KX = M_PER_DEG * Math.cos((LAT * Math.PI) / 180);
const LON0 = -71.08;
/** A flat [lat, lon, ...] line due east from LON0, one vertex per 100 m. */
function eastLine(lengthM) {
const out = [];
for (let d = 0; d <= lengthM; d += 100) out.push(LAT, LON0 + d / KX);
return out;
}
const PACK = Object.freeze({
version: 1,
feedId: 'mbta-rail',
builtAt: '2026-09-09T00:00:00.000Z',
shapes: [eastLine(6000)],
dist: [[]],
shapeSources: ['operator'],
trips: { 'trip-T1': 0, 'trip-T2': 0 },
routes: { R1: [0] },
});
/** Two trains on the line, T1 running east and T2 west, a step a poll. */
async function onTheLine(t, options = {}) {
const app = harness(t, {
paths: { 'mbta-rail': PACK },
at: BOSTON,
...options,
});
let step = 0;
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + (1000 + step * 150) / KX, { speedMps: 15 }),
train('T2', LAT, LON0 + (5000 - step * 150) / KX),
]);
await app.enable();
for (let i = 0; i < 4; i += 1) {
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
}
return app;
}
/** Whether the selected train's route line is drawn: its live set's `show`. */
const routeShown = (app) =>
[...app.draw.sets.values()].find(
(set) =>
!set.disposed && set.kind === 'lines' && /:route:\d+$/.test(set.spec.id),
)?.show;
const T1 = railTrainKey('mbta-rail', 'T1');
const T2 = railTrainKey('mbta-rail', 'T2');
test('the selected train reads as a snapshot of its place, motion and sources', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected');
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, T1);
assert.equal(view.feedId, 'mbta-rail');
assert.equal(view.id, 'T1');
assert.equal(view.tripId, 'trip-T1');
assert.equal(view.routeId, 'R1');
assert.equal(view.category, 'regional');
assert.equal(view.mode, 'rail');
const listed = publicRailCatalog().find((feed) => feed.id === 'mbta-rail');
assert.equal(view.feed.attribution, listed.attribution);
assert.equal(view.feed.license, listed.license);
assert.equal(view.feed.licenseUrl, listed.licenseUrl);
assert.equal(view.feed.positions, 'gps');
assert.equal(view.path.shapeIndex, 0);
assert.equal(view.path.builtAt, PACK.builtAt);
assert.equal(view.path.via, 'trip');
assert.ok(Math.abs(view.path.lengthM - 6000) < 1);
assert.ok(view.path.s > 1000 && view.path.s < 2000, `s ${view.path.s}`);
assert.equal(view.path.direction, 1, 'runs along the shape');
assert.equal(typeof view.path.line.length, 'number');
assert.equal(view.motion.reportedSpeedMps, 15);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.equal(view.provenance.timestampSource, 'vehicle');
const drawn = app.entry(T1).drawnHeight;
assert.equal(view.position.railHeightM, drawn.h - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
assert.ok(Array.isArray(view.stops));
app.parts().selection.selectTrain(T2);
const west = app.layer.getSelectedTrain();
assert.equal(west.path.direction, -1, 'runs against the shape');
assert.equal(west.motion.reportedSpeedMps, null);
assert.equal(
west.motion.speedSource,
west.motion.derivedSpeedMps === null ? null : 'derived',
);
});
/** A trip's stops as a stops provider lists them. */
const stopList = (...names) =>
names.map((name, i) => ({
stopId: name,
name,
lat: LAT,
lon: LON0 + (i * 2000) / KX,
state: 'upcoming',
}));
test('a snapshot read again while nothing changed is the one read before', async (t) => {
let list = stopList('Alpha', 'Bravo', 'Charlie');
const app = await onTheLine(t, {
stops: { stopsFor: () => ({ stops: list, headsign: 'Charlie' }) },
});
app.parts().selection.selectTrain(T1);
const first = app.layer.getSelectedTrain();
assert.equal(app.layer.getSelectedTrain(), first, 'the same snapshot');
// Its stops are frozen copies of the provider's.
assert.equal(first.stops.length, 3);
assert.ok(Object.isFrozen(first.stops));
assert.ok(Object.isFrozen(first.stops[0]));
assert.notEqual(first.stops[0], list[0]);
assert.equal(first.stops[0].name, 'Alpha');
// It moves on: a new snapshot at its new place, what did not change kept.
app.run(RAIL_POLL_MS);
await app.poll();
app.run(RAIL_POLL_MS);
const moved = app.layer.getSelectedTrain();
assert.notEqual(moved, first, 'a new snapshot');
assert.ok(Object.isFrozen(moved) && Object.isFrozen(moved.path));
assert.ok(moved.path.s > first.path.s, 'at its new place');
assert.equal(moved.stops, first.stops, 'the same stops');
assert.equal(moved.feed, first.feed);
assert.equal(moved.provenance, first.provenance);
assert.equal(moved.path.line, first.path.line);
assert.equal(app.layer.getSelectedTrain(), moved);
// The provider lists other stops: new ones.
list = stopList('Delta', 'Echo');
app.run(STOP_REFRESH_MS);
const later = app.layer.getSelectedTrain();
assert.notEqual(later.stops, first.stops);
assert.deepEqual(
later.stops.map((stop) => stop.name),
['Delta', 'Echo'],
);
// A provider that updates its list in place: the stops are copied again.
list[0].state = 'passed';
app.run(STOP_REFRESH_MS);
const updated = app.layer.getSelectedTrain();
assert.notEqual(updated.stops, later.stops);
assert.equal(updated.stops[0].state, 'passed');
assert.equal(app.layer.getSelectedTrain().stops, updated.stops);
});
test('a snapshot’s line is a frozen copy: writing to it leaves the layer’s line', async (t) => {
const app = await onTheLine(t);
app.parts().selection.selectTrain(T1);
const { line, s } = app.layer.getSelectedTrain().path;
const own = app.entry(T1).path.path;
assert.notEqual(line, own, 'not the layer’s own');
assert.ok(Object.isFrozen(line));
for (const name of ['lat', 'lon', 'x', 'y', 's', 'box'])
assert.ok(Object.isFrozen(line[name]), name);
const lat = own.lat[1];
assert.throws(() => {
line.lat[1] = 0;
}, TypeError);
assert.equal(own.lat[1], lat, 'the layer’s line is as it was');
assert.deepEqual(pointAtS(line, s), pointAtS(own, s), 'it reads the same');
// Copied once per line: T2 runs on the same one.
app.parts().selection.selectTrain(T2);
assert.equal(app.layer.getSelectedTrain().path.line, line);
});
test('a held train hides its marker and card and keeps the selection', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.setCockpitSubject('rail:mbta-rail:nope'), false);
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._selectedKey, T1, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, T1);
app.run(1000);
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.entry(T2).marker.show, true);
// From inside the train its selected line would run under the eye.
assert.equal(routeShown(app), false, 'no line');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// Escape is the view's while it holds the train.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, T1);
// It still moves.
const before = app.layer.getCockpitSubject().path.s;
app.run(RAIL_POLL_MS);
await app.poll();
app.run(RAIL_POLL_MS);
assert.ok(app.layer.getCockpitSubject().path.s > before, 'still moving');
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
app.run(1000);
assert.equal(app.entry(T1).marker.show, true);
assert.equal(routeShown(app), true, 'the line is back');
assert.equal(
(app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? []).length,
1,
'the card is back',
);
});
test('a held train draws no 3D model either; let go, its model draws again', async (t) => {
const models = await fleetModelFakes();
const app = await onTheLine(t, { fleet: models.fleet, altitude: 1_000 });
models.watch(app.draw);
// A model's load answers off the frame; the next frames place it.
const frames = async () => {
app.run(500);
models.load();
await app.settle();
app.run(500);
};
await frames();
assert.equal(models.drawn(T1).length, 1, 'near the camera: its model');
assert.equal(app.entry(T1).modelOwnsVisual, true);
assert.equal(app.entry(T1).marker.show, false, 'its icon hands over');
assert.equal(app.layer.setCockpitSubject(T1), true);
app.run(250);
// The view's eye is inside the train.
assert.equal(models.drawn(T1).length, 0, 'no model');
assert.equal(app.entry(T1).modelOwnsVisual, false);
assert.equal(app.entry(T1).marker.show, false, 'and no icon');
assert.equal(models.drawn(T2).length, 1, 'another train keeps its model');
await frames();
assert.equal(models.drawn(T1).length, 0, 'not on a later frame either');
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.layer.setCockpitSubject(null), true);
await frames();
assert.equal(models.drawn(T1).length, 1, 'let go: its model again');
assert.equal(app.entry(T1).modelOwnsVisual, true);
assert.equal(app.entry(T1).marker.show, false);
});
const MADRID = { lat: 40.4168, lon: -3.7038 };
test('a held train stays the copy drawn when another feed’s copy outranks it, and keeps moving', async (t) => {
const app = harness(t, { at: MADRID });
// One Alvia in two feeds: a station-event copy, held, and a poll later a
// GPS copy that would outrank it.
let step = 0;
let gpsCopy = false;
const lat = (offset) => MADRID.lat + offset + step * 0.003;
app.feeds.set('renfe-cercanias', () => [
train('A1', lat(0), MADRID.lon, {
label: 'ALVIA 4073',
positionSource: 'event',
}),
]);
app.feeds.set('renfe-larga-distancia', () =>
gpsCopy ? [train('B1', lat(0.01), MADRID.lon, { label: '4073' })] : [],
);
await app.enable();
const a = railTrainKey('renfe-cercanias', 'A1');
const b = railTrainKey('renfe-larga-distancia', 'B1');
for (let i = 0; i < 12 && !railTrainFollowable(app.entry(a)); i += 1) {
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.ok(railTrainFollowable(app.entry(a)), 'the train is moving');
assert.equal(app.layer.setCockpitSubject(a), true);
gpsCopy = true;
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
// The view knows the train by its key, and the copies stand apart: the
// held copy stays drawn and selected, the other is the one hidden.
assert.equal(app.layer.getCockpitSubject()?.key, a);
assert.equal(app.state()._selectedKey, a);
assert.equal(app.entry(a).duplicate, false);
assert.equal(app.entry(b).duplicate, true);
assert.equal(app.entry(a).marker.show, false);
assert.equal(app.entry(b).marker.show, false, 'no other marker on it');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// It moves between polls, frame by frame.
assert.ok(app.state()._moving.has(app.entry(a)), 'still playing');
const before = app.layer.getCockpitSubject().position.latitude;
app.run(2000);
assert.ok(
app.layer.getCockpitSubject().position.latitude > before,
'still moving',
);
// Let go: the better copy takes over at the next poll, with the selection.
app.layer.setCockpitSubject(null);
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
assert.equal(app.entry(a).duplicate, true);
assert.equal(app.entry(b).duplicate, false);
assert.equal(app.state()._selectedKey, b);
assert.equal(app.entry(b).marker.show, true);
assert.equal(
(app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? []).length,
1,
'its card',
);
// The copy hidden is not focused: the selection stays on the one drawn.
assert.equal(app.layer.focusTrain(a), false);
assert.equal(app.state()._selectedKey, b);
// A hold of the copy hidden draws it at once, in place of the other.
assert.equal(app.layer.setCockpitSubject(a), true);
assert.equal(app.state()._selectedKey, a);
assert.equal(app.entry(a).duplicate, false);
assert.equal(app.entry(b).duplicate, true);
assert.equal(app.entry(b).marker.show, false);
assert.ok(app.state()._moving.has(app.entry(a)), 'playing');
});
test('a held train keeps the selection and moves, hidden, when its category is turned off', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.run(1000);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing');
app.layer.setParams({ regional: false });
assert.equal(app.state()._selectedKey, T1, 'still selected');
assert.equal(app.layer.getCockpitSubject()?.key, T1);
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.entry(T2).marker.show, false, 'its category is hidden');
assert.equal(routeShown(app), false, 'no line');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// It moves between polls, frame by frame.
assert.ok(app.state()._moving.has(app.entry(T1)), 'still playing');
const before = app.layer.getCockpitSubject().path.s;
app.run(2000);
assert.ok(app.layer.getCockpitSubject().path.s > before, 'still moving');
assert.equal(app.entry(T1).marker.show, false, 'and still hidden');
// Let go: a train of a hidden category, deselected and stopped as the
// toggle would have left it.
app.layer.setCockpitSubject(null);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._moving.has(app.entry(T1)), false);
assert.equal(app.entry(T1).marker.show, false);
const parked = app.entry(T1).path.drawS;
app.run(2000);
assert.equal(app.entry(T1).path.drawS, parked, 'stopped');
// Held again, hidden, it plays at once; let go, it stops again.
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing at once');
app.layer.setCockpitSubject(null);
assert.equal(app.state()._moving.has(app.entry(T1)), false);
// Shown again, it is drawn and moves as any other.
app.layer.setParams({ regional: true });
assert.equal(app.entry(T1).marker.show, true);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing again');
});
test('a ride let go with restore does not focus a train its category hides', async (t) => {
const app = await onTheLine(t);
// The documented provider: hold on entry; on exit, release, then focus
// the train again when asked to restore.
assert.equal(app.layer.setCockpitSubject(T1), true);
app.layer.setParams({ regional: false });
app.layer.setCockpitSubject(null);
assert.equal(app.layer.focusTrain(T1), false, 'not drawn');
assert.equal(app.state()._selectedKey, null, 'not selected');
assert.equal(app.parts().follow.stats(), null, 'not followed');
assert.equal(app.viewer.trackedEntity, undefined);
assert.equal(app.focusRequests.length, 0, 'not flown to');
assert.equal(app.entry(T1).marker.show, false);
// Shown again, it focuses as before.
app.layer.setParams({ regional: true });
assert.equal(app.layer.focusTrain(T1), true);
assert.equal(app.state()._selectedKey, T1);
assert.ok(app.parts().follow.isFollowing(T1), 'the camera is handed to it');
});
test('a held train that goes takes the hold with it; focusTrain selects', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.feeds.set('mbta-rail', () => [train('T2', LAT, LON0 + 4000 / KX)]);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.focusTrain(T1), false);
assert.equal(app.layer.focusTrain(T2), true);
assert.equal(app.state()._selectedKey, T2);
});
test('a held train its feed drops leaves the feed polled until the view lets go', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
// From the cab the camera looks along the ground, here past the feed's range.
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._heldFeedId, 'mbta-rail', 'held for the train');
const others = () => [train('T2', LAT, LON0 + 4000 / KX)];
app.feeds.set('mbta-rail', others);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
await app.recheck();
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'its feed is polled');
await app.moveCamera({ lat: 40.72, lon: -74.0 });
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'whatever the camera');
// Listed again: the view holds it again.
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + 2500 / KX, { speedMps: 15 }),
...others(),
]);
app.run(RAIL_POLL_MS);
await app.poll();
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.state()._selectedKey, T1);
// Let go, and the feed is the viewport's again: out of range, released.
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.setCockpitSubject(null);
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._activeFeeds.has('mbta-rail'), false);
assert.equal(app.state()._trains.size, 0);
});
test('selectedAtMs is the user’s selection time, never a hold’s or another train’s', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.focusTrain(T1), true);
const first = app.layer.getSelectedTrain().selectedAtMs;
assert.ok(Number.isFinite(first), 'a click or focusTrain stamps it');
// Selected again: a later stamp.
app.run(1000);
app.layer.focusTrain(T1);
assert.ok(app.layer.getSelectedTrain().selectedAtMs > first);
// A hold of another train is not the user's selection.
app.layer.setCockpitSubject(T2);
assert.equal(app.layer.getCockpitSubject().key, T2);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
app.layer.setCockpitSubject(null);
// Nor after a deselection (Escape), then a hold.
app.layer.focusTrain(T1);
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._selectedAtMs, null, 'deselection clears it');
app.layer.setCockpitSubject(T2);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
// Releasing twice is harmless: the selection stays.
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.state()._selectedKey, T2);
assert.equal(app.layer.getCockpitSubject(), null);
});
test('turning the layer off ends the hold', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.disable(app.viewer);
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+7 -1
View File
@@ -91,7 +91,13 @@ export function createControls({ state, parts, timetable }) {
return true;
state._categories = next;
const selected = state._trains.get(state._selectedKey);
if (selected && next[selected.category] === false)
// A held train keeps the selection until its view lets it go
// (cockpitSubject.js).
if (
selected &&
next[selected.category] === false &&
selected.key !== state._cockpitSubjectKey
)
parts.selection.clearSelection();
parts.rendering.applyCategoryVisibility();
state._revision += 1;
+14 -5
View File
@@ -25,9 +25,13 @@ import { greatCircleKm } from '../../geoDistance.js';
* 2. the line: a copy bound to its operator's shape (a built pack), then
* one without.
* The copy drawn stays drawn until another scores strictly higher, so equal
* copies never trade places. A losing copy keeps its playback and is only
* hidden; when a feed leaves the viewport its copies' partners come back.
* The comparison runs once per poll, never per frame.
* copies never trade places. A copy a first-person view holds
* (cockpitSubject.js) stays drawn whatever the scores until the view lets
* go: the view knows the train by that copy's key and rides it where that
* copy's feed puts it, tens of kilometres from another feed's copy at
* times. A losing copy keeps its playback and is only hidden; when a feed
* leaves the viewport its copies' partners come back. The comparison runs
* once per poll, never per frame.
*/
/**
@@ -288,10 +292,12 @@ function better(a, b) {
* scores strictly higher.
* @param {object[][]} groups From matchCopies.
* @param {Map<string, string>} [previous] copy key → key drawn last time.
* @param {string|null} [held] A copy drawn whatever the scores: the train a
* first-person view holds.
* @returns {{winners: Map<string, string>, hidden: Set<string>}}
* `winners`: every grouped copy's key → the key drawn for its train.
*/
export function chooseCopies(groups, previous = new Map()) {
export function chooseCopies(groups, previous = new Map(), held = null) {
const winners = new Map();
const hidden = new Set();
for (const group of groups) {
@@ -305,6 +311,7 @@ export function chooseCopies(groups, previous = new Map()) {
scored.reduce((a, b) => (better(b.score, a.score) ? b : a));
for (const candidate of scored)
if (better(candidate.score, best.score)) best = candidate;
best = scored.find(({ copy }) => copy.key === held) ?? best;
for (const { copy } of scored) {
winners.set(copy.key, best.copy.key);
if (copy.key !== best.copy.key) hidden.add(copy.key);
@@ -318,7 +325,8 @@ export function chooseCopies(groups, previous = new Map()) {
* loaded feed carries, marks the copies not drawn (`entry.duplicate`), and
* moves a selection that sat on a copy now hidden to the copy drawn, so the
* card follows the same physical train (its feed line names the new
* source).
* source). A held copy is never the one hidden, so the hold and the
* selection stay on it.
* @param {{state: object, parts: object,
* defer?: (fn: Function) => unknown}} context
*/
@@ -355,6 +363,7 @@ export function createDuplicateFilter({
const { winners, hidden } = chooseCopies(
matchCopies(entries.map(copyOf)),
previous,
state._cockpitSubjectKey ?? null,
);
previous = winners;
for (const entry of entries) {
+26
View File
@@ -252,6 +252,32 @@ test('the filter hides the weaker copy and the selection follows its train', ()
assert.deepEqual(filter.stats(), { groups: 0, hidden: 0 });
});
test('a copy a first-person view holds stays drawn, with the selection', () => {
const pair = [
copy('a', 'f1', { number: '160', position: 'event' }),
copy('b', 'f2', { number: '160', position: 'gps' }),
];
assert.equal(chooseCopies([pair]).winners.get('a'), 'b');
const held = chooseCopies([pair], new Map(), 'a');
assert.equal(held.winners.get('b'), 'a', 'drawn whatever the scores');
assert.deepEqual([...held.hidden], ['b']);
// Let go, the better copy takes over.
assert.equal(chooseCopies([pair], held.winners).winners.get('a'), 'b');
const layer = fakeLayer({ selected: 'feed-a:v160' });
layer.state._cockpitSubjectKey = 'feed-a:v160';
const filter = createDuplicateFilter({ ...layer, defer: (fn) => fn() });
filter.refresh();
const [unbound, operator] = layer.trains;
assert.equal(unbound.duplicate, false, 'the held copy');
assert.equal(operator.duplicate, true);
assert.deepEqual(layer.calls.selected, [], 'the selection stays on it');
layer.state._cockpitSubjectKey = null;
filter.refresh();
assert.equal(unbound.duplicate, true);
assert.deepEqual(layer.calls.selected, [operator.key]);
});
test('a short number after a local product names a line, not a train (S1, RB 1, U6)', () => {
for (const label of ['S1', 'RB 1', 'U6', 'S 12', 'RE5'])
assert.equal(recordTrainNumber({ label }), null, label);
+15
View File
@@ -7,6 +7,7 @@ import { createIngestion } from './ingestion.js';
import { createViewport } from './viewport.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createRailCockpitSubject } from './cockpitSubject.js';
import { createRouteDisplay } from './routeDisplay.js';
import { createRailSchedules } from './schedules.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
@@ -85,12 +86,24 @@ function createState({ services }) {
_stopAnchors: new Map(),
_categories: { ...DEFAULT_RAIL_CATEGORY_VISIBILITY },
_selectedKey: null,
/** When the user last selected a train, even the selected one (ms). */
_selectedAtMs: null,
_selectedCardAt: 0,
_selectedCardText: null,
/** The camera's follow of the selected train (follow.js), or null. */
_follow: null,
/** A feed polled only for the selected train (viewport.js), or null. */
_heldFeedId: null,
/**
* The train a first-person view holds (cockpitSubject.js), or null: its
* marker, 3D model and card are hidden and the selection stays on it.
*/
_cockpitSubjectKey: null,
/**
* The feed of a held train the feed dropped (ingestion.js), polled until
* the view takes a train again or lets go (cockpitSubject.js), or null.
*/
_cockpitLostFeedId: null,
_revision: 0,
_controlsListener: null,
_dataManager: null,
@@ -182,11 +195,13 @@ export function createRailLayer({
parts.ingestion = createIngestion(context);
parts.viewport = createViewport(context);
parts.lifecycle = createLifecycle(context);
parts.cockpit = createRailCockpitSubject(context);
return Object.assign(
{ updateInterval: RAIL_POLL_MS },
parts.lifecycle.methods,
parts.controls.methods,
parts.cockpit.methods,
{
/** Test seams: this instance's own state and parts. */
_railStateForTest: () => state,
+7
View File
@@ -69,6 +69,13 @@ export function createIngestion({ state, services, parts, source }) {
function removeTrain(key) {
const entry = state._trains.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js); its
// feed stays polled until the view lets go, so the train is found again
// if the feed lists it again.
if (state._cockpitSubjectKey === key) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = entry.feedId;
}
if (state._selectedKey === key) parts.selection.clearSelection();
parts.rendering.removeMarker(entry);
entry.marker = null;
+2
View File
@@ -94,6 +94,8 @@ export function createLifecycle({ state, services, parts, timetable }) {
parts.ingestion.abortAllInFlight();
state._activeFeeds.clear();
state._heldFeedId = null;
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
state._feedStatus.clear();
dropAllTrains();
parts.rendering.stopModels();
+29
View File
@@ -47,11 +47,31 @@ export function pathWindowM(dtMs) {
return window > PATH_WINDOW_MAX_M ? NaN : window;
}
/** Arc moved between two reports before it says which way a train runs (m). */
const DIRECTION_MIN_M = 1;
/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */
function directionOf(step, known) {
return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M
? Math.sign(step)
: known;
}
function createBinding(shapeIndex, path, via, s, fix) {
return {
shapeIndex,
path,
via,
/**
* Which way the drawn train runs along the shape: +1 along it, -1
* against it, 0 until two reports or a playback segment tell. Kept until
* a rebind. Once playback has placed the train, only playback changes
* it: the newest reports run ahead of the drawn train, so a reversal
* they show turns it when playback reaches it.
*/
direction: 0,
/** The direction the last placed playback segment ran, 0 before one. */
drawDirection: 0,
/** Arc and time of the newest report. */
fixS: s,
fixT: fix.t,
@@ -139,6 +159,8 @@ export function followFix(binding, fix) {
pathWindowM(fix.t - binding.fixT),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
if (!binding.drawDirection)
binding.direction = directionOf(hit.s - binding.fixS, binding.direction);
binding.fixS = hit.s;
binding.fixT = fix.t;
binding.fixLat = fix.lat;
@@ -230,6 +252,13 @@ export function placeOnPath(binding, sample, segment, out) {
cache.sFrom = sFrom;
cache.sTo = sTo;
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok) {
binding.drawDirection = directionOf(
sTo - sFrom,
binding.drawDirection || binding.direction || 0,
);
binding.direction = binding.drawDirection;
}
}
if (!cache.ok) return false;
const f = Number.isFinite(sample.fraction)
+61
View File
@@ -201,3 +201,64 @@ test('a segment whose reports do not fit the line keeps the straight line', () =
assert.equal(placeOnPath(binding, stale.sample, stale.segment, out), false);
assert.equal(placeOnPath(null, stale.sample, stale.segment, out), false);
});
test('a binding learns which way its train runs, and keeps it through a stop', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const along = bindTrainPath(p, ids, fix(0, 500, 0));
assert.equal(along.direction, 0, 'one report tells no direction');
assert.ok(followFix(along, fix(10_000, 700, 0)));
assert.equal(along.direction, 1);
// Standing still (under a metre) keeps what it learnt.
assert.ok(followFix(along, fix(20_000, 700.4, 0)));
assert.equal(along.direction, 1);
const against = bindTrainPath(p, ids, fix(0, 1500, 0));
assert.ok(followFix(against, fix(10_000, 1200, 0)));
assert.equal(against.direction, -1);
// A playback segment between two reports tells it too.
const played = bindTrainPath(p, ids, fix(0, 300, 0));
const segment = {
from: { seq: 1, ...fix(0, 300, 0) },
to: { seq: 2, ...fix(10_000, 100, 0) },
};
assert.ok(
placeOnPath(played, { fromSeq: 1, toSeq: 2, fraction: 0.5 }, segment, {}),
);
assert.equal(played.direction, -1);
// A rebind starts again.
const rebound = rebindTrainPath(
p,
{ routeId: 'main' },
along,
fix(30_000, 2000, -300),
);
assert.equal(rebound?.direction ?? 0, 0);
});
test('a report that runs back turns the drawn train only when playback does', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const binding = bindTrainPath(p, ids, fix(0, 300, 0));
const forward = {
from: { seq: 1, ...fix(0, 300, 0) },
to: { seq: 2, ...fix(10_000, 500, 0) },
};
const sample = (fraction) => ({ fromSeq: 1, toSeq: 2, fraction });
assert.ok(placeOnPath(binding, sample(0.2), forward, {}));
assert.equal(binding.direction, 1);
// The newest report lies behind the last one (a reversal, or GPS jitter)
// while playback still draws the forward segment.
assert.ok(followFix(binding, fix(10_000, 500, 0)));
assert.ok(followFix(binding, fix(20_000, 450, 0)));
assert.ok(placeOnPath(binding, sample(0.6), forward, {}));
assert.equal(binding.direction, 1, 'the drawn train still runs forward');
// Playback reaches the reversed segment: now it turns.
const back = {
from: { seq: 2, ...fix(10_000, 500, 0) },
to: { seq: 3, ...fix(20_000, 450, 0) },
};
assert.ok(
placeOnPath(binding, { fromSeq: 2, toSeq: 3, fraction: 0.5 }, back, {}),
);
assert.equal(binding.direction, -1);
});
+23 -5
View File
@@ -693,9 +693,25 @@ export function createRendering({ state, services, parts }) {
);
}
/** Whether a train's icon is drawn: shown, and not drawn by its model. */
/**
* Whether a train's icon is drawn: shown, not drawn by its model, and no
* first-person view rides it (cockpitSubject.js). A held train keeps its
* playback; only its icon and model hide.
*/
function markerShown(entry) {
return categoryShown(entry) && !entry.modelOwnsVisual;
return (
categoryShown(entry) &&
!entry.modelOwnsVisual &&
entry.key !== state._cockpitSubjectKey
);
}
/**
* Whether the train's playback runs: it is drawn, or a first-person view
* rides it, which keeps it moving, hidden, in a category turned off.
*/
function playing(entry) {
return categoryShown(entry) || entry.key === state._cockpitSubjectKey;
}
/**
@@ -781,7 +797,7 @@ export function createRendering({ state, services, parts }) {
place(entry);
const sample = entry.sample;
const moving =
categoryShown(entry) &&
playing(entry) &&
sample?.phase === 'playing' &&
sample.segmentSpeedMps > 0;
if (moving) {
@@ -789,7 +805,7 @@ export function createRendering({ state, services, parts }) {
return;
}
state._moving.delete(entry);
if (categoryShown(entry) && Number.isFinite(sample?.nextWakeMonoMs)) {
if (playing(entry) && Number.isFinite(sample?.nextWakeMonoMs)) {
entry.wakeTimer = setTimeout(
() => {
entry.wakeTimer = null;
@@ -920,7 +936,9 @@ export function createRendering({ state, services, parts }) {
}
item.position = entry.marker.position;
item.headingDeg = Number.isFinite(entry.courseDeg) ? entry.courseDeg : 0;
item.show = categoryShown(entry);
// A train a first-person view rides draws no model: the camera is inside
// it (cockpitSubject.js).
item.show = categoryShown(entry) && entry.key !== state._cockpitSubjectKey;
return item;
}
+19
View File
@@ -378,10 +378,28 @@ export function createRouteDisplay({
updateSplit();
}
/**
* Show the selected line unless a first-person view rides its train
* (cockpitSubject.js): from inside the train it would run up the middle of
* the view and under the eye.
*/
function applyHold() {
if (!state._route || !routeSet) return;
const shown = !(
state._cockpitSubjectKey !== null &&
state._cockpitSubjectKey === state._selectedKey
);
if (routeSet.show !== shown) {
routeSet.show = shown;
governorRequestRender('rail-route');
}
}
/** Move the travelled/ahead split to where the train is drawn now. */
function updateSplit() {
const route = state._route;
if (!route) return;
applyHold();
const binding = route.binding;
const s = binding ? binding.drawS : NaN;
if (route.direction === 0 && Number.isFinite(s)) {
@@ -732,6 +750,7 @@ export function createRouteDisplay({
applyNetwork,
onCamera,
syncRoute,
applyHold,
refreshStops,
cullStops,
onSelectionChanged,
+17
View File
@@ -34,6 +34,16 @@ export function createSelection({ state, services, parts }) {
function refreshSelectedCard(force) {
const entry = state._trains.get(state._selectedKey);
if (!entry) return;
// A train a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.setEntries(
RAIL_SELECTED_OVERLAY_SOURCE_ID,
[],
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -102,6 +112,8 @@ export function createSelection({ state, services, parts }) {
*/
function selectAndFocusTrain(key) {
if (!state._trains.has(key)) return;
// A selection by the user, even of the selected train (cockpitSubject.js).
state._selectedAtMs = Date.now();
const following = parts.follow.isFollowing(key);
// Another train's follow lets go first, so this is never taken for a
// move between two copies of one train.
@@ -119,6 +131,7 @@ export function createSelection({ state, services, parts }) {
const hadSelection = state._selectedKey !== null;
parts.follow.release({ untrack });
state._selectedKey = null;
state._selectedAtMs = null;
state._selectedCardText = null;
if (hadSelection) {
parts.rendering.paintAll();
@@ -135,6 +148,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the train, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -156,6 +171,8 @@ export function createSelection({ state, services, parts }) {
// and skips it while a tool holds the pointer.
state._clickSubscription = inputFor(viewer).onClick((event) => {
if (!state._enabled) return;
// A held train keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const key = trainKeyOf(event.drawHit);
if (key) selectAndFocusTrain(key);
else if (state._selectedKey) clearSelection();
+6
View File
@@ -155,6 +155,12 @@ export function createViewport({ state, services, parts, source }) {
))
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
// A first-person view whose train its feed dropped keeps the feed polled
// until it lets go (cockpitSubject.js): from the cab the camera looks
// along the ground, often at a point beyond the feed's range.
const lost = state._cockpitLostFeedId;
if (lost && !desired.has(lost) && state._activeFeeds.has(lost))
desired.set(lost, state._activeFeeds.get(lost));
// The selected train's feed stays polled however far out or away the
// camera goes, so the train and its line stay on the map; while nothing
// else would keep the feed, it carries the selected train alone and its
+237
View File
@@ -0,0 +1,237 @@
import { toCartographicRadians } from '../../geo/ellipsoid.js';
import {
getRegisteredTransitFeed,
transitRouteLabel,
} from '../../data/transitFeeds.js';
import { displayMotion } from './movement.js';
/**
* `previous` when it holds each of `next`'s values, else a frozen copy of
* `next`: a part of a snapshot that did not change is the one read before.
* `next` is a draft, filled again on every read.
*/
function reuse(previous, next) {
if (!previous) return Object.freeze({ ...next });
for (const name in next)
if (!Object.is(previous[name], next[name]))
return Object.freeze({ ...next });
return previous;
}
/**
* Read access to one vehicle, and a hold on it for a first-person view.
*
* `getSelectedVehicle()` and `getCockpitSubject()` describe the selected
* vehicle and the held one as a frozen snapshot, read again on each call:
* where it is drawn, how fast it moves and how that is known. A call while
* nothing in it changed returns the snapshot it returned before, and a part
* that did not change (its feed, its stop) is the same object in the next
* one, so a view can read it on every frame. Transit has no route shapes or
* stops, so a snapshot names only the vehicle's last reported stop.
* `setCockpitSubject(key)` holds a vehicle: its sprite, 3D model, card,
* trail and detection box are hidden, it keeps moving when it is out of the camera's
* view, its feed stays polled, and clicks and Escape no longer change the
* selection. The hold ends with `setCockpitSubject(null)`, and on
* its own when the vehicle is removed or the layer is turned off.
* `focusVehicle(key)` selects a vehicle, as a click does. A snapshot's
* `selectedAtMs` is when the user last selected the selected vehicle (a
* click, or `focusVehicle`), even again. It is null for any other vehicle,
* after a deselection, and for a vehicle selected only by a hold: a hold is
* not a user's selection.
*
* @param {object} context The layer's state, parts and services.
* @returns {{methods: object}}
*/
export function createTransitCockpitSubject({ state, parts, services }) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
/** Each vehicle's last snapshot, returned again while nothing changed. */
const views = new WeakMap();
/** The drafts vehicleView fills on every read (reuse). */
const draft = {
view: {},
feed: {},
position: {},
motion: {},
stop: {},
provenance: {},
};
/** The feed in use, else the registry's entry for it. */
function feedEntry(feedId) {
return state._activeFeeds.get(feedId) || getRegisteredTransitFeed(feedId);
}
function feedOf(feed, previous) {
if (!feed) return null;
const next = draft.feed;
next.id = feed.id;
next.name = feed.name ?? null;
next.operator = feed.operator ?? null;
next.region = feed.region ?? null;
next.attribution = feed.attribution ?? null;
next.license = feed.license ?? null;
next.licenseUrl = feed.licenseUrl ?? null;
return reuse(previous, next);
}
/**
* The floor under the vehicle where playback draws it, without the shared
* lift: the drawn marker's height while the frame pass places it (in view,
* or held), which near the ground follows the terrain between reports;
* else its segment's two reports' floors at the playback fraction. Null
* while either floor is unknown, as on cold terrain, so a view waits for
* the surface. Not `entry.heightM`, the floor at the newest report, which
* playback has not reached yet.
*/
function drawnFloorOf(entry) {
const segment = entry.segment;
if (!segment || entry.heightPending) return null;
const placed =
entry.surfaceReady === true &&
entry.hasRendered &&
entry.marker?.position &&
(state._visible.has(entry) || entry.key === state._cockpitSubjectKey);
if (placed) {
const drawn = toCartographicRadians(entry.marker.position);
if (drawn) return drawn.height - liftM;
}
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const f = Number.isFinite(segment.fraction)
? Math.max(0, Math.min(1, segment.fraction))
: 1;
return from + (to - from) * f - liftM;
}
/** The vehicle as a frozen snapshot (see the module comment), or null. */
function vehicleView(entry) {
if (!entry?.record) return null;
const previous = views.get(entry);
const record = entry.record;
const sample = entry.sample ?? null;
const feed = feedEntry(entry.feedId);
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const status = state._feedStatus.get(entry.feedId);
const position = draft.position;
position.latitude = finiteOrNull(sample?.lat) ?? record.lat;
position.longitude = finiteOrNull(sample?.lon) ?? record.lon;
position.groundHeightM = drawnFloorOf(entry);
position.atMs = finiteOrNull(sample?.displayT);
const motion = draft.motion;
motion.reportedSpeedMps = reported;
motion.derivedSpeedMps = derived;
motion.speedSource =
reported !== null ? 'reported' : derived !== null ? 'derived' : null;
motion.courseDeg = finiteOrNull(entry.courseDeg);
motion.reportedBearingDeg = finiteOrNull(record.bearing);
motion.segmentCourseDeg = finiteOrNull(sample?.segmentCourseDeg);
motion.phase = sample?.phase ?? null;
motion.word = displayMotion(entry, Date.now()).word;
motion.reportAgeMs = finiteOrNull(sample?.latestReportAgeMs);
motion.shownBehindMs = finiteOrNull(sample?.actualDelayMs);
motion.feedStale = status?.stale === true;
const stop = draft.stop;
stop.stopId = record.stopId || null;
stop.status = record.status || null;
const provenance = draft.provenance;
provenance.positionSource = 'gps';
provenance.timestampSource = record.timestampSource ?? null;
const view = draft.view;
view.key = entry.key;
view.feedId = entry.feedId;
view.selectedAtMs =
state._selectedKey === entry.key ? state._selectedAtMs : null;
view.id = String(record.id ?? '');
view.routeId = record.routeId || null;
view.routeLabel =
(feed && record.routeId
? transitRouteLabel(feed, record.routeId)
: null) || null;
view.tripId = record.tripId || null;
view.directionId = record.directionId ?? null;
view.label = record.label || null;
view.mode = entry.mode ?? null;
view.modeInferred = entry.modeInferred === true;
view.feed = feedOf(feed, previous?.feed);
view.position = reuse(previous?.position, position);
view.motion = reuse(previous?.motion, motion);
view.stop = reuse(previous?.stop, stop);
view.provenance = reuse(previous?.provenance, provenance);
const snapshot = reuse(previous, view);
views.set(entry, snapshot);
return snapshot;
}
/** Show or hide a vehicle's sprite and trail for the hold. */
function repaint(entry) {
if (!entry?.marker) return;
if (entry.key === state._cockpitSubjectKey) entry.marker.show = false;
else parts.rendering.placeSample(entry);
parts.rendering.schedulePlayback(entry);
parts.trails.update();
state._detectRevision += 1;
}
const methods = {
/** The selected vehicle (see createTransitCockpitSubject), or null. */
getSelectedVehicle() {
return vehicleView(state._vehicles.get(state._selectedKey));
},
/** The held vehicle, or null when none is held. */
getCockpitSubject() {
return vehicleView(state._vehicles.get(state._cockpitSubjectKey));
},
/**
* Hold the vehicle `key` for a first-person view, or release the hold
* with null. A vehicle it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
setCockpitSubject(key) {
const previous = state._vehicles.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
// The hold kept it in play out of view: it leaves until the next
// visibility sweep finds it in view again.
if (previous) {
state._visible.delete(previous);
parts.rendering.requestVisibility();
}
repaint(previous);
parts.selection.refreshSelectedCard(true);
return true;
}
const entry = state._vehicles.get(key);
if (!entry?.marker) return false;
if (state._selectedKey !== key) parts.selection.selectVehicle(key);
state._cockpitSubjectKey = key;
state._visible.add(entry);
if (previous && previous !== entry) repaint(previous);
repaint(entry);
parts.selection.refreshSelectedCard(true);
return true;
},
/**
* Select the vehicle `key`, as a click on it does.
* @param {string} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
focusVehicle(key) {
if (!state._vehicles.get(key)?.marker) return false;
parts.selection.selectVehicle(key, { byUser: true });
return true;
},
};
return { methods, vehicleView };
}
+3
View File
@@ -10,6 +10,7 @@ import { createQueries } from './queries.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createTesting } from './testing.js';
import { createTransitCockpitSubject } from './cockpitSubject.js';
import { TRANSIT_POLL_MS } from './policy.js';
/**
@@ -54,12 +55,14 @@ export function createTransitLayer({
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
parts.testing = createTesting(context);
parts.cockpit = createTransitCockpitSubject(context);
return Object.assign(
{ updateInterval: TRANSIT_POLL_MS },
parts.lifecycle.methods,
parts.queries.methods,
parts.controls.methods,
parts.cockpit.methods,
parts.testing,
);
}
+2
View File
@@ -71,6 +71,8 @@ export function createIngestion({ state, services, parts, source }) {
function removeVehicle(key) {
const entry = state._vehicles.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js).
if (state._cockpitSubjectKey === key) state._cockpitSubjectKey = null;
if (state._selectedKey === key) parts.selection.clearSelection();
parts.rendering.removeMarker(entry);
entry.marker = null;
+1
View File
@@ -102,6 +102,7 @@ export function createLifecycle({ state, services, parts }) {
state._vehicles.clear();
parts.height.clear();
state._selectedKey = null;
state._cockpitSubjectKey = null;
state._lastUpdate = null;
state._error = null;
state._limitWarned = false;
+245
View File
@@ -8,9 +8,11 @@ import {
FEED_STALE_AFTER_MS,
MISSED_POLLS_TO_DROP,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_ID,
VEHICLE_MAX_FIX_AGE_MS,
} from './policy.js';
import { FLOOR_WARM_PER_POLL } from './policy.js';
import { fleetModelFakes } from '../../testSupport/fleetModelFakes.mjs';
import {
FUTURE_STAMP_TOLERANCE_MS,
ORDER_REJECTS_BEFORE_RESET,
@@ -224,6 +226,9 @@ function harness(
east: at.lon + 0.1,
north: at.lat + 0.1,
},
// Fleet-model services (testSupport/fleetModelFakes.mjs), with a camera
// looking straight down for them; without them vehicles stay icons.
fleet = null,
} = {},
) {
const viewRect = { ...view };
@@ -290,6 +295,7 @@ function harness(
viewRect.north,
);
},
...(fleet ? { view: viewFrom(at.lon, at.lat, altitude) } : {}),
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
@@ -339,6 +345,7 @@ function harness(
const layer = createTransitLayer({
source,
services: {
...(fleet ? { fleet } : {}),
ground,
mesh: {
sampleMeshFloorCells(scene, points, options) {
@@ -944,6 +951,27 @@ test('disable aborts in-flight work and a response that lands late is ignored',
assert.equal(app.vehicles().length, 1);
});
test('a held vehicle with no floor yet tells its view no height', async (t) => {
// Not the ellipsoid: a first-person view waits for the surface instead.
const app = harness(t, { floorAt: () => undefined });
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();
app.settle();
const entry = app.vehicles()[0];
assert.equal(entry.heightPending, true, 'it has nothing to stand on');
assert.ok(app.layer.setCockpitSubject(entry.key) !== false);
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => {
// The shared ground-floor system answers from the rendered mesh cell or the
// real DEM cell; until one of them is warm there is no honest height to draw
@@ -1966,11 +1994,19 @@ test('a segment climbs from the ground it left to the ground it reaches', async
assert.ok(Math.abs(entry.heightM - 101.5) < 1, 'the destination is uphill');
const height = () =>
Cesium.Cartographic.fromCartesian(entry.marker.position).height;
// A first-person view reads the floor where the vehicle is drawn, not the
// newest report's floor uphill.
app.layer.setCockpitSubject(entry.key);
const floor = () => app.layer.getCockpitSubject().position.groundHeightM;
app.run(400);
assert.ok(
height() < 30,
`still on the ground it is drawn on, got ${height().toFixed(1)} m`,
);
assert.ok(
Math.abs(floor() + 1.5 - height()) < 1,
`its snapshot stands where it is drawn, got ${floor().toFixed(1)} m`,
);
// Halfway along the segment it is halfway up; at the end, on the high ground.
const firstFixAt = start - AGE_MS;
@@ -1984,6 +2020,7 @@ test('a segment climbs from the ground it left to the ground it reaches', async
Math.abs(height() - 101.5) < 1.5,
`and arrives on the high ground, got ${height().toFixed(1)} m`,
);
assert.ok(Math.abs(floor() - 100) < 1.5, 'and so does its snapshot');
});
test('a lone impossible fix leaves the displayed vehicle and health untouched', async (t) => {
const app = harness(t, { floorAt: () => 5 });
@@ -4452,3 +4489,211 @@ test('the prompt names the altitude the gate opens at, not 3,000 km', async (t)
'Fly below 2,850 km to a covered region',
);
});
/** A bus running north a step a poll, polled `polls` times; its key. */
async function busRunningNorth(app, polls = 4, extra = {}) {
let step = 0;
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[
vehicle('bus-1', 42.36 + step * 0.001, -71.06, reported(), {
stopId: 'place-1',
status: 'IN_TRANSIT_TO',
...extra,
}),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
for (let i = 0; i < polls; i += 1) {
step += 1;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
}
return 'mbta:bus-1';
}
test('the selected vehicle reads as a snapshot of its place, motion and source', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app, 4, { speedMps: 9 });
assert.equal(app.layer.getSelectedVehicle(), null);
app.layer._transitPartsForTest().selection.selectVehicle(key);
const view = app.layer.getSelectedVehicle();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, key);
assert.equal(view.feedId, 'mbta');
assert.equal(view.id, 'bus-1');
assert.equal(view.routeId, '1');
assert.equal(typeof view.mode, 'string');
assert.ok(view.feed.attribution, 'the feed names its credit');
assert.equal(view.motion.reportedSpeedMps, 9);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.deepEqual(view.stop, { stopId: 'place-1', status: 'IN_TRANSIT_TO' });
const entry = app.vehicles()[0];
// Where it is drawn, without the shared lift (read back from the marker).
assert.ok(
Math.abs(view.position.groundHeightM - (entry.heightM - 1.5)) < 1e-3,
);
assert.ok(Number.isFinite(view.position.latitude));
});
test('a vehicle read again while nothing changed is the snapshot read before', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
app.layer._transitPartsForTest().selection.selectVehicle(key);
const first = app.layer.getSelectedVehicle();
assert.equal(app.layer.getSelectedVehicle(), first, 'the same snapshot');
// It moves on: a new snapshot at its new place, what did not change kept.
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
const moved = app.layer.getSelectedVehicle();
assert.notEqual(moved, first, 'a new snapshot');
assert.ok(Object.isFrozen(moved) && Object.isFrozen(moved.position));
assert.ok(moved.position.latitude > first.position.latitude, 'moved');
assert.equal(moved.feed, first.feed);
assert.equal(moved.stop, first.stop);
assert.equal(moved.provenance, first.provenance);
assert.equal(app.layer.getSelectedVehicle(), moved);
});
test('a held vehicle draws no 3D model either; let go, its model draws again', async (t) => {
const models = await fleetModelFakes();
const app = harness(t, { fleet: models.fleet, altitude: 1_000 });
models.watch(app.draw);
const key = await busRunningNorth(app);
const [entry] = app.vehicles();
assert.notEqual(entry.mode, 'unknown', 'a mode its model is chosen by');
// The throttled sweep runs; a model's load answers off the frame and the
// next frames place it.
const frames = async () => {
app.advance(250);
app.settle();
models.load();
for (let i = 0; i < 8; i += 1) await Promise.resolve();
app.settle();
};
await frames();
assert.equal(models.drawn(key).length, 1, 'near the camera: its model');
assert.equal(entry.modelOwnsVisual, true);
assert.equal(entry.marker.show, false, 'its icon hands over');
assert.equal(app.layer.setCockpitSubject(key), true);
app.frame();
// The view's eye is inside the vehicle.
assert.equal(models.drawn(key).length, 0, 'no model');
assert.equal(entry.modelOwnsVisual, false);
assert.equal(entry.marker.show, false, 'and no icon');
await frames();
assert.equal(models.drawn(key).length, 0, 'not on a later frame either');
assert.equal(entry.marker.show, false);
assert.equal(app.layer.setCockpitSubject(null), true);
await frames();
assert.equal(models.drawn(key).length, 1, 'let go: its model again');
assert.equal(entry.modelOwnsVisual, true);
assert.equal(entry.marker.show, false);
});
test('selectedAtMs is the user’s selection time; a hold and a deselection leave none', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
// A vehicle only a hold selected reports none.
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
app.layer.setCockpitSubject(null);
assert.equal(app.layer.setCockpitSubject(null), true, 'twice is harmless');
assert.equal(app.state()._selectedKey, key);
// The user's selection stamps it, again on a re-selection.
assert.equal(app.layer.focusVehicle(key), true);
const first = app.layer.getSelectedVehicle().selectedAtMs;
assert.ok(Number.isFinite(first));
app.run(1000);
app.layer.focusVehicle(key);
assert.ok(app.layer.getSelectedVehicle().selectedAtMs > first);
// Deselected, then held: none.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._selectedAtMs, null);
app.layer.setCockpitSubject(key);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
});
test('a held vehicle hides, keeps moving out of view, and lets go when it goes', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
assert.equal(app.layer.setCockpitSubject('mbta:nope'), false);
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(app.state()._selectedKey, key, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, key);
assert.equal(
app.overlaySources.has(TRANSIT_SELECTED_OVERLAY_SOURCE_ID),
false,
'no card',
);
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, false);
// The camera's view leaves it, as a view from inside it does: it plays on.
app.lookAt({ west: 10, south: 10, east: 11, north: 11 });
app.settle();
assert.equal(
app.layer._transitPartsForTest().rendering.vehicleInView(entry),
true,
);
const before = app.layer.getCockpitSubject().position.latitude;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
assert.ok(
app.layer.getCockpitSubject().position.latitude > before,
'still moving',
);
// Escape and clicks are the view's while it holds the vehicle.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, key);
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
// Let go, it is out of play until a sweep finds it in view.
assert.equal(app.state()._visible.has(entry), false, 'out of play');
app.lookAt({
west: -71.2,
south: 42.2,
east: -70.9,
north: 42.5,
});
app.advance(250);
app.settle();
assert.equal(entry.marker.show, true, 'shown again');
assert.equal(app.layer.focusVehicle('mbta:nope'), false);
assert.equal(app.layer.focusVehicle(key), true);
app.layer.setCockpitSubject(key);
app.silence('mbta');
app.serve('mbta', () => ({
status: 200,
body: snapshot('mbta', 'MBTA', [], { fetchedAt: Date.now() }),
}));
for (let i = 0; i < MISSED_POLLS_TO_DROP + 1; i += 1) {
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
assert.equal(app.vehicles().length, 0, 'the vehicle is gone');
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+23 -6
View File
@@ -484,7 +484,14 @@ export function createRendering({ state, services, parts }) {
);
entry.surfaceReady = !!known;
entry.heightPending = !known;
setShown(entry, !!known && vehicleInView(entry) && !entry.modelOwnsVisual);
// A vehicle a first-person view rides keeps moving, unseen.
setShown(
entry,
!!known &&
vehicleInView(entry) &&
!entry.modelOwnsVisual &&
entry.key !== state._cockpitSubjectKey,
);
if (known) {
const p = entry.marker.position;
const s = state._scratchCartesian;
@@ -566,7 +573,7 @@ export function createRendering({ state, services, parts }) {
* @returns {boolean}
*/
function vehicleInView(entry) {
return state._visible.has(entry);
return state._visible.has(entry) || entry.key === state._cockpitSubjectKey;
}
/** A preset tuple as a colour (0..1 channels), cached per profile+mode. */
@@ -892,7 +899,7 @@ export function createRendering({ state, services, parts }) {
});
}
/** Hand an entry's visual back to its icon. */
/** Hand an entry's visual back to its icon, unless a view rides it. */
function handBack(entry) {
if (!entry.modelOwnsVisual) return;
entry.modelOwnsVisual = false;
@@ -901,7 +908,8 @@ export function createRendering({ state, services, parts }) {
entry,
vehicleInView(entry) &&
!entry.heightPending &&
entry.surfaceReady !== false,
entry.surfaceReady !== false &&
entry.key !== state._cockpitSubjectKey,
);
}
@@ -939,7 +947,12 @@ export function createRendering({ state, services, parts }) {
}
item.position = entry.marker.position;
item.headingDeg = Number.isFinite(entry.courseDeg) ? entry.courseDeg : 0;
item.show = !entry.heightPending && entry.surfaceReady !== false;
// A vehicle a first-person view rides draws no model: the camera is
// inside it (cockpitSubject.js).
item.show =
!entry.heightPending &&
entry.surfaceReady !== false &&
entry.key !== state._cockpitSubjectKey;
next.set(entry.key, item);
}
for (const [key, item] of modelItems)
@@ -1055,7 +1068,10 @@ export function createRendering({ state, services, parts }) {
}
}
}
const visible = (planes || bounds) && horizon && inFrustum;
// A held vehicle (cockpitSubject.js) is the camera's own: it stays in
// play wherever the view looks.
const held = entry.key === state._cockpitSubjectKey;
const visible = held || ((planes || bounds) && horizon && inFrustum);
const visibility = (entry.visibility ||= {});
visibility.bounds = bounds;
visibility.boundsApplied = !planes;
@@ -1085,6 +1101,7 @@ export function createRendering({ state, services, parts }) {
setShown(
entry,
Boolean(
!held &&
visible &&
!entry.heightPending &&
entry.surfaceReady !== false &&
+20 -2
View File
@@ -47,6 +47,12 @@ export function createSelection({ state, services, parts }) {
? state._vehicles.get(state._selectedKey)
: null;
if (!entry) return;
// A vehicle a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -92,6 +98,7 @@ export function createSelection({ state, services, parts }) {
: null;
parts.trails.clear();
state._selectedKey = null;
state._selectedAtMs = null;
state._selectedCardText = null;
state._detectRevision += 1;
// Cleared first: the styling path reads the selection from state.
@@ -99,11 +106,18 @@ export function createSelection({ state, services, parts }) {
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
}
function selectVehicle(key) {
/**
* Select a vehicle. `byUser` marks a selection the user made (a click, or
* focusVehicle), even of the selected vehicle again: its time is the
* snapshot's `selectedAtMs` (cockpitSubject.js). A first-person view's hold
* selects without it.
*/
function selectVehicle(key, { byUser = false } = {}) {
clearSelection();
const entry = state._vehicles.get(key);
if (!entry?.marker) return;
state._selectedKey = key;
if (byUser) state._selectedAtMs = Date.now();
state._detectRevision += 1;
parts.rendering.paintSelected(entry, true);
parts.trails.select(entry);
@@ -112,6 +126,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the vehicle, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -120,6 +136,8 @@ export function createSelection({ state, services, parts }) {
// The dispatcher maps a sensor-style click back into the pick buffer
// (src/input/sensorPick.js) and skips it while a tool holds the pointer.
state._clickSubscription = inputFor(viewer).onClick((event) => {
// A held vehicle keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const position = event.position;
// A marker is an item of one of this layer's two sets, by its key.
const hit = event.drawHit;
@@ -134,7 +152,7 @@ export function createSelection({ state, services, parts }) {
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
};
if (key) {
selectVehicle(key);
selectVehicle(key, { byUser: true });
return;
}
if (state._selectedKey) clearSelection();
+9
View File
@@ -96,6 +96,15 @@ export function createState({ services }) {
/** @type {string|null} */
state._selectedKey = null;
/** When the user last selected a vehicle, even the selected one (ms). */
state._selectedAtMs = null;
/**
* The vehicle a first-person view holds (cockpitSubject.js), or null: its
* sprite, 3D model, card, trail and detection box are hidden, and it keeps
* moving out of the camera's view.
* @type {string|null}
*/
state._cockpitSubjectKey = null;
state._selectedCardAt = 0;
/** The card text last published, so an unchanged card is not re-sent. */
state._selectedCardText = null;
+4 -1
View File
@@ -235,8 +235,11 @@ export function createTrails({ state, services, parts, source }) {
}
function update() {
if (!selected || !renderer) return;
// A first-person view on the vehicle rides where its trail would start.
renderer.setVisible(
state._enabled && state._vehicles.get(selected.key) === selected,
state._enabled &&
state._vehicles.get(selected.key) === selected &&
selected.key !== state._cockpitSubjectKey,
);
renderer.setDisplaySample(selected.sample, selected.marker?.position);
}
+4
View File
@@ -91,6 +91,10 @@ export function createViewport({ state, services, parts }) {
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
}
// A vehicle a first-person view rides keeps its feed polled.
const held = state._vehicles.get(state._cockpitSubjectKey);
if (held && state._activeFeeds.has(held.feedId))
desired.set(held.feedId, state._activeFeeds.get(held.feedId));
for (const feedId of [...state._activeFeeds.keys()]) {
if (!desired.has(feedId)) {
state._inFlight.get(feedId)?.controller.abort();