From b65bb86db325ae023ffa976b18fbca73bd968d07 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 16:13:28 -0800 Subject: [PATCH 1/6] vessels: project label candidates with the camera read once per pass The label pass projects every vessel in view each time it runs. It asked Cesium for each one, which reads the camera and allocates for every point. createWindowProjector reads the camera's matrices and the canvas size once and runs the same arithmetic in the same order, so the window positions are the same numbers (a test compares them bit for bit with Cesium); outside a 3D perspective view it asks Cesium as before. Grid cells are keyed by number, a cell's candidate is made only for its first vessel and updated in place, and whether a name is worth a card is kept per vessel until its name, MMSI or id changes. Measured in the browser (perf harness, 9,000 vessels, 1 min/s): the label pass 33 ms -> 11 ms, the forced visibility pass 42 ms -> 27 ms. --- scripts/package-boundaries.json | 3 + src/data/windowProjection.js | 65 +++++++++++++++ src/data/windowProjection.test.mjs | 122 +++++++++++++++++++++++++++++ src/layers/vessels/rendering.js | 63 +++++++++++---- 4 files changed, 239 insertions(+), 14 deletions(-) create mode 100644 src/data/windowProjection.js create mode 100644 src/data/windowProjection.test.mjs diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ec76dd86f..2aa8c9452 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1734,6 +1734,7 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -3038,6 +3039,7 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -4232,6 +4234,7 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", diff --git a/src/data/windowProjection.js b/src/data/windowProjection.js new file mode 100644 index 000000000..5533103cb --- /dev/null +++ b/src/data/windowProjection.js @@ -0,0 +1,65 @@ +import * as Cesium from 'cesium'; + +/** + * A projector from world positions to window coordinates for one pass over + * many positions under one camera, giving what + * `Cesium.SceneTransforms.worldToWindowCoordinates` gives: in a 3D scene with + * a perspective camera it runs the same arithmetic in the same order once the + * camera's matrices and the canvas size are read, so the results are the same + * numbers; otherwise it asks Cesium for each. + * + * Read the camera again (a new projector) whenever it may have moved. + * @param {Cesium.Scene} scene + * @returns {(position: Cesium.Cartesian3, result: Cesium.Cartesian2) => + * Cesium.Cartesian2|undefined} The window position in `result`, or + * undefined behind the camera. + */ +export function createWindowProjector(scene) { + const camera = scene?.camera; + const frustum = camera?.frustum; + if ( + scene?.frameState?.mode !== Cesium.SceneMode.SCENE3D || + !camera || + frustum instanceof Cesium.OrthographicFrustum || + frustum instanceof Cesium.OrthographicOffCenterFrustum + ) + return (position, result) => + Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result); + const v = camera.viewMatrix; + const p = frustum.projectionMatrix; + const width = scene.canvas.clientWidth; + const height = scene.canvas.clientHeight; + const halfWidth = width * 0.5; + const halfHeight = height * 0.5; + return (position, result) => { + if (!position) + return Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + position, + result, + ); + const { x, y, z } = position; + // Eye coordinates, as Matrix4.multiplyByVector computes them (w = 1). + const ex = v[0] * x + v[4] * y + v[8] * z + v[12]; + const ey = v[1] * x + v[5] * y + v[9] * z + v[13]; + const ez = v[2] * x + v[6] * y + v[10] * z + v[14]; + const ew = v[3] * x + v[7] * y + v[11] * z + v[15]; + // At the eye itself Cesium's own steps have no direction to take. + if (ex === 0 && ey === 0 && ez === 0) + return Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + position, + result, + ); + // Clip coordinates. + const cx = p[0] * ex + p[4] * ey + p[8] * ez + p[12] * ew; + const cy = p[1] * ex + p[5] * ey + p[9] * ez + p[13] * ew; + const cz = p[2] * ex + p[6] * ey + p[10] * ez + p[14] * ew; + const cw = p[3] * ex + p[7] * ey + p[11] * ez + p[15] * ew; + if (cz < 0) return undefined; + // The viewport transform of the canvas, then window y downward. + result.x = halfWidth * (cx / cw) + halfWidth; + result.y = height - (halfHeight * (cy / cw) + halfHeight); + return result; + }; +} diff --git a/src/data/windowProjection.test.mjs b/src/data/windowProjection.test.mjs new file mode 100644 index 000000000..ae1fe4883 --- /dev/null +++ b/src/data/windowProjection.test.mjs @@ -0,0 +1,122 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { createWindowProjector } from './windowProjection.js'; + +function sceneLooking( + lon, + lat, + heightM, + pitchDeg, + mode = Cesium.SceneMode.SCENE3D, +) { + const scene = { + canvas: { clientWidth: 1713, clientHeight: 941 }, + drawingBufferWidth: 1713, + drawingBufferHeight: 941, + mapProjection: new Cesium.GeographicProjection(), + ellipsoid: Cesium.Ellipsoid.WGS84, + frameState: { mode, mapProjection: new Cesium.GeographicProjection() }, + globe: undefined, + tweens: { add() {} }, + screenSpaceCameraController: { minimumZoomDistance: 1 }, + }; + scene.camera = new Cesium.Camera(scene); + scene.camera.frustum.aspectRatio = 1713 / 941; + scene.camera.setView({ + destination: Cesium.Cartesian3.fromDegrees(lon, lat, heightM), + orientation: { + heading: 0.3, + pitch: Cesium.Math.toRadians(pitchDeg), + roll: 0, + }, + }); + return scene; +} + +function positionsAround(lon, lat, spreadDeg, count) { + let seed = 7; + const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + return Array.from({ length: count }, () => + Cesium.Cartesian3.fromDegrees( + lon + (rnd() - 0.5) * spreadDeg, + lat + (rnd() - 0.5) * spreadDeg, + rnd() * 50, + ), + ); +} + +test('a 3D perspective projector gives the same numbers Cesium gives', () => { + for (const [pitch, spread, heightM] of [ + [-90, 1, 60_000], + [-35, 4, 60_000], + [-5, 40, 60_000], + // Just above the sea, points near and behind the near plane. + [-10, 0.002, 3], + ]) { + const scene = sceneLooking(4.1, 51.95, heightM, pitch); + const project = createWindowProjector(scene); + let behind = 0; + for (const position of positionsAround(4.1, 51.95, spread, 2000)) { + const expected = Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + position, + new Cesium.Cartesian2(), + ); + const actual = project(position, new Cesium.Cartesian2()); + if (!expected) { + behind++; + assert.equal(actual, undefined); + continue; + } + assert.equal(actual.x, expected.x); + assert.equal(actual.y, expected.y); + } + if (pitch === -5) + assert.ok(behind > 0, 'some positions fall behind the camera'); + } +}); + +test('outside a 3D scene the projector asks Cesium', () => { + const scene = sceneLooking( + 4.1, + 51.95, + 60_000, + -90, + Cesium.SceneMode.COLUMBUS_VIEW, + ); + const calls = []; + const original = Cesium.SceneTransforms.worldToWindowCoordinates; + Cesium.SceneTransforms.worldToWindowCoordinates = (...args) => { + calls.push(args); + return args[2]; + }; + try { + const result = new Cesium.Cartesian2(); + const position = Cesium.Cartesian3.fromDegrees(4.1, 51.95); + assert.equal(createWindowProjector(scene)(position, result), result); + assert.equal(calls.length, 1); + assert.equal(calls[0][1], position); + } finally { + Cesium.SceneTransforms.worldToWindowCoordinates = original; + } +}); + +test('at the eye itself, or with no position, the projector asks Cesium', () => { + const scene = sceneLooking(4.1, 51.95, 60_000, -90); + const original = Cesium.SceneTransforms.worldToWindowCoordinates; + const asked = []; + Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => { + asked.push(position); + return undefined; + }; + try { + const project = createWindowProjector(scene); + const eye = Cesium.Cartesian3.clone(scene.camera.positionWC); + assert.equal(project(eye, new Cesium.Cartesian2()), undefined); + assert.equal(project(undefined, new Cesium.Cartesian2()), undefined); + assert.deepEqual(asked, [eye, undefined]); + } finally { + Cesium.SceneTransforms.worldToWindowCoordinates = original; + } +}); diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index cc49ce7b4..bb4c2aa90 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -31,6 +31,12 @@ import { } from '../../data/fleetModels.js'; import { createFleetModelLayer } from '../../data/fleetModelInstances.js'; import { isAidToNavigation } from '../../data/vesselTypes.js'; +import { createWindowProjector } from '../../data/windowProjection.js'; + +// Label grid cells are keyed by column * LABEL_CELL_ROW + row, unique while +// rows stay within half of it either side; a cell further off screen is keyed +// by its text. +const LABEL_CELL_ROW = 1 << 20; /** A moving vessel's next frame is asked for once it would move this far on * screen (pixels), so it glides when it moves visibly and the scene idles @@ -70,6 +76,7 @@ export function createRendering({ }) { const { state } = vesselState; let visualRecords = new WeakMap(); + const labelScreenScratch = new Cesium.Cartesian2(); // The fallback preserves helper calls with externally supplied render records. function getVisual(record) { @@ -1038,25 +1045,30 @@ export function createRendering({ return; } + // Every vessel in view is projected, so the camera is read once and each + // is a few multiplications (see windowProjection.js) into one screen + // point; a cell gets a candidate only for the vessel that leads it. + const project = createWindowProjector(scene); const cells = new Map(); for (const record of records) { - const visual = getVisual(record); if (record === selected) continue; - const screen = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - visual.position, - ); + const screen = project(getVisual(record).position, labelScreenScratch); if (!screen) continue; - const key = `${Math.floor(screen.x / LABEL_GRID_PX)}:${Math.floor(screen.y / LABEL_GRID_PX)}`; - const candidate = { - record, - score: labelPriority(record, selected), - x: screen.x, - y: screen.y, - }; + const column = Math.floor(screen.x / LABEL_GRID_PX); + const row = Math.floor(screen.y / LABEL_GRID_PX); + const key = + Math.abs(row) < LABEL_CELL_ROW / 2 && Math.abs(column) < LABEL_CELL_ROW + ? column * LABEL_CELL_ROW + row + : `${column}:${row}`; + const score = labelPriority(record, selected); const existing = cells.get(key); - if (!existing || candidate.score > existing.score) { - cells.set(key, candidate); + if (!existing) { + cells.set(key, { record, score, x: screen.x, y: screen.y }); + } else if (score > existing.score) { + existing.record = record; + existing.score = score; + existing.x = screen.x; + existing.y = screen.y; } } @@ -1148,7 +1160,30 @@ export function createRendering({ return score; } + // Whether a vessel's name is worth a card, kept per vessel until what it + // is judged from changes: the label pass asks for every vessel in view. + const usefulNames = new WeakMap(); + function hasUsefulName(record) { + const known = usefulNames.get(record); + if ( + known && + known.name === record.name && + known.mmsi === record.mmsi && + known.id === record.id + ) + return known.useful; + const useful = nameIsUseful(record); + usefulNames.set(record, { + name: record.name, + mmsi: record.mmsi, + id: record.id, + useful, + }); + return useful; + } + + function nameIsUseful(record) { const text = String(record.name || '').trim(); return Boolean( text && From 121b69561a3edf50f7a5223e922acf917ce88c44 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 16:13:28 -0800 Subject: [PATCH 2/6] timeline: read each entry's time once when merging runs mergeTimelineRuns read an entry's time again on every comparison, and the vessel layer passed a new arrow for every vessel. Times are now read once into arrays, the leading older entries the loop would keep one by one are sliced in one step, and the layer passes one function. The result is the same entries in the same order; a test checks 3,000 random merges against the previous algorithm. Measured in the browser, one implementation per page, 9,000 vessels with 240 kept fixes each, 5 alternating pairs: 65-87 ms -> 57-61 ms per snapshot. --- src/layers/vessels/records.js | 5 +- src/time/timelineFixes.js | 47 ++++++++++++----- src/time/timelineFixes.test.mjs | 93 +++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 13 deletions(-) diff --git a/src/layers/vessels/records.js b/src/layers/vessels/records.js index c0ad357e8..e18d380db 100644 --- a/src/layers/vessels/records.js +++ b/src/layers/vessels/records.js @@ -58,6 +58,9 @@ function stampFix(record, receivedAtMs, feedLatestEpoch) { record.fixFeedEpoch = feedLatestEpoch; } +/** A fix's time, as the fixes are merged (one function for every vessel). */ +const fixTime = (fix) => fix.atMs; + function positiveNumber(value) { const number = finiteNumber(value); return number !== null && number > 0 ? number : null; @@ -164,7 +167,7 @@ export class VesselRecords { ? mergeTimelineRuns( record.fixes ?? [], next.fixes, - (fix) => fix.atMs, + fixTime, (next.lastPositionEpoch ?? 0) * 1000, ) : null; diff --git a/src/time/timelineFixes.js b/src/time/timelineFixes.js index e8b078cc3..5ba1c24e3 100644 --- a/src/time/timelineFixes.js +++ b/src/time/timelineFixes.js @@ -82,43 +82,66 @@ export function mergeTimelineRuns( centreMs, limit = TIMELINE_FIXES_LIMIT, ) { - const first = newer.length ? timeOf(newer[0]) : Infinity; - const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity; + // Each entry's time is read once: a layer merges a run for every contact + // in a snapshot, each holding up to `limit` entries. + const olderTimes = new Array(older.length); + for (let k = 0; k < older.length; k++) olderTimes[k] = timeOf(older[k]); + const newerTimes = new Array(newer.length); + for (let k = 0; k < newer.length; k++) newerTimes[k] = timeOf(newer[k]); + const first = newer.length ? newerTimes[0] : Infinity; + const last = newer.length ? newerTimes[newer.length - 1] : -Infinity; const newest = newer[newer.length - 1]; + // The older entries before the newer run that the loop below would keep + // one by one, each far enough from the one before, are taken at once: a + // contact's kept entries mostly stand before each snapshot's run. + let lead = 0; + while ( + lead < older.length && + !(olderTimes[lead] >= first && olderTimes[lead] <= last) && + (newer.length === 0 || olderTimes[lead] < first) && + (lead === 0 || + olderTimes[lead] - olderTimes[lead - 1] >= TIMELINE_FIX_SPACING_MS) + ) + lead++; // Both runs in order, the older entries within the newer run's time left // out, thinned to the spacing. - const merged = []; - const take = (entry) => { + const merged = older.slice(0, lead); + const times = olderTimes.slice(0, lead); + const take = (entry, t) => { const k = merged.length - 1; - if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= TIMELINE_FIX_SPACING_MS) { + if (k < 0 || t - times[k] >= TIMELINE_FIX_SPACING_MS) { merged.push(entry); + times.push(t); } else if (entry === newest) { merged[k] = entry; + times[k] = t; } }; - let i = 0; + let i = lead; let j = 0; while (i < older.length || j < newer.length) { if (i < older.length) { - const t = timeOf(older[i]); + const t = olderTimes[i]; if (t >= first && t <= last) { i++; continue; } - if (j >= newer.length || t < timeOf(newer[j])) { - take(older[i++]); + if (j >= newer.length || t < newerTimes[j]) { + take(older[i], t); + i++; continue; } } - take(newer[j++]); + take(newer[j], newerTimes[j]); + j++; } if (merged.length <= limit) return merged; // The window of `limit` entries nearest the centre. let start = 0; while ( start + limit < merged.length && - Math.abs(timeOf(merged[start + limit]) - centreMs) < - Math.abs(timeOf(merged[start]) - centreMs) + Math.abs(times[start + limit] - centreMs) < + Math.abs(times[start] - centreMs) ) start++; return merged.slice(start, start + limit); diff --git a/src/time/timelineFixes.test.mjs b/src/time/timelineFixes.test.mjs index 9ab47c184..346388872 100644 --- a/src/time/timelineFixes.test.mjs +++ b/src/time/timelineFixes.test.mjs @@ -96,3 +96,96 @@ test('past the limit only the fixes nearest the centre are kept', () => { [0, 1, 2, 3], ); }); + +/** The merge as first written, a reference the faster one must match. */ +function referenceMerge(older, newer, timeOf, centreMs, limit = 240) { + const SPACING = 20_000; + const first = newer.length ? timeOf(newer[0]) : Infinity; + const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity; + const newest = newer[newer.length - 1]; + const merged = []; + const take = (entry) => { + const k = merged.length - 1; + if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= SPACING) + merged.push(entry); + else if (entry === newest) merged[k] = entry; + }; + let i = 0; + let j = 0; + while (i < older.length || j < newer.length) { + if (i < older.length) { + const t = timeOf(older[i]); + if (t >= first && t <= last) { + i++; + continue; + } + if (j >= newer.length || t < timeOf(newer[j])) { + take(older[i++]); + continue; + } + } + take(newer[j++]); + } + if (merged.length <= limit) return merged; + let start = 0; + while ( + start + limit < merged.length && + Math.abs(timeOf(merged[start + limit]) - centreMs) < + Math.abs(timeOf(merged[start]) - centreMs) + ) + start++; + return merged.slice(start, start + limit); +} + +test('the merge keeps exactly what it always kept, for runs of every shape', () => { + let seed = 3; + const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const run = (n, from, stepMs, sorted) => { + const out = Array.from({ length: n }, (_, k) => ({ + atMs: + rnd() < 0.05 + ? Number.NaN + : from + + Math.round((sorted ? k : rnd() * n) * stepMs * (0.5 + rnd())), + })); + if (sorted) out.sort((a, b) => a.atMs - b.atMs); + return out; + }; + for (let round = 0; round < 3000; round++) { + const sorted = round % 5 !== 0; + const older = run( + Math.floor(rnd() * 300), + Math.floor(rnd() * 4e6), + 15_000 + rnd() * 50_000, + sorted, + ); + const newer = run( + Math.floor(rnd() * 30), + Math.floor(rnd() * 6e6), + 5_000 + rnd() * 70_000, + sorted, + ); + // The newest of the newer run is sometimes an entry of the older one. + if (newer.length && older.length && rnd() < 0.1) + newer[newer.length - 1] = older[older.length - 1]; + const centreMs = rnd() * 7e6; + const limit = rnd() < 0.5 ? 240 : 1 + Math.floor(rnd() * 40); + const expected = referenceMerge( + older, + newer, + (f) => f.atMs, + centreMs, + limit, + ); + const actual = mergeTimelineRuns( + older, + newer, + (f) => f.atMs, + centreMs, + limit, + ); + assert.equal(actual.length, expected.length, `round ${round}`); + for (let k = 0; k < expected.length; k++) + assert.equal(actual[k], expected[k], `round ${round} entry ${k}`); + } +}); From 3909c7735a41038afff49ff7c47ebc48d403b802 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 16:13:56 -0800 Subject: [PATCH 3/6] changelog: vessel labels and fix merge --- changelog.d/1757-vessel-labels-merge.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1757-vessel-labels-merge.md diff --git a/changelog.d/1757-vessel-labels-merge.md b/changelog.d/1757-vessel-labels-merge.md new file mode 100644 index 000000000..4aff2b35e --- /dev/null +++ b/changelog.d/1757-vessel-labels-merge.md @@ -0,0 +1,3 @@ +### Changed + +- Playing the world clock with thousands of vessels in view spends less time choosing which vessels get name cards (about a third of the time before) and merging each vessel's kept positions at every snapshot. From d232d9afe41714923cdfbbd12c86256ca6bde2ed Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 17:41:37 -0800 Subject: [PATCH 4/6] flights: grounded aircraft turn 3D as soon as the tiles settle Tiles still streaming no longer count as a failed ground sample: they leave the retry backoff alone and return the last measured ground, if any, so the first tick after the tiles settle samples and hands the icon to the model. --- docs/CURRENT-STATE.md | 2 +- src/data/trackedModelRegime.test.mjs | 30 ++++------ src/services/groundSnap.js | 22 ++++--- src/services/groundSnap.test.mjs | 87 ++++++++++++++++++++++++++-- 4 files changed, 108 insertions(+), 33 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7d6fc3698..51c359573 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7655,7 +7655,7 @@ pins and share links already supply complete boxes. ### 3D Aircraft + Tracking (June 2026) - **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load. -- **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. +- **Grounded 3D handoff is terrain-validity gated (2026-08-23).** A ready civilian or military glTF does not own the visual until `groundSnap` (`src/data/groundSnap.js`) can answer with a MEASURED photoreal-surface height. On success the layer writes `height + the model's measured belly offset` before revealing the model. Cache movement is measured on the WGS84 surface, not across altitude, so a stationary contact keeps its snap through poll-time vertical-datum changes. Model existence or GPU readiness alone never suppresses the billboard floor, and ordinary zoom/style/deselect transitions preserve a valid snap cache. **Two states, and the difference is the whole design.** COLD — nothing has ever resolved for this icao (tiles still streaming on first sight, sample failure, backoff after a first miss): there is no evidence of where the ground is, `heightFor` returns null, the model stays hidden and the depth-test-free 2D billboard remains opaque and floored. Tiles still streaming is not a miss: no sample is taken, so it earns no retry backoff, and the first fleet tick after the tiles settle samples (2026-11-15); only a sample that finds no ground backs off (2 s, doubling to 30 s). WARM — a snap resolved and then a >`MOVE_INVALIDATE_M` (50 m) taxi move stopped it answering directly: the measurement is DEMOTED to a bounded last-known rather than deleted, and it keeps answering while the resample is outstanding, so a taxiing aircraft does not pop 3D→2D→3D across a 2–30 s retry backoff. The bound is `HELD_SNAP_MAX_DRIFT_M` = 250 m from the spot the value was measured at, past which the hold is dropped rather than stretched and the contact is COLD again. It is spatial with no timer beside it (ground under a contact that has not moved does not change; what invalidates the value is the contact MOVING) and deliberately a quarter of the billboard chain's `HELD_FLOOR_MAX_DRIFT_KM` — that hold only ever RAISES a sprite, while a held snap IS the model's placement, so its error shows in both directions. A fresh sample releases the hold, and so does a ground flip (which already calls `forget`). **A loading model is HIDDEN, never zero-scaled:** admission sets `show = false` (Cesium's default is `true`, and an unplaced primitive would claim the visual at the identity matrix), and ownership is `ready && show` — Cesium 1.138's `Model.update` has no `show` guard, so hiding a primitive costs its load nothing. - **Ground-snap clock rollback recovery.** If the wall clock moves before the sampling-window start, ground snap opens a new window while retaining the normal four-samples-per-250-ms budget. Retry timestamps more than the maximum diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index e673775cd..71cdc82c8 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -373,16 +373,12 @@ for (const fixture of LAYERS) { assert.ok(model.show || billboard.show, 'the contact never has both visuals hidden'); assert.equal(sampleCalls, 0, 'cold tiles do not force sampleHeight'); - now += 1000; + // Streaming tiles are not a miss, so they earn no retry backoff: the + // first frame after the tiles settle samples and hands over. + now += 100; viewer.tileset.tilesLoaded = true; ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); - assert.equal(ownsVisual, false, 'the miss backoff remains in force before two seconds'); - assert.equal(sampleCalls, 0, 'backoff prevents an early synchronous sample'); - assert.ok(model.show || billboard.show, 'backoff still leaves a visible owner'); - - now += 1500; - ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); - assert.equal(ownsVisual, true, 'the model takes over after a valid terrain sample'); + assert.equal(ownsVisual, true, 'the model takes over on the first settled frame'); assert.equal(sampleCalls, 1, 'the settled terrain is sampled exactly once'); assert.equal(model.show, true); assert.equal(billboard.show, false); @@ -403,13 +399,13 @@ for (const fixture of LAYERS) { // Taxi past the 50 m resample threshold while the tiles are gone. The old // snap stops being the direct answer, but it is still a MEASUREMENT of // ground this contact was standing on ~96 m ago, so it is held: hiding the - // model here would pop a taxiing aircraft from 3D to 2D for a whole retry - // backoff (2–30 s), which is the one thing the gate must not introduce. + // model here would pop a taxiing aircraft from 3D to 2D until the tiles + // return, which is the one thing the gate must not introduce. const taxied = Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500); ownsVisual = fixture.driveFleetModel({ icao24, position: taxied, course: 92 }); assert.equal(ownsVisual, true, 'a taxi-invalidated snap is HELD through the resample outage, not dropped'); - assert.equal(model.show, true, 'no 3D→2D pop while the resample is backing off'); + assert.equal(model.show, true, 'no 3D→2D pop while the resample waits for tiles'); assert.equal(billboard.show, false); assert.equal(sampleCalls, 1, 'and the hold costs no extra synchronous sample'); const held = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3()); @@ -646,17 +642,11 @@ for (const fixture of LAYERS) { 1e-6, ), 'a hidden tracked model cannot steal the proximity position'); - now += 1000; + // Streaming tiles earned no backoff, so the first settled turn samples. + now += 100; viewer.tileset.tilesLoaded = true; sampledHeight = 187.5; fixture.driveTrackedModel(); - assert.equal(sampleCalls, 0, 'the tracked path honors the same retry backoff before sampling'); - assert.equal(model.show, false, 'retry backoff keeps the unplaced primitive hidden'); - assert.equal(fixture.trackedBillboardColor().alpha, 1, - 'retry backoff leaves the tracked billboard opaque'); - - now += 1500; - fixture.driveTrackedModel(); assert.equal(sampleCalls, 1, 'the first settled turn samples once'); assert.equal(model.show, false, 'terrain alone does not reveal an unready model'); assert.equal(fixture.trackedBillboardColor().alpha, 1, @@ -683,7 +673,7 @@ for (const fixture of LAYERS) { // Taxi past the resample threshold with the tiles gone: the tracked model // holds its last measured floor rather than handing the operator's own - // selection back to a 2D glyph for a retry backoff. + // selection back to a 2D glyph until the tiles return. billboard.position = Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500); fixture.driveTrackedModel(); assert.equal(model.show, true, diff --git a/src/services/groundSnap.js b/src/services/groundSnap.js index b1d75cfbb..35fd9e8ff 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -11,11 +11,16 @@ * Discipline (CCTV-B9b style): scene.sampleHeight forces a synchronous offscreen * pick render, so it is NEVER called per frame. Each grounded modeled plane gets * ONE successful sample, cached per icao; the cache stops answering directly when - * the plane moves >MOVE_INVALIDATE_M from the sampled spot (taxiing). Misses (tiles - * still streaming, OSM fallback with no tileset skin, sample outside loaded - * geometry) are a retry-later signal with per-icao exponential backoff. A - * per-window budget stops a freshly modeled airport cluster from firing dozens of - * pick renders in one fleet tick. + * the plane moves >MOVE_INVALIDATE_M from the sampled spot (taxiing). A sample + * that misses (OSM fallback with no tileset skin, sample outside loaded + * geometry) is a retry-later signal with per-icao exponential backoff. Tiles + * still streaming is not a miss: no sample was taken, so it earns no backoff + * and the plane asks again on the next tick, sampling as soon as the tiles + * settle. Counting it as a miss had every grounded plane in view back off to + * RETRY_MAX_MS while the camera moved, then wait out that backoff after the + * tiles had loaded, so models replaced icons late and in batches. A per-window + * budget stops a freshly modeled airport cluster from firing dozens of pick + * renders in one fleet tick. * * What a caller gets while a sample is outstanding depends on whether this * contact has ever HAD one, and the difference is the difference between two @@ -121,7 +126,7 @@ const HELD_SNAP_MAX_DRIFT_M = 250; * alternative because it errs UPWARD and stays visible, where a buried model * errs into the terrain and cannot be seen at all. */ const HELD_SNAP_CONTRADICTION_M = 5; -/** First retry delay after a miss / tiles-not-ready (ms); doubles per consecutive miss. */ +/** First retry delay after a sample finds no ground (ms); doubles per consecutive miss. */ const RETRY_BASE_MS = 2000; /** Backoff cap (ms) — on the OSM fallback (no tile skin) sampleHeight misses forever. */ const RETRY_MAX_MS = 30000; @@ -345,7 +350,10 @@ export function createGroundSnap({ groundFloor }) { entries.set(icao, next); return heldSnapM(next, surfacePos); }; - if (!_tilesReady(viewer)) return miss(); + // Tiles still streaming: no sample is taken, so no backoff is earned (as + // with the budget above). The next tick asks again, and the first one after + // the tiles settle samples. + if (!_tilesReady(viewer)) return heldSnapM(entry, surfacePos); windowCount += 1; let sampled; try { diff --git a/src/services/groundSnap.test.mjs b/src/services/groundSnap.test.mjs index 8dfe42c46..80f1eded4 100644 --- a/src/services/groundSnap.test.mjs +++ b/src/services/groundSnap.test.mjs @@ -13,13 +13,15 @@ const groundFloor = { function makeViewer() { const calls = { samples: 0 }; const tileset = { show: true, tilesLoaded: true }; + const ground = { heightM: 1650 }; return { calls, + ground, scene: { primitives: { length: 1, get: () => tileset }, sampleHeight() { calls.samples += 1; - return 1650; + return ground.heightM; }, globe: { getHeight: () => 1600 }, }, @@ -49,14 +51,89 @@ test('a retry backoff stamped before the clock stepped back does not wait for it const viewer = makeViewer(); const tileset = viewer.scene.primitives.get(0); const snap = createGroundSnap({ groundFloor }); - // Tiles still streaming: a miss, backed off for 2 s. - tileset.tilesLoaded = false; + // A sample that finds no ground: a miss, backed off for 2 s. + viewer.ground.heightM = undefined; assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); - tileset.tilesLoaded = true; + viewer.ground.heightM = 1650; assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); - assert.equal(viewer.calls.samples, 0, 'the backoff holds'); + assert.equal(viewer.calls.samples, 1, 'the backoff holds'); // The clock steps back an hour: the stamp is an hour off, past any backoff. t.mock.timers.setTime(10_000_000 - 3_600_000); assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); + assert.equal(viewer.calls.samples, 2); +}); + +test('tiles still streaming earn no backoff: the first tick after they settle samples', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 20_000_000 }); + const viewer = makeViewer(); + const tileset = viewer.scene.primitives.get(0); + const snap = createGroundSnap({ groundFloor }); + // The camera moves for 40 s: tiles stream the whole time, and the aircraft + // asks on every tick. + tileset.tilesLoaded = false; + for (let ms = 0; ms <= 40_000; ms += 100) { + t.mock.timers.setTime(20_000_000 + ms); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + } + assert.equal(viewer.calls.samples, 0, 'nothing samples while tiles stream'); + // The tiles settle: the very next tick samples, with no backoff to wait out. + tileset.tilesLoaded = true; + t.mock.timers.setTime(20_000_000 + 40_100); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); assert.equal(viewer.calls.samples, 1); }); + +test('a held measurement still answers while tiles stream', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 30_000_000 }); + const viewer = makeViewer(); + const tileset = viewer.scene.primitives.get(0); + const snap = createGroundSnap({ groundFloor }); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); + // Taxi 100 m: the snap is demoted to a held value and a resample is due, + // but the tiles are streaming. The held value answers. + tileset.tilesLoaded = false; + const taxied = Cesium.Cartesian3.fromDegrees(-104.6737, 39.857, 0); + assert.equal(snap.heightFor(viewer, 'a00001', taxied), 1650); + assert.equal(viewer.calls.samples, 1); + // Tiles settle: the resample runs at once and answers fresh. + viewer.ground.heightM = 1652; + tileset.tilesLoaded = true; + assert.equal(snap.heightFor(viewer, 'a00001', taxied), 1652); + assert.equal(viewer.calls.samples, 2); +}); + +test('a sample that finds no ground still backs off', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 40_000_000 }); + const viewer = makeViewer(); + const snap = createGroundSnap({ groundFloor }); + viewer.ground.heightM = undefined; + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + t.mock.timers.setTime(40_000_000 + 1_000); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(viewer.calls.samples, 1, 'inside the 2 s backoff'); + t.mock.timers.setTime(40_000_000 + 2_001); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(viewer.calls.samples, 2, 'retried once the backoff ended'); +}); + +test('streaming tiles after a real miss leave its backoff as it was', (t) => { + t.mock.timers.enable({ apis: ['Date'], now: 50_000_000 }); + const viewer = makeViewer(); + const tileset = viewer.scene.primitives.get(0); + const snap = createGroundSnap({ groundFloor }); + // One real miss: backed off for 2 s. + viewer.ground.heightM = undefined; + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + // Tiles stream on every tick of that backoff and past it. + tileset.tilesLoaded = false; + for (let ms = 100; ms <= 3_000; ms += 100) { + t.mock.timers.setTime(50_000_000 + ms); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + } + // They settle 3 s in: still the first 2 s backoff, not a doubled 4 s one. + viewer.ground.heightM = 1650; + tileset.tilesLoaded = true; + t.mock.timers.setTime(50_000_000 + 3_100); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); + assert.equal(viewer.calls.samples, 2); +}); From 2fa89a98aeac827d071576a69d2ea2f1f02610e1 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 17:41:58 -0800 Subject: [PATCH 5/6] changelog: grounded aircraft models after the tiles settle --- changelog.d/1758-ground-models-at-once.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1758-ground-models-at-once.md diff --git a/changelog.d/1758-ground-models-at-once.md b/changelog.d/1758-ground-models-at-once.md new file mode 100644 index 000000000..4c8e08cc1 --- /dev/null +++ b/changelog.d/1758-ground-models-at-once.md @@ -0,0 +1,3 @@ +### Fixed + +- A grounded aircraft turns from its icon into its 3D model as soon as the 3D tiles under it have loaded. Tiles still streaming no longer count as a failed ground sample, so after a pan the models no longer appear late and in batches, up to half a minute after the view settled. From 33c98118ba7783ee61559b93ed10b31c163e41a2 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 18:18:42 -0800 Subject: [PATCH 6/6] Revert "Merge pull request #1757 from bilawalsidhu/perf/vessel-labels-merge" This reverts commit 15d1855dd351c416565bb71a63acb4c395ec8645, reversing changes made to 663b56f6208adca70ea06b897a352c56036c3c80. --- changelog.d/1757-vessel-labels-merge.md | 3 - scripts/package-boundaries.json | 3 - src/data/windowProjection.js | 65 ------------- src/data/windowProjection.test.mjs | 122 ------------------------ src/layers/vessels/records.js | 5 +- src/layers/vessels/rendering.js | 63 +++--------- src/time/timelineFixes.js | 47 +++------ src/time/timelineFixes.test.mjs | 93 ------------------ 8 files changed, 27 insertions(+), 374 deletions(-) delete mode 100644 changelog.d/1757-vessel-labels-merge.md delete mode 100644 src/data/windowProjection.js delete mode 100644 src/data/windowProjection.test.mjs diff --git a/changelog.d/1757-vessel-labels-merge.md b/changelog.d/1757-vessel-labels-merge.md deleted file mode 100644 index 4aff2b35e..000000000 --- a/changelog.d/1757-vessel-labels-merge.md +++ /dev/null @@ -1,3 +0,0 @@ -### Changed - -- Playing the world clock with thousands of vessels in view spends less time choosing which vessels get name cards (about a third of the time before) and merging each vessel's kept positions at every snapshot. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 2aa8c9452..ec76dd86f 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1734,7 +1734,6 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", - "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -3039,7 +3038,6 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", - "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -4234,7 +4232,6 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", - "src/data/windowProjection.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", diff --git a/src/data/windowProjection.js b/src/data/windowProjection.js deleted file mode 100644 index 5533103cb..000000000 --- a/src/data/windowProjection.js +++ /dev/null @@ -1,65 +0,0 @@ -import * as Cesium from 'cesium'; - -/** - * A projector from world positions to window coordinates for one pass over - * many positions under one camera, giving what - * `Cesium.SceneTransforms.worldToWindowCoordinates` gives: in a 3D scene with - * a perspective camera it runs the same arithmetic in the same order once the - * camera's matrices and the canvas size are read, so the results are the same - * numbers; otherwise it asks Cesium for each. - * - * Read the camera again (a new projector) whenever it may have moved. - * @param {Cesium.Scene} scene - * @returns {(position: Cesium.Cartesian3, result: Cesium.Cartesian2) => - * Cesium.Cartesian2|undefined} The window position in `result`, or - * undefined behind the camera. - */ -export function createWindowProjector(scene) { - const camera = scene?.camera; - const frustum = camera?.frustum; - if ( - scene?.frameState?.mode !== Cesium.SceneMode.SCENE3D || - !camera || - frustum instanceof Cesium.OrthographicFrustum || - frustum instanceof Cesium.OrthographicOffCenterFrustum - ) - return (position, result) => - Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result); - const v = camera.viewMatrix; - const p = frustum.projectionMatrix; - const width = scene.canvas.clientWidth; - const height = scene.canvas.clientHeight; - const halfWidth = width * 0.5; - const halfHeight = height * 0.5; - return (position, result) => { - if (!position) - return Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - result, - ); - const { x, y, z } = position; - // Eye coordinates, as Matrix4.multiplyByVector computes them (w = 1). - const ex = v[0] * x + v[4] * y + v[8] * z + v[12]; - const ey = v[1] * x + v[5] * y + v[9] * z + v[13]; - const ez = v[2] * x + v[6] * y + v[10] * z + v[14]; - const ew = v[3] * x + v[7] * y + v[11] * z + v[15]; - // At the eye itself Cesium's own steps have no direction to take. - if (ex === 0 && ey === 0 && ez === 0) - return Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - result, - ); - // Clip coordinates. - const cx = p[0] * ex + p[4] * ey + p[8] * ez + p[12] * ew; - const cy = p[1] * ex + p[5] * ey + p[9] * ez + p[13] * ew; - const cz = p[2] * ex + p[6] * ey + p[10] * ez + p[14] * ew; - const cw = p[3] * ex + p[7] * ey + p[11] * ez + p[15] * ew; - if (cz < 0) return undefined; - // The viewport transform of the canvas, then window y downward. - result.x = halfWidth * (cx / cw) + halfWidth; - result.y = height - (halfHeight * (cy / cw) + halfHeight); - return result; - }; -} diff --git a/src/data/windowProjection.test.mjs b/src/data/windowProjection.test.mjs deleted file mode 100644 index ae1fe4883..000000000 --- a/src/data/windowProjection.test.mjs +++ /dev/null @@ -1,122 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; -import { createWindowProjector } from './windowProjection.js'; - -function sceneLooking( - lon, - lat, - heightM, - pitchDeg, - mode = Cesium.SceneMode.SCENE3D, -) { - const scene = { - canvas: { clientWidth: 1713, clientHeight: 941 }, - drawingBufferWidth: 1713, - drawingBufferHeight: 941, - mapProjection: new Cesium.GeographicProjection(), - ellipsoid: Cesium.Ellipsoid.WGS84, - frameState: { mode, mapProjection: new Cesium.GeographicProjection() }, - globe: undefined, - tweens: { add() {} }, - screenSpaceCameraController: { minimumZoomDistance: 1 }, - }; - scene.camera = new Cesium.Camera(scene); - scene.camera.frustum.aspectRatio = 1713 / 941; - scene.camera.setView({ - destination: Cesium.Cartesian3.fromDegrees(lon, lat, heightM), - orientation: { - heading: 0.3, - pitch: Cesium.Math.toRadians(pitchDeg), - roll: 0, - }, - }); - return scene; -} - -function positionsAround(lon, lat, spreadDeg, count) { - let seed = 7; - const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647; - return Array.from({ length: count }, () => - Cesium.Cartesian3.fromDegrees( - lon + (rnd() - 0.5) * spreadDeg, - lat + (rnd() - 0.5) * spreadDeg, - rnd() * 50, - ), - ); -} - -test('a 3D perspective projector gives the same numbers Cesium gives', () => { - for (const [pitch, spread, heightM] of [ - [-90, 1, 60_000], - [-35, 4, 60_000], - [-5, 40, 60_000], - // Just above the sea, points near and behind the near plane. - [-10, 0.002, 3], - ]) { - const scene = sceneLooking(4.1, 51.95, heightM, pitch); - const project = createWindowProjector(scene); - let behind = 0; - for (const position of positionsAround(4.1, 51.95, spread, 2000)) { - const expected = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - new Cesium.Cartesian2(), - ); - const actual = project(position, new Cesium.Cartesian2()); - if (!expected) { - behind++; - assert.equal(actual, undefined); - continue; - } - assert.equal(actual.x, expected.x); - assert.equal(actual.y, expected.y); - } - if (pitch === -5) - assert.ok(behind > 0, 'some positions fall behind the camera'); - } -}); - -test('outside a 3D scene the projector asks Cesium', () => { - const scene = sceneLooking( - 4.1, - 51.95, - 60_000, - -90, - Cesium.SceneMode.COLUMBUS_VIEW, - ); - const calls = []; - const original = Cesium.SceneTransforms.worldToWindowCoordinates; - Cesium.SceneTransforms.worldToWindowCoordinates = (...args) => { - calls.push(args); - return args[2]; - }; - try { - const result = new Cesium.Cartesian2(); - const position = Cesium.Cartesian3.fromDegrees(4.1, 51.95); - assert.equal(createWindowProjector(scene)(position, result), result); - assert.equal(calls.length, 1); - assert.equal(calls[0][1], position); - } finally { - Cesium.SceneTransforms.worldToWindowCoordinates = original; - } -}); - -test('at the eye itself, or with no position, the projector asks Cesium', () => { - const scene = sceneLooking(4.1, 51.95, 60_000, -90); - const original = Cesium.SceneTransforms.worldToWindowCoordinates; - const asked = []; - Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => { - asked.push(position); - return undefined; - }; - try { - const project = createWindowProjector(scene); - const eye = Cesium.Cartesian3.clone(scene.camera.positionWC); - assert.equal(project(eye, new Cesium.Cartesian2()), undefined); - assert.equal(project(undefined, new Cesium.Cartesian2()), undefined); - assert.deepEqual(asked, [eye, undefined]); - } finally { - Cesium.SceneTransforms.worldToWindowCoordinates = original; - } -}); diff --git a/src/layers/vessels/records.js b/src/layers/vessels/records.js index e18d380db..c0ad357e8 100644 --- a/src/layers/vessels/records.js +++ b/src/layers/vessels/records.js @@ -58,9 +58,6 @@ function stampFix(record, receivedAtMs, feedLatestEpoch) { record.fixFeedEpoch = feedLatestEpoch; } -/** A fix's time, as the fixes are merged (one function for every vessel). */ -const fixTime = (fix) => fix.atMs; - function positiveNumber(value) { const number = finiteNumber(value); return number !== null && number > 0 ? number : null; @@ -167,7 +164,7 @@ export class VesselRecords { ? mergeTimelineRuns( record.fixes ?? [], next.fixes, - fixTime, + (fix) => fix.atMs, (next.lastPositionEpoch ?? 0) * 1000, ) : null; diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index bb4c2aa90..cc49ce7b4 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -31,12 +31,6 @@ import { } from '../../data/fleetModels.js'; import { createFleetModelLayer } from '../../data/fleetModelInstances.js'; import { isAidToNavigation } from '../../data/vesselTypes.js'; -import { createWindowProjector } from '../../data/windowProjection.js'; - -// Label grid cells are keyed by column * LABEL_CELL_ROW + row, unique while -// rows stay within half of it either side; a cell further off screen is keyed -// by its text. -const LABEL_CELL_ROW = 1 << 20; /** A moving vessel's next frame is asked for once it would move this far on * screen (pixels), so it glides when it moves visibly and the scene idles @@ -76,7 +70,6 @@ export function createRendering({ }) { const { state } = vesselState; let visualRecords = new WeakMap(); - const labelScreenScratch = new Cesium.Cartesian2(); // The fallback preserves helper calls with externally supplied render records. function getVisual(record) { @@ -1045,30 +1038,25 @@ export function createRendering({ return; } - // Every vessel in view is projected, so the camera is read once and each - // is a few multiplications (see windowProjection.js) into one screen - // point; a cell gets a candidate only for the vessel that leads it. - const project = createWindowProjector(scene); const cells = new Map(); for (const record of records) { + const visual = getVisual(record); if (record === selected) continue; - const screen = project(getVisual(record).position, labelScreenScratch); + const screen = Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + visual.position, + ); if (!screen) continue; - const column = Math.floor(screen.x / LABEL_GRID_PX); - const row = Math.floor(screen.y / LABEL_GRID_PX); - const key = - Math.abs(row) < LABEL_CELL_ROW / 2 && Math.abs(column) < LABEL_CELL_ROW - ? column * LABEL_CELL_ROW + row - : `${column}:${row}`; - const score = labelPriority(record, selected); + const key = `${Math.floor(screen.x / LABEL_GRID_PX)}:${Math.floor(screen.y / LABEL_GRID_PX)}`; + const candidate = { + record, + score: labelPriority(record, selected), + x: screen.x, + y: screen.y, + }; const existing = cells.get(key); - if (!existing) { - cells.set(key, { record, score, x: screen.x, y: screen.y }); - } else if (score > existing.score) { - existing.record = record; - existing.score = score; - existing.x = screen.x; - existing.y = screen.y; + if (!existing || candidate.score > existing.score) { + cells.set(key, candidate); } } @@ -1160,30 +1148,7 @@ export function createRendering({ return score; } - // Whether a vessel's name is worth a card, kept per vessel until what it - // is judged from changes: the label pass asks for every vessel in view. - const usefulNames = new WeakMap(); - function hasUsefulName(record) { - const known = usefulNames.get(record); - if ( - known && - known.name === record.name && - known.mmsi === record.mmsi && - known.id === record.id - ) - return known.useful; - const useful = nameIsUseful(record); - usefulNames.set(record, { - name: record.name, - mmsi: record.mmsi, - id: record.id, - useful, - }); - return useful; - } - - function nameIsUseful(record) { const text = String(record.name || '').trim(); return Boolean( text && diff --git a/src/time/timelineFixes.js b/src/time/timelineFixes.js index 5ba1c24e3..e8b078cc3 100644 --- a/src/time/timelineFixes.js +++ b/src/time/timelineFixes.js @@ -82,66 +82,43 @@ export function mergeTimelineRuns( centreMs, limit = TIMELINE_FIXES_LIMIT, ) { - // Each entry's time is read once: a layer merges a run for every contact - // in a snapshot, each holding up to `limit` entries. - const olderTimes = new Array(older.length); - for (let k = 0; k < older.length; k++) olderTimes[k] = timeOf(older[k]); - const newerTimes = new Array(newer.length); - for (let k = 0; k < newer.length; k++) newerTimes[k] = timeOf(newer[k]); - const first = newer.length ? newerTimes[0] : Infinity; - const last = newer.length ? newerTimes[newer.length - 1] : -Infinity; + const first = newer.length ? timeOf(newer[0]) : Infinity; + const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity; const newest = newer[newer.length - 1]; - // The older entries before the newer run that the loop below would keep - // one by one, each far enough from the one before, are taken at once: a - // contact's kept entries mostly stand before each snapshot's run. - let lead = 0; - while ( - lead < older.length && - !(olderTimes[lead] >= first && olderTimes[lead] <= last) && - (newer.length === 0 || olderTimes[lead] < first) && - (lead === 0 || - olderTimes[lead] - olderTimes[lead - 1] >= TIMELINE_FIX_SPACING_MS) - ) - lead++; // Both runs in order, the older entries within the newer run's time left // out, thinned to the spacing. - const merged = older.slice(0, lead); - const times = olderTimes.slice(0, lead); - const take = (entry, t) => { + const merged = []; + const take = (entry) => { const k = merged.length - 1; - if (k < 0 || t - times[k] >= TIMELINE_FIX_SPACING_MS) { + if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= TIMELINE_FIX_SPACING_MS) { merged.push(entry); - times.push(t); } else if (entry === newest) { merged[k] = entry; - times[k] = t; } }; - let i = lead; + let i = 0; let j = 0; while (i < older.length || j < newer.length) { if (i < older.length) { - const t = olderTimes[i]; + const t = timeOf(older[i]); if (t >= first && t <= last) { i++; continue; } - if (j >= newer.length || t < newerTimes[j]) { - take(older[i], t); - i++; + if (j >= newer.length || t < timeOf(newer[j])) { + take(older[i++]); continue; } } - take(newer[j], newerTimes[j]); - j++; + take(newer[j++]); } if (merged.length <= limit) return merged; // The window of `limit` entries nearest the centre. let start = 0; while ( start + limit < merged.length && - Math.abs(times[start + limit] - centreMs) < - Math.abs(times[start] - centreMs) + Math.abs(timeOf(merged[start + limit]) - centreMs) < + Math.abs(timeOf(merged[start]) - centreMs) ) start++; return merged.slice(start, start + limit); diff --git a/src/time/timelineFixes.test.mjs b/src/time/timelineFixes.test.mjs index 346388872..9ab47c184 100644 --- a/src/time/timelineFixes.test.mjs +++ b/src/time/timelineFixes.test.mjs @@ -96,96 +96,3 @@ test('past the limit only the fixes nearest the centre are kept', () => { [0, 1, 2, 3], ); }); - -/** The merge as first written, a reference the faster one must match. */ -function referenceMerge(older, newer, timeOf, centreMs, limit = 240) { - const SPACING = 20_000; - const first = newer.length ? timeOf(newer[0]) : Infinity; - const last = newer.length ? timeOf(newer[newer.length - 1]) : -Infinity; - const newest = newer[newer.length - 1]; - const merged = []; - const take = (entry) => { - const k = merged.length - 1; - if (k < 0 || timeOf(entry) - timeOf(merged[k]) >= SPACING) - merged.push(entry); - else if (entry === newest) merged[k] = entry; - }; - let i = 0; - let j = 0; - while (i < older.length || j < newer.length) { - if (i < older.length) { - const t = timeOf(older[i]); - if (t >= first && t <= last) { - i++; - continue; - } - if (j >= newer.length || t < timeOf(newer[j])) { - take(older[i++]); - continue; - } - } - take(newer[j++]); - } - if (merged.length <= limit) return merged; - let start = 0; - while ( - start + limit < merged.length && - Math.abs(timeOf(merged[start + limit]) - centreMs) < - Math.abs(timeOf(merged[start]) - centreMs) - ) - start++; - return merged.slice(start, start + limit); -} - -test('the merge keeps exactly what it always kept, for runs of every shape', () => { - let seed = 3; - const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647; - const run = (n, from, stepMs, sorted) => { - const out = Array.from({ length: n }, (_, k) => ({ - atMs: - rnd() < 0.05 - ? Number.NaN - : from + - Math.round((sorted ? k : rnd() * n) * stepMs * (0.5 + rnd())), - })); - if (sorted) out.sort((a, b) => a.atMs - b.atMs); - return out; - }; - for (let round = 0; round < 3000; round++) { - const sorted = round % 5 !== 0; - const older = run( - Math.floor(rnd() * 300), - Math.floor(rnd() * 4e6), - 15_000 + rnd() * 50_000, - sorted, - ); - const newer = run( - Math.floor(rnd() * 30), - Math.floor(rnd() * 6e6), - 5_000 + rnd() * 70_000, - sorted, - ); - // The newest of the newer run is sometimes an entry of the older one. - if (newer.length && older.length && rnd() < 0.1) - newer[newer.length - 1] = older[older.length - 1]; - const centreMs = rnd() * 7e6; - const limit = rnd() < 0.5 ? 240 : 1 + Math.floor(rnd() * 40); - const expected = referenceMerge( - older, - newer, - (f) => f.atMs, - centreMs, - limit, - ); - const actual = mergeTimelineRuns( - older, - newer, - (f) => f.atMs, - centreMs, - limit, - ); - assert.equal(actual.length, expected.length, `round ${round}`); - for (let k = 0; k < expected.length; k++) - assert.equal(actual[k], expected[k], `round ${round} entry ${k}`); - } -});