From 134138931fa93a29c78dfd9a93e54389782fff70 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Tue, 17 Nov 2026 19:30:47 +0400 Subject: [PATCH 01/18] Transit cockpit rides: hide the held icon, end a hold with the layer, no ellipsoid height - A held vehicle's icon is hidden through the renderer (setShown, then flushMarkers). The icon sets draw a marker only as last pushed, so the direct marker.show write left a parked vehicle's icon drawn under the view's eye. - disable() ends the hold: turned off and on again, the vehicle shows and clicks and Escape reach the layer. - Far above the ground a vehicle with no floor is drawn on the ellipsoid. Its snapshot now reports groundHeightM null there, as near the ground, instead of -1.5 m. - The uneven-ground test also checks the snapshot mid-segment, where a blend of the two reports' floors would read about 55 m instead of 10 m. --- src/layers/transit/cockpitSubject.js | 21 +++-- src/layers/transit/lifecycle.js | 2 + src/layers/transit/lifecycle.test.mjs | 106 ++++++++++++++++++++++++++ src/layers/transit/rendering.js | 1 + 4 files changed, 123 insertions(+), 7 deletions(-) diff --git a/src/layers/transit/cockpitSubject.js b/src/layers/transit/cockpitSubject.js index 909e4702f6..e135835a95 100644 --- a/src/layers/transit/cockpitSubject.js +++ b/src/layers/transit/cockpitSubject.js @@ -84,12 +84,16 @@ export function createTransitCockpitSubject({ state, parts, services }) { * or held), which near the ground follows the terrain between reports; * else its segment's two reports' floors at the playback fraction. Null * while either floor is unknown, as on cold terrain, so a view waits for - * the surface. Not `entry.heightM`, the floor at the newest report, which - * playback has not reached yet. + * the surface: far above the ground such a marker is drawn on the + * ellipsoid, which is no floor. Not `entry.heightM`, the floor at the + * newest report, which playback has not reached yet. */ function drawnFloorOf(entry) { const segment = entry.segment; if (!segment || entry.heightPending) return null; + const from = segment.from?.h; + const to = segment.to?.h; + if (!Number.isFinite(from) || !Number.isFinite(to)) return null; const placed = entry.surfaceReady === true && entry.hasRendered && @@ -99,9 +103,6 @@ export function createTransitCockpitSubject({ state, parts, services }) { const drawn = toCartographicRadians(entry.marker.position); if (drawn) return drawn.height - liftM; } - const from = segment.from?.h; - const to = segment.to?.h; - if (!Number.isFinite(from) || !Number.isFinite(to)) return null; const f = Number.isFinite(segment.fraction) ? Math.max(0, Math.min(1, segment.fraction)) : 1; @@ -173,11 +174,17 @@ export function createTransitCockpitSubject({ state, parts, services }) { return snapshot; } - /** Show or hide a vehicle's sprite and trail for the hold. */ + /** + * Show or hide a vehicle's sprite and trail for the hold. The sprite goes + * through the renderer (setShown, flushMarkers): its set draws a marker + * only as last pushed. + */ function repaint(entry) { if (!entry?.marker) return; - if (entry.key === state._cockpitSubjectKey) entry.marker.show = false; + if (entry.key === state._cockpitSubjectKey) + parts.rendering.setShown(entry, false); else parts.rendering.placeSample(entry); + parts.rendering.flushMarkers(); parts.rendering.schedulePlayback(entry); parts.trails.update(); state._detectRevision += 1; diff --git a/src/layers/transit/lifecycle.js b/src/layers/transit/lifecycle.js index 5e4428f55b..0f3473ffa5 100644 --- a/src/layers/transit/lifecycle.js +++ b/src/layers/transit/lifecycle.js @@ -165,6 +165,8 @@ export function createLifecycle({ state, services, parts }) { state._visible.clear(); clearTimeout(state._cameraDebounceTimer); state._cameraDebounceTimer = null; + // A hold ends with the layer (cockpitSubject.js). + state._cockpitSubjectKey = null; parts.selection.clearSelection(); state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false); parts.selection.removeClickHandler(); diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 49a3e7f17a..3fcfa3f9ea 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -978,6 +978,34 @@ test('a held vehicle with no floor yet tells its view no height', async (t) => { assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); }); +test('far above the ground, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => { + // Above the height gate a vehicle with no floor is drawn on the ellipsoid + // at once, not held back; the ellipsoid is still no floor to stand a view + // on. + const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const [entry] = app.vehicles(); + assert.ok(app.layer.setCockpitSubject(entry.key) !== false); + app.frame(); + assert.equal(entry.surfaceReady, true, 'it is drawn'); + const drawnM = Cesium.Cartographic.fromCartesian( + entry.marker.position, + ).height; + assert.ok(Math.abs(drawnM) < 1e-3, `on the ellipsoid, got ${drawnM} m`); + assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); +}); + test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => { // The shared ground-floor system answers from the rendered mesh cell or the // real DEM cell; until one of them is warm there is no honest height to draw @@ -2125,6 +2153,11 @@ test('a segment climbs from the ground it left to the ground it reaches', async Math.abs(height() - 11.5) < 3, `at the corridor floor, got ${height().toFixed(1)} m`, ); + // The two reports' floors blended at the fraction would say about 55 m. + assert.ok( + Math.abs(floor() + 1.5 - height()) < 1, + `its snapshot stands on that floor too, got ${floor().toFixed(1)} m`, + ); app.run(TRANSIT_POLL_MS); assert.ok( Math.abs(height() - 101.5) < 1.5, @@ -4880,3 +4913,76 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes', assert.equal(app.state()._cockpitSubjectKey, null); assert.equal(app.layer.getCockpitSubject(), null); }); + +test('turning Transit off ends a hold; on again, Escape deselects and the vehicle shows', async (t) => { + const app = harness(t); + const key = await busRunningNorth(app); + assert.equal(app.layer.setCockpitSubject(key), true); + app.layer.disable(app.viewer); + assert.equal( + app.state()._cockpitSubjectKey, + null, + 'the hold ended with the layer', + ); + // On again, without a release: the same bus is listed again. + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + app.settle(); + assert.equal(app.layer.focusVehicle(key), true); + const [entry] = app.vehicles(); + app.frame(); + assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held'); + globalThis.document.dispatchEvent( + Object.assign(new Event('keydown'), { key: 'Escape' }), + ); + assert.equal(app.state()._selectedKey, null, 'Escape deselects'); +}); + +test('a held parked vehicle draws no icon; let go, it draws its icon again', async (t) => { + // A parked bus with no course: nothing moves or turns its icon, so only the + // hold itself can take the icon out of the set that draws it. + const app = harness(t); + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [vehicle('bus-1', 42.36, -71.06, reported(), { stopId: 'place-1' })], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + for (let i = 0; i < 3; i += 1) { + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + app.settle(); + } + const key = 'mbta:bus-1'; + const [entry] = app.vehicles(); + const icon = () => + app.markers('still').get(key) ?? app.markers('moving').get(key); + assert.equal(icon()?.show, true, 'drawn before the hold'); + assert.equal(app.layer.setCockpitSubject(key), true); + // The view rides it for a while: frames, a sweep, a poll. + app.run(2_000, 16); + app.settle(); + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + app.settle(); + assert.equal(entry.marker.show, false, 'its marker is hidden'); + assert.equal( + icon()?.show ?? false, + false, + 'and so is the icon the set draws', + ); + + assert.equal(app.layer.setCockpitSubject(null), true); + app.advance(250); + app.settle(); + assert.equal(icon()?.show, true, 'let go: drawn again'); +}); diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 194d042a3e..8b0ecc1e8e 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -1225,6 +1225,7 @@ export function createRendering({ state, services, parts }) { setNameOf, markerShown, markDirty, + setShown, flushMarkers, removeMarker, watchCamera, From a7d966ae7e3d43fa9934d88de765bdbd37292445 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Tue, 17 Nov 2026 19:30:47 +0400 Subject: [PATCH 02/18] Rail cockpit rides: no height on an unknown floor, a standing train keeps its direction - railHeightM is null while the train is drawn on the ellipsoid (floor quality 0) instead of -1.5 m, so a view waits for the surface. - An arc step between two reports tells which way a train runs only above 15 m, the layer's parked-train jitter (FOLLOW_MIN_MOVE_M). GPS jitter of a standing train no longer flips the direction through the playback segments, which turned a ride 180 degrees every poll. - drawDirection, a copy of direction, becomes a directionPlayed flag. --- src/layers/rail/cockpitSubject.js | 5 +- src/layers/rail/cockpitSubject.test.mjs | 24 ++++++++- src/layers/rail/pathBinding.js | 28 ++++++----- src/layers/rail/pathBinding.test.mjs | 65 ++++++++++++++++++++++++- 4 files changed, 105 insertions(+), 17 deletions(-) diff --git a/src/layers/rail/cockpitSubject.js b/src/layers/rail/cockpitSubject.js index 80cfc1daa6..286160d3aa 100644 --- a/src/layers/rail/cockpitSubject.js +++ b/src/layers/rail/cockpitSubject.js @@ -205,7 +205,10 @@ export function createRailCockpitSubject({ finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat; position.longitude = finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon; - position.railHeightM = Number.isFinite(drawn?.h) ? drawn.h - liftM : null; + // Quality 0 is the ellipsoid a train is drawn on while no floor is + // known: no height, so a view waits for the surface. + position.railHeightM = + Number.isFinite(drawn?.h) && drawn.q > 0 ? drawn.h - liftM : null; position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0; position.atMs = finiteOrNull(drawn?.at); diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs index b439e1eecc..c8c764aad3 100644 --- a/src/layers/rail/cockpitSubject.test.mjs +++ b/src/layers/rail/cockpitSubject.test.mjs @@ -44,6 +44,13 @@ const PACK = Object.freeze({ routes: { R1: [0] }, }); +/** A floor service that knows the ground everywhere, at 12 m. */ +const WARM_GROUND = Object.freeze({ + GROUND_FLOOR_LIFT_M: 1.5, + cachedGroundFloor: () => 12, + warmGroundFloor() {}, +}); + /** Two trains on the line, T1 running east and T2 west, a step a poll. */ async function onTheLine(t, options = {}) { const app = harness(t, { @@ -76,7 +83,7 @@ const T1 = railTrainKey('mbta-rail', 'T1'); const T2 = railTrainKey('mbta-rail', 'T2'); test('the selected train reads as a snapshot of its place, motion and sources', async (t) => { - const app = await onTheLine(t); + const app = await onTheLine(t, { ground: WARM_GROUND }); assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected'); app.parts().selection.selectTrain(T1); const view = app.layer.getSelectedTrain(); @@ -105,6 +112,7 @@ test('the selected train reads as a snapshot of its place, motion and sources', assert.equal(view.provenance.positionSource, 'gps'); assert.equal(view.provenance.timestampSource, 'vehicle'); const drawn = app.entry(T1).drawnHeight; + assert.ok(view.position.heightQuality > 0, 'on a known floor'); assert.equal(view.position.railHeightM, drawn.h - 1.5); assert.ok(Number.isFinite(view.position.latitude)); assert.ok(Array.isArray(view.stops)); @@ -129,6 +137,20 @@ const stopList = (...names) => state: 'upcoming', })); +test('a train drawn on an unknown floor reports no rail height', async (t) => { + // The harness's floor service is always cold: the train is drawn on the + // ellipsoid, which is no floor for a view to stand on. + const app = await onTheLine(t); + app.parts().selection.selectTrain(T1); + const view = app.layer.getSelectedTrain(); + assert.equal(view.position.heightQuality, 0, 'no floor is known'); + assert.equal( + view.position.railHeightM, + null, + 'an unknown floor is no height', + ); +}); + test('a snapshot read again while nothing changed is the one read before', async (t) => { let list = stopList('Alpha', 'Bravo', 'Charlie'); const app = await onTheLine(t, { diff --git a/src/layers/rail/pathBinding.js b/src/layers/rail/pathBinding.js index 9eba452d37..a432095b7a 100644 --- a/src/layers/rail/pathBinding.js +++ b/src/layers/rail/pathBinding.js @@ -47,8 +47,13 @@ export function pathWindowM(dtMs) { return window > PATH_WINDOW_MAX_M ? NaN : window; } -/** Arc moved between two reports before it says which way a train runs (m). */ -const DIRECTION_MIN_M = 1; +/** + * Arc moved between two reports before it says which way a train runs (m). + * A standing train's GPS jitter, a few metres back and forth, stays under it + * (the same parked-train jitter as FOLLOW_MIN_MOVE_M, policy.js) and keeps + * the direction learnt. + */ +const DIRECTION_MIN_M = 15; /** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */ function directionOf(step, known) { @@ -65,13 +70,13 @@ function createBinding(shapeIndex, path, via, s, fix) { /** * Which way the drawn train runs along the shape: +1 along it, -1 * against it, 0 until two reports or a playback segment tell. Kept until - * a rebind. Once playback has placed the train, only playback changes - * it: the newest reports run ahead of the drawn train, so a reversal - * they show turns it when playback reaches it. + * a rebind, and while the train stands. Once a playback segment has told + * it (`directionPlayed`), only playback changes it: the newest reports + * run ahead of the drawn train, so a reversal they show turns it when + * playback reaches it. */ direction: 0, - /** The direction the last placed playback segment ran, 0 before one. */ - drawDirection: 0, + directionPlayed: false, /** Arc and time of the newest report. */ fixS: s, fixT: fix.t, @@ -159,7 +164,7 @@ export function followFix(binding, fix) { pathWindowM(fix.t - binding.fixT), ); if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false; - if (!binding.drawDirection) + if (!binding.directionPlayed) binding.direction = directionOf(hit.s - binding.fixS, binding.direction); binding.fixS = hit.s; binding.fixT = fix.t; @@ -253,11 +258,8 @@ export function placeOnPath(binding, sample, segment, out) { cache.sTo = sTo; cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo); if (cache.ok) { - binding.drawDirection = directionOf( - sTo - sFrom, - binding.drawDirection || binding.direction || 0, - ); - binding.direction = binding.drawDirection; + binding.direction = directionOf(sTo - sFrom, binding.direction); + if (binding.direction) binding.directionPlayed = true; } } if (!cache.ok) return false; diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index 7b9e11c0cc..e257fb86da 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -209,8 +209,9 @@ test('a binding learns which way its train runs, and keeps it through a stop', ( assert.equal(along.direction, 0, 'one report tells no direction'); assert.ok(followFix(along, fix(10_000, 700, 0))); assert.equal(along.direction, 1); - // Standing still (under a metre) keeps what it learnt. - assert.ok(followFix(along, fix(20_000, 700.4, 0))); + // Standing at a stop, its reports jitter back a few metres: it keeps what + // it learnt. + assert.ok(followFix(along, fix(20_000, 690, 0))); assert.equal(along.direction, 1); const against = bindTrainPath(p, ids, fix(0, 1500, 0)); assert.ok(followFix(against, fix(10_000, 1200, 0))); @@ -262,3 +263,63 @@ test('a report that runs back turns the drawn train only when playback does', () ); assert.equal(binding.direction, -1); }); + +test('jitter segments played back at a standing train keep the direction it learnt', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + const binding = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.ok(followFix(binding, fix(15_000, 1600, 0))); + // Playback runs the train east, 1000 m -> 1600 m: direction +1. + const out = {}; + let seq = 0; + const play = (fromM, toM, t0) => { + const segment = { + from: { seq, ...fix(t0, fromM, 0) }, + to: { seq: seq + 1, ...fix(t0 + 15_000, toM, 0) }, + }; + assert.ok( + placeOnPath( + binding, + { fromSeq: seq, toSeq: seq + 1, fraction: 0.5 }, + segment, + out, + ), + ); + seq += 1; + return binding.direction; + }; + assert.equal(play(1000, 1600, 0), 1); + assert.equal( + binding.directionPlayed, + true, + 'playback owns the direction now', + ); + // At the platform: reports 3-5 m apart, back and forth, polled and played. + const learnt = []; + let t0 = 15_000; + for (const [fromM, toM] of [ + [1600, 1597], + [1597, 1600], + [1600, 1596], + [1596, 1601], + ]) { + assert.ok(followFix(binding, fix(t0 + 15_000, toM, 0))); + learnt.push(play(fromM, toM, t0)); + t0 += 15_000; + } + assert.deepEqual(learnt, [1, 1, 1, 1], 'from the played-back segments'); +}); + +test('GPS jitter in the newest reports before playback keeps the direction', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + const binding = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.ok(followFix(binding, fix(15_000, 1600, 0))); + assert.equal(binding.direction, 1); + const learnt = []; + [1597, 1600, 1596, 1601].forEach((eastM, i) => { + assert.ok(followFix(binding, fix(30_000 + i * 15_000, eastM, 0))); + learnt.push(binding.direction); + }); + assert.deepEqual(learnt, [1, 1, 1, 1], 'from the newest reports'); +}); From ec9d5c9e060647d3781fe2eb7ce839d5d6d5da34 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Tue, 17 Nov 2026 19:30:47 +0400 Subject: [PATCH 03/18] Describe the cockpit ride fixes and add their changelog entry --- changelog.d/0000-cockpit-ride-transit-rail.md | 8 ++++++++ docs/CURRENT-STATE.md | 19 ++++++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 changelog.d/0000-cockpit-ride-transit-rail.md diff --git a/changelog.d/0000-cockpit-ride-transit-rail.md b/changelog.d/0000-cockpit-ride-transit-rail.md new file mode 100644 index 0000000000..284b570388 --- /dev/null +++ b/changelog.d/0000-cockpit-ride-transit-rail.md @@ -0,0 +1,8 @@ +- Fix rides on a Rail train or Transit vehicle for an application's Cockpit + subjects. A held parked vehicle no longer leaves its icon drawn under the + view, and turning Transit off ends a hold, so the vehicle shows again when + the layer is back on. A train or vehicle drawn on the ellipsoid while no + floor is known reports no height, so the view waits for the ground instead + of standing on the ellipsoid. A train standing at a platform keeps the way + it runs: GPS jitter of a few metres no longer turns the ride around + (German, @gekh, #0000). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4a5d97da6e..f2a437aea0 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2768,8 +2768,9 @@ HUD view is. The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, -which way it runs (`pathBinding.js` learns it), its rail height, speed as -reported or derived, position source, feed credit and stops, and +which way it runs (`pathBinding.js` learns it), its rail height (null while +no floor is known and it is drawn on the ellipsoid), speed as reported or +derived, position source, feed credit and stops, and `selectedAtMs`, when the user last selected it by a click or `focusTrain`, even again; null after a deselection and for a train only a hold selected), `setCockpitSubject(key)` (its marker, 3D model and card hidden, the selection kept, its @@ -2784,11 +2785,15 @@ offers the same for a vehicle (`getSelectedVehicle`, `getCockpitSubject`, `setCockpitSubject`, `focusVehicle`): a held vehicle keeps playing when it is out of the camera's view, and its sprite, 3D model, card, trail and detection box are hidden; released, it is out of play until a visibility sweep finds it in -view. Its snapshot's `position.groundHeightM` is the floor where playback draws -it (the drawn marker's height while it is placed, else its segment's two -reports' floors at the playback fraction), not the newest report's, and null while that floor is unknown. Rail's `path.direction` is the -way the drawn train runs: once playback has placed it, a report that runs back -turns it only when playback reaches that report. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, +view. Turning the layer off ends the hold. Its snapshot's +`position.groundHeightM` is the floor where playback draws it (the drawn +marker's height while it is placed, else its segment's two reports' floors at +the playback fraction), not the newest report's, and null while that floor is +unknown, also far above the ground, where such a vehicle is drawn on the +ellipsoid. Rail's `path.direction` is the way the drawn train runs: once +playback has placed it, a report that runs back turns it only when playback +reaches that report, and a step of at most 15 m between two reports (a standing +train's GPS jitter) keeps the direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, `src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, `src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests cover them. From a2a61c506fe7ad7f0fd01d5c755d10d519081d00 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Tue, 17 Nov 2026 19:34:32 +0400 Subject: [PATCH 04/18] Keep an application's Cockpit subject steady in the camera and HUD - A height the entry frame gave holds while later frames give none and the floor is still cold, so the view no longer waits and ends. - A subject's camera update advances by the time since the last one, up to its interval plus a second: at 5 frames a second an inertial subject no longer falls behind (700 m in a minute at 30 m/s), while a hidden tab still counts as one late update. - A provider's Live Signals rows change where they stand and come back after newer rows pushed them off, so a changing ETA no longer hides a steady warning; the built-in rows log as before. - Progress labels give full-width glyphs (CJK, kana, Hangul) about 1 em, so such stop names no longer overlap. - A provider's labels, entry face and look start from the words checked at registration, so one that fails on its next read keeps them. The double-click test on a selected vessel now projects through SceneTransforms, as the scene query port does, with a control that enters the bridge. --- docs/CURRENT-STATE.md | 17 ++- src/cockpitMath.js | 15 ++- src/cockpitMath.test.mjs | 11 +- src/cockpitProgress.js | 28 +++- src/cockpitProgress.test.mjs | 19 ++- src/cockpitSubjectProviders.js | 43 +++--- src/ui/cockpitCamera.js | 4 +- src/ui/cockpitController.js | 12 +- src/ui/cockpitInstruments.js | 4 + src/ui/cockpitSignals.js | 29 +++- src/ui/cockpitSubjectView.test.mjs | 201 ++++++++++++++++++++++++++-- src/ui/cockpitTrackingController.js | 4 +- 12 files changed, 329 insertions(+), 58 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4a5d97da6e..67d063bd73 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2743,28 +2743,33 @@ first in that order decides alone: when its gate is shut there is no entry rather than the next subject's. A frame places the eye `eye.upM` above `heightM` (the shared floor where the -frame gives none, or where it last stood while that floor is cold; with -neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for +frame gives none, or the last height it had, the entry frame's included, while +that floor is cold; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may turn off the floor clamps (`groundClamp: false`, for a subject inside a structure) or keep the anchor exactly on the subject (`anchor: 'exact'`, for a layer that already moves it smoothly; a frame with no `speedMps` is always exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs: 0` updates the -camera every rendered frame. A frame that is null, malformed or for another +camera every rendered frame. Each update turns, eases and moves the view by the +time since the last one, so it keeps up when the browser draws few frames; an +update more than a second past its interval (a hidden tab) moves it as one a +second late would. A frame that is null, malformed or for another subject ends the view (`restoreTracking: false`), as an aircraft tracked meanwhile and the provider's layer turning off do; the exit control asks the provider to restore its subject. The generic HUD shows the provider's kicker, title, meta line, speed with its unit and tag, readout cards, always-visible -source rows, banner, route card and Live Signals rows, a veil that darkens the +source rows, banner, route card and Live Signals rows (each changes where it +stands, so a changing ETA never pushes a steady warning off the list), a veil that darkens the picture under the HUD (with passing light streaks, which stop under reduced motion), arrow-key look-around when the provider asks for it, and a progress line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, -labels never overlap). Core translates none of the provider's text: a host +labels never overlap, a full-width CJK, kana or Hangul glyph given about 1 em). Core translates none of the provider's text: a host words it for the page's language (`gods-eye-view/i18n`: `getLocale`, `onLocaleChange`). Its entry face, labels and look may be functions, read again when they are shown and on a change of language, as the -HUD view is. +HUD view is; a read that throws or is malformed keeps the last good words, at +first those checked when the provider was registered. The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, diff --git a/src/cockpitMath.js b/src/cockpitMath.js index 05a69904c7..45348a2f39 100644 --- a/src/cockpitMath.js +++ b/src/cockpitMath.js @@ -58,12 +58,19 @@ export function cockpitAnchorCorrectionStep( return Math.min(distanceM, eased, correctionRateMps * dt); } +/** + * How late past its interval a subject's camera update may come and still + * advance by all of it: a browser drawing a frame a second still keeps up. + */ +const COCKPIT_SUBJECT_LATE_SEC = 1; + /** * The seconds an application subject's camera update advances its heading * slew, ground lift and anchor by: the time since the last update, at most - * its update interval plus 0.1 s. A subject updated every 500 ms then turns - * and eases at its configured rates, while a long stall (a hidden tab) still - * moves it no further than one late update would. + * its update interval plus a second. A subject updated every 500 ms, or a + * browser drawing 5 frames a second, then turns, eases and moves at its + * configured rates, while a long stall (a hidden tab) still moves it no + * further than one late update would. * @param {number} elapsedMs Time since the last camera update. * @param {number} intervalMs The subject's update interval (0: every frame). * @returns {number} @@ -75,7 +82,7 @@ export function cockpitSubjectStepSec(elapsedMs, intervalMs) { const intervalSec = Number.isFinite(intervalMs) ? Math.max(0, intervalMs) / 1000 : 0; - return Math.min(intervalSec + 0.1, elapsedSec); + return Math.min(intervalSec + COCKPIT_SUBJECT_LATE_SEC, elapsedSec); } /** Return whether a throttled cockpit presentation update is due. */ diff --git a/src/cockpitMath.test.mjs b/src/cockpitMath.test.mjs index 29c2654c6c..3892d510b0 100644 --- a/src/cockpitMath.test.mjs +++ b/src/cockpitMath.test.mjs @@ -73,12 +73,15 @@ test('an application subject steps by its interval, never by a long stall', () = assert.equal(cockpitSubjectStepSec(16, 0), 0.016); assert.equal(cockpitSubjectStepSec(500, 500), 0.5); assert.equal(cockpitSubjectStepSec(520, 500), 0.52); - // A hidden tab's minutes count as one late update. - assert.equal(cockpitSubjectStepSec(60_000, 500), 0.6); - assert.equal(cockpitSubjectStepSec(60_000, 0), 0.1); + // Slow frames (5 a second) count in full... + assert.equal(cockpitSubjectStepSec(200, 50), 0.2); + assert.equal(cockpitSubjectStepSec(1000, 0), 1); + // ...and a hidden tab's minutes as one late update. + assert.equal(cockpitSubjectStepSec(60_000, 500), 1.5); + assert.equal(cockpitSubjectStepSec(60_000, 0), 1); assert.equal(cockpitSubjectStepSec(-5, 500), 0); assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0); - assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1); + assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 1); }); test('cockpit camera clearance never falls below the rendered ground floor', () => { diff --git a/src/cockpitProgress.js b/src/cockpitProgress.js index 67a3be951c..0d9f38920e 100644 --- a/src/cockpitProgress.js +++ b/src/cockpitProgress.js @@ -30,13 +30,29 @@ const TONE_RANK = Object.freeze([ const stronger = (a, b) => TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a; -/** A label's width estimate (px): its longer line in small capitals. */ +/** + * Full-width glyphs (CJK ideographs and punctuation, kana, Hangul, full-width + * forms), each about 1 em wide. + */ +const WIDE_GLYPH = + /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꥠ-꥿가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u; + +/** One line's width in the label's 10 px type, 0.06 em apart (px). */ +function lineWidthPx(line) { + let wide = 0; + let narrow = 0; + for (const glyph of String(line ?? '')) + if (WIDE_GLYPH.test(glyph)) wide += 1; + else narrow += 1; + return wide * 10.6 + narrow * 6.4; +} + +/** + * A label's width estimate (px): its longer line, a full-width glyph at + * 10.6 px and any other at 6.4 px. + */ export function estimateProgressLabelPx(label) { - const longest = Math.max( - String(label?.text ?? '').length, - String(label?.detail ?? '').length, - ); - return longest * 6.4 + 8; + return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8; } /** diff --git a/src/cockpitProgress.test.mjs b/src/cockpitProgress.test.mjs index f1bd9d819b..5d5885cd2c 100644 --- a/src/cockpitProgress.test.mjs +++ b/src/cockpitProgress.test.mjs @@ -4,7 +4,10 @@ // the travelled part. import test from 'node:test'; import assert from 'node:assert/strict'; -import { cockpitProgressLayout } from './cockpitProgress.js'; +import { + cockpitProgressLayout, + estimateProgressLabelPx, +} from './cockpitProgress.js'; const tick = (at, label = null, tone = 'normal') => ({ at, tone, label }); const label = (text, priority, align = 'center', detail = '') => ({ @@ -142,3 +145,17 @@ test('a long run of calls still lays out, every one a tick or part of one', () = assert.ok(narrow.ticks.length < wide.ticks.length); assert.equal(wide.ticks.length, 60); }); + +test('a CJK stop name gets the width its full-width glyphs need', () => { + const text = '中央駅前広場東口'; // 8 full-width glyphs + // 10 px type, 0.06 em apart. + const needPx = text.length * (10 + 0.6); + const givenPx = estimateProgressLabelPx({ text, detail: '' }); + assert.ok( + givenPx >= needPx, + `${givenPx} px given, about ${needPx} px needed`, + ); + // Latin, and half-width katakana, keep the narrower estimate. + assert.equal(estimateProgressLabelPx({ text: 'CENTRAL' }), 7 * 6.4 + 8); + assert.equal(estimateProgressLabelPx({ text: 'カタカナ' }), 4 * 6.4 + 8); +}); diff --git a/src/cockpitSubjectProviders.js b/src/cockpitSubjectProviders.js index 88b91e62cb..bed39e6bca 100644 --- a/src/cockpitSubjectProviders.js +++ b/src/cockpitSubjectProviders.js @@ -146,8 +146,12 @@ function providerName(provider, order) { return `#${order}`; } -/** Why `provider` cannot be kept, or null. */ -function refusal(provider, kinds) { +/** + * Why `provider` cannot be kept, or null. Its worded members, read once here, + * go into `words` (`face`, `labels`, `look`) to seed its copy, so one that + * fails when read again cannot undo this check. + */ +function refusal(provider, kinds, words) { if (!isObject(provider)) return 'not an object'; if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind)) return 'malformed kind'; @@ -165,11 +169,14 @@ function refusal(provider, kinds) { typeof provider.isEntryAllowed !== 'function' ) return 'isEntryAllowed is not a function'; - if (!wordedNow(provider, 'entryFace', faceOf)) return 'malformed entry face'; - if (!wordedNow(provider, 'labels', labelsOf)) - return 'labels need view, exit and exitText'; - if (provider.look != null && !wordedNow(provider, 'look', lookOf)) - return 'look needs an aheadLabel'; + words.face = wordedNow(provider, 'entryFace', faceOf); + if (!words.face) return 'malformed entry face'; + words.labels = wordedNow(provider, 'labels', labelsOf); + if (!words.labels) return 'labels need view, exit and exitText'; + if (provider.look != null) { + words.look = wordedNow(provider, 'look', lookOf); + if (!words.look) return 'look needs an aheadLabel'; + } return null; } @@ -222,9 +229,10 @@ export function cockpitSubjectProviders( (Array.isArray(list) ? list : []).forEach((provider, order) => { let reason; let copy = null; + const words = { face: null, labels: null, look: null }; try { - reason = refusal(provider, kinds); - if (!reason) copy = keptProvider(provider, order); + reason = refusal(provider, kinds, words); + if (!reason) copy = keptProvider(provider, order, words); } catch { reason = 'a member threw when read'; } @@ -241,14 +249,15 @@ export function cockpitSubjectProviders( return Object.freeze(kept); } -/** The frozen copy the Cockpit keeps of a provider `refusal` passed. */ -function keptProvider(provider, order) { +/** + * The frozen copy the Cockpit keeps of a provider `refusal` passed, seeded + * with the worded members it checked. + */ +function keptProvider(provider, order, words) { // Worded members are read again on each use (see above); the last good // read stands in for one that is malformed or throws. - let face = wordedNow(provider, 'entryFace', faceOf); - let labels = wordedNow(provider, 'labels', labelsOf); + let { face, labels, look } = words; // On or off, and its rest pitch, as first read. - let look = wordedNow(provider, 'look', lookOf); const restPitchDeg = look?.restPitchDeg ?? 0; return Object.freeze({ kind: provider.kind, @@ -337,9 +346,9 @@ function candidateOf(raw) { * A `heightM` that is not finite or lies outside * COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null: * the eye then stands on the shared floor, or where it last stood while that - * is cold. The anchor is `'inertial'` only when asked for and the frame - * gives a speed; otherwise it is `'exact'`. An id is compared with `heldId` - * trimmed, as `cockpitSubjectCandidate` trims it. + * is cold. The anchor is `'inertial'` by default for a frame with a valid + * speed, and `'exact'` when asked for or with no speed. An id is compared + * with `heldId` trimmed, as `cockpitSubjectCandidate` trims it. * @param {unknown} raw What `read()` returned. * @param {string} heldId The subject the view holds. * @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg, diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index e93bdf41fb..e6eeb1ea57 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -336,7 +336,7 @@ function updateVessel(nowMs) { * gives none) and slew toward its heading. A frame that is null, malformed or * for another subject ends the view, as an aircraft tracked meanwhile does. * The update runs on the provider's `cameraIntervalMs` (0: every frame), and - * its rates advance by the time that interval spans (cockpitSubjectStepSec). + * its rates advance by the time since the last update (cockpitSubjectStepSec). */ function updateSubject(nowMs) { const provider = this.subjectProvider; @@ -366,7 +366,7 @@ function updateSubject(nowMs) { frame.longitude, ); // A frame with no height stands on the shared floor; while that is cold - // it keeps the height it last stood at. + // it keeps the last height it had, the entry frame's included. heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM; } if (!Number.isFinite(heightM)) { diff --git a/src/ui/cockpitController.js b/src/ui/cockpitController.js index 39881f5df4..00552532c7 100644 --- a/src/ui/cockpitController.js +++ b/src/ui/cockpitController.js @@ -735,8 +735,16 @@ export class CockpitViewController { publishCockpitSignals() { return publishCockpitSignals.call(this); } - pushCockpitSignal(key, tone, title, detail, target) { - return pushCockpitSignal.call(this, key, tone, title, detail, target); + pushCockpitSignal(key, tone, title, detail, target, options) { + return pushCockpitSignal.call( + this, + key, + tone, + title, + detail, + target, + options, + ); } dropCockpitSignal(key) { return dropCockpitSignal.call(this, key); diff --git a/src/ui/cockpitInstruments.js b/src/ui/cockpitInstruments.js index 62cb0e6ec0..d64890bd8d 100644 --- a/src/ui/cockpitInstruments.js +++ b/src/ui/cockpitInstruments.js @@ -257,6 +257,8 @@ function updateSubjectHud(info, nowMs, forceContext) { this.maybeRefreshRegionalBrief(info); this.showContextCard(false); const keys = new Set(); + // The view's rows are its current signals: each changes where it stands, + // so a changing one (an ETA) never pushes a steady one off the list. for (const signal of hud.signals) { const key = `subject:${signal.id}`; keys.add(key); @@ -265,6 +267,8 @@ function updateSubjectHud(info, nowMs, forceContext) { SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info', signal.title, signal.detail || signal.title, + null, + { inPlace: true }, ); } for (const key of this.subjectSignalKeys ?? []) diff --git a/src/ui/cockpitSignals.js b/src/ui/cockpitSignals.js index 54889a82d7..14e8cca528 100644 --- a/src/ui/cockpitSignals.js +++ b/src/ui/cockpitSignals.js @@ -39,17 +39,32 @@ export function publishCockpitSignals() { this.scheduleContextLayout(); } -export function pushCockpitSignal(key, tone, title, detail, target = null) { +/** + * Log a signal as the newest row, unless its key last said the same. + * @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a + * provider's, that changes where it stands rather than log a new row, and + * comes back if newer rows pushed it off the list. + */ +export function pushCockpitSignal( + key, + tone, + title, + detail, + target = null, + { inPlace = false } = {}, +) { if (!title || !detail) return; const signature = `${title}|${detail}|${target?.layerId || ''}|${target?.id || ''}`; - if (this.signalSignatures.get(key) === signature) return; - this.signalSignatures.set(key, signature); // A locale change words the signal again where it stands. - const shown = this.rewordingSignals - ? this.signalItems.find((item) => item.key === key) - : null; + const shown = + this.rewordingSignals || inPlace + ? this.signalItems.find((item) => item.key === key) + : null; + if (this.signalSignatures.get(key) === signature && (!inPlace || shown)) + return; + this.signalSignatures.set(key, signature); if (shown) { - Object.assign(shown, { title, detail }); + Object.assign(shown, { tone, title, detail }); this.publishCockpitSignals(); return; } diff --git a/src/ui/cockpitSubjectView.test.mjs b/src/ui/cockpitSubjectView.test.mjs index 63fffb0630..6c0fe249d4 100644 --- a/src/ui/cockpitSubjectView.test.mjs +++ b/src/ui/cockpitSubjectView.test.mjs @@ -585,7 +585,44 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it // A long stall (a hidden tab) moves it as one late update would. clock.advance(60_000); cockpit.update(); - assert.ok(Math.abs(cockpit.heading - 101) < 1e-6, 'at most 0.6 s'); + assert.ok(Math.abs(cockpit.heading - 110) < 1e-6, 'at most 1.5 s'); +}); + +test('an inertial subject drawn at 5 frames a second stays near its target', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + const SPEED_MPS = 30; + const startMs = 10_000; + const eastOf = (ms) => + LON + + (SPEED_MPS * (ms - startMs)) / + 1000 / + (111_320 * Math.cos((LAT * Math.PI) / 180)); + let nowMs = startMs; + ride.subject.frame = () => ({ + ...subjectProvider().subject.frame, + longitude: eastOf(nowMs), + speedMps: SPEED_MPS, + anchor: 'inertial', + }); + const { cockpit, shots } = fixture(t, { providers: [ride] }); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + for (let i = 0; i < 300; i += 1) { + clock.advance(200); + nowMs += 200; + cockpit.update(); + } + const target = Cesium.Cartesian3.fromDegrees( + eastOf(nowMs), + LAT, + FLOOR_M + 3.5, + ); + const gapM = Cesium.Cartesian3.distance(shots.at(-1).destination, target); + assert.ok( + gapM < 50, + `after 60 s the camera is ${gapM.toFixed(0)} m from the subject`, + ); }); test('an exact anchor sits on the subject, wherever the frame moves it', async (t) => { @@ -863,6 +900,32 @@ test('a floor that never comes ends the view after the bounded wait, releasing t assert.deepEqual(lastRelease(ride.calls), ['release', 'a1', false]); }); +test('a height the entry frame gave holds while later frames give none and the floor is cold', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + // The entry frame stands at FLOOR_M (heightM 400). + assert.equal(cockpit.enter(), true); + ride.subject.frame = { ...ride.subject.frame, heightM: null }; + for ( + let elapsed = 0; + elapsed < COCKPIT_GROUND_WAIT_TIMEOUT_MS + 1000; + elapsed += 100 + ) { + clock.advance(100); + cockpit.update(); + } + assert.equal( + cockpit.active, + true, + 'the view keeps the height its entry frame gave', + ); + assert.ok(shots.length > 0, 'the camera is placed'); + assert.ok(Math.abs(shotHeight(shots) - (FLOOR_M + 3.5)) < 0.01); +}); + test('an asynchronous hold that lands after entry was refused is released again', async (t) => { let heldId = null; const releases = []; @@ -942,6 +1005,41 @@ test('a provider’s labels, entry face and look follow a change of language', a ); }); +/** Labels that read well once, when the provider is checked, then throw. */ +const GOOD_LABELS = Object.freeze({ + view: 'Ride view', + exit: 'Exit ride view', + exitText: 'EXIT RIDE', + kicker: 'RIDE', +}); +const labelsOnce = () => { + let reads = 0; + return function labels() { + reads += 1; + if (reads > 1) throw new Error('word bundle unloaded'); + return GOOD_LABELS; + }; +}; + +test('labels that start throwing after the first read keep the first good words', () => { + const warned = []; + const [kept] = cockpitSubjectProviders( + [{ ...subjectProvider().definition, labels: labelsOnce() }], + { warn: (message) => warned.push(message) }, + ); + assert.ok(kept, 'the provider is kept'); + assert.deepEqual({ ...kept.labels }, GOOD_LABELS); +}); + +test('entering such a provider with no HUD kicker does not throw', async (t) => { + manualClock(t, 10_000); + const ride = subjectProvider({ labels: labelsOnce() }); + ride.subject.hud = { title: 'Example 12' }; + const { cockpit } = fixture(t, { providers: [ride] }); + cockpit.syncEntry(); + assert.doesNotThrow(() => cockpit.enter()); +}); + test('a read that throws ends the view once; a hud that throws keeps the last', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); @@ -1122,26 +1220,57 @@ test('a subject first seen together with a built-in one comes after it', async ( assert.equal(store.presence.entryKind, 'vessel'); }); +/** + * Every world position projects to (x, y): the scene query port projects + * through Cesium.SceneTransforms. + */ +function everythingAt(t, x, y) { + t.mock.method( + Cesium.SceneTransforms, + 'worldToWindowCoordinates', + (_scene, _position, result = new Cesium.Cartesian2()) => + Object.assign(result, { x, y }), + ); +} + test("a double-click on the selected vessel does not enter an application's subject", async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); ride.subject.candidate = null; - const { cockpit, store, viewer } = fixture(t, { + const { cockpit, store } = fixture(t, { providers: [ride], vessel: VESSEL, }); + everythingAt(t, 100, 100); cockpit.syncEntry(); + assert.equal(store.presence.entryKind, 'vessel'); // The application's subject is selected after the vessel: it takes entry. clock.advance(500); ride.subject.candidate = { id: 'a1', name: 'Example 12', selectedAt: 1 }; cockpit.syncEntry(); - assert.equal(cockpit.resolveEntryKind(), 'example-kind'); - // Every world position lands under the pointer, the vessel's sprite too. - viewer.scene.cartesianToCanvasCoordinates = (_position, result = {}) => - Object.assign(result, { x: 400, y: 300 }); - assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }), false); + assert.equal(store.presence.entryKind, 'example-kind'); + // The user double-clicks the vessel, still selected. + assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), false); await settle(); - assert.notEqual(store.presence.active, true); + assert.equal( + cockpit.subjectProvider ?? null, + null, + 'no provider view entered from a double-click on the vessel', + ); + assert.equal( + ride.calls.some(([name]) => name === 'hold'), + false, + 'the provider subject was not held', + ); +}); + +test('the same double-click on the vessel alone enters its bridge', async (t) => { + manualClock(t, 10_000); + const { cockpit, store } = fixture(t, { vessel: VESSEL }); + everythingAt(t, 100, 100); + cockpit.syncEntry(); + assert.equal(store.presence.entryKind, 'vessel'); + assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), true); }); test('a provider view with look turns with the arrow keys and words its readout', async (t) => { @@ -1188,3 +1317,59 @@ test('rows a HUD view no longer lists leave Live Signals', async (t) => { cockpit.update(); assert.ok(dropped.includes('subject:note')); }); + +test('a signal still listed stays in Live Signals while another one changes', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + const { cockpit } = fixture(t, { providers: [ride] }); + // The real Live Signals rows, not the fixture's recorder. + delete cockpit.pushCockpitSignal; + delete cockpit.dropCockpitSignal; + const hudWith = (minutes) => ({ + ...HUD, + signals: [ + { + id: 'doors', + tone: 'warning', + title: 'DOORS', + detail: 'door fault, car 2', + }, + { id: 'eta', title: 'NEXT', detail: `Central in ${minutes} min` }, + ], + }); + ride.subject.hud = hudWith(10); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + for (let minutes = 9; minutes >= 2; minutes -= 1) { + ride.subject.hud = hudWith(minutes); + clock.advance(1000); + cockpit.update(); + } + const keys = cockpit.signalItems.map((row) => row.key); + assert.ok( + keys.includes('subject:doors'), + `the warning the HUD still lists is shown (rows: ${keys.join(', ')})`, + ); + // The changing one is one row, worded as it reads now. + const etas = cockpit.signalItems.filter((row) => row.key === 'subject:eta'); + assert.deepEqual( + etas.map((row) => row.detail), + ['Central in 2 min'], + ); + // Rows pushed off the list by newer ones come back while still listed. + for (let i = 0; i < 5; i += 1) + cockpit.pushCockpitSignal(`other-${i}`, 'info', 'OTHER', `row ${i}`); + assert.equal( + cockpit.signalItems.some((row) => row.key.startsWith('subject:')), + false, + ); + clock.advance(1000); + cockpit.update(); + assert.deepEqual( + cockpit.signalItems + .map((row) => row.key) + .filter((key) => key.startsWith('subject:')) + .sort(), + ['subject:doors', 'subject:eta'], + ); +}); diff --git a/src/ui/cockpitTrackingController.js b/src/ui/cockpitTrackingController.js index 8e3868bb7d..314a8c1b38 100644 --- a/src/ui/cockpitTrackingController.js +++ b/src/ui/cockpitTrackingController.js @@ -516,7 +516,9 @@ function enterSubject(provider) { this.surfaceAcquiring = false; this.surfaceFallback = false; this.cockpitAnchorValid = false; - this.subjectHeightM = null; + // A height the entry frame gave is where the eye stands until a later frame + // or the warmed floor gives another. + this.subjectHeightM = frame.heightM; this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null; this.resetLook({ immediate: true }); this.active = true; From 5cc217dd1c37c6b3ea7cd351c00552e2a9007ffa Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Tue, 17 Nov 2026 19:34:33 +0400 Subject: [PATCH 05/18] Correct the Cockpit subject docs and release note The entry face icon must be one of the Material Symbols the page loads, and under reduced motion the veil stays: only its light streaks stop. --- changelog.d/1686-cockpit-subjects.md | 15 ++++++++------- docs/APPLICATION.md | 3 ++- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/changelog.d/1686-cockpit-subjects.md b/changelog.d/1686-cockpit-subjects.md index 715561e8e2..8fd069db31 100644 --- a/changelog.d/1686-cockpit-subjects.md +++ b/changelog.d/1686-cockpit-subjects.md @@ -3,10 +3,11 @@ heading and HUD (in the page's language, via `getLocale` and `onLocaleChange` from `./i18n`); the camera can follow it without the ground clamp, anchored exactly on it, and a generic HUD adds source rows, a - banner, a veil (off under reduced motion) and a bottom progress line. The - Rail and Transit layers expose read and hold APIs so a selected train or - vehicle can be ridden, and `./layers/rail/paths` is exported; that export - and the read APIs are experimental. `docs/APPLICATION.md` shows a minimal - provider. GEV itself registers none, and entry to the built-in aircraft, - satellite and vessel views is unchanged; a provider's subject takes entry - when it was selected after them (Denis Groshev, @ZloyS, #1686). + banner, a veil (its light streaks stop under reduced motion) and a bottom + progress line. The Rail and Transit layers expose read and hold APIs so a + selected train or vehicle can be ridden, and `./layers/rail/paths` is + exported; that export and the read APIs are experimental. + `docs/APPLICATION.md` shows a minimal provider. GEV itself registers none, + and entry to the built-in aircraft, satellite and vessel views is + unchanged; a provider's subject takes entry when it was selected after them + (Denis Groshev, @ZloyS, #1686). diff --git a/docs/APPLICATION.md b/docs/APPLICATION.md index 301ca53cd2..b1e81b4682 100644 --- a/docs/APPLICATION.md +++ b/docs/APPLICATION.md @@ -396,7 +396,8 @@ their `this`; one that throws or returns a promise is treated as having failed. What a method returns may carry getters: one that throws when read makes a candidate none, a frame malformed (the view ends) and a HUD view keep the last; a worded member (labels, entry face, look) that throws keeps its -last good words. +last good words. An entry face's `icon` must be one of the Material Symbols +`index.html` loads (`icon_names`); any other renders as its name. ```js import { getLocale, onLocaleChange } from 'gods-eye-view/i18n'; From ebf2686e2f19009434a5c15f7a2aa22515fcda63 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 00:51:07 +0400 Subject: [PATCH 06/18] Number the changelog fragment for #1786 --- ...t-ride-transit-rail.md => 1786-cockpit-ride-transit-rail.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename changelog.d/{0000-cockpit-ride-transit-rail.md => 1786-cockpit-ride-transit-rail.md} (95%) diff --git a/changelog.d/0000-cockpit-ride-transit-rail.md b/changelog.d/1786-cockpit-ride-transit-rail.md similarity index 95% rename from changelog.d/0000-cockpit-ride-transit-rail.md rename to changelog.d/1786-cockpit-ride-transit-rail.md index 284b570388..4e29e30d74 100644 --- a/changelog.d/0000-cockpit-ride-transit-rail.md +++ b/changelog.d/1786-cockpit-ride-transit-rail.md @@ -5,4 +5,4 @@ floor is known reports no height, so the view waits for the ground instead of standing on the ellipsoid. A train standing at a platform keeps the way it runs: GPS jitter of a few metres no longer turns the ride around - (German, @gekh, #0000). + (German, @gekh, #1786). From c2f73cdc047dce25bdfc59121b20199d2564183f Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 00:51:07 +0400 Subject: [PATCH 07/18] Add the changelog fragment for #1787 --- changelog.d/1787-cockpit-subject-camera-hud.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 changelog.d/1787-cockpit-subject-camera-hud.md diff --git a/changelog.d/1787-cockpit-subject-camera-hud.md b/changelog.d/1787-cockpit-subject-camera-hud.md new file mode 100644 index 0000000000..96eb5d6fb5 --- /dev/null +++ b/changelog.d/1787-cockpit-subject-camera-hud.md @@ -0,0 +1,8 @@ +- Keep an application's Cockpit subject steady: a height its entry frame gave + holds while the floor is still cold, so the view no longer ends; the camera + keeps up when the browser draws few frames (at 5 a second it fell 700 m + behind a 30 m/s subject in a minute); a provider's Live Signals rows change + where they stand, so a changing ETA no longer pushes a steady warning off + the list; progress labels give CJK, kana and Hangul names the width they + need; and labels, entry face and look keep the words checked at + registration when a later read fails (German, @gekh, #1787). From eb82842e0d5eba15ce8af8c7d24821ce807b8c55 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 17 Nov 2026 21:46:32 -0800 Subject: [PATCH 08/18] Name the world timeline's real-time speed Real-time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The speed control's first entry runs the world clock at real time, which 1× did not say beside 1 min/s, 1 h/s, 1 d/s and 1 wk/s. It now reads Real-time, translated in every catalog. --- changelog.d/XXXX-timeline-real-time.md | 1 + src/i18n/locales/ar.json | 1 + src/i18n/locales/de.json | 1 + src/i18n/locales/es.json | 1 + src/i18n/locales/fr.json | 1 + src/i18n/locales/he.json | 1 + src/i18n/locales/it.json | 1 + src/i18n/locales/ja.json | 1 + src/i18n/locales/pt.json | 1 + src/i18n/locales/ru.json | 1 + src/i18n/locales/sv.json | 1 + src/i18n/locales/uk.json | 1 + src/i18n/locales/zh-CN.json | 1 + src/i18n/locales/zh-Hant.json | 1 + src/ui/views/panels/WorldTimeline.vue | 2 +- 15 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog.d/XXXX-timeline-real-time.md diff --git a/changelog.d/XXXX-timeline-real-time.md b/changelog.d/XXXX-timeline-real-time.md new file mode 100644 index 0000000000..769a49f284 --- /dev/null +++ b/changelog.d/XXXX-timeline-real-time.md @@ -0,0 +1 @@ +- The world timeline's speed control names its real-time speed **Real-time** instead of `1×`, beside `1 min/s`, `1 h/s`, `1 d/s` and `1 wk/s` (Sameh Khamis, @samehkhamis, #XXXX). diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 092d56b5b5..a3e3957f7b 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -3847,6 +3847,7 @@ "1 wk/s": "أسبوع/ث", "Play speed": "سرعة التشغيل", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "مرّر أو اقرص للتكبير، واسحب للتنقل · انقر نقرًا مزدوجًا لرؤية الكل", + "Real-time": "الوقت الفعلي", "1 min/s": "دقيقة/ث", "Photo © {photographer}": "صورة © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "الرحلة المشتركة: لا بيانات واردة الآن — يُعرض آخر موضع معروف", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 4fb272f5e3..7a31f7310c 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -3487,6 +3487,7 @@ "1 wk/s": "1 Wo./s", "Play speed": "Wiedergabegeschwindigkeit", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Scrollen oder mit zwei Fingern zoomen, ziehen zum Verschieben · Doppelklick zeigt alles", + "Real-time": "Echtzeit", "1 min/s": "1 min/s", "Photo © {photographer}": "Foto © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Der geteilte Flug sendet gerade nicht – letzte bekannte Position wird gezeigt", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 51c9620487..511439532a 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -3577,6 +3577,7 @@ "1 wk/s": "1 sem/s", "Play speed": "Velocidad de reproducción", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Usa la rueda o pellizca para hacer zoom, arrastra para desplazarte · doble clic para verlo todo", + "Real-time": "Tiempo real", "1 min/s": "1 min/s", "Photo © {photographer}": "Foto © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "El vuelo compartido no está transmitiendo ahora; se muestra dónde se vio por última vez", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index a32d5848a3..117b8d7129 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -3577,6 +3577,7 @@ "1 wk/s": "1 sem/s", "Play speed": "Vitesse de lecture", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Faites défiler ou pincez pour zoomer, glissez pour vous déplacer · double-cliquez pour tout voir", + "Real-time": "Temps réel", "1 min/s": "1 min/s", "Photo © {photographer}": "Photo © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Le vol partagé n'émet pas actuellement — affichage de sa dernière position connue", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 2c667d78ec..16aabce453 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -3385,6 +3385,7 @@ "Bridge radar": "רדאר הגשר", "Reported voyage": "הפלגה שדווחה", "REPORTED VOYAGE": "הפלגה שדווחה", + "Real-time": "זמן אמת", "1 min/s": "דקה/שנ׳", "Photo © {photographer}": "צילום © {photographer}", "1 h/s": "שעה/שנ׳", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 3fec1221ae..8ab4346305 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -3577,6 +3577,7 @@ "1 wk/s": "1 sett/s", "Play speed": "Velocità di riproduzione", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Scorri o pizzica per lo zoom, trascina per spostarti · doppio clic per vedere tutto", + "Real-time": "Tempo reale", "1 min/s": "1 min/s", "Photo © {photographer}": "Foto © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Il volo condiviso non sta trasmettendo ora: viene mostrata l'ultima posizione nota", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index d888830101..49d45a921b 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -3397,6 +3397,7 @@ "1 wk/s": "1週間/秒", "Play speed": "再生速度", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "スクロールまたはピンチでズーム、ドラッグで移動 · ダブルクリックで全体表示", + "Real-time": "リアルタイム", "1 min/s": "1分/秒", "Photo © {photographer}": "写真 © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "共有されたフライトの位置情報は現在届いていません。最後に確認された位置を表示しています", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index fb8db96a34..c092ea9e8c 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -3577,6 +3577,7 @@ "1 wk/s": "1 sem/s", "Play speed": "Velocidade de reprodução", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Role ou use o gesto de pinça para dar zoom, arraste para percorrer · clique duplo para ver tudo", + "Real-time": "Tempo real", "1 min/s": "1 min/s", "Photo © {photographer}": "Foto © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "O voo compartilhado não está transmitindo agora — mostrando a última posição conhecida", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index bd2171f4ee..3eb475d768 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -3667,6 +3667,7 @@ "1 wk/s": "1 нед./с", "Play speed": "Скорость воспроизведения", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Прокрутите или сведите пальцы для масштаба, перетащите для перемещения · двойной щелчок — показать всё", + "Real-time": "Реальное время", "1 min/s": "1 мин/с", "Photo © {photographer}": "Фото © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Рейс по ссылке сейчас не передаёт данные — показано последнее известное положение", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 480c92ca35..4a1a2e1fdd 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -3479,6 +3479,7 @@ "Bridge radar": "Bryggradar", "Reported voyage": "Angiven resa", "REPORTED VOYAGE": "ANGIVEN RESA", + "Real-time": "Realtid", "1 min/s": "1 min/s", "Photo © {photographer}": "Foto © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Den delade flygningen rapporterar inte just nu – visar senast kända position", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index afd2ec608e..fedb158454 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -3667,6 +3667,7 @@ "1 wk/s": "1 тиж/с", "Play speed": "Швидкість відтворення", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Прокрутіть або зведіть пальці для масштабу, перетягніть для переміщення · подвійне клацання — показати все", + "Real-time": "Реальний час", "1 min/s": "1 хв/с", "Photo © {photographer}": "Фото © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "Рейс за посиланням зараз не передає даних — показано останнє відоме місце", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 4d0b3c0de0..394148c70e 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -3397,6 +3397,7 @@ "1 wk/s": "1 周/秒", "Play speed": "播放速度", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "滚动或双指缩放,拖动以移动 · 双击查看全部", + "Real-time": "实时", "1 min/s": "1 分钟/秒", "Photo © {photographer}": "照片 © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "分享的航班目前无位置更新——显示其最后出现的位置", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index c10cc827f3..2d7e5b00cb 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -3397,6 +3397,7 @@ "1 wk/s": "1 週/秒", "Play speed": "播放速度", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "滾動或雙指縮放,拖動以移動 · 雙擊查看全部", + "Real-time": "實時", "1 min/s": "1 分鐘/秒", "Photo © {photographer}": "照片 © {photographer}", "The shared flight isn't reporting now — showing where it was last seen": "分享的航班目前無位置更新——顯示其最後出現的位置", diff --git a/src/ui/views/panels/WorldTimeline.vue b/src/ui/views/panels/WorldTimeline.vue index 054e4370d6..fe0a62e391 100644 --- a/src/ui/views/panels/WorldTimeline.vue +++ b/src/ui/views/panels/WorldTimeline.vue @@ -20,7 +20,7 @@ import UiSelect from '../../kit/UiSelect.js'; const store = useWorldTimeStore(); const { time, speed } = storeToRefs(store); const speeds = computed(() => [ - { value: 'real', label: '1×' }, + { value: 'real', label: t('Real-time') }, { value: 'minute', label: t('1 min/s') }, { value: 'hour', label: t('1 h/s') }, { value: 'day', label: t('1 d/s') }, From 747082a5eb4f064c33e7c2aac300b1c86a805069 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 17 Nov 2026 21:46:37 -0800 Subject: [PATCH 09/18] Name the changelog entry for its pull request number --- .../{XXXX-timeline-real-time.md => 1805-timeline-real-time.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/{XXXX-timeline-real-time.md => 1805-timeline-real-time.md} (100%) diff --git a/changelog.d/XXXX-timeline-real-time.md b/changelog.d/1805-timeline-real-time.md similarity index 100% rename from changelog.d/XXXX-timeline-real-time.md rename to changelog.d/1805-timeline-real-time.md From ee5a6ab317deb49e88181b331642417aa3992684 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 14:32:36 +0400 Subject: [PATCH 10/18] Turn a train that backs away steadily, however small each step The direction now follows how far a train has come back from the farthest point it reached, so a slow reversal of under 15 m per report still turns it, while GPS jitter around one spot does not. Rail policy takes the 15 m figure from pathBinding instead of repeating it. --- docs/CURRENT-STATE.md | 5 ++- src/layers/rail/pathBinding.js | 46 +++++++++++++++------ src/layers/rail/pathBinding.test.mjs | 61 ++++++++++++++++++++++++++++ src/layers/rail/policy.js | 3 +- 4 files changed, 100 insertions(+), 15 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f2a437aea0..95b73b39ec 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2792,8 +2792,9 @@ the playback fraction), not the newest report's, and null while that floor is unknown, also far above the ground, where such a vehicle is drawn on the ellipsoid. Rail's `path.direction` is the way the drawn train runs: once playback has placed it, a report that runs back turns it only when playback -reaches that report, and a step of at most 15 m between two reports (a standing -train's GPS jitter) keeps the direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, +reaches that report. A train turns once it is 15 m back from the farthest point +it reached, however slowly it backs, so a standing train's GPS jitter keeps the +direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, `src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, `src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests cover them. diff --git a/src/layers/rail/pathBinding.js b/src/layers/rail/pathBinding.js index a432095b7a..4afe9b7872 100644 --- a/src/layers/rail/pathBinding.js +++ b/src/layers/rail/pathBinding.js @@ -48,18 +48,35 @@ export function pathWindowM(dtMs) { } /** - * Arc moved between two reports before it says which way a train runs (m). - * A standing train's GPS jitter, a few metres back and forth, stays under it - * (the same parked-train jitter as FOLLOW_MIN_MOVE_M, policy.js) and keeps - * the direction learnt. + * Arc a train must move before that says which way it runs (m): a standing + * train's GPS jitter, back and forth, stays within it. */ -const DIRECTION_MIN_M = 15; +export const DIRECTION_MIN_M = 15; -/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */ -function directionOf(step, known) { - return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M - ? Math.sign(step) - : known; +/** + * Track one more arc position of a train. `turn.s` is the farthest arc it + * has reached the way it runs (where it was first seen while that is + * unknown); it turns once it is DIRECTION_MIN_M or more back from there, + * however small each step. + * @param {number} direction +1, -1 or 0. + * @param {{s: number}} turn Updated in place. + * @param {number} s + * @returns {number} The direction now. + */ +function steer(direction, turn, s) { + if (!Number.isFinite(s)) return direction; + if (!Number.isFinite(turn.s)) { + turn.s = s; + return direction; + } + const step = s - turn.s; + if (direction && step * direction >= 0) { + turn.s = s; + return direction; + } + if (Math.abs(step) < DIRECTION_MIN_M) return direction; + turn.s = s; + return Math.sign(step); } function createBinding(shapeIndex, path, via, s, fix) { @@ -77,6 +94,9 @@ function createBinding(shapeIndex, path, via, s, fix) { */ direction: 0, directionPlayed: false, + /** How far the reports and the played segments have run (steer). */ + reportTurn: { s }, + playTurn: { s: NaN }, /** Arc and time of the newest report. */ fixS: s, fixT: fix.t, @@ -165,7 +185,7 @@ export function followFix(binding, fix) { ); if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false; if (!binding.directionPlayed) - binding.direction = directionOf(hit.s - binding.fixS, binding.direction); + binding.direction = steer(binding.direction, binding.reportTurn, hit.s); binding.fixS = hit.s; binding.fixT = fix.t; binding.fixLat = fix.lat; @@ -258,7 +278,9 @@ export function placeOnPath(binding, sample, segment, out) { cache.sTo = sTo; cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo); if (cache.ok) { - binding.direction = directionOf(sTo - sFrom, binding.direction); + const turn = binding.playTurn; + binding.direction = steer(binding.direction, turn, sFrom); + binding.direction = steer(binding.direction, turn, sTo); if (binding.direction) binding.directionPlayed = true; } } diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index e257fb86da..2e01da82c9 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -323,3 +323,64 @@ test('GPS jitter in the newest reports before playback keeps the direction', () }); assert.deepEqual(learnt, [1, 1, 1, 1], 'from the newest reports'); }); + +/** The direction after each played segment, `[fromM, toM]` 15 s apart. */ +function playDirections(binding, steps) { + return steps.map(([fromM, toM], seq) => { + const { sample, segment } = playback( + seq, + seq + 1, + fix(seq * 15_000, fromM, 0), + fix((seq + 1) * 15_000, toM, 0), + 0.5, + ); + assert.ok(placeOnPath(binding, sample, segment, {})); + return binding.direction; + }); +} + +test('a train that moves under 15 m a report still tells its direction', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + // It sets off slowly, runs east, then backs out 10 m a report. + const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); + const learnt = [1010, 1020, 1600, 1590, 1580, 1570].map((eastM, i) => { + assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); + return reports.direction; + }); + assert.deepEqual(learnt, [0, 1, 1, 1, -1, -1], 'from the newest reports'); + const played = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.deepEqual( + playDirections(played, [ + [1000, 1600], + [1600, 1590], + [1590, 1580], + [1580, 1570], + ]), + [1, 1, -1, -1], + 'from the played-back segments', + ); +}); + +test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); + const learnt = [1600, 1588, 1600, 1586, 1599, 1587].map((eastM, i) => { + assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); + return reports.direction; + }); + assert.deepEqual(learnt, [1, 1, 1, 1, 1, 1], 'from the newest reports'); + const played = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.deepEqual( + playDirections(played, [ + [1000, 1600], + [1600, 1588], + [1588, 1600], + [1600, 1586], + [1586, 1599], + ]), + [1, 1, 1, 1, 1], + 'from the played-back segments', + ); +}); diff --git a/src/layers/rail/policy.js b/src/layers/rail/policy.js index ecb3121760..57d8598459 100644 --- a/src/layers/rail/policy.js +++ b/src/layers/rail/policy.js @@ -16,6 +16,7 @@ import { import { displayMotion } from '../transit/movement.js'; import { FIX_FLAGS, readFix } from '../../data/contactPlayback.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; +import { DIRECTION_MIN_M } from './pathBinding.js'; import { stopClock, stopLateMinutes, @@ -295,7 +296,7 @@ export function playbackModeFor(railMode) { } /** Two reports closer than this are one place: a parked train's jitter (m). */ -export const FOLLOW_MIN_MOVE_M = 15; +export const FOLLOW_MIN_MOVE_M = DIRECTION_MIN_M; const lastFix = {}; const priorFix = {}; From a72c0ba2371ff558b578547f6a1f7c8291d44c4c Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 14:32:45 +0400 Subject: [PATCH 11/18] Fix tone-only signal changes, the first anchor step, row order and emoji widths - A provider's Live Signals row now changes when only its tone does; fields are compared one by one instead of through a joined signature. - The frame that first sets an inertial subject's anchor puts it on the subject, so the view no longer jumps ahead after waiting for the floor. - The subject HUD drops vanished rows before it adds new ones, so TRACK ACQUIRED and a steady warning keep their place. - Progress labels give astral-plane glyphs such as emoji at least main's width, so they are not clipped. --- .../1787-cockpit-subject-camera-hud.md | 13 ++- docs/CURRENT-STATE.md | 9 +- src/cockpitProgress.js | 18 ++- src/cockpitProgress.test.mjs | 19 +++ src/ui/cockpitCamera.js | 7 +- src/ui/cockpitInstruments.js | 17 ++- src/ui/cockpitSignals.js | 10 +- src/ui/cockpitSubjectView.test.mjs | 109 ++++++++++++++++++ 8 files changed, 171 insertions(+), 31 deletions(-) diff --git a/changelog.d/1787-cockpit-subject-camera-hud.md b/changelog.d/1787-cockpit-subject-camera-hud.md index 96eb5d6fb5..0e860b64f4 100644 --- a/changelog.d/1787-cockpit-subject-camera-hud.md +++ b/changelog.d/1787-cockpit-subject-camera-hud.md @@ -1,8 +1,9 @@ - Keep an application's Cockpit subject steady: a height its entry frame gave holds while the floor is still cold, so the view no longer ends; the camera - keeps up when the browser draws few frames (at 5 a second it fell 700 m - behind a 30 m/s subject in a minute); a provider's Live Signals rows change - where they stand, so a changing ETA no longer pushes a steady warning off - the list; progress labels give CJK, kana and Hangul names the width they - need; and labels, entry face and look keep the words checked at - registration when a later read fails (German, @gekh, #1787). + keeps up when the browser draws few frames (at 5 a second, one updated every + frame fell 700 m behind a 30 m/s subject in a minute); a provider's Live + Signals rows change where they stand, their tone included, and rows it drops + leave before new ones come in, so a changing ETA or a replaced row no longer + pushes a steady warning off the list; progress labels give CJK, kana and + Hangul names the width they need; and labels, entry face and look keep the + words checked at registration when a later read fails (German, @gekh, #1787). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 67d063bd73..ff6762f4c5 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2754,17 +2754,20 @@ exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs camera every rendered frame. Each update turns, eases and moves the view by the time since the last one, so it keeps up when the browser draws few frames; an update more than a second past its interval (a hidden tab) moves it as one a -second late would. A frame that is null, malformed or for another +second late would, and the update that first places the camera (after entry or +a floor wait) stands its anchor on the subject. A frame that is null, malformed or for another subject ends the view (`restoreTracking: false`), as an aircraft tracked meanwhile and the provider's layer turning off do; the exit control asks the provider to restore its subject. The generic HUD shows the provider's kicker, title, meta line, speed with its unit and tag, readout cards, always-visible source rows, banner, route card and Live Signals rows (each changes where it -stands, so a changing ETA never pushes a steady warning off the list), a veil that darkens the +stands, its tone included, so a changing ETA never pushes a steady warning off +the list; rows the view no longer lists leave before new ones come in), a veil that darkens the picture under the HUD (with passing light streaks, which stop under reduced motion), arrow-key look-around when the provider asks for it, and a progress line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, -labels never overlap, a full-width CJK, kana or Hangul glyph given about 1 em). Core translates none of the provider's text: a host +labels never overlap and get about 1 em for each full-width CJK, kana or Hangul +glyph and a little more for an emoji or other astral glyph). Core translates none of the provider's text: a host words it for the page's language (`gods-eye-view/i18n`: `getLocale`, `onLocaleChange`). Its entry face, labels and look may be functions, read again when they are shown and on a change of language, as the diff --git a/src/cockpitProgress.js b/src/cockpitProgress.js index 0d9f38920e..c8114d3e84 100644 --- a/src/cockpitProgress.js +++ b/src/cockpitProgress.js @@ -30,27 +30,25 @@ const TONE_RANK = Object.freeze([ const stronger = (a, b) => TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a; -/** - * Full-width glyphs (CJK ideographs and punctuation, kana, Hangul, full-width - * forms), each about 1 em wide. - */ +/** Full-width glyphs (CJK, kana, Hangul, full-width forms): about 1 em each. */ const WIDE_GLYPH = /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꥠ-꥿가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u; -/** One line's width in the label's 10 px type, 0.06 em apart (px). */ +/** + * One line's width (px) in `.cockpit-progress-label` type (cockpitSubject.css: + * 10 px, 0.06 em spacing): 10.6 px a full-width glyph and 6.4 px each UTF-16 + * unit of any other, so an emoji or other astral glyph gets 12.8 px. + */ function lineWidthPx(line) { let wide = 0; let narrow = 0; for (const glyph of String(line ?? '')) if (WIDE_GLYPH.test(glyph)) wide += 1; - else narrow += 1; + else narrow += glyph.length; return wide * 10.6 + narrow * 6.4; } -/** - * A label's width estimate (px): its longer line, a full-width glyph at - * 10.6 px and any other at 6.4 px. - */ +/** A label's width estimate (px): its longer line and 8 px of padding. */ export function estimateProgressLabelPx(label) { return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8; } diff --git a/src/cockpitProgress.test.mjs b/src/cockpitProgress.test.mjs index 5d5885cd2c..e05f3fe0ff 100644 --- a/src/cockpitProgress.test.mjs +++ b/src/cockpitProgress.test.mjs @@ -159,3 +159,22 @@ test('a CJK stop name gets the width its full-width glyphs need', () => { assert.equal(estimateProgressLabelPx({ text: 'CENTRAL' }), 7 * 6.4 + 8); assert.equal(estimateProgressLabelPx({ text: 'カタカナ' }), 4 * 6.4 + 8); }); + +test('emoji and other astral glyphs in a progress label get at least 1 em each', () => { + // About 1 em in 10 px type, 0.06 em apart. + const emPx = 10 + 0.6; + for (const [text, needPx] of [ + ['🚉🚆🚇🚋', 4 * emPx], + ['🚆'.repeat(8), 8 * emPx], + // Supplementary kana, outside the full-width ranges. + ['𛀁𛀂', 2 * emPx], + // Mixed: four emoji, a space and two full-width glyphs. + ['🚆🚇🚌🚕 乗換', 4 * emPx + 6.4 + 2 * emPx], + ]) { + const givenPx = estimateProgressLabelPx({ text, detail: '' }); + assert.ok( + givenPx >= needPx + 8, + `${text}: ${givenPx} px given, about ${needPx} px needed`, + ); + } +}); diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index e6eeb1ea57..feb7734798 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -459,7 +459,10 @@ function updateSubject(nowMs) { * Aircraft pass none and look along the heading at the profile pitch. */ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { - if (!this.cockpitAnchorValid) { + // The update that first sets the anchor stands it on the target: the time + // before it (an entry, a floor wait) moved nothing, so it has no step. + const anchoring = !this.cockpitAnchorValid; + if (anchoring) { this.cockpitAnchor = clone(target); this.cockpitAnchorValid = true; this.subjectLiftM = null; @@ -485,7 +488,7 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { : 0; const groundClamp = info.groundClamp !== false; - if (info.stale || info.anchor === 'exact') { + if (anchoring || info.stale || info.anchor === 'exact') { // A feed backoff has no authoritative velocity epoch to advance from. // Hold the cockpit on the exact layer-rendered position so the camera // cannot coast away while the icon correctly remains fixed. diff --git a/src/ui/cockpitInstruments.js b/src/ui/cockpitInstruments.js index d64890bd8d..cf3cea895d 100644 --- a/src/ui/cockpitInstruments.js +++ b/src/ui/cockpitInstruments.js @@ -256,24 +256,23 @@ function updateSubjectHud(info, nowMs, forceContext) { this.updateLocalPosition(info); this.maybeRefreshRegionalBrief(info); this.showContextCard(false); - const keys = new Set(); + const keys = new Set(hud.signals.map(({ id }) => `subject:${id}`)); + // Rows the view no longer lists leave first, so new ones take their + // places rather than push a listed one (or TRACK ACQUIRED) off. + for (const key of this.subjectSignalKeys ?? []) + if (!keys.has(key)) this.dropCockpitSignal(key); + this.subjectSignalKeys = keys; // The view's rows are its current signals: each changes where it stands, // so a changing one (an ETA) never pushes a steady one off the list. - for (const signal of hud.signals) { - const key = `subject:${signal.id}`; - keys.add(key); + for (const signal of hud.signals) this.pushCockpitSignal( - key, + `subject:${signal.id}`, SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info', signal.title, signal.detail || signal.title, null, { inPlace: true }, ); - } - for (const key of this.subjectSignalKeys ?? []) - if (!keys.has(key)) this.dropCockpitSignal(key); - this.subjectSignalKeys = keys; } } diff --git a/src/ui/cockpitSignals.js b/src/ui/cockpitSignals.js index 14e8cca528..abfcfd12fa 100644 --- a/src/ui/cockpitSignals.js +++ b/src/ui/cockpitSignals.js @@ -54,7 +54,15 @@ export function pushCockpitSignal( { inPlace = false } = {}, ) { if (!title || !detail) return; - const signature = `${title}|${detail}|${target?.layerId || ''}|${target?.id || ''}`; + // Each field on its own, so no title and detail read as another pair; an + // in-place row also changes with its tone alone. + const signature = JSON.stringify([ + title, + detail, + target?.layerId || '', + target?.id || '', + inPlace ? tone : '', + ]); // A locale change words the signal again where it stands. const shown = this.rewordingSignals || inPlace diff --git a/src/ui/cockpitSubjectView.test.mjs b/src/ui/cockpitSubjectView.test.mjs index 6c0fe249d4..92a7a9b2eb 100644 --- a/src/ui/cockpitSubjectView.test.mjs +++ b/src/ui/cockpitSubjectView.test.mjs @@ -625,6 +625,55 @@ test('an inertial subject drawn at 5 frames a second stays near its target', asy ); }); +for (const [intervalMs, waitMs] of [ + [0, 1000], + [500, 2000], +]) { + test(`an inertial subject's first camera update after a ${waitMs} ms floor wait (interval ${intervalMs} ms) stands on it`, async (t) => { + const startMs = 10_000; + const clock = manualClock(t, startMs); + const SPEED_MPS = 30; + const mPerDegLon = 111_320 * Math.cos(Cesium.Math.toRadians(LAT)); + const eastOf = () => + LON + (SPEED_MPS * (performance.now() - startMs)) / 1000 / mPerDegLon; + const ride = subjectProvider({ cameraIntervalMs: intervalMs }); + const base = ride.subject.frame; + ride.subject.frame = () => ({ + ...base, + heightM: null, + longitude: eastOf(), + speedMps: SPEED_MPS, + anchor: 'inertial', + eye: { ...base.eye, forwardM: 0 }, + }); + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + const before = shots.length; + const stepMs = intervalMs || 100; + for (let waited = stepMs; waited < waitMs; waited += stepMs) { + clock.advance(stepMs); + cockpit.update(); + } + assert.equal( + shots.length, + before, + 'no camera update while the floor is cold', + ); + setFloor(FLOOR_M); + clock.advance(stepMs); + cockpit.update(); + const shot = Cesium.Cartographic.fromCartesian(shots[before].destination); + const leadM = + (Cesium.Math.toDegrees(shot.longitude) - eastOf()) * mPerDegLon; + assert.ok( + Math.abs(leadM) < 1, + `the first camera update leads the subject by ${leadM.toFixed(2)} m`, + ); + }); +} + test('an exact anchor sits on the subject, wherever the frame moves it', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); @@ -1373,3 +1422,63 @@ test('a signal still listed stays in Live Signals while another one changes', as ['subject:doors', 'subject:eta'], ); }); + +test('a Live Signals row whose tone alone changes takes the new tone', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + const { cockpit } = fixture(t, { providers: [ride] }); + delete cockpit.pushCockpitSignal; + delete cockpit.dropCockpitSignal; + const hudWith = (tone) => ({ + ...HUD, + signals: [ + { id: 'doors', tone, title: 'DOORS', detail: 'door fault, car 2' }, + ], + }); + const doorsTone = () => + cockpit.signalItems.find((row) => row.key === 'subject:doors').tone; + ride.subject.hud = hudWith('normal'); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + const tones = [doorsTone()]; + for (const tone of ['warning', 'normal']) { + ride.subject.hud = hudWith(tone); + clock.advance(1000); + cockpit.update(); + tones.push(doorsTone()); + } + assert.deepEqual(tones, ['info', 'warning', 'info']); +}); + +test('rows a HUD view replaces leave before new ones push a listed one off', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + const { cockpit } = fixture(t, { providers: [ride] }); + delete cockpit.pushCockpitSignal; + delete cockpit.dropCockpitSignal; + const row = (id, tone) => ({ + id, + tone, + title: id.toUpperCase(), + detail: `row ${id}`, + }); + ride.subject.hud = { + ...HUD, + signals: [row('w', 'warning'), row('a'), row('b'), row('c')], + }; + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + assert.ok(cockpit.signalItems.some((item) => item.key === 'track')); + ride.subject.hud = { + ...HUD, + signals: [row('w', 'warning'), row('a'), row('d'), row('e')], + }; + clock.advance(1000); + cockpit.update(); + const keys = cockpit.signalItems.map((item) => item.key); + assert.deepEqual( + [...keys].sort(), + ['subject:a', 'subject:d', 'subject:e', 'subject:w', 'track'], + `rows right after the change: ${keys.join(', ')}`, + ); +}); From df4d76384c4715801ac4f99a6a538d0fa85b4f9c Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:07:06 +0400 Subject: [PATCH 12/18] Tidy the Rail and Transit ride fixes after review - A train first seen standing takes its direction from the operator's course, not from a course drawn out of GPS jitter. - Moving a hold to another vehicle releases the first one the same way as ending the hold. - repaint always goes through placeSample, which hides the held vehicle and puts it on its current segment, so setShown is no longer exported. - Tests cover the icon right after a hold, a segment with one known floor, a known floor at 0 m and selection by click after the layer comes back; shared helpers replace repeated setup. - Comments, CURRENT-STATE and the release note say what the code does without internal figures. --- changelog.d/1786-cockpit-ride-transit-rail.md | 11 +- docs/CURRENT-STATE.md | 20 +-- src/layers/rail/cockpitSubject.js | 17 +- src/layers/rail/cockpitSubject.test.mjs | 33 ++++ src/layers/rail/pathBinding.test.mjs | 37 ++--- src/layers/transit/cockpitSubject.js | 34 ++-- src/layers/transit/lifecycle.test.mjs | 146 +++++++++++++++--- src/layers/transit/rendering.js | 1 - 8 files changed, 209 insertions(+), 90 deletions(-) diff --git a/changelog.d/1786-cockpit-ride-transit-rail.md b/changelog.d/1786-cockpit-ride-transit-rail.md index 4e29e30d74..995e0b491e 100644 --- a/changelog.d/1786-cockpit-ride-transit-rail.md +++ b/changelog.d/1786-cockpit-ride-transit-rail.md @@ -1,8 +1,5 @@ -- Fix rides on a Rail train or Transit vehicle for an application's Cockpit - subjects. A held parked vehicle no longer leaves its icon drawn under the - view, and turning Transit off ends a hold, so the vehicle shows again when - the layer is back on. A train or vehicle drawn on the ellipsoid while no - floor is known reports no height, so the view waits for the ground instead - of standing on the ellipsoid. A train standing at a platform keeps the way - it runs: GPS jitter of a few metres no longer turns the ride around +- Fix application Cockpit rides on Rail trains and Transit vehicles: a held + parked vehicle no longer leaves its icon under the view, turning Transit off + ends a hold, a view waits for the ground instead of standing on the + ellipsoid, and GPS jitter at a platform no longer turns a ride around (German, @gekh, #1786). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 95b73b39ec..d83e762add 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2769,7 +2769,7 @@ HUD view is. The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, which way it runs (`pathBinding.js` learns it), its rail height (null while -no floor is known and it is drawn on the ellipsoid), speed as reported or +no floor is known), speed as reported or derived, position source, feed credit and stops, and `selectedAtMs`, when the user last selected it by a click or `focusTrain`, even again; null after a deselection and for a train only a hold selected), @@ -2789,15 +2789,17 @@ view. Turning the layer off ends the hold. Its snapshot's `position.groundHeightM` is the floor where playback draws it (the drawn marker's height while it is placed, else its segment's two reports' floors at the playback fraction), not the newest report's, and null while that floor is -unknown, also far above the ground, where such a vehicle is drawn on the -ellipsoid. Rail's `path.direction` is the way the drawn train runs: once -playback has placed it, a report that runs back turns it only when playback -reaches that report. A train turns once it is 15 m back from the farthest point -it reached, however slowly it backs, so a standing train's GPS jitter keeps the -direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, +unknown, also while the camera is too high for the layer to sample the ground +and such a vehicle is drawn on the ellipsoid. Rail's `path.direction` is the +way the drawn train runs: once playback has placed it, a report that runs back +turns it only when playback starts the segment to that report. A train turns +once it has backed away from the farthest point it reached by more than a +standing train's GPS jitter, however slowly it backs, so that jitter keeps the +direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal +provider. `src/ui/cockpitSubjectView.test.mjs`, `src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, -`src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests -cover them. +`src/layers/rail/cockpitSubject.test.mjs`, `src/layers/rail/pathBinding.test.mjs` +and the Transit lifecycle tests cover them. ## Context coordination diff --git a/src/layers/rail/cockpitSubject.js b/src/layers/rail/cockpitSubject.js index 286160d3aa..1d9c02cb39 100644 --- a/src/layers/rail/cockpitSubject.js +++ b/src/layers/rail/cockpitSubject.js @@ -173,14 +173,16 @@ export function createRailCockpitSubject({ /** * Which way the train runs along its shape: as its binding learnt it from - * successive reports, else from its drawn course against the line's - * bearing there; 0 while neither tells. + * successive reports, else from its reported bearing against the line's + * bearing there; 0 while neither tells. Not the drawn course: until the + * binding tells, the train has not moved past GPS jitter, and a course + * drawn between such reports is that jitter. */ function directionOf(entry) { const binding = entry.path; if (binding.direction === 1 || binding.direction === -1) return binding.direction; - const course = finiteOrNull(entry.courseDeg); + const course = finiteOrNull(entry.record?.bearing); const point = pointAtS(binding.path, binding.drawS, scratch); if (course === null || !Number.isFinite(point?.bearingDeg)) return 0; const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180); @@ -205,11 +207,12 @@ export function createRailCockpitSubject({ finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat; position.longitude = finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon; - // Quality 0 is the ellipsoid a train is drawn on while no floor is - // known: no height, so a view waits for the surface. + const quality = Number.isFinite(drawn?.q) ? drawn.q : 0; + // Quality 0: no floor known here, so no height; a view waits for the + // surface. position.railHeightM = - Number.isFinite(drawn?.h) && drawn.q > 0 ? drawn.h - liftM : null; - position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0; + quality > 0 && Number.isFinite(drawn.h) ? drawn.h - liftM : null; + position.heightQuality = quality; position.atMs = finiteOrNull(drawn?.at); let path = null; diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs index c8c764aad3..08bf66d15c 100644 --- a/src/layers/rail/cockpitSubject.test.mjs +++ b/src/layers/rail/cockpitSubject.test.mjs @@ -151,6 +151,39 @@ test('a train drawn on an unknown floor reports no rail height', async (t) => { ); }); +test('a train on a known floor at sea level reports a rail height of 0 m', async (t) => { + const app = await onTheLine(t, { + ground: { ...WARM_GROUND, cachedGroundFloor: () => 0 }, + }); + app.parts().selection.selectTrain(T1); + const { position } = app.layer.getSelectedTrain(); + assert.ok(position.heightQuality > 0, 'the floor is known'); + assert.equal(position.railHeightM, 0, 'a height, not none'); +}); + +test('a train first seen standing takes no direction from its GPS jitter', async (t) => { + // Neither reports 13 m apart nor the course drawn between them say which way + // it runs; an operator's bearing does. + const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON }); + let jitterM = 0; + app.feeds.set('mbta-rail', () => [ + train('T1', LAT, LON0 + (1000 + jitterM) / KX), + train('T2', LAT, LON0 + (3000 + jitterM) / KX, { bearing: 270 }), + ]); + await app.enable(); + const seen = []; + for (const next of [13, 0, 13, 0, 13, 0]) { + jitterM = next; + app.run(RAIL_POLL_MS); + await app.poll(); + app.parts().selection.selectTrain(T1); + const standing = app.layer.getSelectedTrain().path.direction; + app.parts().selection.selectTrain(T2); + seen.push([standing, app.layer.getSelectedTrain().path.direction]); + } + assert.deepEqual(seen, Array(6).fill([0, -1])); +}); + test('a snapshot read again while nothing changed is the one read before', async (t) => { let list = stopList('Alpha', 'Bravo', 'Charlie'); const app = await onTheLine(t, { diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index 2e01da82c9..6dcc9fab99 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -209,8 +209,8 @@ test('a binding learns which way its train runs, and keeps it through a stop', ( assert.equal(along.direction, 0, 'one report tells no direction'); assert.ok(followFix(along, fix(10_000, 700, 0))); assert.equal(along.direction, 1); - // Standing at a stop, its reports jitter back a few metres: it keeps what - // it learnt. + // Standing at a stop, its reports jitter back 10 m: it keeps what it + // learnt. assert.ok(followFix(along, fix(20_000, 690, 0))); assert.equal(along.direction, 1); const against = bindTrainPath(p, ids, fix(0, 1500, 0)); @@ -269,33 +269,22 @@ test('jitter segments played back at a standing train keep the direction it lear const ids = { tripId: 'full', routeId: 'main' }; const binding = bindTrainPath(p, ids, fix(0, 1000, 0)); assert.ok(followFix(binding, fix(15_000, 1600, 0))); - // Playback runs the train east, 1000 m -> 1600 m: direction +1. - const out = {}; let seq = 0; const play = (fromM, toM, t0) => { - const segment = { - from: { seq, ...fix(t0, fromM, 0) }, - to: { seq: seq + 1, ...fix(t0 + 15_000, toM, 0) }, - }; - assert.ok( - placeOnPath( - binding, - { fromSeq: seq, toSeq: seq + 1, fraction: 0.5 }, - segment, - out, - ), + const { sample, segment } = playback( + seq, + seq + 1, + fix(t0, fromM, 0), + fix(t0 + 15_000, toM, 0), + 0.5, ); + assert.ok(placeOnPath(binding, sample, segment, {})); seq += 1; return binding.direction; }; - assert.equal(play(1000, 1600, 0), 1); - assert.equal( - binding.directionPlayed, - true, - 'playback owns the direction now', - ); - // At the platform: reports 3-5 m apart, back and forth, polled and played. - const learnt = []; + // It runs east, then stands at the platform: reports 3-5 m apart, back and + // forth, polled and played. + const learnt = [play(1000, 1600, 0)]; let t0 = 15_000; for (const [fromM, toM] of [ [1600, 1597], @@ -307,7 +296,7 @@ test('jitter segments played back at a standing train keep the direction it lear learnt.push(play(fromM, toM, t0)); t0 += 15_000; } - assert.deepEqual(learnt, [1, 1, 1, 1], 'from the played-back segments'); + assert.deepEqual(learnt, [1, 1, 1, 1, 1], 'from the played-back segments'); }); test('GPS jitter in the newest reports before playback keeps the direction', () => { diff --git a/src/layers/transit/cockpitSubject.js b/src/layers/transit/cockpitSubject.js index e135835a95..ff31f0722f 100644 --- a/src/layers/transit/cockpitSubject.js +++ b/src/layers/transit/cockpitSubject.js @@ -84,9 +84,10 @@ export function createTransitCockpitSubject({ state, parts, services }) { * or held), which near the ground follows the terrain between reports; * else its segment's two reports' floors at the playback fraction. Null * while either floor is unknown, as on cold terrain, so a view waits for - * the surface: far above the ground such a marker is drawn on the - * ellipsoid, which is no floor. Not `entry.heightM`, the floor at the - * newest report, which playback has not reached yet. + * the surface: with the camera above HEIGHT_SAMPLE_MAX_ALTITUDE_M such a + * marker is drawn on the ellipsoid, which is no floor. Not + * `entry.heightM`, the floor at the newest report, which playback has not + * reached yet. */ function drawnFloorOf(entry) { const segment = entry.segment; @@ -175,21 +176,26 @@ export function createTransitCockpitSubject({ state, parts, services }) { } /** - * Show or hide a vehicle's sprite and trail for the hold. The sprite goes - * through the renderer (setShown, flushMarkers): its set draws a marker - * only as last pushed. + * Place a vehicle and show or hide its sprite and trail for the hold now: + * the icon set draws a marker as it was last pushed, not as it is. */ function repaint(entry) { if (!entry?.marker) return; - if (entry.key === state._cockpitSubjectKey) - parts.rendering.setShown(entry, false); - else parts.rendering.placeSample(entry); + parts.rendering.placeSample(entry); parts.rendering.flushMarkers(); parts.rendering.schedulePlayback(entry); parts.trails.update(); state._detectRevision += 1; } + /** A vehicle let go of is out of play until a sweep finds it in view. */ + function release(entry) { + if (!entry) return; + state._visible.delete(entry); + parts.rendering.requestVisibility(); + repaint(entry); + } + const methods = { /** The selected vehicle (see createTransitCockpitSubject), or null. */ getSelectedVehicle() { @@ -209,13 +215,7 @@ export function createTransitCockpitSubject({ state, parts, services }) { const previous = state._vehicles.get(state._cockpitSubjectKey); if (key === null || key === undefined) { state._cockpitSubjectKey = null; - // The hold kept it in play out of view: it leaves until the next - // visibility sweep finds it in view again. - if (previous) { - state._visible.delete(previous); - parts.rendering.requestVisibility(); - } - repaint(previous); + release(previous); parts.selection.refreshSelectedCard(true); return true; } @@ -224,7 +224,7 @@ export function createTransitCockpitSubject({ state, parts, services }) { if (state._selectedKey !== key) parts.selection.selectVehicle(key); state._cockpitSubjectKey = key; state._visible.add(entry); - if (previous && previous !== entry) repaint(previous); + if (previous !== entry) release(previous); repaint(entry); parts.selection.refreshSelectedCard(true); return true; diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 3fcfa3f9ea..4c2e217073 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -957,45 +957,36 @@ test('disable aborts in-flight work and a response that lands late is ignored', assert.equal(app.vehicles().length, 1); }); -test('a held vehicle with no floor yet tells its view no height', async (t) => { - // Not the ellipsoid: a first-person view waits for the surface instead. - const app = harness(t, { floorAt: () => undefined }); +/** A bus at `place.lat`, read on each poll, polled once and settled; its entry. */ +async function oneBus(app, place = { lat: 42.36 }) { app.serve('mbta', () => ({ status: 200, body: snapshot( 'mbta', 'MBTA', - [vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)], + [vehicle('bus-1', place.lat, -71.06, reported())], { fetchedAt: Date.now() }, ), })); app.layer.enable(app.viewer); await app.layer.update(); app.settle(); - const entry = app.vehicles()[0]; + return app.vehicles()[0]; +} + +test('a held vehicle with no floor yet tells its view no height', async (t) => { + // Not the ellipsoid: a first-person view waits for the surface instead. + const app = harness(t, { floorAt: () => undefined }); + const entry = await oneBus(app); assert.equal(entry.heightPending, true, 'it has nothing to stand on'); assert.ok(app.layer.setCockpitSubject(entry.key) !== false); assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); }); -test('far above the ground, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => { - // Above the height gate a vehicle with no floor is drawn on the ellipsoid - // at once, not held back; the ellipsoid is still no floor to stand a view - // on. +test('with the camera above the height gate, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => { + // There a vehicle with no floor is drawn on the ellipsoid, which is no floor. const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); - app.serve('mbta', () => ({ - status: 200, - body: snapshot( - 'mbta', - 'MBTA', - [vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)], - { fetchedAt: Date.now() }, - ), - })); - app.layer.enable(app.viewer); - await app.layer.update(); - app.settle(); - const [entry] = app.vehicles(); + const entry = await oneBus(app); assert.ok(app.layer.setCockpitSubject(entry.key) !== false); app.frame(); assert.equal(entry.surfaceReady, true, 'it is drawn'); @@ -1006,6 +997,28 @@ test('far above the ground, a held vehicle drawn on the ellipsoid tells its view assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); }); +test('with the camera above the height gate, a held vehicle with one floor unknown tells its view no height', async (t) => { + // Drawn between a floor its view could stand on and none. + for (const knownLat of [42.36, 42.361]) { + await t.test(`floor known at ${knownLat}`, async (t) => { + const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); + app.ground._warm.set(app.ground._key(knownLat, -71.06), 12); + const start = Date.now(); + const place = { lat: 42.36 }; + const entry = await oneBus(app, place); + place.lat = 42.361; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + assert.equal(app.layer.setCockpitSubject(entry.key), true); + app.run(start - AGE_MS + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now()); + const { from, to } = entry.segment; + assert.notEqual(Number.isFinite(from.h), Number.isFinite(to.h)); + assert.equal(entry.surfaceReady, true, 'it is drawn'); + assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); + }); + } +}); + test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => { // The shared ground-floor system answers from the rendered mesh cell or the // real DEM cell; until one of them is warm there is no honest height to draw @@ -2146,7 +2159,8 @@ test('a segment climbs from the ground it left to the ground it reaches', async `its snapshot stands where it is drawn, got ${floor().toFixed(1)} m`, ); - // Halfway along the segment it is halfway up; at the end, on the high ground. + // Halfway along the segment it still follows the low ground it crosses; at + // the end, it is on the high ground. const firstFixAt = start - AGE_MS; app.run(firstFixAt + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now()); assert.ok( @@ -4914,7 +4928,7 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes', assert.equal(app.layer.getCockpitSubject(), null); }); -test('turning Transit off ends a hold; on again, Escape deselects and the vehicle shows', async (t) => { +test('turning Transit off ends a hold; on again, the vehicle shows and clicks and Escape select it', async (t) => { const app = harness(t); const key = await busRunningNorth(app); assert.equal(app.layer.setCockpitSubject(key), true); @@ -4931,10 +4945,12 @@ test('turning Transit off ends a hold; on again, Escape deselects and the vehicl app.run(TRANSIT_POLL_MS); await app.layer.update(); app.settle(); - assert.equal(app.layer.focusVehicle(key), true); const [entry] = app.vehicles(); app.frame(); assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held'); + app.viewer.scene.pick = () => app.pickOf(entry); + app.input.click(new Cesium.Cartesian2(500, 400)); + assert.equal(app.state()._selectedKey, key, 'a click selects it'); globalThis.document.dispatchEvent( Object.assign(new Event('keydown'), { key: 'Escape' }), ); @@ -4968,6 +4984,7 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy app.markers('still').get(key) ?? app.markers('moving').get(key); assert.equal(icon()?.show, true, 'drawn before the hold'); assert.equal(app.layer.setCockpitSubject(key), true); + assert.equal(icon()?.show ?? false, false, 'hidden at once'); // The view rides it for a while: frames, a sweep, a poll. app.run(2_000, 16); app.settle(); @@ -4986,3 +5003,82 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy app.settle(); assert.equal(icon()?.show, true, 'let go: drawn again'); }); + +test('a hold moved to another vehicle lets the first go out of view', async (t) => { + const app = harness(t); + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [ + vehicle('bus-1', 42.36, -71.06, reported()), + vehicle('bus-2', 42.37, -71.05, reported()), + ], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const bus = (id) => app.vehicles().find((entry) => entry.key === id); + const first = bus('mbta:bus-1'); + assert.equal(app.layer.setCockpitSubject(first.key), true); + // The view looks away from both, as a view from inside the first does. + app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 }); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(bus('mbta:bus-2')), false); + assert.equal(app.layer.setCockpitSubject('mbta:bus-2'), true); + assert.equal(app.state()._visible.has(first), false, 'let go, out of play'); + assert.equal(first.marker.show, false, 'and not drawn out of view'); +}); + +test('holding a vehicle out of view tells its view at once the floor it stands on', async (t) => { + // Out of view a vehicle plays on but its marker is not moved: the hold + // places it, so its view reads neither the floor where it was last drawn + // nor nothing. + const app = harness(t, { floorAt: (lat) => (lat > 42.3625 ? 100 : 10) }); + for (const [lat, floorM] of [ + [42.361, 10], + [42.362, 10], + [42.363, 100], + [42.364, 100], + ]) + app.ground._warm.set(app.ground._key(lat, -71.06), floorM); + let lat = 42.36; + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [vehicle('bus-1', lat, -71.06, reported())], + { + fetchedAt: Date.now(), + }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const [entry] = app.vehicles(); + const drawnM = () => + Cesium.Cartographic.fromCartesian(entry.marker.position).height; + assert.ok(Math.abs(drawnM() - 11.5) < 1, 'drawn on the low ground'); + app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 }); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(entry), false, 'out of view'); + // Unseen, it drives up the hill and stands there. + for (const next of [42.361, 42.362, 42.363, 42.364, 42.364, 42.364]) { + lat = next; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + } + app.run(LAG_MS); + app.settle(); + assert.ok(drawnM() < 30, 'its marker was left on the low ground'); + assert.equal(app.layer.setCockpitSubject(entry.key), true); + const floorM = app.layer.getCockpitSubject().position.groundHeightM; + assert.ok(Math.abs(floorM - 100) < 1.5, `up the hill, got ${floorM} m`); +}); diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 8b0ecc1e8e..194d042a3e 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -1225,7 +1225,6 @@ export function createRendering({ state, services, parts }) { setNameOf, markerShown, markDirty, - setShown, flushMarkers, removeMarker, watchCamera, From 109bb0fd4f8533901d2b65221e7a34de41a28198 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:07:20 +0400 Subject: [PATCH 13/18] Tidy the Cockpit subject camera and HUD fixes after review - A provider's look, height and speed are read once, so a getter that answers once is not lost; a Promise in a provider's words is refused and its rejection handled. - A huge heading slew rate is capped at a half turn per step instead of overflowing to Infinity. - A row changed in place keeps the time it first appeared; JSDoc, CURRENT-STATE and the ETA test say so. - APPLICATION.md says the app page must load the entry icon's glyph. - Tests check that entry succeeds, the vessel bridge is entered, a floor takes over from the entry height (also at 0 m), and share helpers; the provider unit test moves to the provider tests. - WIDE_GLYPH uses escapes; comments, the release notes and CURRENT-STATE match the code. --- changelog.d/1686-cockpit-subjects.md | 6 +- .../1787-cockpit-subject-camera-hud.md | 17 +- docs/APPLICATION.md | 5 +- docs/CURRENT-STATE.md | 27 ++- src/cockpitMath.js | 12 +- src/cockpitProgress.js | 8 +- src/cockpitProgress.test.mjs | 9 +- src/cockpitSubjectProviders.js | 99 ++++++---- src/cockpitSubjectProviders.test.mjs | 58 ++++++ src/ui/cockpitCamera.js | 8 +- src/ui/cockpitController.js | 5 +- src/ui/cockpitInstruments.js | 3 +- src/ui/cockpitSignals.js | 5 +- src/ui/cockpitSubjectView.test.mjs | 180 ++++++++++-------- 14 files changed, 279 insertions(+), 163 deletions(-) diff --git a/changelog.d/1686-cockpit-subjects.md b/changelog.d/1686-cockpit-subjects.md index 8fd069db31..9cae4ddbbd 100644 --- a/changelog.d/1686-cockpit-subjects.md +++ b/changelog.d/1686-cockpit-subjects.md @@ -3,9 +3,9 @@ heading and HUD (in the page's language, via `getLocale` and `onLocaleChange` from `./i18n`); the camera can follow it without the ground clamp, anchored exactly on it, and a generic HUD adds source rows, a - banner, a veil (its light streaks stop under reduced motion) and a bottom - progress line. The Rail and Transit layers expose read and hold APIs so a - selected train or vehicle can be ridden, and `./layers/rail/paths` is + banner, a veil (its light streaks stand still under reduced motion) and a + bottom progress line. The Rail and Transit layers expose read and hold APIs + so a selected train or vehicle can be ridden, and `./layers/rail/paths` is exported; that export and the read APIs are experimental. `docs/APPLICATION.md` shows a minimal provider. GEV itself registers none, and entry to the built-in aircraft, satellite and vessel views is diff --git a/changelog.d/1787-cockpit-subject-camera-hud.md b/changelog.d/1787-cockpit-subject-camera-hud.md index 0e860b64f4..eb1b463dd4 100644 --- a/changelog.d/1787-cockpit-subject-camera-hud.md +++ b/changelog.d/1787-cockpit-subject-camera-hud.md @@ -1,9 +1,10 @@ - Keep an application's Cockpit subject steady: a height its entry frame gave - holds while the floor is still cold, so the view no longer ends; the camera - keeps up when the browser draws few frames (at 5 a second, one updated every - frame fell 700 m behind a 30 m/s subject in a minute); a provider's Live - Signals rows change where they stand, their tone included, and rows it drops - leave before new ones come in, so a changing ETA or a replaced row no longer - pushes a steady warning off the list; progress labels give CJK, kana and - Hangul names the width they need; and labels, entry face and look keep the - words checked at registration when a later read fails (German, @gekh, #1787). + holds while the floor is still cold, so the view no longer ends after the + floor wait; the camera keeps up when the browser draws few frames (at 5 a + second, one updated every frame fell 700 m behind a 30 m/s subject in a + minute); a provider's Live Signals rows change where they stand, their tone + included, and rows it drops leave before new ones come in, so a changing ETA + or a replaced row no longer pushes a steady warning off the list; progress + labels give CJK, kana and Hangul names the width they need; and labels, + entry face and look keep the words checked at registration when a later + read fails (German, @gekh, #1787). diff --git a/docs/APPLICATION.md b/docs/APPLICATION.md index b1e81b4682..4b3c05e920 100644 --- a/docs/APPLICATION.md +++ b/docs/APPLICATION.md @@ -396,8 +396,9 @@ their `this`; one that throws or returns a promise is treated as having failed. What a method returns may carry getters: one that throws when read makes a candidate none, a frame malformed (the view ends) and a HUD view keep the last; a worded member (labels, entry face, look) that throws keeps its -last good words. An entry face's `icon` must be one of the Material Symbols -`index.html` loads (`icon_names`); any other renders as its name. +last good words. An entry face's `icon` is a Material Symbols name whose glyph +the application's page must load (GEV's own `index.html` loads a subset, its +`icon_names`); a glyph the page does not load renders as its name. ```js import { getLocale, onLocaleChange } from 'gods-eye-view/i18n'; diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ff6762f4c5..1a40abe9c3 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2743,31 +2743,30 @@ first in that order decides alone: when its gate is shut there is no entry rather than the next subject's. A frame places the eye `eye.upM` above `heightM` (the shared floor where the -frame gives none, or the last height it had, the entry frame's included, while -that floor is cold; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for +frame gives none, or, while that floor is cold, the last height a frame gave, +the entry frame's included; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may turn off the floor clamps (`groundClamp: false`, for a subject inside a structure) or keep the anchor exactly on the subject (`anchor: 'exact'`, for a layer that already moves it smoothly; a frame with no `speedMps` is always exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs: 0` updates the -camera every rendered frame. Each update turns, eases and moves the view by the -time since the last one, so it keeps up when the browser draws few frames; an -update more than a second past its interval (a hidden tab) moves it as one a -second late would, and the update that first places the camera (after entry or -a floor wait) stands its anchor on the subject. A frame that is null, malformed or for another +camera every rendered frame. Each update turns the view, eases its lift and +moves an inertial anchor by the time since the last one, at most a second past +the interval (`cockpitSubjectStepSec`); an exact anchor stands where the frame +is. The update that first places the camera (after entry or a floor wait) +stands its anchor on the subject. A frame that is null, malformed or for another subject ends the view (`restoreTracking: false`), as an aircraft tracked meanwhile and the provider's layer turning off do; the exit control asks the provider to restore its subject. The generic HUD shows the provider's kicker, title, meta line, speed with its unit and tag, readout cards, always-visible -source rows, banner, route card and Live Signals rows (each changes where it -stands, its tone included, so a changing ETA never pushes a steady warning off -the list; rows the view no longer lists leave before new ones come in), a veil that darkens the -picture under the HUD (with passing light streaks, which stop under reduced -motion), arrow-key look-around when the provider asks for it, and a progress +source rows, banner, route card and Live Signals rows (each changes in place, +its tone included, and keeps the time it first appeared; rows the view no +longer lists leave before new ones come in), a veil that darkens the +picture under the HUD (with passing light streaks, which stand still under +reduced motion), arrow-key look-around when the provider asks for it, and a progress line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, -labels never overlap and get about 1 em for each full-width CJK, kana or Hangul -glyph and a little more for an emoji or other astral glyph). Core translates none of the provider's text: a host +labels never overlap and are sized for CJK and emoji glyphs). Core translates none of the provider's text: a host words it for the page's language (`gods-eye-view/i18n`: `getLocale`, `onLocaleChange`). Its entry face, labels and look may be functions, read again when they are shown and on a change of language, as the diff --git a/src/cockpitMath.js b/src/cockpitMath.js index 45348a2f39..7332a8634a 100644 --- a/src/cockpitMath.js +++ b/src/cockpitMath.js @@ -58,19 +58,15 @@ export function cockpitAnchorCorrectionStep( return Math.min(distanceM, eased, correctionRateMps * dt); } -/** - * How late past its interval a subject's camera update may come and still - * advance by all of it: a browser drawing a frame a second still keeps up. - */ +/** How late past its interval an update may come and still count in full. */ const COCKPIT_SUBJECT_LATE_SEC = 1; /** * The seconds an application subject's camera update advances its heading * slew, ground lift and anchor by: the time since the last update, at most - * its update interval plus a second. A subject updated every 500 ms, or a - * browser drawing 5 frames a second, then turns, eases and moves at its - * configured rates, while a long stall (a hidden tab) still moves it no - * further than one late update would. + * its interval plus COCKPIT_SUBJECT_LATE_SEC. A subject updated every 500 ms, + * or a browser drawing 5 frames a second, then keeps up, while a long stall + * (a hidden tab) counts as one late update. * @param {number} elapsedMs Time since the last camera update. * @param {number} intervalMs The subject's update interval (0: every frame). * @returns {number} diff --git a/src/cockpitProgress.js b/src/cockpitProgress.js index c8114d3e84..6d31cdfe88 100644 --- a/src/cockpitProgress.js +++ b/src/cockpitProgress.js @@ -30,9 +30,13 @@ const TONE_RANK = Object.freeze([ const stronger = (a, b) => TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a; -/** Full-width glyphs (CJK, kana, Hangul, full-width forms): about 1 em each. */ +/** + * Full-width glyphs in the BMP (CJK, kana, Hangul, full-width forms): about + * 1 em each. Astral ones (CJK extensions, emoji) are wide enough as any + * other two UTF-16 units (lineWidthPx). + */ const WIDE_GLYPH = - /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꥠ-꥿가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u; + /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/; /** * One line's width (px) in `.cockpit-progress-label` type (cockpitSubject.css: diff --git a/src/cockpitProgress.test.mjs b/src/cockpitProgress.test.mjs index e05f3fe0ff..e1835caea8 100644 --- a/src/cockpitProgress.test.mjs +++ b/src/cockpitProgress.test.mjs @@ -155,9 +155,12 @@ test('a CJK stop name gets the width its full-width glyphs need', () => { givenPx >= needPx, `${givenPx} px given, about ${needPx} px needed`, ); - // Latin, and half-width katakana, keep the narrower estimate. - assert.equal(estimateProgressLabelPx({ text: 'CENTRAL' }), 7 * 6.4 + 8); - assert.equal(estimateProgressLabelPx({ text: 'カタカナ' }), 4 * 6.4 + 8); + // As many Latin letters are narrower; half-width katakana are as narrow. + assert.ok(givenPx > estimateProgressLabelPx({ text: 'CENTRALS' })); + assert.equal( + estimateProgressLabelPx({ text: 'カタカナ' }), + estimateProgressLabelPx({ text: 'KANA' }), + ); }); test('emoji and other astral glyphs in a progress label get at least 1 em each', () => { diff --git a/src/cockpitSubjectProviders.js b/src/cockpitSubjectProviders.js index bed39e6bca..94def7c828 100644 --- a/src/cockpitSubjectProviders.js +++ b/src/cockpitSubjectProviders.js @@ -118,20 +118,31 @@ function lookOf(raw) { } /** - * A provider's worded member `key` as it reads now, normalized: the value, - * or what the function it is returns when called on `provider` (so it can - * follow the page's language); null when it is malformed or a read throws. - * Reading the member, and reading what it gives, runs provider code too (a - * getter), so both are guarded as the call is. + * A worded member's `value` normalized: the value, or what it returns when it + * is a function called on `provider` (so it can follow the page's language); + * null when it is malformed or a read throws. Reading what it gives runs + * provider code too (a getter), so it is guarded as the call is; a promise is + * malformed, and its rejection is caught rather than left unhandled. */ +function worded(provider, value, normalize) { + try { + const words = typeof value === 'function' ? value.call(provider) : value; + if (typeof words?.then === 'function') { + Promise.resolve(words).catch(() => {}); + return null; + } + return normalize(words) ?? null; + } catch { + return null; + } +} + +/** A provider's worded member `key` as it reads now (see `worded`). */ function wordedNow(provider, key, normalize) { try { - const value = provider[key]; - return ( - normalize(typeof value === 'function' ? value.call(provider) : value) ?? - null - ); + return worded(provider, provider[key], normalize); } catch { + // A getter for the member threw. return null; } } @@ -146,12 +157,8 @@ function providerName(provider, order) { return `#${order}`; } -/** - * Why `provider` cannot be kept, or null. Its worded members, read once here, - * go into `words` (`face`, `labels`, `look`) to seed its copy, so one that - * fails when read again cannot undo this check. - */ -function refusal(provider, kinds, words) { +/** Why `provider` cannot be kept, its worded members aside, or null. */ +function refusal(provider, kinds) { if (!isObject(provider)) return 'not an object'; if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind)) return 'malformed kind'; @@ -169,17 +176,25 @@ function refusal(provider, kinds, words) { typeof provider.isEntryAllowed !== 'function' ) return 'isEntryAllowed is not a function'; - words.face = wordedNow(provider, 'entryFace', faceOf); - if (!words.face) return 'malformed entry face'; - words.labels = wordedNow(provider, 'labels', labelsOf); - if (!words.labels) return 'labels need view, exit and exitText'; - if (provider.look != null) { - words.look = wordedNow(provider, 'look', lookOf); - if (!words.look) return 'look needs an aheadLabel'; - } return null; } +/** + * A provider's worded members, each read once, to seed its copy (so one that + * fails when read again cannot undo this check), or why one is malformed. + * @returns {{face: object, labels: object, look: ?object}|string} + */ +function checkedWords(provider) { + const face = wordedNow(provider, 'entryFace', faceOf); + if (!face) return 'malformed entry face'; + const labels = wordedNow(provider, 'labels', labelsOf); + if (!labels) return 'labels need view, exit and exitText'; + const lookValue = provider.look; + if (lookValue == null) return { face, labels, look: null }; + const look = worded(provider, lookValue, lookOf); + return look ? { face, labels, look } : 'look needs an aheadLabel'; +} + /** * The application's subject providers, checked once and frozen, in the order * entry asks them: ascending `priority`, ties in list order. Each has @@ -198,7 +213,8 @@ function refusal(provider, kinds, words) { * object: it is called on the provider again whenever they are shown and * when the page's language changes, so its words can follow it * (`./i18n`). A read that throws or is malformed keeps the last - * good one; `look` is on or off and `restPitchDeg` fixed as first read; + * good one; `look` is on or off and `restPitchDeg` fixed as read at + * registration; * - `cameraIntervalMs` (optional): 0..1000, null for the Cockpit's default; 0 * updates the camera every rendered frame; * - `headingSlewDps` (optional): how fast the view turns to a new heading, @@ -229,10 +245,13 @@ export function cockpitSubjectProviders( (Array.isArray(list) ? list : []).forEach((provider, order) => { let reason; let copy = null; - const words = { face: null, labels: null, look: null }; try { - reason = refusal(provider, kinds, words); - if (!reason) copy = keptProvider(provider, order, words); + reason = refusal(provider, kinds); + if (!reason) { + const words = checkedWords(provider); + if (typeof words === 'string') reason = words; + else copy = keptProvider(provider, order, words); + } } catch { reason = 'a member threw when read'; } @@ -250,14 +269,14 @@ export function cockpitSubjectProviders( } /** - * The frozen copy the Cockpit keeps of a provider `refusal` passed, seeded - * with the worded members it checked. + * The frozen copy the Cockpit keeps of a provider that passed `refusal`, + * seeded with the worded members `checkedWords` read. */ function keptProvider(provider, order, words) { // Worded members are read again on each use (see above); the last good // read stands in for one that is malformed or throws. let { face, labels, look } = words; - // On or off, and its rest pitch, as first read. + // Look stays on or off, at its rest pitch, as read at registration. const restPitchDeg = look?.restPitchDeg ?? 0; return Object.freeze({ kind: provider.kind, @@ -345,8 +364,8 @@ function candidateOf(raw) { * read of it that throws (a getter runs provider code). * A `heightM` that is not finite or lies outside * COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null: - * the eye then stands on the shared floor, or where it last stood while that - * is cold. The anchor is `'inertial'` by default for a frame with a valid + * the eye then stands on the shared floor, or at the last height a frame gave, + * the entry frame's included, while that is cold. The anchor is `'inertial'` by default for a frame with a valid * speed, and `'exact'` when asked for or with no speed. An id is compared * with `heldId` trimmed, as `cockpitSubjectCandidate` trims it. * @param {unknown} raw What `read()` returned. @@ -376,18 +395,20 @@ function frameOf(raw, heldId) { const heading = (value) => finite(value) ? ((value % 360) + 360) % 360 : null; const headingDeg = heading(raw.headingDeg); - const speedMps = - finite(raw.speedMps) && raw.speedMps >= 0 ? raw.speedMps : null; + // Each read once: a getter on the frame runs provider code. + const rawSpeedMps = raw.speedMps; + const speedMps = finite(rawSpeedMps) && rawSpeedMps >= 0 ? rawSpeedMps : null; + const rawHeightM = raw.heightM; return { id: heldId, name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64), latitude, longitude: ((((longitude + 180) % 360) + 360) % 360) - 180, heightM: - finite(raw.heightM) && - raw.heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M && - raw.heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M - ? raw.heightM + finite(rawHeightM) && + rawHeightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M && + rawHeightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M + ? rawHeightM : null, headingDeg, courseDeg: heading(raw.courseDeg) ?? headingDeg, diff --git a/src/cockpitSubjectProviders.test.mjs b/src/cockpitSubjectProviders.test.mjs index 2063cca412..979442cb4d 100644 --- a/src/cockpitSubjectProviders.test.mjs +++ b/src/cockpitSubjectProviders.test.mjs @@ -670,6 +670,64 @@ test('a worded getter that starts throwing keeps the last good words', () => { assert.equal(ride.labels.view, 'Ride view'); }); +for (const form of ['function', 'getter']) { + test(`worded members (as a ${form}) that throw from their second read keep the words checked at registration`, () => { + const definition = provider(); + for (const [key, value] of Object.entries({ + labels: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT' }, + entryFace: { icon: 'commute', label: 'RIDE' }, + look: { restPitchDeg: 10, aheadLabel: 'Look ahead' }, + })) { + let read = false; + const once = () => { + if (read) throw new Error('word bundle unloaded'); + read = true; + return value; + }; + if (form === 'function') definition[key] = once; + else Object.defineProperty(definition, key, { get: once }); + } + const { kept, warnings } = keep([definition]); + assert.deepEqual(warnings, []); + const [ride] = kept; + assert.equal(ride.labels.view, 'Ride view'); + assert.equal(ride.entryFace.label, 'RIDE'); + assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' }); + }); +} + +test('a worded member that returns a rejected promise keeps the last good words, the rejection caught', async () => { + const definition = provider(); + const words = definition.labels; + let reads = 0; + definition.labels = () => { + reads += 1; + return reads === 1 ? words : Promise.reject(new Error('late words')); + }; + const { kept, warnings } = keep([definition]); + assert.deepEqual(warnings, []); + assert.equal(kept[0].labels.view, words.view); + // An unhandled rejection would fail this test once it surfaces. + await new Promise((resolve) => setTimeout(resolve, 10)); +}); + +test('a frame field read through a getter is read once', () => { + const frame = { id: 'a1', latitude: 1, longitude: 2, eye: { upM: 3 } }; + const once = (value) => { + let read = false; + return () => { + const answer = read ? undefined : value; + read = true; + return answer; + }; + }; + Object.defineProperty(frame, 'heightM', { get: once(420) }); + Object.defineProperty(frame, 'speedMps', { get: once(12) }); + const normalized = cockpitSubjectFrame(frame, 'a1'); + assert.equal(normalized.heightM, 420); + assert.equal(normalized.speedMps, 12); +}); + test('a candidate, frame or HUD view whose getter throws reads as null', () => { assert.equal( cockpitSubjectCandidate(throwingGetter({ name: 'Example' }, 'id')), diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index feb7734798..ea371dab1b 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -411,7 +411,9 @@ function updateSubject(nowMs) { : slewHeading( this.heading ?? frame.headingDeg, frame.headingDeg, - rate * dtSec, + // At most half a turn, which reaches any heading: a huge rate times + // the step must not overflow to Infinity and stop the turn. + Math.min(rate * dtSec, 180), ); } let look = null; @@ -506,8 +508,8 @@ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { ); const correction = sub(target, this.cockpitAnchor); const correctionDistanceM = magnitude(correction); - // An application subject's step is already bounded by its own update - // interval (cockpitSubjectStepSec); the built-in views keep the 0.1 s. + // An application subject's step is already bounded (cockpitSubjectStepSec); + // the built-in views keep the 0.1 s. const correctionStepM = cockpitAnchorCorrectionStep( correctionDistanceM, speedMps, diff --git a/src/ui/cockpitController.js b/src/ui/cockpitController.js index 00552532c7..ded0f1fd87 100644 --- a/src/ui/cockpitController.js +++ b/src/ui/cockpitController.js @@ -194,7 +194,10 @@ export class CockpitViewController { this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; this.surfaceFallback = false; - /** The height an application subject's frame last stood at (m). */ + /** + * The last height an application subject's frame gave, the entry frame's + * included (m). + */ this.subjectHeightM = null; /** The ground clamp's eased lift under that subject's eye (m). */ this.subjectLiftM = null; diff --git a/src/ui/cockpitInstruments.js b/src/ui/cockpitInstruments.js index cf3cea895d..5e67a47e01 100644 --- a/src/ui/cockpitInstruments.js +++ b/src/ui/cockpitInstruments.js @@ -262,8 +262,7 @@ function updateSubjectHud(info, nowMs, forceContext) { for (const key of this.subjectSignalKeys ?? []) if (!keys.has(key)) this.dropCockpitSignal(key); this.subjectSignalKeys = keys; - // The view's rows are its current signals: each changes where it stands, - // so a changing one (an ETA) never pushes a steady one off the list. + // The view's rows are its current signals, each changed in place. for (const signal of hud.signals) this.pushCockpitSignal( `subject:${signal.id}`, diff --git a/src/ui/cockpitSignals.js b/src/ui/cockpitSignals.js index abfcfd12fa..997b978eee 100644 --- a/src/ui/cockpitSignals.js +++ b/src/ui/cockpitSignals.js @@ -42,8 +42,9 @@ export function publishCockpitSignals() { /** * Log a signal as the newest row, unless its key last said the same. * @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a - * provider's, that changes where it stands rather than log a new row, and - * comes back if newer rows pushed it off the list. + * provider's, that changes where it stands rather than log a new row, so a + * changing ETA never pushes a steady warning off the list; it keeps the + * time it first appeared, and comes back if newer rows pushed it off. */ export function pushCockpitSignal( key, diff --git a/src/ui/cockpitSubjectView.test.mjs b/src/ui/cockpitSubjectView.test.mjs index 92a7a9b2eb..63d39455a9 100644 --- a/src/ui/cockpitSubjectView.test.mjs +++ b/src/ui/cockpitSubjectView.test.mjs @@ -27,6 +27,10 @@ import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; const LAT = 47; const LON = 8; const FLOOR_M = 400; +/** Metres in a degree of longitude at LAT. */ +const M_PER_DEG_LON = 111_320 * Math.cos(Cesium.Math.toRadians(LAT)); +/** The longitude `m` metres east of LON. */ +const eastM = (m) => LON + m / M_PER_DEG_LON; /** A HUD view model as a provider words it. */ const HUD = Object.freeze({ @@ -560,7 +564,7 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it ride.subject.frame = { ...ride.subject.frame, headingDeg: 180, - longitude: LON + 100 / (111_320 * Math.cos(Cesium.Math.toRadians(LAT))), + longitude: eastM(100), }; setFloor(FLOOR_M + 3.5); clock.advance(500); @@ -588,20 +592,35 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it assert.ok(Math.abs(cockpit.heading - 110) < 1e-6, 'at most 1.5 s'); }); -test('an inertial subject drawn at 5 frames a second stays near its target', async (t) => { +test('a subject turning at the largest finite rate reaches its heading after a late update', async (t) => { const clock = manualClock(t, 10_000); + const ride = subjectProvider({ + cameraIntervalMs: 500, + headingSlewDps: Number.MAX_VALUE, + }); + const { cockpit } = fixture(t, { providers: [ride] }); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + clock.advance(500); + cockpit.update(); + ride.subject.frame = { ...ride.subject.frame, headingDeg: 180 }; + // A 1.5 s step: the rate times it overflows to Infinity. + clock.advance(1500); + cockpit.update(); + assert.equal(cockpit.heading, 180); +}); + +test('an inertial subject drawn at 5 frames a second stays near its target', async (t) => { + const startMs = 10_000; + const clock = manualClock(t, startMs); const ride = subjectProvider(); const SPEED_MPS = 30; - const startMs = 10_000; - const eastOf = (ms) => - LON + - (SPEED_MPS * (ms - startMs)) / - 1000 / - (111_320 * Math.cos((LAT * Math.PI) / 180)); - let nowMs = startMs; + const eastNow = () => + eastM((SPEED_MPS * (performance.now() - startMs)) / 1000); + const base = ride.subject.frame; ride.subject.frame = () => ({ - ...subjectProvider().subject.frame, - longitude: eastOf(nowMs), + ...base, + longitude: eastNow(), speedMps: SPEED_MPS, anchor: 'inertial', }); @@ -610,14 +629,9 @@ test('an inertial subject drawn at 5 frames a second stays near its target', asy assert.equal(cockpit.enter(), true); for (let i = 0; i < 300; i += 1) { clock.advance(200); - nowMs += 200; cockpit.update(); } - const target = Cesium.Cartesian3.fromDegrees( - eastOf(nowMs), - LAT, - FLOOR_M + 3.5, - ); + const target = Cesium.Cartesian3.fromDegrees(eastNow(), LAT, FLOOR_M + 3.5); const gapM = Cesium.Cartesian3.distance(shots.at(-1).destination, target); assert.ok( gapM < 50, @@ -633,15 +647,14 @@ for (const [intervalMs, waitMs] of [ const startMs = 10_000; const clock = manualClock(t, startMs); const SPEED_MPS = 30; - const mPerDegLon = 111_320 * Math.cos(Cesium.Math.toRadians(LAT)); - const eastOf = () => - LON + (SPEED_MPS * (performance.now() - startMs)) / 1000 / mPerDegLon; + const eastNow = () => + eastM((SPEED_MPS * (performance.now() - startMs)) / 1000); const ride = subjectProvider({ cameraIntervalMs: intervalMs }); const base = ride.subject.frame; ride.subject.frame = () => ({ ...base, heightM: null, - longitude: eastOf(), + longitude: eastNow(), speedMps: SPEED_MPS, anchor: 'inertial', eye: { ...base.eye, forwardM: 0 }, @@ -666,7 +679,7 @@ for (const [intervalMs, waitMs] of [ cockpit.update(); const shot = Cesium.Cartographic.fromCartesian(shots[before].destination); const leadM = - (Cesium.Math.toDegrees(shot.longitude) - eastOf()) * mPerDegLon; + (Cesium.Math.toDegrees(shot.longitude) - eastNow()) * M_PER_DEG_LON; assert.ok( Math.abs(leadM) < 1, `the first camera update leads the subject by ${leadM.toFixed(2)} m`, @@ -949,31 +962,46 @@ test('a floor that never comes ends the view after the bounded wait, releasing t assert.deepEqual(lastRelease(ride.calls), ['release', 'a1', false]); }); -test('a height the entry frame gave holds while later frames give none and the floor is cold', async (t) => { - const clock = manualClock(t, 10_000); - const ride = subjectProvider(); - const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); - setFloor(undefined); - cockpit.syncEntry(); - // The entry frame stands at FLOOR_M (heightM 400). - assert.equal(cockpit.enter(), true); - ride.subject.frame = { ...ride.subject.frame, heightM: null }; - for ( - let elapsed = 0; - elapsed < COCKPIT_GROUND_WAIT_TIMEOUT_MS + 1000; - elapsed += 100 - ) { +for (const entryHeightM of [0, FLOOR_M]) { + test(`a height the entry frame gave (${entryHeightM} m) holds while later frames give none and the floor is cold`, async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + ride.subject.frame = { ...ride.subject.frame, heightM: entryHeightM }; + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + ride.subject.frame = { ...ride.subject.frame, heightM: null }; + const waitPastTimeout = () => { + for ( + let elapsed = 0; + elapsed < COCKPIT_GROUND_WAIT_TIMEOUT_MS + 1000; + elapsed += 100 + ) { + clock.advance(100); + cockpit.update(); + } + }; + waitPastTimeout(); + assert.equal( + cockpit.active, + true, + 'the view keeps the height its entry frame gave', + ); + assert.ok(shots.length > 0, 'the camera is placed'); + assert.ok(Math.abs(shotHeight(shots) - (entryHeightM + 3.5)) < 0.01); + // A floor that comes takes over, and is kept once it is cold again. + const floorM = FLOOR_M - 100; + setFloor(floorM); clock.advance(100); cockpit.update(); - } - assert.equal( - cockpit.active, - true, - 'the view keeps the height its entry frame gave', - ); - assert.ok(shots.length > 0, 'the camera is placed'); - assert.ok(Math.abs(shotHeight(shots) - (FLOOR_M + 3.5)) < 0.01); -}); + assert.ok(Math.abs(shotHeight(shots) - (floorM + 3.5)) < 0.01); + setFloor(undefined); + waitPastTimeout(); + assert.equal(cockpit.active, true); + assert.ok(Math.abs(shotHeight(shots) - (floorM + 3.5)) < 0.01); + }); +} test('an asynchronous hold that lands after entry was refused is released again', async (t) => { let heldId = null; @@ -1054,39 +1082,28 @@ test('a provider’s labels, entry face and look follow a change of language', a ); }); -/** Labels that read well once, when the provider is checked, then throw. */ -const GOOD_LABELS = Object.freeze({ - view: 'Ride view', - exit: 'Exit ride view', - exitText: 'EXIT RIDE', - kicker: 'RIDE', -}); -const labelsOnce = () => { - let reads = 0; - return function labels() { - reads += 1; - if (reads > 1) throw new Error('word bundle unloaded'); - return GOOD_LABELS; - }; -}; - -test('labels that start throwing after the first read keep the first good words', () => { - const warned = []; - const [kept] = cockpitSubjectProviders( - [{ ...subjectProvider().definition, labels: labelsOnce() }], - { warn: (message) => warned.push(message) }, - ); - assert.ok(kept, 'the provider is kept'); - assert.deepEqual({ ...kept.labels }, GOOD_LABELS); -}); - -test('entering such a provider with no HUD kicker does not throw', async (t) => { +test('a provider whose labels throw after registration enters with no HUD kicker', async (t) => { manualClock(t, 10_000); - const ride = subjectProvider({ labels: labelsOnce() }); + let read = false; + const ride = subjectProvider({ + labels() { + if (read) throw new Error('word bundle unloaded'); + read = true; + return { + view: 'Tram view', + exit: 'Exit tram view', + exitText: 'EXIT TRAM', + kicker: 'TRAM 4', + }; + }, + }); ride.subject.hud = { title: 'Example 12' }; - const { cockpit } = fixture(t, { providers: [ride] }); + const { $, cockpit } = fixture(t, { providers: [ride] }); cockpit.syncEntry(); - assert.doesNotThrow(() => cockpit.enter()); + assert.equal(cockpit.enter(), true); + await settle(); + // The kicker checked at registration stands in for the HUD view's. + assert.equal($('.cockpit-kicker').textContent, 'TRAM 4'); }); test('a read that throws ends the view once; a hud that throws keeps the last', async (t) => { @@ -1320,6 +1337,9 @@ test('the same double-click on the vessel alone enters its bridge', async (t) => cockpit.syncEntry(); assert.equal(store.presence.entryKind, 'vessel'); assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), true); + await settle(); + assert.equal(store.presence.active, true, 'the bridge is entered'); + assert.equal(cockpit.subjectKind, 'vessel'); }); test('a provider view with look turns with the arrow keys and words its readout', async (t) => { @@ -1374,27 +1394,35 @@ test('a signal still listed stays in Live Signals while another one changes', as // The real Live Signals rows, not the fixture's recorder. delete cockpit.pushCockpitSignal; delete cockpit.dropCockpitSignal; + // The ETA is logged first, so it stands below the warning. const hudWith = (minutes) => ({ ...HUD, signals: [ + { id: 'eta', title: 'NEXT', detail: `Central in ${minutes} min` }, { id: 'doors', tone: 'warning', title: 'DOORS', detail: 'door fault, car 2', }, - { id: 'eta', title: 'NEXT', detail: `Central in ${minutes} min` }, ], }); + const etaRow = () => + cockpit.signalItems.find((row) => row.key === 'subject:eta'); ride.subject.hud = hudWith(10); cockpit.syncEntry(); assert.equal(cockpit.enter(), true); + const keysAtEntry = cockpit.signalItems.map((row) => row.key); + const etaFirstSeen = etaRow().timestamp; for (let minutes = 9; minutes >= 2; minutes -= 1) { ride.subject.hud = hudWith(minutes); clock.advance(1000); cockpit.update(); } const keys = cockpit.signalItems.map((row) => row.key); + // Each row keeps its place, and the ETA the time it first appeared. + assert.deepEqual(keys, keysAtEntry); + assert.equal(etaRow().timestamp, etaFirstSeen); assert.ok( keys.includes('subject:doors'), `the warning the HUD still lists is shown (rows: ${keys.join(', ')})`, From 58afb169d19c9016967d7e577000ae0dd731e8cd Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 20:49:15 +0400 Subject: [PATCH 14/18] Keep a standing train's direction through jitter and missing bearings - GPS jitter under 15 m at a standing train no longer turns it, in reports and in playback; a reversal needs at least 15 m of movement. - A standing train keeps its operator's last bearing through reports that leave it out. - Playback resets its turn point at a break, so a jump to a corrected position is not a reversal. - A train bound while its line is still loading takes its direction from the movement it already made. - A vehicle in view that leaves a Transit hold goes on from its own clock instead of rewinding. - Tests cover the 15 m boundary, the late line, the hold release and the icon after Transit is turned back on; duplicate jitter tests are merged. - FOLLOW_MIN_MOVE_M is gone; comments and CURRENT-STATE match the code. --- docs/CURRENT-STATE.md | 31 +++--- src/layers/rail/cockpitSubject.js | 9 +- src/layers/rail/cockpitSubject.test.mjs | 44 ++++++++- src/layers/rail/ingestion.js | 27 ++++- src/layers/rail/pathBinding.js | 73 +++++++++----- src/layers/rail/pathBinding.test.mjs | 126 +++++++++++++++--------- src/layers/rail/policy.js | 5 +- src/layers/transit/cockpitSubject.js | 14 +-- src/layers/transit/lifecycle.test.mjs | 83 +++++++++++----- src/layers/transit/rendering.js | 6 +- 10 files changed, 291 insertions(+), 127 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index d83e762add..8e7e94299d 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2769,8 +2769,8 @@ HUD view is. The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, which way it runs (`pathBinding.js` learns it), its rail height (null while -no floor is known), speed as reported or -derived, position source, feed credit and stops, and +no floor is known), speed as reported or derived, position source, feed +credit and stops, and `selectedAtMs`, when the user last selected it by a click or `focusTrain`, even again; null after a deselection and for a train only a hold selected), `setCockpitSubject(key)` (its marker, 3D model and card hidden, the selection kept, its @@ -2788,18 +2788,21 @@ box are hidden; released, it is out of play until a visibility sweep finds it in view. Turning the layer off ends the hold. Its snapshot's `position.groundHeightM` is the floor where playback draws it (the drawn marker's height while it is placed, else its segment's two reports' floors at -the playback fraction), not the newest report's, and null while that floor is -unknown, also while the camera is too high for the layer to sample the ground -and such a vehicle is drawn on the ellipsoid. Rail's `path.direction` is the -way the drawn train runs: once playback has placed it, a report that runs back -turns it only when playback starts the segment to that report. A train turns -once it has backed away from the farthest point it reached by more than a -standing train's GPS jitter, however slowly it backs, so that jitter keeps the -direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal -provider. `src/ui/cockpitSubjectView.test.mjs`, -`src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, -`src/layers/rail/cockpitSubject.test.mjs`, `src/layers/rail/pathBinding.test.mjs` -and the Transit lifecycle tests cover them. +the playback fraction), not the newest report's, and null while either of +those two floors is unknown. Rail's `path.direction` is the way the drawn +train runs: once playback has placed it, a report that runs back turns it +only when playback starts the segment to that report. A train turns once it +is more than a standing train's GPS jitter back from the last place a longer +move took it, however slowly it backs, so jitter on either side of where it +stands keeps its direction, and so does a jump to a corrected position. +A train bound after it stopped takes its direction from earlier reports in +the same run. While movement gives no direction, the snapshot uses the +operator's last reported bearing. +`docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. +`src/ui/cockpitSubjectView.test.mjs`, `src/cockpitSubjectProviders.test.mjs`, +`src/cockpitProgress.test.mjs`, `src/layers/rail/cockpitSubject.test.mjs`, +`src/layers/rail/pathBinding.test.mjs` and the Transit lifecycle tests cover +them. ## Context coordination diff --git a/src/layers/rail/cockpitSubject.js b/src/layers/rail/cockpitSubject.js index 1d9c02cb39..2a66d4f28c 100644 --- a/src/layers/rail/cockpitSubject.js +++ b/src/layers/rail/cockpitSubject.js @@ -173,16 +173,15 @@ export function createRailCockpitSubject({ /** * Which way the train runs along its shape: as its binding learnt it from - * successive reports, else from its reported bearing against the line's - * bearing there; 0 while neither tells. Not the drawn course: until the - * binding tells, the train has not moved past GPS jitter, and a course - * drawn between such reports is that jitter. + * successive reports, else from its operator's last reported bearing + * against the line's bearing there; 0 while neither tells. Not the drawn + * course: before the binding tells, that course is GPS jitter. */ function directionOf(entry) { const binding = entry.path; if (binding.direction === 1 || binding.direction === -1) return binding.direction; - const course = finiteOrNull(entry.record?.bearing); + const course = finiteOrNull(binding.bearingDeg); const point = pointAtS(binding.path, binding.drawS, scratch); if (course === null || !Number.isFinite(point?.bearingDeg)) return 0; const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180); diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs index 08bf66d15c..60f31ba8af 100644 --- a/src/layers/rail/cockpitSubject.test.mjs +++ b/src/layers/rail/cockpitSubject.test.mjs @@ -162,8 +162,8 @@ test('a train on a known floor at sea level reports a rail height of 0 m', async }); test('a train first seen standing takes no direction from its GPS jitter', async (t) => { - // Neither reports 13 m apart nor the course drawn between them say which way - // it runs; an operator's bearing does. + // Reports 13 m apart, and the course drawn between them, do not tell which + // way it runs; an operator's bearing does. const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON }); let jitterM = 0; app.feeds.set('mbta-rail', () => [ @@ -184,6 +184,46 @@ test('a train first seen standing takes no direction from its GPS jitter', async assert.deepEqual(seen, Array(6).fill([0, -1])); }); +test('a standing train keeps its operator’s bearing through reports that leave it out', async (t) => { + const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON }); + let bearing = 270; + app.feeds.set('mbta-rail', () => [ + train('T1', LAT, LON0 + 1000 / KX, { bearing }), + ]); + await app.enable(); + const seen = []; + for (const next of [270, 270, 270, null, null, null]) { + bearing = next; + app.run(RAIL_POLL_MS); + await app.poll(); + app.parts().selection.selectTrain(T1); + seen.push(app.layer.getSelectedTrain().path.direction); + } + assert.deepEqual(seen, Array(6).fill(-1)); +}); + +test('a train bound standing, its line late, runs the way its earlier reports went', async (t) => { + t.mock.method(console, 'warn', () => {}); + const paths = { 'mbta-rail': 503 }; + const app = harness(t, { paths, at: BOSTON }); + let eastM = 1600; + app.feeds.set('mbta-rail', () => [train('T1', LAT, LON0 + eastM / KX)]); + await app.enable(); + // No line yet: it runs 300 m west, with no bearing, and stands. + for (const next of [1500, 1400, 1300, 1300, 1300, 1300, 1300, 1300]) { + eastM = next; + app.run(RAIL_POLL_MS); + await app.poll(); + } + assert.equal(app.entry(T1).path, null, 'not bound yet'); + paths['mbta-rail'] = PACK; + const slot = app.state()._pathPacks.get('mbta-rail'); + app.run(Math.max(0, slot.retryAt - Date.now())); + await app.poll(); + app.parts().selection.selectTrain(T1); + assert.equal(app.layer.getSelectedTrain().path.direction, -1); +}); + test('a snapshot read again while nothing changed is the one read before', async (t) => { let list = stopList('Alpha', 'Bravo', 'Charlie'); const app = await onTheLine(t, { diff --git a/src/layers/rail/ingestion.js b/src/layers/rail/ingestion.js index 721e15f2bd..5316134ba8 100644 --- a/src/layers/rail/ingestion.js +++ b/src/layers/rail/ingestion.js @@ -23,7 +23,12 @@ import { railTrainKey, trainReportTimeMs, } from './policy.js'; -import { bindTrainPath, followFix, rebindTrainPath } from './pathBinding.js'; +import { + bindTrainPath, + followFix, + rebindTrainPath, + recallDirection, +} from './pathBinding.js'; import { scheduleRetryDelayMs } from './schedules.js'; import { createDuplicateFilter } from './dedupe.js'; @@ -220,6 +225,23 @@ export function createIngestion({ state, services, parts, source }) { entry.path = rebindTrainPath(pack, ids, entry.path, fix); } + /** + * A track's reports before `newest`, newest first, back to the start of + * its run of playback (a new epoch or a break). + */ + function earlierFixes(track, newest) { + const fixes = []; + let later = newest; + for (let i = track.count - 2; i >= 0; i--) { + if (later.flags & FIX_FLAGS.BREAK) break; + const fix = readFix(track, i); + if (fix.epoch !== later.epoch) break; + fixes.push(fix); + later = fix; + } + return fixes; + } + /** Bind the trains a feed already shows once its pack arrives. */ function bindFeedTrains(feedId) { const newest = {}; @@ -228,6 +250,9 @@ export function createIngestion({ state, services, parts, source }) { if (!entry.track?.count) continue; readFix(entry.track, entry.track.count - 1, newest); followPath(entry, entry.record, newest); + // It may have run, and stopped, before its line came. + if (entry.path) + recallDirection(entry.path, earlierFixes(entry.track, newest)); parts.rendering.schedulePlayback(entry); } governorRequestRender('rail-paths'); diff --git a/src/layers/rail/pathBinding.js b/src/layers/rail/pathBinding.js index 4afe9b7872..b2f34b5200 100644 --- a/src/layers/rail/pathBinding.js +++ b/src/layers/rail/pathBinding.js @@ -1,3 +1,4 @@ +import { FIX_FLAGS } from '../../data/contactPlayback.js'; import { pointAtS, projectOnPath } from '../../data/railPaths.js'; /** @@ -48,32 +49,19 @@ export function pathWindowM(dtMs) { } /** - * Arc a train must move before that says which way it runs (m): a standing - * train's GPS jitter, back and forth, stays within it. + * Arc a train must move before it tells which way it runs (m); a standing + * train's GPS jitter stays within it. */ export const DIRECTION_MIN_M = 15; /** - * Track one more arc position of a train. `turn.s` is the farthest arc it - * has reached the way it runs (where it was first seen while that is - * unknown); it turns once it is DIRECTION_MIN_M or more back from there, - * however small each step. - * @param {number} direction +1, -1 or 0. - * @param {{s: number}} turn Updated in place. - * @param {number} s - * @returns {number} The direction now. + * The direction after one more arc position `s`: once `s` is DIRECTION_MIN_M + * or more from `turn.s`, the sign of that move, and `turn.s` moves to `s`. */ function steer(direction, turn, s) { if (!Number.isFinite(s)) return direction; - if (!Number.isFinite(turn.s)) { - turn.s = s; - return direction; - } + if (!Number.isFinite(turn.s)) turn.s = s; const step = s - turn.s; - if (direction && step * direction >= 0) { - turn.s = s; - return direction; - } if (Math.abs(step) < DIRECTION_MIN_M) return direction; turn.s = s; return Math.sign(step); @@ -86,17 +74,19 @@ function createBinding(shapeIndex, path, via, s, fix) { via, /** * Which way the drawn train runs along the shape: +1 along it, -1 - * against it, 0 until two reports or a playback segment tell. Kept until - * a rebind, and while the train stands. Once a playback segment has told - * it (`directionPlayed`), only playback changes it: the newest reports - * run ahead of the drawn train, so a reversal they show turns it when - * playback reaches it. + * against it, 0 until it has moved DIRECTION_MIN_M (steer, or + * recallDirection). Kept until a rebind, and while the train stands. + * Once a playback segment has told it (`directionPlayed`), only playback + * changes it: the newest reports run ahead of the drawn train, so a + * reversal they show turns it when playback reaches it. */ direction: 0, directionPlayed: false, - /** How far the reports and the played segments have run (steer). */ + /** steer() turn points: one for the reports, one for the played segments. */ reportTurn: { s }, playTurn: { s: NaN }, + /** The newest operator bearing its reports gave (deg), NaN before one. */ + bearingDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN, /** Arc and time of the newest report. */ fixS: s, fixT: fix.t, @@ -149,7 +139,7 @@ function bestRouteShape(pack, routeId, fix, accept) { * * @param {object} pack From createRailPathPack. * @param {{tripId?: string, routeId?: string}} ids - * @param {{t: number, lat: number, lon: number}} fix The newest report. + * @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix The newest report. * @returns {object|null} A binding, or null to keep straight-line motion. */ export function bindTrainPath(pack, { tripId, routeId } = {}, fix) { @@ -171,7 +161,7 @@ export function bindTrainPath(pack, { tripId, routeId } = {}, fix) { /** * Follow a new report on the bound shape. * @param {object} binding - * @param {{t: number, lat: number, lon: number}} fix + * @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix * @returns {boolean} False when the report lies off the line: the binding is wrong. */ export function followFix(binding, fix) { @@ -186,6 +176,7 @@ export function followFix(binding, fix) { if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false; if (!binding.directionPlayed) binding.direction = steer(binding.direction, binding.reportTurn, hit.s); + if (Number.isFinite(fix.bearingDeg)) binding.bearingDeg = fix.bearingDeg; binding.fixS = hit.s; binding.fixT = fix.t; binding.fixLat = fix.lat; @@ -214,6 +205,32 @@ export function rebindTrainPath(pack, { routeId } = {}, binding, fix) { : null; } +/** + * Which way a train just bound standing ran before: the newest of its + * earlier reports (newest first) DIRECTION_MIN_M or more along the line + * from its newest one tells. Stops at the first report off the line. + * @param {object} binding Just made, from the newest report. + * @param {Array<{t: number, lat: number, lon: number}>} earlier + */ +export function recallDirection(binding, earlier) { + if (!binding || binding.direction) return; + for (const fix of earlier) { + const hit = projectOnPath( + binding.path, + fix.lat, + fix.lon, + binding.fixS, + pathWindowM(binding.fixT - fix.t), + ); + if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return; + const step = binding.fixS - hit.s; + if (Math.abs(step) >= DIRECTION_MIN_M) { + binding.direction = Math.sign(step); + return; + } + } +} + /** Project one playback report, near the last drawn arc when that is useful. */ function projectReport(binding, fix, hintS, hintT) { const path = binding.path; @@ -236,7 +253,7 @@ function projectReport(binding, fix, hintS, hintT) { * * @param {object} binding * @param {{fromSeq: number, toSeq: number, fraction: number}} sample Playback sample. - * @param {{from: {seq:number, t:number, lat:number, lon:number}, + * @param {{from: {seq:number, t:number, lat:number, lon:number, flags?:number}, * to: {seq:number, t:number, lat:number, lon:number}}} segment The sample's two reports. * @param {{lat?: number, lon?: number, bearingDeg?: number}} out * @returns {boolean} False when the train should stay on its straight-line point. @@ -279,6 +296,8 @@ export function placeOnPath(binding, sample, segment, out) { cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo); if (cache.ok) { const turn = binding.playTurn; + // A break is a corrected position, not a move: steer on from there. + if (from.flags & FIX_FLAGS.BREAK) turn.s = sFrom; binding.direction = steer(binding.direction, turn, sFrom); binding.direction = steer(binding.direction, turn, sTo); if (binding.direction) binding.directionPlayed = true; diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index 6dcc9fab99..04d718874b 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -1,5 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { FIX_FLAGS } from '../../data/contactPlayback.js'; import { createRailPathPack } from '../../data/railPaths.js'; import { PATH_OFF_TRACK_M, @@ -264,53 +265,41 @@ test('a report that runs back turns the drawn train only when playback does', () assert.equal(binding.direction, -1); }); -test('jitter segments played back at a standing train keep the direction it learnt', () => { - const p = pack(); - const ids = { tripId: 'full', routeId: 'main' }; - const binding = bindTrainPath(p, ids, fix(0, 1000, 0)); - assert.ok(followFix(binding, fix(15_000, 1600, 0))); - let seq = 0; - const play = (fromM, toM, t0) => { - const { sample, segment } = playback( - seq, - seq + 1, - fix(t0, fromM, 0), - fix(t0 + 15_000, toM, 0), - 0.5, +test('a jump to a corrected position in a new playback epoch is no reversal', () => { + const binding = bindTrainPath( + pack(), + { tripId: 'full', routeId: 'main' }, + fix(0, 1000, 0), + ); + const play = (seq, from, to) => + placeOnPath( + binding, + { fromSeq: seq, toSeq: seq + 1, fraction: 0.5 }, + { from: { seq, ...from }, to: { seq: seq + 1, ...to } }, + {}, ); - assert.ok(placeOnPath(binding, sample, segment, {})); - seq += 1; - return binding.direction; - }; - // It runs east, then stands at the platform: reports 3-5 m apart, back and - // forth, polled and played. - const learnt = [play(1000, 1600, 0)]; - let t0 = 15_000; - for (const [fromM, toM] of [ - [1600, 1597], - [1597, 1600], - [1600, 1596], - [1596, 1601], - ]) { - assert.ok(followFix(binding, fix(t0 + 15_000, toM, 0))); - learnt.push(play(fromM, toM, t0)); - t0 += 15_000; - } - assert.deepEqual(learnt, [1, 1, 1, 1, 1], 'from the played-back segments'); -}); - -test('GPS jitter in the newest reports before playback keeps the direction', () => { - const p = pack(); - const ids = { tripId: 'full', routeId: 'main' }; - const binding = bindTrainPath(p, ids, fix(0, 1000, 0)); - assert.ok(followFix(binding, fix(15_000, 1600, 0))); + assert.ok(play(0, fix(0, 1000, 0), fix(60_000, 1600, 0))); assert.equal(binding.direction, 1); - const learnt = []; - [1597, 1600, 1596, 1601].forEach((eastM, i) => { - assert.ok(followFix(binding, fix(30_000 + i * 15_000, eastM, 0))); - learnt.push(binding.direction); - }); - assert.deepEqual(learnt, [1, 1, 1, 1], 'from the newest reports'); + // The source puts it back at 1400 m: a new epoch whose first report is a + // break, and no segment is played from 1600 m to there. + const epoch = { epoch: 1 }; + assert.ok( + play( + 5, + { ...fix(70_000, 1400, 0), ...epoch, flags: FIX_FLAGS.BREAK }, + { ...fix(85_000, 1400, 0), ...epoch }, + ), + ); + assert.equal(binding.direction, 1, 'standing there, it keeps its way'); + // From there, a real move back still turns it. + assert.ok( + play( + 6, + { ...fix(85_000, 1400, 0), ...epoch }, + { ...fix(100_000, 1380, 0), ...epoch }, + ), + ); + assert.equal(binding.direction, -1); }); /** The direction after each played segment, `[fromM, toM]` 15 s apart. */ @@ -351,6 +340,30 @@ test('a train that moves under 15 m a report still tells its direction', () => { ); }); +test('a train turns 15 m back from where it ran to, not 14.9 m', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + for (const [backM, want, label] of [ + [1100, -1, '15 m back'], + [1100.1, 1, '14.9 m back'], + ]) { + const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); + const learnt = [1115, backM].map((eastM, i) => { + assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); + return reports.direction; + }); + assert.deepEqual(learnt, [1, want], `${label}, from the newest reports`); + assert.deepEqual( + playDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [ + [1000, 1115], + [1115, backM], + ]), + [1, want], + `${label}, from the played-back segments`, + ); + } +}); + test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { const p = pack(); const ids = { tripId: 'full', routeId: 'main' }; @@ -372,4 +385,27 @@ test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { [1, 1, 1, 1, 1], 'from the played-back segments', ); + + // On both sides of where it stopped: 8 m either way, 16 m from end to end. + const both = bindTrainPath(p, ids, fix(0, 600, 0)); + assert.deepEqual( + [1000, 1008, 1000, 992, 1000, 1008].map((eastM, i) => { + assert.ok(followFix(both, fix((i + 1) * 15_000, eastM, 0))); + return both.direction; + }), + [1, 1, 1, 1, 1, 1], + 'both sides, from the newest reports', + ); + assert.deepEqual( + playDirections(bindTrainPath(p, ids, fix(0, 600, 0)), [ + [600, 1000], + [1000, 1008], + [1008, 1000], + [1000, 992], + [992, 1000], + [1000, 1008], + ]), + [1, 1, 1, 1, 1, 1], + 'both sides, from the played-back segments', + ); }); diff --git a/src/layers/rail/policy.js b/src/layers/rail/policy.js index 57d8598459..f367c8f32c 100644 --- a/src/layers/rail/policy.js +++ b/src/layers/rail/policy.js @@ -295,9 +295,6 @@ export function playbackModeFor(railMode) { : 'rail'; } -/** Two reports closer than this are one place: a parked train's jitter (m). */ -export const FOLLOW_MIN_MOVE_M = DIRECTION_MIN_M; - const lastFix = {}; const priorFix = {}; @@ -334,7 +331,7 @@ export function railTrainFollowable(entry) { sample.nextMotionT > sample.displayT ) return true; - return lastReportsApartM(entry.track) >= FOLLOW_MIN_MOVE_M; + return lastReportsApartM(entry.track) >= DIRECTION_MIN_M; } /** diff --git a/src/layers/transit/cockpitSubject.js b/src/layers/transit/cockpitSubject.js index ff31f0722f..521263874f 100644 --- a/src/layers/transit/cockpitSubject.js +++ b/src/layers/transit/cockpitSubject.js @@ -83,11 +83,9 @@ export function createTransitCockpitSubject({ state, parts, services }) { * lift: the drawn marker's height while the frame pass places it (in view, * or held), which near the ground follows the terrain between reports; * else its segment's two reports' floors at the playback fraction. Null - * while either floor is unknown, as on cold terrain, so a view waits for - * the surface: with the camera above HEIGHT_SAMPLE_MAX_ALTITUDE_M such a - * marker is drawn on the ellipsoid, which is no floor. Not - * `entry.heightM`, the floor at the newest report, which playback has not - * reached yet. + * while either of those two floors is unknown, as on cold terrain, so a + * view waits for the surface. Not `entry.heightM`, the floor at the newest + * report, which playback has not reached yet. */ function drawnFloorOf(entry) { const segment = entry.segment; @@ -188,10 +186,14 @@ export function createTransitCockpitSubject({ state, parts, services }) { state._detectRevision += 1; } - /** A vehicle let go of is out of play until a sweep finds it in view. */ + /** + * A vehicle let go of is out of play until a sweep finds it in view. It + * played on while held, so that sweep keeps its clock (rendering.js). + */ function release(entry) { if (!entry) return; state._visible.delete(entry); + entry.releasedFromHold = true; parts.rendering.requestVisibility(); repaint(entry); } diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 4c2e217073..dfc1398982 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -957,7 +957,10 @@ test('disable aborts in-flight work and a response that lands late is ignored', assert.equal(app.vehicles().length, 1); }); -/** A bus at `place.lat`, read on each poll, polled once and settled; its entry. */ +/** + * Serves one bus at `place.lat` (read on every poll), enables the layer and + * polls once; returns its entry. + */ async function oneBus(app, place = { lat: 42.36 }) { app.serve('mbta', () => ({ status: 200, @@ -984,7 +987,6 @@ test('a held vehicle with no floor yet tells its view no height', async (t) => { }); test('with the camera above the height gate, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => { - // There a vehicle with no floor is drawn on the ellipsoid, which is no floor. const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); const entry = await oneBus(app); assert.ok(app.layer.setCockpitSubject(entry.key) !== false); @@ -4928,7 +4930,7 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes', assert.equal(app.layer.getCockpitSubject(), null); }); -test('turning Transit off ends a hold; on again, the vehicle shows and clicks and Escape select it', async (t) => { +test('turning Transit off ends a hold; on again, the vehicle shows, a click selects it and Escape deselects it', async (t) => { const app = harness(t); const key = await busRunningNorth(app); assert.equal(app.layer.setCockpitSubject(key), true); @@ -4948,6 +4950,8 @@ test('turning Transit off ends a hold; on again, the vehicle shows and clicks an const [entry] = app.vehicles(); app.frame(); assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held'); + const icon = app.markers('still').get(key) ?? app.markers('moving').get(key); + assert.equal(icon?.show, true, 'and so is its icon in the set'); app.viewer.scene.pick = () => app.pickOf(entry); app.input.click(new Cesium.Cartesian2(500, 400)); assert.equal(app.state()._selectedKey, key, 'a click selects it'); @@ -5034,10 +5038,59 @@ test('a hold moved to another vehicle lets the first go out of view', async (t) assert.equal(first.marker.show, false, 'and not drawn out of view'); }); +test('a vehicle in view let go of a hold goes on from its own clock', async (t) => { + // Held, it played on; let go, the sweep that finds it in view does not + // set its clock again, though the feed's lag has grown since. + for (const next of ['mbta:b', null]) { + await t.test(`the hold moves to ${next}`, async (t) => { + const app = harness(t, { floorAt: () => 5 }); + let fixAt = Date.now() - AGE_MS; + let north = 42.36; + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [ + vehicle('a', north, -71.06, fixAt / 1000), + vehicle('b', 42.37, -71.05, reported()), + ], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const a = app.vehicles().find((e) => e.key === 'mbta:a'); + app.layer.setCockpitSubject(a.key); + for (let poll = 1; poll <= 5; poll += 1) { + fixAt += TRANSIT_POLL_MS; + north += 0.001; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + } + // One late poll: the lag the feed earns grows. + app.run(TRANSIT_POLL_MS + 10_000); + fixAt += TRANSIT_POLL_MS; + north += 0.001; + await app.layer.update(); + app.run(3_000); + const beforeT = a.track.displayT; + const beforeLat = lat(a); + app.layer.setCockpitSubject(next); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(a), true, 'A is in view'); + assert.ok(a.track.displayT >= beforeT, 'its clock did not go back'); + assert.ok(lat(a) >= beforeLat, 'nor did it move back'); + }); + } +}); + test('holding a vehicle out of view tells its view at once the floor it stands on', async (t) => { // Out of view a vehicle plays on but its marker is not moved: the hold - // places it, so its view reads neither the floor where it was last drawn - // nor nothing. + // places it, so its view reads the floor it is on now, not the old one or + // null. const app = harness(t, { floorAt: (lat) => (lat > 42.3625 ? 100 : 10) }); for (const [lat, floorM] of [ [42.361, 10], @@ -5046,22 +5099,8 @@ test('holding a vehicle out of view tells its view at once the floor it stands o [42.364, 100], ]) app.ground._warm.set(app.ground._key(lat, -71.06), floorM); - let lat = 42.36; - app.serve('mbta', () => ({ - status: 200, - body: snapshot( - 'mbta', - 'MBTA', - [vehicle('bus-1', lat, -71.06, reported())], - { - fetchedAt: Date.now(), - }, - ), - })); - app.layer.enable(app.viewer); - await app.layer.update(); - app.settle(); - const [entry] = app.vehicles(); + const place = { lat: 42.36 }; + const entry = await oneBus(app, place); const drawnM = () => Cesium.Cartographic.fromCartesian(entry.marker.position).height; assert.ok(Math.abs(drawnM() - 11.5) < 1, 'drawn on the low ground'); @@ -5071,7 +5110,7 @@ test('holding a vehicle out of view tells its view at once the floor it stands o assert.equal(app.state()._visible.has(entry), false, 'out of view'); // Unseen, it drives up the hill and stands there. for (const next of [42.361, 42.362, 42.363, 42.364, 42.364, 42.364]) { - lat = next; + place.lat = next; app.run(TRANSIT_POLL_MS); await app.layer.update(); } diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 194d042a3e..0d31053f34 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -1134,13 +1134,17 @@ export function createRendering({ state, services, parts }) { visibility.noSample = noSample; const wasShown = entry.marker.show; const wasVisible = state._visible.has(entry); + // Let go of a hold, it played on (cockpitSubject.js): its clock stands. + const playedOn = entry.releasedFromHold === true; + entry.releasedFromHold = false; if (visible) state._visible.add(entry); else state._visible.delete(entry); // Turned afresh once back in view: the camera may have moved while it // was out, after the pass that would have turned it. if (visible && !wasVisible) entry.rotationCourse = undefined; if (visible && entry.track?.count) { - if (!wasVisible && !entry.qaFixture) syncPlayback(entry, now); + if (!wasVisible && !playedOn && !entry.qaFixture) + syncPlayback(entry, now); // Re-entry can advance into an unprepared corridor; loaded tiles can // also resolve a cold path without a poll or a render-loop wakeup. if (!wasVisible || entry.surfaceReady === false || entry.heightPending) From c190e662bc1dbd19839ed9a55c44151aa20036e8 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 20:49:21 +0400 Subject: [PATCH 15/18] Stand an inertial subject on its floor once the floor arrives - The first floor height that replaces the entry frame's height re-anchors the camera and resets the smoothed rise, so the subject stands on the floor within a second instead of hovering above it. - A provider's thenable gets one rejection handler; frame fields and eye are read once each. - A progress label's width counts the smaller detail line and full-width and astral glyphs. - Tests cover the first camera update of an aircraft and a vessel, a double-click on a selected vessel, a tone-only Live Signals change and a getter that throws on its second read; repeated cases share helpers. - Comments, the release note and CURRENT-STATE say which height the camera holds while it waits for the surface and how a Live Signals row keeps its time. --- .../1787-cockpit-subject-camera-hud.md | 20 +- docs/CURRENT-STATE.md | 16 +- src/cockpitProgress.js | 45 +++-- src/cockpitProgress.test.mjs | 20 ++ src/cockpitSubjectProviders.js | 115 ++++++----- src/cockpitSubjectProviders.test.mjs | 44 +--- src/ui/cockpitCamera.js | 21 +- src/ui/cockpitController.js | 7 +- src/ui/cockpitController.test.mjs | 32 +++ src/ui/cockpitInstruments.js | 1 - src/ui/cockpitSignals.js | 9 +- src/ui/cockpitSubjectView.test.mjs | 190 +++++++++++------- src/ui/cockpitTrackingController.js | 5 +- 13 files changed, 314 insertions(+), 211 deletions(-) diff --git a/changelog.d/1787-cockpit-subject-camera-hud.md b/changelog.d/1787-cockpit-subject-camera-hud.md index eb1b463dd4..9231f3578b 100644 --- a/changelog.d/1787-cockpit-subject-camera-hud.md +++ b/changelog.d/1787-cockpit-subject-camera-hud.md @@ -1,10 +1,10 @@ -- Keep an application's Cockpit subject steady: a height its entry frame gave - holds while the floor is still cold, so the view no longer ends after the - floor wait; the camera keeps up when the browser draws few frames (at 5 a - second, one updated every frame fell 700 m behind a 30 m/s subject in a - minute); a provider's Live Signals rows change where they stand, their tone - included, and rows it drops leave before new ones come in, so a changing ETA - or a replaced row no longer pushes a steady warning off the list; progress - labels give CJK, kana and Hangul names the width they need; and labels, - entry face and look keep the words checked at registration when a later - read fails (German, @gekh, #1787). +- Keep an application's Cockpit subject steady. A subject whose entry frame + gives a height stands there until a later frame or the floor under it gives + another, so the view no longer ends while the floor loads. The camera keeps + up when the browser draws few frames: at 5 frames a second it used to fall + 700 m behind a 30 m/s subject in a minute. A provider's Live Signals rows + change where they stand, their tone included, and rows it drops leave + before new ones come in, so a changing ETA or a replaced row no longer + pushes a steady warning off the list. Progress labels give CJK, kana and + Hangul names the width they need. Labels, entry face and look keep their + last good words when a later read fails (German, @gekh, #1787). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 1a40abe9c3..1adff6c421 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2743,8 +2743,8 @@ first in that order decides alone: when its gate is shut there is no entry rather than the next subject's. A frame places the eye `eye.upM` above `heightM` (the shared floor where the -frame gives none, or, while that floor is cold, the last height a frame gave, -the entry frame's included; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for +frame gives none, or, while that floor is cold, the last height the eye stood +at, a frame's or the floor's, at first the entry frame's; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may turn off the floor clamps (`groundClamp: false`, for a subject inside a @@ -2754,19 +2754,21 @@ exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs camera every rendered frame. Each update turns the view, eases its lift and moves an inertial anchor by the time since the last one, at most a second past the interval (`cockpitSubjectStepSec`); an exact anchor stands where the frame -is. The update that first places the camera (after entry or a floor wait) -stands its anchor on the subject. A frame that is null, malformed or for another +is. The first update after entry (after any floor wait) stands its anchor on +the subject, as does the first to replace the entry frame's height with +another. A frame that is null, malformed or for another subject ends the view (`restoreTracking: false`), as an aircraft tracked meanwhile and the provider's layer turning off do; the exit control asks the provider to restore its subject. The generic HUD shows the provider's kicker, title, meta line, speed with its unit and tag, readout cards, always-visible source rows, banner, route card and Live Signals rows (each changes in place, -its tone included, and keeps the time it first appeared; rows the view no -longer lists leave before new ones come in), a veil that darkens the +its tone included, and keeps its time while it stays listed; one pushed off +comes back as the newest row; rows the view no longer lists leave before new +ones come in), a veil that darkens the picture under the HUD (with passing light streaks, which stand still under reduced motion), arrow-key look-around when the provider asks for it, and a progress line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, -labels never overlap and are sized for CJK and emoji glyphs). Core translates none of the provider's text: a host +labels never overlap and are sized for CJK, kana and Hangul). Core translates none of the provider's text: a host words it for the page's language (`gods-eye-view/i18n`: `getLocale`, `onLocaleChange`). Its entry face, labels and look may be functions, read again when they are shown and on a change of language, as the diff --git a/src/cockpitProgress.js b/src/cockpitProgress.js index 6d31cdfe88..1761829798 100644 --- a/src/cockpitProgress.js +++ b/src/cockpitProgress.js @@ -30,31 +30,40 @@ const TONE_RANK = Object.freeze([ const stronger = (a, b) => TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a; -/** - * Full-width glyphs in the BMP (CJK, kana, Hangul, full-width forms): about - * 1 em each. Astral ones (CJK extensions, emoji) are wide enough as any - * other two UTF-16 units (lineWidthPx). - */ -const WIDE_GLYPH = - /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/; +/** Full-width glyphs in the BMP: CJK, kana, Hangul, full-width forms. */ +const WIDE_GLYPHS = + /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/g; + +/** What a full-width glyph and any other UTF-16 unit take in a title (px). */ +const TITLE_PX = Object.freeze({ wide: 10.6, narrow: 6.4 }); +/** The same in a detail line (px). */ +const DETAIL_PX = Object.freeze({ + wide: 10 / 1.2 + 0.6, + narrow: 5.8 / 1.2 + 0.6, +}); /** * One line's width (px) in `.cockpit-progress-label` type (cockpitSubject.css: - * 10 px, 0.06 em spacing): 10.6 px a full-width glyph and 6.4 px each UTF-16 - * unit of any other, so an emoji or other astral glyph gets 12.8 px. + * 10 px, 0.06 em spacing) at the glyph widths `px`: about 1 em a full-width + * glyph and 0.58 em each UTF-16 unit of any other, so an astral glyph (an + * emoji, a CJK extension) counts as two and an emoji in the BMP (☕) as one, + * narrower than it is drawn. The detail line's `` is 1/1.2 the size; + * the 0.6 px spacing it inherits is not scaled. */ -function lineWidthPx(line) { - let wide = 0; - let narrow = 0; - for (const glyph of String(line ?? '')) - if (WIDE_GLYPH.test(glyph)) wide += 1; - else narrow += glyph.length; - return wide * 10.6 + narrow * 6.4; +function lineWidthPx(line, px) { + const text = String(line ?? ''); + const wide = text.match(WIDE_GLYPHS)?.length ?? 0; + return wide * px.wide + (text.length - wide) * px.narrow; } -/** A label's width estimate (px): its longer line and 8 px of padding. */ +/** A label's width estimate (px): its wider line and 8 px of padding. */ export function estimateProgressLabelPx(label) { - return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8; + return ( + Math.max( + lineWidthPx(label?.text, TITLE_PX), + lineWidthPx(label?.detail, DETAIL_PX), + ) + 8 + ); } /** diff --git a/src/cockpitProgress.test.mjs b/src/cockpitProgress.test.mjs index e1835caea8..04920ccd68 100644 --- a/src/cockpitProgress.test.mjs +++ b/src/cockpitProgress.test.mjs @@ -181,3 +181,23 @@ test('emoji and other astral glyphs in a progress label get at least 1 em each', ); } }); + +test('a label is as wide as its wider line, its smaller detail line included', () => { + // The detail line's is 1/1.2 of 10 px; its 0.6 px spacing is not. + const detailEmPx = 10 / 1.2 + 0.6; + const detail = '中央駅前'; // 4 full-width glyphs + const givenPx = estimateProgressLabelPx({ text: 'GATE', detail }); + assert.ok( + givenPx > estimateProgressLabelPx({ text: 'GATE', detail: '' }), + 'the wider detail line widens the label', + ); + assert.ok( + givenPx >= detail.length * detailEmPx + 8, + `${givenPx} px given, about ${detail.length * detailEmPx} px needed`, + ); + // A line takes less room as the smaller detail than as the title. + assert.ok( + estimateProgressLabelPx({ text: 'A', detail: 'CENTRAL STATION' }) < + estimateProgressLabelPx({ text: 'CENTRAL STATION', detail: '' }), + ); +}); diff --git a/src/cockpitSubjectProviders.js b/src/cockpitSubjectProviders.js index 94def7c828..fa0b4deffb 100644 --- a/src/cockpitSubjectProviders.js +++ b/src/cockpitSubjectProviders.js @@ -117,18 +117,23 @@ function lookOf(raw) { }); } +/** Promises worded members gave, each one's rejection caught once. */ +const caughtWords = new WeakSet(); + /** - * A worded member's `value` normalized: the value, or what it returns when it - * is a function called on `provider` (so it can follow the page's language); - * null when it is malformed or a read throws. Reading what it gives runs - * provider code too (a getter), so it is guarded as the call is; a promise is - * malformed, and its rejection is caught rather than left unhandled. + * A worded member as `read()` gives it, normalized: called on `provider` + * when it is a function (so it can follow the page's language); null when it + * is malformed (a promise too) or provider code throws. */ -function worded(provider, value, normalize) { +function worded(provider, read, normalize) { try { + const value = read(); const words = typeof value === 'function' ? value.call(provider) : value; if (typeof words?.then === 'function') { - Promise.resolve(words).catch(() => {}); + if (!caughtWords.has(words)) { + caughtWords.add(words); + Promise.resolve(words).catch(() => {}); + } return null; } return normalize(words) ?? null; @@ -137,16 +142,6 @@ function worded(provider, value, normalize) { } } -/** A provider's worded member `key` as it reads now (see `worded`). */ -function wordedNow(provider, key, normalize) { - try { - return worded(provider, provider[key], normalize); - } catch { - // A getter for the member threw. - return null; - } -} - /** A provider's name in a warning: its kind, cut, or its place in the list. */ function providerName(provider, order) { try { @@ -185,13 +180,13 @@ function refusal(provider, kinds) { * @returns {{face: object, labels: object, look: ?object}|string} */ function checkedWords(provider) { - const face = wordedNow(provider, 'entryFace', faceOf); + const face = worded(provider, () => provider.entryFace, faceOf); if (!face) return 'malformed entry face'; - const labels = wordedNow(provider, 'labels', labelsOf); + const labels = worded(provider, () => provider.labels, labelsOf); if (!labels) return 'labels need view, exit and exitText'; const lookValue = provider.look; if (lookValue == null) return { face, labels, look: null }; - const look = worded(provider, lookValue, lookOf); + const look = worded(provider, () => lookValue, lookOf); return look ? { face, labels, look } : 'look needs an aheadLabel'; } @@ -273,8 +268,6 @@ export function cockpitSubjectProviders( * seeded with the worded members `checkedWords` read. */ function keptProvider(provider, order, words) { - // Worded members are read again on each use (see above); the last good - // read stands in for one that is malformed or throws. let { face, labels, look } = words; // Look stays on or off, at its rest pitch, as read at registration. const restPitchDeg = look?.restPitchDeg ?? 0; @@ -284,16 +277,16 @@ function keptProvider(provider, order, words) { priority: finite(provider.priority) ? provider.priority : 0, order, get entryFace() { - face = wordedNow(provider, 'entryFace', faceOf) ?? face; + face = worded(provider, () => provider.entryFace, faceOf) ?? face; return face; }, get labels() { - labels = wordedNow(provider, 'labels', labelsOf) ?? labels; + labels = worded(provider, () => provider.labels, labelsOf) ?? labels; return labels; }, get look() { if (!look) return null; - const now = wordedNow(provider, 'look', lookOf); + const now = worded(provider, () => provider.look, lookOf); if (now) look = Object.freeze({ restPitchDeg, aheadLabel: now.aheadLabel }); return look; @@ -363,11 +356,11 @@ function candidateOf(raw) { * a position that is not finite, an eye with no valid `upM` (0..1000), or a * read of it that throws (a getter runs provider code). * A `heightM` that is not finite or lies outside - * COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null: - * the eye then stands on the shared floor, or at the last height a frame gave, - * the entry frame's included, while that is cold. The anchor is `'inertial'` by default for a frame with a valid - * speed, and `'exact'` when asked for or with no speed. An id is compared - * with `heldId` trimmed, as `cockpitSubjectCandidate` trims it. + * COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null, + * for the eye to stand on the shared floor (ui/cockpitCamera.js). The anchor + * is `'inertial'` by default for a frame with a valid speed, and `'exact'` + * when asked for or with no speed. An id is compared with `heldId` trimmed, + * as `cockpitSubjectCandidate` trims it. * @param {unknown} raw What `read()` returned. * @param {string} heldId The subject the view holds. * @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg, @@ -384,51 +377,57 @@ export function cockpitSubjectFrame(raw, heldId) { } function frameOf(raw, heldId) { - if (!isObject(raw) || typeof raw.id !== 'string' || raw.id.trim() !== heldId) - return null; - const latitude = raw.latitude; - const longitude = raw.longitude; + if (!isObject(raw)) return null; + // Each field read once: a getter on the frame runs provider code. + const { + id, + name, + latitude, + longitude, + heightM, + headingDeg: rawHeadingDeg, + courseDeg, + speedMps: rawSpeedMps, + stale, + groundClamp, + anchor, + eye: rawEye, + } = raw; + if (typeof id !== 'string' || id.trim() !== heldId) return null; if (!finite(latitude) || !finite(longitude) || Math.abs(latitude) > 90) return null; - const eye = isObject(raw.eye) ? raw.eye : null; - if (!eye || !finite(eye.upM) || eye.upM < 0 || eye.upM > 1000) return null; + if (!isObject(rawEye)) return null; + const { upM, forwardM, pitchDeg, minClearanceM } = rawEye; + if (!finite(upM) || upM < 0 || upM > 1000) return null; const heading = (value) => finite(value) ? ((value % 360) + 360) % 360 : null; - const headingDeg = heading(raw.headingDeg); - // Each read once: a getter on the frame runs provider code. - const rawSpeedMps = raw.speedMps; + const headingDeg = heading(rawHeadingDeg); const speedMps = finite(rawSpeedMps) && rawSpeedMps >= 0 ? rawSpeedMps : null; - const rawHeightM = raw.heightM; return { id: heldId, - name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64), + name: cockpitSubjectText(name, 64) || cockpitSubjectText(heldId, 64), latitude, longitude: ((((longitude + 180) % 360) + 360) % 360) - 180, heightM: - finite(rawHeightM) && - rawHeightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M && - rawHeightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M - ? rawHeightM + finite(heightM) && + heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M && + heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M + ? heightM : null, headingDeg, - courseDeg: heading(raw.courseDeg) ?? headingDeg, + courseDeg: heading(courseDeg) ?? headingDeg, speedMps, - stale: raw.stale === true, - groundClamp: raw.groundClamp !== false, + stale: stale === true, + groundClamp: groundClamp !== false, // An inertial anchor runs on at the frame's speed; with none it would // close on a moving subject at the correction's floor and fall behind. - anchor: raw.anchor === 'exact' || speedMps === null ? 'exact' : 'inertial', + anchor: anchor === 'exact' || speedMps === null ? 'exact' : 'inertial', eye: { - upM: eye.upM, - forwardM: - finite(eye.forwardM) && Math.abs(eye.forwardM) <= 500 - ? eye.forwardM - : 0, - pitchDeg: finite(eye.pitchDeg) ? clamp(eye.pitchDeg, -90, 90) : 0, + upM, + forwardM: finite(forwardM) && Math.abs(forwardM) <= 500 ? forwardM : 0, + pitchDeg: finite(pitchDeg) ? clamp(pitchDeg, -90, 90) : 0, minClearanceM: - finite(eye.minClearanceM) && eye.minClearanceM >= 0 - ? eye.minClearanceM - : 0, + finite(minClearanceM) && minClearanceM >= 0 ? minClearanceM : 0, }, }; } diff --git a/src/cockpitSubjectProviders.test.mjs b/src/cockpitSubjectProviders.test.mjs index 979442cb4d..9debba2f66 100644 --- a/src/cockpitSubjectProviders.test.mjs +++ b/src/cockpitSubjectProviders.test.mjs @@ -642,11 +642,15 @@ test('a provider whose getter throws is left out with one warning; the next is k ]); }); -test('a worded getter that starts throwing keeps the last good words', () => { - let failing = false; - const words = (value) => () => { - if (failing) throw new Error('translations unavailable'); - return value; +test('a worded getter that throws from its second read keeps the last good words', () => { + // Registration reads each once: the second read is the first use. + const once = (value) => { + let read = false; + return () => { + if (read) throw new Error('translations unavailable'); + read = true; + return value; + }; }; const definition = provider(); for (const [key, value] of Object.entries({ @@ -654,48 +658,20 @@ test('a worded getter that starts throwing keeps the last good words', () => { entryFace: { icon: 'commute', label: 'RIDE' }, look: { restPitchDeg: 10, aheadLabel: 'Look ahead' }, })) - Object.defineProperty(definition, key, { get: words(value) }); + Object.defineProperty(definition, key, { get: once(value) }); const { kept, warnings } = keep([definition]); assert.deepEqual(warnings, []); const [ride] = kept; - failing = true; assert.equal(ride.labels.view, 'Ride view'); assert.equal(ride.entryFace.label, 'RIDE'); assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' }); // So does a worded object whose own member throws when read. - failing = false; Object.defineProperty(definition, 'labels', { get: () => throwingGetter({ view: 'v', exit: 'e', exitText: 'x' }, 'view'), }); assert.equal(ride.labels.view, 'Ride view'); }); -for (const form of ['function', 'getter']) { - test(`worded members (as a ${form}) that throw from their second read keep the words checked at registration`, () => { - const definition = provider(); - for (const [key, value] of Object.entries({ - labels: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT' }, - entryFace: { icon: 'commute', label: 'RIDE' }, - look: { restPitchDeg: 10, aheadLabel: 'Look ahead' }, - })) { - let read = false; - const once = () => { - if (read) throw new Error('word bundle unloaded'); - read = true; - return value; - }; - if (form === 'function') definition[key] = once; - else Object.defineProperty(definition, key, { get: once }); - } - const { kept, warnings } = keep([definition]); - assert.deepEqual(warnings, []); - const [ride] = kept; - assert.equal(ride.labels.view, 'Ride view'); - assert.equal(ride.entryFace.label, 'RIDE'); - assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' }); - }); -} - test('a worded member that returns a rejected promise keeps the last good words, the rejection caught', async () => { const definition = provider(); const words = definition.labels; diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index ea371dab1b..0aaf4bcf25 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -357,6 +357,7 @@ function updateSubject(nowMs) { } this.lastSubjectFrame = frame; let heightM = frame.heightM; + let held = false; if (heightM === null) { this.services.warmGroundFloor?.([ { lat: frame.latitude, lon: frame.longitude }, @@ -366,8 +367,10 @@ function updateSubject(nowMs) { frame.longitude, ); // A frame with no height stands on the shared floor; while that is cold - // it keeps the last height it had, the entry frame's included. - heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM; + // the eye keeps the last height it stood at (a frame's or the floor's), + // at first the entry frame's. + held = !Number.isFinite(floorM); + heightM = held ? this.subjectHeightM : floorM; } if (!Number.isFinite(heightM)) { // Nothing to stand on yet, from the first frame: the camera stays where @@ -399,6 +402,14 @@ function updateSubject(nowMs) { } this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; + if (!held) { + // The first height to replace the entry frame's places the anchor + // anew: an inertial one would close on it only at the horizontal + // correction's rate. + if (this.subjectHeightFromEntry && heightM !== this.subjectHeightM) + this.cockpitAnchorValid = false; + this.subjectHeightFromEntry = false; + } this.subjectHeightM = heightM; const target = fromDegrees(frame.longitude, frame.latitude, heightM); const dtSec = cockpitSubjectStepSec(nowMs - this.lastFrameMs, intervalMs); @@ -461,11 +472,11 @@ function updateSubject(nowMs) { * Aircraft pass none and look along the heading at the profile pitch. */ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { - // The update that first sets the anchor stands it on the target: the time - // before it (an entry, a floor wait) moved nothing, so it has no step. + // An update that sets the anchor stands it on the target with no step: + // the first one (the time before it, an entry or a floor wait, moved + // nothing), and a subject's whose height replaced its entry frame's. const anchoring = !this.cockpitAnchorValid; if (anchoring) { - this.cockpitAnchor = clone(target); this.cockpitAnchorValid = true; this.subjectLiftM = null; } diff --git a/src/ui/cockpitController.js b/src/ui/cockpitController.js index ded0f1fd87..6bdd97f5f0 100644 --- a/src/ui/cockpitController.js +++ b/src/ui/cockpitController.js @@ -194,11 +194,10 @@ export class CockpitViewController { this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; this.surfaceFallback = false; - /** - * The last height an application subject's frame gave, the entry frame's - * included (m). - */ + /** The height an application subject's eye last stood at (m). */ this.subjectHeightM = null; + /** Whether `subjectHeightM` is still the one its entry frame gave. */ + this.subjectHeightFromEntry = false; /** The ground clamp's eased lift under that subject's eye (m). */ this.subjectLiftM = null; /** diff --git a/src/ui/cockpitController.test.mjs b/src/ui/cockpitController.test.mjs index 077ed48bbe..9a08f13e77 100644 --- a/src/ui/cockpitController.test.mjs +++ b/src/ui/cockpitController.test.mjs @@ -495,6 +495,38 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async () } }); +test("a live aircraft's first Cockpit update stands the anchor on it", async () => { + const Cesium = await import('cesium'); + const env = environment(); + try { + const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 1200); + const info = { + icao24: 'abc123', + layerId: 'flights', + track: 72, + velocityMps: 200, + latitude: 30.19, + longitude: -97.67, + onGround: false, + stale: false, + }; + const { owner, views } = cockpitOver({ info, target }); + // Entry was a while ago: the step would carry the anchor 20 m ahead. + owner.update(); + const expected = cesiumCockpitEye(Cesium, { + target, + info: { ...info, stale: true }, + heading: 72, + dtSec: 0, + liftM: 0, + }); + near(views[0].destination, expected.eye, 1e-6, 'first live eye'); + owner.dispose(); + } finally { + env.restore(); + } +}); + test('a grounded Cockpit probes the mesh from the camera and keeps the eye above the floor', async () => { const Cesium = await import('cesium'); const env = environment(); diff --git a/src/ui/cockpitInstruments.js b/src/ui/cockpitInstruments.js index 5e67a47e01..c7226fcb90 100644 --- a/src/ui/cockpitInstruments.js +++ b/src/ui/cockpitInstruments.js @@ -262,7 +262,6 @@ function updateSubjectHud(info, nowMs, forceContext) { for (const key of this.subjectSignalKeys ?? []) if (!keys.has(key)) this.dropCockpitSignal(key); this.subjectSignalKeys = keys; - // The view's rows are its current signals, each changed in place. for (const signal of hud.signals) this.pushCockpitSignal( `subject:${signal.id}`, diff --git a/src/ui/cockpitSignals.js b/src/ui/cockpitSignals.js index 997b978eee..96446163ef 100644 --- a/src/ui/cockpitSignals.js +++ b/src/ui/cockpitSignals.js @@ -43,8 +43,9 @@ export function publishCockpitSignals() { * Log a signal as the newest row, unless its key last said the same. * @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a * provider's, that changes where it stands rather than log a new row, so a - * changing ETA never pushes a steady warning off the list; it keeps the - * time it first appeared, and comes back if newer rows pushed it off. + * changing ETA never pushes a steady warning off the list; it keeps its + * time while it stays listed, and one pushed off comes back as the newest + * row. */ export function pushCockpitSignal( key, @@ -55,8 +56,8 @@ export function pushCockpitSignal( { inPlace = false } = {}, ) { if (!title || !detail) return; - // Each field on its own, so no title and detail read as another pair; an - // in-place row also changes with its tone alone. + // JSON keeps the fields apart: joined with `|`, a title or detail holding a + // `|` read as another pair. An in-place row also changes with its tone alone. const signature = JSON.stringify([ title, detail, diff --git a/src/ui/cockpitSubjectView.test.mjs b/src/ui/cockpitSubjectView.test.mjs index 63d39455a9..7d6150f046 100644 --- a/src/ui/cockpitSubjectView.test.mjs +++ b/src/ui/cockpitSubjectView.test.mjs @@ -127,7 +127,10 @@ function subjectProvider(overrides = {}) { return { definition, subject, calls }; } -function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) { +function fixture( + t, + { providers = [], vessel = null, layerOn = true, realSignals = false } = {}, +) { document.body.replaceChildren(); const host = document.body.appendChild(document.createElement('div')); const pinia = createPinia(); @@ -208,6 +211,7 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) { instruments: (view) => store.publishInstruments(view), route: (view) => store.publishRoute(view), radar: (view) => store.publishRadar(view), + signals: realSignals ? (view) => store.publishSignals(view) : undefined, }, }); Object.assign(cockpit, { @@ -226,6 +230,11 @@ function fixture(t, { providers = [], vessel = null, layerOn = true } = {}) { maybeRefreshRegionalBrief() {}, showContextCard() {}, }); + if (realSignals) { + // The real Live Signals rows, published, not the recorder above. + delete cockpit.pushCockpitSignal; + delete cockpit.dropCockpitSignal; + } t.after(() => { cockpit.stop(); app.unmount(); @@ -285,6 +294,25 @@ async function settle() { /** The provider's last release call. */ const lastRelease = (calls) => calls.findLast(([name]) => name === 'release'); +/** + * Move `ride`'s subject east at `speedMps` from `startMs` (the manual clock's + * start) on an inertial anchor, its frame otherwise as it was with `extra` + * on top; returns where it is now (longitude). + */ +function movingEast(ride, startMs, speedMps, extra = {}) { + const eastNow = () => + eastM((speedMps * (performance.now() - startMs)) / 1000); + const base = ride.subject.frame; + ride.subject.frame = () => ({ + ...base, + longitude: eastNow(), + speedMps, + anchor: 'inertial', + ...extra, + }); + return eastNow; +} + /** The camera's height above the ellipsoid in its last shot (m). */ const shotHeight = (shots) => Cesium.Cartographic.fromCartesian(shots.at(-1).destination).height; @@ -614,16 +642,7 @@ test('an inertial subject drawn at 5 frames a second stays near its target', asy const startMs = 10_000; const clock = manualClock(t, startMs); const ride = subjectProvider(); - const SPEED_MPS = 30; - const eastNow = () => - eastM((SPEED_MPS * (performance.now() - startMs)) / 1000); - const base = ride.subject.frame; - ride.subject.frame = () => ({ - ...base, - longitude: eastNow(), - speedMps: SPEED_MPS, - anchor: 'inertial', - }); + const eastNow = movingEast(ride, startMs, 30); const { cockpit, shots } = fixture(t, { providers: [ride] }); cockpit.syncEntry(); assert.equal(cockpit.enter(), true); @@ -639,53 +658,38 @@ test('an inertial subject drawn at 5 frames a second stays near its target', asy ); }); -for (const [intervalMs, waitMs] of [ - [0, 1000], - [500, 2000], -]) { - test(`an inertial subject's first camera update after a ${waitMs} ms floor wait (interval ${intervalMs} ms) stands on it`, async (t) => { - const startMs = 10_000; - const clock = manualClock(t, startMs); - const SPEED_MPS = 30; - const eastNow = () => - eastM((SPEED_MPS * (performance.now() - startMs)) / 1000); - const ride = subjectProvider({ cameraIntervalMs: intervalMs }); - const base = ride.subject.frame; - ride.subject.frame = () => ({ - ...base, - heightM: null, - longitude: eastNow(), - speedMps: SPEED_MPS, - anchor: 'inertial', - eye: { ...base.eye, forwardM: 0 }, - }); - const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); - setFloor(undefined); - cockpit.syncEntry(); - assert.equal(cockpit.enter(), true); - const before = shots.length; - const stepMs = intervalMs || 100; - for (let waited = stepMs; waited < waitMs; waited += stepMs) { - clock.advance(stepMs); - cockpit.update(); - } - assert.equal( - shots.length, - before, - 'no camera update while the floor is cold', - ); - setFloor(FLOOR_M); - clock.advance(stepMs); +test("an inertial subject's first camera update after a floor wait longer than its step stands on it", async (t) => { + const startMs = 10_000; + const clock = manualClock(t, startMs); + const intervalMs = 500; + const ride = subjectProvider({ cameraIntervalMs: intervalMs }); + const eastNow = movingEast(ride, startMs, 30, { heightM: null }); + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + const before = shots.length; + // 2 s cold: longer than the 1.5 s an update may step. + for (let waited = intervalMs; waited < 2000; waited += intervalMs) { + clock.advance(intervalMs); cockpit.update(); - const shot = Cesium.Cartographic.fromCartesian(shots[before].destination); - const leadM = - (Cesium.Math.toDegrees(shot.longitude) - eastNow()) * M_PER_DEG_LON; - assert.ok( - Math.abs(leadM) < 1, - `the first camera update leads the subject by ${leadM.toFixed(2)} m`, - ); - }); -} + } + assert.equal( + shots.length, + before, + 'no camera update while the floor is cold', + ); + setFloor(FLOOR_M); + clock.advance(intervalMs); + cockpit.update(); + const shot = Cesium.Cartographic.fromCartesian(shots[before].destination); + const leadM = + (Cesium.Math.toDegrees(shot.longitude) - eastNow()) * M_PER_DEG_LON; + assert.ok( + Math.abs(leadM) < 1, + `the first camera update leads the subject by ${leadM.toFixed(2)} m`, + ); +}); test('an exact anchor sits on the subject, wherever the frame moves it', async (t) => { const clock = manualClock(t, 10_000); @@ -1310,6 +1314,8 @@ test("a double-click on the selected vessel does not enter an application's subj everythingAt(t, 100, 100); cockpit.syncEntry(); assert.equal(store.presence.entryKind, 'vessel'); + // The first press of the double-click notes where the vessel is drawn. + cockpit.onScenePointerDown(); // The application's subject is selected after the vessel: it takes entry. clock.advance(500); ride.subject.candidate = { id: 'a1', name: 'Example 12', selectedAt: 1 }; @@ -1342,6 +1348,24 @@ test('the same double-click on the vessel alone enters its bridge', async (t) => assert.equal(cockpit.subjectKind, 'vessel'); }); +test("a moving vessel's first bridge update after entry stands the anchor on its fix", async (t) => { + const clock = manualClock(t, 10_000); + const { cockpit } = fixture(t, { vessel: VESSEL }); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + clock.advance(1000); + cockpit.update(); + const anchor = Cesium.Cartographic.fromCartesian( + Cesium.Cartesian3.clone(cockpit.cockpitAnchor), + ); + const fix = cockpit.vesselFix; + const gapM = Cesium.Cartesian3.distance( + Cesium.Cartesian3.fromRadians(anchor.longitude, anchor.latitude, 0), + Cesium.Cartesian3.fromDegrees(fix.longitude, fix.latitude, 0), + ); + assert.ok(gapM < 0.01, `the anchor is ${gapM.toFixed(2)} m from the fix`); +}); + test('a provider view with look turns with the arrow keys and words its readout', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); @@ -1390,10 +1414,7 @@ test('rows a HUD view no longer lists leave Live Signals', async (t) => { test('a signal still listed stays in Live Signals while another one changes', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); - const { cockpit } = fixture(t, { providers: [ride] }); - // The real Live Signals rows, not the fixture's recorder. - delete cockpit.pushCockpitSignal; - delete cockpit.dropCockpitSignal; + const { cockpit } = fixture(t, { providers: [ride], realSignals: true }); // The ETA is logged first, so it stands below the warning. const hudWith = (minutes) => ({ ...HUD, @@ -1454,17 +1475,19 @@ test('a signal still listed stays in Live Signals while another one changes', as test('a Live Signals row whose tone alone changes takes the new tone', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); - const { cockpit } = fixture(t, { providers: [ride] }); - delete cockpit.pushCockpitSignal; - delete cockpit.dropCockpitSignal; + const { cockpit, store } = fixture(t, { + providers: [ride], + realSignals: true, + }); const hudWith = (tone) => ({ ...HUD, signals: [ { id: 'doors', tone, title: 'DOORS', detail: 'door fault, car 2' }, ], }); + // The class of the row Live Signals shows. const doorsTone = () => - cockpit.signalItems.find((row) => row.key === 'subject:doors').tone; + store.signals.find((row) => row.title === 'DOORS').className; ride.subject.hud = hudWith('normal'); cockpit.syncEntry(); assert.equal(cockpit.enter(), true); @@ -1481,9 +1504,7 @@ test('a Live Signals row whose tone alone changes takes the new tone', async (t) test('rows a HUD view replaces leave before new ones push a listed one off', async (t) => { const clock = manualClock(t, 10_000); const ride = subjectProvider(); - const { cockpit } = fixture(t, { providers: [ride] }); - delete cockpit.pushCockpitSignal; - delete cockpit.dropCockpitSignal; + const { cockpit } = fixture(t, { providers: [ride], realSignals: true }); const row = (id, tone) => ({ id, tone, @@ -1510,3 +1531,36 @@ test('rows a HUD view replaces leave before new ones push a listed one off', asy `rows right after the change: ${keys.join(', ')}`, ); }); + +// An inertial subject placed at its entry frame's height while the floor was +// cold stands on the floor as soon as it warms, as an exact anchor does. +test('an inertial subject placed at its entry height stands on the floor once it warms', async (t) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + ride.subject.frame = { + ...ride.subject.frame, + heightM: FLOOR_M, + speedMps: 0, + anchor: 'inertial', + eye: { ...ride.subject.frame.eye, forwardM: 0 }, + }; + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + ride.subject.frame = { ...ride.subject.frame, heightM: null }; + clock.advance(100); + cockpit.update(); + assert.ok(Math.abs(shotHeight(shots) - (FLOOR_M + 3.5)) < 0.01); + const floorM = FLOOR_M - 100; + setFloor(floorM); + for (let i = 0; i < 10; i += 1) { + clock.advance(100); + cockpit.update(); + } + const heightM = shotHeight(shots); + assert.ok( + Math.abs(heightM - (floorM + 3.5)) < 1, + `1 s after the floor came the eye is at ${heightM.toFixed(2)} m, not ${floorM + 3.5} m`, + ); +}); diff --git a/src/ui/cockpitTrackingController.js b/src/ui/cockpitTrackingController.js index 314a8c1b38..3cfcc76fb9 100644 --- a/src/ui/cockpitTrackingController.js +++ b/src/ui/cockpitTrackingController.js @@ -516,9 +516,10 @@ function enterSubject(provider) { this.surfaceAcquiring = false; this.surfaceFallback = false; this.cockpitAnchorValid = false; - // A height the entry frame gave is where the eye stands until a later frame - // or the warmed floor gives another. + // The entry frame's height, if any, stands in for a cold floor + // (updateSubject). this.subjectHeightM = frame.heightM; + this.subjectHeightFromEntry = true; this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null; this.resetLook({ immediate: true }); this.active = true; From e8ef4d1293c4ac99e290d514b5bd2b39dd7a20e8 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 00:26:57 +0400 Subject: [PATCH 16/18] Reset a train's turn point on a new playback epoch - A clock correction starts a new epoch, and playback may first draw its second report. The turn point now resets on a new epoch as well as on a break, so a standing train no longer turns around after a correction. - recallDirection and earlierFixes are gone: comparing each earlier report with the newest turned a standing train on GPS jitter. A train bound when its line arrives late shows no direction until it has moved 15 m. - Tests share reportDirections, iconOf and the playback helper. - Comments and CURRENT-STATE match the code. --- docs/CURRENT-STATE.md | 21 +++-- src/layers/rail/cockpitSubject.test.mjs | 22 ------ src/layers/rail/ingestion.js | 27 +------ src/layers/rail/pathBinding.js | 39 ++------- src/layers/rail/pathBinding.test.mjs | 100 +++++++++++++++++------- src/layers/transit/cockpitSubject.js | 3 +- src/layers/transit/lifecycle.test.mjs | 24 +++--- src/layers/transit/rendering.js | 3 +- 8 files changed, 108 insertions(+), 131 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8e7e94299d..ee3569c8b4 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2770,9 +2770,9 @@ The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, which way it runs (`pathBinding.js` learns it), its rail height (null while no floor is known), speed as reported or derived, position source, feed -credit and stops, and -`selectedAtMs`, when the user last selected it by a click or `focusTrain`, -even again; null after a deselection and for a train only a hold selected), +credit and stops, and `selectedAtMs`, when the user last selected it by a +click or `focusTrain`, even again; null after a deselection and for a train +only a hold selected), `setCockpitSubject(key)` (its marker, 3D model and card hidden, the selection kept, its feed held, clicks and Escape left to the view; the held copy stays the one drawn of its train while held, another feed's copy hidden, and it keeps @@ -2790,14 +2790,13 @@ view. Turning the layer off ends the hold. Its snapshot's marker's height while it is placed, else its segment's two reports' floors at the playback fraction), not the newest report's, and null while either of those two floors is unknown. Rail's `path.direction` is the way the drawn -train runs: once playback has placed it, a report that runs back turns it -only when playback starts the segment to that report. A train turns once it -is more than a standing train's GPS jitter back from the last place a longer -move took it, however slowly it backs, so jitter on either side of where it -stands keeps its direction, and so does a jump to a corrected position. -A train bound after it stopped takes its direction from earlier reports in -the same run. While movement gives no direction, the snapshot uses the -operator's last reported bearing. +train runs: once playback has told its direction, a report that runs back +turns it only when playback starts the segment to that report. A train turns +once it is more than a standing train's GPS jitter back from the last place a +longer move took it, however slowly it backs, so jitter on either side of +where it stands keeps its direction, and so does playback's jump to a +corrected position (a break, or a new clock epoch). While movement gives no +direction, the snapshot uses the operator's last reported bearing. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`, `src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, `src/layers/rail/cockpitSubject.test.mjs`, diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs index 60f31ba8af..44043f7012 100644 --- a/src/layers/rail/cockpitSubject.test.mjs +++ b/src/layers/rail/cockpitSubject.test.mjs @@ -202,28 +202,6 @@ test('a standing train keeps its operator’s bearing through reports that leave assert.deepEqual(seen, Array(6).fill(-1)); }); -test('a train bound standing, its line late, runs the way its earlier reports went', async (t) => { - t.mock.method(console, 'warn', () => {}); - const paths = { 'mbta-rail': 503 }; - const app = harness(t, { paths, at: BOSTON }); - let eastM = 1600; - app.feeds.set('mbta-rail', () => [train('T1', LAT, LON0 + eastM / KX)]); - await app.enable(); - // No line yet: it runs 300 m west, with no bearing, and stands. - for (const next of [1500, 1400, 1300, 1300, 1300, 1300, 1300, 1300]) { - eastM = next; - app.run(RAIL_POLL_MS); - await app.poll(); - } - assert.equal(app.entry(T1).path, null, 'not bound yet'); - paths['mbta-rail'] = PACK; - const slot = app.state()._pathPacks.get('mbta-rail'); - app.run(Math.max(0, slot.retryAt - Date.now())); - await app.poll(); - app.parts().selection.selectTrain(T1); - assert.equal(app.layer.getSelectedTrain().path.direction, -1); -}); - test('a snapshot read again while nothing changed is the one read before', async (t) => { let list = stopList('Alpha', 'Bravo', 'Charlie'); const app = await onTheLine(t, { diff --git a/src/layers/rail/ingestion.js b/src/layers/rail/ingestion.js index 5316134ba8..721e15f2bd 100644 --- a/src/layers/rail/ingestion.js +++ b/src/layers/rail/ingestion.js @@ -23,12 +23,7 @@ import { railTrainKey, trainReportTimeMs, } from './policy.js'; -import { - bindTrainPath, - followFix, - rebindTrainPath, - recallDirection, -} from './pathBinding.js'; +import { bindTrainPath, followFix, rebindTrainPath } from './pathBinding.js'; import { scheduleRetryDelayMs } from './schedules.js'; import { createDuplicateFilter } from './dedupe.js'; @@ -225,23 +220,6 @@ export function createIngestion({ state, services, parts, source }) { entry.path = rebindTrainPath(pack, ids, entry.path, fix); } - /** - * A track's reports before `newest`, newest first, back to the start of - * its run of playback (a new epoch or a break). - */ - function earlierFixes(track, newest) { - const fixes = []; - let later = newest; - for (let i = track.count - 2; i >= 0; i--) { - if (later.flags & FIX_FLAGS.BREAK) break; - const fix = readFix(track, i); - if (fix.epoch !== later.epoch) break; - fixes.push(fix); - later = fix; - } - return fixes; - } - /** Bind the trains a feed already shows once its pack arrives. */ function bindFeedTrains(feedId) { const newest = {}; @@ -250,9 +228,6 @@ export function createIngestion({ state, services, parts, source }) { if (!entry.track?.count) continue; readFix(entry.track, entry.track.count - 1, newest); followPath(entry, entry.record, newest); - // It may have run, and stopped, before its line came. - if (entry.path) - recallDirection(entry.path, earlierFixes(entry.track, newest)); parts.rendering.schedulePlayback(entry); } governorRequestRender('rail-paths'); diff --git a/src/layers/rail/pathBinding.js b/src/layers/rail/pathBinding.js index b2f34b5200..a07cf1b20f 100644 --- a/src/layers/rail/pathBinding.js +++ b/src/layers/rail/pathBinding.js @@ -74,8 +74,8 @@ function createBinding(shapeIndex, path, via, s, fix) { via, /** * Which way the drawn train runs along the shape: +1 along it, -1 - * against it, 0 until it has moved DIRECTION_MIN_M (steer, or - * recallDirection). Kept until a rebind, and while the train stands. + * against it, 0 until it has moved DIRECTION_MIN_M (steer). Kept until + * a rebind, and while the train stands. * Once a playback segment has told it (`directionPlayed`), only playback * changes it: the newest reports run ahead of the drawn train, so a * reversal they show turns it when playback reaches it. @@ -84,7 +84,7 @@ function createBinding(shapeIndex, path, via, s, fix) { directionPlayed: false, /** steer() turn points: one for the reports, one for the played segments. */ reportTurn: { s }, - playTurn: { s: NaN }, + playTurn: { s: NaN, epoch: NaN }, /** The newest operator bearing its reports gave (deg), NaN before one. */ bearingDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN, /** Arc and time of the newest report. */ @@ -205,32 +205,6 @@ export function rebindTrainPath(pack, { routeId } = {}, binding, fix) { : null; } -/** - * Which way a train just bound standing ran before: the newest of its - * earlier reports (newest first) DIRECTION_MIN_M or more along the line - * from its newest one tells. Stops at the first report off the line. - * @param {object} binding Just made, from the newest report. - * @param {Array<{t: number, lat: number, lon: number}>} earlier - */ -export function recallDirection(binding, earlier) { - if (!binding || binding.direction) return; - for (const fix of earlier) { - const hit = projectOnPath( - binding.path, - fix.lat, - fix.lon, - binding.fixS, - pathWindowM(binding.fixT - fix.t), - ); - if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return; - const step = binding.fixS - hit.s; - if (Math.abs(step) >= DIRECTION_MIN_M) { - binding.direction = Math.sign(step); - return; - } - } -} - /** Project one playback report, near the last drawn arc when that is useful. */ function projectReport(binding, fix, hintS, hintT) { const path = binding.path; @@ -296,8 +270,11 @@ export function placeOnPath(binding, sample, segment, out) { cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo); if (cache.ok) { const turn = binding.playTurn; - // A break is a corrected position, not a move: steer on from there. - if (from.flags & FIX_FLAGS.BREAK) turn.s = sFrom; + // A break or a new epoch is a corrected position, not a move: steer + // on from there. + if (from.flags & FIX_FLAGS.BREAK || from.epoch !== turn.epoch) + turn.s = sFrom; + turn.epoch = from.epoch; binding.direction = steer(binding.direction, turn, sFrom); binding.direction = steer(binding.direction, turn, sTo); if (binding.direction) binding.directionPlayed = true; diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index 04d718874b..7f3f9e707e 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -1,6 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { FIX_FLAGS } from '../../data/contactPlayback.js'; +import { + FIX_FLAGS, + advance, + createSample, + createTrack, + insertFix, + readFix, +} from '../../data/contactPlayback.js'; import { createRailPathPack } from '../../data/railPaths.js'; import { PATH_OFF_TRACK_M, @@ -271,13 +278,10 @@ test('a jump to a corrected position in a new playback epoch is no reversal', () { tripId: 'full', routeId: 'main' }, fix(0, 1000, 0), ); - const play = (seq, from, to) => - placeOnPath( - binding, - { fromSeq: seq, toSeq: seq + 1, fraction: 0.5 }, - { from: { seq, ...from }, to: { seq: seq + 1, ...to } }, - {}, - ); + const play = (seq, from, to) => { + const { sample, segment } = playback(seq, seq + 1, from, to, 0.5); + return placeOnPath(binding, sample, segment, {}); + }; assert.ok(play(0, fix(0, 1000, 0), fix(60_000, 1600, 0))); assert.equal(binding.direction, 1); // The source puts it back at 1400 m: a new epoch whose first report is a @@ -302,6 +306,42 @@ test('a jump to a corrected position in a new playback epoch is no reversal', () assert.equal(binding.direction, -1); }); +test('a clock correction played from past its break is no reversal', () => { + const binding = bindTrainPath( + pack(), + { tripId: 'full', routeId: 'main' }, + fix(0, 600, 0), + ); + const track = createTrack(); + const sample = createSample(); + const segment = { from: {}, to: {} }; + let now = 0; + /** One report at `t`, then 15 s of frames; the direction after each. */ + const report = (t, eastM) => { + insertFix(track, fix(t, eastM, 0), { receivedAt: now, wallNowMs: now }); + return [1, 2, 3].map(() => { + now += 5000; + advance(track, { wallNowMs: now, monoNowMs: now }, sample); + if (sample.fromSeq >= 0) { + readFix(track, sample.fromSeq - track.baseSeq, segment.from); + readFix(track, sample.toSeq - track.baseSeq, segment.to); + placeOnPath(binding, sample, segment, {}); + } + return binding.direction; + }); + }; + for (const eastM of [600, 750, 900, 1050, 1200, 1200, 1200, 1200]) + report(now, eastM); + assert.equal(binding.direction, 1); + assert.ok(binding.directionPlayed); + // Its source's clock falls 120 s behind and puts it at 1000 m. The third + // such report starts a new epoch, and playback starts at the newest one, + // past the break. + const seen = [0, 1, 2].flatMap(() => report(now - 120_000, 1000)); + assert.equal(track.resetReason, 'out-of-order'); + assert.deepEqual(seen, Array(9).fill(1)); +}); + /** The direction after each played segment, `[fromM, toM]` 15 s apart. */ function playDirections(binding, steps) { return steps.map(([fromM, toM], seq) => { @@ -317,15 +357,22 @@ function playDirections(binding, steps) { }); } +/** The direction after each report, `eastMs` 15 s apart. */ +function reportDirections(binding, eastMs) { + return eastMs.map((eastM, i) => { + assert.ok(followFix(binding, fix((i + 1) * 15_000, eastM, 0))); + return binding.direction; + }); +} + test('a train that moves under 15 m a report still tells its direction', () => { const p = pack(); const ids = { tripId: 'full', routeId: 'main' }; // It sets off slowly, runs east, then backs out 10 m a report. - const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); - const learnt = [1010, 1020, 1600, 1590, 1580, 1570].map((eastM, i) => { - assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); - return reports.direction; - }); + const learnt = reportDirections( + bindTrainPath(p, ids, fix(0, 1000, 0)), + [1010, 1020, 1600, 1590, 1580, 1570], + ); assert.deepEqual(learnt, [0, 1, 1, 1, -1, -1], 'from the newest reports'); const played = bindTrainPath(p, ids, fix(0, 1000, 0)); assert.deepEqual( @@ -347,11 +394,10 @@ test('a train turns 15 m back from where it ran to, not 14.9 m', () => { [1100, -1, '15 m back'], [1100.1, 1, '14.9 m back'], ]) { - const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); - const learnt = [1115, backM].map((eastM, i) => { - assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); - return reports.direction; - }); + const learnt = reportDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [ + 1115, + backM, + ]); assert.deepEqual(learnt, [1, want], `${label}, from the newest reports`); assert.deepEqual( playDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [ @@ -367,11 +413,10 @@ test('a train turns 15 m back from where it ran to, not 14.9 m', () => { test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { const p = pack(); const ids = { tripId: 'full', routeId: 'main' }; - const reports = bindTrainPath(p, ids, fix(0, 1000, 0)); - const learnt = [1600, 1588, 1600, 1586, 1599, 1587].map((eastM, i) => { - assert.ok(followFix(reports, fix((i + 1) * 15_000, eastM, 0))); - return reports.direction; - }); + const learnt = reportDirections( + bindTrainPath(p, ids, fix(0, 1000, 0)), + [1600, 1588, 1600, 1586, 1599, 1587], + ); assert.deepEqual(learnt, [1, 1, 1, 1, 1, 1], 'from the newest reports'); const played = bindTrainPath(p, ids, fix(0, 1000, 0)); assert.deepEqual( @@ -387,12 +432,11 @@ test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { ); // On both sides of where it stopped: 8 m either way, 16 m from end to end. - const both = bindTrainPath(p, ids, fix(0, 600, 0)); assert.deepEqual( - [1000, 1008, 1000, 992, 1000, 1008].map((eastM, i) => { - assert.ok(followFix(both, fix((i + 1) * 15_000, eastM, 0))); - return both.direction; - }), + reportDirections( + bindTrainPath(p, ids, fix(0, 600, 0)), + [1000, 1008, 1000, 992, 1000, 1008], + ), [1, 1, 1, 1, 1, 1], 'both sides, from the newest reports', ); diff --git a/src/layers/transit/cockpitSubject.js b/src/layers/transit/cockpitSubject.js index 521263874f..70cd6ecbfd 100644 --- a/src/layers/transit/cockpitSubject.js +++ b/src/layers/transit/cockpitSubject.js @@ -188,7 +188,8 @@ export function createTransitCockpitSubject({ state, parts, services }) { /** * A vehicle let go of is out of play until a sweep finds it in view. It - * played on while held, so that sweep keeps its clock (rendering.js). + * played on while held, so the next sweep keeps its clock if it finds it in + * view (rendering.js). */ function release(entry) { if (!entry) return; diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index dfc1398982..68ae7a9110 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -958,8 +958,8 @@ test('disable aborts in-flight work and a response that lands late is ignored', }); /** - * Serves one bus at `place.lat` (read on every poll), enables the layer and - * polls once; returns its entry. + * Serves one bus at `place.lat` (read on every poll), enables the layer, polls + * once and settles; returns its entry. */ async function oneBus(app, place = { lat: 42.36 }) { app.serve('mbta', () => ({ @@ -4930,6 +4930,11 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes', assert.equal(app.layer.getCockpitSubject(), null); }); +/** A vehicle's icon in the set that draws it, still or moving. */ +function iconOf(app, key) { + return app.markers('still').get(key) ?? app.markers('moving').get(key); +} + test('turning Transit off ends a hold; on again, the vehicle shows, a click selects it and Escape deselects it', async (t) => { const app = harness(t); const key = await busRunningNorth(app); @@ -4950,8 +4955,7 @@ test('turning Transit off ends a hold; on again, the vehicle shows, a click sele const [entry] = app.vehicles(); app.frame(); assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held'); - const icon = app.markers('still').get(key) ?? app.markers('moving').get(key); - assert.equal(icon?.show, true, 'and so is its icon in the set'); + assert.equal(iconOf(app, key)?.show, true, 'and so is its icon in the set'); app.viewer.scene.pick = () => app.pickOf(entry); app.input.click(new Cesium.Cartesian2(500, 400)); assert.equal(app.state()._selectedKey, key, 'a click selects it'); @@ -4984,11 +4988,9 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy } const key = 'mbta:bus-1'; const [entry] = app.vehicles(); - const icon = () => - app.markers('still').get(key) ?? app.markers('moving').get(key); - assert.equal(icon()?.show, true, 'drawn before the hold'); + assert.equal(iconOf(app, key)?.show, true, 'drawn before the hold'); assert.equal(app.layer.setCockpitSubject(key), true); - assert.equal(icon()?.show ?? false, false, 'hidden at once'); + assert.equal(iconOf(app, key)?.show ?? false, false, 'hidden at once'); // The view rides it for a while: frames, a sweep, a poll. app.run(2_000, 16); app.settle(); @@ -4997,7 +4999,7 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy app.settle(); assert.equal(entry.marker.show, false, 'its marker is hidden'); assert.equal( - icon()?.show ?? false, + iconOf(app, key)?.show ?? false, false, 'and so is the icon the set draws', ); @@ -5005,7 +5007,7 @@ test('a held parked vehicle draws no icon; let go, it draws its icon again', asy assert.equal(app.layer.setCockpitSubject(null), true); app.advance(250); app.settle(); - assert.equal(icon()?.show, true, 'let go: drawn again'); + assert.equal(iconOf(app, key)?.show, true, 'let go: drawn again'); }); test('a hold moved to another vehicle lets the first go out of view', async (t) => { @@ -5069,7 +5071,7 @@ test('a vehicle in view let go of a hold goes on from its own clock', async (t) app.run(TRANSIT_POLL_MS); await app.layer.update(); } - // One late poll: the lag the feed earns grows. + // One late poll raises the feed's target lag. app.run(TRANSIT_POLL_MS + 10_000); fixAt += TRANSIT_POLL_MS; north += 0.001; diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index 0d31053f34..4a54dfb6ff 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -1134,7 +1134,8 @@ export function createRendering({ state, services, parts }) { visibility.noSample = noSample; const wasShown = entry.marker.show; const wasVisible = state._visible.has(entry); - // Let go of a hold, it played on (cockpitSubject.js): its clock stands. + // Just let go of a hold (cockpitSubject.js): it played on, so keep + // its clock. const playedOn = entry.releasedFromHold === true; entry.releasedFromHold = false; if (visible) state._visible.add(entry); From 83081730c0ef5b52f9f4a80021291634821fb881 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 00:26:57 +0400 Subject: [PATCH 17/18] Move only the anchor's height when the floor height arrives - The first height that replaces the entry frame's now moves only the anchor's height. The anchor keeps its place and its eased lift, so the camera no longer jumps to a corrected fix or steps back. - A detail line is measured with the title's glyph widths. They are a little wide for its smaller type, so a long detail line is no longer clipped. - The first aircraft update is checked in the existing test, and the copy is removed; test fixtures are simpler. - Comments, the release note and CURRENT-STATE match the code. --- .../1787-cockpit-subject-camera-hud.md | 15 +-- docs/CURRENT-STATE.md | 63 ++++++----- src/cockpitProgress.js | 28 ++--- src/cockpitProgress.test.mjs | 30 ++--- src/cockpitSubjectProviders.js | 6 +- src/ui/cockpitCamera.js | 22 ++-- src/ui/cockpitController.test.mjs | 39 +------ src/ui/cockpitSignals.js | 4 +- src/ui/cockpitSubjectView.test.mjs | 107 +++++++++++++++--- 9 files changed, 176 insertions(+), 138 deletions(-) diff --git a/changelog.d/1787-cockpit-subject-camera-hud.md b/changelog.d/1787-cockpit-subject-camera-hud.md index 9231f3578b..35b3245281 100644 --- a/changelog.d/1787-cockpit-subject-camera-hud.md +++ b/changelog.d/1787-cockpit-subject-camera-hud.md @@ -1,10 +1,11 @@ - Keep an application's Cockpit subject steady. A subject whose entry frame gives a height stands there until a later frame or the floor under it gives another, so the view no longer ends while the floor loads. The camera keeps - up when the browser draws few frames: at 5 frames a second it used to fall - 700 m behind a 30 m/s subject in a minute. A provider's Live Signals rows - change where they stand, their tone included, and rows it drops leave - before new ones come in, so a changing ETA or a replaced row no longer - pushes a steady warning off the list. Progress labels give CJK, kana and - Hangul names the width they need. Labels, entry face and look keep their - last good words when a later read fails (German, @gekh, #1787). + up when the browser draws few frames: updated every frame at 5 frames a + second, it used to fall 700 m behind a 30 m/s subject in a minute. A + provider's Live Signals rows change where they stand, their tone included, + and rows it drops leave before new ones come in, so a changing ETA or a + replaced row no longer pushes a steady warning off the list. Progress labels + give CJK, kana and Hangul names the width they need. Labels, entry face and + look keep their last good words when a later read fails + (German, @gekh, #1787). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 1adff6c421..bb301fd01a 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2742,38 +2742,39 @@ priority; one first seen together with a built-in subject comes after it. The first in that order decides alone: when its gate is shut there is no entry rather than the next subject's. -A frame places the eye `eye.upM` above `heightM` (the shared floor where the -frame gives none, or, while that floor is cold, the last height the eye stood -at, a frame's or the floor's, at first the entry frame's; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for -at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the -subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may -turn off the floor clamps (`groundClamp: false`, for a subject inside a -structure) or keep the anchor exactly on the subject (`anchor: 'exact'`, for a -layer that already moves it smoothly; a frame with no `speedMps` is always -exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs: 0` updates the -camera every rendered frame. Each update turns the view, eases its lift and -moves an inertial anchor by the time since the last one, at most a second past -the interval (`cockpitSubjectStepSec`); an exact anchor stands where the frame -is. The first update after entry (after any floor wait) stands its anchor on -the subject, as does the first to replace the entry frame's height with -another. A frame that is null, malformed or for another -subject ends the view (`restoreTracking: false`), as an aircraft tracked -meanwhile and the provider's layer turning off do; the exit control asks the -provider to restore its subject. The generic HUD shows the provider's kicker, -title, meta line, speed with its unit and tag, readout cards, always-visible -source rows, banner, route card and Live Signals rows (each changes in place, -its tone included, and keeps its time while it stays listed; one pushed off -comes back as the newest row; rows the view no longer lists leave before new -ones come in), a veil that darkens the +A frame places the eye `eye.upM` above `heightM`. With no `heightM` the eye +stands on the shared floor; while that floor is cold, at the last height it +stood at (at first the entry frame's). With neither, the camera stays where it +is and the HUD reads ACQUIRING SURFACE for at most +`COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the subject is +released: no height stands in for a floor never read. The view slews toward +`headingDeg` at the provider's rate. A frame may turn off the floor clamps +(`groundClamp: false`, for a subject inside a structure) or keep the anchor +exactly on the subject (`anchor: 'exact'`, for a layer that already moves it +smoothly; a frame with no `speedMps` is always exact, since an inertial anchor +runs on at the frame's speed); `cameraIntervalMs: 0` updates the camera every +rendered frame. Each update turns the view, eases its lift and moves an inertial +anchor by the time since the last one, at most a second past the interval +(`cockpitSubjectStepSec`); an exact anchor stands where the frame is. The first +update after entry (after any floor wait) stands its anchor on the subject; the +first height to replace the entry frame's moves the anchor to that height where +it stands. A frame that is null, malformed or for another subject ends the view +(`restoreTracking: false`), as an aircraft tracked meanwhile and the provider's +layer turning off do; the exit control asks the provider to restore its subject. +The generic HUD shows the provider's kicker, title, meta line, speed with its +unit and tag, readout cards, always-visible source rows, banner, route card and +Live Signals rows (each changes in place, its tone included, and keeps its time +while it stays listed; one pushed off comes back as the newest row; rows the +view no longer lists leave before new ones come in), a veil that darkens the picture under the HUD (with passing light streaks, which stand still under -reduced motion), arrow-key look-around when the provider asks for it, and a progress -line along the bottom edge (`src/cockpitProgress.js`: close ticks merge, -labels never overlap and are sized for CJK, kana and Hangul). Core translates none of the provider's text: a host -words it for the page's language (`gods-eye-view/i18n`: -`getLocale`, `onLocaleChange`). Its entry face, labels and look may be -functions, read again when they are shown and on a change of language, as the -HUD view is; a read that throws or is malformed keeps the last good words, at -first those checked when the provider was registered. +reduced motion), arrow-key look-around when the provider asks for it, and a +progress line along the bottom edge (`src/cockpitProgress.js`: close ticks +merge, labels never overlap and are sized for CJK, kana and Hangul). Core +translates none of the provider's text: a host words it for the page's language +(`gods-eye-view/i18n`: `getLocale`, `onLocaleChange`). Its entry face, labels +and look may be functions, read again when they are shown and on a change of +language, as the HUD view is; a read that throws or is malformed keeps the last +good words, at first those checked when the provider was registered. The Rail layer offers a read API for such a view: `getSelectedTrain()` and `getCockpitSubject()` (a snapshot of the train: where it is along its line, diff --git a/src/cockpitProgress.js b/src/cockpitProgress.js index 1761829798..abdc0eb467 100644 --- a/src/cockpitProgress.js +++ b/src/cockpitProgress.js @@ -34,36 +34,22 @@ const stronger = (a, b) => const WIDE_GLYPHS = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/g; -/** What a full-width glyph and any other UTF-16 unit take in a title (px). */ -const TITLE_PX = Object.freeze({ wide: 10.6, narrow: 6.4 }); -/** The same in a detail line (px). */ -const DETAIL_PX = Object.freeze({ - wide: 10 / 1.2 + 0.6, - narrow: 5.8 / 1.2 + 0.6, -}); - /** * One line's width (px) in `.cockpit-progress-label` type (cockpitSubject.css: - * 10 px, 0.06 em spacing) at the glyph widths `px`: about 1 em a full-width - * glyph and 0.58 em each UTF-16 unit of any other, so an astral glyph (an - * emoji, a CJK extension) counts as two and an emoji in the BMP (☕) as one, - * narrower than it is drawn. The detail line's `` is 1/1.2 the size; - * the 0.6 px spacing it inherits is not scaled. + * 10 px, 0.06 em spacing): 10.6 px a full-width glyph and 6.4 px each UTF-16 + * unit of any other, so an astral glyph (an emoji, a CJK extension) counts as + * two and an emoji in the BMP (☕) as one, narrower than it is drawn. The + * detail line's `` draws smaller, so these widths only overestimate it. */ -function lineWidthPx(line, px) { +function lineWidthPx(line) { const text = String(line ?? ''); const wide = text.match(WIDE_GLYPHS)?.length ?? 0; - return wide * px.wide + (text.length - wide) * px.narrow; + return wide * 10.6 + (text.length - wide) * 6.4; } /** A label's width estimate (px): its wider line and 8 px of padding. */ export function estimateProgressLabelPx(label) { - return ( - Math.max( - lineWidthPx(label?.text, TITLE_PX), - lineWidthPx(label?.detail, DETAIL_PX), - ) + 8 - ); + return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8; } /** diff --git a/src/cockpitProgress.test.mjs b/src/cockpitProgress.test.mjs index 04920ccd68..dcf2836bce 100644 --- a/src/cockpitProgress.test.mjs +++ b/src/cockpitProgress.test.mjs @@ -163,7 +163,7 @@ test('a CJK stop name gets the width its full-width glyphs need', () => { ); }); -test('emoji and other astral glyphs in a progress label get at least 1 em each', () => { +test('astral glyphs (emoji outside the BMP, supplementary kana) in a progress label get at least 1 em each', () => { // About 1 em in 10 px type, 0.06 em apart. const emPx = 10 + 0.6; for (const [text, needPx] of [ @@ -183,21 +183,21 @@ test('emoji and other astral glyphs in a progress label get at least 1 em each', }); test('a label is as wide as its wider line, its smaller detail line included', () => { - // The detail line's is 1/1.2 of 10 px; its 0.6 px spacing is not. - const detailEmPx = 10 / 1.2 + 0.6; - const detail = '中央駅前'; // 4 full-width glyphs - const givenPx = estimateProgressLabelPx({ text: 'GATE', detail }); assert.ok( - givenPx > estimateProgressLabelPx({ text: 'GATE', detail: '' }), + estimateProgressLabelPx({ text: 'GATE', detail: '中央駅前' }) > + estimateProgressLabelPx({ text: 'GATE', detail: '' }), 'the wider detail line widens the label', ); - assert.ok( - givenPx >= detail.length * detailEmPx + 8, - `${givenPx} px given, about ${detail.length * detailEmPx} px needed`, - ); - // A line takes less room as the smaller detail than as the title. - assert.ok( - estimateProgressLabelPx({ text: 'A', detail: 'CENTRAL STATION' }) < - estimateProgressLabelPx({ text: 'CENTRAL STATION', detail: '' }), - ); + // As headless Chrome draws the detail's (8.333 px JetBrains Mono, + // 0.6 px apart): 'WWWWMMMMWWWW' at 67.2 px, '中央駅前広場東口' at 72.9 px. + for (const [detail, needPx] of [ + ['W'.repeat(64), 64 * (67.2 / 12)], + ['駅'.repeat(45), 45 * (72.9 / 8)], + ]) { + const givenPx = estimateProgressLabelPx({ text: 'A', detail }); + assert.ok( + givenPx >= needPx, + `${detail.length} × ${detail[0]}: ${givenPx} px given, ${needPx} px needed`, + ); + } }); diff --git a/src/cockpitSubjectProviders.js b/src/cockpitSubjectProviders.js index fa0b4deffb..cb528decfa 100644 --- a/src/cockpitSubjectProviders.js +++ b/src/cockpitSubjectProviders.js @@ -117,13 +117,14 @@ function lookOf(raw) { }); } -/** Promises worded members gave, each one's rejection caught once. */ +/** Promises already given a catch: a pending one is read again on every use. */ const caughtWords = new WeakSet(); /** * A worded member as `read()` gives it, normalized: called on `provider` * when it is a function (so it can follow the page's language); null when it - * is malformed (a promise too) or provider code throws. + * is malformed (a promise too) or provider code throws, its getter included + * (hence `read`). */ function worded(provider, read, normalize) { try { @@ -269,7 +270,6 @@ export function cockpitSubjectProviders( */ function keptProvider(provider, order, words) { let { face, labels, look } = words; - // Look stays on or off, at its rest pitch, as read at registration. const restPitchDeg = look?.restPitchDeg ?? 0; return Object.freeze({ kind: provider.kind, diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index 0aaf4bcf25..439b5fa9f3 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -403,11 +403,18 @@ function updateSubject(nowMs) { this.surfaceWaitStartedMs = 0; this.surfaceAcquiring = false; if (!held) { - // The first height to replace the entry frame's places the anchor - // anew: an inertial one would close on it only at the horizontal - // correction's rate. - if (this.subjectHeightFromEntry && heightM !== this.subjectHeightM) - this.cockpitAnchorValid = false; + // The first height to replace the entry frame's is the anchor's at once + // (an inertial anchor would close on it only at the horizontal + // correction's rate); where the anchor stands, it stays. + if ( + this.subjectHeightFromEntry && + this.cockpitAnchorValid && + heightM !== this.subjectHeightM + ) { + const anchor = toCartographicRadians(this.cockpitAnchor); + if (anchor) + this.cockpitAnchor = fromRadians(anchor.lon, anchor.lat, heightM); + } this.subjectHeightFromEntry = false; } this.subjectHeightM = heightM; @@ -472,9 +479,8 @@ function updateSubject(nowMs) { * Aircraft pass none and look along the heading at the profile pitch. */ function placeCamera(target, info, nowMs, dtSec, profile, look = null) { - // An update that sets the anchor stands it on the target with no step: - // the first one (the time before it, an entry or a floor wait, moved - // nothing), and a subject's whose height replaced its entry frame's. + // The update that first sets the anchor stands it on the target: the time + // before it (an entry, a floor wait) moved nothing, so it has no step. const anchoring = !this.cockpitAnchorValid; if (anchoring) { this.cockpitAnchorValid = true; diff --git a/src/ui/cockpitController.test.mjs b/src/ui/cockpitController.test.mjs index 9a08f13e77..6cea3b1bcb 100644 --- a/src/ui/cockpitController.test.mjs +++ b/src/ui/cockpitController.test.mjs @@ -444,10 +444,10 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async () latitude: 30.19, longitude: -97.67, onGround: false, - stale: true, + stale: false, }; const { owner, views } = cockpitOver({ info, target }); - // Held on the target while the feed is stale. + // The first update stands the anchor on the target. owner.update(); let expected = cesiumCockpitEye(Cesium, { target, @@ -456,13 +456,12 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async () dtSec: 0, liftM: 0, }); - near(views[0].destination, expected.eye, 1e-6, 'stale eye'); + near(views[0].destination, expected.eye, 1e-6, 'first eye'); near(views[0].orientation.direction, expected.forward, 1e-12, 'direction'); near(views[0].orientation.up, expected.up, 1e-12, 'up'); // Live: the anchor coasts 80 ms along the heading and is pulled toward // where the layer now shows the aircraft. - info.stale = false; const anchor = Cesium.Cartesian3.clone(expected.anchor); const moved = Cesium.Cartesian3.fromDegrees(-97.6698, 30.1901, 1210); owner.trackedFollow.position = () => moved; @@ -495,38 +494,6 @@ test('Cockpit places the eye at its aircraft as the Cesium maths did', async () } }); -test("a live aircraft's first Cockpit update stands the anchor on it", async () => { - const Cesium = await import('cesium'); - const env = environment(); - try { - const target = Cesium.Cartesian3.fromDegrees(-97.67, 30.19, 1200); - const info = { - icao24: 'abc123', - layerId: 'flights', - track: 72, - velocityMps: 200, - latitude: 30.19, - longitude: -97.67, - onGround: false, - stale: false, - }; - const { owner, views } = cockpitOver({ info, target }); - // Entry was a while ago: the step would carry the anchor 20 m ahead. - owner.update(); - const expected = cesiumCockpitEye(Cesium, { - target, - info: { ...info, stale: true }, - heading: 72, - dtSec: 0, - liftM: 0, - }); - near(views[0].destination, expected.eye, 1e-6, 'first live eye'); - owner.dispose(); - } finally { - env.restore(); - } -}); - test('a grounded Cockpit probes the mesh from the camera and keeps the eye above the floor', async () => { const Cesium = await import('cesium'); const env = environment(); diff --git a/src/ui/cockpitSignals.js b/src/ui/cockpitSignals.js index 96446163ef..6ed054a0a4 100644 --- a/src/ui/cockpitSignals.js +++ b/src/ui/cockpitSignals.js @@ -56,8 +56,8 @@ export function pushCockpitSignal( { inPlace = false } = {}, ) { if (!title || !detail) return; - // JSON keeps the fields apart: joined with `|`, a title or detail holding a - // `|` read as another pair. An in-place row also changes with its tone alone. + // JSON, not a joined string, so a separator inside a title or detail cannot + // make two rows match. An in-place row also changes with its tone alone. const signature = JSON.stringify([ title, detail, diff --git a/src/ui/cockpitSubjectView.test.mjs b/src/ui/cockpitSubjectView.test.mjs index 7d6150f046..7df612e056 100644 --- a/src/ui/cockpitSubjectView.test.mjs +++ b/src/ui/cockpitSubjectView.test.mjs @@ -219,22 +219,20 @@ function fixture( showBriefPage() {}, startBriefRotation() {}, stopBriefRotation() {}, - pushCockpitSignal(key, tone, title, detail) { - signals.push({ key, tone, title, detail }); - }, - dropCockpitSignal(key) { - dropped.push(key); - }, scheduleContextLayout() {}, updateLocalPosition() {}, maybeRefreshRegionalBrief() {}, showContextCard() {}, }); - if (realSignals) { - // The real Live Signals rows, published, not the recorder above. - delete cockpit.pushCockpitSignal; - delete cockpit.dropCockpitSignal; - } + if (!realSignals) + Object.assign(cockpit, { + pushCockpitSignal(key, tone, title, detail) { + signals.push({ key, tone, title, detail }); + }, + dropCockpitSignal(key) { + dropped.push(key); + }, + }); t.after(() => { cockpit.stop(); app.unmount(); @@ -297,7 +295,7 @@ const lastRelease = (calls) => calls.findLast(([name]) => name === 'release'); /** * Move `ride`'s subject east at `speedMps` from `startMs` (the manual clock's * start) on an inertial anchor, its frame otherwise as it was with `extra` - * on top; returns where it is now (longitude). + * on top; returns a function giving its longitude now. */ function movingEast(ride, startMs, speedMps, extra = {}) { const eastNow = () => @@ -1355,9 +1353,7 @@ test("a moving vessel's first bridge update after entry stands the anchor on its assert.equal(cockpit.enter(), true); clock.advance(1000); cockpit.update(); - const anchor = Cesium.Cartographic.fromCartesian( - Cesium.Cartesian3.clone(cockpit.cockpitAnchor), - ); + const anchor = Cesium.Cartographic.fromCartesian(cockpit.cockpitAnchor); const fix = cockpit.vesselFix; const gapM = Cesium.Cartesian3.distance( Cesium.Cartesian3.fromRadians(anchor.longitude, anchor.latitude, 0), @@ -1564,3 +1560,84 @@ test('an inertial subject placed at its entry height stands on the floor once it `1 s after the floor came the eye is at ${heightM.toFixed(2)} m, not ${floorM + 3.5} m`, ); }); + +/** How far east of LON the camera's last shot is (m). */ +const shotEastM = (shots) => + (Cesium.Math.toDegrees( + Cesium.Cartographic.fromCartesian(shots.at(-1).destination).longitude, + ) - + LON) * + M_PER_DEG_LON; + +test('the first floor after an entry height moves an inertial anchor as a cold floor does', async (t) => { + // The provider corrects its subject 100 m east as the floor arrives. + const run = (warm) => { + const clock = manualClock(t, 10_000); + const ride = subjectProvider(); + ride.subject.frame = { + ...ride.subject.frame, + heightM: FLOOR_M, + speedMps: 0, + anchor: 'inertial', + groundClamp: false, + }; + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + ride.subject.frame = { ...ride.subject.frame, heightM: null }; + clock.advance(100); + cockpit.update(); + const beforeM = shotEastM(shots); + ride.subject.frame = { ...ride.subject.frame, longitude: eastM(100) }; + if (warm) setFloor(FLOOR_M + 0.1); + clock.advance(100); + cockpit.update(); + const stepM = shotEastM(shots) - beforeM; + const heightM = shotHeight(shots); + cockpit.stop(); + return { stepM, heightM }; + }; + const cold = run(false); + const warm = run(true); + assert.ok( + Math.abs(warm.stepM - cold.stepM) < 0.02, + `east step ${warm.stepM.toFixed(3)} m with the floor arriving, ${cold.stepM.toFixed(3)} m with it cold`, + ); + assert.ok(Math.abs(warm.heightM - (FLOOR_M + 0.1 + 3.5)) < 0.02); +}); + +test('the first floor after an entry height never steps an inertial anchor back to a held fix', async (t) => { + const startMs = 10_000; + const clock = manualClock(t, startMs); + const ride = subjectProvider(); + const base = { + ...ride.subject.frame, + heightM: FLOOR_M, + speedMps: 30, + anchor: 'inertial', + groundClamp: false, + }; + ride.subject.frame = base; + const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] }); + setFloor(undefined); + cockpit.syncEntry(); + assert.equal(cockpit.enter(), true); + // Telemetry that gives a new fix once a second, 30 m on each time. + ride.subject.frame = () => ({ + ...base, + heightM: null, + longitude: eastM(30 * Math.floor((performance.now() - startMs) / 1000)), + }); + for (let i = 0; i < 17; i += 1) { + clock.advance(100); + cockpit.update(); + } + const beforeM = shotEastM(shots); + // The floor arrives 1 cm off the entry height, between two fixes. + setFloor(FLOOR_M + 0.01); + clock.advance(100); + cockpit.update(); + const stepM = shotEastM(shots) - beforeM; + assert.ok(stepM > 0, `the eye stepped ${stepM.toFixed(2)} m east`); +}); From 5234747b2232134e13950638d286de51319a5386 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 18 Nov 2026 13:10:35 -0800 Subject: [PATCH 18/18] changelog: name PR #1805 --- changelog.d/1805-timeline-real-time.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/1805-timeline-real-time.md b/changelog.d/1805-timeline-real-time.md index 769a49f284..734c5d18aa 100644 --- a/changelog.d/1805-timeline-real-time.md +++ b/changelog.d/1805-timeline-real-time.md @@ -1 +1 @@ -- The world timeline's speed control names its real-time speed **Real-time** instead of `1×`, beside `1 min/s`, `1 h/s`, `1 d/s` and `1 wk/s` (Sameh Khamis, @samehkhamis, #XXXX). +- The world timeline's speed control names its real-time speed **Real-time** instead of `1×`, beside `1 min/s`, `1 h/s`, `1 d/s` and `1 wk/s` (Sameh Khamis, @samehkhamis, #1805).