Move the flights and military layers onto the renderer ports

The flights and military layers now reach the renderer only through its
ports: motion, queries, state, tracking, enrichment, evidence and policy
read the camera pose, project through the query port, request and
suspend frames through the frame port, and key per-frame caches on the
frames drawn rather than the scene's frame number. Policy is plain data,
the enrichment view test is pose-based, and the tracked aircraft is an
icon in a draw-port set with a plain holder standing in for the entity
that Cockpit, the tracked card and share links read.

The mesh floor sampler can sample through the query port, excluding
named draw sets, and both layers use it that way. A pick of another
layer's tracked icon is never taken for one of a layer's own contacts.

Twelve layer files leave the Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-07 18:49:23 -08:00
1 parent 00a0a0dbc7
commit 23d56f8393
40 files changed
+1638 -908

No files matched your search

+3 -3
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { TRACKED_ICON_COLOR } from '../layers/military/policy.js';
import { TRACKED_CYAN } from '../layers/flights/policy.js';
import { createRendering as civilRendering } from '../layers/flights/rendering.js';
import { createRendering as militaryRendering } from '../layers/military/rendering.js';
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
@@ -456,7 +456,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
const red = rendering._fleetBillboardColor('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
assert.ok(red.red > 0.9 && red.green < 0.5);
assert.ok(red[0] > 0.9 && red[1] < 0.5);
flightState.records.data.set('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
@@ -466,7 +466,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
flightState._trackedIcao = 'civil';
assert.equal(
rendering._modelColor('civil'),
factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR,
factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR,
);
flightState._trackedIcao = null;
flightState.records.data.set('civil', { emergency: null });
+11 -4
View File
@@ -517,9 +517,16 @@ test('real civil track path creates no native label and publishes every cached h
);
const entity = followedOf(viewer)?.entity;
assert.ok(
entity instanceof Cesium.Entity,
'trackById must create the real Cesium entity',
readEntityRecord(entity)?.trackedId,
'trackById must record the tracked contact',
);
assert.ok(
!(entity instanceof Cesium.Entity),
'tracking draws through the draw port, not a viewer entity',
);
assert.ok(entity.position, 'Cockpit sees a contact it can fly');
assert.equal(readEntityRecord(entity).drawn(), true);
assert.equal(entity.show, true);
assert.equal(entity.label, undefined);
assert.ok(
entities.values.every((candidate) => candidate.label === undefined),
@@ -579,8 +586,8 @@ test('real civil track path creates no native label and publishes every cached h
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');
const display = followedOf(viewer)?.position(Date.now());
assert.ok(display, 'the follow target must seed the frame cache');
assert.equal(
entry.position(),
display,
+88 -5
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { findCamera, findQuery } from '../render/rendererOf.js';
/**
* Focus-aware sprite treatment shared by the live contact layers.
@@ -213,6 +214,91 @@ export function publishFocusTargetFromCachedPosition({
displayPosition,
_scratchScreen,
);
return publishFocusRect({
ownerLayer,
id,
screen,
cameraDistance: Cesium.Cartesian3.distance(
camera.positionWC,
displayPosition,
),
frameNumber: scene.frameState?.frameNumber ?? -1,
widthPx,
heightPx,
params,
});
}
/**
* `publishFocusTargetFromCachedPosition` through the renderer bound to
* `viewer`: its query port projects the cached position and its camera's
* pose gives the distance. Same contract: the position must be the one the
* tracking/render path already cached this frame.
*
* @param {object} input
* @param {string} input.ownerLayer
* @param {string|number} input.id
* @param {object} input.viewer The host the renderer is bound to.
* @param {{x: number, y: number, z: number}} input.displayPosition Cached display position.
* @param {number} [input.widthPx=24]
* @param {number} [input.heightPx=24]
* @param {Partial<typeof DEFAULT_FOCUS_DEEMPHASIS_PARAMS>} [input.params]
* @returns {object|null} Published target, or null when it cannot be projected.
*/
export function publishFocusTargetAt({
ownerLayer,
id,
viewer,
displayPosition,
widthPx = 24,
heightPx = 24,
params,
}) {
const query = viewer ? findQuery(viewer) : null;
let eye = null;
try {
eye = viewer ? (findCamera(viewer)?.pose().position ?? null) : null;
} catch {
eye = null;
}
if (
!ownerLayer ||
id === null ||
id === undefined ||
!query ||
!eye ||
!displayPosition
) {
clearFocusTarget(ownerLayer, id);
return null;
}
return publishFocusRect({
ownerLayer,
id,
screen: query.project(displayPosition),
cameraDistance: Math.hypot(
displayPosition.x - eye.x,
displayPosition.y - eye.y,
displayPosition.z - eye.z,
),
frameNumber: -1,
widthPx,
heightPx,
params,
});
}
/** Publish the focus rectangle around `screen`, or clear it when there is none. */
function publishFocusRect({
ownerLayer,
id,
screen,
cameraDistance,
frameNumber,
widthPx,
heightPx,
params,
}) {
if (!screen || !Number.isFinite(screen.x) || !Number.isFinite(screen.y)) {
clearFocusTarget(ownerLayer, id);
return null;
@@ -232,11 +318,8 @@ export function publishFocusTargetFromCachedPosition({
bottom: screen.y + halfHeight + padding,
},
paddingPx: padding,
cameraDistance: Cesium.Cartesian3.distance(
camera.positionWC,
displayPosition,
),
frameNumber: scene.frameState?.frameNumber ?? -1,
cameraDistance,
frameNumber,
};
if (appeared) {
for (const listener of _focusAppearListeners) {
+11 -65
View File
@@ -23,16 +23,10 @@
*/
import * as Cesium from 'cesium';
import { poseSignature } from '../render/camera/poseSignature.js';
/** Meters used to give the course vector a stable projection magnitude. */
const FORWARD_PROBE_M = 2000;
/**
* Minimum camera-plane component before we trust the angle — below this the
* course points almost exactly into/out of the screen and the angle is noise.
*/
const MIN_SCREEN_COMPONENT_M = 0.5;
/** Ignore sub-degree projection noise while retaining deliberate camera-orbit rotation. */
const ROTATION_DEADBAND_RAD = Cesium.Math.toRadians(0.5);
import {
courseScreenRotation,
stabilizeScreenRotation,
} from './screenRotation.js';
const _scratchEnu = new Cesium.Matrix4();
const _scratchForward = new Cesium.Cartesian3();
@@ -41,7 +35,8 @@ const _scratchWorldForward = new Cesium.Cartesian3();
/**
* Computes the billboard rotation (radians, CCW-positive, for
* alignedAxis = Cartesian3.ZERO) that points an icon along its real-world
* course in the stable camera-basis approximation described above.
* course in the stable camera-basis approximation described above; the
* scene's camera axes in `screenRotation.js`'s `courseScreenRotation`.
*
* @param {Cesium.Scene} scene - The scene (projection source).
* @param {Cesium.Cartesian3} position - Entity world position.
@@ -57,64 +52,15 @@ export function screenProjectedRotation(
previous = null,
) {
const camera = scene?.camera;
if (!camera?.rightWC || !camera?.upWC || !position) return previous;
const courseRad = Cesium.Math.toRadians(courseDeg || 0);
Cesium.Cartesian3.fromElements(
Math.sin(courseRad) * FORWARD_PROBE_M,
Math.cos(courseRad) * FORWARD_PROBE_M,
0,
_scratchForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
return courseScreenRotation(
camera && { right: camera.rightWC, up: camera.upWC },
position,
Cesium.Ellipsoid.WGS84,
_scratchEnu,
courseDeg,
previous,
);
Cesium.Matrix4.multiplyByPointAsVector(
enu,
_scratchForward,
_scratchWorldForward,
);
// Screen x follows camera-right. Window y grows downward, the opposite of
// camera-up. Projecting the vector itself avoids clipping/behind-camera
// failure modes from the old forward-point worldToWindowCoordinates probe.
const dx = Cesium.Cartesian3.dot(_scratchWorldForward, camera.rightWC);
const dy = -Cesium.Cartesian3.dot(_scratchWorldForward, camera.upWC);
if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M)
return previous;
// Window y grows downward; rotation 0 = icon pointing screen-up.
// Icon direction in window coords after CCW rotation r is (-sin r, -cos r),
// so matching the projected course (dx, dy) gives r = atan2(-dx, -dy).
return Math.atan2(-dx, -dy);
}
/**
* Hold a billboard rotation when the newly projected angle differs only by
* sub-degree render noise. The comparison uses the shortest wrapped arc so
* values around ±π do not jump.
*
* @param {number|null} previous Last displayed rotation.
* @param {number|null} next Newly projected rotation.
* @param {number} [deadbandRad=ROTATION_DEADBAND_RAD] Angular hold threshold.
* @returns {number|null} Stable rotation.
*/
export function stabilizeScreenRotation(
previous,
next,
deadbandRad = ROTATION_DEADBAND_RAD,
) {
if (!Number.isFinite(next))
return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(previous)) return next;
const delta = Math.atan2(
Math.sin(next - previous),
Math.cos(next - previous),
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
export { stabilizeScreenRotation };
const _occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
+30
View File
@@ -21,6 +21,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { sampleMeshFloorCells } from './meshFloorSampler.js';
import { bindRenderer } from '../render/rendererOf.js';
import { resolveEllipsoidalGround } from './terrainHeights.js';
import {
cachedGroundFloor, cachedMeshFloor, setMeshFloorPreferred,
@@ -153,3 +154,32 @@ test('sampler: a scene without depth-texture support is never probed', async ()
assert.equal(calls, 0);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), null);
});
test('sampler: with `sets` the probe asks the query port, naming those sets', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
const scene = fakeScene(() => {
throw new Error('the scene is not asked when sets are named');
});
const viewer = { scene };
const asked = [];
bindRenderer(viewer, {
capabilities: new Set(['sampleHeight']),
query: {
sampleHeightNow(point, options) {
asked.push({ point: { ...point }, options });
return 138.0;
},
},
});
sampleMeshFloorCells(viewer, [cell], {
sets: ['flights-models:1', 'flights-icons:1'],
viewerLat: cell.lat,
viewerLon: cell.lon,
});
assert.equal(asked.length, 1);
assert.deepEqual(asked[0].options.exclude, ['flights-models:1', 'flights-icons:1']);
assert.ok(Math.abs(asked[0].point.lat - cell.lat) < 0.05);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 138.0);
});
+11 -4
View File
@@ -439,9 +439,16 @@ test('real military track path creates no native label and publishes every cache
);
const entity = followedOf(viewer)?.entity;
assert.ok(
entity instanceof Cesium.Entity,
'trackById must create the real Cesium entity',
readEntityRecord(entity)?.trackedId,
'trackById must record the tracked contact',
);
assert.ok(
!(entity instanceof Cesium.Entity),
'tracking draws through the draw port, not a viewer entity',
);
assert.ok(entity.position, 'Cockpit sees a contact it can fly');
assert.equal(readEntityRecord(entity).drawn(), true);
assert.equal(entity.show, true);
assert.equal(entity.label, undefined);
assert.ok(
entities.values.every((candidate) => candidate.label === undefined),
@@ -507,8 +514,8 @@ test('real military track path creates no native label and publishes every cache
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');
const display = followedOf(viewer)?.position(Date.now());
assert.ok(display, 'the follow target must seed the frame cache');
assert.equal(
entry.position(),
display,
+33
View File
@@ -0,0 +1,33 @@
/**
* @module data/renderedFrames
* @description How many frames a viewer's renderer has drawn: a key that
* changes once per drawn frame, after it is drawn, for per-frame caches.
* Everything that reads a cache keyed by it in one tick (the follow camera,
* the frame's `preUpdate` and `preRender` work, the readouts in its
* `postRender`) sees one value; a tick that draws nothing keeps the key, as
* the default renderer's own frame number does.
*/
import { findFrame } from '../render/rendererOf.js';
/** Per frame port: `{count}`, counted on its `postRender`. */
const counters = new WeakMap();
/**
* The number of frames drawn so far on `viewer`'s frame port, or -1 when it
* has none. Counting starts on the first call.
* @param {object|null|undefined} viewer
* @returns {number}
*/
export function renderedFrames(viewer) {
const frame = viewer ? findFrame(viewer) : null;
if (!frame) return -1;
let counter = counters.get(frame);
if (!counter) {
counter = { count: 0 };
counters.set(frame, counter);
frame.on('postRender', () => {
counter.count += 1;
});
}
return counter.count;
}
+29
View File
@@ -0,0 +1,29 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindRenderer } from '../render/rendererOf.js';
import { renderedFrames } from './renderedFrames.js';
test('the key changes once per drawn frame, after it is drawn', () => {
const viewer = {};
const listeners = { postRender: new Set() };
bindRenderer(viewer, {
frame: {
on(phase, cb) {
listeners[phase].add(cb);
return () => listeners[phase].delete(cb);
},
},
});
assert.equal(renderedFrames(viewer), 0);
assert.equal(renderedFrames(viewer), 0, 'reading does not advance it');
assert.equal(listeners.postRender.size, 1);
for (const cb of listeners.postRender) cb({});
assert.equal(renderedFrames(viewer), 1);
renderedFrames(viewer);
assert.equal(listeners.postRender.size, 1, 'one listener per frame port');
});
test('without a frame port the key is -1', () => {
assert.equal(renderedFrames(null), -1);
assert.equal(renderedFrames({}), -1);
});
+81
View File
@@ -0,0 +1,81 @@
/**
* @module data/screenRotation
* @description The screen rotation that points a camera-facing icon along
* its real-world course, from the camera's right and up axes (a camera
* port pose's `right` and `up`), and the deadband that holds it through
* render noise. See `iconOrientation.js` for why the course is projected
* onto the camera basis. No engine.
*/
import { eastNorthUp, frameVector } from '../geo/frames.js';
import { dot, toRadians, vec } from '../geo/vector.js';
/** Meters used to give the course vector a stable projection magnitude. */
const FORWARD_PROBE_M = 2000;
/**
* Minimum camera-plane component before we trust the angle — below this the
* course points almost exactly into/out of the screen and the angle is noise.
*/
const MIN_SCREEN_COMPONENT_M = 0.5;
/** Ignore sub-degree projection noise while retaining deliberate camera-orbit rotation. */
const ROTATION_DEADBAND_RAD = toRadians(0.5);
/**
* The icon rotation (radians, counter-clockwise on screen, 0 pointing
* screen-up) that points it along `courseDeg` at `position`, projected onto
* the camera's `right` and `up` axes (ECEF).
* @param {{right?: object, up?: object}|null} basis The camera's axes.
* @param {{x: number, y: number, z: number}|null} position ECEF.
* @param {number} courseDeg Degrees clockwise from north.
* @param {number|null} [previous] Kept when the projection is unknown.
* @returns {number|null}
*/
export function courseScreenRotation(
basis,
position,
courseDeg,
previous = null,
) {
if (!basis?.right || !basis?.up || !position) return previous;
const courseRad = toRadians(courseDeg || 0);
const forward = frameVector(
eastNorthUp(position),
vec(
Math.sin(courseRad) * FORWARD_PROBE_M,
Math.cos(courseRad) * FORWARD_PROBE_M,
0,
),
);
// Screen x follows camera-right; window y grows downward, against up.
const dx = dot(forward, basis.right);
const dy = -dot(forward, basis.up);
if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M)
return previous;
// Icon direction in window coords after CCW rotation r is (-sin r, -cos r),
// so matching the projected course (dx, dy) gives r = atan2(-dx, -dy).
return Math.atan2(-dx, -dy);
}
/**
* Hold a billboard rotation when the newly projected angle differs only by
* sub-degree render noise. The comparison uses the shortest wrapped arc so
* values around ±π do not jump.
*
* @param {number|null} previous Last displayed rotation.
* @param {number|null} next Newly projected rotation.
* @param {number} [deadbandRad=ROTATION_DEADBAND_RAD] Angular hold threshold.
* @returns {number|null} Stable rotation.
*/
export function stabilizeScreenRotation(
previous,
next,
deadbandRad = ROTATION_DEADBAND_RAD,
) {
if (!Number.isFinite(next))
return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(previous)) return next;
const delta = Math.atan2(
Math.sin(next - previous),
Math.cos(next - previous),
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
+10 -6
View File
@@ -250,21 +250,25 @@ test('both flight layers keep a converted contact 2D and visible (render invaria
// 3. Every aircraftIcon() CALL SITE routes through the kind resolver, so no
// refresh path (poll reconciler, raster swap, presentation, tracked
// entity) can silently revert a conversion.
// billboard) can silently revert a conversion. The tracked billboard's
// sites share one helper; the fleet's live in aircraftIconLayer.js.
const code = stripComments(source);
const callSites = code.match(/aircraftIcon\(\s*[^;]*?\)/g) || [];
assert.equal(callSites.length >= 4, true, `${name}: expected the known aircraftIcon call sites`);
assert.equal(callSites.length >= 1, true, `${name}: expected the known aircraftIcon call sites`);
for (const call of callSites) {
assert.match(call, /aircraftIcon\(\s*\s*(?:(?:parts\.)?rendering\.)?_iconKind\(\s*/,
`${name}: ${call.replace(/\s+/g, ' ')} must resolve its sprite kind through _iconKind`);
}
// 4. Orientation contract is untouched: still a screen-projected rotation
// with alignedAxis ZERO, and no new per-frame CallbackProperty.
assert.match(source, /alignedAxis: Cesium\.Cartesian3\.ZERO/, `${name}: alignedAxis stays ZERO`);
assert.doesNotMatch(source, /isTr3b[\s\S]{0,200}new Cesium\.CallbackProperty/,
// 4. Orientation contract is untouched: the tracked billboard is still a
// screen-rotated icon, and no per-frame CallbackProperty is added.
assert.doesNotMatch(source, /new Cesium\.CallbackProperty/,
`${name}: the Easter egg adds no per-frame CallbackProperty`);
}
const tracked = stripComments(
await readFile(new URL('./trackedAircraftIcon.js', import.meta.url), 'utf8'),
);
assert.match(tracked, /rotationMode: 'screen'/, 'the tracked billboard rotates in screen space');
});
test('conversions are session-scoped and no lifecycle path clears them', async () => {
+197
View File
@@ -0,0 +1,197 @@
/**
* @module data/trackedAircraftIcon
* @description The tracked aircraft's billboard, for the flights and military
* layers: one icon in an icon set of the renderer's draw port, re-posed,
* re-rotated and recoloured each drawn frame (its `preRender`) from the
* layer's own per-frame display cache, the same value the follow camera
* frames. It is drawn over depth, screen-rotated along the course, and
* sized by eye distance. It is only ever written in `preRender`, so the
* display cache is never sampled between frames; a frame whose icon would
* draw exactly as the last writes nothing, so a parked contact asks for no
* frames.
*
* The set is made on the first `show` and kept for the layer's lifetime;
* `hide` empties it and stops the frame work, `dispose` lets it go. Its
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
const sameColor = (a, b) =>
a === b ||
(Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((value, i) => value === b[i]));
/**
* Whether `setId` names another layer's tracked icon set: a layer must not
* take a pick of that icon for one of its own contacts.
* @param {string} setId A picked draw set's id.
* @param {string} setPrefix The asking layer's prefix, e.g. `military`.
* @returns {boolean}
*/
export function isOtherTrackedIconSet(setId, setPrefix) {
return (
typeof setId === 'string' &&
setId.includes('-tracked-icon:') &&
!setId.startsWith(`${setPrefix}-tracked-icon:`)
);
}
/**
* @param {object} options
* @param {() => object|null} options.viewer The layer's viewer, read when
* the set is made.
* @param {string} options.setPrefix The set id's prefix, e.g. `flights`.
*/
export function createTrackedAircraftIcon({ viewer, setPrefix }) {
let set = null;
let offFrame = null;
/** What is shown: the id and the per-frame readers. */
let shown = null;
/** The item last written, to skip a frame that changes nothing. */
let written = null;
/** Whether the shown icon draws (false while Cockpit hides it). */
let visible = true;
/** Ask for a frame, whose `preRender` draws the icon. */
function requestFrame(reason) {
const host = viewer();
if (host) findFrame(host)?.requestRender(`${setPrefix}: ${reason}`);
}
function ensureSet() {
if (set) return set;
const host = viewer();
const port = host ? findDraw(host) : null;
if (!port) return null;
set = port.icons({ id: `${setPrefix}-tracked-icon:${++instances}` });
return set;
}
/** Write the icon as it is drawn this frame, when that changed. */
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
written &&
written.id === item.id &&
written.show === item.show &&
written.pos.x === item.pos.x &&
written.pos.y === item.pos.y &&
written.pos.z === item.pos.z &&
written.image === item.image &&
written.scale === item.scale &&
written.rotation === item.rotation &&
sameColor(written.color, item.color)
)
return;
written = item;
set.upsert([item]);
}
return {
/**
* Show the tracked contact `id`'s icon, drawn before each frame from the
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string} target.image
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
this.hide();
if (!ensureSet()) return;
shown = { ...target };
const host = viewer();
offFrame = (host && findFrame(host)?.on('preRender', draw)) ?? null;
requestFrame('tracked icon');
},
/** Draw it from a new image (the class or conversion changed) next frame. */
setImage(image) {
if (!shown) return;
shown.image = image;
requestFrame('tracked icon image');
},
/** Whether the shown icon draws. */
get visible() {
return visible;
},
/** Hide or show the icon without letting the contact go. */
setVisible(value) {
if (visible === Boolean(value)) return;
visible = Boolean(value);
requestFrame('tracked icon visibility');
},
/** The set's id while it is made, for picks and height samples. */
get setId() {
return set?.id ?? null;
},
/** Stop showing the icon. */
hide() {
offFrame?.();
offFrame = null;
shown = null;
written = null;
visible = true;
if (set?.size()) set.clear();
},
/** Let the set go (layer teardown). */
dispose() {
this.hide();
set?.dispose();
set = null;
},
};
}
/**
* The tracked contact as its readers see it (the tracked card, Cockpit,
* share links): a plain holder that the layer keeps its entity record on.
* Cockpit reads `position` for whether there is a contact to fly and sets
* `show` to hide the icon while it flies it; the record's `drawn` says
* whether the layer still tracks it.
* @param {string} id e.g. `flights:a1b2c3`.
* @param {ReturnType<typeof createTrackedAircraftIcon>} icon
* @param {() => object|null} position The contact's display position.
*/
export function trackedContactHolder(id, icon, position) {
return {
id,
position: { getValue: () => position() ?? undefined },
get show() {
return icon.visible;
},
set show(value) {
icon.setVisible(value);
},
};
}
+190
View File
@@ -0,0 +1,190 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
createTrackedAircraftIcon,
isOtherTrackedIconSet,
trackedContactHolder,
} from './trackedAircraftIcon.js';
/** A viewer double with a fake draw port and a frame port whose preRender the test runs. */
function harness() {
const viewer = {};
const listeners = new Set();
const requests = [];
const frame = {
requestRender(reason) {
requests.push(reason);
},
on(phase, cb) {
assert.equal(phase, 'preRender');
listeners.add(cb);
return () => listeners.delete(cb);
},
};
const { draw } = bindFakeDraw(viewer, { frame });
const tick = () => {
for (const cb of [...listeners]) cb({});
};
return { viewer, draw, listeners, tick, requests };
}
const SPRITE = Object.freeze({
width: 28,
height: 28,
scale: 1.2,
scaleByDistance: { near: 1000, nearValue: 3, far: 8e6, farValue: 0.5 },
});
test('the tracked billboard is one icon re-posed each frame, and only when it changed', () => {
const { viewer, draw, listeners, tick, requests } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
assert.equal(icon.setId, null, 'no set before anything is shown');
let pos = { x: 1, y: 2, z: 3 };
let rotation = 0.5;
let color = [0, 1, 1, 1];
icon.show({
id: 'abc123',
image: 'data:image/svg+xml;base64,AAA',
sprite: SPRITE,
position: () => pos,
rotation: () => rotation,
color: () => color,
});
const set = draw.find('flights-tracked-icon:');
assert.ok(set, 'an icon set on the draw port');
assert.equal(set.kind, 'icons');
assert.equal(icon.setId, set.spec.id);
assert.equal(listeners.size, 1, 'drawn before each frame');
assert.equal(set.items.size, 0, 'nothing is drawn between frames');
assert.equal(requests.length, 1, 'a frame is asked for');
tick();
const item = set.items.get('abc123');
assert.deepEqual(item.pos, { x: 1, y: 2, z: 3 });
assert.notEqual(item.pos, pos, 'the position is copied');
assert.deepEqual(item.size, [28, 28]);
assert.equal(item.scale, 1.2);
assert.equal(item.scaleByDistance, SPRITE.scaleByDistance);
assert.equal(item.rotationMode, 'screen');
assert.equal(item.rotation, 0.5);
assert.deepEqual(item.color, [0, 1, 1, 1]);
assert.equal(item.disableDepthTest, Number.POSITIVE_INFINITY);
assert.equal(item.show, true);
const writes = set.writes;
color = [0, 1, 1, 1];
tick();
assert.equal(
set.writes,
writes,
'a frame that changes nothing writes nothing',
);
pos = { x: 4, y: 5, z: 6 };
rotation = 1;
color = [0, 1, 1, 0];
tick();
assert.equal(set.writes, writes + 1);
assert.deepEqual(set.items.get('abc123').pos, { x: 4, y: 5, z: 6 });
assert.equal(set.items.get('abc123').rotation, 1);
assert.deepEqual(set.items.get('abc123').color, [0, 1, 1, 0]);
icon.setImage('data:image/svg+xml;base64,BBB');
assert.equal(set.items.get('abc123').image, 'data:image/svg+xml;base64,AAA');
tick();
assert.equal(set.items.get('abc123').image, 'data:image/svg+xml;base64,BBB');
const holder = trackedContactHolder('flights:abc123', icon, () => pos);
assert.equal(holder.show, true);
assert.deepEqual(holder.position.getValue(), { x: 4, y: 5, z: 6 });
holder.show = false;
tick();
assert.equal(holder.show, false);
assert.equal(set.items.get('abc123').show, false, 'hidden while kept');
holder.show = true;
tick();
assert.equal(set.items.get('abc123').show, true);
pos = null;
tick();
assert.equal(set.items.get('abc123').show, false, 'no position hides it');
icon.hide();
assert.equal(set.items.size, 0);
assert.equal(listeners.size, 0, 'no frame work while hidden');
icon.setImage('ignored');
assert.equal(set.items.size, 0);
icon.dispose();
assert.equal(draw.sets.get(set.spec.id).disposed, true);
});
test('each layer lifetime gets its own set id, and showing again replaces the contact', () => {
const { viewer, draw, tick } = harness();
const a = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'military',
});
const b = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'military',
});
const target = (id) => ({
id,
image: 'img',
sprite: SPRITE,
position: () => ({ x: 1, y: 1, z: 1 }),
rotation: () => 0,
color: () => [1, 1, 1, 1],
});
a.show(target('one'));
b.show(target('two'));
tick();
assert.notEqual(a.setId, b.setId);
a.show(target('three'));
tick();
assert.deepEqual([...draw.set(a.setId).items.keys()], ['three']);
});
test('without a draw port nothing is drawn and nothing throws', () => {
const icon = createTrackedAircraftIcon({
viewer: () => null,
setPrefix: 'flights',
});
icon.show({
id: 'x',
image: 'img',
sprite: SPRITE,
position: () => ({ x: 0, y: 0, z: 1 }),
rotation: () => 0,
color: () => [1, 1, 1, 1],
});
icon.setVisible(false);
icon.hide();
icon.dispose();
assert.equal(icon.setId, null);
});
test("a layer tells another layer's tracked icon set from its own sets", () => {
assert.equal(
isOtherTrackedIconSet('flights-tracked-icon:3', 'military'),
true,
);
assert.equal(
isOtherTrackedIconSet('military-tracked-icon:1', 'flights'),
true,
);
assert.equal(
isOtherTrackedIconSet('military-tracked-icon:1', 'military'),
false,
);
assert.equal(isOtherTrackedIconSet('flights-icons:2', 'military'), false);
assert.equal(
isOtherTrackedIconSet('flights-tracked-model:2', 'military'),
false,
);
assert.equal(isOtherTrackedIconSet(undefined, 'military'), false);
});
+6 -6
View File
@@ -660,7 +660,7 @@ for (const fixture of LAYERS) {
assert.equal(model.show, false, 'the loading model is drawn hidden, not zero-scaled');
assert.equal(tracked.items.get(icao24).show, false);
const baseScale = model.scale;
assert.equal(fixture.trackedBillboardColor().alpha, 1,
assert.equal(fixture.trackedBillboardColor()[3], 1,
'the tracked billboard remains opaque while the model lacks safe placement');
assert.equal(sampleCalls, 0, 'cold tiles do not force a synchronous sample');
const loadingDetection = fixture.layer.getDetectableObjects({ maxCount: 50 })
@@ -689,14 +689,14 @@ for (const fixture of LAYERS) {
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,
assert.equal(fixture.trackedBillboardColor()[3], 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,
assert.equal(fixture.trackedBillboardColor()[3], 1,
'the billboard retains ownership until GPU readiness too');
assert.equal(model.scale, baseScale, 'its scale is left to the pixel-cap driver');
@@ -704,7 +704,7 @@ for (const fixture of LAYERS) {
fixture.driveTrackedModel();
assert.equal(model.show, true, 'the model appears only after its snapped matrix is written');
assert.equal(tracked.items.get(icao24).show, true);
assert.equal(fixture.trackedBillboardColor().alpha, 0,
assert.equal(fixture.trackedBillboardColor()[3], 0,
'the billboard becomes transparent only when the model actually owns the visual');
const placed = placedAt(model);
const placedHeight = Cesium.Cartographic.fromCartesian(placed).height;
@@ -727,7 +727,7 @@ for (const fixture of LAYERS) {
fixture.driveTrackedModel();
assert.equal(model.show, true,
'a taxi-invalidated tracked snap is HELD through the resample outage');
assert.equal(fixture.trackedBillboardColor().alpha, 0,
assert.equal(fixture.trackedBillboardColor()[3], 0,
'the model still owns the visual, so the billboard stays transparent');
assert.equal(sampleCalls, 1, 'the hold costs no extra synchronous sample');
@@ -736,7 +736,7 @@ for (const fixture of LAYERS) {
fixture.driveTrackedModel();
assert.equal(model.show, false,
'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld');
assert.equal(fixture.trackedBillboardColor().alpha, 1,
assert.equal(fixture.trackedBillboardColor()[3], 1,
'there is no invisible-owner gap while the replacement snap is unavailable');
} finally {
Date.now = realNow;