- `${tag}.${cls.split(' ').filter((name) => !/^ui-/.test(name)).join(' ')}`);
- assert.deepEqual(tags, ['span.panel-title', 'span.panel-divider', 'button.panel-collapse-btn']);
+ const tags = [
+ ...header[1].matchAll(/<(\w+)\s+(?:type="button"\s+)?class="([^"]+)"/g),
+ ].map(
+ ([, tag, cls]) =>
+ `${tag}.${cls
+ .split(' ')
+ .filter((name) => !/^ui-/.test(name))
+ .join(' ')}`,
+ );
+ assert.deepEqual(tags, [
+ 'span.panel-title',
+ 'span.panel-divider',
+ 'button.panel-edge-btn',
+ 'span.material-symbols-outlined',
+ 'button.panel-collapse-btn',
+ ]);
});
test('Context reads as one segmented control with legible type and no halo', () => {
const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
- const clean = (selector) => selector.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim();
- const rule = (selector) => rules.find(([, s]) => clean(s) === selector)?.[2] || '';
- const px = (body, prop) => Number(body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0);
+ const clean = (selector) =>
+ selector
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ const rule = (selector) =>
+ rules.find(([, s]) => clean(s) === selector)?.[2] || '';
+ const px = (body, prop) =>
+ Number(
+ body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0,
+ );
assert.match(rule('#global-context-panel .panel-glow'), /display:\s*none/);
const modes = rule('.global-context-modes');
assert.match(modes, /border:\s*1px solid/);
assert.match(modes, /padding:\s*2px/);
- assert.ok(px(rule('.context-mode-button'), 'font') >= 10, 'mode labels must stay at least 10px');
+ assert.ok(
+ px(rule('.context-mode-button'), 'font') >= 10,
+ 'mode labels must stay at least 10px',
+ );
assert.doesNotMatch(rule('.context-mode-button.active'), /box-shadow/);
const standby = rule('.context-mode-standby');
- assert.ok(px(standby, 'font') >= 10, 'standby guidance must stay at least 10px');
+ assert.ok(
+ px(standby, 'font') >= 10,
+ 'standby guidance must stay at least 10px',
+ );
assert.doesNotMatch(standby, /dashed/);
- assert.ok(px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10);
+ assert.ok(
+ px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10,
+ );
// The shared rail title colour (brighter than --text-secondary) keeps the
// open Context title legible; no Context-only rule dims it again.
assert.equal(
- rule(":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title"),
+ rule(
+ ":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title",
+ ),
'',
);
});
diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js
index 55f21d3d1..2b593ebe7 100644
--- a/src/data/aircraftIconLayer.js
+++ b/src/data/aircraftIconLayer.js
@@ -357,6 +357,9 @@ let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
+/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
+const PLACED_PLAN_MS = 1000;
+
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
return { currentMs: ms, step: () => ms };
@@ -399,6 +402,12 @@ function fixedDelay(ms) {
* @param {(icao24: string) => void} [options.afterSettle] Runs after it.
* @param {(icao24: string) => void} [options.onForget] Drops the layer's own
* per-contact state when a contact goes.
+ * @param {((icao24: string, wallMs: number, info: object|undefined,
+ * history: object[], out: {x: number, y: number, z: number}) =>
+ * {courseDeg: number, speedMps: number}|null)|null} [options.placeAt]
+ * Where a host-supplied placement draws a live contact at a wall time,
+ * written into `out` (`placeAircraftAt`), or null when it does not place
+ * it; none without a placement.
*/
export function createAircraftIcons({
state,
@@ -415,6 +424,7 @@ export function createAircraftIcons({
beforeSettle = () => {},
afterSettle = () => {},
onForget = () => {},
+ placeAt = null,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
@@ -560,6 +570,10 @@ export function createAircraftIcons({
fromCourseDeg ??
(icons.expires(icao24) === -Infinity ? null : icons.course(icao24, t));
+ // A host-supplied placement decides where a live contact is drawn; with
+ // none, or no answer for this contact, the layer's own motion below does.
+ if (_planPlaced(icao24, info, history, t)) return;
+
const regime = parts.motion._motionRegime(history, info, renderTime);
let speed;
let motion;
@@ -691,6 +705,44 @@ export function createAircraftIcons({
icons.update(icao24, { pos, course, motion, courseGlide }, { expiresAt });
}
+ /**
+ * Plan a live contact a host-supplied placement places: from where it
+ * places it at `t` (display ms, the live clock's delayed time) to where it
+ * places it PLACED_PLAN_MS on, asked again when that runs out. Display
+ * time is wall time less the display delay, so the placement is asked at
+ * the wall times the segment's ends stand for.
+ * @returns {boolean} False when there is no placement, the layer follows
+ * the world clock, or it has no answer for this contact.
+ */
+ function _planPlaced(icao24, info, history, t) {
+ if (!placeAt || followsClock()) return false;
+ const leadMs = displayDelay.currentMs;
+ const from = vec();
+ const start = placeAt(icao24, t + leadMs, info, history, from);
+ if (!start) return false;
+ const { courseDeg: course } = start;
+ const t1 = t + PLACED_PLAN_MS;
+ const to = vec();
+ const end = placeAt(icao24, t1 + leadMs, info, history, to);
+ const motion = end
+ ? {
+ kind: 'lerp',
+ from,
+ to,
+ t0: t,
+ t1,
+ course0Deg: course,
+ courseSlopeDeg: norm180(end.courseDeg - course),
+ }
+ : { kind: 'hold', courseDeg: course };
+ state._icons.update(
+ icao24,
+ { pos: clone(from), course, motion, courseGlide: undefined },
+ { expiresAt: t1 },
+ );
+ return true;
+ }
+
/** Re-plan every row whose regime ended by `t` (epoch ms). */
function _replanExpired(t) {
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
@@ -839,6 +891,8 @@ export function createAircraftIcons({
state._icons?.remove(icao24);
parts.rendering._releaseModel(icao24);
state.records.forget(icao24);
+ // The host-supplied placement, if any, forgets it as well.
+ services.placement?.forget(icao24);
state._positionHistory.delete(icao24);
state._displayCourse.delete(icao24);
state._groundSnap.forget(icao24);
diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs
index f082a11ef..1b091ec4f 100644
--- a/src/data/aisLiveVessels.test.mjs
+++ b/src/data/aisLiveVessels.test.mjs
@@ -2192,3 +2192,57 @@ test('detection objects name the vessel card their callout gives way to', () =>
_setVesselStateForTest({ enabled: false });
}
});
+
+test('an aid to navigation card shows its kind, never a speed or heading', () => {
+ const aid = makeRecord({
+ name: 'SF APPROACH N',
+ mmsi: '993672001',
+ type: 'Cardinal Mark N',
+ speed: 0,
+ course: 135,
+ heading: 135,
+ });
+ const card = buildVesselCard(aid);
+ assert.deepEqual(card.details, ['CARDINAL MARK N']);
+ assert.equal(card.accent, '217, 210, 192');
+ const selected = buildSelectedVesselCard(aid);
+ assert.equal(selected.details[0], 'CARDINAL MARK N');
+ assert.equal(selected.accent, '217, 210, 192');
+ // Known only by its MMSI, an aid is named as one.
+ const unnamed = buildSelectedVesselCard({ ...aid, type: '' });
+ assert.equal(unnamed.details[0], 'AID TO NAVIGATION');
+ assert.deepEqual(buildVesselCard({ ...aid, type: '' }).details, []);
+});
+
+test('the HUD of a selected aid to navigation shows no speed or heading', () => {
+ const harness = installWireHarness(undefined, { selectedRecord: null });
+ try {
+ Object.assign(harness.record, {
+ type: 'Port hand Mark',
+ speed: 0,
+ heading: 135,
+ course: 135,
+ });
+ assert.equal(aisLiveVesselsLayer.selectById(harness.record.mmsi), true);
+ assert.match(harness.hud.readout.text, /\nPort hand Mark\n/);
+ assert.doesNotMatch(harness.hud.readout.text, /SPD|HDG|KT/);
+ harness.record.virtual = true;
+ aisLiveVesselsLayer.selectById(harness.record.mmsi);
+ assert.match(harness.hud.readout.text, /\nPort hand Mark · VIRTUAL\n/);
+ } finally {
+ harness.cleanup();
+ }
+});
+
+test('a virtual aid to navigation card says it is virtual', () => {
+ const aid = makeRecord({
+ mmsi: '993672001',
+ type: 'Isolated danger',
+ virtual: true,
+ });
+ assert.deepEqual(buildVesselCard(aid).details, ['ISOLATED DANGER · VIRTUAL']);
+ assert.equal(
+ buildSelectedVesselCard(aid).details[0],
+ 'ISOLATED DANGER · VIRTUAL',
+ );
+});
diff --git a/src/data/aisStreamSentinels.test.mjs b/src/data/aisStreamSentinels.test.mjs
index 93569fc97..563bf9f65 100644
--- a/src/data/aisStreamSentinels.test.mjs
+++ b/src/data/aisStreamSentinels.test.mjs
@@ -316,3 +316,97 @@ test('a Class B report carries its dimensions in part B', () => {
assert.equal(row.length, 12);
assert.equal(row.beam, 4);
});
+
+test('an aid-to-navigation report is a row named by its kind of aid, not a ship type', () => {
+ assert.equal(
+ ingestAisStreamEnvelope({
+ MessageType: 'AidsToNavigationReport',
+ Message: {
+ AidsToNavigationReport: {
+ UserID: 993672001,
+ Type: 20,
+ Name: 'SF APPROACH N',
+ },
+ },
+ MetaData: {
+ MMSI: '993672001',
+ latitude: 37.79,
+ longitude: -122.52,
+ time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
+ },
+ }),
+ true,
+ );
+ const row = rowFor('993672001');
+ assert.equal(row.type, 'Cardinal Mark N');
+ assert.equal(row.name, 'SF APPROACH N');
+ assert.equal(row.speed, null);
+});
+
+test("an aid's name runs on into its name extension", () => {
+ ingestAisStreamEnvelope({
+ MessageType: 'AidsToNavigationReport',
+ Message: {
+ AidsToNavigationReport: {
+ UserID: 993672002,
+ Type: 13,
+ Name: 'SAN FRANCISCO MAIN S',
+ NameExtension: 'HIP CHANNEL 2',
+ },
+ },
+ MetaData: {
+ MMSI: '993672002',
+ ShipName: 'SAN FRANCISCO MAIN S',
+ latitude: 37.79,
+ longitude: -122.52,
+ time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
+ },
+ });
+ assert.equal(rowFor('993672002').name, 'SAN FRANCISCO MAIN SHIP CHANNEL 2');
+});
+
+test('a capped row request keeps every vessel ahead of aids to navigation', () => {
+ // The aid reports last, so it is the newest row.
+ ingestAisStreamEnvelope(positionReport('244060901', { Sog: 3 }));
+ ingestAisStreamEnvelope({
+ MessageType: 'AidsToNavigationReport',
+ Message: { AidsToNavigationReport: { UserID: 993672003, Type: 24 } },
+ MetaData: {
+ MMSI: '993672003',
+ latitude: 37.79,
+ longitude: -122.52,
+ time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
+ },
+ });
+ const rows = aisStreamRows(50000);
+ const firstAid = rows.findIndex((row) => row.mmsi.startsWith('99'));
+ const lastVessel = rows.findLastIndex((row) => !row.mmsi.startsWith('99'));
+ assert.ok(firstAid > lastVessel, `${firstAid} > ${lastVessel}`);
+ const vesselCount =
+ rows.length - rows.filter((row) => row.mmsi.startsWith('99')).length;
+ assert.ok(
+ aisStreamRows(vesselCount).every((row) => !row.mmsi.startsWith('99')),
+ );
+});
+
+test('a virtual aid to navigation is marked virtual; a real one carries no flag', () => {
+ const aidReport = (mmsi, VirtualAtoN) => ({
+ MessageType: 'AidsToNavigationReport',
+ Message: {
+ AidsToNavigationReport: { UserID: Number(mmsi), Type: 28, VirtualAtoN },
+ },
+ MetaData: {
+ MMSI: mmsi,
+ latitude: 37.79,
+ longitude: -122.52,
+ time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
+ },
+ });
+ ingestAisStreamEnvelope(aidReport('993672004', true));
+ ingestAisStreamEnvelope(aidReport('993672005', false));
+ assert.equal(rowFor('993672004').virtual, true);
+ assert.equal('virtual' in rowFor('993672005'), false);
+ // A later real report of the same aid drops the flag.
+ ingestAisStreamEnvelope(aidReport('993672004', false));
+ assert.equal('virtual' in rowFor('993672004'), false);
+});
diff --git a/src/data/fleetModels.js b/src/data/fleetModels.js
index 6b436bae6..69ab2a678 100644
--- a/src/data/fleetModels.js
+++ b/src/data/fleetModels.js
@@ -11,6 +11,9 @@
* vehicle's road or rail top), and is drawn life size: a type's published
* length over the model's built length is its scale.
*
+ * An aid to navigation (a buoy, beacon, mark, RACON or light) is drawn as
+ * the set's buoy of its IALA mark, by the mark its type names.
+ *
* The resolvers are plain functions over the parsed JSON; `loadFleetModelSet`
* fetches the JSON and every GLB once, up front, so no model is fetched
* mid-session.
@@ -18,6 +21,7 @@
import { classifyAircraft } from './aircraftClass.js';
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
+import { isAidToNavigation } from './vesselTypes.js';
/** Where the model set is served, relative to the application base. */
export const FLEET_MODEL_BASE = '/models/fleet/';
@@ -84,6 +88,44 @@ const TEXT_SHIP_TYPES = [
[/pleasure|yacht/i, 37],
];
+/**
+ * The buoy an aid to navigation is drawn as, by the mark its type names
+ * ("Cardinal Mark N", "Beacon, Port hand", "Safe Water"): the first pattern
+ * that matches. Beacons, lights, RACONs and reference points with no mark of
+ * their own are the special mark.
+ */
+const AID_MODELS = [
+ [/cardinal\b.*\bn(orth)?$/i, 'buoy_cardinal_north'],
+ [/cardinal\b.*\be(ast)?$/i, 'buoy_cardinal_east'],
+ [/cardinal\b.*\bs(outh)?$/i, 'buoy_cardinal_south'],
+ [/cardinal\b.*\bw(est)?$/i, 'buoy_cardinal_west'],
+ [/isolated danger/i, 'buoy_isolated_danger'],
+ [/safe water/i, 'buoy_safe_water'],
+ [/port hand/i, 'buoy_lateral_port'],
+ [/starboard hand/i, 'buoy_lateral_starboard'],
+ [/special mark|light vessel|lanby/i, 'buoy_special'],
+ [
+ /^(beacon|light\b|leading light|racon|reference point|navigation aid)/i,
+ 'buoy_special',
+ ],
+];
+
+/** The buoy an aid to navigation whose type names no mark is drawn as. */
+export const DEFAULT_AID_MODEL = 'can_red';
+
+/**
+ * The buoy model of an aid to navigation's type, else undefined when the
+ * type names no mark.
+ * @param {string|null} [type]
+ * @returns {string|undefined}
+ */
+export function aidToNavigationModel(type) {
+ const text = String(type ?? '').trim();
+ for (const [pattern, model] of AID_MODELS)
+ if (pattern.test(text)) return model;
+ return undefined;
+}
+
/**
* The model for an aircraft of ICAO type `type` (A320, B738, R44), ADS-B
* emitter category `category` and callsign `callsign`: the first of the
@@ -397,13 +439,33 @@ export function aircraftModelSpec(
/**
* The model a vessel is drawn with, from its AIS ship type (a code or a text
- * family), reported length and beam (metres) and name.
+ * family), reported length and beam (metres) and name. An aid to navigation
+ * ({@link isAidToNavigation}: its type names a buoy, beacon, mark, RACON or
+ * light, or its MMSI is an aid's) is the buoy of its mark
+ * ({@link aidToNavigationModel}), else {@link DEFAULT_AID_MODEL}, drawn as
+ * built and flagged `fixed`: it has no heading to turn to. A virtual aid
+ * (`virtual`) is broadcast where nothing physical stands, so it has no model.
* @param {{catalog: object, types: object}} set
- * @param {{type?: string|number|null, length?: number|null,
- * beam?: number|null, name?: string|null}} vessel
- * @returns {object} {@link fleetModelSpec}
+ * @param {{type?: string|number|null, mmsi?: string|number|null,
+ * virtual?: boolean, length?: number|null, beam?: number|null,
+ * name?: string|null}} vessel
+ * @returns {object|null} {@link fleetModelSpec}, with `fixed` for an aid;
+ * null for a virtual aid
*/
-export function vesselModelSpec(set, { type, length, beam, name } = {}) {
+export function vesselModelSpec(
+ set,
+ { type, mmsi, virtual, length, beam, name } = {},
+) {
+ if (virtual === true) return null;
+ if (isAidToNavigation({ type, mmsi })) {
+ const model = aidToNavigationModel(type);
+ const known = model && set.catalog[model] ? model : DEFAULT_AID_MODEL;
+ if (set.catalog[known])
+ return Object.freeze({
+ ...fleetModelSpec(set, known, null),
+ fixed: true,
+ });
+ }
// A beam counts only beside a reported length: a vessel drawn at its type's
// typical length keeps the model's proportions.
const reported = hullLength(length ?? undefined);
@@ -460,6 +522,8 @@ export function namedFleetModels(types) {
transit.default[0],
...Object.keys(transit.elevation),
...Object.values(CLASS_MODELS),
+ ...AID_MODELS.map(([, model]) => model),
+ DEFAULT_AID_MODEL,
]);
}
diff --git a/src/data/fleetModels.test.mjs b/src/data/fleetModels.test.mjs
index f9ef47bc6..315c53746 100644
--- a/src/data/fleetModels.test.mjs
+++ b/src/data/fleetModels.test.mjs
@@ -4,7 +4,9 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
+ DEFAULT_AID_MODEL,
FLEET_MODEL_BASE,
+ aidToNavigationModel,
aircraftModelSpec,
aisShipTypeCode,
emitterCategory,
@@ -23,6 +25,7 @@ import {
vesselModelSpec,
} from './fleetModels.js';
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
+import { TRANSIT_MODES } from './transitFeeds.js';
import {
centrelineSegments,
distanceToSurface,
@@ -381,6 +384,99 @@ test('vessel specs read AIS codes and text families, stretched to the reported b
assert.equal(unknown.scale, 1);
});
+test('aids to navigation are the buoy of the mark their type names', () => {
+ const cases = [
+ ['Cardinal Mark N', 'buoy_cardinal_north'],
+ ['Beacon, Cardinal E', 'buoy_cardinal_east'],
+ ['Cardinal Mark S', 'buoy_cardinal_south'],
+ ['Beacon, Cardinal W', 'buoy_cardinal_west'],
+ ['Port Hand Mark', 'buoy_lateral_port'],
+ ['Beacon, Port hand', 'buoy_lateral_port'],
+ ['Starboard Hand Mark', 'buoy_lateral_starboard'],
+ ['Preferred Channel Starboard hand', 'buoy_lateral_starboard'],
+ ['Safe Water', 'buoy_safe_water'],
+ ['Isolated danger', 'buoy_isolated_danger'],
+ ['Beacon, Special Mark', 'buoy_special'],
+ ['Special Mark', 'buoy_special'],
+ ['Light Vessel / LANBY / Rigs', 'buoy_special'],
+ ['RACON', 'buoy_special'],
+ ['Light, with Sectors', 'buoy_special'],
+ ['Reference point', 'buoy_special'],
+ ['Navigation aid', 'buoy_special'],
+ ];
+ for (const [type, model] of cases) {
+ assert.equal(aidToNavigationModel(type), model, type);
+ assert.ok(catalog[model], model);
+ const spec = vesselModelSpec(set, { type, mmsi: '993672001' });
+ assert.equal(spec.model, model, type);
+ assert.equal(spec.category, 'buoys', type);
+ assert.equal(spec.fixed, true, type);
+ // A buoy is drawn as built, whatever length the report gives.
+ assert.equal(spec.scale, 1, type);
+ }
+ assert.equal(
+ vesselModelSpec(set, { type: 'Safe Water', length: 120, beam: 30 }).scale,
+ 1,
+ );
+ // An aid of no stated kind, known only by its MMSI, is the default can.
+ assert.ok(catalog[DEFAULT_AID_MODEL]);
+ const unnamed = vesselModelSpec(set, { type: '', mmsi: '993660123' });
+ assert.equal(unnamed.model, DEFAULT_AID_MODEL);
+ assert.equal(unnamed.fixed, true);
+ assert.equal(aidToNavigationModel('Fixed structure off shore'), undefined);
+ // A virtual aid is broadcast where nothing stands: it keeps its disc.
+ assert.equal(
+ vesselModelSpec(set, {
+ type: 'Cardinal Mark N',
+ mmsi: '993672001',
+ virtual: true,
+ }),
+ null,
+ );
+ // Vessels, including those that work on buoys, keep their hulls.
+ for (const vessel of [
+ { type: 'Buoy Tender', mmsi: '366999001', length: 60 },
+ { type: '70', mmsi: '366999002' },
+ { type: 'Tug', mmsi: '' },
+ ]) {
+ const spec = vesselModelSpec(set, vessel);
+ assert.notEqual(spec.category, 'buoys', vessel.type);
+ assert.equal(spec.fixed, undefined, vessel.type);
+ }
+});
+
+test('every transit mode but unknown draws its own model, and a route type a finer one', () => {
+ for (const mode of TRANSIT_MODES.filter((m) => m !== 'unknown')) {
+ assert.ok(types.transit.modes[mode], `${mode} has a model`);
+ assert.equal(
+ resolveTransit(types, { mode }).model,
+ types.transit.modes[mode][0],
+ );
+ }
+ for (const [mode, model] of [
+ ['trolleybus', 'trolleybus'],
+ ['cable_tram', 'cable_tram'],
+ ['aerial_lift', 'gondola'],
+ ['funicular', 'funicular'],
+ ['monorail', 'monorail'],
+ ])
+ assert.equal(resolveTransit(types, { mode }).model, model, mode);
+ // A route type outranks the mode: a coach and a high-speed set are still
+ // the bus and rail modes.
+ for (const [routeType, mode, model] of [
+ [200, 'bus', 'coach'],
+ [101, 'rail', 'high_speed'],
+ [106, 'rail', 'regional_dmu'],
+ [710, 'bus', 'double_decker'],
+ ])
+ assert.equal(resolveTransit(types, { routeType, mode }).model, model);
+ // A type the table lacks falls back to the mode.
+ assert.equal(
+ resolveTransit(types, { routeType: 300, mode: 'rail' }).model,
+ 'commuter_emu',
+ );
+});
+
test('transit specs: rail category and mode, then route type, then mode, then the default', () => {
assert.deepEqual(resolveTransit(types, { railCategory: 'national' }), {
model: 'intercity',
diff --git a/src/data/placementProvider.js b/src/data/placementProvider.js
new file mode 100644
index 000000000..98210a257
--- /dev/null
+++ b/src/data/placementProvider.js
@@ -0,0 +1,131 @@
+/**
+ * A host-supplied placement provider: an application embedding the catalog
+ * may decide where its moving contacts are drawn while live. Each layer that
+ * takes one tells it every fix it accepts (`observe`) and asks it, each time
+ * it draws a contact, where to draw it now (`place`). A layer given none, or
+ * asking about a contact the provider does not place (`null`), draws the
+ * contact with its own motion, exactly as without a provider. A provider
+ * that throws is treated as having no answer for that call.
+ *
+ * Layers consult a provider only while live: following the world clock, the
+ * layer's own motion places every contact.
+ *
+ * @typedef {'aircraft'|'military'|'vessels'|'transit'|'rail'} PlacementKind
+ *
+ * @typedef {object} PlacementFix
+ * @property {number} timeMs The fix's own time, Unix ms.
+ * @property {number} lat
+ * @property {number} lon
+ * @property {number} [altitudeM] The height the layer draws the fix at,
+ * metres above the ellipsoid; NaN when the layer keeps its own height.
+ * @property {number} [speedMps] Reported ground speed, NaN for none.
+ * @property {number} [courseDeg] Reported course over ground, NaN for none.
+ * @property {number} [headingDeg] Reported heading, NaN for none.
+ * @property {boolean} [onGround] Reported on the ground (aircraft).
+ * @property {string} [feedId] The feed the contact belongs to (transit, rail).
+ *
+ * @typedef {object} Placement
+ * @property {number} lat
+ * @property {number} lon
+ * @property {number} altitudeM Metres above the ellipsoid, as the observed
+ * fixes' `altitudeM`; NaN keeps the layer's own height.
+ * @property {number} courseDeg Direction of travel, NaN for none.
+ * @property {number} speedMps NaN for none.
+ * @property {boolean} extrapolating Past the contact's newest fix.
+ *
+ * @typedef {object} LayerPlacement What a layer is handed: never throws.
+ * @property {(id: string, fix: PlacementFix) => void} observe
+ * @property {(id: string, wallMs: number) => Placement|null} place The
+ * answer is one object reused by every call: read it before the next.
+ * @property {(id: string) => void} forget The contact left the layer.
+ *
+ * @typedef {object} PlacementProvider
+ * @property {(kind: PlacementKind) => object|null|undefined} layer The
+ * placement for one kind of contact: an object with `place(id, wallMs)`
+ * and optionally `observe(id, fix)` and `forget(id)`, or null to leave that
+ * kind to its layer's own motion.
+ */
+
+/** The kinds of contact a provider may place. */
+export const PLACEMENT_KINDS = Object.freeze([
+ 'aircraft',
+ 'military',
+ 'vessels',
+ 'transit',
+ 'rail',
+]);
+
+const finiteOr = (value, fallback) =>
+ typeof value === 'number' && Number.isFinite(value) ? value : fallback;
+
+/**
+ * One kind's placement from a provider, guarded so a layer can call it every
+ * frame: null when there is no provider or it does not place `kind`.
+ * @param {PlacementProvider|null|undefined} provider
+ * @param {PlacementKind} kind
+ * @returns {LayerPlacement|null}
+ */
+export function layerPlacement(provider, kind) {
+ if (!PLACEMENT_KINDS.includes(kind))
+ throw new TypeError(`Unknown placement kind: ${kind}`);
+ if (provider == null) return null;
+ if (typeof provider.layer !== 'function')
+ throw new TypeError('A placement provider needs a layer(kind) function');
+ const placement = provider.layer(kind);
+ if (placement == null) return null;
+ if (typeof placement.place !== 'function')
+ throw new TypeError(`The ${kind} placement needs a place(id, wallMs)`);
+ const observe =
+ typeof placement.observe === 'function' ? placement.observe : null;
+ const forget =
+ typeof placement.forget === 'function' ? placement.forget : null;
+ // Asked for every drawn contact every frame: one answer, reused.
+ const answer = {
+ lat: NaN,
+ lon: NaN,
+ altitudeM: NaN,
+ courseDeg: NaN,
+ speedMps: NaN,
+ extrapolating: false,
+ };
+ return Object.freeze({
+ observe(id, fix) {
+ if (!observe) return;
+ try {
+ observe.call(placement, id, fix);
+ } catch {
+ // A provider that fails to take a fix only answers less.
+ }
+ },
+ place(id, wallMs) {
+ let placed;
+ try {
+ placed = placement.place(id, wallMs);
+ } catch {
+ return null;
+ }
+ if (
+ !placed ||
+ !Number.isFinite(placed.lat) ||
+ !Number.isFinite(placed.lon) ||
+ Math.abs(placed.lat) > 90
+ )
+ return null;
+ answer.lat = placed.lat;
+ answer.lon = placed.lon;
+ answer.altitudeM = finiteOr(placed.altitudeM, NaN);
+ answer.courseDeg = finiteOr(placed.courseDeg, NaN);
+ answer.speedMps = finiteOr(placed.speedMps, NaN);
+ answer.extrapolating = placed.extrapolating === true;
+ return answer;
+ },
+ forget(id) {
+ if (!forget) return;
+ try {
+ forget.call(placement, id);
+ } catch {
+ // Nothing to undo.
+ }
+ },
+ });
+}
diff --git a/src/data/placementProvider.test.mjs b/src/data/placementProvider.test.mjs
new file mode 100644
index 000000000..a865ba7ba
--- /dev/null
+++ b/src/data/placementProvider.test.mjs
@@ -0,0 +1,108 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { PLACEMENT_KINDS, layerPlacement } from './placementProvider.js';
+
+test('no provider, or a provider that leaves a kind alone, gives no placement', () => {
+ for (const kind of PLACEMENT_KINDS) {
+ assert.equal(layerPlacement(null, kind), null);
+ assert.equal(layerPlacement(undefined, kind), null);
+ assert.equal(layerPlacement({ layer: () => null }, kind), null);
+ }
+ assert.throws(() => layerPlacement(null, 'satellites'), TypeError);
+ assert.throws(() => layerPlacement({}, 'aircraft'), TypeError);
+ assert.throws(
+ () => layerPlacement({ layer: () => ({ observe() {} }) }, 'aircraft'),
+ TypeError,
+ );
+});
+
+test('a placement is asked by id and wall time, and its answer is checked', () => {
+ const asked = [];
+ const seen = [];
+ const forgotten = [];
+ const answers = new Map([
+ [
+ 'a',
+ { lat: 51.5, lon: -0.1, altitudeM: 900, courseDeg: 270, speedMps: 80 },
+ ],
+ ['partial', { lat: 10, lon: 20, altitudeM: 'high', extrapolating: true }],
+ ['off-globe', { lat: 91, lon: 0 }],
+ ['nan', { lat: NaN, lon: 0 }],
+ ]);
+ const provider = {
+ layer: (kind) =>
+ kind === 'aircraft'
+ ? {
+ observe: (id, fix) => seen.push([id, fix.timeMs]),
+ place(id, wallMs) {
+ asked.push([id, wallMs]);
+ return answers.get(id) ?? null;
+ },
+ forget: (id) => forgotten.push(id),
+ }
+ : null,
+ };
+ assert.equal(layerPlacement(provider, 'vessels'), null);
+ const placement = layerPlacement(provider, 'aircraft');
+ placement.observe('a', { timeMs: 5, lat: 0, lon: 0 });
+ assert.deepEqual(seen, [['a', 5]]);
+ const placed = placement.place('a', 1000);
+ assert.deepEqual(
+ { ...placed },
+ {
+ lat: 51.5,
+ lon: -0.1,
+ altitudeM: 900,
+ courseDeg: 270,
+ speedMps: 80,
+ extrapolating: false,
+ },
+ );
+ const partial = placement.place('partial', 2000);
+ assert.equal(partial, placed, 'one answer object, reused');
+ assert.ok(Number.isNaN(partial.altitudeM));
+ assert.ok(Number.isNaN(partial.courseDeg));
+ assert.ok(Number.isNaN(partial.speedMps));
+ assert.equal(partial.extrapolating, true);
+ assert.equal(placement.place('off-globe', 3000), null);
+ assert.equal(placement.place('nan', 3000), null);
+ assert.equal(placement.place('unknown', 3000), null);
+ assert.deepEqual(
+ asked.map(([id]) => id),
+ ['a', 'partial', 'off-globe', 'nan', 'unknown'],
+ );
+ placement.forget('a');
+ assert.deepEqual(forgotten, ['a']);
+});
+
+test('a provider that throws has no answer, and observe and forget are optional', () => {
+ const placement = layerPlacement(
+ {
+ layer: () => ({
+ place() {
+ throw new Error('not ready');
+ },
+ }),
+ },
+ 'transit',
+ );
+ assert.equal(placement.place('x', 0), null);
+ assert.doesNotThrow(() => placement.observe('x', { timeMs: 0 }));
+ assert.doesNotThrow(() => placement.forget('x'));
+ const failing = layerPlacement(
+ {
+ layer: () => ({
+ place: () => null,
+ observe() {
+ throw new Error('full');
+ },
+ forget() {
+ throw new Error('gone');
+ },
+ }),
+ },
+ 'rail',
+ );
+ assert.doesNotThrow(() => failing.observe('x', { timeMs: 0 }));
+ assert.doesNotThrow(() => failing.forget('x'));
+});
diff --git a/src/data/transitFeeds.js b/src/data/transitFeeds.js
index 42f399d77..0f6844c65 100644
--- a/src/data/transitFeeds.js
+++ b/src/data/transitFeeds.js
@@ -29,12 +29,21 @@ import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
* node:test. No Cesium, no Node built-ins.
*/
-/** Transit modes the layer colors. `routeMode` hints refine a feed's default. */
+/**
+ * Transit modes the layer colors: the GTFS basic route types, by name. A
+ * vehicle's GTFS `route_type` settles its mode when its record carries one;
+ * otherwise `routeMode` hints refine a feed's default.
+ */
export const TRANSIT_MODES = Object.freeze([
'bus',
+ 'trolleybus',
'tram',
+ 'cable_tram',
'subway',
+ 'monorail',
'rail',
+ 'funicular',
+ 'aerial_lift',
'ferry',
'unknown',
]);
@@ -42,13 +51,81 @@ export const TRANSIT_MODES = Object.freeze([
/** Per-mode icon used in labels and the selection card. */
export const TRANSIT_MODE_ICON = Object.freeze({
bus: '🚌',
+ trolleybus: '🚎',
tram: '🚊',
+ cable_tram: '🚋',
subway: '🚇',
+ monorail: '🚝',
rail: '🚆',
+ funicular: '🚞',
+ aerial_lift: '🚡',
ferry: '⛴️',
unknown: '🚏',
});
+/** The basic GTFS route types (0–7, 11, 12) by mode. */
+const BASIC_ROUTE_TYPE_MODES = Object.freeze({
+ 0: 'tram',
+ 1: 'subway',
+ 2: 'rail',
+ 3: 'bus',
+ 4: 'ferry',
+ 5: 'cable_tram',
+ 6: 'aerial_lift',
+ 7: 'funicular',
+ 11: 'trolleybus',
+ 12: 'monorail',
+});
+
+/**
+ * A GTFS `route_type` as an integer: a basic type (0–12) or an extended one
+ * (100–1799), as a number or its decimal text. Null for anything else.
+ * @param {unknown} value
+ * @returns {number|null}
+ */
+export function transitRouteType(value) {
+ const n =
+ typeof value === 'number'
+ ? value
+ : typeof value === 'string' && /^\d{1,4}$/.test(value.trim())
+ ? Number(value.trim())
+ : NaN;
+ return Number.isInteger(n) && n >= 0 && n < 1800 ? n : null;
+}
+
+/**
+ * The mode of a GTFS `route_type`: the basic types, and the extended ones
+ * mapped to the basic mode they are a kind of (a coach, 200, is a bus; a
+ * high-speed train, 101, is rail; 405 is a monorail). Air, taxi and other
+ * services, and a value GTFS does not define, are `unknown`.
+ * @param {unknown} routeType
+ * @returns {string} One of TRANSIT_MODES.
+ */
+export function transitModeOfRouteType(routeType) {
+ const n = transitRouteType(routeType);
+ if (n === null) return 'unknown';
+ if (n < 100) return BASIC_ROUTE_TYPE_MODES[n] ?? 'unknown';
+ if (n === 405) return 'monorail';
+ const family = Math.floor(n / 100);
+ return (
+ {
+ 1: 'rail', // railway
+ 2: 'bus', // coach
+ 3: 'rail', // suburban railway
+ 4: 'subway', // urban railway
+ 5: 'subway', // metro
+ 6: 'subway', // underground
+ 7: 'bus',
+ 8: 'trolleybus',
+ 9: 'tram',
+ 10: 'ferry', // water transport
+ 12: 'ferry', // ferry
+ 13: 'aerial_lift',
+ 14: 'funicular',
+ }[family] ?? 'unknown'
+ );
+}
+
/**
* MBTA route ids are human-readable and mode-typed: rapid-transit lines carry
* colour names, commuter rail is prefixed `CR-`, ferries `Boat-`, buses are
@@ -443,7 +520,7 @@ const liaRouteLabel = routeIdPattern(/^8-0*(\w.*)$/);
function liaRouteMode(routeId) {
if (!routeId) return 'unknown';
const line = liaRouteLabel(routeId);
- if (line === 'FUNI') return 'rail';
+ if (line === 'FUNI') return 'funicular';
return /^[AB]$/.test(line) ? 'tram' : 'bus';
}
@@ -470,10 +547,14 @@ function astuceRouteLabel(routeId) {
return ASTUCE_ROUTES[routeId ?? '']?.label ?? astuceNetworkLabel(routeId);
}
+/** PID trolleybus lines: route_type 11 in PID's routes.txt (checked 2026-11-14). */
+const PID_TROLLEYBUS_LINES = new Set([51, 52, 53, 58, 59, 232, 275]);
+
/**
* Prague PID route ids are `L` plus a number whose range says what runs it,
* per PID's GTFS routes.txt (data.pid.cz, checked 2026-11-09): 1–99 trams
* (50–59 trolleybuses, 49 the Petřín funicular `LD`), 100–990 buses (the
+ * trolleybus routes 232 and 275 among them, GTFS route type 11; the
* 800s are the X replacement lines, `L803` is X3), 991–993 metro A–C,
* 1000s and 1100s the S and R trains (`L1004` is S4, `L1109` R9), the rest
* of 1200–1399 other trains, 1700s town buses, 1800s the P ferries, and from
@@ -487,7 +568,9 @@ function pidRoute(routeId) {
if (!match) return { mode: 'unknown', label: routeId };
const n = Number(match[1]);
// i18n-ignore: line code, as signed
- if (n === 49) return { mode: 'rail', label: 'LD' };
+ if (n === 49) return { mode: 'funicular', label: 'LD' };
+ if (PID_TROLLEYBUS_LINES.has(n))
+ return { mode: 'trolleybus', label: String(n) };
if (n >= 50 && n <= 59) return { mode: 'bus', label: String(n) };
if (n < 100) return { mode: 'tram', label: String(n) };
if (n >= 800 && n < 900) return { mode: 'bus', label: `X${n - 800}` };
@@ -512,6 +595,102 @@ function pidRouteLabel(routeId) {
return pidRoute(routeId).label;
}
+/**
+ * A feed's route hint from its static GTFS routes.txt: the route ids of
+ * every mode but `bus`, which is everything else.
+ * @param {Record
} idsByMode
+ * @returns {(routeId: string|null) => string}
+ */
+function routeModeTable(idsByMode) {
+ const modes = new Map(
+ Object.entries(idsByMode).flatMap(([mode, ids]) =>
+ ids.map((id) => [id, mode]),
+ ),
+ );
+ return (routeId) => (routeId ? (modes.get(routeId) ?? 'bus') : 'unknown');
+}
+
+/**
+ * Bucharest TPBI by route id, from its routes.txt (checked 2026-11-14): the
+ * trams (route type 0), metro lines M1–M5 (1) and trolleybuses (11); every
+ * other route is a bus. Realtime route ids are the static ones.
+ */
+const tpbiRouteMode = routeModeTable({
+ tram: [
+ '54',
+ '55',
+ '57',
+ '61',
+ '63',
+ '65',
+ '66',
+ '67',
+ '68',
+ '69',
+ '70',
+ '814',
+ '915',
+ '1013',
+ ],
+ subway: ['968', '969', '970', '971', '999'],
+ trolleybus: [
+ '72',
+ '73',
+ '74',
+ '75',
+ '76',
+ '78',
+ '81',
+ '83',
+ '84',
+ '85',
+ '86',
+ '87',
+ '247',
+ '910',
+ '916',
+ '924',
+ '925',
+ ],
+});
+
+/**
+ * Cluj-Napoca CTP by route id, from its routes.txt (checked 2026-11-14): the
+ * trams 100–102L (route type 0) and the trolleybuses (11).
+ */
+const ctpClujRouteMode = routeModeTable({
+ tram: ['2', '3', '4', '5'],
+ trolleybus: [
+ '1',
+ '10',
+ '14',
+ '15',
+ '22',
+ '36',
+ '49',
+ '53',
+ '54',
+ '55',
+ '117',
+ '119',
+ '120',
+ '153',
+ '166',
+ '187',
+ ],
+});
+
+/**
+ * Turin GTT by route id, from its routes.txt (checked 2026-11-14): the trams
+ * (route type 0), metro M1, and the Sassi–Superga rack tramway `79U`, which
+ * the file types as a funicular (7).
+ */
+const gttRouteMode = routeModeTable({
+ tram: ['3U', '4U', '7U', '9U', '10U', '13U', '15U', '16CDU', '16CSU'],
+ subway: ['METROU'],
+ funicular: ['79U'],
+});
+
/**
* Bordeaux TBM tram and boat lines by route id, from TBM's static GTFS
* routes.txt (checked 2026-11-09): the trams are numbered ids, not letters.
@@ -571,6 +750,7 @@ function transitFeed(fields) {
* url: string, headers?: Record,
* license: string, licenseUrl: string, attribution: string,
* defaultMode: string, routeMode?: (routeId: string|null) => string,
+ * routeCorrections?: Readonly>,
* speedUnit?: 'km/h', refreshMs?: number, sourceUrl?: string,
* creditDated?: boolean,
* }>>}
@@ -579,6 +759,9 @@ function transitFeed(fields) {
* stretches the proxy's cache for an upstream that rate-limits below one
* request per 15 s TTL. `sourceUrl` and `creditDated` add a link and a date
* to the credit for licences that ask for them (`transitFeedCredit`).
+ * `routeCorrections` names the routes whose `route_type` the operator's own
+ * routes.txt gets wrong, `route_id` to the mode they really are; a correction
+ * outranks the route type, which would otherwise outrank the route hint.
*/
export const TRANSIT_FEED_REGISTRY = Object.freeze([
Object.freeze({
@@ -1264,6 +1447,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
note: 'Keyless public endpoint from the metropolitan transport authority; no licence found. Same basis as Metro Transit and OVapi.',
},
defaultMode: 'bus',
+ routeMode: tpbiRouteMode,
}),
transitFeed({
id: 'roma-mobilita',
@@ -1296,6 +1480,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
note: 'Official keyless endpoint; no licence found. Same basis as Metro Transit and OVapi. Route ids append `U` for urban lines.',
},
defaultMode: 'bus',
+ routeMode: gttRouteMode,
routeLabel: gttRouteLabel,
}),
transitFeed({
@@ -1401,6 +1586,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi.',
},
defaultMode: 'bus',
+ routeMode: ctpClujRouteMode,
}),
transitFeed({
id: 'ctp-iasi',
@@ -1567,6 +1753,8 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
defaultMode: 'bus',
routeLabel: liaRouteLabel,
routeMode: liaRouteMode,
+ // LiA's routes.txt types the funicular (`8-FUNI`) as a bus (3).
+ routeCorrections: Object.freeze({ '8-FUNI': 'funicular' }),
}),
transitFeed({
id: 'filbleu-tours',
@@ -1664,54 +1852,89 @@ export function transitFeedsInRange(lat, lon, slackKm = 0) {
}
/**
- * The feed's own hint for a vehicle: its fleet number when the feed maps
- * those (`vehicleMode`), else its route (`routeMode`). Null when neither knows.
+ * What settles a vehicle's mode, most specific first: the feed's fleet hint
+ * (`vehicleMode`, which knows a bus standing in on a tram route), else the
+ * feed's correction for a route its routes.txt mistypes (`routeCorrections`),
+ * else the GTFS `route_type` of its route when the record carries one, else
+ * the feed's route hint (`routeMode`). Null when none of them knows.
* @param {object} feed Registry entry.
* @param {string|null} routeId
* @param {string|null} vehicleId
+ * @param {unknown} routeType GTFS `route_type`, when the record has one.
* @returns {string|null}
*/
-function hintedMode(feed, routeId, vehicleId) {
+function hintedMode(feed, routeId, vehicleId, routeType) {
const byVehicle =
typeof feed?.vehicleMode === 'function'
? feed.vehicleMode(vehicleId)
: null;
if (byVehicle && byVehicle !== 'unknown') return byVehicle;
+ const corrections = feed?.routeCorrections;
+ if (routeId && corrections && Object.hasOwn(corrections, routeId))
+ return corrections[routeId];
+ const byType = transitModeOfRouteType(routeType);
+ if (byType !== 'unknown') return byType;
return typeof feed?.routeMode === 'function' ? feed.routeMode(routeId) : null;
}
/**
- * Mode for a vehicle: the feed's fleet or route hint when it has one, else
- * its default.
+ * Mode for a vehicle: its fleet hint, route type or route hint when one
+ * knows ({@link hintedMode}), else its feed's default.
* @param {object} feed Registry entry.
* @param {string|null} routeId GTFS route_id from the vehicle's trip.
* @param {string|null} [vehicleId] GTFS-RT vehicle id.
+ * @param {unknown} [routeType] GTFS `route_type` of the route, when known.
* @returns {string} One of TRANSIT_MODES.
*/
-export function transitModeFor(feed, routeId, vehicleId = null) {
- const hinted = hintedMode(feed, routeId, vehicleId);
+export function transitModeFor(
+ feed,
+ routeId,
+ vehicleId = null,
+ routeType = null,
+) {
+ const hinted = hintedMode(feed, routeId, vehicleId, routeType);
const mode =
hinted && hinted !== 'unknown' ? hinted : feed?.defaultMode || 'unknown';
return TRANSIT_MODES.includes(mode) ? mode : 'unknown';
}
/**
- * Whether the mode came from the route id rather than the feed's default. A
- * default is a guess about a fleet — TransLink's is "bus" while it publishes
- * rail in the same feed — so a consumer judging physical plausibility must
- * not hold a defaulted vehicle to a bus's limits.
+ * Whether the mode came from the vehicle, its route type or its route id
+ * rather than the feed's default. A default is a guess about a fleet —
+ * TransLink's is "bus" while it publishes rail in the same feed — so a
+ * consumer judging physical plausibility must not hold a defaulted vehicle
+ * to a bus's limits.
* @param {object} feed Registry entry.
* @param {string|null} routeId
* @param {string|null} [vehicleId]
+ * @param {unknown} [routeType]
* @returns {boolean}
*/
-export function transitModeResolved(feed, routeId, vehicleId = null) {
- const hinted = hintedMode(feed, routeId, vehicleId);
+export function transitModeResolved(
+ feed,
+ routeId,
+ vehicleId = null,
+ routeType = null,
+) {
+ const hinted = hintedMode(feed, routeId, vehicleId, routeType);
return (
Boolean(hinted) && hinted !== 'unknown' && TRANSIT_MODES.includes(hinted)
);
}
+/**
+ * The route type a vehicle's model is chosen by: its record's, when that type
+ * is a kind of the mode it was given. A fleet hint can overrule the route (a
+ * bus on a tram route), and then the route's type does not describe it.
+ * @param {string} mode The vehicle's mode ({@link transitModeFor}).
+ * @param {unknown} routeType
+ * @returns {number|null}
+ */
+export function transitModelRouteType(mode, routeType) {
+ const n = transitRouteType(routeType);
+ return n !== null && transitModeOfRouteType(n) === mode ? n : null;
+}
+
/**
* The route as a rider would say it. Most feeds publish that already, so this
* is identity for them; a feed that publishes internal keys supplies its own
diff --git a/src/data/transitFeeds.test.mjs b/src/data/transitFeeds.test.mjs
index 75a902728..85a3a8243 100644
--- a/src/data/transitFeeds.test.mjs
+++ b/src/data/transitFeeds.test.mjs
@@ -11,9 +11,13 @@ import {
haversineKm,
publicTransitCatalog,
transitFeedsInRange,
+ TRANSIT_MODE_ICON,
transitModeFor,
+ transitModeOfRouteType,
transitModeResolved,
+ transitModelRouteType,
transitRouteLabel,
+ transitRouteType,
} from './transitFeeds.js';
import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
@@ -729,8 +733,10 @@ test('Prague route-id ranges give metro, trains, ferries and trolleybuses their
transitRouteLabel(feed, routeId),
];
assert.deepEqual(read('L22'), ['tram', '22']);
- assert.deepEqual(read('L58'), ['bus', '58'], 'trolleybus');
- assert.deepEqual(read('L49'), ['rail', 'LD'], 'Petřín funicular');
+ assert.deepEqual(read('L58'), ['trolleybus', '58']);
+ assert.deepEqual(read('L55'), ['bus', '55'], 'not a PID trolleybus line');
+ assert.deepEqual(read('L275'), ['trolleybus', '275'], 'route type 11');
+ assert.deepEqual(read('L49'), ['funicular', 'LD'], 'Petřín funicular');
assert.deepEqual(read('L135'), ['bus', '135']);
assert.deepEqual(read('L803'), ['bus', 'X3']);
assert.deepEqual(read('L991'), ['subway', 'A']);
@@ -767,7 +773,7 @@ test('Rouen Métro and Calypso are not buses; Le Havre reads its own ids', () =>
assert.equal(transitModeFor(feed, 'TCAR:93'), 'bus');
assert.equal(transitRouteLabel(feed, 'TAE:F'), 'F');
const lia = getTransitFeed('lia-le-havre');
- assert.equal(transitModeFor(lia, '8-FUNI'), 'rail');
+ assert.equal(transitModeFor(lia, '8-FUNI'), 'funicular');
assert.equal(transitRouteLabel(lia, '8-C3'), 'C3');
assert.equal(transitRouteLabel(lia, '8-09'), '9');
assert.equal(transitRouteLabel(lia, '8-A'), 'A');
@@ -778,3 +784,114 @@ test('data.gov.my feeds ask the proxy for no more than its 4 a minute', () => {
assert.ok(getTransitFeed(id).refreshMs >= 30_000, id);
}
});
+
+test('a GTFS route type names its mode, basic and extended alike', () => {
+ for (const [routeType, mode] of [
+ [0, 'tram'],
+ [1, 'subway'],
+ [2, 'rail'],
+ [3, 'bus'],
+ [4, 'ferry'],
+ [5, 'cable_tram'],
+ [6, 'aerial_lift'],
+ [7, 'funicular'],
+ [11, 'trolleybus'],
+ [12, 'monorail'],
+ [101, 'rail'],
+ [106, 'rail'],
+ [200, 'bus'],
+ [300, 'rail'],
+ [401, 'subway'],
+ [405, 'monorail'],
+ [702, 'bus'],
+ [800, 'trolleybus'],
+ [900, 'tram'],
+ [1000, 'ferry'],
+ [1200, 'ferry'],
+ [1300, 'aerial_lift'],
+ [1400, 'funicular'],
+ ['11', 'trolleybus'],
+ ])
+ assert.equal(transitModeOfRouteType(routeType), mode, String(routeType));
+ // Air, taxi and other services, and values GTFS does not define.
+ for (const other of [8, 1100, 1500, 1700, 1800, -1, 2.5, '', 'tram', null])
+ assert.equal(transitModeOfRouteType(other), 'unknown', String(other));
+ assert.equal(transitRouteType(' 200 '), 200);
+ assert.equal(transitRouteType('2e2'), null);
+});
+
+test('every mode has an icon, and every mode a route type names is a mode', () => {
+ for (const mode of TRANSIT_MODES) assert.ok(TRANSIT_MODE_ICON[mode], mode);
+ for (let routeType = 0; routeType < 1800; routeType++)
+ assert.ok(TRANSIT_MODES.includes(transitModeOfRouteType(routeType)));
+});
+
+test('a route type settles the mode before a route hint or the default', () => {
+ const mbta = getTransitFeed('mbta');
+ // The hint calls every numbered MBTA route a bus; a route type is finer.
+ assert.equal(transitModeFor(mbta, '71'), 'bus');
+ assert.equal(transitModeFor(mbta, '71', 'y1', 11), 'trolleybus');
+ assert.equal(transitModeResolved(mbta, '71', 'y1', 11), true);
+ // A default-only feed is resolved by a route type alone.
+ const durham = getTransitFeed('durham-region');
+ assert.equal(transitModeResolved(durham, '915', 'b1'), false);
+ assert.equal(transitModeFor(durham, '915', 'b1', 200), 'bus');
+ assert.equal(transitModeResolved(durham, '915', 'b1', 200), true);
+ // A type that names no mode leaves the hints in charge.
+ assert.equal(transitModeFor(mbta, 'Red', null, 1700), 'subway');
+ assert.equal(transitModeFor(mbta, 'Red', null, 'x'), 'subway');
+});
+
+test('a fleet hint outranks the route type, and then the type picks no model', () => {
+ const ttc = getTransitFeed('ttc-toronto');
+ // A bus standing in on the 501 streetcar route (route type 0).
+ const mode = transitModeFor(ttc, '501', '8400', 0);
+ assert.equal(mode, 'bus');
+ assert.equal(transitModelRouteType(mode, 0), null);
+ assert.equal(transitModelRouteType('tram', 0), 0);
+ assert.equal(transitModelRouteType('bus', 200), 200, 'a coach is a bus');
+ assert.equal(transitModelRouteType('bus', null), null);
+});
+
+test('a route correction outranks a mistyped route type, and only for its route', () => {
+ const lia = getTransitFeed('lia-le-havre');
+ // LiA's routes.txt types the funicular as a bus (3).
+ assert.equal(transitModeFor(lia, '8-FUNI', null, 3), 'funicular');
+ assert.equal(transitModeResolved(lia, '8-FUNI', null, 3), true);
+ // A correction is a mode, so the bus type picks no model for it.
+ assert.equal(transitModelRouteType('funicular', 3), null);
+ // Every other route still takes its route type.
+ assert.equal(transitModeFor(lia, '8-A', null, 0), 'tram');
+ assert.equal(transitModeFor(lia, '8-C3', null, 3), 'bus');
+ assert.equal(transitModeFor(lia, null, null, 3), 'bus');
+ // Corrections are narrow: a few named routes, each to a known mode.
+ for (const feed of TRANSIT_FEED_REGISTRY) {
+ if (!feed.routeCorrections) continue;
+ assert.ok(Object.isFrozen(feed.routeCorrections), feed.id);
+ for (const [route, mode] of Object.entries(feed.routeCorrections)) {
+ assert.ok(TRANSIT_MODES.includes(mode), `${feed.id} ${route}`);
+ assert.notEqual(mode, 'unknown', `${feed.id} ${route}`);
+ }
+ }
+ // An inherited key is not a correction.
+ assert.equal(transitModeFor(lia, 'toString', null, 3), 'bus');
+});
+
+// Route ids as each realtime feed and its operator's routes.txt carried them
+// on 2026-11-14.
+test('Bucharest, Cluj and Turin route ids give trams, trolleybuses and a funicular', () => {
+ const mode = (id, routeId) => transitModeFor(getTransitFeed(id), routeId);
+ assert.equal(mode('tpbi-bucuresti', '85'), 'trolleybus', 'line 74');
+ assert.equal(mode('tpbi-bucuresti', '1013'), 'tram', 'line 4');
+ assert.equal(mode('tpbi-bucuresti', '968'), 'subway', 'M1');
+ assert.equal(mode('tpbi-bucuresti', '828'), 'bus');
+ assert.equal(mode('tpbi-bucuresti', 'PV1_407'), 'bus');
+ assert.equal(mode('ctp-cluj', '1'), 'trolleybus');
+ assert.equal(mode('ctp-cluj', '2'), 'tram', 'line 100');
+ assert.equal(mode('ctp-cluj', '6'), 'bus', 'line 19');
+ assert.equal(mode('gtt-torino', '79U'), 'funicular', 'Sassi–Superga');
+ assert.equal(mode('gtt-torino', '16CDU'), 'tram');
+ assert.equal(mode('gtt-torino', 'METROU'), 'subway');
+ assert.equal(mode('gtt-torino', '6U'), 'bus');
+ assert.equal(mode('gtt-torino', null), 'bus', 'no route: the default');
+});
diff --git a/src/data/transitIcons.js b/src/data/transitIcons.js
index 453414a6c..6d83ec1ad 100644
--- a/src/data/transitIcons.js
+++ b/src/data/transitIcons.js
@@ -21,7 +21,9 @@ import {
* at the ~18 px the fleet renders at, by shape and not only by colour: a bus is
* short and blunt, a tram is long and slender with articulation joints, a metro
* car is squared off, a mainline train has a tapered nose, and a ferry is a
- * hull with a bow.
+ * hull with a bow. A trolleybus trails its two poles, a cable car is a short
+ * single car, a monorail the slimmest bullet, a funicular hangs off its rope,
+ * and a gondola is a cabin on its cable.
*
* Interior detail is drawn with the same dark hairline as the edge — windscreen
* lines, articulation joints, a deck line — because a solid dark panel would
@@ -103,6 +105,49 @@ const HEADING_BODIES = {
fill="white" ${STROKE}/>
`,
+ // ── Trolleybus: a bus a little narrower, trailing the two trolley poles
+ // that reach back to its wires. Body and poles are one outline, so no
+ // edge is drawn across the body.
+ trolleybus: `
+
+ `,
+
+ // ── Cable car (street cable railway): a short single car, under half a
+ // tram, with open platforms at both ends.
+ cable_tram: `
+
+
+ `,
+
+ // ── Monorail: the slimmest train in the set, a rounded bullet nose over
+ // its beam.
+ monorail: `
+
+ `,
+
+ // ── Funicular: a squat car hauled by the rope at its upper end.
+ funicular: `
+
+
+ `,
+
+ // ── Gondola (aerial lift): a cabin hung on the cable that runs through
+ // it; the cabin's nose is its front.
+ aerial_lift: `
+ `,
+
// ── Unknown: a plain marker with a nose and nothing else, so an
// unclassified vehicle never pretends to be a mode it is not.
unknown: `
@@ -146,6 +191,40 @@ const NEUTRAL_BODIES = {
fill="white" ${STROKE}/>
`,
+ trolleybus: `
+ `,
+
+ cable_tram: `
+
+
+ `,
+
+ monorail: `
+
+ `,
+
+ funicular: `
+
+
+ `,
+
+ aerial_lift: `
+ `,
+
unknown: `
{
+test('every variant retains the specified final halo at both display sizes', async () => {
const { presetSpriteScale, presetSpriteOutlinePx } =
await import('./transitPresetStyle.js');
for (const kind of TRANSIT_ICON_KINDS) {
@@ -96,7 +96,8 @@ test('all 72 variants retain the specified final halo at both display sizes', as
}
for (let i = 0; i < 100; i++)
transitIcon('invalid', i, { haloScreenPx: i, screenPx: i });
- assert.equal(transitIconCacheSize(), 72);
+ // Every kind at two sizes, three profiles, with and without a course.
+ assert.equal(transitIconCacheSize(), TRANSIT_ICON_KINDS.length * 12);
});
test('every mono raster preserves the normal silhouette mask and aspect at CRT display size', async () => {
@@ -194,6 +195,11 @@ test('sensor raster halo stays dark across its screen-space band on a white roof
subway: 11.5,
rail: 10.5,
ferry: 12.5,
+ trolleybus: 15,
+ cable_tram: 11,
+ monorail: 8.5,
+ funicular: 11,
+ aerial_lift: 12,
unknown: 10,
};
for (const selected of [false, true]) {
diff --git a/src/data/transitPresetStyle.js b/src/data/transitPresetStyle.js
index 5996d4d97..cfb39053a 100644
--- a/src/data/transitPresetStyle.js
+++ b/src/data/transitPresetStyle.js
@@ -60,9 +60,14 @@ const SPRITE_STYLE = Object.freeze({
outlinePx: 1.25,
rgbaByMode: Object.freeze({
bus: Object.freeze([0, 255, 102, 1]),
+ trolleybus: Object.freeze([170, 255, 0, 1]),
tram: Object.freeze([255, 179, 0, 1]),
+ cable_tram: Object.freeze([255, 120, 0, 1]),
subway: Object.freeze([255, 59, 48, 1]),
+ monorail: Object.freeze([255, 64, 170, 1]),
rail: Object.freeze([215, 139, 255, 1]),
+ funicular: Object.freeze([255, 214, 140, 1]),
+ aerial_lift: Object.freeze([90, 140, 255, 1]),
ferry: Object.freeze([58, 208, 255, 1]),
unknown: Object.freeze([255, 255, 255, 1]),
}),
@@ -72,9 +77,14 @@ const SPRITE_STYLE = Object.freeze({
/** Modes with a bracket tier of their own. */
const TIER_MODES = Object.freeze([
'bus',
+ 'trolleybus',
'tram',
+ 'cable_tram',
'subway',
+ 'monorail',
'rail',
+ 'funicular',
+ 'aerial_lift',
'ferry',
'unknown',
]);
@@ -128,7 +138,7 @@ export function presetSpriteOutlinePx(styleName, selected = false) {
/**
* Detection-overlay tier key for a transit mode. Every theme's `tiers`
- * table carries these six, so the bracket colour is per mode in every
+ * table carries one per mode, so the bracket colour is per mode in every
* preset. Unlike traffic, transit sets its tier keyless as well: the feeds
* are keyless, and there is no separate keyless experience to keep
* byte-identical.
diff --git a/src/data/transitProxy.js b/src/data/transitProxy.js
index 6b328e5a5..e601a592d 100644
--- a/src/data/transitProxy.js
+++ b/src/data/transitProxy.js
@@ -19,6 +19,7 @@ import {
decodeVehiclePositions,
} from './gtfsRealtime.js';
import { getTransitFeed } from './transitFeeds.js';
+export { transitModeFor, transitRouteType } from './transitFeeds.js';
/** Fresh window: a snapshot younger than this is served without refetching. */
export const TRANSIT_PROXY_TTL_MS = 15_000;
diff --git a/src/data/vesselLabels.js b/src/data/vesselLabels.js
index 0a8a164f7..3a237f53b 100644
--- a/src/data/vesselLabels.js
+++ b/src/data/vesselLabels.js
@@ -46,6 +46,15 @@ const TYPE_STYLES = [
];
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
+/**
+ * An aid to navigation's disc and card accent: a bone white apart from every
+ * ship type's colour.
+ */
+export const AID_TO_NAVIGATION_STYLE = Object.freeze({
+ css: '#d9d2c0',
+ accent: '217, 210, 192',
+});
+
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
// and tests match on them.
const TYPE_DISPLAY_KEYS = Object.freeze({
diff --git a/src/data/vesselTypes.js b/src/data/vesselTypes.js
index 550f4596b..742187548 100644
--- a/src/data/vesselTypes.js
+++ b/src/data/vesselTypes.js
@@ -45,3 +45,110 @@ export function normalizeVesselType(type) {
if (NUMERIC_TYPE_SPECIALS[code]) return NUMERIC_TYPE_SPECIALS[code];
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
}
+
+/**
+ * The kind of aid to navigation an AIS aid-to-navigation report (message 21)
+ * names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
+ * floating marks by their cardinal quadrant, lateral side, safe water,
+ * isolated danger or special mark, and the lights, RACONs and reference
+ * points around them. Code 0 names no kind.
+ */
+const AID_TYPE_NAMES = Object.freeze([
+ 'Navigation aid',
+ 'Reference point',
+ 'RACON',
+ 'Fixed structure off shore',
+ 'Emergency wreck marking buoy',
+ 'Light, without sectors',
+ 'Light, with sectors',
+ 'Leading light front',
+ 'Leading light rear',
+ 'Beacon, Cardinal N',
+ 'Beacon, Cardinal E',
+ 'Beacon, Cardinal S',
+ 'Beacon, Cardinal W',
+ 'Beacon, Port hand',
+ 'Beacon, Starboard hand',
+ 'Beacon, Preferred channel port hand',
+ 'Beacon, Preferred channel starboard hand',
+ 'Beacon, Isolated danger',
+ 'Beacon, Safe water',
+ 'Beacon, Special mark',
+ 'Cardinal Mark N',
+ 'Cardinal Mark E',
+ 'Cardinal Mark S',
+ 'Cardinal Mark W',
+ 'Port hand Mark',
+ 'Starboard hand Mark',
+ 'Preferred Channel Port hand',
+ 'Preferred Channel Starboard hand',
+ 'Isolated danger',
+ 'Safe Water',
+ 'Special Mark',
+ 'Light Vessel / LANBY / Rigs',
+]);
+
+/**
+ * The kind an AIS aid-to-navigation type code names ("19" → "Beacon, Special
+ * mark"); "Navigation aid" for code 0 and for a code outside 0 to 31.
+ * @param {string|number|null|undefined} code
+ * @returns {string}
+ */
+export function aidToNavigationTypeName(code) {
+ const text = String(code ?? '').trim();
+ const index = /^\d+$/.test(text) ? Number(text) : -1;
+ return AID_TYPE_NAMES[index] ?? AID_TYPE_NAMES[0];
+}
+
+/** Every kind {@link aidToNavigationTypeName} names, lowercased. */
+const AID_TYPE_NAME_SET = new Set(
+ AID_TYPE_NAMES.map((name) => name.toLowerCase()),
+);
+
+/**
+ * Words a vessel type uses for an aid to navigation. A vessel that works on
+ * one ("Buoy Tender", "Buoy-Laying Vessel", "Buoy Layer") is a ship underway,
+ * not a mark on the water.
+ */
+const AID_TYPE_TEXT =
+ /navaid|\baton\b|aids? to nav|nav(igation)? aid|racon|lighthouse|lightship|light vessel|reference point|hand mark|cardinal|safe water|preferred channel|isolated danger|special mark|beacon|buoy/i;
+const AID_WORKER_TEXT = /tender|lay(ing|er)\b/i;
+
+/** ITU MID 99: the MMSI of an AIS aid-to-navigation station (99MIDxxxx). */
+const AID_MMSI = /^99\d{7}$/;
+
+/**
+ * Whether each type text seen names an aid. Vessel layers ask per vessel on
+ * their draw passes, and a feed uses few distinct type texts, so each is
+ * matched once; the memo is bounded against a feed of free-form types.
+ */
+const AID_TYPE_MEMO = new Map();
+const AID_TYPE_MEMO_MAX = 1024;
+
+function typeNamesAid(text) {
+ let aid = AID_TYPE_MEMO.get(text);
+ if (aid !== undefined) return aid;
+ aid =
+ AID_TYPE_NAME_SET.has(text.toLowerCase()) ||
+ (AID_TYPE_TEXT.test(text) && !AID_WORKER_TEXT.test(text));
+ if (AID_TYPE_MEMO.size >= AID_TYPE_MEMO_MAX) AID_TYPE_MEMO.clear();
+ AID_TYPE_MEMO.set(text, aid);
+ return aid;
+}
+
+/**
+ * Whether a vessel record is an aid to navigation (a buoy, beacon, mark,
+ * RACON or light) rather than a vessel: its type is one of the kinds an aid
+ * report names or uses a word for one, or its MMSI is an aid-to-navigation
+ * station's, or it is a virtual aid. A numeric AIS ship type never names one.
+ * @param {{type?: string|number|null, mmsi?: string|number|null,
+ * virtual?: boolean}} vessel
+ * @returns {boolean}
+ */
+export function isAidToNavigation({ type, mmsi, virtual } = {}) {
+ if (virtual === true) return true;
+ const text = typeof type === 'string' ? type.trim() : String(type ?? '');
+ if (text && typeNamesAid(text)) return true;
+ if (mmsi === null || mmsi === undefined || mmsi === '') return false;
+ return AID_MMSI.test(typeof mmsi === 'string' ? mmsi.trim() : String(mmsi));
+}
diff --git a/src/data/vesselTypes.test.mjs b/src/data/vesselTypes.test.mjs
new file mode 100644
index 000000000..65816743c
--- /dev/null
+++ b/src/data/vesselTypes.test.mjs
@@ -0,0 +1,61 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { aidToNavigationTypeName, isAidToNavigation } from './vesselTypes.js';
+
+test('an aid-to-navigation type code names its kind of aid', () => {
+ assert.equal(aidToNavigationTypeName(20), 'Cardinal Mark N');
+ assert.equal(aidToNavigationTypeName('13'), 'Beacon, Port hand');
+ assert.equal(aidToNavigationTypeName(2), 'RACON');
+ assert.equal(aidToNavigationTypeName(29), 'Safe Water');
+ assert.equal(aidToNavigationTypeName(31), 'Light Vessel / LANBY / Rigs');
+ // Code 0, a code past 31 and no code name no kind.
+ for (const code of [0, 32, -1, '', null, undefined, 'x'])
+ assert.equal(aidToNavigationTypeName(code), 'Navigation aid', code);
+});
+
+test('aids to navigation are known by their type, else their MMSI', () => {
+ for (const type of [
+ 'Beacon, Special Mark',
+ 'Cardinal Mark N',
+ 'Port Hand Mark',
+ 'Starboard Hand Mark',
+ 'Safe Water',
+ 'Isolated danger',
+ 'Preferred Channel Port hand',
+ 'RACON',
+ 'Light Vessel / LANBY / Rigs',
+ 'Reference point',
+ 'Navigation aid',
+ 'AtoN',
+ 'Lighthouse',
+ 'Buoy',
+ // Every kind an aid report names is an aid, whatever its MMSI.
+ 'Light, with sectors',
+ 'Leading light rear',
+ 'Fixed structure off shore',
+ 'Emergency wreck marking buoy',
+ ])
+ assert.equal(isAidToNavigation({ type, mmsi: '' }), true, type);
+ // A virtual aid is an aid whatever its type or MMSI.
+ assert.equal(
+ isAidToNavigation({ type: '', mmsi: '', virtual: true }),
+ true,
+ );
+ // AIS aid-to-navigation stations are numbered 99MIDxxxx.
+ assert.equal(isAidToNavigation({ type: '', mmsi: '993672001' }), true);
+ assert.equal(isAidToNavigation({ type: '0', mmsi: ' 992351234 ' }), true);
+ for (const vessel of [
+ { type: 'Buoy Tender', mmsi: '366999001' },
+ { type: 'Buoy-Laying Vessel', mmsi: '' },
+ { type: 'Buoy Layer', mmsi: '' },
+ { type: 'Lighter', mmsi: '' },
+ { type: 'Flight deck', mmsi: '' },
+ { type: 70, mmsi: 366999002 },
+ { type: '70', mmsi: '366999002' },
+ { type: '0', mmsi: '' },
+ { type: 'Cargo', mmsi: '99' },
+ { type: 'Passenger', mmsi: '9936720011' },
+ {},
+ ])
+ assert.equal(isAidToNavigation(vessel), false, JSON.stringify(vessel));
+});
diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json
index 7ccc204e4..c42e7e25b 100644
--- a/src/i18n/locales/ar.json
+++ b/src/i18n/locales/ar.json
@@ -775,6 +775,8 @@
"TANKER": "ناقلة",
"OTHER": "أخرى",
"VESSEL": "سفينة",
+ "AID TO NAVIGATION": "مساعدة ملاحية",
+ "VIRTUAL": "افتراضي",
"POS: LIVE": "الموضع: مباشر",
"POS: {time}Z": "الموضع: {time}Z",
"AIS: --": "AIS: --",
@@ -3971,5 +3973,12 @@
"Reset view reloads the app without the view restored from the address bar.": "تعيد «إعادة ضبط العرض» تحميل التطبيق دون العرض المستعاد من شريط العنوان.",
"Reload": "إعادة التحميل",
"Retry": "إعادة المحاولة",
- "Reset view": "إعادة ضبط العرض"
+ "Reset view": "إعادة ضبط العرض",
+ "Trolleybus": "ترولي باص",
+ "Cable car": "ترام كابلي",
+ "Monorail": "قطار أحادي السكة",
+ "Funicular": "قطار جبلي مائل",
+ "Gondola": "تلفريك",
+ "Move panels back beside the rail": "إعادة اللوحات إلى جانب الشريط",
+ "Move panels over the rail, to the edge": "نقل اللوحات فوق الشريط إلى الحافة"
}
diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json
index b23d680c8..d23b3e225 100644
--- a/src/i18n/locales/de.json
+++ b/src/i18n/locales/de.json
@@ -415,6 +415,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "SCHIFF",
+ "AID TO NAVIGATION": "SEEZEICHEN",
+ "VIRTUAL": "VIRTUELL",
"POS: LIVE": "POS: LIVE",
"POS: {time}Z": "POS: {time}Z",
"awaiting first AIS position…": "warten auf erste AIS-Position…",
@@ -3623,5 +3625,12 @@
"Reset view reloads the app without the view restored from the address bar.": "Ansicht zurücksetzen lädt die App ohne die aus der Adressleiste wiederhergestellte Ansicht neu.",
"Reload": "Neu laden",
"Retry": "Erneut versuchen",
- "Reset view": "Ansicht zurücksetzen"
+ "Reset view": "Ansicht zurücksetzen",
+ "Trolleybus": "Oberleitungsbus",
+ "Cable car": "Kabelstraßenbahn",
+ "Monorail": "Einschienenbahn",
+ "Funicular": "Standseilbahn",
+ "Gondola": "Gondelbahn",
+ "Move panels back beside the rail": "Bedienfelder zurück neben die Leiste",
+ "Move panels over the rail, to the edge": "Bedienfelder über die Leiste an den Rand verschieben"
}
diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json
index 84b1f477e..edbdb7cc9 100644
--- a/src/i18n/locales/es.json
+++ b/src/i18n/locales/es.json
@@ -649,6 +649,8 @@
"TANKER": "PETROLERO",
"OTHER": "OTRO",
"VESSEL": "BUQUE",
+ "AID TO NAVIGATION": "AYUDA A LA NAVEGACIÓN",
+ "VIRTUAL": "VIRTUAL",
"POS: LIVE": "POS: EN VIVO",
"POS: {time}Z": "POS: {time}Z",
"AIS: --": "AIS: --",
@@ -3710,5 +3712,12 @@
"Reset view reloads the app without the view restored from the address bar.": "Restablecer la vista recarga la app sin la vista restaurada desde la barra de direcciones.",
"Reload": "Recargar",
"Retry": "Reintentar",
- "Reset view": "Restablecer la vista"
+ "Reset view": "Restablecer la vista",
+ "Trolleybus": "Trolebús",
+ "Cable car": "Tranvía de cable",
+ "Monorail": "Monorraíl",
+ "Funicular": "Funicular",
+ "Gondola": "Góndola",
+ "Move panels back beside the rail": "Devolver los paneles junto a la barra",
+ "Move panels over the rail, to the edge": "Mover los paneles sobre la barra, hasta el borde"
}
diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json
index 773a0f95a..b0320cd29 100644
--- a/src/i18n/locales/fr.json
+++ b/src/i18n/locales/fr.json
@@ -1290,6 +1290,8 @@
"AIS: {name}": "AIS : {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD : {speed} HDG : {heading}",
"VESSEL": "NAVIRE",
+ "AID TO NAVIGATION": "AIDE À LA NAVIGATION",
+ "VIRTUAL": "VIRTUEL",
"{speed}KT": "{speed} ND",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS : DIRECT",
@@ -3710,5 +3712,12 @@
"Reset view reloads the app without the view restored from the address bar.": "Réinitialiser la vue recharge l’app sans la vue restaurée depuis la barre d’adresse.",
"Reload": "Recharger",
"Retry": "Réessayer",
- "Reset view": "Réinitialiser la vue"
+ "Reset view": "Réinitialiser la vue",
+ "Trolleybus": "Trolleybus",
+ "Cable car": "Tramway à câble",
+ "Monorail": "Monorail",
+ "Funicular": "Funiculaire",
+ "Gondola": "Télécabine",
+ "Move panels back beside the rail": "Remettre les panneaux à côté de la barre",
+ "Move panels over the rail, to the edge": "Déplacer les panneaux par-dessus la barre, jusqu’au bord"
}
diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json
index d52265837..2ee2cee1b 100644
--- a/src/i18n/locales/he.json
+++ b/src/i18n/locales/he.json
@@ -1148,6 +1148,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "אונייה",
+ "AID TO NAVIGATION": "עזר ניווט",
+ "VIRTUAL": "וירטואלי",
"{speed}KT": "{speed} קשר",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS: חי",
@@ -3710,5 +3712,12 @@
"Reset view reloads the app without the view restored from the address bar.": "\"איפוס תצוגה\" טוען מחדש את האפליקציה בלי התצוגה ששוחזרה משורת הכתובת.",
"Reload": "טען מחדש",
"Retry": "נסה שוב",
- "Reset view": "איפוס תצוגה"
+ "Reset view": "איפוס תצוגה",
+ "Trolleybus": "טרוליבוס",
+ "Cable car": "חשמלית כבלים",
+ "Monorail": "מונורייל",
+ "Funicular": "פוניקולר",
+ "Gondola": "רכבל",
+ "Move panels back beside the rail": "החזרת הלוחות לצד הסרגל",
+ "Move panels over the rail, to the edge": "הזזת הלוחות מעל הסרגל, אל הקצה"
}
diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json
index 7eb03a710..73de3f271 100644
--- a/src/i18n/locales/it.json
+++ b/src/i18n/locales/it.json
@@ -1290,6 +1290,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} VEL: {speed} HDG: {heading}",
"VESSEL": "NAVE",
+ "AID TO NAVIGATION": "AIUTO ALLA NAVIGAZIONE",
+ "VIRTUAL": "VIRTUALE",
"{speed}KT": "{speed}KT",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS: LIVE",
@@ -3710,5 +3712,12 @@
"Reset view reloads the app without the view restored from the address bar.": "Ripristina vista ricarica l’app senza la vista ripristinata dalla barra degli indirizzi.",
"Reload": "Ricarica",
"Retry": "Riprova",
- "Reset view": "Ripristina vista"
+ "Reset view": "Ripristina vista",
+ "Trolleybus": "Filobus",
+ "Cable car": "Tram a fune",
+ "Monorail": "Monorotaia",
+ "Funicular": "Funicolare",
+ "Gondola": "Cabinovia",
+ "Move panels back beside the rail": "Riporta i pannelli accanto alla barra",
+ "Move panels over the rail, to the edge": "Sposta i pannelli sopra la barra, fino al bordo"
}
diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json
index fe108d6a8..02dca3b7d 100644
--- a/src/i18n/locales/ja.json
+++ b/src/i18n/locales/ja.json
@@ -1252,6 +1252,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "船舶",
+ "AID TO NAVIGATION": "航路標識",
+ "VIRTUAL": "仮想",
"{speed}KT": "{speed} kt",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS: ライブ",
@@ -3536,5 +3538,12 @@
"Reset view reloads the app without the view restored from the address bar.": "「ビューをリセット」は、アドレスバーから復元したビューを使わずにアプリを再読み込みします。",
"Reload": "再読み込み",
"Retry": "再試行",
- "Reset view": "ビューをリセット"
+ "Reset view": "ビューをリセット",
+ "Trolleybus": "トロリーバス",
+ "Cable car": "ケーブルトラム",
+ "Monorail": "モノレール",
+ "Funicular": "ケーブルカー",
+ "Gondola": "ゴンドラ",
+ "Move panels back beside the rail": "パネルをレールの横に戻す",
+ "Move panels over the rail, to the edge": "パネルをレールの上、画面端へ移動"
}
diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json
index ddceca56d..6859125e6 100644
--- a/src/i18n/locales/pt.json
+++ b/src/i18n/locales/pt.json
@@ -1288,6 +1288,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "EMBARCAÇÃO",
+ "AID TO NAVIGATION": "AUXÍLIO À NAVEGAÇÃO",
+ "VIRTUAL": "VIRTUAL",
"{speed}KT": "{speed} KT",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS: AO VIVO",
@@ -3710,5 +3712,12 @@
"Reset view reloads the app without the view restored from the address bar.": "Redefinir vista recarrega o app sem a vista restaurada da barra de endereços.",
"Reload": "Recarregar",
"Retry": "Tentar novamente",
- "Reset view": "Redefinir vista"
+ "Reset view": "Redefinir vista",
+ "Trolleybus": "Trólebus",
+ "Cable car": "Bonde a cabo",
+ "Monorail": "Monotrilho",
+ "Funicular": "Funicular",
+ "Gondola": "Teleférico",
+ "Move panels back beside the rail": "Voltar os painéis para junto da barra",
+ "Move panels over the rail, to the edge": "Mover os painéis sobre a barra, até a borda"
}
diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json
index 69da590fc..d0aa48e4e 100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@ -393,6 +393,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} СКОР: {speed} КУРС: {heading}",
"VESSEL": "СУДНО",
+ "AID TO NAVIGATION": "СРЕДСТВО НАВИГАЦИИ",
+ "VIRTUAL": "ВИРТУАЛЬНЫЙ",
"AIS: --": "AIS: --",
"awaiting first AIS position…": "ожидание первой позиции AIS…",
"awaiting usable AIS positions…": "ожидание пригодных позиций AIS…",
@@ -3797,5 +3799,12 @@
"Reset view reloads the app without the view restored from the address bar.": "«Сбросить вид» перезагружает приложение без вида, восстановленного из адресной строки.",
"Reload": "Перезагрузить",
"Retry": "Повторить",
- "Reset view": "Сбросить вид"
+ "Reset view": "Сбросить вид",
+ "Trolleybus": "Троллейбус",
+ "Cable car": "Канатный трамвай",
+ "Monorail": "Монорельс",
+ "Funicular": "Фуникулёр",
+ "Gondola": "Канатная дорога",
+ "Move panels back beside the rail": "Вернуть панели к боковой панели",
+ "Move panels over the rail, to the edge": "Переместить панели поверх боковой панели к краю"
}
diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json
index d82929d9d..41858177b 100644
--- a/src/i18n/locales/sv.json
+++ b/src/i18n/locales/sv.json
@@ -381,6 +381,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "FARTYG",
+ "AID TO NAVIGATION": "SJÖMÄRKE",
+ "VIRTUAL": "VIRTUELL",
"POS: LIVE": "POS: LIVE",
"POS: {time}Z": "POS: {time}Z",
"awaiting first AIS position…": "väntar på första AIS-positionen …",
@@ -3623,5 +3625,12 @@
"Reset view reloads the app without the view restored from the address bar.": "”Återställ vy” laddar om appen utan vyn som återställdes från adressfältet.",
"Reload": "Ladda om",
"Retry": "Försök igen",
- "Reset view": "Återställ vy"
+ "Reset view": "Återställ vy",
+ "Trolleybus": "Trådbuss",
+ "Cable car": "Kabelspårvagn",
+ "Monorail": "Enskensbana",
+ "Funicular": "Bergbana",
+ "Gondola": "Kabinbana",
+ "Move panels back beside the rail": "Flytta tillbaka panelerna bredvid listen",
+ "Move panels over the rail, to the edge": "Flytta panelerna över listen, till kanten"
}
diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json
index c3f36b4e6..39fa54f11 100644
--- a/src/i18n/locales/uk.json
+++ b/src/i18n/locales/uk.json
@@ -1308,6 +1308,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} ШВИД: {speed} КУРС: {heading}",
"VESSEL": "СУДНО",
+ "AID TO NAVIGATION": "ЗАСІБ НАВІГАЦІЇ",
+ "VIRTUAL": "ВІРТУАЛЬНИЙ",
"{speed}KT": "{speed} ВУЗ",
"{heading}DEG": "{heading}°",
"POS: LIVE": "ПОЗ.: ОНЛАЙН",
@@ -3797,5 +3799,12 @@
"Reset view reloads the app without the view restored from the address bar.": "«Скинути вигляд» перезавантажує застосунок без вигляду, відновленого з адресного рядка.",
"Reload": "Перезавантажити",
"Retry": "Повторити",
- "Reset view": "Скинути вигляд"
+ "Reset view": "Скинути вигляд",
+ "Trolleybus": "Тролейбус",
+ "Cable car": "Канатний трамвай",
+ "Monorail": "Монорейка",
+ "Funicular": "Фунікулер",
+ "Gondola": "Канатна дорога",
+ "Move panels back beside the rail": "Повернути панелі до бічної смуги",
+ "Move panels over the rail, to the edge": "Перемістити панелі поверх бічної смуги до краю"
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 72ee79dd9..c541fdf49 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -1228,6 +1228,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "船舶",
+ "AID TO NAVIGATION": "助航标志",
+ "VIRTUAL": "虚拟",
"{speed}KT": "{speed} kn",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS:实时",
@@ -3536,5 +3538,12 @@
"Reset view reloads the app without the view restored from the address bar.": "“重置视图”会重新加载应用,不使用从地址栏恢复的视图。",
"Reload": "重新加载",
"Retry": "重试",
- "Reset view": "重置视图"
+ "Reset view": "重置视图",
+ "Trolleybus": "无轨电车",
+ "Cable car": "缆索电车",
+ "Monorail": "单轨列车",
+ "Funicular": "缆索铁路",
+ "Gondola": "缆车",
+ "Move panels back beside the rail": "将面板移回侧栏旁",
+ "Move panels over the rail, to the edge": "将面板移到侧栏上方,贴靠边缘"
}
diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json
index 4b3a467a4..62f5d5436 100644
--- a/src/i18n/locales/zh-Hant.json
+++ b/src/i18n/locales/zh-Hant.json
@@ -1223,6 +1223,8 @@
"AIS: {name}": "AIS: {name}",
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
"VESSEL": "船舶",
+ "AID TO NAVIGATION": "助航標誌",
+ "VIRTUAL": "虛擬",
"{speed}KT": "{speed} kn",
"{heading}DEG": "{heading}°",
"POS: LIVE": "POS:實時",
@@ -3536,5 +3538,12 @@
"Reset view reloads the app without the view restored from the address bar.": "「重置視圖」會重新加載應用,不使用從地址欄恢復的視圖。",
"Reload": "重新加載",
"Retry": "重試",
- "Reset view": "重置視圖"
+ "Reset view": "重置視圖",
+ "Trolleybus": "無軌電車",
+ "Cable car": "纜索電車",
+ "Monorail": "單軌列車",
+ "Funicular": "纜索鐵路",
+ "Gondola": "纜車",
+ "Move panels back beside the rail": "將面板移回側欄旁",
+ "Move panels over the rail, to the edge": "將面板移到側欄上方,貼齊邊緣"
}
diff --git a/src/i18n/same-as-english.json b/src/i18n/same-as-english.json
index 1ab9b364f..e95d5afc4 100644
--- a/src/i18n/same-as-english.json
+++ b/src/i18n/same-as-english.json
@@ -291,6 +291,7 @@
"FOV {value}°",
"FT",
"Folk",
+ "Funicular",
"Funk",
"GEO",
"GOOGLE STREET VIEW",
@@ -411,7 +412,8 @@
"MMSI: {id}",
"NORAD: {id}",
"Regional",
- "{datasets} · {tiles} · {packs}"
+ "{datasets} · {tiles} · {packs}",
+ "VIRTUAL"
],
"fr": [
"1 min/s",
@@ -500,6 +502,7 @@
"MINI",
"MISSION",
"MM",
+ "Monorail",
"MSG/S",
"Metal",
"Minimal",
@@ -570,6 +573,7 @@
"TAGS · {tags}",
"TEMP",
"TLE",
+ "Trolleybus",
"TYPE",
"Tallinn",
"Techno",
@@ -949,6 +953,7 @@
"FOV {value}°",
"FT",
"Folk",
+ "Funicular",
"Funk",
"GEO",
"GOOGLE STREET VIEW",
@@ -1067,7 +1072,8 @@
"ICAO: {id}",
"MMSI: {id}",
"NORAD: {id}",
- "Regional"
+ "Regional",
+ "VIRTUAL"
],
"ru": [
"1900–1945",
diff --git a/src/layers/firms/cards.js b/src/layers/firms/cards.js
index 2698f024a..3c8e79813 100644
--- a/src/layers/firms/cards.js
+++ b/src/layers/firms/cards.js
@@ -32,7 +32,8 @@ export function createCards({
if (!layerState._viewer) return;
const { query } = components.rendering.scenePorts();
const project = (position) => query?.project(position) ?? null;
- const now = Date.now();
+ // Ages count back from the time shown: the window's end, or now when live.
+ const now = components.model.ageReferenceMs();
const entries = [];
/** @type {Array<{x: number, y: number}>} Screen positions of accepted labels. */
const accepted = [];
diff --git a/src/layers/firms/model.js b/src/layers/firms/model.js
index d50dcf8e9..1cc70efc4 100644
--- a/src/layers/firms/model.js
+++ b/src/layers/firms/model.js
@@ -310,7 +310,7 @@ export function createModel({
* (on top) and never distance-faded by the overlay.
* Exported for unit tests.
* @param {Object} fire - Detection record.
- * @param {number} nowMs - Current epoch milliseconds.
+ * @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -351,9 +351,10 @@ export function createModel({
* Card model for an ambient fire detection, e.g. title "▲ 47 MW", detail
* "high · 14h · N20". Ages are computed against each detection's acquisition
* time — with the live feed everything reads under 24 h (and a stale cache
- * reads truthfully old). Exported for unit tests.
+ * reads truthfully old); `nowMs` is the time ages count back from, the end
+ * of the window shown (see {@link ageReferenceMs}). Exported for unit tests.
* @param {{fire: Object, position: {x: number, y: number, z: number}}} candidate - Label candidate.
- * @param {number} nowMs - Current epoch milliseconds.
+ * @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -385,7 +386,7 @@ export function createModel({
* "max 210 MW · new 3h". Accent comes from the candidate (renderHeat sets
* it with {@link cellCardAccent}). Exported for unit tests.
* @param {{cell: Object, position: {x: number, y: number, z: number}, accent: string}} candidate
- * @param {number} nowMs - Current epoch milliseconds.
+ * @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -516,6 +517,19 @@ export function createModel({
return { unit: 'd', count: Math.round(hours / 24) };
}
+ /**
+ * The time a card's ages count back from: the end of the 24 hours shown
+ * when the snapshot ends at a set time, now while it runs to now. A window
+ * that ended months ago then reads its fires as hours old, as they were.
+ * @param {number} [nowMs] - Current epoch milliseconds.
+ * @returns {number}
+ */
+
+ function ageReferenceMs(nowMs = Date.now()) {
+ const at = layerState?._at;
+ return Number.isFinite(at) ? at : nowMs;
+ }
+
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
function formatAge(deltaMs) {
@@ -590,6 +604,7 @@ export function createModel({
cellCardAccent,
formatLatLon,
formatFrp,
+ ageReferenceMs,
formatAge,
formatAgeLabel,
formatAgoMinutes,
diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js
index cc67e5010..db80cef72 100644
--- a/src/layers/firms/selection.js
+++ b/src/layers/firms/selection.js
@@ -183,7 +183,9 @@ export function createSelection({
confidence: components.model.confidenceBucket(fire.confidence),
age:
fire.acqMs > 0
- ? components.model.formatAge(Date.now() - fire.acqMs)
+ ? components.model.formatAge(
+ components.model.ageReferenceMs() - fire.acqMs,
+ )
: 'unknown',
sensor: fire.sensor || 'unknown',
},
diff --git a/src/layers/firms/windowLabel.test.mjs b/src/layers/firms/windowLabel.test.mjs
index c668f8bb4..aa6c848c9 100644
--- a/src/layers/firms/windowLabel.test.mjs
+++ b/src/layers/firms/windowLabel.test.mjs
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
+import { createCards } from './cards.js';
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
const now = 1800000000000;
@@ -42,3 +43,60 @@ test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (conte
setLocale(previousLocale);
}
});
+
+test('fire cards count ages from the end of the window shown, and from now when live', (context) => {
+ const now = Date.UTC(2026, 10, 14, 12);
+ context.mock.method(Date, 'now', () => now);
+ // A window that ended months before now: its newest fire three hours earlier.
+ const at = Date.UTC(2026, 7, 1, 12);
+ const layerState = { _at: at };
+ const model = createModel({ layerState, services: { anchors: {} } });
+ const cell = {
+ count: 4,
+ maxFrp: 210,
+ newestAcqMs: at - 3 * 3_600_000,
+ latCell: 1,
+ lonCell: 2,
+ };
+ const previousLocale = getLocale();
+ try {
+ setLocale('en');
+ assert.equal(model.ageReferenceMs(), at);
+ const card = model.buildCellCard({ cell, position: {} }, model.ageReferenceMs());
+ assert.equal(card.details[0], 'max 210 MW · new 3h', 'not months old');
+
+ // The cards the scene shows use the same time.
+ const entries = [];
+ layerState._viewer = { canvas: { clientWidth: 800, clientHeight: 600 } };
+ layerState._fireByCardId = new Map();
+ layerState._selectedFire = null;
+ layerState._labelCandidates = [{ cell, position: {} }];
+ layerState._labelLodDistance = 0;
+ const { rebuildAmbientLabels } = createCards({
+ layerState,
+ services: {},
+ components: {
+ model,
+ rendering: {
+ scenePorts: () => ({
+ query: { project: () => ({ x: 400, y: 300 }), isOccluded: () => false },
+ }),
+ },
+ },
+ config: { overlayHost: { setEntries: (source, shown) => entries.push(...shown) } },
+ });
+ rebuildAmbientLabels();
+ assert.equal(entries.length, 1);
+ assert.equal(entries[0].details[0], 'max 210 MW · new 3h');
+
+ // Live, they count from now.
+ layerState._at = null;
+ cell.newestAcqMs = now - 5 * 3_600_000;
+ assert.equal(model.ageReferenceMs(), now);
+ entries.length = 0;
+ rebuildAmbientLabels();
+ assert.equal(entries[0].details[0], 'max 210 MW · new 5h');
+ } finally {
+ setLocale(previousLocale);
+ }
+});
diff --git a/src/layers/flights/clockFollow.js b/src/layers/flights/clockFollow.js
index b7929a1f9..7b9e8a2b7 100644
--- a/src/layers/flights/clockFollow.js
+++ b/src/layers/flights/clockFollow.js
@@ -1,14 +1,20 @@
+import { forgetPlacedAircraft } from './placed.js';
+
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
-export function createClockFollow({ flightState, parts }) {
+export function createClockFollow({ flightState, services, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses, floors and the tracked
* trail belong to the time the clock left.
*/
function resetMotion() {
+ forgetPlacedAircraft(
+ services?.placement,
+ flightState._positionHistory.keys(),
+ );
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
diff --git a/src/layers/flights/clockFollow.test.mjs b/src/layers/flights/clockFollow.test.mjs
index 9878858e9..ea2e8520f 100644
--- a/src/layers/flights/clockFollow.test.mjs
+++ b/src/layers/flights/clockFollow.test.mjs
@@ -223,6 +223,25 @@ test('a jump forgets how contacts moved; clearing drops every contact', () => {
assert.ok(calls.includes('model:abc123'));
});
+test('leaving the live edge forgets every contact a host placement was told of', () => {
+ const forgotten = [];
+ const flightState = {
+ records: records(),
+ _positionHistory: new Map([
+ ['abc123', []],
+ ['def456', []],
+ ]),
+ _displayCourse: new Map(),
+ _groundSnap: { clear() {} },
+ _displayFloorState: new Map(),
+ };
+ const parts = { tracking: { _clearTrail() {} } };
+ const services = { placement: { forget: (id) => forgotten.push(id) } };
+ createClockFollow({ flightState, services, parts }).resetMotion();
+ assert.deepEqual(forgotten, ['abc123', 'def456']);
+ assert.equal(flightState._positionHistory.size, 0);
+});
+
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
const probe = ingestion({
async getSnapshot() {
diff --git a/src/layers/flights/icons.js b/src/layers/flights/icons.js
index 493d3fc91..92f7e4f0a 100644
--- a/src/layers/flights/icons.js
+++ b/src/layers/flights/icons.js
@@ -1,5 +1,6 @@
import { courseSlewCapDps } from '../../data/motionModel.js';
import { createAircraftIcons } from '../../data/aircraftIconLayer.js';
+import { placeAircraftAt } from './placed.js';
import { motionCourse } from '../../render/motion/iconMotion.js';
import { distanceSquared, norm180 } from '../../geo/vector.js';
import {
@@ -31,6 +32,18 @@ export function createIcons({ flightState, services, parts }) {
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
+ // A host-supplied placement, if any, draws a live contact where it places it.
+ placeAt: services.placement
+ ? (icao24, wallMs, info, history, out) =>
+ placeAircraftAt(
+ services.placement,
+ icao24,
+ wallMs,
+ info,
+ history,
+ out,
+ )
+ : null,
holdsPlan: (icao24) =>
flightState._focusEvidenceIds.has(icao24) ||
flightState._floorPinned.has(icao24),
diff --git a/src/layers/flights/icons.test.mjs b/src/layers/flights/icons.test.mjs
index 649f1f553..e48de4cea 100644
--- a/src/layers/flights/icons.test.mjs
+++ b/src/layers/flights/icons.test.mjs
@@ -4,6 +4,7 @@ import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createIcons } from './icons.js';
import { createContactIcons } from '../../data/aircraftIconLayer.js';
+import { layerPlacement } from '../../data/placementProvider.js';
function services(focus = {}) {
return {
@@ -17,8 +18,11 @@ function services(focus = {}) {
};
}
-function setup({ focus, motion = {}, rendering = {} } = {}) {
- const svc = services(focus);
+function setup({ focus, motion = {}, rendering = {}, placement = null } = {}) {
+ const svc = {
+ ...services(focus),
+ ...(placement ? { placement: layerPlacement(placement, 'aircraft') } : {}),
+ };
const flightState = createFlightState({ services: svc });
flightState._icons = createContactIcons();
const parts = {
@@ -214,3 +218,85 @@ test('a hidden contact shown again is where dead reckoning puts it now', (t) =>
'not where it was hidden',
);
});
+
+test('a live contact a placement places is drawn along where it places it', (t) => {
+ const t0 = Date.UTC(2026, 10, 9, 12);
+ t.mock.timers.enable({ apis: ['Date'], now: t0 });
+ const asked = [];
+ let places = true;
+ const regimes = [];
+ const { flightState, icons, set } = setup({
+ placement: {
+ layer: () => ({
+ place(id, wallMs) {
+ asked.push(wallMs);
+ if (!places) return null;
+ // A degree of longitude every 10 s, at its own height and course.
+ return {
+ lat: 30,
+ lon: (wallMs - t0) / 10_000,
+ altitudeM: 2000,
+ courseDeg: 90 + (wallMs - t0) / 1000,
+ speedMps: 200,
+ };
+ },
+ }),
+ },
+ motion: {
+ _motionRegime: () => {
+ regimes.push(1);
+ return {
+ kind: 'fix',
+ fix: { position: at(5), time: null },
+ speed: 0,
+ heading: 10,
+ };
+ },
+ _fixEpochMs: () => t0,
+ },
+ });
+ hold(set, 'p', at(0), 0, true);
+ flightState._positionHistory.set('p', [{ position: at(0) }]);
+ flightState.records.data.set('p', { renderAltitudeM: 1000 });
+ const now = icons._displayMs();
+ const leadMs = Date.now() - now;
+ icons._planIcon('p');
+ // Asked for the wall times the segment's ends stand for.
+ assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
+ assert.equal(regimes.length, 0, 'its own motion is not planned');
+ const item = set.item('p');
+ assert.equal(item.motion.kind, 'lerp');
+ assert.ok(
+ Cesium.Cartesian3.distance(
+ item.motion.from,
+ Cesium.Cartesian3.fromDegrees((now + leadMs - t0) / 10_000, 30, 2000),
+ ) < 1e-6,
+ );
+ assert.ok(
+ Cesium.Cartesian3.distance(
+ item.motion.to,
+ Cesium.Cartesian3.fromDegrees(
+ (now + 1000 + leadMs - t0) / 10_000,
+ 30,
+ 2000,
+ ),
+ ) < 1e-6,
+ );
+ assert.equal(item.motion.t0, now);
+ assert.equal(item.motion.t1, now + 1000);
+ assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
+ assert.equal(set.expires('p'), now + 1000);
+
+ // No answer: the layer's own motion plans it.
+ places = false;
+ icons._planIcon('p');
+ assert.equal(regimes.length, 1);
+ assert.equal(set.item('p').motion.kind, 'hold');
+
+ // Following the world clock, the placement is not asked.
+ places = true;
+ asked.length = 0;
+ flightState.timeline = { active: () => true };
+ icons._planIcon('p');
+ assert.deepEqual(asked, []);
+});
diff --git a/src/layers/flights/index.js b/src/layers/flights/index.js
index 49bf09770..3c5de4050 100644
--- a/src/layers/flights/index.js
+++ b/src/layers/flights/index.js
@@ -37,6 +37,7 @@ export function createCivilFlightLayer({
parts.clockFollow = createClockFollow(context);
const applySnapshot = createFlightSnapshotRenderer({
flightState,
+ placement: services.placement ?? null,
records: flightState.records,
militaryRegistry: services.militaryRegistry,
groundFloor: services.groundFloor,
diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js
index 9e7aaf9f3..790aad149 100644
--- a/src/layers/flights/lifecycle.js
+++ b/src/layers/flights/lifecycle.js
@@ -1,5 +1,6 @@
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
+import { forgetPlacedAircraft } from './placed.js';
export function createLifecycle({
flightState,
@@ -56,6 +57,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects = new Map();
flightState.records.data = new Map();
+ forgetPlacedAircraft(
+ services.placement,
+ flightState._positionHistory.keys(),
+ );
flightState._positionHistory = new Map();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
@@ -247,6 +252,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects.clear();
flightState.records.data.clear();
+ forgetPlacedAircraft(
+ services.placement,
+ flightState._positionHistory.keys(),
+ );
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js
index 4054ad792..a5be9ed2a 100644
--- a/src/layers/flights/motion.js
+++ b/src/layers/flights/motion.js
@@ -42,6 +42,7 @@ import {
corridorPathLatLon,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
+import { placeLiveAircraft } from './placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -231,6 +232,19 @@ export function createMotion({
}
const out = result || vec();
+ // A host-supplied placement decides where a live contact is drawn; with
+ // none, or no answer for this contact, the layer's own motion below does.
+ if (
+ placeLiveAircraft(
+ flightState,
+ services.placement,
+ icao24,
+ info,
+ history,
+ out,
+ )
+ )
+ return out;
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
diff --git a/src/layers/flights/motion.test.mjs b/src/layers/flights/motion.test.mjs
index 380261647..3a26c120a 100644
--- a/src/layers/flights/motion.test.mjs
+++ b/src/layers/flights/motion.test.mjs
@@ -3,8 +3,11 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { arcOffsetEnu } from '../../data/motionModel.js';
+import { createMotion as createMilitaryMotion } from '../military/motion.js';
+import { layerPlacement } from '../../data/placementProvider.js';
+import { observeLiveAircraft } from './placed.js';
-function fixture() {
+function fixture(placement = null) {
const flightState = {
records: { data: new Map() },
_positionHistory: new Map(),
@@ -16,7 +19,7 @@ function fixture() {
};
const motion = createMotion({
flightState,
- services: { groundFloor: {}, camera: {}, focus: {} },
+ services: { groundFloor: {}, camera: {}, focus: {}, placement },
parts: {},
});
return { flightState, motion };
@@ -182,3 +185,189 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
),
);
});
+
+/** Two fixes a minute apart, read across the minute from a clock at `start`. */
+function placedScenario(create, placement, record) {
+ const flightState = {
+ records: { data: new Map() },
+ _positionHistory: new Map(),
+ _focusEvidenceIds: new Set(),
+ _scratchArc: {},
+ _scratchOffset: new Cesium.Cartesian3(),
+ _scratchRenderTime: new Cesium.JulianDate(),
+ now: () => 0,
+ };
+ const motion = create({
+ flightState,
+ services: { groundFloor: {}, camera: {}, focus: {}, placement },
+ parts: {},
+ });
+ const start = Date.parse('2026-10-24T12:00:00Z');
+ const at = (seconds) =>
+ Cesium.JulianDate.fromDate(new Date(start + seconds * 1000));
+ flightState.records.data.set('abc123', record);
+ flightState._positionHistory.set('abc123', [
+ {
+ time: at(0),
+ position: Cesium.Cartesian3.fromDegrees(-97, 30, 1000),
+ track: 90,
+ velocity: 100,
+ },
+ {
+ time: at(60),
+ position: Cesium.Cartesian3.fromDegrees(-96.99, 30, 1000),
+ track: 90,
+ velocity: 100,
+ },
+ ]);
+ const drawn = [];
+ for (let seconds = 0; seconds <= 150; seconds += 7.5) {
+ flightState.now = () => start + seconds * 1000;
+ const position = motion._deadReckon('abc123', new Cesium.Cartesian3());
+ drawn.push({
+ position,
+ course: flightState._drCourseDeg,
+ speed: flightState._drSpeedMps,
+ hold: flightState._drCourseHold,
+ });
+ }
+ return { flightState, motion, drawn, start };
+}
+
+const declining = (asked) =>
+ layerPlacement(
+ {
+ layer: () => ({
+ place: (id, wallMs) => {
+ asked.push([id, wallMs]);
+ return null;
+ },
+ }),
+ },
+ 'aircraft',
+ );
+
+// Each kind's record carries only its own kinematics fields.
+for (const [name, create, record] of [
+ [
+ 'civil',
+ createMotion,
+ { velocity: 100, true_track: 90, renderAltitudeM: 1234 },
+ ],
+ [
+ 'military',
+ createMilitaryMotion,
+ { speedMps: 100, track: 90, renderAltitudeM: 1234 },
+ ],
+]) {
+ test(`${name} aircraft move as before without a placement or with one that places nothing`, () => {
+ const own = placedScenario(create, null, record).drawn;
+ const asked = [];
+ const declined = placedScenario(create, declining(asked), record).drawn;
+ assert.equal(asked.length, own.length);
+ assert.equal(declined.length, own.length);
+ for (let i = 0; i < own.length; i++) {
+ assert.ok(
+ Cesium.Cartesian3.equals(declined[i].position, own[i].position),
+ );
+ assert.equal(declined[i].course, own[i].course);
+ assert.equal(declined[i].speed, own[i].speed);
+ assert.equal(declined[i].hold, own[i].hold);
+ }
+ });
+
+ test(`${name} aircraft are drawn where a placement places them, live only`, () => {
+ const asked = [];
+ const placement = layerPlacement(
+ {
+ layer: () => ({
+ place(id, wallMs) {
+ asked.push(wallMs);
+ return wallMs % 2 === 0
+ ? {
+ lat: 30.5,
+ lon: -96.5,
+ altitudeM: 2000,
+ courseDeg: 45,
+ speedMps: 0.5,
+ extrapolating: true,
+ }
+ : { lat: 30.6, lon: -96.4 };
+ },
+ }),
+ },
+ 'aircraft',
+ );
+ const { flightState, motion, start } = placedScenario(
+ create,
+ placement,
+ record,
+ );
+ flightState.now = () => start + 2000;
+ const out = motion._deadReckon('abc123', new Cesium.Cartesian3());
+ close(out, Cesium.Cartesian3.fromDegrees(-96.5, 30.5, 2000));
+ assert.equal(flightState._drCourseDeg, 45);
+ assert.equal(flightState._drSpeedMps, 0.5);
+ assert.equal(flightState._drCourseHold, true);
+ // No height, course or speed placed: the record's drawn height and kinematics.
+ flightState.now = () => start + 2001;
+ close(
+ motion._deadReckon('abc123', new Cesium.Cartesian3()),
+ Cesium.Cartesian3.fromDegrees(-96.4, 30.6, 1234),
+ );
+ assert.equal(flightState._drCourseDeg, 90);
+ assert.equal(flightState._drSpeedMps, 100);
+ // Following the world clock the layer's own motion places it, unasked.
+ const before = asked.length;
+ flightState.timeline = { active: () => true };
+ const own = motion._deadReckon('abc123', new Cesium.Cartesian3());
+ assert.equal(asked.length, before);
+ assert.ok(Cesium.Cartesian3.distance(own, out) > 1000);
+ });
+}
+
+test('an aircraft fix is told to the placement live, with its drawn height', () => {
+ const told = [];
+ const placement = layerPlacement(
+ {
+ layer: () => ({
+ place: () => null,
+ observe: (id, fix) => told.push([id, fix]),
+ }),
+ },
+ 'aircraft',
+ );
+ const state = { timeline: { active: () => false } };
+ const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false };
+ observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270);
+ observeLiveAircraft(
+ state,
+ placement,
+ 'abc123',
+ 6000,
+ { ...meta, renderAltitudeInvented: true, onGround: true },
+ null,
+ undefined,
+ );
+ observeLiveAircraft(state, null, 'abc123', 7000, meta, 80, 270);
+ state.timeline.active = () => true;
+ observeLiveAircraft(state, placement, 'abc123', 8000, meta, 80, 270);
+ assert.equal(told.length, 2);
+ assert.deepEqual(told[0], [
+ 'abc123',
+ {
+ timeMs: 5000,
+ lat: 1,
+ lon: 2,
+ altitudeM: 300,
+ speedMps: 80,
+ courseDeg: 270,
+ headingDeg: NaN,
+ onGround: false,
+ },
+ ]);
+ assert.ok(Number.isNaN(told[1][1].altitudeM));
+ assert.ok(Number.isNaN(told[1][1].speedMps));
+ assert.ok(Number.isNaN(told[1][1].courseDeg));
+ assert.equal(told[1][1].onGround, true);
+});
diff --git a/src/layers/flights/placed.js b/src/layers/flights/placed.js
new file mode 100644
index 000000000..69949087d
--- /dev/null
+++ b/src/layers/flights/placed.js
@@ -0,0 +1,127 @@
+import { fromDegreesInto, toCartographicRadians } from '../../geo/ellipsoid.js';
+import { COURSE_HOLD_SPEED_MPS } from '../../data/motionModel.js';
+import { followsClock } from './policy.js';
+
+/**
+ * Where the host-supplied placement (`services.placement`,
+ * ../../data/placementProvider.js) draws an aircraft at `wallMs`, written
+ * into `out`, with the course and speed it is drawn with; null when it has
+ * no answer for this aircraft. A placement without a height keeps the
+ * aircraft's newest drawn height, and one without a course or speed the
+ * record's own.
+ * @param {object} placement
+ * @param {string} icao24
+ * @param {number} wallMs
+ * @param {object|undefined} info The aircraft's record.
+ * @param {{position: {x: number, y: number, z: number}}[]} history Its fixes, newest last.
+ * @param {{x: number, y: number, z: number}} out
+ * @returns {{courseDeg: number, speedMps: number, extrapolating: boolean}|null}
+ */
+export function placeAircraftAt(placement, icao24, wallMs, info, history, out) {
+ const placed = placement.place(icao24, wallMs);
+ if (!placed) return null;
+ let heightM = placed.altitudeM;
+ if (!Number.isFinite(heightM)) heightM = info?.renderAltitudeM;
+ if (!Number.isFinite(heightM))
+ heightM =
+ toCartographicRadians(history[history.length - 1].position)?.height ?? 0;
+ const speedMps = Number.isFinite(placed.speedMps)
+ ? placed.speedMps
+ : // Civil records carry velocity and true_track, military speedMps and track.
+ Number.isFinite(info?.velocity)
+ ? info.velocity
+ : info?.speedMps || 0;
+ const courseDeg = Number.isFinite(placed.courseDeg)
+ ? placed.courseDeg
+ : Number.isFinite(info?.true_track)
+ ? info.true_track
+ : info?.track || 0;
+ fromDegreesInto(placed.lon, placed.lat, heightM, out);
+ return { courseDeg, speedMps, extrapolating: placed.extrapolating };
+}
+
+/**
+ * Where the host-supplied placement draws a live aircraft now, written into
+ * `out` with the course scratches `_deadReckon` sets on `flightState`; false
+ * when there is no placement, the layer follows the world clock, or it has
+ * no answer for this aircraft, and the layer's own motion places it.
+ * @param {object} flightState The civil or military flight state.
+ * @param {object|null|undefined} placement
+ * @param {string} icao24
+ * @param {object|undefined} info The aircraft's record.
+ * @param {{position: {x: number, y: number, z: number}}[]} history Its fixes, newest last.
+ * @param {{x: number, y: number, z: number}} out
+ * @returns {boolean}
+ */
+export function placeLiveAircraft(
+ flightState,
+ placement,
+ icao24,
+ info,
+ history,
+ out,
+) {
+ if (!placement || followsClock(flightState)) return false;
+ const placed = placeAircraftAt(
+ placement,
+ icao24,
+ flightState.now(),
+ info,
+ history,
+ out,
+ );
+ if (!placed) return false;
+ flightState._drCourseDeg = placed.courseDeg;
+ flightState._drSpeedMps = placed.speedMps;
+ flightState._drCourseHold = placed.speedMps < COURSE_HOLD_SPEED_MPS;
+ flightState._drExtrapolating = placed.extrapolating;
+ return true;
+}
+
+/**
+ * Tell the host-supplied placement, if any, that the aircraft `ids` left the
+ * layer (removed, the layer off, or the world clock moved it to another time).
+ * @param {object|null|undefined} placement
+ * @param {Iterable} ids
+ */
+export function forgetPlacedAircraft(placement, ids) {
+ if (!placement) return;
+ for (const id of ids) placement.forget(id);
+}
+
+/**
+ * Tell the host-supplied placement an aircraft's fix as the layer took it
+ * (nothing while the layer follows the world clock): its own time, its
+ * position, the height the layer draws it at (NaN when that height is
+ * invented), and its reported speed, course and ground state.
+ * @param {object} flightState
+ * @param {object|null|undefined} placement
+ * @param {string} icao24
+ * @param {number} fixEpochMs
+ * @param {{rawLat: number, rawLon: number, renderAltitudeM: number,
+ * renderAltitudeInvented?: boolean, onGround?: boolean}} meta
+ * @param {number|null|undefined} speedMps
+ * @param {number|null|undefined} courseDeg
+ */
+export function observeLiveAircraft(
+ flightState,
+ placement,
+ icao24,
+ fixEpochMs,
+ meta,
+ speedMps,
+ courseDeg,
+) {
+ if (!placement || followsClock(flightState)) return;
+ placement.observe(icao24, {
+ timeMs: fixEpochMs,
+ lat: meta.rawLat,
+ lon: meta.rawLon,
+ altitudeM:
+ meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM,
+ speedMps: Number.isFinite(speedMps) ? speedMps : NaN,
+ courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN,
+ headingDeg: NaN,
+ onGround: meta.onGround === true,
+ });
+}
diff --git a/src/layers/flights/snapshotRenderer.js b/src/layers/flights/snapshotRenderer.js
index 09c67f83a..dc27d756a 100644
--- a/src/layers/flights/snapshotRenderer.js
+++ b/src/layers/flights/snapshotRenderer.js
@@ -8,6 +8,7 @@ import {
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
+import { observeLiveAircraft } from './placed.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
@@ -35,6 +36,7 @@ function noteDelivery(flightState, snapshot) {
/** Apply reconciled aircraft records to the layer's drawing and follow state. */
export function createFlightSnapshotRenderer({
flightState,
+ placement = null,
records,
militaryRegistry,
groundFloor,
@@ -112,6 +114,17 @@ export function createFlightSnapshotRenderer({
}
const isTracked = icao24 === flightState._trackedIcao;
+ // A host-supplied placement, if any, is told every fix as taken.
+ observeLiveAircraft(
+ flightState,
+ placement,
+ icao24,
+ fixEpochMs,
+ meta,
+ meta.velocity,
+ meta.true_track,
+ );
+
// Append to position history stamped with the FEED's fix epoch
// (time_position), not client receipt time — OpenSky positions arrive
// 5-15s stale and receipt-time stamping is what caused the
diff --git a/src/layers/military/clockFollow.js b/src/layers/military/clockFollow.js
index 204ddc3ac..f5c12bf97 100644
--- a/src/layers/military/clockFollow.js
+++ b/src/layers/military/clockFollow.js
@@ -1,14 +1,20 @@
+import { forgetPlacedAircraft } from '../flights/placed.js';
+
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
-export function createClockFollow({ flightState, parts }) {
+export function createClockFollow({ flightState, services, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses and the tracked trail
* belong to the time the clock left.
*/
function resetMotion() {
+ forgetPlacedAircraft(
+ services?.placement,
+ flightState._positionHistory.keys(),
+ );
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
diff --git a/src/layers/military/icons.js b/src/layers/military/icons.js
index f117d68df..1cc3fc8f6 100644
--- a/src/layers/military/icons.js
+++ b/src/layers/military/icons.js
@@ -1,4 +1,5 @@
import { createAircraftIcons } from '../../data/aircraftIconLayer.js';
+import { placeAircraftAt } from '../flights/placed.js';
import {
COCKPIT_CONTACT_SIZE_PX,
COURSE_MAX_DPS,
@@ -18,5 +19,17 @@ export function createIcons({ flightState, services, parts }) {
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
+ // A host-supplied placement, if any, draws a live contact where it places it.
+ placeAt: services.placement
+ ? (icao24, wallMs, info, history, out) =>
+ placeAircraftAt(
+ services.placement,
+ icao24,
+ wallMs,
+ info,
+ history,
+ out,
+ )
+ : null,
});
}
diff --git a/src/layers/military/index.js b/src/layers/military/index.js
index 10c636297..0f30a391c 100644
--- a/src/layers/military/index.js
+++ b/src/layers/military/index.js
@@ -33,6 +33,7 @@ export function createMilitaryFlightLayer({
parts.clockFollow = createClockFollow(context);
const applySnapshot = createMilitarySnapshotRenderer({
flightState,
+ placement: services.placement ?? null,
records: flightState.records,
groundFloor: services.groundFloor,
militaryRegistry: services.militaryRegistry,
diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js
index 084460277..0389ef3f0 100644
--- a/src/layers/military/lifecycle.js
+++ b/src/layers/military/lifecycle.js
@@ -1,5 +1,6 @@
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
+import { forgetPlacedAircraft } from '../flights/placed.js';
export function createLifecycle({
flightState,
@@ -52,6 +53,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects = new Map();
flightState.records.data = new Map();
+ forgetPlacedAircraft(
+ services.placement,
+ flightState._positionHistory.keys(),
+ );
flightState._positionHistory = new Map();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
@@ -224,6 +229,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects.clear();
flightState.records.data.clear();
+ forgetPlacedAircraft(
+ services.placement,
+ flightState._positionHistory.keys(),
+ );
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js
index 499b4c247..ac28506f4 100644
--- a/src/layers/military/motion.js
+++ b/src/layers/military/motion.js
@@ -35,6 +35,7 @@ import {
limitCourseStep,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
+import { placeLiveAircraft } from '../flights/placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -133,6 +134,19 @@ export function createMotion({
}
const out = result || vec();
+ // A host-supplied placement decides where a live contact is drawn; with
+ // none, or no answer for this contact, the layer's own motion below does.
+ if (
+ placeLiveAircraft(
+ flightState,
+ services.placement,
+ icao24,
+ info,
+ history,
+ out,
+ )
+ )
+ return out;
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
diff --git a/src/layers/military/snapshotRenderer.js b/src/layers/military/snapshotRenderer.js
index ba1394eb7..f07164208 100644
--- a/src/layers/military/snapshotRenderer.js
+++ b/src/layers/military/snapshotRenderer.js
@@ -8,6 +8,7 @@ import {
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
+import { observeLiveAircraft } from '../flights/placed.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
@@ -35,6 +36,7 @@ function noteDelivery(flightState, snapshot) {
/** Apply military record changes to the layer's drawing and existing follow operations. */
export function createMilitarySnapshotRenderer({
flightState,
+ placement = null,
records,
groundFloor,
militaryRegistry,
@@ -86,6 +88,17 @@ export function createMilitarySnapshotRenderer({
if (groundFlipped) flightState._groundSnap.forget(icao24);
const isTracked = icao24 === flightState._trackedIcao;
+ // A host-supplied placement, if any, is told every fix as taken.
+ observeLiveAircraft(
+ flightState,
+ placement,
+ icao24,
+ fixEpochMs,
+ meta,
+ meta.speedMps,
+ meta.track,
+ );
+
// Append to position history stamped with the FEED's fix epoch.
// adsb.lol's seen_pos is the AGE in seconds of the last position
// report, so the fix epoch is receipt time minus that age. Only
diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs
index 667b65692..b439e1eec 100644
--- a/src/layers/rail/cockpitSubject.test.mjs
+++ b/src/layers/rail/cockpitSubject.test.mjs
@@ -19,6 +19,7 @@ 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';
+import { PLACED_WAKE_MS } from '../transit/movement.js';
const M_PER_DEG = 111_320;
const LAT = 42.36;
@@ -511,3 +512,31 @@ test('turning the layer off ends the hold', async (t) => {
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+
+test('a train a placement holds still stops animating, and moves on when the placement does', async (t) => {
+ let spot = { lat: LAT, lon: LON0 + 3000 / KX };
+ const app = await onTheLine(t, {
+ placement: {
+ layer: () => ({
+ place: (id) => (id === T1 ? { ...spot, speedMps: 0 } : null),
+ }),
+ },
+ });
+ app.run(1_000);
+ const entry = app.entry(T1);
+ assert.equal(entry.placed, true);
+ assert.equal(app.state()._moving.has(entry), false, 'parked: not animating');
+ assert.notEqual(entry.wakeTimer, null, 'a wake asks the placement again');
+ assert.ok(app.state()._moving.has(app.entry(T2)), 'its own motion runs on');
+
+ spot = { lat: LAT, lon: spot.lon + 10 / KX };
+ t.mock.timers.tick(PLACED_WAKE_MS);
+ assert.ok(app.state()._moving.has(entry), 'moving again');
+ for (let i = 0; i < 3; i += 1) {
+ spot = { lat: LAT, lon: spot.lon + 1 / KX };
+ app.run(250);
+ assert.ok(app.state()._moving.has(entry), 'while it moves');
+ }
+ app.run(250);
+ assert.equal(app.state()._moving.has(entry), false, 'stopped again');
+});
diff --git a/src/layers/rail/ingestion.js b/src/layers/rail/ingestion.js
index 90c54ce36..721e15f2b 100644
--- a/src/layers/rail/ingestion.js
+++ b/src/layers/rail/ingestion.js
@@ -82,6 +82,7 @@ export function createIngestion({ state, services, parts, source }) {
state._moving.delete(entry);
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
+ entry.placement?.forget(key);
state._trains.delete(key);
state._revision += 1;
// A copy it hid may now be the one to draw.
@@ -274,6 +275,8 @@ export function createIngestion({ state, services, parts, source }) {
const entry = {
key,
feedId: feed.id,
+ // A host-supplied placement, if any, draws it while live.
+ placement: services.placement ?? null,
marker: null,
category: record.category,
railMode: record.mode,
diff --git a/src/layers/rail/lifecycle.js b/src/layers/rail/lifecycle.js
index 39a3d2b49..9ec056877 100644
--- a/src/layers/rail/lifecycle.js
+++ b/src/layers/rail/lifecycle.js
@@ -22,6 +22,7 @@ export function createLifecycle({ state, services, parts, timetable }) {
for (const entry of state._trains.values()) {
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
+ entry.placement?.forget(entry.key);
}
state._trains.clear();
state._moving.clear();
diff --git a/src/layers/rail/rendering.js b/src/layers/rail/rendering.js
index ed7f3819b..b2c37b922 100644
--- a/src/layers/rail/rendering.js
+++ b/src/layers/rail/rendering.js
@@ -11,7 +11,12 @@ import {
} from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distanceSquared } from '../../geo/vector.js';
-import { applyDisplayCourse, updatePlayback } from '../transit/movement.js';
+import {
+ PLACED_WAKE_MS,
+ applyDisplayCourse,
+ playbackMoving,
+ updatePlayback,
+} from '../transit/movement.js';
import { HEIGHT_SAMPLE_MAX_ALTITUDE_M } from '../transit/policy.js';
import {
COLD_CELL_FLUSH_MS,
@@ -721,8 +726,11 @@ export function createRendering({ state, services, parts }) {
*/
function place(entry) {
const sample = entry.sample;
+ // Placed by a host-supplied placement, it is drawn where that puts it.
const onPath =
- entry.path && placeOnPath(entry.path, sample, entry.segment, pathPoint);
+ !entry.placed &&
+ entry.path &&
+ placeOnPath(entry.path, sample, entry.segment, pathPoint);
const lat = onPath
? pathPoint.lat
: Number.isFinite(sample?.lat)
@@ -796,16 +804,26 @@ export function createRendering({ state, services, parts }) {
if (!entry.marker) return;
place(entry);
const sample = entry.sample;
- const moving =
- playing(entry) &&
- sample?.phase === 'playing' &&
- sample.segmentSpeedMps > 0;
+ const moving = playing(entry) && playbackMoving(entry);
if (moving) {
state._moving.add(entry);
return;
}
state._moving.delete(entry);
- if (playing(entry) && Number.isFinite(sample?.nextWakeMonoMs)) {
+ if (!playing(entry)) return;
+ // A train a host-supplied placement holds still is asked again every
+ // PLACED_WAKE_MS: it moves on once the placement does.
+ const monoNow = performance.now();
+ const placedWake = entry.placed === true;
+ const boundary = sample?.nextWakeMonoMs;
+ const wakeMonoMs = placedWake
+ ? Math.min(
+ Number.isFinite(boundary) ? boundary : Infinity,
+ monoNow + PLACED_WAKE_MS,
+ )
+ : boundary;
+ if (Number.isFinite(wakeMonoMs)) {
+ const atBoundary = !placedWake || boundary <= wakeMonoMs;
entry.wakeTimer = setTimeout(
() => {
entry.wakeTimer = null;
@@ -813,9 +831,10 @@ export function createRendering({ state, services, parts }) {
updatePlayback(entry, Date.now(), performance.now());
schedulePlayback(entry);
syncRenderHold();
- governorRequestRender('rail-motion-boundary');
+ if (atBoundary || state._moving.has(entry))
+ governorRequestRender('rail-motion-boundary');
},
- Math.max(1, sample.nextWakeMonoMs - performance.now()),
+ Math.max(1, wakeMonoMs - monoNow),
);
}
}
@@ -1021,7 +1040,8 @@ export function createRendering({ state, services, parts }) {
place(entry);
if (
entry.sample.phase !== 'playing' ||
- entry.sample.segmentSpeedMps === 0
+ entry.sample.segmentSpeedMps === 0 ||
+ (entry.placed === true && entry.placedMoving !== true)
)
schedulePlayback(entry);
}
diff --git a/src/layers/transit/ingestion.js b/src/layers/transit/ingestion.js
index b62c6d34c..93340d989 100644
--- a/src/layers/transit/ingestion.js
+++ b/src/layers/transit/ingestion.js
@@ -16,6 +16,7 @@ import {
import {
transitModeFor,
transitModeResolved,
+ transitModelRouteType,
} from '../../data/transitFeeds.js';
import {
attachFloorToPlace,
@@ -85,6 +86,7 @@ export function createIngestion({ state, services, parts, source }) {
state._heightDirty.delete(entry);
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
+ entry.placement?.forget(key);
state._vehicles.delete(key);
state._detectRevision += 1;
}
@@ -222,12 +224,19 @@ export function createIngestion({ state, services, parts, source }) {
for (const record of records) {
if (isStaleVehicleFix(record, now, fetchedAt)) continue;
const key = transitVehicleKey(feed.id, record.id);
- const mode = transitModeFor(feed, record.routeId, record.id);
+ const mode = transitModeFor(
+ feed,
+ record.routeId,
+ record.id,
+ record.routeType,
+ );
const modeInferred = !transitModeResolved(
feed,
record.routeId,
record.id,
+ record.routeType,
);
+ const routeType = transitModelRouteType(mode, record.routeType);
// A stamp ahead of the fetch is a clock fault; the fetch time bounds it.
const stamped = vehicleReportTimeMs(record, fetchedAt);
const reportAt =
@@ -267,6 +276,7 @@ export function createIngestion({ state, services, parts, source }) {
continue;
}
if (entry.mode !== mode) parts.rendering.paintMode(entry, mode);
+ entry.routeType = routeType;
entry.modeInferred = modeInferred;
updatePlayback(entry, now, monoNow);
parts.rendering.schedulePlayback(entry);
@@ -318,8 +328,12 @@ export function createIngestion({ state, services, parts, source }) {
entry = {
key,
feedId: feed.id,
+ // A host-supplied placement, if any, draws it while live.
+ placement: services.placement ?? null,
marker: null,
mode,
+ // The GTFS route type its model is chosen by, when it has one.
+ routeType,
modeInferred,
heightM: prior === null ? 0 : prior,
heightCell: height.cell,
diff --git a/src/layers/transit/lifecycle.js b/src/layers/transit/lifecycle.js
index 3b0986051..5e4428f55 100644
--- a/src/layers/transit/lifecycle.js
+++ b/src/layers/transit/lifecycle.js
@@ -98,6 +98,7 @@ export function createLifecycle({ state, services, parts }) {
entry.detectContact = null;
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
+ entry.placement?.forget(entry.key);
}
state._vehicles.clear();
parts.height.clear();
@@ -179,6 +180,7 @@ export function createLifecycle({ state, services, parts }) {
entry.detectContact = null;
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
+ entry.placement?.forget(entry.key);
}
state._vehicles.clear();
parts.rendering.stopModels();
diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs
index 829e64597..1a7805a53 100644
--- a/src/layers/transit/lifecycle.test.mjs
+++ b/src/layers/transit/lifecycle.test.mjs
@@ -13,6 +13,8 @@ import {
} from './policy.js';
import { FLOOR_WARM_PER_POLL } from './policy.js';
import { fleetModelFakes } from '../../testSupport/fleetModelFakes.mjs';
+import { layerPlacement } from '../../data/placementProvider.js';
+import { PLACED_WAKE_MS } from './movement.js';
import {
FUTURE_STAMP_TOLERANCE_MS,
ORDER_REJECTS_BEFORE_RESET,
@@ -229,6 +231,8 @@ function harness(
// Fleet-model services (testSupport/fleetModelFakes.mjs), with a camera
// looking straight down for them; without them vehicles stay icons.
fleet = null,
+ // A host-supplied placement (../../data/placementProvider.js), or none.
+ placement = null,
} = {},
) {
const viewRect = { ...view };
@@ -346,6 +350,7 @@ function harness(
source,
services: {
...(fleet ? { fleet } : {}),
+ ...(placement ? { placement: layerPlacement(placement, 'transit') } : {}),
ground,
mesh: {
sampleMeshFloorCells(scene, points, options) {
@@ -1329,6 +1334,110 @@ test('a parked fleet that keeps reporting the same position stops asking for fra
'only the vehicle that actually moved is animating',
);
});
+test('a vehicle a placement holds still stops asking for frames, and moves on when the placement does', async (t) => {
+ // The placement parks bus-1 at a terminal until `spot` moves.
+ let spot = { lat: 42.3605, lon: -71.0605 };
+ let asked = 0;
+ const app = harness(t, {
+ placement: {
+ layer: () => ({
+ place: () => {
+ asked += 1;
+ return { ...spot, courseDeg: 0, speedMps: 0 };
+ },
+ }),
+ },
+ });
+ app.serve('mbta', () => ({
+ status: 200,
+ body: snapshot(
+ 'mbta',
+ 'MBTA',
+ [vehicle('bus-1', 42.36, -71.06, reported())],
+ { fetchedAt: Date.now() },
+ ),
+ }));
+ app.layer.enable(app.viewer);
+ await app.layer.update();
+ app.settle();
+ const entry = app.vehicles()[0];
+ assert.equal(entry.placed, true);
+ for (let i = 0; i < 3; i += 1) {
+ app.advance(16);
+ app.frame();
+ }
+ assert.equal(app.state()._moving.has(entry), false, 'parked: not animating');
+ assert.equal(app.holds().includes('transit'), false, 'and the loop idles');
+ assert.notEqual(entry.wakeTimer, null, 'a wake asks the placement again');
+ assert.ok(Math.abs(lat(entry) - 42.3605) < 1e-6, 'drawn where placed');
+
+ // Asked again while it stays put: still idle, the wake re-armed.
+ const before = asked;
+ app.advance(PLACED_WAKE_MS);
+ assert.ok(asked > before, 'the wake asked the placement');
+ assert.equal(app.state()._moving.has(entry), false);
+ assert.equal(app.holds().includes('transit'), false);
+
+ // The placement moves it: the next wake picks that up and the loop runs.
+ spot = { lat: 42.361, lon: -71.0605 };
+ app.advance(PLACED_WAKE_MS);
+ assert.equal(app.state()._moving.has(entry), true, 'moving again');
+ assert.ok(app.holds().includes('transit'), 'and holds the loop');
+ assert.ok(Math.abs(lat(entry) - 42.361) < 1e-6);
+ for (let i = 0; i < 3; i += 1) {
+ spot = { lat: spot.lat + 1e-5, lon: spot.lon };
+ app.advance(16);
+ app.frame();
+ assert.equal(app.state()._moving.has(entry), true, 'while it moves');
+ }
+
+ // It stops again: the next frame that sees it unchanged lets go.
+ app.advance(16);
+ app.frame();
+ assert.equal(app.state()._moving.has(entry), false, 'stopped again');
+ assert.equal(app.holds().includes('transit'), false);
+});
+
+test('a vehicle a placement draws is shown from a high camera, as one it does not', async (t) => {
+ // Far above the ground no floor is asked for, so the fixes carry no height
+ // and the vehicle stands on the ellipsoid, placed or not.
+ const app = harness(t, {
+ at: { lat: 52.09, lon: 5.12 },
+ altitude: 1_500_000,
+ view: { west: -78.084, south: 20, east: 88.084, north: 84 },
+ placement: {
+ layer: () => ({
+ place: (id) =>
+ id.endsWith('nl-1')
+ ? { lat: 52.091, lon: 5.12, courseDeg: 0, speedMps: 0 }
+ : null,
+ }),
+ },
+ });
+ const now = Date.now();
+ app.serve('ovapi-nl', () => ({
+ status: 200,
+ body: snapshot(
+ 'ovapi-nl',
+ 'OVapi',
+ [
+ vehicle('nl-1', 52.09, 5.12, now / 1000),
+ vehicle('nl-2', 51.92, 4.48, now / 1000),
+ ],
+ { fetchedAt: Date.now() },
+ ),
+ }));
+ app.layer.enable(app.viewer);
+ await app.layer.update();
+ app.advance(250);
+ app.frame();
+ const placed = app.vehicles().find((entry) => entry.placed === true);
+ assert.ok(placed, 'one vehicle is placed');
+ const shown = app.vehicles().filter((entry) => entry.marker?.show !== false);
+ assert.equal(shown.length, 2, 'both vehicles are drawn');
+ assert.ok(Math.abs(lat(placed) - 52.091) < 1e-6, 'where placed');
+});
+
test('the last vehicle leaving mid-segment takes the render hold with it', async (t) => {
const app = harness(t);
const fetchedAt = Date.now();
diff --git a/src/layers/transit/movement.js b/src/layers/transit/movement.js
index 2c9a61dcd..8ebb4d383 100644
--- a/src/layers/transit/movement.js
+++ b/src/layers/transit/movement.js
@@ -11,9 +11,14 @@ import {
} from '../../data/contactPlayback.js';
const MODE_MAX_SPEED_MPS = Object.freeze({
bus: 36, // ~130 km/h — a coach on a motorway
+ trolleybus: 28, // ~100 km/h — wired to the street
tram: 28, // ~100 km/h — interurban light rail
+ cable_tram: 12, // ~43 km/h — the cable runs at a walking-pace multiple
subway: 42, // ~150 km/h
+ monorail: 42, // ~150 km/h
rail: 111, // ~400 km/h — high-speed services exist on some feeds
+ funicular: 16, // ~58 km/h — the fastest lines
+ aerial_lift: 15, // ~54 km/h — the fastest gondolas and trams
ferry: 25, // ~90 km/h — fast catamarans
unknown: 56, // ~200 km/h
});
@@ -181,13 +186,57 @@ export function recordFix(entry, fix, observation = {}) {
);
entry.currentEpoch = latest.epoch;
if (context) entry.track.epochs.set(latest.epoch, context);
+ entry.placement?.observe(entry.key, {
+ timeMs: fix.t,
+ lat: fix.lat,
+ lon: fix.lon,
+ altitudeM: NaN,
+ speedMps: NaN,
+ courseDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN,
+ headingDeg: NaN,
+ feedId: entry.feedId,
+ });
}
return result;
}
+/**
+ * How often a vehicle a host-supplied placement holds still is asked again
+ * whether it moves, so it resumes without the frame loop running for it.
+ */
+export const PLACED_WAKE_MS = 1000;
+
+/**
+ * Advance a vehicle's playback to now. With a host-supplied placement
+ * (`entry.placement`, ../../data/placementProvider.js) that places it, it is
+ * drawn there, its course and speed the placement's (`entry.placed`); the
+ * playback's own phase, motion and segment stand. `entry.placedMoving` says
+ * whether the placed position changed since the placement was last asked at
+ * an earlier time (true for its first answer, so one more frame can tell).
+ */
export function updatePlayback(entry, wallNowMs, monoNowMs) {
entry.clocks.wallNowMs = wallNowMs;
entry.clocks.monoNowMs = monoNowMs;
advance(entry.track, entry.clocks, entry.sample);
+ const placed = entry.placement?.place(entry.key, wallNowMs) ?? null;
+ const wasPlaced = entry.placed === true;
+ entry.placed = placed !== null;
+ if (!placed) entry.placedMoving = false;
+ else if (!wasPlaced) entry.placedMoving = true;
+ else if (wallNowMs !== entry.placedAtWallMs)
+ entry.placedMoving =
+ placed.lat !== entry.placedLat || placed.lon !== entry.placedLon;
+ if (placed) {
+ entry.placedLat = placed.lat;
+ entry.placedLon = placed.lon;
+ entry.placedAtWallMs = wallNowMs;
+ const sample = entry.sample;
+ sample.lat = placed.lat;
+ sample.lon = placed.lon;
+ if (Number.isFinite(placed.courseDeg))
+ sample.segmentCourseDeg = placed.courseDeg;
+ if (Number.isFinite(placed.speedMps))
+ sample.segmentSpeedMps = placed.speedMps;
+ }
entry.resets = entry.track.resets;
const segment = entry.segment;
readFix(
@@ -212,6 +261,16 @@ export function syncPlayback(entry, wallNowMs, monoNowMs = performance.now()) {
}
updatePlayback(entry, wallNowMs, monoNowMs);
}
+/**
+ * Whether a vehicle's drawn position changes on its own: a vehicle a
+ * host-supplied placement draws moves while that placement's position
+ * changes; any other while its playback glides along a segment.
+ */
+export function playbackMoving(entry) {
+ if (entry.placed === true) return entry.placedMoving === true;
+ const sample = entry.sample;
+ return sample?.phase === 'playing' && sample.segmentSpeedMps > 0;
+}
export function playbackPosition(entry) {
if (!entry?.track) return null;
return {
diff --git a/src/layers/transit/movement.test.mjs b/src/layers/transit/movement.test.mjs
index 692d2d3ac..6b87157a7 100644
--- a/src/layers/transit/movement.test.mjs
+++ b/src/layers/transit/movement.test.mjs
@@ -10,6 +10,7 @@ import {
} from './movement.js';
import { buildTransitSelectionCopy } from './policy.js';
import { sampleAt } from '../../data/contactPlayback.js';
+import { layerPlacement } from '../../data/placementProvider.js';
const entry = () => {
const e = { mode: 'bus', modeInferred: false, courseDeg: null };
initializePlayback(e);
@@ -163,3 +164,101 @@ test('course fallback prefers held course, then finite reported bearing, then un
assert.equal(e.courseDeg, expected);
}
});
+
+const placedEntry = (placement) => {
+ const e = {
+ key: 'feed:7',
+ feedId: 'feed',
+ mode: 'bus',
+ modeInferred: false,
+ courseDeg: null,
+ placement,
+ };
+ initializePlayback(e);
+ return e;
+};
+const drive = (e) => {
+ recordFix(e, { ...fix(0), bearingDeg: 10 });
+ recordFix(e, { ...fix(15000, 42.001), bearingDeg: 20 });
+ recordFix(e, fix(30000, 42.002));
+ const samples = [];
+ for (let wall = 0; wall <= 120000; wall += 2500) {
+ updatePlayback(e, wall, wall);
+ samples.push({ ...e.sample });
+ }
+ return samples;
+};
+test('without a placement, or one that places nothing, playback is the layer own', () => {
+ const own = drive(placedEntry(null));
+ const declined = [];
+ const placement = layerPlacement(
+ {
+ layer: () => ({
+ observe: (id, f) => declined.push([id, f.timeMs]),
+ place: () => null,
+ }),
+ },
+ 'transit',
+ );
+ const e = placedEntry(placement);
+ assert.deepEqual(drive(e), own);
+ assert.equal(e.placed, false);
+ assert.deepEqual(declined, [
+ ['feed:7', 0],
+ ['feed:7', 15000],
+ ['feed:7', 30000],
+ ]);
+});
+test('a placement draws the vehicle where it places it, keeping the playback state', () => {
+ const own = drive(placedEntry(null));
+ const e = placedEntry(
+ layerPlacement(
+ {
+ layer: () => ({
+ place: (id, wallMs) =>
+ wallMs >= 60000
+ ? { lat: 1, lon: 2, courseDeg: 45, speedMps: 7 }
+ : { lat: 3, lon: 4 },
+ }),
+ },
+ 'transit',
+ ),
+ );
+ const placed = drive(e);
+ assert.equal(e.placed, true);
+ for (let i = 0; i < own.length; i++) {
+ const late = i * 2500 >= 60000;
+ assert.equal(placed[i].lat, late ? 1 : 3);
+ assert.equal(placed[i].lon, late ? 2 : 4);
+ assert.equal(placed[i].phase, own[i].phase);
+ assert.equal(placed[i].motion, own[i].motion);
+ if (late) {
+ assert.equal(placed[i].segmentCourseDeg, 45);
+ assert.equal(placed[i].segmentSpeedMps, 7);
+ } else {
+ // No course or speed placed: the playback's own stand.
+ assert.deepEqual(
+ [placed[i].segmentCourseDeg, placed[i].segmentSpeedMps],
+ [own[i].segmentCourseDeg, own[i].segmentSpeedMps],
+ );
+ }
+ }
+});
+test('a refused fix is never told to the placement', () => {
+ const told = [];
+ const e = placedEntry(
+ layerPlacement(
+ {
+ layer: () => ({
+ observe: (id, f) => told.push(f.lat),
+ place: () => null,
+ }),
+ },
+ 'transit',
+ ),
+ );
+ recordFix(e, fix(0));
+ recordFix(e, fix(15000, 42.001));
+ assert.equal(recordFix(e, fix(30000, 43)).accepted, false);
+ assert.deepEqual(told, [42, 42.001]);
+});
diff --git a/src/layers/transit/policy.js b/src/layers/transit/policy.js
index 40e0be872..d8567b77c 100644
--- a/src/layers/transit/policy.js
+++ b/src/layers/transit/policy.js
@@ -188,9 +188,14 @@ export const SELECTED_CARD_REFRESH_MS = 250;
/** Mode palette: distinct at a glance, none reused by flights (white/cyan), military (amber), or vessels. */
export const TRANSIT_MODE_COLORS = Object.freeze({
bus: '#5EF08A',
+ trolleybus: '#B6F04A',
tram: '#FFC24A',
+ cable_tram: '#FF8F4A',
subway: '#FF4538',
+ monorail: '#FF6FB8',
rail: '#D9A6FF',
+ funicular: '#E8C98A',
+ aerial_lift: '#7FA8FF',
ferry: '#5FD6FF',
unknown: '#D8DDE5',
});
@@ -525,9 +530,14 @@ const UNDERGROUND_MODES = new Set(['subway']);
/** The mode in plain words, for a card a person reads rather than scans. */
const TRANSIT_MODE_WORD = Object.freeze({
bus: msg('Bus'),
+ trolleybus: msg('Trolleybus'),
tram: msg('Tram'),
+ cable_tram: msg('Cable car'),
subway: msg('Subway'),
+ monorail: msg('Monorail'),
rail: msg('Train'),
+ funicular: msg('Funicular'),
+ aerial_lift: msg('Gondola'),
ferry: msg('Ferry'),
unknown: msg('Transit vehicle'),
});
@@ -535,9 +545,14 @@ const TRANSIT_MODE_WORD = Object.freeze({
/** Short, fixed-width mode word for the detection card's class field. */
const TRANSIT_MODE_ABBR = Object.freeze({
bus: 'BUS',
+ trolleybus: 'TROLLEY',
tram: 'TRAM',
+ cable_tram: 'CABLE',
subway: 'METRO',
+ monorail: 'MONO',
rail: 'RAIL',
+ funicular: 'FUNI',
+ aerial_lift: 'GONDOLA',
ferry: 'FERRY',
unknown: 'TRANSIT',
});
diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js
index 6a43861e6..d13fa1621 100644
--- a/src/layers/transit/rendering.js
+++ b/src/layers/transit/rendering.js
@@ -12,8 +12,10 @@ import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { frustumPlanes } from '../../geo/frustum.js';
import { perspectiveCourseRotation } from '../../data/screenRotation.js';
import {
+ PLACED_WAKE_MS,
updatePlayback,
applyDisplayCourse,
+ playbackMoving,
syncPlayback,
} from './movement.js';
import {
@@ -535,7 +537,7 @@ export function createRendering({ state, services, parts }) {
migrateMarker(entry, false);
return;
}
- const positional = sample.phase === 'playing' && sample.segmentSpeedMps > 0;
+ const positional = playbackMoving(entry);
const turning =
Number.isFinite(sample.segmentCourseDeg) &&
Number.isFinite(entry.courseDeg) &&
@@ -548,7 +550,19 @@ export function createRendering({ state, services, parts }) {
} else {
state._moving.delete(entry);
migrateMarker(entry, false);
- if (Number.isFinite(sample.nextWakeMonoMs)) {
+ // A vehicle a host-supplied placement holds still is asked again every
+ // PLACED_WAKE_MS: it moves on once the placement does.
+ const monoNow = performance.now();
+ const placedWake = entry.placed === true;
+ const boundary = sample.nextWakeMonoMs;
+ const wakeMonoMs = placedWake
+ ? Math.min(
+ Number.isFinite(boundary) ? boundary : Infinity,
+ monoNow + PLACED_WAKE_MS,
+ )
+ : boundary;
+ if (Number.isFinite(wakeMonoMs)) {
+ const atBoundary = !placedWake || boundary <= wakeMonoMs;
entry.wakeTimer = setTimeout(
() => {
entry.wakeTimer = null;
@@ -558,9 +572,10 @@ export function createRendering({ state, services, parts }) {
schedulePlayback(entry);
flushMarkers();
syncRenderHold();
- governorRequestRender('transit-motion-boundary');
+ if (atBoundary || state._moving.has(entry))
+ governorRequestRender('transit-motion-boundary');
},
- Math.max(1, sample.nextWakeMonoMs - performance.now()),
+ Math.max(1, wakeMonoMs - monoNow),
);
}
}
@@ -836,7 +851,8 @@ export function createRendering({ state, services, parts }) {
if (
!entry.surfaceReady ||
entry.sample.phase !== 'playing' ||
- entry.sample.segmentSpeedMps === 0
+ entry.sample.segmentSpeedMps === 0 ||
+ (entry.placed === true && entry.placedMoving !== true)
)
schedulePlayback(entry);
if (!state._moving.has(entry)) settleSelectedCard(entry);
@@ -939,9 +955,15 @@ export function createRendering({ state, services, parts }) {
groundLiftM,
};
}
- if (item.mode !== entry.mode) {
+ if (item.mode !== entry.mode || item.routeType !== entry.routeType) {
item.mode = entry.mode;
- item.spec = transitModelSpec(set, { mode: entry.mode });
+ item.routeType = entry.routeType;
+ // The route type picks the finer model (a coach, a high-speed set);
+ // the mode is the fallback for a type the model table lacks.
+ item.spec = transitModelSpec(set, {
+ routeType: entry.routeType,
+ mode: entry.mode,
+ });
item.tint =
TRANSIT_MODE_COLORS[entry.mode] || TRANSIT_MODE_COLORS.unknown;
}
diff --git a/src/layers/transit/trails.js b/src/layers/transit/trails.js
index 91bc4a900..c090b492b 100644
--- a/src/layers/transit/trails.js
+++ b/src/layers/transit/trails.js
@@ -1,5 +1,5 @@
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
-import { fromDegrees } from '../../geo/ellipsoid.js';
+import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import {
readFix,
correctHeight,
@@ -8,16 +8,9 @@ import {
} from '../../data/contactPlayback.js';
import { createContactTrailRenderer } from '../../data/contactTrailRenderer.js';
import { fixDistanceM } from './movement.js';
+import { TRANSIT_MODE_COLORS } from './policy.js';
import { transitStyleProfile } from '../../data/transitPresetStyle.js';
-const MODE_COLOR = {
- bus: '#5EF08A',
- tram: '#FFC24A',
- subway: '#FF4538',
- rail: '#D9A6FF',
- ferry: '#5FD6FF',
- unknown: '#D8DDE5',
-};
// Final Cesium batching uses 3,152 bytes per two-lane edge.
// The 1,278-instance body plus 64 bytes/instance reserve stays below 2 MiB.
export const TRAIL_VERTEX_LIMIT = 640;
@@ -41,7 +34,7 @@ export function createTrails({ state, services, parts, source }) {
renderer?.setStyle(
transitStyleProfile(state._stylePreset) === 'mono'
? '#FFFFFF'
- : MODE_COLOR[selected?.mode] || MODE_COLOR.unknown,
+ : TRANSIT_MODE_COLORS[selected?.mode] || TRANSIT_MODE_COLORS.unknown,
);
}
function releaseSelectionGeometry(entry) {
@@ -200,6 +193,18 @@ export function createTrails({ state, services, parts, source }) {
nearGround = parts.height.nearGround(),
) {
pruneMarkerPaths(entry, sample);
+ // Placed by a host-supplied placement, it is drawn at the placed point,
+ // at the height its own playback has reached; far above the ground, where
+ // no floor is asked for, on the ellipsoid as an unplaced vehicle is.
+ if (entry.placed === true) {
+ const heightM = Number.isFinite(sample.heightM)
+ ? sample.heightM
+ : nearGround
+ ? NaN
+ : 0;
+ if (!Number.isFinite(heightM)) return null;
+ return fromDegreesInto(sample.lon, sample.lat, heightM, out);
+ }
if (!nearGround) {
const a = entry.fromCart,
b = entry.toCart,
diff --git a/src/layers/vessels/cards.js b/src/layers/vessels/cards.js
index 8cbe250f2..042166bff 100644
--- a/src/layers/vessels/cards.js
+++ b/src/layers/vessels/cards.js
@@ -1,8 +1,10 @@
import {
+ AID_TO_NAVIGATION_STYLE,
accentForVesselType,
displayVesselType,
normalizeVesselType,
} from '../../data/vesselLabels.js';
+import { isAidToNavigation } from '../../data/vesselTypes.js';
import { formatNumber, t } from '../../i18n/index.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
@@ -16,14 +18,21 @@ export function createCards({
function updateSelectedVesselHud(record) {
// Pinned vessels missing from recent refreshes get a stale marker
const stale = (record.missedRefreshes || 0) > 0;
+ // An aid to navigation is a fixed mark: it has no speed or heading to show.
+ const aid = isAidToNavigation(record);
services.readouts?.presentSelectedVessel({
text: [
t('AIS: {name}', { name: trimHudValue(record.name, 32) }),
- t('{type} SPD: {speed} HDG: {heading}', {
- type: trimHudValue(record.type || t('VESSEL'), 24),
- speed: formatSpeed(record.speed),
- heading: formatHeading(record.heading ?? record.course),
- }),
+ aid
+ ? aidKind(
+ trimHudValue(record.type || t('AID TO NAVIGATION'), 24),
+ record,
+ )
+ : t('{type} SPD: {speed} HDG: {heading}', {
+ type: trimHudValue(record.type || t('VESSEL'), 24),
+ speed: formatSpeed(record.speed),
+ heading: formatHeading(record.heading ?? record.course),
+ }),
`MMSI: ${record.mmsi || '--'} ${formatPositionTime(record)}${stale ? ` · ${t('STALE')}` : ''}`,
].join('\n'),
});
@@ -43,27 +52,29 @@ export function createCards({
/**
* Card model for an ambient (decluttered-in) vessel — name title plus one
* compact type/speed/heading detail line, anchored at the record's current
- * rendered position (height-datum caveat: no datum work here). Pure —
- * exported for unit tests.
+ * rendered position (height-datum caveat: no datum work here). An aid to
+ * navigation's line is its kind alone. Pure — exported for unit tests.
* @param {Object} record - Vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildVesselCard(record) {
const parts = [];
+ const aid = isAidToNavigation(record);
const type = vesselTypeShort(record);
if (type) parts.push(type);
- if (record.speed !== null && record.speed !== undefined)
+ if (record.virtual === true) parts.push(t('VIRTUAL'));
+ if (!aid && record.speed !== null && record.speed !== undefined)
parts.push(formatSpeed(record.speed));
const direction = record.heading ?? record.course;
- if (Number.isFinite(direction))
+ if (!aid && Number.isFinite(direction))
parts.push(`${roundHeadingDegrees(direction)}°`);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 10,
- accent: accentForVesselType(record.type),
+ accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 26),
details: parts.length ? [parts.join(' · ')] : [],
selected: false,
@@ -74,22 +85,26 @@ export function createCards({
/**
* Card model for the click-selected vessel — the full-detail card, drawn last
* (on top) and never distance-faded by the overlay. Pinned-but-vanished
- * vessels carry a STALE marker (mirrors the HUD readout). Pure — exported
- * for unit tests.
+ * vessels carry a STALE marker (mirrors the HUD readout). An aid to
+ * navigation shows its kind with no speed or heading. Pure — exported for
+ * unit tests.
* @param {Object} record - Selected vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildSelectedVesselCard(record) {
+ const aid = isAidToNavigation(record);
const direction = record.heading ?? record.course;
const details = [
- [
- vesselTypeShort(record) || t('VESSEL'),
- formatSpeed(record.speed),
- Number.isFinite(direction)
- ? `${roundHeadingDegrees(direction)}°`
- : '--°',
- ].join(' · '),
+ aid
+ ? aidKind(vesselTypeShort(record) || t('AID TO NAVIGATION'), record)
+ : [
+ vesselTypeShort(record) || t('VESSEL'),
+ formatSpeed(record.speed),
+ Number.isFinite(direction)
+ ? `${roundHeadingDegrees(direction)}°`
+ : '--°',
+ ].join(' · '),
];
const destination = String(record.destination || '').trim();
if (destination) details.push(`→ ${trimHudValue(destination, 24)}`);
@@ -102,7 +117,7 @@ export function createCards({
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 12,
- accent: accentForVesselType(record.type),
+ accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 32),
details,
selected: true,
@@ -110,6 +125,20 @@ export function createCards({
};
}
+ /** An aid's kind, marked virtual when nothing physical stands there. */
+
+ function aidKind(kind, record) {
+ return record.virtual === true ? `${kind} · ${t('VIRTUAL')}` : kind;
+ }
+
+ /** A card's accent: an aid's disc colour, else its ship type's. */
+
+ function vesselAccent(record, aid) {
+ return aid
+ ? AID_TO_NAVIGATION_STYLE.accent
+ : accentForVesselType(record.type);
+ }
+
/** Stable overlay identity for keyed and source-retained unkeyed rows. */
function vesselOverlayEntryId(record) {
@@ -125,9 +154,15 @@ export function createCards({
* Uppercased AIS type for the card (empty string when unknown). Free feed
* text is bounded to the card width; a translated type token is a short
* catalog word and shows whole, never cut mid-word ("AUXILIAR DE PUERTO").
+ * An aid's kind is the whole line, so it keeps the room speed and heading
+ * would take ("CARDINAL MARK N", not "CARDINAL MARK ").
*/
function vesselTypeShort(record) {
+ if (isAidToNavigation(record)) {
+ const kind = String(record.type || '').trim();
+ return kind ? trimHudValue(kind.toUpperCase(), 26) : '';
+ }
const feedType = normalizeVesselType(record.type);
const shown = displayVesselType(record.type);
return shown === feedType
diff --git a/src/layers/vessels/index.js b/src/layers/vessels/index.js
index c6d1429dc..57c3e2dc1 100644
--- a/src/layers/vessels/index.js
+++ b/src/layers/vessels/index.js
@@ -31,6 +31,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
parts.queries = createQueries(context);
parts.snapshots = createVesselSnapshotRenderer({
state: vesselState.state,
+ placement: services?.placement ?? null,
records: vesselState.state.records,
rendering: parts.rendering,
tracking: parts.tracking,
diff --git a/src/layers/vessels/ingestion.js b/src/layers/vessels/ingestion.js
index c291c8e35..2eb2d34f0 100644
--- a/src/layers/vessels/ingestion.js
+++ b/src/layers/vessels/ingestion.js
@@ -218,6 +218,7 @@ export function createIngestion({
speed: record.speedMps == null ? null : record.speedMps / 0.514444,
course: record.courseDeg,
heading: record.headingDeg,
+ virtual: record.virtual === true,
last_position_epoch:
record.observedAtMs == null ? null : record.observedAtMs / 1000,
last_position_UTC:
diff --git a/src/layers/vessels/lifecycle.js b/src/layers/vessels/lifecycle.js
index 99df957d2..eb1c7eb76 100644
--- a/src/layers/vessels/lifecycle.js
+++ b/src/layers/vessels/lifecycle.js
@@ -115,6 +115,8 @@ export function createLifecycle({
state.feed.firstConnectTimer = null;
state.feed.abort = null;
state.icons = null;
+ if (services.placement)
+ for (const id of state.records.byId.keys()) services.placement.forget(id);
state.records.all = [];
state.records.byId = new Map();
state.records.unkeyed = [];
@@ -207,6 +209,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels');
components.rendering.cancelTrailingVisibilityPass();
+ components.rendering.cancelPlacementFrame();
unregisterPickOwner('ais-live-vessels');
components.rendering.setVisible(false);
vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID);
@@ -228,6 +231,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels'); // direct-destroy path (perf wave 2 fix)
components.rendering.cancelTrailingVisibilityPass();
+ components.rendering.cancelPlacementFrame();
if (state.feed.abort) state.feed.abort.abort();
unregisterPickOwner('ais-live-vessels');
components.selection.clearVesselInspection();
diff --git a/src/layers/vessels/ownership.test.mjs b/src/layers/vessels/ownership.test.mjs
index daf94e235..265c25e27 100644
--- a/src/layers/vessels/ownership.test.mjs
+++ b/src/layers/vessels/ownership.test.mjs
@@ -556,3 +556,48 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
['235000001', '235000001'],
);
});
+
+test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
+ const aid = {
+ ...observation('993672001'),
+ mmsi: '993672001',
+ type: 'Port Hand Mark',
+ speedMps: 0,
+ };
+ const ship = { ...observation('366999002'), type: 'Cargo' };
+ const { layer, icons } = setup({
+ async getSnapshot() {
+ return snapshot([aid, ship]);
+ },
+ });
+ await layer.update();
+ const svgOf = (id) => {
+ assert.ok(icons.has(id), id);
+ return atob(icons.item(id).image.split(',')[1]);
+ };
+ assert.match(svgOf('993672001'), / layer.testing._vesselRecordForTest(id);
+ assert.equal(recordOf('993672001').virtual, false);
+ assert.equal(recordOf('366999002').virtual, false);
+ assert.doesNotMatch(svgOf('993672001'), / {
+ const aid = {
+ ...observation('993672009'),
+ mmsi: '993672009',
+ type: 'Isolated danger',
+ virtual: true,
+ };
+ const { layer, icons } = setup({
+ async getSnapshot() {
+ return snapshot([aid]);
+ },
+ });
+ await layer.update();
+ assert.ok(icons.has('993672009'));
+ assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
+ assert.match(atob(icons.item('993672009').image.split(',')[1]), / ({
+ id,
+ mmsi: id,
+ lat: 51.93,
+ lon: 4.05,
+ speed: 10,
+ course: 90,
+ heading: 92,
+ last_position_epoch: 1_000,
+ ...fields,
+});
+
+function harness({ placement = null, following = false } = {}) {
+ const visuals = [];
+ const state = { selectedRecord: null, trailId: null };
+ const records = new VesselRecords({ now: () => 5_000_000 });
+ const rendering = {
+ ensureCollections() {},
+ makeOccluder: () => null,
+ renderRowLimit: () => Infinity,
+ prepareRecordVisual(record) {
+ visuals.push(record.id);
+ return { billboard: null };
+ },
+ addRecordPrimitives() {},
+ removeRecordPrimitives() {},
+ shipIcon: () => 'icon',
+ shipScale: () => 1,
+ syncRecordIcon() {},
+ updateVisibility() {},
+ };
+ const renderer = createVesselSnapshotRenderer({
+ state,
+ placement,
+ records,
+ rendering,
+ tracking: {},
+ selection: {},
+ cards: {},
+ followsClock: () => following,
+ });
+ return {
+ visuals,
+ reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
+ };
+}
+
+function recording() {
+ const told = [];
+ const forgotten = [];
+ const placement = layerPlacement(
+ {
+ layer: () => ({
+ observe: (id, fix) => told.push([id, fix]),
+ place: () => null,
+ forget: (id) => forgotten.push(id),
+ }),
+ },
+ 'vessels',
+ );
+ return { told, forgotten, placement };
+}
+
+test('vessels reconcile as before with no placement', () => {
+ const own = harness();
+ own.reconcile([row('a'), row('b')]);
+ own.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
+ const { placement } = recording();
+ const placed = harness({ placement });
+ placed.reconcile([row('a'), row('b')]);
+ placed.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
+ assert.deepEqual(placed.visuals, own.visuals);
+});
+
+test('each live vessel fix is told to the placement, in m/s, and a vessel that leaves is forgotten', () => {
+ const { told, forgotten, placement } = recording();
+ const probe = harness({ placement });
+ probe.reconcile([row('a'), row('b', { speed: null, course: null })]);
+ probe.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
+ assert.deepEqual(
+ told.map(([id, fix]) => [id, fix.timeMs, fix.lat]),
+ [
+ ['a', 1_000_000, 51.93],
+ ['b', 1_000_000, 51.93],
+ ['a', 1_060_000, 52],
+ ],
+ );
+ assert.ok(Math.abs(told[0][1].speedMps - 10 * (1852 / 3600)) < 1e-12);
+ assert.equal(told[0][1].courseDeg, 90);
+ assert.equal(told[0][1].headingDeg, 92);
+ assert.ok(Number.isNaN(told[1][1].speedMps));
+ assert.ok(Number.isNaN(told[1][1].courseDeg));
+ assert.deepEqual(forgotten, ['b']);
+});
+
+test('following the world clock, or rows at another time, tell the placement nothing', () => {
+ const { told, placement } = recording();
+ harness({ placement, following: true }).reconcile([row('a')]);
+ harness({ placement }).reconcile([row('a')], { replace: true });
+ assert.deepEqual(told, []);
+});
diff --git a/src/layers/vessels/records.js b/src/layers/vessels/records.js
index c63f8b955..5b7b08117 100644
--- a/src/layers/vessels/records.js
+++ b/src/layers/vessels/records.js
@@ -31,6 +31,8 @@ export function normalizeVessel(row) {
speed: finiteNumber(row.speed),
course: finiteNumber(row.course),
heading: finiteNumber(row.heading),
+ // A virtual aid to navigation: a mark with nothing physical there.
+ virtual: row.virtual === true,
lastPositionUtc: String(row.last_position_UTC || ''),
lastPositionEpoch: finiteNumber(row.last_position_epoch),
missedRefreshes: 0,
@@ -159,6 +161,7 @@ export class VesselRecords {
record.speed = next.speed;
record.course = next.course;
record.heading = next.heading;
+ record.virtual = next.virtual;
record.lastPositionUtc = next.lastPositionUtc;
record.lastPositionEpoch = next.lastPositionEpoch;
record.missedRefreshes = 0;
diff --git a/src/layers/vessels/renderGovernor.test.mjs b/src/layers/vessels/renderGovernor.test.mjs
index 3c537c318..c3f195cec 100644
--- a/src/layers/vessels/renderGovernor.test.mjs
+++ b/src/layers/vessels/renderGovernor.test.mjs
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { VISIBILITY_UPDATE_MS } from './policy.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
+import { layerPlacement } from '../../data/placementProvider.js';
// Vessels move only when a poll lands, so the layer must let the scene idle:
// it asks for frames for forced passes and one trailing frame after the camera
@@ -10,7 +11,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
-function setup({ focusPassIsNeeded = () => false } = {}) {
+function setup({ focusPassIsNeeded = () => false, placement = null } = {}) {
let clock = 10_000;
const requests = [];
const holds = new Set();
@@ -47,6 +48,7 @@ function setup({ focusPassIsNeeded = () => false } = {}) {
releaseContinuousRender: (id) => holds.delete(id),
governorRequestRender: (reason) => requests.push(reason),
},
+ ...(placement ? { placement: layerPlacement(placement, 'vessels') } : {}),
},
});
const camera = {
@@ -184,3 +186,56 @@ test('a focus pass reads the camera pose even with a trailing frame waiting', ()
frame();
assert.ok(reads > 0, 'the focus pass needs the eye');
});
+
+test('a placement that places nothing asks for no frames; one that places a drawn vessel moves it in place', (t) => {
+ let mono = 0;
+ t.mock.method(performance, 'now', () => mono);
+ const originalDocument = globalThis.document;
+ globalThis.document = { getElementById: () => null };
+ t.after(() => {
+ if (originalDocument === undefined) delete globalThis.document;
+ else globalThis.document = originalDocument;
+ });
+ let spot = null;
+ const { layer, camera, requests, timers, advance } = setup({
+ placement: { layer: () => ({ place: () => spot }) },
+ });
+ const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
+ const viewer = { camera, scene: {} };
+ bindFakeCesiumScene(viewer);
+ layer.testing._setVesselStateForTest({ viewer, records: [record] });
+ const visual = layer.testing._prepareVesselVisualForTest(record);
+ // Drawn: on the camera's side of the horizon.
+ visual.visible = true;
+ const position = visual.position;
+ const before = { ...position };
+
+ // Nothing placed: no frame is asked for, and the vessel stays put.
+ for (let i = 0; i < 8; i += 1) {
+ mono += 250;
+ layer.testing._runPlacementPassForTest();
+ advance(250);
+ }
+ assert.equal(timers.size, 0);
+ assert.deepEqual(requests, []);
+ assert.deepEqual({ ...visual.position }, before);
+
+ // Placed: moved in place, no new positions, and a frame asked for.
+ spot = { lat: 51.94, lon: 4.05 };
+ mono += 250;
+ layer.testing._runPlacementPassForTest();
+ assert.equal(visual.position, position, 'written in place');
+ assert.notDeepEqual({ ...visual.position }, before);
+ assert.equal(timers.size, 1);
+ advance(1_000);
+ assert.deepEqual(requests, ['ais-vessels-placement']);
+
+ // Turning the layer off drops the pending frame.
+ mono += 250;
+ layer.testing._runPlacementPassForTest();
+ assert.equal(timers.size, 1);
+ layer.destroy();
+ assert.equal(timers.size, 0);
+ advance(1_000);
+ assert.deepEqual(requests, ['ais-vessels-placement']);
+});
diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js
index da8e268e6..f25e23160 100644
--- a/src/layers/vessels/rendering.js
+++ b/src/layers/vessels/rendering.js
@@ -1,12 +1,13 @@
import { t } from '../../i18n/index.js';
import {
+ AID_TO_NAVIGATION_STYLE,
vesselTypeCss,
vesselOverlayCohortLimit,
VESSEL_OVERLAY_SOURCE_ID,
applyVesselOverlayPolicy,
VESSEL_CARD_FADE_DISTANCE_M,
} from '../../data/vesselLabels.js';
-import { fromDegrees } from '../../geo/ellipsoid.js';
+import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
import { distance, distanceSquared } from '../../geo/vector.js';
import {
@@ -35,9 +36,12 @@ import {
vesselModelSpec,
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
+import { isAidToNavigation } from '../../data/vesselTypes.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
+/** A frame is asked for this often while a placement moves live vessels. */
+const PLACEMENT_FRAME_MS = 1000;
/** The ship artwork's own raster size (px). */
const SHIP_ICON_PX = 32;
@@ -79,26 +83,43 @@ export function createRendering({
};
visualRecords.set(record, visual);
}
- visual.position = anchorPosition(record);
+ const { lat, lon } = drawnAt(record);
+ visual.position = anchorAt(lat, lon);
// A ship model's origin is its waterline: the sea surface, unlifted.
- visual.waterline = anchorPosition(record, 0);
+ visual.waterline = anchorAt(lat, lon, 0);
+ if (services.placement) {
+ visual.drawnLat = lat;
+ visual.drawnLon = lon;
+ }
return visual;
}
/**
- * Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface
- * (the geoid, once its grid has loaded). Following the world clock, a
- * vessel is drawn where it was at the time.
+ * Where a record is drawn now: following the world clock, where it was at
+ * the time; live, where a host-supplied placement draws it, if one does.
* @param {Object} record - Vessel record with a finite lat/lon.
+ * @returns {{lat: number, lon: number}} A fresh pair (the placement's
+ * answer is reused by its next call).
+ */
+ function drawnAt(record) {
+ const { lat, lon } = followsClock(vesselState)
+ ? vesselPositionAt(record, vesselState.worldNow())
+ : (services.placement?.place(record.id, vesselState._aisRuntime.now()) ??
+ record);
+ return { lat, lon };
+ }
+
+ /**
+ * Where an icon at `lat`/`lon` is anchored: VESSEL_LIFT_M above the sea
+ * surface (the geoid, once its grid has loaded).
+ * @param {number} lat
+ * @param {number} lon
* @param {number} [liftM] Height above the sea surface (the icon's lift by
* default; 0 for a ship model's waterline).
* @returns {{x: number, y: number, z: number}} ECEF metres: icon items,
* focus and the layer's queries take it as it is.
*/
- function anchorPosition(record, liftM = VESSEL_LIFT_M) {
- const { lat, lon } = followsClock(vesselState)
- ? vesselPositionAt(record, vesselState.worldNow())
- : record;
+ function anchorAt(lat, lon, liftM = VESSEL_LIFT_M) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
liftM,
@@ -106,6 +127,35 @@ export function createRendering({
return fromDegrees(lon, lat, heightM);
}
+ /**
+ * Where a record's icon is anchored (see drawnAt and anchorAt).
+ * @param {Object} record - Vessel record with a finite lat/lon.
+ * @param {number} [liftM] Height above the sea surface.
+ * @returns {{x: number, y: number, z: number}} ECEF metres.
+ */
+ function anchorPosition(record, liftM = VESSEL_LIFT_M) {
+ const { lat, lon } = drawnAt(record);
+ return anchorAt(lat, lon, liftM);
+ }
+
+ /**
+ * Move a prepared vessel visual to `lat`/`lon` (a host-supplied placement
+ * moved it), writing into its own positions rather than allocating new
+ * ones: the placement pass runs for every drawn vessel several times a
+ * second. Its icon is drawn there again.
+ */
+ function moveRecordVisual(record, visual, lat, lon) {
+ const heightM = components.queries.vesselDatumHeightM(
+ components.tracking.currentGeoidN(lat, lon),
+ VESSEL_LIFT_M,
+ );
+ fromDegreesInto(lon, lat, heightM, visual.position);
+ fromDegreesInto(lon, lat, heightM - VESSEL_LIFT_M, visual.waterline);
+ visual.drawnLat = lat;
+ visual.drawnLon = lon;
+ syncRecordIcon(record);
+ }
+
// Reused projection buffers for the card pass, grown to the candidates.
let worldXyz = new Float64Array(0);
let screenXy = new Float32Array(0);
@@ -281,12 +331,14 @@ export function createRendering({
/**
* Best available real-world direction of travel for a vessel, degrees
* clockwise from north (true heading preferred, course-over-ground fallback).
- * The renderer turns this into its screen rotation each frame.
+ * The renderer turns this into its screen rotation each frame. An aid to
+ * navigation is fixed, so it has none.
* @param {Object} record - Vessel record.
* @returns {number} Course in degrees (0 when unknown).
*/
function vesselCourseDeg(record) {
+ if (isAidToNavigation(record)) return 0;
const direction = record.heading ?? record.course;
return Number.isFinite(direction) ? direction : 0;
}
@@ -294,6 +346,7 @@ export function createRendering({
/**
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
* The shape points north (up) so the row's course maps directly to heading.
+ * An aid to navigation, which has no heading, is a ringed disc instead.
* One icon is generated per color+variant and shares one atlas slot.
* @param {Object} record - Vessel record (drives per-type tint).
* @param {boolean} selected - True for the white/brighter selected variant.
@@ -301,16 +354,25 @@ export function createRendering({
*/
function shipIcon(record, selected) {
- const cssColor = selected ? '#ffffff' : vesselTypeCss(record.type);
- const key = `${cssColor}:${selected ? 'selected' : 'normal'}`;
+ const aid = isAidToNavigation(record);
+ const cssColor = selected
+ ? '#ffffff'
+ : aid
+ ? AID_TO_NAVIGATION_STYLE.css
+ : vesselTypeCss(record.type);
+ const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`;
if (vesselState.shipIconCache.has(key))
return vesselState.shipIconCache.get(key);
const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)';
const strokeWidth = selected ? 1.1 : 0.7;
+ const shape = aid
+ ? `
+ `
+ : ` `;
const svg = `
-
+ ${shape}
`;
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
@@ -344,8 +406,13 @@ export function createRendering({
});
}
- /** The model item for `record`, its spec rebuilt only when its type or size changes. */
+ /**
+ * The model item for `record`, its spec rebuilt only when its type or size
+ * changes; null for a virtual aid to navigation, which keeps its disc: no
+ * buoy stands there (vesselModelSpec).
+ */
function modelItem(record, set) {
+ if (record.virtual === true) return null;
let item = modelItems.get(record.id);
if (!item || item.record !== record)
item = {
@@ -354,13 +421,14 @@ export function createRendering({
tint: null,
modelOwnsVisual: false,
};
- const specKey = `${record.type}|${record.length}|${record.beam}|${record.name}`;
+ const specKey = `${record.type}|${record.mmsi}|${record.length}|${record.beam}|${record.name}`;
if (item.specKey !== specKey) {
item.specKey = specKey;
item.spec = vesselModelSpec(set, record);
}
item.position = getVisual(record).waterline;
- item.headingDeg = vesselCourseDeg(record);
+ // An aid to navigation is a fixed mark: it does not turn to a heading.
+ item.headingDeg = item.spec?.fixed ? 0 : vesselCourseDeg(record);
item.show = record.id !== state.cockpitSubjectId;
return item;
}
@@ -381,7 +449,8 @@ export function createRendering({
const waterline = getVisual(record).waterline;
if (!waterline) continue;
if (distanceSquared(eye, waterline) > limitSq) continue;
- into.set(record.id, modelItem(record, set));
+ const item = modelItem(record, set);
+ if (item) into.set(record.id, item);
}
}
@@ -412,8 +481,10 @@ export function createRendering({
gatherModelItems(set, next);
} else {
for (const [id, item] of modelItems)
- if (state.records.byId.get(id) === item.record)
- next.set(id, modelItem(item.record, set));
+ if (state.records.byId.get(id) === item.record) {
+ const kept = modelItem(item.record, set);
+ if (kept) next.set(id, kept);
+ }
}
for (const [id, item] of modelItems)
if (next.get(id) !== item) handBackVisual(item.record);
@@ -453,6 +524,7 @@ export function createRendering({
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => {
if (followsClock(vesselState)) followClockPositions();
+ else if (services.placement && state.feed.enabled) followPlacements();
updateVisibility();
if (state.feed.enabled) updateModels();
}) ?? null;
@@ -475,6 +547,52 @@ export function createRendering({
}
}
+ // Live with a host-supplied placement, vessels move on between refreshes:
+ // drawn where it places them at most every FOLLOW_POSITION_MS, with a frame
+ // asked for every PLACEMENT_FRAME_MS while it places any drawn vessel, so
+ // they move while the scene idles.
+ let placedAtWallMs = -Infinity;
+ let placing = false;
+ let placementFrameTimer = null;
+ function followPlacements() {
+ const wallMs = performance.now();
+ if (wallMs - placedAtWallMs >= FOLLOW_POSITION_MS) {
+ placedAtWallMs = wallMs;
+ placing = false;
+ const nowMs = vesselState._aisRuntime.now();
+ // Drawn vessels only, as a sprite or a model: a hidden one is placed
+ // again when it is drawn.
+ for (const record of state.records.all) {
+ const visual = visualRecords.get(record);
+ if (!visual?.position) continue;
+ const drawn =
+ (visual.visible && !isCockpitSubject(record)) ||
+ visual.modelOwnsVisual;
+ if (!drawn) continue;
+ const placed = services.placement.place(record.id, nowMs);
+ if (placed) placing = true;
+ const { lat, lon } = placed ?? record;
+ if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
+ moveRecordVisual(record, visual, lat, lon);
+ }
+ }
+ if (placing && placementFrameTimer === null)
+ placementFrameTimer = vesselState._aisRuntime.setTimeout(() => {
+ placementFrameTimer = null;
+ if (state.feed.enabled && !followsClock(vesselState))
+ governorRequestRender('ais-vessels-placement');
+ }, PLACEMENT_FRAME_MS);
+ }
+
+ /** Stop asking for placement frames (the layer turned off or went away). */
+ function cancelPlacementFrame() {
+ placedAtWallMs = -Infinity;
+ placing = false;
+ if (placementFrameTimer === null) return;
+ vesselState._aisRuntime.clearTimeout(placementFrameTimer);
+ placementFrameTimer = null;
+ }
+
function scheduleTrailingVisibilityPass(now) {
if (state.trailingVisibilityTimer) return;
const waitMs = Math.max(
@@ -837,6 +955,8 @@ export function createRendering({
installRuntime,
updateVisibility,
cancelTrailingVisibilityPass,
+ cancelPlacementFrame,
+ followPlacements,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
diff --git a/src/layers/vessels/snapshotRenderer.js b/src/layers/vessels/snapshotRenderer.js
index ae648574f..ab10a9fe1 100644
--- a/src/layers/vessels/snapshotRenderer.js
+++ b/src/layers/vessels/snapshotRenderer.js
@@ -1,7 +1,32 @@
-/** Connect portable vessel reconciliation to scene and selection operations. */
+const KNOT_MPS = 1852 / 3600;
+const finiteOrNaN = (value) =>
+ typeof value === 'number' && Number.isFinite(value) ? value : NaN;
+/**
+ * A vessel record's fix as a host-supplied placement takes it: its own time
+ * (when it was received, if the row gives none), position, speed in m/s
+ * (rows give knots), course and heading.
+ */
+function placementFix(record) {
+ const epoch = record.lastPositionEpoch;
+ return {
+ timeMs: Number.isFinite(epoch) ? epoch * 1000 : record.receivedAtMs,
+ lat: record.lat,
+ lon: record.lon,
+ altitudeM: NaN,
+ speedMps: Number.isFinite(record.speed) ? record.speed * KNOT_MPS : NaN,
+ courseDeg: finiteOrNaN(record.course),
+ headingDeg: finiteOrNaN(record.heading),
+ };
+}
+
+/**
+ * Connect portable vessel reconciliation to scene and selection operations.
+ * `placement`, a host-supplied placement, is told each live fix.
+ */
export function createVesselSnapshotRenderer({
state,
+ placement = null,
records,
rendering,
tracking,
@@ -18,6 +43,13 @@ export function createVesselSnapshotRenderer({
rendering.ensureCollections(viewer);
const occluder = rendering.makeOccluder();
const follow = followsClock();
+ // Live fixes only: following the clock, the layer places every vessel.
+ const observe =
+ placement && !follow && !replace
+ ? (record) => {
+ if (record.id) placement.observe(record.id, placementFix(record));
+ }
+ : () => {};
records.reconcile(
rows,
{
@@ -29,10 +61,12 @@ export function createVesselSnapshotRenderer({
},
{
add(record) {
+ observe(record);
rendering.prepareRecordVisual(record);
rendering.addRecordPrimitives(record, occluder);
},
updated(record) {
+ observe(record);
const selected = record === state.selectedRecord;
rendering.prepareRecordVisual(record);
rendering.syncRecordIcon(record);
@@ -48,6 +82,7 @@ export function createVesselSnapshotRenderer({
rendering.removeRecordPrimitives(record);
},
removed(id) {
+ placement?.forget(id);
if (state.trailId === id) tracking.clearSelectedVesselTrail();
},
staleSelected(record) {
diff --git a/src/layers/vessels/testing.js b/src/layers/vessels/testing.js
index 5a7c7bf4b..1ad1a4162 100644
--- a/src/layers/vessels/testing.js
+++ b/src/layers/vessels/testing.js
@@ -164,6 +164,18 @@ export function createTesting({
components.rendering.updateVisibility(force);
}
+ /** Draw a record's visual where it stands now. Test-only seam. */
+
+ function _prepareVesselVisualForTest(record) {
+ return components.rendering.prepareRecordVisual(record);
+ }
+
+ /** Run one live placement pass (a host-supplied placement). Test-only seam. */
+
+ function _runPlacementPassForTest() {
+ components.rendering.followPlacements();
+ }
+
/** True while a trailing visibility frame is scheduled. Test-only seam. */
function _hasTrailingVisibilityPassForTest() {
@@ -183,6 +195,12 @@ export function createTesting({
vesselCount: state.records.byId.size,
};
}
+
+ /** The layer's record for a vessel id, or null. Test-only seam. */
+
+ function _vesselRecordForTest(id) {
+ return state.records.byId.get(id) ?? null;
+ }
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
@@ -195,7 +213,10 @@ export function createTesting({
_setAisRuntimeForTest,
_getVesselFeedStateForTest,
_getVesselStateForTest,
+ _vesselRecordForTest,
_runVisibilityPassForTest,
+ _prepareVesselVisualForTest,
+ _runPlacementPassForTest,
_hasTrailingVisibilityPassForTest,
};
}
diff --git a/src/layers/vessels/tracking.js b/src/layers/vessels/tracking.js
index 7b416a720..84fd886bd 100644
--- a/src/layers/vessels/tracking.js
+++ b/src/layers/vessels/tracking.js
@@ -66,6 +66,11 @@ export function createTracking({
continue;
visual.position = components.rendering.anchorPosition(record);
components.rendering.syncRecordIcon(record);
+ // A placed vessel is drawn again at its placement on the next pass.
+ if (services.placement) {
+ visual.drawnLat = NaN;
+ visual.drawnLon = NaN;
+ }
}
// The rows moved with no poll behind them: draw the frame that shows it.
governorRequestRender('ais-vessels-refloor');
diff --git a/src/layers/weather/clock.js b/src/layers/weather/clock.js
index 754887235..15d242742 100644
--- a/src/layers/weather/clock.js
+++ b/src/layers/weather/clock.js
@@ -4,6 +4,52 @@ export const RADAR_MAX_GAP_MS = 30 * 60_000;
export const REGIONAL_INFRARED_MAX_GAP_MS = 30 * 60_000;
export const GLOBAL_INFRARED_MAX_GAP_MS = 3 * 60 * 60_000;
export const LIGHTNING_MAX_GAP_MS = 30 * 60_000;
+/** How many of a feed's latest frames say how far apart its frames come. */
+const SPACING_FRAMES = 12;
+/** A frame holds this many of its feed's frame spacings before it lapses. */
+const SPACING_SLACK = 1.5;
+
+/**
+ * How far apart a feed's frames come: the median spacing of its latest
+ * frames, in ms, or null with fewer than two. Takes UTC times or epoch ms.
+ * @param {Array} times
+ * @returns {number|null}
+ */
+export function frameSpacingMs(times) {
+ const at = [
+ ...new Set(
+ (times ?? [])
+ .map((time) => (typeof time === 'number' ? time : Date.parse(time)))
+ .filter(Number.isFinite),
+ ),
+ ]
+ .sort((a, b) => a - b)
+ .slice(-(SPACING_FRAMES + 1));
+ if (at.length < 2) return null;
+ const gaps = at
+ .slice(1)
+ .map((time, i) => time - at[i])
+ .sort((a, b) => a - b);
+ const middle = gaps.length >> 1;
+ return gaps.length % 2 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
+}
+
+/**
+ * A product's least time, `leastMs`, held to its feed's own frame spacing:
+ * never less than one and a half spacings, so a feed whose frames come an
+ * hour apart covers the whole hour between them, while one with frames
+ * minutes apart keeps `leastMs`.
+ * @param {number} leastMs
+ * @param {Array} times
+ * @returns {number}
+ */
+export function atLeastFrameSpacing(leastMs, times) {
+ const spacing = frameSpacingMs(times);
+ return spacing === null
+ ? leastMs
+ : Math.max(leastMs, spacing * SPACING_SLACK);
+}
+
/** The longest play waits on a frame before it goes on without it. */
export const PLAY_WAIT_MS = 8_000;
// Playing on its own, the world does not wait on the frame it is at: that
diff --git a/src/layers/weather/clock.test.mjs b/src/layers/weather/clock.test.mjs
index dd2535ffc..90cd1bd6b 100644
--- a/src/layers/weather/clock.test.mjs
+++ b/src/layers/weather/clock.test.mjs
@@ -7,6 +7,8 @@ import {
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
PLAY_WAIT_MS,
+ frameSpacingMs,
+ atLeastFrameSpacing,
} from './clock.js';
import { createWorldClock } from '../../time/worldClock.js';
@@ -94,6 +96,68 @@ test('union excludes suspended products; nearest selection never uses future or
assert.equal(LIGHTNING_MAX_GAP_MS, 30 * 60_000);
});
+test('a feed’s frame spacing is the median of its latest frames', () => {
+ assert.equal(frameSpacingMs([]), null);
+ assert.equal(frameSpacingMs([time(0)]), null);
+ assert.equal(frameSpacingMs([0, 10, 20, 30].map(time)), 10 * 60_000);
+ // Out of order, repeated, unparseable, and one late frame among many.
+ assert.equal(
+ frameSpacingMs([
+ time(60),
+ time(0),
+ 'never',
+ time(0),
+ time(10),
+ time(20),
+ time(30),
+ ]),
+ 10 * 60_000,
+ );
+ assert.equal(frameSpacingMs([0, 60, 120].map(time)), 60 * 60_000);
+ assert.equal(frameSpacingMs([0, 10, 70, 130]), 60);
+ // Only the latest frames count: an hourly start gives way to ten minutes.
+ const times = [
+ ...[-600, -540, -480, -420, -360, -300, -240, -180, -120, -60],
+ ...[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
+ ].map(time);
+ assert.equal(frameSpacingMs(times), 10 * 60_000);
+});
+
+test('a product’s gap is at least one and a half of its feed’s frame spacings', (t) => {
+ const tenMinutes = [0, 10, 20, 30].map(time);
+ const hourly = [0, 60, 120].map(time);
+ assert.equal(
+ atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, tenMinutes),
+ REGIONAL_INFRARED_MAX_GAP_MS,
+ 'frames minutes apart keep the product’s own gap',
+ );
+ assert.equal(
+ atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, hourly),
+ 90 * 60_000,
+ );
+ assert.equal(
+ atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, [time(0)]),
+ REGIONAL_INFRARED_MAX_GAP_MS,
+ );
+ assert.equal(
+ atLeastFrameSpacing(GLOBAL_INFRARED_MAX_GAP_MS, hourly),
+ GLOBAL_INFRARED_MAX_GAP_MS,
+ );
+
+ // Selected against it, an hourly feed has a frame all through each hour.
+ const { clock } = harness(t);
+ const clouds = product(
+ 'clouds',
+ [0, 60, 120],
+ atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, hourly),
+ );
+ clock.register(clouds);
+ assert.equal(clock.selectFor('clouds', time(45)), time(0));
+ assert.equal(clock.selectFor('clouds', time(119)), time(60));
+ assert.equal(clock.selectFor('clouds', time(210)), time(120));
+ assert.equal(clock.selectFor('clouds', time(211)), null);
+});
+
test('history applies per-product selections, including null; latest restores unequal newest times', async (t) => {
const { clock } = harness(t);
const radar = product('radar', [0, 10, 20]);
diff --git a/src/layers/weather/index.js b/src/layers/weather/index.js
index 215061970..9f393ddfe 100644
--- a/src/layers/weather/index.js
+++ b/src/layers/weather/index.js
@@ -8,6 +8,7 @@ import {
REGIONAL_INFRARED_MAX_GAP_MS,
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
+ atLeastFrameSpacing,
} from './clock.js';
import { formatUtcDayMonth, t, msg } from '../../i18n/index.js';
import { formatScaleLabel } from '../../ui/unitLabels.js';
@@ -102,7 +103,10 @@ export function createWeatherLayer({
let unregisterClock = null;
let frameRequest = null;
let noFrame = false;
- const maxGap = () =>
+ // A product's own gap, and the delay after which its latest frame reads
+ // late. A feed whose frames come further apart holds each frame, and waits
+ // for the next, as long as its frames are apart (see atLeastFrameSpacing).
+ const productGap = () =>
radar
? RADAR_MAX_GAP_MS
: lightning
@@ -110,6 +114,23 @@ export function createWeatherLayer({
: product === 'clouds'
? GLOBAL_INFRARED_MAX_GAP_MS
: REGIONAL_INFRARED_MAX_GAP_MS;
+ const productDelay = () =>
+ (product === 'clouds' ? 240 : lightning ? 45 : 20) * 60_000;
+ // Read for every frame a selection weighs, so worked out once per product
+ // and frame list.
+ let spaced = null;
+ const spacedTimes = () => {
+ const times = manifest?.times ?? [];
+ if (spaced?.times !== times || spaced?.product !== product)
+ spaced = {
+ times,
+ product,
+ gap: atLeastFrameSpacing(productGap(), times),
+ delay: atLeastFrameSpacing(productDelay(), times),
+ };
+ return spaced;
+ };
+ const maxGap = () => spacedTimes().gap;
const isLatest = () =>
clock ? clock.getState().mode === 'latest' : followLatest;
const getHost = () => imageryHost?.() ?? globeImageryHost(viewer);
@@ -130,8 +151,7 @@ export function createWeatherLayer({
};
const observationDelayed = () =>
manifest?.latest &&
- worldNow() - Date.parse(manifest.latest) >
- (product === 'clouds' ? 240 : lightning ? 45 : 20) * 60_000;
+ worldNow() - Date.parse(manifest.latest) > spacedTimes().delay;
const stop = () => {
if (clock) return;
playing = false;
@@ -560,11 +580,11 @@ export function createWeatherLayer({
shared.products.find((entry) => entry.id === id)?.selected === null
? maxGap() / 60_000 < 60
? t('No frame within {gap} min of {time}', {
- gap: maxGap() / 60_000,
+ gap: Math.round(maxGap() / 60_000),
time: utc(shared.target),
})
: t('No frame within {gap} h of {time}', {
- gap: maxGap() / 3600_000,
+ gap: Math.round(maxGap() / 360_000) / 10,
time: utc(shared.target),
})
: null;
@@ -699,7 +719,7 @@ export function createWeatherLayer({
? t('Global · 60°S–60°N')
: t('North America')),
shownTime: time,
- maxGapMinutes: maxGap() / 60_000,
+ maxGapMinutes: Math.round(maxGap() / 60_000),
detail,
status:
missing ||
diff --git a/src/layers/weather/weather.test.mjs b/src/layers/weather/weather.test.mjs
index 4eee04135..bd67d8305 100644
--- a/src/layers/weather/weather.test.mjs
+++ b/src/layers/weather/weather.test.mjs
@@ -1986,6 +1986,69 @@ test('satellite global selection uses the three-hour gap and preserves the share
assert.equal(params.target, undefined);
});
+test('satellite clouds from an hourly feed draw all through each hour and read late only past it', async (t) => {
+ const clock = createWeatherClock();
+ const now = Date.now();
+ const hour = 3_600_000;
+ const top = Math.floor(now / hour) * hour;
+ // Frames an hour apart, the latest forty minutes old.
+ const hourly = [3, 2, 1].map((back) =>
+ new Date(top - back * hour + 20 * 60_000).toISOString(),
+ );
+ const latest = hourly.at(-1);
+ const h = layerHarness({
+ clock,
+ id: 'weather-satellite',
+ feed: {
+ getSnapshot: async ({ product }) => ({
+ ...snapshot,
+ product,
+ times: hourly,
+ latest,
+ }),
+ },
+ });
+ t.after(() => {
+ h.layer.destroy();
+ clock.destroy();
+ });
+ t.mock.method(Date, 'now', () => Date.parse(latest) + 40 * 60_000);
+ const update = h.layer.update();
+ await flush();
+ h.stages.at(-1).finish();
+ await update;
+ assert.equal(h.layer.getParams().product, 'clouds-regional');
+ assert.equal(h.layer.getRowControls().summary.maxGapMinutes, 90);
+ assert.equal(
+ h.layer.getStats().stale,
+ false,
+ 'forty minutes is within the hour',
+ );
+
+ // Forty-five minutes past a frame, between it and the next, it still shows.
+ const between = clock.setTarget(
+ new Date(Date.parse(hourly[0]) + 45 * 60_000).toISOString(),
+ );
+ await flush();
+ h.stages.at(-1).finish();
+ await between;
+ assert.equal(h.layer.getDiagnostics().hidden, false);
+ assert.equal(h.stages.at(-1).time, hourly[0]);
+
+ // Live again (a past time judges delay from the timeline's time), past
+ // one and a half hours it reads late.
+ const live = clock.latest();
+ await flush();
+ h.stages.at(-1).finish();
+ await live;
+ t.mock.method(Date, 'now', () => Date.parse(latest) + 100 * 60_000);
+ assert.equal(
+ h.layer.getStats().stale,
+ true,
+ 'past one and a half hours, late',
+ );
+});
+
test('switching to history cancels a still-loading latest refresh and a later target cancels the first history load', async (t) => {
const clock = createWeatherClock();
const h = layerHarness({ clock });
diff --git a/src/overlays/worldOverlayTokens.js b/src/overlays/worldOverlayTokens.js
index c03383148..895ba9ac7 100644
--- a/src/overlays/worldOverlayTokens.js
+++ b/src/overlays/worldOverlayTokens.js
@@ -139,9 +139,14 @@ export const DETECTION_THEME_MAP = Object.freeze({
veh_free: '#00ff66',
veh_nodata: '#c9c9c9',
transit_bus: '#5EF08A',
+ transit_trolleybus: '#B6F04A',
transit_tram: '#FFC24A',
+ transit_cable_tram: '#FF8F4A',
transit_subway: '#FF4538',
+ transit_monorail: '#FF6FB8',
transit_rail: '#D9A6FF',
+ transit_funicular: '#E8C98A',
+ transit_aerial_lift: '#7FA8FF',
transit_ferry: '#5FD6FF',
transit_unknown: '#D8DDE5',
},
@@ -169,9 +174,14 @@ export const DETECTION_THEME_MAP = Object.freeze({
veh_free: '#45d8ff',
veh_nodata: '#dcdcdc',
transit_bus: '#5EF08A',
+ transit_trolleybus: '#B6F04A',
transit_tram: '#FFC24A',
+ transit_cable_tram: '#FF8F4A',
transit_subway: '#FF4538',
+ transit_monorail: '#FF6FB8',
transit_rail: '#D9A6FF',
+ transit_funicular: '#E8C98A',
+ transit_aerial_lift: '#7FA8FF',
transit_ferry: '#5FD6FF',
transit_unknown: '#D8DDE5',
},
@@ -199,9 +209,14 @@ export const DETECTION_THEME_MAP = Object.freeze({
veh_free: '#2ecc71',
veh_nodata: '#d8d8d8',
transit_bus: '#5EF08A',
+ transit_trolleybus: '#B6F04A',
transit_tram: '#FFC24A',
+ transit_cable_tram: '#FF8F4A',
transit_subway: '#FF4538',
+ transit_monorail: '#FF6FB8',
transit_rail: '#D9A6FF',
+ transit_funicular: '#E8C98A',
+ transit_aerial_lift: '#7FA8FF',
transit_ferry: '#5FD6FF',
transit_unknown: '#D8DDE5',
},
@@ -229,9 +244,14 @@ export const DETECTION_THEME_MAP = Object.freeze({
veh_free: '#2ecc71',
veh_nodata: '#c9c9c9',
transit_bus: '#5EF08A',
+ transit_trolleybus: '#B6F04A',
transit_tram: '#FFC24A',
+ transit_cable_tram: '#FF8F4A',
transit_subway: '#FF4538',
+ transit_monorail: '#FF6FB8',
transit_rail: '#D9A6FF',
+ transit_funicular: '#E8C98A',
+ transit_aerial_lift: '#7FA8FF',
transit_ferry: '#5FD6FF',
transit_unknown: '#D8DDE5',
},
diff --git a/src/sources/live/contract.js b/src/sources/live/contract.js
index c40d23b0f..e201fc8de 100644
--- a/src/sources/live/contract.js
+++ b/src/sources/live/contract.js
@@ -12,7 +12,9 @@
* snapshots. A vessel record's `id` is whatever its source gives, such as a
* provider id; its `mmsi` is an optional attribute ('' or absent when
* unknown), never its key, since vessels can share an MMSI. A source that
- * only has MMSIs uses the MMSI as the id.
+ * only has MMSIs uses the MMSI as the id. A vessel record's `virtual` is true
+ * for a virtual aid to navigation, a mark broadcast where nothing physical
+ * stands (AIS message 21's virtual flag), else false; any source may set it.
*
* A source may also declare a timeline (see readSnapshotTimeline): it can
* answer a snapshot at a given time, so the layer follows the world clock.
diff --git a/src/sources/live/contract.test.mjs b/src/sources/live/contract.test.mjs
index c789458ec..2c22012bf 100644
--- a/src/sources/live/contract.test.mjs
+++ b/src/sources/live/contract.test.mjs
@@ -221,6 +221,18 @@ test('vessel identity, opaque reference and heading/course remain distinct, unkn
assert.equal(row.altitudeDatum, 'sea-surface');
assert.equal(row.observedAtMs, now);
assert.equal('extra' in row, false);
+ // Only a source's own true marks a virtual aid to navigation.
+ assert.equal(row.virtual, false);
+ const base = { mmsi: '993672001', lat: 30, lon: -97 };
+ assert.equal(
+ normalizeVesselObservation({ ...base, virtual: true }).virtual,
+ true,
+ );
+ for (const virtual of ['true', 1, false, null])
+ assert.equal(
+ normalizeVesselObservation({ ...base, virtual }).virtual,
+ false,
+ );
assert.equal(
normalizeVesselObservation({ mmsi: 'x', lat: null, lon: null }),
null,
diff --git a/src/sources/live/vessels.js b/src/sources/live/vessels.js
index 3ea9c113f..d75291911 100644
--- a/src/sources/live/vessels.js
+++ b/src/sources/live/vessels.js
@@ -55,6 +55,8 @@ export function normalizeVesselObservation(row, reference = null, id = null) {
epoch(row.last_position_epoch, 1000) ??
epoch(Date.parse(row.last_position_UTC)),
altitudeDatum: 'sea-surface',
+ // A virtual aid to navigation: a mark broadcast with nothing there.
+ virtual: row.virtual === true,
};
}
diff --git a/src/sources/transitHistoryStore.js b/src/sources/transitHistoryStore.js
index cf82835c1..b53082e27 100644
--- a/src/sources/transitHistoryStore.js
+++ b/src/sources/transitHistoryStore.js
@@ -1,3 +1,4 @@
+import { transitModeFor } from '../data/transitFeeds.js';
import { validTransitIdentifier } from './transitHistory.js';
export { validTransitIdentifier } from './transitHistory.js';
/** Bounded, process-local operator position history. No upstream or scene access. */
@@ -328,12 +329,12 @@ export function createTransitHistory({
t > now + 10000
)
continue;
- const byVehicle = feed.vehicleMode?.(record.id);
- const mode =
- (byVehicle !== 'unknown' && byVehicle) ||
- feed.routeMode?.(record.routeId) ||
- feed.defaultMode ||
- 'unknown';
+ const mode = transitModeFor(
+ feed,
+ record.routeId,
+ record.id,
+ record.routeType,
+ );
const context = contextOf(record, mode);
if (!context) continue;
const key = `${feed.id}\u0000${record.id}`;
diff --git a/src/testSupport/railLayerHarness.mjs b/src/testSupport/railLayerHarness.mjs
index fc2d01a59..5fef479f7 100644
--- a/src/testSupport/railLayerHarness.mjs
+++ b/src/testSupport/railLayerHarness.mjs
@@ -9,6 +9,7 @@ import { eastNorthUp } from '../geo/frames.js';
import { scale } from '../geo/vector.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeDrawPort } from './fakeDrawPort.mjs';
+import { layerPlacement } from '../data/placementProvider.js';
import { CAMERA_DEBOUNCE_MS } from '../layers/rail/policy.js';
import { WORLD_FOCUS_FRAMING } from '../worldFocus.js';
import { publicRailCatalog } from '../data/railFeeds.js';
@@ -69,7 +70,8 @@ const headersOf = (values = {}) => ({
* catalog?: object[]|Promise|Function|false,
* ground?: object,
* stops?: object|null, scheduleStops?: boolean,
- * paths?: Record|null, fleet?: object|null}} [options]
+ * paths?: Record|null, fleet?: object|null,
+ * placement?: object|null}} [options]
* `ground`: a floor service in place of the always-cold stub; `catalog`:
* the server's feed catalog (it may list fewer feeds than are bundled; a
* promise answers when it settles, a function is called per request and
@@ -81,7 +83,8 @@ const headersOf = (values = {}) => ({
* failure status it answers with (404 for any other feed; without it the
* source has no path route at all); `fleet`: the fleet-model services
* (testSupport/fleetModelFakes.mjs), with a camera that looks straight
- * down for them (none by default: trains stay icons).
+ * down for them (none by default: trains stay icons); `placement`: a
+ * host-supplied placement provider (../data/placementProvider.js).
*/
/** The frame of an eye over `view`'s place looking straight down. */
function lookingDown(view) {
@@ -100,6 +103,7 @@ export function railLayerHarness(
scheduleStops = false,
paths = null,
fleet = null,
+ placement = null,
} = {},
) {
const T0 = RAIL_HARNESS_T0;
@@ -386,6 +390,7 @@ export function railLayerHarness(
warmGroundFloor() {},
},
...(fleet ? { fleet } : {}),
+ ...(placement ? { placement: layerPlacement(placement, 'rail') } : {}),
camera: {
framing: WORLD_FOCUS_FRAMING.train,
requestWorldFocus(detail) {
diff --git a/src/tools/queries/maritime.js b/src/tools/queries/maritime.js
index aeb90714f..439721c77 100644
--- a/src/tools/queries/maritime.js
+++ b/src/tools/queries/maritime.js
@@ -21,7 +21,10 @@ import {
thinEvenly,
} from '../results.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
-import { normalizeVesselType } from '../../data/vesselTypes.js';
+import {
+ isAidToNavigation,
+ normalizeVesselType,
+} from '../../data/vesselTypes.js';
const MMSI_SCHEMA = Object.freeze({
type: 'string',
@@ -116,7 +119,8 @@ export const vesselsInArea = defineTool({
title: 'Vessels in an area',
description:
'Ships currently reported by AIS inside an area, nearest the center ' +
- 'first, optionally filtered by vessel type. group_by counts every matched ' +
+ 'first, optionally filtered by vessel type. Buoys, beacons and other ' +
+ 'aids to navigation are not ships and are left out. group_by counts every matched ' +
'ship by type or destination, and stats summarizes their speed; both ' +
'cover all matches, not just the rows returned.',
inputSchema: {
@@ -152,6 +156,8 @@ export const vesselsInArea = defineTool({
const rows = snapshot.records
.filter(
(record) =>
+ // A buoy or beacon in the feed is not a ship to count.
+ !isAidToNavigation(record) &&
areaContains(area, { lat: record.latitude, lon: record.longitude }) &&
(!wanted ||
(vesselType(record.type) ?? '').toLowerCase().includes(wanted)),
diff --git a/src/tools/queries/maritime.test.mjs b/src/tools/queries/maritime.test.mjs
index fa835b5b7..5715a1e4b 100644
--- a/src/tools/queries/maritime.test.mjs
+++ b/src/tools/queries/maritime.test.mjs
@@ -467,3 +467,44 @@ test('vessels in an area can be counted by destination with a speed summary', as
speed_mps: { count: 2, min: 6.2, median: 6.2, mean: 6.2, max: 6.2 },
});
});
+
+test('vessels in an area leave out buoys and beacons', async () => {
+ const withAids = {
+ ...vessels(),
+ async getSnapshot() {
+ return {
+ records: [
+ ...records,
+ vessel('993672001', 37.8, -122.42, {
+ name: 'SF APPROACH N',
+ type: 'Cardinal Mark N',
+ speedMps: 0,
+ headingDeg: 135,
+ }),
+ vessel('993672002', 37.79, -122.43, { type: '' }),
+ ],
+ source: 'AISStream',
+ observedAtMs: Date.UTC(2026, 0, 1),
+ freshness: 'current',
+ };
+ },
+ };
+ const catalog = composeCatalog({
+ tools: coreTools,
+ services: { vessels: withAids },
+ });
+ const all = await catalog.call('vessels_in_area', {
+ area: bay,
+ group_by: 'type',
+ });
+ assert.equal(all.data.total, 2);
+ assert.equal(all.summary.split(' in ')[0], '2 vessels');
+ assert.deepEqual(all.data.rows.map((row) => row.mmsi).sort(), [
+ '366999712',
+ '538001234',
+ ]);
+ assert.equal(all.data.breakdown.unknown_count, 0);
+ assert.ok(
+ !all.data.breakdown.groups.some((group) => /mark/i.test(group.value)),
+ );
+});
diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js
index a754747e4..083e16648 100644
--- a/src/ui/applicationShell.js
+++ b/src/ui/applicationShell.js
@@ -71,6 +71,7 @@ import { useHudStore } from './stores/hud.js';
import { useDisplayStore } from './stores/display.js';
import { useLocaleStore } from './stores/locale.js';
import { useLocationStore } from './stores/location.js';
+import { installRailEdgeScroll } from './railEdgeScroll.js';
import { useCockpitStore } from './stores/cockpit.js';
import { useGlobeActionsStore } from './stores/globeActions.js';
import { useRecordingStore } from './stores/recording.js';
@@ -170,6 +171,8 @@ export class StyleManager extends ShellFacade {
});
// Vue views share this runtime and its stores; dispose unmounts them.
this._ui = createUiRuntime({ pinia: applicationPinia() });
+ // Scrolling at a screen edge steps through that side's rail panels.
+ this._removeRailEdgeScroll = installRailEdgeScroll();
this._feedback = new ShellFeedback({
readLayers: () => withPlacePacks(this._dataManager?.getAll?.() || []),
});
@@ -1870,6 +1873,7 @@ export class StyleManager extends ShellFacade {
const { destroyTrackedReadout, destroyWorldOverlay, destroyDetection } =
this.services;
if (this._disposed) return;
+ this._removeRailEdgeScroll?.();
this._shareRestoration.destroy();
this._feedback.clearLoadingStatus();
this._disposed = true;
diff --git a/src/ui/kit/UiPanel.vue b/src/ui/kit/UiPanel.vue
index 5421fc699..f16adc385 100644
--- a/src/ui/kit/UiPanel.vue
+++ b/src/ui/kit/UiPanel.vue
@@ -1,5 +1,6 @@
+
+
+
+ {{ icon }}
+
+
diff --git a/src/ui/leftPanelRail.js b/src/ui/leftPanelRail.js
index ca11a8149..c5c65378b 100644
--- a/src/ui/leftPanelRail.js
+++ b/src/ui/leftPanelRail.js
@@ -60,6 +60,7 @@ export function layoutLeftPanelRail({
stack.style.removeProperty('--left-stack-safe-bottom');
stack.style.removeProperty('--left-stack-centered-height');
stack.style.removeProperty('--panel-rail-offset');
+ stack.style.removeProperty('--panel-rail-lift');
stack.classList.remove('layout-exclusive');
stack.dataset.layoutMode = 'mobile';
settleSideAccordion({ panels, enabled: false, onCollapse });
@@ -282,10 +283,19 @@ export function layoutLeftPanelRail({
getComputedStyle(stack)
.getPropertyValue?.('--panel-stack-top-pinned')
?.trim() === '1';
- const railOffset = `${(topPinned ? 0 : safeTop - layoutTop).toFixed(1)}px`;
+ // The stack itself rises by the lift below, by a different amount for a
+ // tall panel than at rest; the rail takes up the difference.
+ const lift = (top) => Math.min(0, obstacleSafeTop - top);
+ const railOffset = `${(topPinned ? 0 : safeTop + lift(safeTop) - layoutTop - lift(layoutTop)).toFixed(1)}px`;
if (stack.style.getPropertyValue('--panel-rail-offset') !== railOffset) {
stack.style.setProperty('--panel-rail-offset', railOffset);
}
+ // How far the column can rise before it meets the HUD readout, so the rail
+ // and any open panel sit just under it, whether or not a panel is open.
+ const railLift = `${(topPinned ? 0 : lift(layoutTop)).toFixed(1)}px`;
+ if (stack.style.getPropertyValue('--panel-rail-lift') !== railLift) {
+ stack.style.setProperty('--panel-rail-lift', railLift);
+ }
stack.style.removeProperty('--left-stack-centered-height');
for (const panel of panels)
panel.style.removeProperty('--left-panel-allocated-height');
diff --git a/src/ui/mobileShell.js b/src/ui/mobileShell.js
index 65673cd55..7570e2d17 100644
--- a/src/ui/mobileShell.js
+++ b/src/ui/mobileShell.js
@@ -368,7 +368,8 @@ export function initMobileShell({
: sheet === 'search'
? [dock]
: sheet === 'more'
- ? [element('right-context-rail'), dock]
+ ? // Visual lives in the left stack; the dock holds the presets.
+ [element('left-panel-stack'), dock]
: [element('right-context-rail')];
return roots.find((root) => root?.contains(target));
};
diff --git a/src/ui/mobileShell.test.mjs b/src/ui/mobileShell.test.mjs
index 3627c4a62..aff246987 100644
--- a/src/ui/mobileShell.test.mjs
+++ b/src/ui/mobileShell.test.mjs
@@ -624,7 +624,7 @@ test('the phone shell keeps the required attribution visible', () => {
);
const openDock = rule('body.mobile-shell[data-mobile-sheet] #command-dock');
const railSheet = rule(
- "body.mobile-shell[data-mobile-sheet='more'] #right-context-rail",
+ "body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack",
);
assert.ok(z(sheetCredit) > z(openDock));
assert.ok(z(sheetCredit) > z(railSheet));
diff --git a/src/ui/panelChromeButtons.test.mjs b/src/ui/panelChromeButtons.test.mjs
index 543a77730..ae3a212c0 100644
--- a/src/ui/panelChromeButtons.test.mjs
+++ b/src/ui/panelChromeButtons.test.mjs
@@ -141,6 +141,7 @@ test("UiPanel draws Core's panel markup and asks for the other state", async (t)
'demo-badge',
'panel-divider',
'demo-action',
+ 'panel-edge-btn',
'panel-collapse-btn',
],
);
diff --git a/src/ui/panelEdge.js b/src/ui/panelEdge.js
new file mode 100644
index 000000000..85b9d353f
--- /dev/null
+++ b/src/ui/panelEdge.js
@@ -0,0 +1,42 @@
+import { ref } from 'vue';
+
+// Panels can slide over their rail to the screen edge, one setting per side:
+// the left column moves onto the left rail, the right column onto the right
+// rail. Each panel header has the switch (UiPanelEdge); the choice is kept
+// for the next visit and shows as a body class the stylesheet reads.
+const KEY = 'gev.panelEdge';
+function read() {
+ try {
+ const saved = JSON.parse(globalThis.localStorage?.getItem(KEY) || '{}');
+ return { left: saved.left === true, right: saved.right === true };
+ } catch {
+ return { left: false, right: false };
+ }
+}
+
+export const panelEdge = ref(read());
+
+function apply() {
+ const body = globalThis.document?.body;
+ if (!body) return;
+ body.classList.toggle('panels-edge-left', panelEdge.value.left);
+ body.classList.toggle('panels-edge-right', panelEdge.value.right);
+}
+apply();
+
+/** Which side a panel element sits on, from the column it is in. */
+export function panelSide(element) {
+ return element?.closest?.('#right-context-rail, #cockpit-utility-controls')
+ ? 'right'
+ : 'left';
+}
+
+export function togglePanelEdge(side) {
+ panelEdge.value = { ...panelEdge.value, [side]: !panelEdge.value[side] };
+ try {
+ globalThis.localStorage?.setItem(KEY, JSON.stringify(panelEdge.value));
+ } catch {
+ // Without storage the choice lasts for this visit.
+ }
+ apply();
+}
diff --git a/src/ui/panelLayoutController.js b/src/ui/panelLayoutController.js
index a3f3eae52..abcd4dff0 100644
--- a/src/ui/panelLayoutController.js
+++ b/src/ui/panelLayoutController.js
@@ -191,7 +191,11 @@ export class PanelLayoutController {
const stack = this._rightPanelStack;
if (!stack || !this._ppToggles) return;
- stack.prepend(this._ppToggles);
+ // Visual (presets and display settings) is the last panel of the left
+ // column, after the other tools, and opens from the left rail like them.
+ if (typeof this._leftPanelStack?.append === 'function')
+ this._leftPanelStack.append(this._ppToggles);
+ else stack.prepend(this._ppToggles);
const globalContextPanel = document.getElementById('global-context-panel');
for (const panel of [
this._cctvPanel,
@@ -203,6 +207,9 @@ export class PanelLayoutController {
if (!panel) continue;
stack.insertBefore(panel, globalContextPanel);
}
+ // Context leads the right column: it is the panel for whatever is picked,
+ // and the camera panels follow it.
+ if (globalContextPanel) stack.prepend(globalContextPanel);
if (typeof ResizeObserver !== 'undefined') {
this._rightStackResizeObserver = new ResizeObserver(() => {
this._scheduleRightPanelLayout();
diff --git a/src/ui/panelMeasurement.js b/src/ui/panelMeasurement.js
index dcd9de464..86be6f95c 100644
--- a/src/ui/panelMeasurement.js
+++ b/src/ui/panelMeasurement.js
@@ -6,9 +6,20 @@
* @returns {number} Natural height in CSS pixels.
*/
export function measurePanelNaturalHeight(panel, getComputedStyle) {
- const inner = [...panel.children].find(
+ const content = [...panel.children].filter(
(child) => !child.classList.contains('panel-glow'),
);
+ // A panel built as a header row and a body (Visual) scrolls as a whole, so
+ // its full scroll height is its natural height.
+ if (content.length > 1) {
+ const panelStyle = getComputedStyle(panel);
+ return Math.ceil(
+ panel.scrollHeight +
+ (parseFloat(panelStyle.borderTopWidth) || 0) +
+ (parseFloat(panelStyle.borderBottomWidth) || 0),
+ );
+ }
+ const inner = content[0];
if (!inner)
return Math.ceil(
panel.scrollHeight || panel.getBoundingClientRect().height,
diff --git a/src/ui/panelRailCatalog.js b/src/ui/panelRailCatalog.js
index dbda77dcd..6e0b0a876 100644
--- a/src/ui/panelRailCatalog.js
+++ b/src/ui/panelRailCatalog.js
@@ -19,7 +19,7 @@ export const PANEL_RAIL_ITEMS = Object.freeze({
},
'utilities-panel': { icon: 'handyman', label: msg('UTILITIES') },
'scene-panel': { icon: 'movie', label: msg('AUTHORING') },
- 'pp-toggles': { icon: 'tune', label: msg('DISPLAY') },
+ 'pp-toggles': { icon: 'palette', label: msg('VISUAL') },
'cctv-panel': { icon: 'videocam', label: msg('CCTV') },
'weather-panel': { icon: 'partly_cloudy_day', label: msg('WEATHER') },
'news-panel': { icon: 'public', label: msg('NEWS') },
diff --git a/src/ui/panelRails.test.mjs b/src/ui/panelRails.test.mjs
index 40c2be20b..ce1c82446 100644
--- a/src/ui/panelRails.test.mjs
+++ b/src/ui/panelRails.test.mjs
@@ -359,14 +359,23 @@ test('right rail aligns to the left rail buttons while the left stack is offset'
assert.equal(f.stack.dataset.safeTop, '286.7');
});
-test('left rail buttons hold still while a tall panel moves the stack', () => {
+test('left rail buttons hold still whether the open panel is short or tall', () => {
+ // Where the rail sits: the stack's top, the stack's rise, and the rail's
+ // own offset inside the stack.
+ const railTop = (stack) =>
+ (parseFloat(stack.style.getPropertyValue('--left-stack-safe-top')) * 900) /
+ 100 +
+ parseFloat(stack.style.getPropertyValue('--panel-rail-lift')) +
+ parseFloat(stack.style.getPropertyValue('--panel-rail-offset'));
+ const short = fixture('left');
+ short.expand(short.first, 250);
+ short.run();
const f = fixture('left');
f.expand(f.first, 900);
f.run();
assert.equal(f.stack.dataset.layoutMode, 'focus');
- assert.ok(
- parseFloat(f.stack.style.getPropertyValue('--panel-rail-offset')) > 0,
- );
+ assert.notEqual(short.stack.dataset.layoutMode, 'focus');
+ assert.ok(Math.abs(railTop(f.stack) - railTop(short.stack)) < 0.2);
// A theme that pins the stack's top (Cyber) leaves nothing to offset.
f.stack.computed.getPropertyValue = (name) =>
@@ -447,13 +456,17 @@ test('natural height includes visible content, margins and wrapper chrome, exclu
// Outside measurement, CCTV is 391 px in focus and 629 px in normal mode;
// Removing only the allocation leaves focus CSS active: its next reading is
// 422 px, so the old decision exits focus and then re-enters on the 629 px read.
-function thrashingRightRail({ focused = false, weatherOpen = false } = {}) {
+function thrashingRightRail({
+ focused = false,
+ weatherOpen = false,
+ tallId = 'cctv-panel',
+} = {}) {
const f = fixture('right');
f.options.windowRef.innerHeight = 920;
f.options.leftStack.rect.top = 439.6;
f.stack.computed.rowGap = '8px';
const display = element('pp-toggles', { collapsed: true });
- const cctv = element('cctv-panel', { height: 629 });
+ const cctv = element(tallId, { height: 629 });
const weather = element('weather-panel', {
height: 444,
collapsed: !weatherOpen,
@@ -524,8 +537,10 @@ for (const focused of [false, true]) {
});
}
+// The hysteresis applies to panels that size to their content; CCTV and
+// Context take the column's full height whenever they are open.
test('right rail keeps focus through 30 px content growth inside the hysteresis band', () => {
- const f = thrashingRightRail();
+ const f = thrashingRightRail({ tallId: 'news-panel' });
f.run();
// Header + gap contribute 52 px: need moves 420 -> 450 -> 420.
for (const height of [368, 398, 368, 398, 368]) {
@@ -542,7 +557,7 @@ test('right rail keeps focus through 30 px content growth inside the hysteresis
});
test('right rail enters focus only above available height and leaves below the full deadband', () => {
- const f = thrashingRightRail();
+ const f = thrashingRightRail({ tallId: 'news-panel' });
f.options.windowRef.innerHeight = 1000;
f.options.leftStack.rect.top = 500;
f.cctv.intrinsicHeight = 408; // Need equals available (460 px).
@@ -559,6 +574,16 @@ test('right rail enters focus only above available height and leaves below the f
assert.equal(f.stack.classList.contains('layout-focus'), false);
});
+test('an open CCTV panel takes the full column however short its content', () => {
+ const f = thrashingRightRail();
+ f.cctv.intrinsicHeight = 200;
+ f.run();
+ assert.equal(f.stack.classList.contains('layout-focus'), true);
+ f.cctv.classList.add('collapsed');
+ f.run();
+ assert.equal(f.stack.classList.contains('layout-focus'), false);
+});
+
test('right rail settles a second tall panel through the accordion in one pass', () => {
const f = thrashingRightRail({ weatherOpen: true });
const modes = [];
diff --git a/src/ui/railEdgeScroll.js b/src/ui/railEdgeScroll.js
new file mode 100644
index 000000000..4e3d9b0a4
--- /dev/null
+++ b/src/ui/railEdgeScroll.js
@@ -0,0 +1,393 @@
+// Edge scrolling for the side rails. While the pointer is in a screen edge's
+// strip (from the edge to just past its rail), that rail's border lights up,
+// and the scroll wheel steps to the next or previous panel on that side
+// instead of zooming the globe, wrapping round at either end. The open item's
+// highlight slides between items however the panel changes, and a panel
+// opened by the wheel slides in from the direction of travel.
+
+/** How far past the rail the strip reaches, in pixels. */
+const STRIP_MARGIN = 16;
+/** Wheel travel (pixels) that counts as one step. */
+const STEP_DELTA = 40;
+/**
+ * A pause this long (ms) with no wheel events ends a scroll gesture. One
+ * gesture moves one step, however long it runs, trackpad coasting included.
+ */
+const GESTURE_GAP_MS = 180;
+/** After a step, how long (ms) before the same motion can count as a new flick. */
+const STEP_COOLDOWN_MS = 220;
+/**
+ * The least time (ms) between two steps, whatever the wheel does. A motion
+ * that would step sooner waits and steps once the gap has passed (one step
+ * held at most), so panels never switch back to back and no step is lost.
+ */
+const STEP_GAP_MS = 500;
+/** A wheel event this large (pixels) is a mouse wheel notch, not a trackpad. */
+const NOTCH_DELTA = 100;
+/** The widest the strip gets, measured from the screen edge, whatever shape the rail takes. */
+const STRIP_MAX = 84;
+/**
+ * After a step, how long (ms) the rest of that gesture is still swallowed once
+ * the pointer has left the strip, so trackpad coasting does not go on to zoom
+ * the globe. Past it, the wheel belongs to whatever is under the pointer.
+ */
+const COAST_MAX_MS = 800;
+/** Pixels per wheel line, for mice that report lines rather than pixels. */
+const LINE_PX = 16;
+/**
+ * Things in the strip that keep their own pointer and wheel behaviour: any
+ * control, and every panel in either side's stack (a panel scrolls itself).
+ */
+const OWN_CONTROLS =
+ 'a, button, input, select, textarea, dialog, [role="dialog"], .ui-panel, #left-panel-stack > :not(.gev-panel-rail), #right-context-rail > :not(.gev-panel-rail), #first-run-launcher, #cesium-credits, #world-timeline';
+
+/**
+ * @param {Document} [doc]
+ * @returns {() => void} removes the listeners and observers
+ */
+export function installRailEdgeScroll(doc = globalThis.document) {
+ const win = doc?.defaultView;
+ if (!doc || !win) return () => {};
+ const coarse = win.matchMedia?.('(pointer: coarse)');
+
+ let hot = null;
+ let travel = 0;
+ let lastWheel = 0;
+ let lastSpeed = 0;
+ let stepped = false;
+ /** When the last step was taken, the fastest the gesture has been, and whether it has slowed since. */
+ let steppedAt = 0;
+ /** A step waiting for the gap to pass, if any. */
+ let heldStep = 0;
+ let peakSpeed = 0;
+ let slowed = false;
+ let frame = 0;
+ /** Set once removed, so frames already queued do nothing. */
+ let removed = false;
+
+ // Clean view and recording hide the rails with visibility and opacity,
+ // which keep their boxes, so a box alone does not mean the rail shows.
+ const showing = (node) =>
+ node.getBoundingClientRect().width > 0 &&
+ (typeof node.checkVisibility !== 'function' ||
+ node.checkVisibility({
+ visibilityProperty: true,
+ opacityProperty: true,
+ }));
+
+ // Which screen edge a rail is on comes from where it is, not its name: in a
+ // right-to-left language the left stack sits on the right.
+ const rails = () =>
+ ['left', 'right']
+ .map((name) => doc.querySelector(`.ui-rail--${name}`))
+ .filter((rail) => rail && showing(rail))
+ .map((rail) => {
+ const box = rail.getBoundingClientRect();
+ const middle = doc.documentElement.clientWidth / 2;
+ return {
+ side: box.left + box.width / 2 < middle ? 'left' : 'right',
+ rail,
+ };
+ });
+
+ const items = (rail) =>
+ // Only items that show: a theme or mode may hide some, and the wheel must
+ // not open those.
+ [...rail.querySelectorAll('.ui-rail__item')].filter(
+ (item) => !item.disabled && showing(item),
+ );
+
+ // ── The sliding highlight ──
+ // Each rail draws it as a ::before under its items, placed by custom
+ // properties; the open item's own background steps aside while it shows.
+ // Vue rewrites a rail's class list when it folds its labels, so whether the
+ // highlight is showing is kept here, and the classes are put back each time.
+ const gliding = new WeakSet();
+
+ function glide(rail) {
+ if (removed) return;
+ rail.classList.toggle('ui-rail--edge-hot', rail === hot);
+ const on = rail.querySelector('.ui-rail__item[aria-pressed="true"]');
+ if (!on?.offsetWidth) {
+ gliding.delete(rail);
+ rail.classList.remove('ui-rail--glide');
+ return;
+ }
+ const railBox = rail.getBoundingClientRect();
+ const box = on.getBoundingClientRect();
+ const shown = gliding.has(rail);
+ // A rail opening its first panel folds its labelled pills to icons, the
+ // buttons shrinking over a few frames; the highlight waits until the open
+ // button is an icon again (square) rather than fading in at a pill's
+ // width and then shrinking.
+ if (
+ !shown &&
+ (rail.classList.contains('ui-rail--expanded') ||
+ box.width > box.height + 2)
+ )
+ return;
+ // Appearing from nothing: jump into place, then fade in.
+ rail.classList.toggle('ui-rail--glide-jump', !shown);
+ rail.style.setProperty(
+ '--rail-glide-x',
+ `${box.left - railBox.left - rail.clientLeft}px`,
+ );
+ rail.style.setProperty(
+ '--rail-glide-y',
+ `${box.top - railBox.top - rail.clientTop}px`,
+ );
+ rail.style.setProperty('--rail-glide-w', `${box.width}px`);
+ rail.style.setProperty('--rail-glide-h', `${box.height}px`);
+ rail.classList.add('ui-rail--glide');
+ gliding.add(rail);
+ if (!shown)
+ win.requestAnimationFrame(() =>
+ rail.classList.remove('ui-rail--glide-jump'),
+ );
+ }
+
+ // Follow the rails for a few frames after any change, as their items
+ // resize while labels fold away.
+ function follow(frames = 24) {
+ win.cancelAnimationFrame(frame);
+ let left = frames;
+ const tick = () => {
+ if (removed) return;
+ watchRails();
+ doc.querySelectorAll('.ui-rail').forEach(glide);
+ if ((left -= 1) > 0) frame = win.requestAnimationFrame(tick);
+ };
+ tick();
+ }
+
+ const observer =
+ typeof win.MutationObserver === 'function'
+ ? new win.MutationObserver((records) => {
+ // A rail item opened or closed. Nothing here writes aria-pressed,
+ // and the work waits for the next frame, so this never feeds itself.
+ if (
+ records.some((record) =>
+ record.target.classList?.contains('ui-rail__item'),
+ )
+ )
+ win.requestAnimationFrame(() => follow());
+ })
+ : null;
+ observer?.observe(doc.body, {
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['aria-pressed'],
+ });
+
+ // A rail also changes shape with nothing pressed or released: hidden and
+ // shown again (Context docked and undocked), or turned from a column to a
+ // row (panels moved to the screen edge). Its highlight is placed again
+ // whenever its size changes, so it is never left where an icon was.
+ const sized =
+ typeof win.ResizeObserver === 'function'
+ ? new win.ResizeObserver(() => follow(2))
+ : null;
+ const watched = new WeakSet();
+ const watchRails = () => {
+ if (!sized) return;
+ doc.querySelectorAll('.ui-rail').forEach((rail) => {
+ if (watched.has(rail)) return;
+ watched.add(rail);
+ sized.observe(rail);
+ });
+ };
+ watchRails();
+
+ // ── The edge strip ──
+ /** The rail whose strip holds the point, unless a control there owns it. */
+ function railAt(x, target) {
+ if (doc.body.classList.contains('mobile-shell') || coarse?.matches)
+ return null;
+ for (const { side, rail } of rails()) {
+ const box = rail.getBoundingClientRect();
+ // From the screen edge to just past the rail, but never wider than a
+ // rail's own column: a rail laid out as a row across the top of its
+ // panels would otherwise claim most of the panel's width.
+ const width = doc.documentElement.clientWidth;
+ const inStrip =
+ side === 'left'
+ ? x <= Math.min(box.right + STRIP_MARGIN, STRIP_MAX)
+ : x >= Math.max(box.left - STRIP_MARGIN, width - STRIP_MAX);
+ if (!inStrip) continue;
+ if (rail.contains(target)) return rail;
+ if (target?.closest?.(OWN_CONTROLS)) return null;
+ return rail;
+ }
+ return null;
+ }
+
+ function setHot(rail) {
+ if (rail === hot) return;
+ // A held step belongs to the strip it was made in; leaving drops it, so
+ // coming back later does not set it off with no wheel turned.
+ if (heldStep) {
+ win.clearTimeout(heldStep);
+ heldStep = 0;
+ }
+ hot?.classList.remove('ui-rail--edge-hot');
+ hot = rail;
+ travel = 0;
+ hot?.classList.add('ui-rail--edge-hot');
+ follow(2);
+ }
+
+ function onMove(event) {
+ setHot(railAt(event.clientX, event.target));
+ }
+
+ function onLeave(event) {
+ if (!event.relatedTarget) setHot(null);
+ }
+
+ function step(direction) {
+ const list = items(hot);
+ if (!list.length) return;
+ const current = list.findIndex(
+ (item) => item.getAttribute('aria-pressed') === 'true',
+ );
+ // Past either end, carry on from the other.
+ const nextIndex =
+ current < 0
+ ? direction > 0
+ ? 0
+ : list.length - 1
+ : (current + direction + list.length) % list.length;
+ if (nextIndex === current) return;
+ const target = list[nextIndex];
+ target.click();
+ const panel = doc.getElementById(target.dataset.railItem);
+ if (panel) {
+ panel.classList.remove('rail-switch-down', 'rail-switch-up');
+ void panel.offsetWidth;
+ panel.classList.add(
+ direction > 0 ? 'rail-switch-down' : 'rail-switch-up',
+ );
+ // The classes come off when the slide ends, or after a moment where
+ // there is no slide to end (reduced motion).
+ const settle = () => {
+ win.clearTimeout(timer);
+ panel.removeEventListener('animationend', settle);
+ panel.classList.remove('rail-switch-down', 'rail-switch-up');
+ };
+ const timer = win.setTimeout(settle, 600);
+ panel.addEventListener('animationend', settle);
+ }
+ follow();
+ }
+
+ function onWheel(event) {
+ // Pinch zoom, and sideways or empty moves (trackpads send them mid-swipe),
+ // are left alone: they neither step nor turn a gesture round.
+ if (event.ctrlKey || !event.deltaY) return;
+ const now = win.performance?.now?.() ?? Date.now();
+ const inGesture = now - lastWheel <= GESTURE_GAP_MS;
+ // Recheck: the pointer may not have moved since the panels changed.
+ const stillHot =
+ Boolean(hot) && railAt(event.clientX, event.target) === hot;
+ if (!stillHot) {
+ setHot(null);
+ // The rest of a gesture that has already stepped is used up here, so
+ // its coasting does not go on to zoom the globe or scroll what opened
+ // under the pointer.
+ if (stepped && inGesture && now - steppedAt <= COAST_MAX_MS) {
+ event.preventDefault();
+ event.stopPropagation();
+ lastWheel = now;
+ }
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ // Line- and page-based wheels report far smaller numbers than pixels.
+ const deltaY =
+ event.deltaMode === 1
+ ? event.deltaY * LINE_PX
+ : event.deltaMode === 2
+ ? event.deltaY * win.innerHeight
+ : event.deltaY;
+ const speed = Math.abs(deltaY);
+ // A new gesture: after a pause, after turning round, a mouse wheel notch,
+ // or a fresh flick while the last one is still coasting. A flick is a
+ // rise in speed after the gesture has clearly slowed, and not in the
+ // moment after a step: a swipe is still speeding up when it first steps.
+ const turned = travel && Math.sign(deltaY) !== Math.sign(travel);
+ const cooled = now - steppedAt > STEP_COOLDOWN_MS;
+ // Every event from a line- or page-based wheel is a notch.
+ const notch =
+ stepped && cooled && (speed >= NOTCH_DELTA || event.deltaMode > 0);
+ const flick =
+ stepped && cooled && slowed && speed > Math.max(8, lastSpeed * 1.8);
+ if (!inGesture || turned || notch || flick) {
+ // A held step belongs to the motion it came from; a reversal or a new
+ // flick replaces it rather than queueing behind it.
+ if (turned && heldStep) {
+ win.clearTimeout(heldStep);
+ heldStep = 0;
+ }
+ travel = 0;
+ stepped = false;
+ peakSpeed = 0;
+ slowed = false;
+ }
+ lastWheel = now;
+ lastSpeed = speed;
+ peakSpeed = Math.max(peakSpeed, speed);
+ if (stepped) {
+ if (speed < peakSpeed * 0.5) slowed = true;
+ return;
+ }
+ travel += deltaY;
+ if (Math.abs(travel) < STEP_DELTA) return;
+ stepped = true;
+ const direction = Math.sign(travel);
+ const wait = STEP_GAP_MS - (now - steppedAt);
+ if (wait <= 0) {
+ steppedAt = now;
+ step(direction);
+ return;
+ }
+ // Too soon after the last step: hold this one until the gap has passed.
+ if (heldStep) return;
+ const heldRail = hot;
+ heldStep = win.setTimeout(() => {
+ heldStep = 0;
+ // The pointer may have left the strip, or moved to the other rail,
+ // meanwhile; then nothing steps.
+ if (!hot || hot !== heldRail) return;
+ steppedAt = win.performance?.now?.() ?? Date.now();
+ step(direction);
+ }, wait);
+ }
+
+ const onResize = () => follow(2);
+ doc.addEventListener('pointermove', onMove, { passive: true });
+ doc.addEventListener('pointerout', onLeave, { passive: true });
+ win.addEventListener('wheel', onWheel, { capture: true, passive: false });
+ win.addEventListener('resize', onResize, { passive: true });
+ follow();
+
+ return () => {
+ removed = true;
+ win.clearTimeout(heldStep);
+ setHot(null);
+ observer?.disconnect();
+ sized?.disconnect();
+ win.cancelAnimationFrame(frame);
+ doc.removeEventListener('pointermove', onMove);
+ doc.removeEventListener('pointerout', onLeave);
+ win.removeEventListener('wheel', onWheel, { capture: true });
+ win.removeEventListener('resize', onResize);
+ doc.querySelectorAll('.ui-rail').forEach((rail) => {
+ rail.classList.remove(
+ 'ui-rail--glide',
+ 'ui-rail--glide-jump',
+ 'ui-rail--edge-hot',
+ );
+ });
+ };
+}
diff --git a/src/ui/railEdgeScroll.test.mjs b/src/ui/railEdgeScroll.test.mjs
new file mode 100644
index 000000000..a16964ebe
--- /dev/null
+++ b/src/ui/railEdgeScroll.test.mjs
@@ -0,0 +1,177 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Window } from 'happy-dom';
+import { installRailEdgeScroll } from './railEdgeScroll.js';
+
+// A page with a left and a right rail of three items each, laid out by hand:
+// happy-dom does no layout, so boxes and the clock are stubbed.
+function page({ rtl = false } = {}) {
+ const window = new Window({ width: 1600, height: 900 });
+ const doc = window.document;
+ let now = 1000;
+ const timers = new Map();
+ let nextTimer = 1;
+ window.performance.now = () => now;
+ window.setTimeout = (fn, ms) => {
+ const id = nextTimer++;
+ timers.set(id, { fn, at: now + ms });
+ return id;
+ };
+ window.clearTimeout = (id) => timers.delete(id);
+ window.requestAnimationFrame = () => 0;
+ window.cancelAnimationFrame = () => {};
+ Object.defineProperty(doc.documentElement, 'clientWidth', { value: 1600 });
+ const box = (el, left, top, width, height) => {
+ el.getBoundingClientRect = () => ({
+ left,
+ top,
+ width,
+ height,
+ right: left + width,
+ bottom: top + height,
+ });
+ Object.defineProperty(el, 'offsetWidth', { get: () => width });
+ };
+ const clicks = [];
+ const rail = (name, left) => {
+ const el = doc.createElement('div');
+ el.className = `ui-rail ui-rail--${name}`;
+ box(el, left, 200, 40, 120);
+ for (let i = 0; i < 3; i++) {
+ const item = doc.createElement('button');
+ item.className = 'ui-rail__item';
+ item.dataset.railItem = `${name}-${i}`;
+ item.setAttribute('aria-pressed', i === 0 ? 'true' : 'false');
+ box(item, left + 4, 204 + i * 40, 32, 32);
+ item.addEventListener('click', () => {
+ clicks.push(item.dataset.railItem);
+ for (const other of el.children)
+ other.setAttribute('aria-pressed', String(other === item));
+ });
+ el.append(item);
+ }
+ doc.body.append(el);
+ return el;
+ };
+ // In a right-to-left language the left stack's rail is on the right edge.
+ const left = rail('left', rtl ? 1550 : 10);
+ const right = rail('right', rtl ? 10 : 1550);
+ const remove = installRailEdgeScroll(doc);
+ const wheel = (x, deltaY, { deltaMode = 0, target = doc.body } = {}) => {
+ // happy-dom leaves clientX off these events, so it is set by hand.
+ const at = (event) => Object.defineProperty(event, 'clientX', { value: x });
+ target.dispatchEvent(
+ at(new window.PointerEvent('pointermove', { bubbles: true })),
+ );
+ const event = at(
+ new window.WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY,
+ deltaMode,
+ }),
+ );
+ target.dispatchEvent(event);
+ return event;
+ };
+ const advance = (ms) => {
+ now += ms;
+ for (const [id, timer] of [...timers]) {
+ if (timer.at > now) continue;
+ timers.delete(id);
+ timer.fn();
+ }
+ };
+ return { window, doc, left, right, clicks, wheel, advance, remove };
+}
+
+test('a wheel in the left strip steps that rail and keeps the globe from zooming', () => {
+ const p = page();
+ const event = p.wheel(20, 120);
+ assert.equal(event.defaultPrevented, true);
+ assert.deepEqual(p.clicks, ['left-1']);
+ p.remove();
+});
+
+test('a line-based mouse wheel steps one panel per notch', () => {
+ const p = page();
+ p.wheel(20, 3, { deltaMode: 1 });
+ p.advance(600);
+ p.wheel(20, 3, { deltaMode: 1 });
+ assert.deepEqual(p.clicks, ['left-1', 'left-2']);
+ p.remove();
+});
+
+test('a rail hidden by clean view or recording leaves the wheel to the globe', () => {
+ const p = page();
+ p.left.checkVisibility = () => false;
+ const event = p.wheel(20, 120);
+ assert.equal(event.defaultPrevented, false);
+ assert.deepEqual(p.clicks, []);
+ p.remove();
+});
+
+test('right to left: the wheel at each screen edge steps the rail on that edge', () => {
+ const p = page({ rtl: true });
+ p.wheel(1580, 120);
+ p.advance(600);
+ p.wheel(20, 120);
+ assert.deepEqual(p.clicks, ['left-1', 'right-1']);
+ p.remove();
+});
+
+test('after a step, the wheel goes back to the page once the coasting is over', () => {
+ const p = page();
+ p.wheel(20, 120);
+ // The pointer moves off the strip while the gesture still coasts.
+ let event;
+ for (let i = 0; i < 20; i++) {
+ p.advance(100);
+ event = p.wheel(800, 30);
+ }
+ assert.equal(event.defaultPrevented, false);
+ assert.deepEqual(p.clicks, ['left-1']);
+ p.remove();
+});
+
+test('a held step is dropped when the pointer leaves the strip, even if it comes back', () => {
+ const p = page();
+ p.wheel(20, 120);
+ p.advance(250);
+ p.wheel(20, -120); // turns round: a second step, held for the gap
+ p.wheel(800, 0); // leaves the strip
+ p.wheel(20, 0); // and returns before the gap ends
+ p.advance(600);
+ assert.deepEqual(p.clicks, ['left-1']);
+ p.remove();
+});
+
+test('removing it stops edge scrolling', () => {
+ const p = page();
+ p.remove();
+ const event = p.wheel(20, 120);
+ assert.equal(event.defaultPrevented, false);
+ assert.deepEqual(p.clicks, []);
+});
+
+test('a sideways move mid-swipe neither turns the gesture round nor steps again', () => {
+ const p = page();
+ p.wheel(20, 60);
+ p.advance(50);
+ const sideways = p.wheel(20, 0);
+ p.advance(50);
+ p.wheel(20, 40); // the same swipe coasting on
+ assert.equal(sideways.defaultPrevented, false);
+ assert.deepEqual(p.clicks, ['left-1']);
+ p.remove();
+});
+
+test('an open dialog near the edge keeps its own wheel', () => {
+ const p = page();
+ const dialog = p.doc.createElement('dialog');
+ p.doc.body.append(dialog);
+ const event = p.wheel(20, 120, { target: dialog });
+ assert.equal(event.defaultPrevented, false);
+ assert.deepEqual(p.clicks, []);
+ p.remove();
+});
diff --git a/src/ui/rightPanelRail.js b/src/ui/rightPanelRail.js
index 44043fb01..352ebda94 100644
--- a/src/ui/rightPanelRail.js
+++ b/src/ui/rightPanelRail.js
@@ -31,6 +31,20 @@ function settledLeftRailTop(leftStack, viewportHeight, getComputedStyle) {
return Number.isFinite(targetPct) ? (targetPct * viewportHeight) / 100 : top;
}
+/**
+ * An element's CSS `top` in pixels where it will settle: the end of a running
+ * `top` transition, else its computed value. NaN when it cannot be read.
+ */
+function settledCssTop(element, getComputedStyle) {
+ if (!element) return NaN;
+ const transition = element
+ .getAnimations?.()
+ .find((animation) => animation.transitionProperty === 'top');
+ const target = parseFloat(transition?.effect?.getKeyframes?.().at(-1)?.top);
+ if (Number.isFinite(target)) return target;
+ return parseFloat(getComputedStyle(element).top);
+}
+
/**
* Measure and place the right panel rail for one synchronous layout pass.
* The caller owns scheduling, obstacle selection, disclosure preferences and
@@ -126,9 +140,20 @@ export function layoutRightPanelRail({
viewportHeight,
getComputedStyle,
);
- // Align with the left rail's buttons, which hold still while its stack moves.
- const leftRailOffset =
- parseFloat(leftStack?.style.getPropertyValue('--panel-rail-offset')) || 0;
+ // Align with the left rail's buttons, which hold still while its stack moves:
+ // the rail's own settled `top` inside the stack, so every left layout is
+ // followed (a layout may pin the rail to the stack's top whatever the
+ // offset says). The stack's offset is the fallback when there is no rail.
+ const leftRailInset = settledCssTop(
+ leftStack?.querySelector?.('.gev-panel-rail') ?? null,
+ getComputedStyle,
+ );
+ // A rail that sits lower in its stack has only made room above itself for
+ // the open panel's own icon, which stays at the stack's top: the column's
+ // top has not moved, so that inset is not followed.
+ const leftRailOffset = Number.isFinite(leftRailInset)
+ ? Math.min(0, leftRailInset)
+ : parseFloat(leftStack?.style.getPropertyValue('--panel-rail-offset')) || 0;
const alignedTop = Number.isFinite(leftStackTop)
? leftStackTop + leftRailOffset
: viewportHeight * 0.26;
@@ -206,6 +231,18 @@ export function layoutRightPanelRail({
0,
) +
gap * Math.max(0, measuredPanels.length - 1);
+ // An open Context panel takes the column's full height: up to just under
+ // the HUD readouts at the top of the screen, down to the usual bottom.
+ // CCTV does the same, so its feed and controls have the room.
+ const FULL_HEIGHT = new Set(['global-context-panel', 'cctv-panel']);
+ const contextOpen = panels.some(
+ (panel) =>
+ FULL_HEIGHT.has(panel.id) && !panel.classList.contains('collapsed'),
+ );
+ // Every panel starts level with the left rail, open or not, so the two
+ // rails line up in every HUD layout (Minimal has no top-right readout to
+ // push this column down) and switching between Context, CCTV and Street
+ // Level does not move it. Only the two above also stretch to the bottom.
const layout = resolveHudRailLayout({
viewportHeight,
panelHeight: naturalHeight,
@@ -221,9 +258,11 @@ export function layoutRightPanelRail({
const { safeTop, safeBottom, maxHeight: availableHeight } = layout;
const stabilityBand = Math.max(48, viewportHeight * 0.06);
const wasFocused = stack.classList.contains('layout-focus');
- const shouldFocus = wasFocused
- ? naturalHeight >= availableHeight - stabilityBand
- : naturalHeight > availableHeight;
+ const shouldFocus =
+ contextOpen ||
+ (wasFocused
+ ? naturalHeight >= availableHeight - stabilityBand
+ : naturalHeight > availableHeight);
const layoutTop = shouldFocus ? safeTop : layout.top;
const collapsedHeight = visiblePanels.reduce(
(total, panel) =>
diff --git a/src/ui/shellLifecycle.test.mjs b/src/ui/shellLifecycle.test.mjs
index 2c8bc8ee7..bcefb345e 100644
--- a/src/ui/shellLifecycle.test.mjs
+++ b/src/ui/shellLifecycle.test.mjs
@@ -259,7 +259,7 @@ test('recording restores the original HUD after repeated entry and revokes retai
}
});
-test('weather rail orders between CCTV and Context, observes and presents chrome', (t) => {
+test('Context leads the right rail, weather follows CCTV, observes and presents chrome', (t) => {
const f = fixture();
const observed = new Set();
const previousResizeObserver = globalThis.ResizeObserver;
@@ -319,7 +319,7 @@ test('weather rail orders between CCTV and Context, observes and presents chrome
owner._initRightPanelAdaptiveLayout();
assert.deepEqual(
stack.children.map((panel) => panel.id),
- ['pp-toggles', 'cctv-panel', 'weather-panel', 'global-context-panel'],
+ ['global-context-panel', 'pp-toggles', 'cctv-panel', 'weather-panel'],
);
assert.ok(observed.has(weather));
// Moving a panel into the rail leaves its state as it was.
diff --git a/src/ui/stores/worldTime.js b/src/ui/stores/worldTime.js
index 80f51ac71..9dcb7d4c8 100644
--- a/src/ui/stores/worldTime.js
+++ b/src/ui/stores/worldTime.js
@@ -8,6 +8,11 @@ const LIVE_TICK_MS = 1000;
const LIVE_EDGE = 0.005;
/** The least that counts as at now, past the readout's own second. */
const LIVE_EDGE_MS = 5000;
+/**
+ * The most that counts as at now, however long the track: on a track that
+ * runs over years, a share of it would take whole days back to live.
+ */
+const LIVE_EDGE_MAX_MS = 2 * 60_000;
/** The speeds play offers, in world ms per real ms. */
export const WORLD_TIME_SPEEDS = Object.freeze({
real: 1,
@@ -51,7 +56,7 @@ export const useWorldTimeStore = defineStore('gev-world-time', () => {
};
const nearNow = (ms, length) =>
Math.abs(ms - worldClock.wallNow()) <=
- Math.max(LIVE_EDGE_MS, length * LIVE_EDGE);
+ Math.max(LIVE_EDGE_MS, Math.min(LIVE_EDGE_MAX_MS, length * LIVE_EDGE));
// Whether the track ends at now (and moves on with it), not past it.
const endsAtNow = (covered) =>
covered.end - worldClock.wallNow() <= LIVE_EDGE_MS;
diff --git a/src/ui/styles/left-tools.css b/src/ui/styles/left-tools.css
new file mode 100644
index 000000000..83da30251
--- /dev/null
+++ b/src/ui/styles/left-tools.css
@@ -0,0 +1,37 @@
+/* Visual in the left column: it takes clicks (the column itself lets them
+ through to the globe) and stays inside the column, scrolling as a whole. */
+#left-panel-stack > #pp-toggles {
+ position: relative;
+ inset: auto;
+ flex: 0 1 var(--left-panel-allocated-height, auto);
+ min-height: 0;
+ max-height: var(--left-panel-allocated-height, 100%);
+ overflow-y: auto;
+ pointer-events: auto;
+}
+
+#left-panel-stack > #pp-toggles.collapsed {
+ display: none;
+}
+
+/* ── Expanded panel width ───────────────────────────────────────────────
+ Data Layers opens 15px wider than it used to (280 → 295px), and that is
+ the narrowest any side panel opens to; wider ones (Context, CCTV,
+ Authoring) keep their own width. */
+:root {
+ --side-panel-min-expanded-width: 295px;
+}
+
+#data-panel,
+#utilities-panel {
+ --panel-expanded-width: var(--side-panel-min-expanded-width);
+}
+
+#left-panel-stack > #pp-toggles:not(.collapsed) {
+ --pp-expanded-width: var(--side-panel-min-expanded-width);
+ width: var(--side-panel-min-expanded-width);
+}
+
+:is(#left-panel-stack, #right-context-rail) > [data-panel-id]:not(.collapsed) {
+ min-width: var(--side-panel-min-expanded-width);
+}
diff --git a/src/ui/styles/mobile-shell.css b/src/ui/styles/mobile-shell.css
index 120becf83..c011c9479 100644
--- a/src/ui/styles/mobile-shell.css
+++ b/src/ui/styles/mobile-shell.css
@@ -129,7 +129,9 @@ body.mobile-shell #right-context-rail {
body.mobile-shell[data-mobile-sheet='layers'] #left-panel-stack,
body.mobile-shell[data-mobile-sheet='cameras'] #right-context-rail,
body.mobile-shell[data-mobile-sheet='context'] #right-context-rail,
-body.mobile-shell[data-mobile-sheet='more'] #right-context-rail {
+/* Visual opens from the left rail on wider screens, so it lives in the left
+ stack and the More sheet is that stack showing Visual alone. */
+body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack {
position: fixed;
top: auto;
right: 0;
@@ -189,7 +191,7 @@ body.mobile-shell[data-mobile-sheet='context']
body.mobile-shell[data-mobile-sheet='context']
#right-context-rail
> #recent-imagery-panel:not([hidden]),
-body.mobile-shell[data-mobile-sheet='more'] #right-context-rail > #pp-toggles {
+body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack > #pp-toggles {
position: relative;
inset: auto;
display: block;
diff --git a/src/ui/styles/overlays.css b/src/ui/styles/overlays.css
index 85aaafa06..b45611785 100644
--- a/src/ui/styles/overlays.css
+++ b/src/ui/styles/overlays.css
@@ -310,8 +310,10 @@
bottom: 12vh;
}
+/* Minimal keeps its coordinates in the corner block, where the other layouts
+ have them; the full-width strip would only repeat the same position. */
#intel-hud[data-variant='minimal'] .hud-bottom-bar {
- display: flex;
+ display: none;
bottom: calc(12vh + 4rem);
}
diff --git a/src/ui/styles/panel-edge.css b/src/ui/styles/panel-edge.css
new file mode 100644
index 000000000..5903dd140
--- /dev/null
+++ b/src/ui/styles/panel-edge.css
@@ -0,0 +1,100 @@
+/* ── Panels over the rail ───────────────────────────────────────────────
+ Each panel header's edge switch (UiPanelEdge) slides that side's open
+ panels over their rail to the screen edge; the rail stays underneath. */
+.ui-panel-edge {
+ display: grid;
+ flex: none;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ color: rgba(206, 232, 239, 0.6);
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 6px;
+ cursor: pointer;
+}
+
+.ui-panel-edge .material-symbols-outlined {
+ font-size: 14px;
+}
+
+.ui-panel-edge:hover,
+.ui-panel-edge:focus-visible {
+ color: var(--text-primary, #e8eaed);
+ border-color: rgba(255, 255, 255, 0.24);
+}
+
+.ui-panel-edge[aria-pressed='true'] {
+ color: #36dcff;
+ background: rgba(54, 220, 255, 0.12);
+ border-color: rgba(54, 220, 255, 0.45);
+}
+
+/* Collapsed panels hide the switch; it only means something once open. */
+.panel-collapsible.collapsed .ui-panel-edge {
+ display: none;
+}
+
+/* Right: open panels move right by the rail's width and sit over it. */
+body.panels-edge-right:not(.mobile-shell):not(.cockpit-mode)
+ #right-context-rail
+ > :not(.gev-panel-rail) {
+ z-index: 2;
+ transform: translateX(var(--panel-rail-clearance, 48px));
+}
+
+/* Left: the same, moving left. */
+body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ #left-panel-stack
+ > :not(.gev-panel-rail) {
+ z-index: 2;
+ transform: translateX(calc(-1 * var(--panel-rail-clearance, 48px)));
+}
+
+body.mobile-shell .ui-panel-edge,
+body.cockpit-mode .ui-panel-edge {
+ display: none;
+}
+
+/* ── Edge mode with a panel open: the rail's icons move to a row along the
+ top of the panel, and the panel steps down to make room. ── */
+:root {
+ --edge-rail-row: 50px;
+}
+
+body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ .gev-panel-rail--left:has(.ui-rail--collapsible:not(.ui-rail--expanded)),
+body.panels-edge-right:not(.mobile-shell):not(.cockpit-mode)
+ .gev-panel-rail--right:has(.ui-rail--collapsible:not(.ui-rail--expanded)) {
+ top: 0 !important;
+ z-index: 3;
+}
+
+body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ .gev-panel-rail--left
+ .ui-rail--collapsible:not(.ui-rail--expanded),
+body.panels-edge-right:not(.mobile-shell):not(.cockpit-mode)
+ .gev-panel-rail--right
+ .ui-rail--collapsible:not(.ui-rail--expanded) {
+ flex-direction: row;
+ width: max-content;
+ gap: 4px;
+}
+
+body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ #left-panel-stack
+ > :not(.gev-panel-rail):not(.collapsed) {
+ transform: translate(
+ calc(-1 * var(--panel-rail-clearance, 48px)),
+ var(--edge-rail-row)
+ );
+ max-height: calc(100% - var(--edge-rail-row)) !important;
+}
+
+body.panels-edge-right:not(.mobile-shell):not(.cockpit-mode)
+ #right-context-rail
+ > :not(.gev-panel-rail):not(.collapsed) {
+ transform: translate(var(--panel-rail-clearance, 48px), var(--edge-rail-row));
+ max-height: calc(100% - var(--edge-rail-row)) !important;
+}
diff --git a/src/ui/styles/rail-edge.css b/src/ui/styles/rail-edge.css
new file mode 100644
index 000000000..cbcdb0eda
--- /dev/null
+++ b/src/ui/styles/rail-edge.css
@@ -0,0 +1,103 @@
+/* ── Side rails: sliding highlight and edge scrolling ──────────────────
+ The open item's highlight is drawn once per rail, under the icons, and
+ slides from item to item when the panel changes. With the pointer in a
+ screen edge's strip, the rail's border lights up a little to say the wheel
+ now steps through its panels; the panel that opens slides in from the
+ direction of travel. */
+.ui-rail {
+ position: relative;
+ transition:
+ border-color 240ms ease,
+ border-radius var(--transition-fast);
+}
+
+.ui-rail.ui-rail--edge-hot {
+ border-color: rgba(48, 194, 224, 0.4);
+}
+
+/* The highlight itself, matching an open item's own look. */
+.ui-rail::before {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 0;
+ width: var(--rail-glide-w, 32px);
+ height: var(--rail-glide-h, 32px);
+ background: var(--accent-dim);
+ border: 1px solid var(--accent-dim);
+ border-radius: var(--btn-radius);
+ box-sizing: border-box;
+ content: '';
+ opacity: 0;
+ pointer-events: none;
+ transform: translate(var(--rail-glide-x, 0), var(--rail-glide-y, 0));
+ /* Only the position slides. The size follows at once: it changes only
+ when the rail changes shape (its labelled pills folding to icons as a
+ panel opens), and a size easing there reads as a stretch. */
+ transition:
+ transform 380ms cubic-bezier(0.22, 1, 0.36, 1),
+ border-radius var(--transition-fast),
+ opacity 200ms ease;
+}
+
+.ui-rail--expanded::before {
+ border-radius: 16px;
+}
+
+.ui-rail.ui-rail--glide::before {
+ opacity: 1;
+}
+
+.ui-rail.ui-rail--glide-jump::before {
+ transition: opacity 200ms ease;
+}
+
+/* While the shared highlight shows, the items stay clear and sit above it;
+ the open item keeps its accent colour, which eases in as it arrives. */
+.ui-rail--glide .ui-rail__item {
+ z-index: 1;
+ transition:
+ color 300ms ease,
+ background var(--transition-fast),
+ border-color var(--transition-fast),
+ border-radius var(--transition-fast);
+}
+
+.ui-rail--glide .ui-rail__item--on,
+.ui-rail--glide .ui-rail__item--on:hover:not(:disabled) {
+ background: transparent;
+ border-color: transparent;
+}
+
+.rail-switch-down {
+ animation: rail-switch-down 340ms cubic-bezier(0.22, 1, 0.36, 1);
+}
+
+.rail-switch-up {
+ animation: rail-switch-up 340ms cubic-bezier(0.22, 1, 0.36, 1);
+}
+
+@keyframes rail-switch-down {
+ from {
+ opacity: 0;
+ translate: 0 16px;
+ }
+}
+
+@keyframes rail-switch-up {
+ from {
+ opacity: 0;
+ translate: 0 -16px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ui-rail::before {
+ transition: opacity 200ms ease;
+ }
+
+ .rail-switch-down,
+ .rail-switch-up {
+ animation: none;
+ }
+}
diff --git a/src/ui/styles/rail-split.css b/src/ui/styles/rail-split.css
new file mode 100644
index 000000000..5599180f1
--- /dev/null
+++ b/src/ui/styles/rail-split.css
@@ -0,0 +1,282 @@
+/* The left rail's icons keep their places whether or not a panel is open;
+ only the highlight moves to the open one. */
+
+/* With nothing open, the icons and their names split into two glass panels
+ side by side: the plain icon rail, and a name panel beside it with one row
+ per icon. A name is part of its button, so clicking it opens that panel. */
+.gev-panel-rail--left .ui-rail--expanded {
+ position: relative;
+ border-radius: calc(var(--btn-radius) + 4px);
+}
+
+.gev-panel-rail--left .ui-rail--expanded .ui-rail__item {
+ width: 32px;
+ border-radius: var(--btn-radius);
+}
+
+.gev-panel-rail--left .ui-rail--expanded::after {
+ content: '';
+ position: absolute;
+ top: -1px;
+ bottom: -1px;
+ left: calc(100% + 6px);
+ width: 170px;
+ border: 1px solid var(--glass-border);
+ border-radius: calc(var(--btn-radius) + 4px);
+ background: var(--glass-bg);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ pointer-events: none;
+}
+
+.gev-panel-rail--left .ui-rail--expanded .ui-rail__label {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ bottom: 0;
+ /* Past the rail's padding and border, the 6px gap, and the name panel's
+ border and inner padding. */
+ left: calc(100% + 24px);
+ display: flex;
+ align-items: center;
+ max-width: 150px;
+ margin: 0;
+}
+
+.gev-panel-rail--left .ui-rail--expanded .ui-rail__item:hover .ui-rail__label {
+ color: var(--text-primary);
+}
+
+/* The column rises to sit just under the HUD readout instead of leaving a
+ gap above it, with or without a panel open, so opening one doesn't move
+ the rail down. */
+#left-panel-stack {
+ top: calc(
+ var(--left-stack-safe-top, var(--left-stack-top)) +
+ var(--panel-rail-lift, 0px)
+ );
+}
+
+/* The right rail splits the same way with nothing open, mirrored: the icon
+ rail stays on the screen edge and the name panel sits to its left. */
+.gev-panel-rail--right .ui-rail--expanded {
+ position: relative;
+ border-radius: calc(var(--btn-radius) + 4px);
+}
+
+.gev-panel-rail--right .ui-rail--expanded .ui-rail__item {
+ width: 32px;
+ border-radius: var(--btn-radius);
+}
+
+.gev-panel-rail--right .ui-rail--expanded::after {
+ content: '';
+ position: absolute;
+ top: -1px;
+ bottom: -1px;
+ right: calc(100% + 6px);
+ width: 170px;
+ border: 1px solid var(--glass-border);
+ border-radius: calc(var(--btn-radius) + 4px);
+ background: var(--glass-bg);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ pointer-events: none;
+}
+
+.gev-panel-rail--right .ui-rail--expanded .ui-rail__label {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ bottom: 0;
+ /* From the button's left edge back past the rail's padding and border,
+ the 6px gap and the 170px name panel, to the panel's inner padding. */
+ left: -168px;
+ display: flex;
+ align-items: center;
+ max-width: 150px;
+ margin: 0;
+}
+
+.gev-panel-rail--right .ui-rail--expanded .ui-rail__item:hover .ui-rail__label {
+ color: var(--text-primary);
+}
+
+/* In clean view the screen-edge gutters stay empty: the HUD's vertical edge
+ readouts (ONA / COLL on the left, BAND / BITS / LVL on the right) are not
+ shown. Cyber lays its HUD out differently and keeps them. */
+:root:not([data-ui-theme='cyber']) body.ui-clean-view #intel-hud .hud-edge {
+ display: none !important;
+}
+
+/* The bottom-right readout (GSD / ALT / AIS) has one more line than the
+ bottom-left one (MGRS / coordinates); it drops by that line so the two
+ corners start level. */
+#intel-hud[data-variant='tactical'] .hud-bottom-right {
+ bottom: calc(2vh + 6.5rem - 26px);
+}
+
+@media (min-width: 1200px) {
+ #intel-hud[data-variant='tactical'] .hud-bottom-right {
+ bottom: calc(4.2rem - 26px);
+ }
+}
+
+/* ── Contrast: rails and name panels read clearly over dark space as well
+ as bright imagery. ── */
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail {
+ background: rgba(16, 20, 28, 0.82) !important;
+ border-color: rgba(255, 255, 255, 0.14) !important;
+ box-shadow:
+ 0 6px 20px rgba(0, 0, 0, 0.45),
+ inset 0 1px 0 rgba(255, 255, 255, 0.05);
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail--expanded::after {
+ background: rgba(16, 20, 28, 0.82) !important;
+ border-color: rgba(255, 255, 255, 0.14) !important;
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail__item {
+ color: rgba(225, 236, 242, 0.88);
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail__label {
+ color: rgba(225, 236, 242, 0.82) !important;
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail__item:hover {
+ color: #fff;
+}
+
+/* The open item takes the accent colour; its highlight is the rail's shared
+ one, which slides to it. The button carries no fill of its own: as a rail
+ folds its labelled pills to icons, a fill on the shrinking button would
+ read as the highlight stretching. */
+:is(.gev-panel-rail--left, .gev-panel-rail--right)
+ .ui-rail__item.ui-rail__item--on {
+ color: #00d4ff !important;
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right)
+ .ui-rail:not(.ui-rail--glide)
+ .ui-rail__item.ui-rail__item--on {
+ background: none;
+ border-color: transparent;
+}
+
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail::before {
+ background: rgba(0, 212, 255, 0.15);
+ border-color: rgba(0, 212, 255, 0.28);
+}
+
+/* ── The open icon is its own island ──
+ With a panel open, the rail's glass is drawn in pieces behind its icons:
+ one piece for the open icon, and one for each run of icons above and below
+ it. The icons keep their places, open or not; the spacing between them is
+ what leaves room for the break. */
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail {
+ gap: 12px;
+}
+
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on) {
+ background: none !important;
+ border-color: transparent !important;
+ box-shadow: none !important;
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+}
+
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip::before {
+ position: absolute;
+ inset: -6px -5px;
+ z-index: -1;
+ background: rgba(16, 20, 28, 0.82);
+ border: solid rgba(255, 255, 255, 0.14);
+ border-width: 0 1px;
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ content: '';
+ pointer-events: none;
+}
+
+/* The ends of the rail. */
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip:first-child::before {
+ top: -5px;
+ border-top-width: 1px;
+ border-top-left-radius: 14px;
+ border-top-right-radius: 14px;
+}
+
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip:last-child::before {
+ bottom: -5px;
+ border-bottom-width: 1px;
+ border-bottom-left-radius: 14px;
+ border-bottom-right-radius: 14px;
+}
+
+/* The runs stop short of the open icon. */
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip:has(+ .ui-tooltip > .ui-rail__item--on)::before {
+ bottom: -1px;
+ border-bottom-width: 1px;
+ border-bottom-left-radius: 14px;
+ border-bottom-right-radius: 14px;
+}
+
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip:has(> .ui-rail__item--on)
+ + .ui-tooltip::before {
+ top: -1px;
+ border-top-width: 1px;
+ border-top-left-radius: 14px;
+ border-top-right-radius: 14px;
+}
+
+/* The open icon's own piece. */
+:is(
+ body:not(.panels-edge-left) .gev-panel-rail--left,
+ body:not(.panels-edge-right) .gev-panel-rail--right
+ )
+ .ui-rail--collapsible:not(.ui-rail--expanded):has(.ui-rail__item--on)
+ > .ui-tooltip:has(> .ui-rail__item--on)::before {
+ inset: -4px -5px;
+ border-width: 1px;
+ border-radius: 14px;
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
+}
+
+/* The side rails fold their labels away at once when a panel opens, and back
+ when it closes: easing the labels' width made every button visibly
+ stretch and shrink. Only their fade eases. */
+:is(.gev-panel-rail--left, .gev-panel-rail--right) .ui-rail__label {
+ transition: opacity var(--transition-fast);
+}
diff --git a/src/ui/styles/rtl.css b/src/ui/styles/rtl.css
index fa0179b70..7b596b1ae 100644
--- a/src/ui/styles/rtl.css
+++ b/src/ui/styles/rtl.css
@@ -242,3 +242,47 @@ html[dir='rtl'] select.gev-field--compact {
html[dir='rtl'] .rail-card-scale {
direction: ltr;
}
+
+/* ── Side rails, mirrored ──────────────────────────────────────────────
+ The left stack sits on the right edge, so the left rail's name panel
+ opens to its left and the right rail's to its right, each toward the
+ middle of the screen, as they do in left-to-right. */
+html[dir='rtl'] .gev-panel-rail--left .ui-rail--expanded::after {
+ right: calc(100% + 6px);
+ left: auto;
+}
+html[dir='rtl'] .gev-panel-rail--left .ui-rail--expanded .ui-rail__label {
+ right: calc(100% + 24px);
+ left: auto;
+}
+html[dir='rtl'] .gev-panel-rail--right .ui-rail--expanded::after {
+ right: auto;
+ left: calc(100% + 6px);
+}
+html[dir='rtl'] .gev-panel-rail--right .ui-rail--expanded .ui-rail__label {
+ right: auto;
+ left: calc(100% + 24px);
+}
+
+/* Panels moved to the screen edge slide over their rail toward that edge. */
+html[dir='rtl']
+ body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ #left-panel-stack
+ > :not(.gev-panel-rail) {
+ transform: translateX(var(--panel-rail-clearance, 48px));
+}
+html[dir='rtl']
+ body.panels-edge-left:not(.mobile-shell):not(.cockpit-mode)
+ #left-panel-stack
+ > :not(.gev-panel-rail):not(.collapsed) {
+ transform: translate(var(--panel-rail-clearance, 48px), var(--edge-rail-row));
+}
+html[dir='rtl']
+ body.panels-edge-right:not(.mobile-shell):not(.cockpit-mode)
+ #right-context-rail
+ > :not(.gev-panel-rail) {
+ transform: translate(
+ calc(-1 * var(--panel-rail-clearance, 48px)),
+ var(--edge-rail-row)
+ );
+}
diff --git a/src/ui/views/panels/WorldTimeline.test.mjs b/src/ui/views/panels/WorldTimeline.test.mjs
index 073d6f95e..7785e86c1 100644
--- a/src/ui/views/panels/WorldTimeline.test.mjs
+++ b/src/ui/views/panels/WorldTimeline.test.mjs
@@ -149,6 +149,41 @@ test('the track runs over the time the layers show, to now, and scrubs', async (
assert.equal(worldClock.now(), ahead);
});
+test('on a track that runs over years, only the last minutes are near now', async (t) => {
+ const bar = mount(t);
+ const now = Date.now();
+ // A layer whose source covers fourteen years, up to now.
+ const start = now - 14 * 365 * 86_400_000;
+ const release = worldClock.hold('test-years');
+ const unregister = worldClock.register({
+ id: 'test-years',
+ coverage: () => ({ start, end: now }),
+ });
+ t.after(() => {
+ unregister();
+ release();
+ });
+ await nextTick();
+ const input = bar().querySelector('input[type=range]');
+
+ // A day back is a day back, though it is well within a share of the track.
+ input.value = String(now - 86_400_000);
+ input.dispatchEvent(new Event('input'));
+ await nextTick();
+ assert.equal(worldClock.isLive(), false, 'a day back stays off live');
+ assert.equal(worldClock.now(), now - 86_400_000);
+
+ input.value = String(now - 10 * 60_000);
+ input.dispatchEvent(new Event('input'));
+ await nextTick();
+ assert.equal(worldClock.isLive(), false, 'ten minutes back stays off live');
+
+ input.value = String(Date.now() - 60_000);
+ input.dispatchEvent(new Event('input'));
+ await nextTick();
+ assert.equal(worldClock.isLive(), true, 'a minute back goes live');
+});
+
test('play runs in real time, from the start of the track when at live', async (t) => {
const bar = mount(t);
const now = Date.now();
diff --git a/src/voice/layerManifest.js b/src/voice/layerManifest.js
index 189ee8e44..52cb0f90f 100644
--- a/src/voice/layerManifest.js
+++ b/src/voice/layerManifest.js
@@ -302,7 +302,23 @@ const layers = [
},
{
id: 'transit',
- aliases: ['buses', 'trains', 'public transit', 'trams', 'subway'],
+ aliases: [
+ 'buses',
+ 'trains',
+ 'public transit',
+ 'trams',
+ 'subway',
+ 'trolleybus',
+ 'trolleybuses',
+ 'gondola',
+ 'gondolas',
+ 'cable car',
+ 'cable cars',
+ 'funicular',
+ 'funiculars',
+ 'monorail',
+ 'monorails',
+ ],
context: false,
query: {
fields: {
diff --git a/style.css b/style.css
index 45f4f3eff..012714e4e 100644
--- a/style.css
+++ b/style.css
@@ -45,5 +45,9 @@
@import './src/ui/styles/rtl.css';
@import './src/ui/styles/mobile-shell.css';
@import './src/ui/styles/annotations.css';
+@import './src/ui/styles/rail-edge.css';
+@import './src/ui/styles/rail-split.css';
+@import './src/ui/styles/left-tools.css';
+@import './src/ui/styles/panel-edge.css';
@import './src/ui/styles/ai-chat.css';
@import './src/ui/styles/cyber.css';