mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-21 02:32:18 +00:00
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:
commit
866a9816f2
142 files changed
+9067
-308
No files matched your search
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
Vendored
+7
-1
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user