Keep tracked-entity state in app records instead of on Cesium entities

Flights, military, satellites, installations, local ADS-B and ALPR hung
gevTrackedId, gevDisplayPosition, gevVisualPosition, gevSelectionOrigin and
gevLabelModel on the Cesium entities they draw, and the tracked readout,
follow camera, cockpit, share links and awareness read them back. They now
live in src/data/entityRecords.js, an app-owned record per entity: layers
write entityRecord(entity), readers use readEntityRecord(entity). Nothing
changes on screen. This is the first slice of the renderer plan's state
mirror (P1).

The module is exported as ./data/entity-records so callers can read the
same records, and window.__godsEyeView.entityRecords gives the QA scripts
the same access from the page.
This commit is contained in:
Sameh Khamis committed 2026-11-03 08:09:00 -08:00
1 parent ea69bb4ce2
commit 65587f6c08
53 files changed
+408 -291

No files matched your search

+10 -9
View File
@@ -31,6 +31,7 @@ import {
isAlprSurveillanceType,
normalizeAlprNode,
} from './alprCameras.js';
import { readEntityRecord } from './entityRecords.js';
test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
const record = normalizeAlprNode({
@@ -443,25 +444,25 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
const entities = h.source.entities.values;
assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual(
entities.map((entity) => entity.gevLabelModel.title),
entities.map((entity) => readEntityRecord(entity)?.labelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
);
assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size,
1,
);
assert.deepEqual(entities[0].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [
'OSM MAPPED',
'FLOCK SAFETY · CITY POLICE · FIXED',
'PUBLIC MAP DATA',
]);
assert.deepEqual(entities[1].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'PUBLIC MAP DATA',
]);
assert.deepEqual(
entities[2].gevLabelModel.details,
readEntityRecord(entities[2])?.labelModel.details,
['OSM MAPPED', 'PUBLIC MAP DATA'],
'unknown metadata is not guessed, but the source is always named',
);
@@ -813,7 +814,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian(
entity.gevDisplayPosition(),
readEntityRecord(entity)?.displayPosition(),
);
assert.ok(Math.abs(anchor.height - 187) < 0.001);
assert.ok(
@@ -821,7 +822,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
for (let i = 0; i < 60; i++) {
h.viewer.scene.postRender.raiseEvent();
entity.gevDisplayPosition();
readEntityRecord(entity)?.displayPosition();
}
assert.equal(samples, 1, 'no per-frame raycasts');
h.advance(1000);
@@ -921,9 +922,9 @@ test('two factories keep their requests, records and destruction independent', a
assert.equal(b.source.entities.values[0].id, 'directory:99');
assert.equal(second.source, 'Test camera directory');
assert.ok(
b.source.entities.values[0].gevLabelModel.details.includes(
'Source: Test directory',
),
readEntityRecord(
b.source.entities.values[0],
)?.labelModel.details.includes('Source: Test directory'),
);
assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.viewer.scene.postRender.numberOfListeners, 0);
+52
View File
@@ -0,0 +1,52 @@
/**
* @module entityRecords
* @description Records for the entities layers draw, so layer state lives in the app
* rather than on the renderer's objects. A layer writes the record for an entity it draws;
* the tracked readout, follow camera, cockpit, share links and awareness read it back
* through the entity the renderer hands them (a pick or the tracked entity).
*
* Fields a record may hold:
* - `trackedId`: the normalized `layer:id` identity, e.g. `flights:a1b2c3`.
* - `displayPosition()`: the layer's cached display position (the follow camera's
* anti-jitter contract: the value the camera settled on, never recomputed late).
* - `visualPosition()`: where a 3D model is actually drawn, for the tracked card.
* - `labelModel`: the tracked card's `{ title, details, accent, … }`.
* - `selectionOrigin`: what started the selection (`'user'`, …).
*/
const records = new WeakMap();
/**
* The record for `entity`, made empty on first use. For layers writing their own state.
* @param {Object} entity An entity the layer draws.
* @returns {Object}
*/
export function entityRecord(entity) {
let record = records.get(entity);
if (!record) {
record = {};
records.set(entity, record);
}
return record;
}
/**
* The record for `entity`, or null when it has none (or there is no entity). For readers.
* @param {Object|null|undefined} entity
* @returns {Object|null}
*/
export function readEntityRecord(entity) {
if (!entity || typeof entity !== 'object') return null;
return records.get(entity) ?? null;
}
/**
* Write `fields` into `entity`'s record and return the entity.
* @param {Object} entity
* @param {Object} fields Record fields to set.
* @returns {Object} `entity`
*/
export function withEntityRecord(entity, fields) {
Object.assign(entityRecord(entity), fields);
return entity;
}
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { entityRecord, readEntityRecord, withEntityRecord } from './entityRecords.js';
test('an entity record is made on first write and read back by the same entity', () => {
const entity = {};
assert.equal(readEntityRecord(entity), null);
entityRecord(entity).trackedId = 'flights:a1b2c3';
assert.equal(entityRecord(entity), entityRecord(entity), 'one record per entity');
assert.equal(readEntityRecord(entity)?.trackedId, 'flights:a1b2c3');
assert.equal(readEntityRecord({}), null, 'another entity has its own record');
});
test('the record lives in the app, not on the entity', () => {
const entity = {};
entityRecord(entity).labelModel = { title: 'DAL123', details: [] };
assert.deepEqual(Object.keys(entity), []);
});
test('reading without an entity gives null', () => {
assert.equal(readEntityRecord(null), null);
assert.equal(readEntityRecord(undefined), null);
assert.equal(readEntityRecord('flights:a1b2c3'), null);
});
test('withEntityRecord writes fields into the record and returns the entity', () => {
const entity = withEntityRecord({ id: 'alpr:42' }, { trackedId: 'alpr:42' });
assert.equal(entity.id, 'alpr:42');
assert.equal(readEntityRecord(entity)?.trackedId, 'alpr:42');
assert.equal(Object.hasOwn(entity, 'trackedId'), false);
});
+14 -13
View File
@@ -28,6 +28,7 @@ import {
destroyTrackedReadout,
initTrackedReadout,
} from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
test('share-Follow absence requires an accepted OpenSky snapshot', async () => {
_setFlightTrackingRefreshOutcomeForTest({ status: 'source-unavailable' });
@@ -184,7 +185,7 @@ test('flights first update forwards caller cancellation into the feed request',
test('nonempty OpenSky payload with zero usable rows cannot prove share target absence', async () => {
_setTrackedFlightRefreshStateForTest({
icao24: 'abc123',
entity: { gevLabelModel: { title: 'WARM', details: [] } },
entity: withEntityRecord({}, { labelModel: { title: 'WARM', details: [] } }),
billboard: { show: false },
billboardCollection: { show: true, remove() {} },
viewer: { camera: { positionCartographic: null }, scene: {} },
@@ -317,7 +318,7 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a
test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STALE', async () => {
const icao24 = 'a1b2c3';
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } });
const billboard = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
@@ -388,13 +389,13 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA
try {
await flightsLayer.update(viewer);
assert.equal(entity.gevLabelModel.title, 'DAL123');
assert.match(entity.gevLabelModel.details.join(' · '), /FL350/);
assert.match(entity.gevLabelModel.details.join(' · '), /486 kts/);
assert.equal(readEntityRecord(entity)?.labelModel.title, 'DAL123');
assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /FL350/);
assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /486 kts/);
await flightsLayer.update(viewer);
assert.match(
[entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '),
[readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · '),
/STALE/,
);
} finally {
@@ -527,7 +528,7 @@ test('real civil track path creates no native label and publishes every cached h
assert.ok(
entities.values.every((candidate) => candidate.label === undefined),
);
assert.deepEqual(entity.gevLabelModel, {
assert.deepEqual(readEntityRecord(entity)?.labelModel, {
title: 'N12345 · FL350 · 486 kts',
details: ['TEST AIR · A320', 'AUS → LAX'],
accent: '#39d0ff',
@@ -546,7 +547,7 @@ test('real civil track path creates no native label and publishes every cached h
'user',
'same-target selection upgrades durable authority',
);
assert.equal(entity.gevSelectionOrigin, 'user');
assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user');
assert.equal(flightsLayer.refocusTrackedById('different-flight'), false);
assert.equal(
flightsLayer.refocusTrackedById(icao24, { origin: 'voice' }),
@@ -579,8 +580,8 @@ test('real civil track path creates no native label and publishes every cached h
const entry = publication.entries[0];
assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'tracked');
assert.equal(entry.title, entity.gevLabelModel.title);
assert.deepEqual(entry.details, entity.gevLabelModel.details);
assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title);
assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details);
const display = entity.position.getValue(now);
assert.ok(display, 'tracked position callback must seed its frame cache');
@@ -941,7 +942,7 @@ test('civil label chain: the awareness selection EVENT uses the canonical chain'
});
test('civil tracked readout: a callsign-less enriched contact reads as its registration', async () => {
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } });
seedLabelContact({ callsign: ' ', registration: ' N123AB ', tracked: true });
_setTrackedFlightRefreshStateForTest({
icao24: LABEL_ICAO,
@@ -981,9 +982,9 @@ test('civil tracked readout: a callsign-less enriched contact reads as its regis
camera: { positionCartographic: null },
scene: {},
});
assert.match(entity.gevLabelModel.title, /^N123AB\b/);
assert.match(readEntityRecord(entity)?.labelModel.title, /^N123AB\b/);
assert.doesNotMatch(
[entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '),
[readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · '),
/ae1fa4/,
);
} finally {
+9 -10
View File
@@ -46,6 +46,7 @@ import {
presentAwarenessDistance,
} from '../layers/awareness/panel.js';
import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js';
import { withEntityRecord } from './entityRecords.js';
const militaryAwarenessSource = readLayerSource(
new URL('./militaryAwareness.js', import.meta.url),
@@ -823,9 +824,7 @@ for (const fixture of [
let retrackCalls = 0;
try {
const trackedEntity = {
gevTrackedId: `${subject.layerId}:${subject.id}`,
};
const trackedEntity = withEntityRecord({}, { trackedId: `${subject.layerId}:${subject.id}` });
runtime.viewer.trackedEntity = trackedEntity;
replaceMethod(
fixture.layer,
@@ -927,7 +926,7 @@ test('Contacts activation adopts the production military tracked-subject descrip
),
'mutating one accessor result must not alter the tracked source position',
);
runtime.viewer.trackedEntity = { gevTrackedId: `military:${id}` };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `military:${id}` });
replaceMethod(flightsLayer, 'getTrackedSubject', () => null, restores);
replaceMethod(
flightsLayer,
@@ -1032,7 +1031,7 @@ test('production military tracked-subject label falls back to registration befor
'getAllPositions id stays the identity hex',
);
runtime.viewer.trackedEntity = { gevTrackedId: `military:${id}` };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `military:${id}` });
replaceMethod(flightsLayer, 'getTrackedSubject', () => null, restores);
replaceMethod(flightsLayer, 'trackById', () => true, restores);
replaceMethod(militaryFlightsLayer, 'trackById', () => true, restores);
@@ -1104,7 +1103,7 @@ test('a cached Context subject re-reads its label when enrichment lands after se
meta,
});
runtime.viewer.trackedEntity = { gevTrackedId: `flights:${id}` };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `flights:${id}` });
replaceMethod(
militaryFlightsLayer,
'getTrackedSubject',
@@ -1247,7 +1246,7 @@ test('Contacts activation adopts the production civilian tracked-subject descrip
),
'mutating one accessor result must not alter the tracked source position',
);
runtime.viewer.trackedEntity = { gevTrackedId: `flights:${id}` };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `flights:${id}` });
replaceMethod(
militaryFlightsLayer,
'getTrackedSubject',
@@ -1334,7 +1333,7 @@ test('Contacts activation reconciles to a newer cross-layer tracked flight after
const restores = [];
try {
runtime.viewer.trackedEntity = { gevTrackedId: 'flights:first' };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'flights:first' });
replaceMethod(
flightsLayer,
'getTrackedSubject',
@@ -1357,7 +1356,7 @@ test('Contacts activation reconciles to a newer cross-layer tracked flight after
civilianTracked = null;
militaryTracked = awarenessSubject('military', 'latest', positions.latest);
runtime.viewer.trackedEntity = { gevTrackedId: 'military:latest' };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'military:latest' });
releaseDependencies();
await nextTurn();
await nextTurn();
@@ -1401,7 +1400,7 @@ test('tracked flight cleared during Contacts activation suppresses fallback auto
const focused = [];
try {
runtime.viewer.trackedEntity = { gevTrackedId: 'flights:selected' };
runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'flights:selected' });
replaceMethod(flightsLayer, 'getTrackedSubject', () => tracked, restores);
replaceMethod(
militaryFlightsLayer,
+13 -12
View File
@@ -17,6 +17,7 @@ import {
destroyTrackedReadout,
initTrackedReadout,
} from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
test('share-Follow absence requires an accepted adsb.lol snapshot', async () => {
_setMilitaryTrackingRefreshOutcomeForTest({ status: 'source-unavailable' });
@@ -147,7 +148,7 @@ test('military first update forwards caller cancellation into the feed request',
test('nonempty adsb.lol payload with zero usable rows cannot prove share target absence', async () => {
_setTrackedMilitaryRefreshStateForTest({
icao24: 'ae1234',
entity: { gevLabelModel: { title: 'WARM', details: [] } },
entity: withEntityRecord({}, { labelModel: { title: 'WARM', details: [] } }),
billboard: { show: false },
billboardCollection: { show: true, remove() {} },
viewer: { camera: { positionCartographic: null }, scene: {} },
@@ -183,7 +184,7 @@ test('nonempty adsb.lol payload with zero usable rows cannot prove share target
test('military poll refreshes tracked callsign/altitude/kts and marks a missed poll STALE', async () => {
const icao24 = 'ae01ce';
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } });
const billboard = {
position: Cesium.Cartesian3.fromDegrees(-97.0, 31.0, 8_000),
color: Cesium.Color.WHITE,
@@ -246,12 +247,12 @@ test('military poll refreshes tracked callsign/altitude/kts and marks a missed p
try {
await militaryFlightsLayer.update(viewer);
assert.equal(entity.gevLabelModel.title, 'RCH451');
assert.match(entity.gevLabelModel.details.join(' · '), /28000 ft/);
assert.match(entity.gevLabelModel.details.join(' · '), /400 kt/);
assert.equal(readEntityRecord(entity)?.labelModel.title, 'RCH451');
assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /28000 ft/);
assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /400 kt/);
await militaryFlightsLayer.update(viewer);
assert.match(entity.gevLabelModel.title, /STALE/);
assert.match(readEntityRecord(entity)?.labelModel.title, /STALE/);
} finally {
globalThis.fetch = realFetch;
}
@@ -264,7 +265,7 @@ test('cached military snapshots retain their observation time and expose stale f
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedMilitaryRefreshStateForTest({
icao24: 'ae01ce',
entity: { gevLabelModel: { title: 'RCH451', details: [] } },
entity: withEntityRecord({}, { labelModel: { title: 'RCH451', details: [] } }),
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97, 31, 8000),
show: false,
@@ -442,7 +443,7 @@ test('real military track path creates no native label and publishes every cache
assert.ok(
entities.values.every((candidate) => candidate.label === undefined),
);
assert.deepEqual(entity.gevLabelModel, {
assert.deepEqual(readEntityRecord(entity)?.labelModel, {
title: 'RCH451',
details: ['C17 · 05-8152', 'United States Air Force · 28000 ft · 450 kt'],
accent: '#ffd166',
@@ -464,7 +465,7 @@ test('real military track path creates no native label and publishes every cache
'user',
'same-target selection upgrades durable authority',
);
assert.equal(entity.gevSelectionOrigin, 'user');
assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user');
assert.equal(
militaryFlightsLayer.refocusTrackedById('different-flight'),
false,
@@ -500,8 +501,8 @@ test('real military track path creates no native label and publishes every cache
const entry = publication.entries[0];
assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'tracked');
assert.equal(entry.title, entity.gevLabelModel.title);
assert.deepEqual(entry.details, entity.gevLabelModel.details);
assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title);
assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details);
const display = entity.position.getValue(now);
assert.ok(display, 'tracked position callback must seed its frame cache');
@@ -845,7 +846,7 @@ test('the military tracked descriptor publishes the reported vertical rate', ()
const seedRate = (verticalRateMps) =>
_setTrackedMilitaryRefreshStateForTest({
icao24: 'ae7f01',
entity: { gevLabelModel: { title: 'TEST', details: [] } },
entity: withEntityRecord({}, { labelModel: { title: 'TEST', details: [] } }),
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97.0, 31.0, 8_000),
color: Cesium.Color.WHITE,
+5 -4
View File
@@ -25,6 +25,7 @@ import {
} from '../renderGovernor.js';
import * as Cesium from 'cesium';
import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
test('clicking a selected installation again or empty map clears it through refresh', async () => {
const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42,
@@ -435,7 +436,7 @@ test('a footprint-less relation just outside the viewport still renders', async
});
try {
assert.deepEqual(
harness.entities().map((entity) => entity.gevLabelModel?.title),
harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title),
['Straddling Range'],
);
} finally {
@@ -475,7 +476,7 @@ test('a legacy-shaped payload at the cap fires the exact-viewport retry end to e
assert.equal(harness.requests.length, 2, 'a legacy entry must not skip the retry');
assert.equal(harness.requests[1].includes('exact=1'), true);
assert.deepEqual(
harness.entities().map((entity) => entity.gevLabelModel?.title),
harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title),
['Rescued From Legacy'],
);
} finally {
@@ -506,7 +507,7 @@ test('off-viewport records from the snapped superset never render or enter conte
],
});
try {
const titles = harness.entities().map((entity) => entity.gevLabelModel?.title);
const titles = harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title);
assert.deepEqual(titles, ['In View'], 'only the in-viewport site renders');
assert.equal(harness.contextLabels().includes('Off View'), false, 'and none enters context');
assert.equal(harness.stats().count, 1);
@@ -534,7 +535,7 @@ test('a saturated snapped tile refetches the exact viewport before rendering', a
assert.equal(harness.requests[0].includes('exact=1'), false, 'first ask uses the shared snapped tile');
assert.equal(harness.requests[1].includes('exact=1'), true, 'retry opts out of the snap');
assert.deepEqual(
harness.entities().map((entity) => entity.gevLabelModel?.title),
harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title),
['Rescued'],
'the in-viewport site is no longer starved by off-view ones',
);
+4 -3
View File
@@ -52,6 +52,7 @@ import {
stationMatchesRadioCategory,
} from './radio.js';
import { radioStationRow, withRadioLayer } from '../testSupport/radioLayerHarness.mjs';
import { withEntityRecord } from './entityRecords.js';
const stations = [
{ id: 'news', tags: ['News', 'Weather Radio', 'air traffic'] },
@@ -1652,10 +1653,10 @@ test('Radio recovery preserves closer altitude and caps extreme full-globe zoom'
test('Radio camera navigation yields to every live tracked-entity owner', () => {
const viewer = { camera: {} };
assert.equal(radioCameraNavigationAllowed(viewer), true);
for (const gevTrackedId of ['flights:abc123', 'military:def456']) {
const trackedEntity = { gevTrackedId };
for (const trackedId of ['flights:abc123', 'military:def456']) {
const trackedEntity = withEntityRecord({}, { trackedId });
viewer.trackedEntity = trackedEntity;
assert.equal(radioCameraNavigationAllowed(viewer), false, gevTrackedId);
assert.equal(radioCameraNavigationAllowed(viewer), false, trackedId);
assert.equal(viewer.trackedEntity, trackedEntity);
}
viewer.trackedEntity = undefined;
+10 -9
View File
@@ -18,6 +18,7 @@ import {
} from './satellites.js';
import satellitesLayer from './satellites.js';
import { createTrackedOverlayEntry } from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
const L1 =
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927';
@@ -117,7 +118,7 @@ test('selected satellite params survive delayed arrival and yield to newer expli
satellitesLayer.setParams({ selectedSatTrackingId: 25544 }),
);
assert.equal(satellitesLayer.getParams().selectedSatTrackingId, 25544);
assert.equal(viewer.trackedEntity?.gevTrackedId, 'satellites:25544');
assert.equal(readEntityRecord(viewer.trackedEntity)?.trackedId, 'satellites:25544');
satellitesLayer.stopTracking();
_removeSatelliteTrackingCandidateForTest(25544);
@@ -194,7 +195,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
// so their ambient labels stack underneath the tracked card. Owner ruling:
// consolidate them as secondary info on that card, and suppress only those
// members — never unrelated satellites that merely happen to be nearby.
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
@@ -229,7 +230,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
const details = entity.gevLabelModel.details;
const details = readEntityRecord(entity)?.labelModel.details;
// Class leads the detail block; the altitude line follows it, and the
// consolidated companions stay last.
assert.equal(
@@ -252,7 +253,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
assert.doesNotMatch(details[2], /\+2/);
});
test('satellite pre-render refreshes the tracked altitude on each propagated frame', () => {
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const viewer = {
camera: null,
@@ -271,17 +272,17 @@ test('satellite pre-render refreshes the tracked altitude on each propagated fra
});
_runSatellitePreRenderForTest();
assert.equal(entity.gevLabelModel.title, 'ISS (ZARYA)');
assert.equal(entity.gevLabelModel.details[0], 'STATION · ISS');
assert.equal(readEntityRecord(entity)?.labelModel.title, 'ISS (ZARYA)');
assert.equal(readEntityRecord(entity)?.labelModel.details[0], 'STATION · ISS');
// formatQuantity keeps the number and its unit together with a no-break space.
assert.equal(entity.gevLabelModel.details[1], '353\u00a0km · NORAD 25544');
assert.equal(readEntityRecord(entity)?.labelModel.details[1], '353\u00a0km · NORAD 25544');
epochIndex = 1;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
assert.equal(entity.gevLabelModel.details[1], '366\u00a0km · NORAD 25544');
assert.equal(readEntityRecord(entity)?.labelModel.details[1], '366\u00a0km · NORAD 25544');
assert.equal(
entity.gevLabelModel.details[0],
readEntityRecord(entity)?.labelModel.details[0],
'STATION · ISS',
'the class line survives an altitude-only republish',
);
+5 -4
View File
@@ -33,6 +33,7 @@ import militaryFlightsLayer, {
import { findCompatibleHistoryIndex } from './militaryAwareness.js';
import { createGevActionRunner } from '../voice/gevActions.js';
import { ANALYST_LAYERS, createAnalystEngine } from './analystEngine.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
/** Strip block and line comments so source pins scan CODE, not prose. */
function stripComments(source) {
@@ -149,7 +150,7 @@ test('a conversion survives a poll refresh, in both the billboard and the tracke
const icao24 = 'a1b2c3';
setTr3b(icao24, true);
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } });
const billboard = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
@@ -212,11 +213,11 @@ test('a conversion survives a poll refresh, in both the billboard and the tracke
assert.equal(billboard.image, aircraftIcon('tr3b'),
'the poll reconciler re-images through the TR-3B resolver, not the raw class');
// Live telemetry keeps flowing; only the class label is the operator's fiction.
assert.match(entity.gevLabelModel.title, /^DAL123 · FL350 · 486 kts$/);
assert.deepEqual(entity.gevLabelModel.details.slice(0, 1), ['TR-3B'],
assert.match(readEntityRecord(entity)?.labelModel.title, /^DAL123 · FL350 · 486 kts$/);
assert.deepEqual(readEntityRecord(entity)?.labelModel.details.slice(0, 1), ['TR-3B'],
'the tracked card class line reports TR-3B, replacing operator/type');
assert.equal(
[entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · ').includes('Southwest'),
[readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · ').includes('Southwest'),
false,
'the real operator is not shown alongside the TR-3B classification',
);
+2 -1
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { readEntityRecord } from './entityRecords.js';
const MAX_FRAME_ATTEMPTS = 120;
const MIN_TRACKED_RANGE_M = 150;
@@ -57,7 +58,7 @@ export function trackedModelScaleForPixelCap({
* @returns {Cesium.Cartesian3|undefined} Camera-frame position.
*/
export function trackedDisplayPositionForCamera(entity, time, result) {
const displayedPosition = entity?.gevDisplayPosition?.();
const displayedPosition = readEntityRecord(entity)?.displayPosition?.();
return displayedPosition
? Cesium.Cartesian3.clone(displayedPosition, result)
: entity?.position?.getValue(time, result);
+3 -5
View File
@@ -6,6 +6,7 @@ import {
trackedDisplayPositionForCamera,
trackedModelScaleForPixelCap,
} from './trackedCamera.js';
import { withEntityRecord } from './entityRecords.js';
test('tracked camera origin crossing returns to the prior side at the minimum range', () => {
const camera = {
@@ -74,15 +75,12 @@ test('tracked model shrinks smoothly when close enough to exceed the pixel cap',
test('tracked camera prefers the already-rendered display cache', () => {
let callbackReads = 0;
const cached = new Cesium.Cartesian3(1, 2, 3);
const entity = {
gevDisplayPosition: () => cached,
position: {
const entity = withEntityRecord({ position: {
getValue: () => {
callbackReads += 1;
return new Cesium.Cartesian3(4, 5, 6);
},
},
};
} }, { displayPosition: () => cached });
const result = trackedDisplayPositionForCamera(
entity,
Cesium.JulianDate.now(),
+3 -2
View File
@@ -8,6 +8,7 @@ import {
_trackedFrameCartesianForTest,
} from './satellites.js';
import { setLocale } from '../i18n/index.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
const L1 =
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927';
@@ -16,7 +17,7 @@ const L2 =
function run(locale) {
setLocale(locale);
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } });
const point = { position: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
@@ -43,7 +44,7 @@ function run(locale) {
nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
_runSatellitePreRenderForTest();
const details = entity.gevLabelModel.details;
const details = readEntityRecord(entity)?.labelModel.details;
setLocale('en');
return details;
}
+14 -10
View File
@@ -4,6 +4,7 @@ import {
setOverlaySourceVisible,
} from '../overlays/worldOverlay.js';
import { WORLD_OVERLAY_STYLE } from '../overlays/worldOverlayTokens.js';
import { readEntityRecord } from './entityRecords.js';
/**
* @module trackedReadout
@@ -79,9 +80,10 @@ export function trackedLabelModelFromText(
* @returns {Object|null}
*/
export function cachedTrackedDisplayPosition(entity) {
if (!entity || typeof entity.gevDisplayPosition !== 'function') return null;
const displayPosition = readEntityRecord(entity)?.displayPosition;
if (typeof displayPosition !== 'function') return null;
try {
return entity.gevDisplayPosition() || null;
return displayPosition() || null;
} catch {
return null;
}
@@ -91,22 +93,23 @@ export function cachedTrackedDisplayPosition(entity) {
* Anchor for the tracked CARD: the position the target is visually at.
*
* A layer that renders its tracked contact as a 3D model publishes
* `gevVisualPosition`, which returns the translation that model is actually rendering
* the entity record's `visualPosition`, which returns the translation that model is actually rendering
* with. For a grounded aircraft that differs from the display position by the full
* ground-snap offset (~100 m at an inland airport), so a card anchored to the display
* position sits below the aircraft and climbs slowly as the coarse floor cell warms.
*
* Falls back to the display position, so layers without a 3D visual (and any layer
* before its model is ready) are unchanged. This deliberately does NOT repurpose
* `gevDisplayPosition`: that accessor carries the follow-camera anti-jitter contract
* the entity record's `displayPosition`: that accessor carries the follow-camera anti-jitter contract
* and must keep returning the value the camera settled on.
* @param {Object|null} entity Tracked or selected presentation entity.
* @returns {Object|null}
*/
export function cachedTrackedVisualPosition(entity) {
if (entity && typeof entity.gevVisualPosition === 'function') {
const visualPosition = readEntityRecord(entity)?.visualPosition;
if (typeof visualPosition === 'function') {
try {
const visual = entity.gevVisualPosition();
const visual = visualPosition();
if (visual) return visual;
} catch {
/* fall through to the display position */
@@ -116,7 +119,7 @@ export function cachedTrackedVisualPosition(entity) {
}
function entryIdFor(entity) {
const explicit = String(entity?.gevTrackedId || '').trim();
const explicit = String(readEntityRecord(entity)?.trackedId || '').trim();
if (explicit) return explicit;
const fallback = String(entity?.id || '').trim();
return fallback ? `entity:${fallback}` : null;
@@ -132,9 +135,10 @@ function activeEntity() {
* @returns {Object|null}
*/
export function createTrackedOverlayEntry(entity) {
const model = entity?.gevLabelModel;
const record = readEntityRecord(entity);
const model = record?.labelModel;
const id = entryIdFor(entity);
if (!id || !model || typeof entity.gevDisplayPosition !== 'function') {
if (!id || !model || typeof record.displayPosition !== 'function') {
return null;
}
const title = String(model.title || '').trim();
@@ -204,7 +208,7 @@ function syncActiveEntity() {
}
/**
* Republish a layer's newly assigned `gevLabelModel` when that entity owns the
* Republish an entity record's newly assigned `labelModel` when that entity owns the
* active tracked readout. Layers call this only when presentation text changes;
* position remains the live frame-cache getter already registered with host.
* @param {Object} entity Entity whose model changed.
+26 -52
View File
@@ -13,6 +13,7 @@ import {
refreshTrackedReadout,
trackedLabelModelFromText,
} from './trackedReadout.js';
import { entityRecord, readEntityRecord, withEntityRecord } from './entityRecords.js';
function makeCesiumEvent() {
const listeners = new Set();
@@ -53,15 +54,12 @@ test('tracked label text becomes an explicit title/details/accent model', () =>
);
});
test('tracked position source reads only gevDisplayPosition and never entity.position', () => {
test('tracked position source reads only the record\'s displayPosition and never entity.position', () => {
const cached = { x: 1, y: 2, z: 3 };
let propertyReads = 0;
const entity = {
gevDisplayPosition: () => cached,
position: {
const entity = withEntityRecord({ position: {
getValue() { propertyReads += 1; throw new Error('fresh position read is forbidden'); },
},
};
} }, { displayPosition: () => cached });
assert.equal(cachedTrackedDisplayPosition(entity), cached);
assert.equal(propertyReads, 0);
assert.equal(cachedTrackedDisplayPosition({ position: entity.position }), null);
@@ -71,17 +69,12 @@ test('tracked position source reads only gevDisplayPosition and never entity.pos
test('the tracked card anchors to the visual position without repurposing the display accessor', () => {
// A grounded aircraft's 3D model rides a ground snap while its billboard stays
// at the reported (buried) altitude — ~100 m apart. The card must follow the
// model you can see, while `gevDisplayPosition` keeps returning the cached
// model you can see, while the record's `displayPosition` keeps returning the cached
// dead-reckoned value the follow camera settled on (anti-jitter contract).
const display = { x: 1, y: 2, z: 3 };
const visual = { x: 1, y: 2, z: 103 };
let displayReads = 0;
const entity = {
gevTrackedId: 'flights:aaa077',
gevDisplayPosition: () => { displayReads += 1; return display; },
gevVisualPosition: () => visual,
gevLabelModel: { title: 'SWA143', details: ['ON GROUND'], accent: '#6be8ff' },
};
const entity = withEntityRecord({}, { trackedId: 'flights:aaa077', displayPosition: () => { displayReads += 1; return display; }, visualPosition: () => visual, labelModel: { title: 'SWA143', details: ['ON GROUND'], accent: '#6be8ff' } });
assert.equal(cachedTrackedVisualPosition(entity), visual);
assert.equal(displayReads, 0, 'the visual accessor short-circuits the display read');
assert.equal(cachedTrackedDisplayPosition(entity), display,
@@ -91,15 +84,12 @@ test('the tracked card anchors to the visual position without repurposing the di
// Layers with no 3D visual, and any layer before its model is ready, are
// unchanged: the accessor falls back to the display position.
const spriteOnly = { gevDisplayPosition: () => display };
const spriteOnly = withEntityRecord({}, { displayPosition: () => display });
assert.equal(cachedTrackedVisualPosition(spriteOnly), display);
assert.equal(cachedTrackedVisualPosition({ ...spriteOnly, gevVisualPosition: () => null }), display,
assert.equal(cachedTrackedVisualPosition(withEntityRecord({}, { displayPosition: () => display, visualPosition: () => null })), display,
'a null visual position falls back rather than blanking the card');
assert.equal(
cachedTrackedVisualPosition({
gevDisplayPosition: () => display,
gevVisualPosition: () => { throw new Error('model gone'); },
}),
cachedTrackedVisualPosition(withEntityRecord({}, { displayPosition: () => display, visualPosition: () => { throw new Error('model gone'); } })),
display,
'a throwing visual accessor falls back instead of dropping the card',
);
@@ -108,11 +98,7 @@ test('the tracked card anchors to the visual position without repurposing the di
test('tracked entry factory pins the production protected-lane policy', () => {
const display = { x: 4, y: 5, z: 6 };
const entry = createTrackedOverlayEntry({
gevTrackedId: 'satellites:25544',
gevDisplayPosition: () => display,
gevLabelModel: { title: 'ISS', details: ['420 km · NORAD 25544'], accent: '#ffd84d' },
});
const entry = createTrackedOverlayEntry(withEntityRecord({}, { trackedId: 'satellites:25544', displayPosition: () => display, labelModel: { title: 'ISS', details: ['420 km · NORAD 25544'], accent: '#ffd84d' } }));
assert.equal(entry.id, 'satellites:25544');
assert.equal(entry.position(), display);
assert.equal(entry.protected, true);
@@ -122,15 +108,12 @@ test('tracked entry factory pins the production protected-lane policy', () => {
});
test('selected camera readout carries tactical animation and fixed badge clearance', () => {
const entry = createTrackedOverlayEntry({
id: 'alpr:42', gevDisplayPosition: () => ({ x: 1, y: 2, z: 3 }),
gevLabelModel: {
const entry = createTrackedOverlayEntry(withEntityRecord({ id: 'alpr:42' }, { displayPosition: () => ({ x: 1, y: 2, z: 3 }), labelModel: {
title: 'ALPR-0042', details: ['OSM MAPPED'], accent: '#ff6474',
cardStyle: 'tactical', selected: true, leaderStyle: 'elbow',
leaderAnimationMs: 440, leaderAnimationStartedAt: 100, leaderDrawRatio: 0.68,
anchorRadiusPx: 30, anchorRadiusScale: null,
},
});
} }));
assert.equal(entry.cardStyle, 'tactical');
assert.equal(entry.selected, true);
assert.equal(entry.leaderStyle, 'elbow');
@@ -146,12 +129,7 @@ test('tracked entity publishes a protected host entry backed by the frame cache'
const fakeWindow = new EventTarget();
const changed = makeCesiumEvent();
const display = { x: 10, y: 20, z: 30 };
const entity = {
id: 'generated',
gevTrackedId: 'flights:abc123',
gevDisplayPosition: () => display,
gevLabelModel: { title: 'UAL123', details: ['FL350 · 451 kts'], accent: '#39d0ff' },
};
const entity = withEntityRecord({ id: 'generated' }, { trackedId: 'flights:abc123', displayPosition: () => display, labelModel: { title: 'UAL123', details: ['FL350 · 451 kts'], accent: '#39d0ff' } });
const viewer = { trackedEntity: entity, trackedEntityChanged: changed };
const recorder = makeHostRecorder();
globalThis.window = fakeWindow;
@@ -174,7 +152,7 @@ test('tracked entity publishes a protected host entry backed by the frame cache'
assert.equal(publication.options.hideInCockpit, true);
assert.equal(getActiveTrackedReadoutId(), 'flights:abc123');
entity.gevLabelModel = { ...entity.gevLabelModel, details: ['FL360 · 455 kts'] };
entityRecord(entity).labelModel = { ...readEntityRecord(entity)?.labelModel, details: ['FL360 · 455 kts'] };
refreshTrackedReadout(entity);
assert.deepEqual(recorder.calls.filter(({ op }) => op === 'set').at(-1).entries[0].details, [
'FL360 · 455 kts',
@@ -197,11 +175,7 @@ test('selection lifecycle leaves installations to their own entry and retains AL
const changed = makeCesiumEvent();
const viewer = { trackedEntity: null, trackedEntityChanged: changed };
const recorder = makeHostRecorder();
const installation = {
gevTrackedId: 'installations:fort-test',
gevDisplayPosition: () => ({ x: 1, y: 2, z: 3 }),
gevLabelModel: { title: 'FORT TEST', details: ['AIRFIELD'], accent: '#5aa9ff' },
};
const installation = withEntityRecord({}, { trackedId: 'installations:fort-test', displayPosition: () => ({ x: 1, y: 2, z: 3 }), labelModel: { title: 'FORT TEST', details: ['AIRFIELD'], accent: '#5aa9ff' } });
globalThis.window = fakeWindow;
_setTrackedOverlayHostForTest(recorder.host);
try {
@@ -219,11 +193,7 @@ test('selection lifecycle leaves installations to their own entry and retains AL
assert.equal(recorder.calls.filter(({ op }) => op === 'set').length, setsBefore, 'installation selection cannot create a second overlay');
// ALPR cameras are static context too: a click publishes the same card.
const camera = {
gevTrackedId: 'alpr:42',
gevDisplayPosition: () => ({ x: 4, y: 5, z: 6 }),
gevLabelModel: { title: 'FLOCK SAFETY ALPR', details: ['CITY PD'], accent: '#ff66c4' },
};
const camera = withEntityRecord({}, { trackedId: 'alpr:42', displayPosition: () => ({ x: 4, y: 5, z: 6 }), labelModel: { title: 'FLOCK SAFETY ALPR', details: ['CITY PD'], accent: '#ff66c4' } });
fakeWindow.dispatchEvent(new CustomEvent('gev:entity-selected', {
detail: { layerId: 'alpr-cameras', entity: camera },
}));
@@ -271,7 +241,7 @@ test('trackedReadout cannot resurrect a dedicated canvas or render listener', as
}
});
test('tracking layers write gevLabelModel and expose only their cached display positions', async () => {
test('tracking layers write the record\'s labelModel and expose only their cached display positions', async () => {
const files = await Promise.all([
'flights.js',
'militaryFlights.js',
@@ -280,12 +250,16 @@ test('tracking layers write gevLabelModel and expose only their cached display p
].map(async (name) => [name, readLayerSource(new URL(`./${name}`, import.meta.url))]));
const sources = Object.fromEntries(files);
for (const [name, source] of files) {
assert.ok(source.includes('.gevLabelModel ='), `${name} writes the explicit model directly`);
assert.ok(source.includes('.gevDisplayPosition ='), `${name} exposes a display-position cache`);
assert.match(source, /entityRecord\([^)]*\)\.labelModel\s*=/, `${name} writes the explicit model into the entity record`);
assert.match(source, /entityRecord\([^)]*\)\.displayPosition\s*=/, `${name} exposes a display-position cache in the entity record`);
assert.doesNotMatch(source, /\.gev(LabelModel|DisplayPosition|VisualPosition|TrackedId|SelectionOrigin)\b/, `${name} hangs no tracked state on the entity`);
}
assert.match(sources['flights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.match(sources['militaryFlights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.ok(sources['satellites.js'].includes('gevDisplayPosition = _trackedDisplayCached'));
assert.match(sources['flights.js'], /entityRecord\([^)]*\)\.displayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.match(sources['militaryFlights.js'], /entityRecord\([^)]*\)\.displayPosition\s*=\s*parts\.motion\._trackedDisplayCached/);
assert.match(
sources['satellites.js'],
/entityRecord\([^)]*\)\.displayPosition\s*=\s*_trackedDisplayCached/,
);
assert.equal(sources['flights.js'].includes('_trackedEntity.label.text'), false);
assert.equal(sources['militaryFlights.js'].includes('_trackedEntity.label.text'), false);
assert.equal(sources['satellites.js'].includes('_trackedEntity.label.text'), false);